Skip to content

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

71.8 KB
Raw Blame
import { ComputerIdleTimer } from "./computer-idle.ts";
import { describe, expect, it, vi } from "vitest";
import { EventEmitter } from "node:events";
import { execFileSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { PassThrough, Writable } from "node:stream";
import { createServer, type Server } from "node:net";

const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }));
vi.mock("node:child_process", async () => ({
  ...(await vi.importActual<typeof import("node:child_process")>("node:child_process")),
  spawn: spawnMock,
}));

vi.mock("./vps-ssh.ts", async () => ({
  ...(await vi.importActual<typeof import("./vps-ssh.ts")>("./vps-ssh.ts")),
  ensureVpsSshMaster: vi.fn().mockResolvedValue(0),
}));

import {
  BASE_IMAGE,
  BASE_IMAGE_DIGEST,
  BASE_IMAGE_LABEL,
  CUA_DRIVER_VERSION,
  DRIVER_LABEL,
  DISPLAY,
  IMAGE_LAYER_LABEL,
  IMAGE_LAYER_VERSION,
  MANAGED_LABEL,
} from "./container-computer.ts";
import { PIDS_LIMIT } from "./container-limits.ts";
import { ensureVpsSshMaster } from "./vps-ssh.ts";
import type { AppConfig } from "./config.ts";
import {
  VPS_CONTAINER_LABEL,
  VPS_ENVIRONMENT_LABEL,
  vpsEnvironmentId,
  VPS_IMAGE,
  VPS_MANAGED_LABEL,
  VPS_VIEWER_LABEL,
  vpsComputerAction,
  vpsComputerJoin,
  vpsDesktopConnection,
  closeVpsDesktopTunnel,
  stopVpsDesktopTunnel,
  closeAllVpsDesktopTunnels,
  vpsComputerRunning,
  vpsComputerScreenshot,
  vpsComputerStatus,
  vpsComputerMcp,
  vpsContainerMcpArgs,
  vpsContainerName,
  vpsContainerRunArgs,
  vpsDockerArgs,
  vpsLifecycleBusy,
  vpsSshTunnelArgs,
  vpsStartsForTurn,
  vpsUnavailableHint,
  inspectVpsForAuto,
  reuseVps,
  dockerCliInstallCommand,
  listManagedVpsComputers,
  VpsHostUnreachableError,
  type VpsCommandRunner,
} from "./vps-computer.ts";

const BOT_ID = "bot-1234-abcd";
const CONFIG: AppConfig = { vps: { sshAlias: "production-vps" } };
const IMAGE_ID = `sha256:${"a".repeat(64)}`;
const CONTAINER_ID = "b".repeat(64);
const screenshot = Buffer.concat([
  Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
  Buffer.alloc(600),
  Buffer.from("IEND", "ascii"),
]);
const hasPillow = (() => {
  if (process.platform === "win32") return false;
  try { execFileSync("python3", ["-I", "-c", "from PIL import Image"], { stdio: "ignore" }); return true; }
  catch { return false; }
})();

function fixture({
  image = true,
  container = true,
  running = true,
  managed = true,
  mounts = false,
  publicPorts = false,
  publishAllPorts = false,
  deviceRequests = false,
  networkMode = "default",
  containerImageId = IMAGE_ID,
  inspectedImageId = IMAGE_ID,
  rebuiltImageId,
  containerId = CONTAINER_ID,
  privileged = false,
  pidMode = "",
  ipcMode,
  capAdd = ["CAP_SETUID", "CAP_SETGID"],
  screenshotValid = true,
  screenshotCaptureFails = false,
  desktopProbeFails = false,
  securityOpt = [],
  memory = 4 * 1024 * 1024 * 1024,
  restartPolicyName = "unless-stopped",
  hostConfig = {},
  cgroupnsMode,
  imageLabelsMatch = true,
  environmentId = null,
}: {
  image?: boolean;
  container?: boolean;
  running?: boolean;
  managed?: boolean;
  mounts?: boolean;
  publicPorts?: boolean;
  publishAllPorts?: boolean;
  deviceRequests?: boolean;
  networkMode?: string;
  containerImageId?: string;
  inspectedImageId?: string;
  rebuiltImageId?: string;
  containerId?: string;
  privileged?: boolean;
  pidMode?: string;
  ipcMode?: string;
  capAdd?: string[];
  screenshotValid?: boolean;
  screenshotCaptureFails?: boolean;
  desktopProbeFails?: boolean;
  securityOpt?: string[];
  memory?: number;
  restartPolicyName?: string;
  hostConfig?: Record<string, unknown>;
  cgroupnsMode?: string;
  imageLabelsMatch?: boolean;
  environmentId?: string | null;
} = {}) {
  const name = vpsContainerName(BOT_ID);
  const provisioningArgs = vpsContainerRunArgs(name);
  const argValue = (flag: string) => {
    const index = provisioningArgs.indexOf(flag);
    if (index >= 0) return provisioningArgs[index + 1] ?? "";
    return provisioningArgs.find((arg) => arg.startsWith(`${flag}=`))?.slice(flag.length + 1) ?? "";
  };
  const calls: Array<{ args: string[]; options?: { input?: string; timeoutMs?: number } }> = [];
  const state = { image, container, running, imageLabelsMatch, inspectedImageId, containerImageId };
  const runner: VpsCommandRunner = async (args, options) => {
    calls.push({ args, options });
    const command = args[2];
    if (command === "image") {
      // The real daemon phrases a clean absence this way; anything else reads as a transport failure.
      if (!state.image) throw new Error(`Error: No such image: ${VPS_IMAGE}`);
      return {
        stdout: JSON.stringify([{
          Config: { Labels: state.imageLabelsMatch ? {
             [MANAGED_LABEL]: "1",
             [DRIVER_LABEL]: CUA_DRIVER_VERSION,
             [BASE_IMAGE_LABEL]: BASE_IMAGE_DIGEST,
             [IMAGE_LAYER_LABEL]: IMAGE_LAYER_VERSION,
          } : { [MANAGED_LABEL]: "0" } },
          Id: state.inspectedImageId,
        }]),
        stderr: "",
      };
    }
    if (command === "inspect") {
      if (!state.container) throw new Error(`Error: No such object: ${name}`);
      return {
        stdout: JSON.stringify([{
          Config: {
            Image: state.image ? VPS_IMAGE : "old-image",
            Env: [`VNC_PW=${argValue("VNC_PW") || "viewer-secret"}`],
            Labels: {
              [VPS_MANAGED_LABEL]: managed ? "1" : "0",
              [VPS_CONTAINER_LABEL]: managed ? name : "other-container",
              [MANAGED_LABEL]: "1",
              [DRIVER_LABEL]: CUA_DRIVER_VERSION,
              [BASE_IMAGE_LABEL]: BASE_IMAGE_DIGEST,
              [IMAGE_LAYER_LABEL]: IMAGE_LAYER_VERSION,
              [VPS_VIEWER_LABEL]: "1",
              ...(environmentId ? { [VPS_ENVIRONMENT_LABEL]: environmentId } : {}),
            },
          },
           Id: containerId,
          Image: state.image ? state.containerImageId : "old-image-id",
          HostConfig: {
            Binds: mounts ? ["/host:/container"] : [],
            VolumesFrom: [],
            NetworkMode: networkMode,
            PortBindings: publicPorts ? { "6901/tcp": [{ HostIp: "0.0.0.0" }] } : {},
            PublishAllPorts: publishAllPorts,
            Memory: memory,
            MemorySwap: 4 * 1024 * 1024 * 1024,
            NanoCpus: 2_000_000_000,
            PidsLimit: 512,
            CapDrop: ["ALL"],
            CapAdd: capAdd,
            Privileged: privileged,
            PidMode: pidMode,
            IpcMode: ipcMode ?? argValue("--ipc"),
            UTSMode: "",
            ShmSize: 512 * 1024 * 1024,
            Devices: [],
            DeviceRequests: deviceRequests ? [{ Driver: "nvidia" }] : [],
            SecurityOpt: securityOpt,
            UsernsMode: "",
            CgroupnsMode: cgroupnsMode ?? argValue("--cgroupns"),
            OomKillDisable: false,
            AutoRemove: false,
            RestartPolicy: { Name: restartPolicyName, MaximumRetryCount: 0 },
            ...hostConfig,
          },
          NetworkSettings: {
            Networks: { [networkMode === "default" ? "bridge" : networkMode]: { IPAddress: "172.17.0.5" } },
          },
          Mounts: mounts ? [{ Source: "/host", Destination: "/container" }] : [],
          State: { Running: state.running },
        }]),
        stderr: "",
      };
    }
    if (command === "exec") {
      if (screenshotCaptureFails && args.includes("--screenshot-out-file")) throw new Error("capture failed");
      if (args.includes("openmausbot-preview")) return { stdout: screenshotValid ? screenshot.toString("base64") : "not-an-image", stderr: "" };
      if (args.includes("tail")) {
        return { stdout: "X display :1 did not become ready within 45 seconds\n", stderr: "" };
      }
      if (args.at(-1) === "--version") {
        if (desktopProbeFails) throw new Error("driver unavailable");
        return { stdout: `cua-driver ${CUA_DRIVER_VERSION}\n`, stderr: "" };
      }
      if (args.includes("status")) return { stdout: "running\n", stderr: "" };
      if (args.includes("health_report")) {
        return { stdout: JSON.stringify({ schema_version: "1", overall: "ok", checks: [] }), stderr: "" };
      }
      if (args.includes("get_desktop_state")) return { stdout: "{}\n", stderr: "" };
      return { stdout: "{}\n", stderr: "" };
    }
    if (command === "pull") return { stdout: "pulled\n", stderr: "" };
    if (command === "build") {
      state.image = true;
      state.imageLabelsMatch = true;
      state.inspectedImageId = rebuiltImageId ?? state.inspectedImageId;
      expect(options?.input).toContain(`FROM ${BASE_IMAGE}`);
      return { stdout: "built\n", stderr: "" };
    }
    if (command === "run") {
      state.container = true;
      state.running = true;
      state.containerImageId = args.at(-1) ?? state.containerImageId;
      return { stdout: `${name}\n`, stderr: "" };
    }
    if (command === "start") {
      state.running = true;
      return { stdout: `${name}\n`, stderr: "" };
    }
    if (command === "stop") {
      state.running = false;
      return { stdout: `${name}\n`, stderr: "" };
    }
    if (command === "rm") {
      state.container = false;
      state.running = false;
      return { stdout: `${name}\n`, stderr: "" };
    }
    throw new Error(`unexpected Docker command ${command}`);
  };
  return { calls, runner, state, name };
}

function mockTransport(runner: VpsCommandRunner): void {
  spawnMock.mockImplementation((_command: string, args: string[]) => {
    const child = Object.assign(new EventEmitter(), {
      stdin: new Writable({ write: (_chunk, _encoding, callback) => callback() }),
      stdout: new PassThrough(), stderr: new PassThrough(),
      kill: () => true,
    });
    queueMicrotask(() => {
      void runner(args).then((output) => {
        child.stdout.end(output.stdout);
        child.stderr.end(output.stderr);
        child.emit("close", 0, null);
      }, (error: Error) => {
        child.stderr.end(error.message);
        child.emit("close", 1, null);
      });
    });
    return child;
  });
}

describe("VPS computer", () => {
  it("uses a deterministic, bot-id-derived managed container name", () => {
    expect(vpsContainerName(BOT_ID)).toBe(vpsContainerName(BOT_ID));
    expect(vpsContainerName(BOT_ID)).not.toBe(vpsContainerName("another-bot"));
    expect(vpsContainerName(BOT_ID)).toMatch(/^openmausbot-vps-[a-z0-9-]+$/);
  });

  it("passes the SSH target as one validated Docker argv value", () => {
    expect(vpsDockerArgs("production-vps", ["info"])).toEqual(["-H", "ssh://production-vps", "info"]);
    for (const alias of ["production-vps;touch", "ssh://production-vps", "-H", "--host=evil", "prod vps", "prod\n-v"] ) {
      expect(() => vpsDockerArgs(alias, ["info"])).toThrow(/alias/);
    }
    expect(() => vpsContainerMcpArgs("production-vps", "not a container")).toThrow(/connection/);
  });

  it("keeps the live desktop behind a validated loopback SSH forward", () => {
    const args = vpsSshTunnelArgs("production-vps", 45678, "172.17.0.5");
    expect(args).toContain("127.0.0.1:45678:172.17.0.5:6901");
    expect(args.at(-1)).toBe("production-vps");
    expect(args).toContain("ExitOnForwardFailure=yes");
    expect(args).toContain("ControlPath=none");
    expect(vpsSshTunnelArgs("production-vps", 45678, "172.17.0.5", "/data/ssh/config").slice(0, 3)).toEqual(["-F", "/data/ssh/config", "-N"]);
    expect(vpsSshTunnelArgs("production-vps", 45678, "172.17.0.5", null)[0]).toBe("-N");
    expect(() => vpsSshTunnelArgs("production-vps", 80, "172.17.0.5")).toThrow(/port/);
    expect(() => vpsSshTunnelArgs("production-vps", 45678, "203.0.113.8")).toThrow(/private/);
  });

  it("reports a ready container only when image, labels, isolation, mounts, network, and Cua pass", async () => {
    const fake = fixture();
    const status = await vpsComputerStatus(CONFIG, BOT_ID, fake.runner);
    expect(status).toMatchObject({
      configured: true,
      daemonUp: true,
      image: true,
      imageMatches: true,
      managed: true,
      network: "private",
      mounts: "none",
      security: "hardened",
      desktopReady: true,
      ready: true,
      problem: null,
    });
    expect(fake.calls[0]?.args).toEqual(["-H", "ssh://production-vps", "image", "inspect", VPS_IMAGE]);
    expect(fake.calls.some(({ args }) => args[2] === "info")).toBe(false);
    const probes = fake.calls.filter(
      ({ args }) =>
        args[2] === "exec" &&
        (args.at(-1) === "--version" || args.includes("status") || args.includes("health_report") || args.includes("get_desktop_state")),
    );
    expect(probes).toHaveLength(4);
    expect(probes.every(({ args }) => args.includes(CONTAINER_ID))).toBe(true);
    expect(probes.every(({ args }) => !args.includes(fake.name))).toBe(true);
    expect(probes.every(({ args }) => args.includes(`DISPLAY=${DISPLAY}`))).toBe(true);
    expect(probes.every(({ args }) => args.includes("CUA_DRIVER_RS_TELEMETRY_ENABLED=0"))).toBe(true);
    expect(fake.calls.some(({ args }) => args.includes("openmausbot-preview"))).toBe(false);
    expect(fake.calls.some(({ args }) => args.includes("--screenshot-out-file"))).toBe(false);
  });

  it.each([
    { Memory: 1024 ** 3, MemorySwap: 2 * 1024 ** 3, NanoCpus: 4_000_000_000, PidsLimit: 1024, ShmSize: 1024 ** 3, OomKillDisable: true },
    { Memory: 0, MemorySwap: -1, NanoCpus: 0, PidsLimit: -1, ShmSize: 64 * 1024 ** 2, OomKillDisable: null },
  ])("reuses a VPS container with operator-selected resources: %j", async (hostConfig) => {
    const fake = fixture({ hostConfig });
    expect(await vpsComputerStatus(CONFIG, BOT_ID, fake.runner)).toMatchObject({ security: "hardened", ready: true });
    expect((await vpsComputerAction("provision", CONFIG, BOT_ID, fake.runner)).ready).toBe(true);
    expect(fake.calls.some(({ args }) => ["rm", "run", "build", "pull"].includes(args[2]!))).toBe(false);
  });

  it("raises a VPS desktop made under the old 512 process cap in place, once, and leaves a chosen cap alone", async () => {
    const updates = (fake: ReturnType<typeof fixture>) => fake.calls.filter(({ args }) => args[2] === "update").map(({ args }) => args.slice(2));
    const settle = () => new Promise((resolve) => setImmediate(resolve));
    const old = fixture({ containerId: "d".repeat(64) });
    await vpsComputerStatus(CONFIG, BOT_ID, old.runner);
    await settle();
    await vpsComputerStatus(CONFIG, BOT_ID, old.runner);
    await settle();
    expect(updates(old)).toEqual([["update", "--pids-limit", String(PIDS_LIMIT), "d".repeat(64)]]);
    const chosen = fixture({ containerId: "e".repeat(64), hostConfig: { PidsLimit: 1024 } });
    await vpsComputerStatus(CONFIG, BOT_ID, chosen.runner);
    await settle();
    expect(updates(chosen)).toEqual([]);
  });

  it.each(["no", "always", "on-failure", "unless-stopped"])(
    "reuses a VPS container with operator-selected restart policy %s", async (restartPolicyName) => {
      const fake = fixture({ restartPolicyName });
      expect(await vpsComputerStatus(CONFIG, BOT_ID, fake.runner)).toMatchObject({ security: "hardened", ready: true });
      expect((await vpsComputerAction("provision", CONFIG, BOT_ID, fake.runner)).ready).toBe(true);
      expect(fake.calls.some(({ args }) => ["rm", "run"].includes(args[2]!))).toBe(false);
    },
  );

  it("refuses host mounts, public ports, and unowned containers", async () => {
    const mounted = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ mounts: true }).runner);
    expect(mounted.ready).toBe(false);
    expect(mounted.mounts).toBe("unsafe");

    const publicPorts = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ publicPorts: true }).runner);
    expect(publicPorts.ready).toBe(false);
    expect(publicPorts.network).toBe("unsafe");

    const publishedAll = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ publishAllPorts: true }).runner);
    expect(publishedAll.ready).toBe(false);
    expect(publishedAll.network).toBe("unsafe");

    const devices = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ deviceRequests: true }).runner);
    expect(devices.ready).toBe(false);
    expect(devices.security).toBe("unsafe");

    const sharedNetwork = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ networkMode: "shared-net" }).runner);
    expect(sharedNetwork.ready).toBe(false);
    expect(sharedNetwork.network).toBe("unsafe");

    const hostNetwork = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ networkMode: "host" }).runner);
    expect(hostNetwork.ready).toBe(false);
    expect(hostNetwork.network).toBe("unsafe");

    const privileged = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ privileged: true }).runner);
    expect(privileged.ready).toBe(false);
    expect(privileged.security).toBe("unsafe");

    const hostNamespaces = await vpsComputerStatus(
      CONFIG,
      BOT_ID,
      fixture({ pidMode: "host", ipcMode: "host" }).runner,
    );
    expect(hostNamespaces.ready).toBe(false);
    expect(hostNamespaces.security).toBe("unsafe");

    const extraCapability = await vpsComputerStatus(
      CONFIG,
      BOT_ID,
      fixture({ capAdd: ["CAP_SETUID", "CAP_SETGID", "CAP_SYS_ADMIN"] }).runner,
    );
    expect(extraCapability.ready).toBe(false);
    expect(extraCapability.security).toBe("unsafe");

    const unsafeProfile = await vpsComputerStatus(
      CONFIG,
      BOT_ID,
      fixture({ securityOpt: ["seccomp=unconfined"], cgroupnsMode: "host" }).runner,
    );
    expect(unsafeProfile.ready).toBe(false);
    expect(unsafeProfile.security).toBe("unsafe");

    const autoRemove = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ hostConfig: { AutoRemove: true } }).runner);
    expect(autoRemove.ready).toBe(false);
    expect(autoRemove.security).toBe("unsafe");

    const wrongImage = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ containerImageId: "c".repeat(64) }).runner);
    expect(wrongImage.ready).toBe(false);
    expect(wrongImage.imageMatches).toBe(false);

    const malformedImageId = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ inspectedImageId: "--help" }).runner);
    expect(malformedImageId.ready).toBe(false);
    expect(malformedImageId.image).toBe(false);

    const malformedContainerId = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ containerId: "--help" }).runner);
    expect(malformedContainerId.ready).toBe(false);
    expect(malformedContainerId.container_id).toBeNull();

    const unowned = await vpsComputerStatus(CONFIG, BOT_ID, fixture({ managed: false }).runner);
    expect(unowned.ready).toBe(false);
    expect(unowned.managed).toBe(false);
  });

  it("lets explicit provisioning build and run the pinned container, but Auto only reuses", async () => {
    const auto = fixture({ image: false, container: false });
    expect(await reuseVps(CONFIG, BOT_ID, auto.runner)).toBeNull();
    expect(auto.calls.some(({ args }) => ["run", "start", "build", "pull"].includes(args[2]!))).toBe(false);

    const provision = fixture({ image: false, container: false });
    const status = await vpsComputerAction("provision", CONFIG, BOT_ID, provision.runner);
    expect(status.ready).toBe(true);
    const run = provision.calls.find(({ args }) => args[2] === "run")?.args ?? [];
    expect(run).toContain("--memory");
    expect(run.join(" "), "a VPS desktop has no host mounts, so root may install packages there")
      .toContain("--cap-drop ALL --cap-add CHOWN --cap-add DAC_OVERRIDE --cap-add FOWNER --cap-add FSETID --cap-add SETGID --cap-add SETUID");
    expect(run).not.toContain("no-new-privileges");
    expect(run[run.indexOf("--pids-limit") + 1], "Firefox needs room for its threads").toBe(String(PIDS_LIMIT));
    expect(run).toContain("--ipc");
    expect(run[run.indexOf("--ipc") + 1]).toBe("private");
    expect(run).toContain("--cgroupns");
    expect(run[run.indexOf("--cgroupns") + 1]).toBe("private");
    expect(run.at(-1)).toBe(IMAGE_ID);
    expect(run.join(" ")).toContain(`--label ${VPS_MANAGED_LABEL}=1`);
    expect(run.find((arg) => arg.startsWith(`${VPS_ENVIRONMENT_LABEL}=`)))
      .toMatch(/^com\.openmausbot\.environment=[0-9a-f-]{36}$/i);
    expect(run.join(" ")).toContain(`--label ${IMAGE_LAYER_LABEL}=${IMAGE_LAYER_VERSION}`);
    expect(run.join(" ")).toContain(`--label ${VPS_VIEWER_LABEL}=1`);
    expect(run.join(" ")).toContain("--restart unless-stopped");
    expect(run).toContain("-e");
    expect(run.some((arg) => /^VNC_PW=[A-Za-z0-9_-]{8,}$/.test(arg))).toBe(true);
    expect(run).not.toContain("--mount");
    expect(run).not.toContain("-p");
    const build = provision.calls.find(({ args }) => args[2] === "build");
    expect(build?.args.slice(2)).toEqual(["build", "--force-rm", "-t", VPS_IMAGE, "-"]);
  });

  it("uses the image id produced by a rebuild", async () => {
    const staleImageId = `sha256:${"b".repeat(64)}`;
    const provision = fixture({
      image: true,
      imageLabelsMatch: false,
      container: false,
      inspectedImageId: staleImageId,
      rebuiltImageId: IMAGE_ID,
    });

    const status = await vpsComputerAction("provision", CONFIG, BOT_ID, provision.runner);
    expect(status.ready).toBe(true);
    const run = provision.calls.find(({ args }) => args[2] === "run")?.args ?? [];
    expect(run.at(-1)).toBe(IMAGE_ID);
    expect(run.at(-1)).not.toBe(staleImageId);
  });

  it("starts and sleeps only the managed container, never the VPS", async () => {
    const start = fixture({ running: false });
    const started = await vpsComputerAction("start", CONFIG, BOT_ID, start.runner);
    expect(started.container).toBe("running");
    expect(start.calls.some(({ args }) => args[2] === "start")).toBe(true);
    expect(start.calls.some(({ args }) => ["rm", "system", "reboot", "shutdown"].includes(args[2]!))).toBe(false);

    const stop = fixture();
    const stopped = await vpsComputerAction("stop", CONFIG, BOT_ID, stop.runner);
    expect(stopped.container).toBe("stopped");
    expect(stop.calls.some(({ args }) => args[2] === "stop" && args[3] === CONTAINER_ID)).toBe(true);
    expect(stop.calls.some(({ args }) => ["rm", "system", "reboot", "shutdown"].includes(args[2]!))).toBe(false);
  });

  it("leaves the desktop running when work arrives during idle-stop inspection", async () => {
    const fake = fixture({ environmentId: vpsEnvironmentId() });
    let idle = true;
    const runner: typeof fake.runner = (args, options) => { idle = false; return fake.runner(args, options); };
    const result = await vpsComputerAction("stop", CONFIG, BOT_ID, runner, () => idle);
    expect(result.container).toBe("running");
    expect(fake.calls.some(({ args }) => ["stop", "rm"].includes(args[2]!))).toBe(false);
  });

  it("restarts the same container after an unattended idle stop", async () => {
    const fake = fixture({ environmentId: vpsEnvironmentId() });
    const stopped = await vpsComputerAction("stop", CONFIG, BOT_ID, fake.runner, () => true);
    expect(stopped.container).toBe("stopped");
    const resumed = await vpsComputerAction("provision", CONFIG, BOT_ID, fake.runner);
    expect(resumed.ready).toBe(true);
    expect(resumed.container_id).toBe(CONTAINER_ID);
    expect(fake.calls.some(({ args }) => ["rm", "run"].includes(args[2]!))).toBe(false);
  });

  it.each([null, "another-installation"])("leaves an unverified idle desktop running (%s)", async environmentId => {
    const fake = fixture({ environmentId });
    await vpsComputerAction("stop", CONFIG, BOT_ID, fake.runner, () => true);
    expect(fake.calls.some(({ args }) => ["stop", "rm"].includes(args[2]!))).toBe(false);
  });

  it("serializes concurrent provisioning for the same bot", async () => {
    const fake = fixture({ image: false, container: false });
    const results = await Promise.all([
      vpsComputerAction("provision", CONFIG, BOT_ID, fake.runner),
      vpsComputerAction("provision", CONFIG, BOT_ID, fake.runner),
    ]);
    expect(results.every((status) => status.ready)).toBe(true);
    expect(fake.calls.filter(({ args }) => args[2] === "run")).toHaveLength(1);
  });

  it("returns an already-ready provision after one fresh inspection", async () => {
    const fake = fixture();
    expect((await vpsComputerAction("provision", CONFIG, BOT_ID, fake.runner)).ready).toBe(true);
    expect(fake.calls.filter(({ args }) => args[2] === "image")).toHaveLength(1);
    expect(fake.calls.filter(({ args }) => args.includes("get_desktop_state"))).toHaveLength(1);
  });

  it("shares a slow provision instead of rejecting its second caller after five seconds", async () => {
    vi.useFakeTimers();
    let release!: () => void;
    const gate = new Promise<void>((resolve) => { release = resolve; });
    const fake = fixture({ image: false, container: false });
    const runner: VpsCommandRunner = async (args, options) => {
      if (args[2] === "build") await gate;
      return fake.runner(args, options);
    };
    const first = vpsComputerAction("provision", CONFIG, BOT_ID, runner);
    let secondFailure: unknown;
    const second = vpsComputerAction("provision", CONFIG, BOT_ID, runner).catch((error) => { secondFailure = error; return null; });
    try {
      await vi.advanceTimersByTimeAsync(6_000);
      expect(secondFailure).toBeUndefined();
      release();
      const results = await Promise.all([first, second]);
      expect(results[0]).toEqual(results[1]);
      expect(fake.calls.filter(({ args }) => args[2] === "run")).toHaveLength(1);
      expect(fake.calls.filter(({ args }) => args.includes("get_desktop_state"))).toHaveLength(1);
    } finally {
      release();
      await Promise.allSettled([first, second]);
      vi.useRealTimers();
    }
  });

  it.each(["provision", "auto"] as const)("waits through a normal slow preview before %s readiness", async (mode) => {
    vi.useFakeTimers();
    let release!: () => void;
    const gate = new Promise<void>((resolve) => { release = resolve; });
    const fake = fixture();
    const runner: VpsCommandRunner = async (args, options) => {
      if (args.includes("--screenshot-out-file")) await gate;
      return fake.runner(args, options);
    };
    const preview = vpsComputerScreenshot(CONFIG, BOT_ID, runner);
    await vi.advanceTimersByTimeAsync(0);
    let failure: unknown;
    const readiness = (mode === "provision"
      ? vpsComputerAction("provision", CONFIG, BOT_ID, runner)
      : inspectVpsForAuto(CONFIG, BOT_ID, runner)).catch((error) => { failure = error; return null; });
    try {
      await vi.advanceTimersByTimeAsync(6_000);
      expect(failure).toBeUndefined();
      expect(vpsLifecycleBusy()).toBe(true);
      release();
      await preview;
      expect((await readiness)?.ready).toBe(true);
      expect(vpsLifecycleBusy()).toBe(false);
    } finally {
      release();
      await Promise.allSettled([preview, readiness]);
      vi.useRealTimers();
    }
  });

  it("shares one Auto inspection among turns that ask while it runs, never jumping a stop queued behind it", async () => {
    const config: AppConfig = { vps: { sshAlias: "burst-vps" } };
    const fake = fixture();
    let release!: () => void;
    let gate = new Promise<void>((resolve) => { release = resolve; });
    const runner: VpsCommandRunner = async (args, options) => {
      if (args[2] === "image") await gate;
      return fake.runner(args, options);
    };
    const inspections = () => fake.calls.filter(({ args }) => args[2] === "image").length;
    const burst = [1, 2, 3].map(() => inspectVpsForAuto(config, BOT_ID, runner));
    release();
    expect((await Promise.all(burst)).map((status) => status.ready)).toEqual([true, true, true]);
    expect(inspections()).toBe(1);

    gate = new Promise<void>((resolve) => { release = resolve; });
    const running = inspectVpsForAuto(config, BOT_ID, runner);
    const stop = vpsComputerAction("stop", config, BOT_ID, runner);
    const after = inspectVpsForAuto(config, BOT_ID, runner);
    release();
    expect((await running).ready).toBe(true);
    expect((await stop).container).toBe("stopped");
    expect(await after).toMatchObject({ ready: false, container: "stopped" });
  });

  it("keeps provisioning and readiness checks on the alias captured at operation start", async () => {
    const fake = fixture({ container: false });
    const config: AppConfig = { vps: { sshAlias: "original-vps" } };
    const runner: VpsCommandRunner = async (args, options) => {
      const result = await fake.runner(args, options);
      if (args[2] === "run") config.vps!.sshAlias = "replacement-vps";
      return result;
    };

    expect((await vpsComputerAction("provision", config, BOT_ID, runner)).ready).toBe(true);
    expect(fake.calls.some(({ args }) => args[2] === "run")).toBe(true);
    expect(fake.calls.every(({ args }) => args[1] === "ssh://original-vps")).toBe(true);
  });

  it("mounts the official Cua MCP server through the tiny remote exec bridge", () => {
    const connection = vpsComputerMcp(CONFIG, BOT_ID);
    expect(connection.command).toBe(process.execPath);
    expect(connection.args.slice(-2)).toEqual(["production-vps", vpsContainerName(BOT_ID)]);
    expect(connection.env).toEqual({ ELECTRON_RUN_AS_NODE: "1" });
    expect(vpsComputerMcp(CONFIG, BOT_ID, CONTAINER_ID).args.slice(-2)).toEqual(["production-vps", CONTAINER_ID]);
    expect(vpsContainerMcpArgs("production-vps", vpsContainerName(BOT_ID))).toEqual([
      "-H",
      "ssh://production-vps",
      "exec",
      "-i",
      "-u",
      "cua",
      "-e",
      "HOME=/home/cua",
      "-e",
      "DISPLAY=:1",
      "-e",
      "CUA_DRIVER_INSTALL_CHANNEL=python_package",
      "-e",
      "CUA_DRIVER_RS_TELEMETRY_ENABLED=0",
      vpsContainerName(BOT_ID),
      "/usr/local/libexec/openmausbot/cua-driver",
      "mcp",
      "--socket",
      "/run/user/1000/openmausbot-cua.sock",
    ]);
  });

  it("captures screenshots through Cua Driver and validates the returned image", async () => {
    const fake = fixture();
    const frame = await vpsComputerScreenshot(CONFIG, BOT_ID, fake.runner);
    expect(frame).toEqual({ png: screenshot.toString("base64"), format: "png" });
    expect(fake.calls.some(({ args }) => args.includes("get_desktop_state"))).toBe(true);
    const transfer = fake.calls.find(({ args }) => args.includes("openmausbot-preview"))!.args;
    expect(transfer.slice(2)).toEqual([
      "exec", "-u", "cua", "-e", "HOME=/home/cua", CONTAINER_ID,
      "sh", "-c", expect.stringContaining('quality=70'), "openmausbot-preview", "/tmp/openmausbot-vps-preview.png",
    ]);
    expect(transfer[transfer.indexOf("-c") + 1]).toContain("image.thumbnail((1280, 1280))");
    expect(fake.calls.some(({ args }) => args.includes("rm") && args.includes("-f"))).toBe(true);

    await expect(vpsComputerScreenshot(CONFIG, BOT_ID, fixture({ screenshotValid: false }).runner)).rejects.toThrow(/incomplete/);

    const failedCapture = fixture({ screenshotCaptureFails: true });
    await expect(vpsComputerScreenshot(CONFIG, BOT_ID, failedCapture.runner)).rejects.toThrow(/capture failed/);
    expect(failedCapture.calls.some(({ args }) => args.includes("rm") && args.includes("-f"))).toBe(true);
  });

  it.skipIf(!hasPillow)("transfers real JPEG previews at quality 70, within 1280px without upscaling", async () => {
    const fake = fixture();
    await vpsComputerScreenshot(CONFIG, BOT_ID, fake.runner);
    const transfer = fake.calls.find(({ args }) => args.includes("openmausbot-preview"))!.args;
    // The exact in-container script with only the local Pillow interpreter and a disposable image swapped in; no Docker or SSH.
    const script = transfer[transfer.indexOf("-c") + 1].replace("/opt/venv/bin/python", "python3");
    const scratch = mkdtempSync(join(tmpdir(), "omb-vps-preview-image-"));
    try {
      for (const [width, height, expected] of [[2560, 1600, [1280, 800]], [1600, 2560, [800, 1280]], [320, 200, [320, 200]]] as const) {
        const original = execFileSync("python3", ["-I", "-c", `from PIL import Image; import sys; Image.effect_noise((${width}, ${height}), 64).convert("RGBA").save(sys.stdout.buffer, format="PNG")`], { maxBuffer: 32 * 1024 * 1024 });
        const path = join(scratch, "preview.png");
        writeFileSync(path, original);
        const encoded = execFileSync("sh", ["-c", script, "openmausbot-preview", path], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
        const jpeg = Buffer.from(encoded, "base64");
        const decoded = execFileSync("python3", ["-I", "-c", [
          "from PIL import Image",
          "import io, json, sys",
          "image = Image.open(io.BytesIO(sys.stdin.buffer.read()))",
          "image.load()",
          "reference = io.BytesIO()",
          "Image.new('RGB', (1, 1)).save(reference, format='JPEG', quality=70)",
          "print(json.dumps(dict(format=image.format, size=image.size, mode=image.mode, quality70=image.quantization == Image.open(reference).quantization)))",
        ].join("\n")], { input: jpeg, encoding: "utf8" });
        expect(JSON.parse(decoded)).toEqual({ format: "JPEG", size: expected, mode: "RGB", quality70: true });
        expect(jpeg.length).toBeLessThan(original.length / 2);
        expect(readFileSync(path).equals(original)).toBe(true);
        const frame = await vpsComputerScreenshot(CONFIG, BOT_ID, async (args, options) => args.includes("openmausbot-preview")
          ? { stdout: encoded, stderr: "" }
          : fake.runner(args, options));
        expect(frame).toEqual({ png: encoded, format: "jpeg" });
      }
    } finally { rmSync(scratch, { recursive: true, force: true }); }
  });

  it.skipIf(process.platform === "win32")("falls back to the original PNG when conversion is unavailable or fails", async () => {
    const fake = fixture();
    await vpsComputerScreenshot(CONFIG, BOT_ID, fake.runner);
    const transfer = fake.calls.find(({ args }) => args.includes("openmausbot-preview"))!.args;
    const originalScript = transfer[transfer.indexOf("-c") + 1];
    const scratch = mkdtempSync(join(tmpdir(), "omb-vps-preview-fallback-"));
    try {
      const path = join(scratch, "preview.png");
      writeFileSync(path, screenshot);
      for (const interpreter of [join(scratch, "missing-python"), "false"]) {
        const script = originalScript.replace("/opt/venv/bin/python", interpreter);
        const encoded = execFileSync("sh", ["-c", script, "openmausbot-preview", path], { encoding: "utf8" });
        expect(encoded).toBe(screenshot.toString("base64"));
      }
    } finally { rmSync(scratch, { recursive: true, force: true }); }
  });

  it("shares overlapping captures of the same target through cleanup", async () => {
    const fake = fixture();
    let release!: () => void;
    let entered!: () => void;
    const gate = new Promise<void>((resolve) => { release = resolve; });
    const capturing = new Promise<void>((resolve) => { entered = resolve; });
    const runner: VpsCommandRunner = async (args, options) => {
      if (args.includes("--screenshot-out-file")) { entered(); await gate; }
      return fake.runner(args, options);
    };
    const first = vpsComputerScreenshot(CONFIG, BOT_ID, runner);
    await capturing;
    const second = vpsComputerScreenshot(CONFIG, BOT_ID, runner);
    expect(vpsLifecycleBusy()).toBe(true);
    release();
    const frames = await Promise.all([first, second]);
    expect(frames[0]).toEqual(frames[1]);
    expect(fake.calls.filter(({ args }) => args.includes("--screenshot-out-file"))).toHaveLength(1);
    expect(fake.calls.filter(({ args }) => args.includes("openmausbot-preview"))).toHaveLength(1);
    expect(fake.calls.filter(({ args }) => args.includes("rm"))).toHaveLength(1);
    expect(vpsLifecycleBusy()).toBe(false);
  });

  it("pins the capture alias and never shares its frame with a different VPS", async () => {
    const cfg: AppConfig = { vps: { sshAlias: "first-preview-vps" } };
    const fake = fixture();
    let release!: () => void;
    let entered!: () => void;
    const gate = new Promise<void>((resolve) => { release = resolve; });
    const capturing = new Promise<void>((resolve) => { entered = resolve; });
    const runner: VpsCommandRunner = async (args, options) => {
      if (args[1] === "ssh://first-preview-vps" && args.includes("--screenshot-out-file")) { entered(); await gate; }
      return fake.runner(args, options);
    };
    const first = vpsComputerScreenshot(cfg, BOT_ID, runner);
    await capturing;
    cfg.vps!.sshAlias = "second-preview-vps";
    await vpsComputerScreenshot(cfg, BOT_ID, runner);
    release();
    await first;
    for (const alias of ["first-preview-vps", "second-preview-vps"]) {
      expect(fake.calls.filter(({ args }) => args[1] === `ssh://${alias}` && args.includes("--screenshot-out-file"))).toHaveLength(1);
      expect(fake.calls.filter(({ args }) => args[1] === `ssh://${alias}` && args.includes("openmausbot-preview"))).toHaveLength(1);
    }
  });

  it("bounds the complete slow preview, holds its lock through timed-out cleanup, and recovers", async () => {
    vi.useFakeTimers();
    try {
      const fake = fixture();
      const calls: Array<{ args: string[]; timeoutMs: number }> = [];
      const runner: VpsCommandRunner = async (args, options) => {
        const timeoutMs = options?.timeoutMs ?? 120_000;
        calls.push({ args, timeoutMs });
        if (args.includes("openmausbot-preview") || args.includes("rm")) {
          // Like defaultRunner: time out, terminate, then wait its 6s kill grace before settling.
          await new Promise((resolve) => setTimeout(resolve, timeoutMs + 6_000));
          throw new Error("Docker-over-SSH command timed out");
        }
        await new Promise((resolve) => setTimeout(resolve, args.includes("--screenshot-out-file") ? 4_000 : 2_000));
        return fake.runner(args, options);
      };
      const start = Date.now();
      let settled = false;
      const first = vpsComputerScreenshot(CONFIG, BOT_ID, runner).finally(() => { settled = true; });
      const rejected = expect(first).rejects.toMatchObject({ status: 504 });
      await vi.advanceTimersByTimeAsync(35_000);
      expect(calls.find(({ args }) => args.includes("openmausbot-preview"))?.timeoutMs).toBe(13_000);
      expect(calls.find(({ args }) => args.includes("rm"))?.timeoutMs).toBe(4_000);
      expect(vpsLifecycleBusy()).toBe(true);
      expect(settled).toBe(false);
      const joined = expect(vpsComputerScreenshot(CONFIG, BOT_ID, runner)).rejects.toMatchObject({ status: 504 });
      await vi.advanceTimersByTimeAsync(9_999);
      expect(settled).toBe(false);
      await vi.advanceTimersByTimeAsync(1);
      await Promise.all([rejected, joined]);
      expect(Date.now() - start).toBe(45_000);
      expect(calls.filter(({ args }) => args.includes("--screenshot-out-file"))).toHaveLength(1);
      expect(vpsLifecycleBusy()).toBe(false);
      await expect(vpsComputerScreenshot(CONFIG, BOT_ID, fixture().runner)).resolves.toMatchObject({ format: "png" });
    } finally { vi.useRealTimers(); }
  });

  it("shares cold status work with a capture and refreshes cache after a slow frame, not before it", async () => {
    vi.useFakeTimers();
    let release!: () => void;
    const gate = new Promise<void>((resolve) => { release = resolve; });
    try {
      const fake = fixture();
      const cfg: AppConfig = { vps: { sshAlias: "cache-preview-vps" } };
      let entered!: () => void;
      const capturing = new Promise<void>((resolve) => { entered = resolve; });
      let captures = 0;
      // The real defaultRunner/cache path with only the child transport replaced; no real provider is reached.
      spawnMock.mockImplementation((_command: string, args: string[]) => {
        const child = Object.assign(new EventEmitter(), {
          stdin: new Writable({ write: (_chunk, _encoding, callback) => callback() }),
          stdout: new PassThrough(), stderr: new PassThrough(),
          kill: () => true,
        });
        queueMicrotask(() => {
          void (async () => {
            if (args.includes("--screenshot-out-file") && ++captures === 1) { entered(); await gate; }
            const output = await fake.runner(args);
            child.stdout.end(output.stdout);
            child.stderr.end(output.stderr);
            child.emit("close", 0, null);
          })().catch((error: Error) => {
            child.stderr.end(error.message);
            child.emit("close", 1, null);
          });
        });
        return child;
      });
      const frame = vpsComputerScreenshot(cfg, BOT_ID);
      await capturing;
      const status = vpsComputerStatus(cfg, BOT_ID);
      await vi.advanceTimersByTimeAsync(12_000);
      expect(fake.calls.filter(({ args }) => args[2] === "image")).toHaveLength(1);
      release();
      await expect(frame).resolves.toMatchObject({ format: "png" });
      await expect(status).resolves.toMatchObject({ ready: true });
      await vpsComputerScreenshot(cfg, BOT_ID);
      expect(captures).toBe(2);
      expect(fake.calls.filter(({ args }) => args[2] === "image")).toHaveLength(1);
      await vpsComputerAction("stop", cfg, BOT_ID);
      await expect(vpsComputerScreenshot(cfg, BOT_ID)).rejects.toThrow(/stopped|running/);
      expect(captures).toBe(2);
    } finally { release(); spawnMock.mockReset(); vi.useRealTimers(); }
  });

  it("shares status-first cold inspection with other polls and a preview", async () => {
    const cfg: AppConfig = { vps: { sshAlias: "status-first-vps" } };
    const fake = fixture();
    let release!: () => void;
    const gate = new Promise<void>((resolve) => { release = resolve; });
    let entered!: () => void;
    const inspecting = new Promise<void>((resolve) => { entered = resolve; });
    mockTransport(async (args, options) => {
      if (args[2] === "image") { entered(); await gate; }
      return fake.runner(args, options);
    });
    const first = vpsComputerStatus(cfg, BOT_ID);
    await inspecting;
    const second = vpsComputerStatus(cfg, BOT_ID);
    const preview = vpsComputerScreenshot(cfg, BOT_ID);
    try {
      release();
      const results = await Promise.all([first, second, preview]);
      expect(results[0]).toMatchObject({ ready: true });
      expect(results[1]).toMatchObject({ ready: true });
      expect(results[2]).toMatchObject({ format: "png" });
      expect(fake.calls.filter(({ args }) => args[2] === "image")).toHaveLength(1);
    } finally {
      release();
      await Promise.allSettled([first, second, preview]);
      spawnMock.mockReset();
    }
  });

  it("keeps a preview bounded when an independently owned status poll is slower", async () => {
    vi.useFakeTimers();
    const cfg: AppConfig = { vps: { sshAlias: "slow-shared-status-vps" } };
    const fake = fixture();
    mockTransport(async (args, options) => {
      // Every command is healthy, but the full inspection outlasts the preview's budget.
      await new Promise((resolve) => setTimeout(resolve, 9_000));
      return fake.runner(args, options);
    });
    try {
      const status = vpsComputerStatus(cfg, BOT_ID);
      await vi.advanceTimersByTimeAsync(0);
      const preview = expect(vpsComputerScreenshot(cfg, BOT_ID)).rejects.toMatchObject({ status: 504 });
      await vi.advanceTimersByTimeAsync(35_000);
      await preview;
      expect(vpsLifecycleBusy()).toBe(false);
      await vi.advanceTimersByTimeAsync(20_000);
      expect((await status).ready).toBe(true);
      const refreshed = vpsComputerStatus(cfg, BOT_ID);
      await vi.advanceTimersByTimeAsync(55_000);
      expect((await refreshed).ready).toBe(true);
      expect(fake.calls.filter(({ args }) => args[2] === "image")).toHaveLength(2);
    } finally { spawnMock.mockReset(); vi.useRealTimers(); }
  });

  it("does not republish an old ready poll after stopping the container", async () => {
    const cfg: AppConfig = { vps: { sshAlias: "stale-status-vps" } };
    const fake = fixture();
    let release!: () => void;
    const gate = new Promise<void>((resolve) => { release = resolve; });
    let entered!: () => void;
    const probing = new Promise<void>((resolve) => { entered = resolve; });
    let probes = 0;
    mockTransport(async (args, options) => {
      if (args.includes("get_desktop_state") && ++probes === 1) { entered(); await gate; }
      return fake.runner(args, options);
    });
    const stale = vpsComputerStatus(cfg, BOT_ID);
    await probing;
    try {
      expect((await vpsComputerAction("stop", cfg, BOT_ID)).container).toBe("stopped");
      release();
      expect((await stale).ready).toBe(true);
      expect(await vpsComputerStatus(cfg, BOT_ID)).toMatchObject({ ready: false, container: "stopped" });
    } finally {
      release();
      await stale;
      spawnMock.mockReset();
    }
  });

  it("invalidates a late startup poll only after provisioning finishes readiness", async () => {
    const cfg: AppConfig = { vps: { sshAlias: "startup-status-vps" } };
    const fake = fixture({ container: false });
    let releaseReady!: () => void;
    const readyGate = new Promise<void>((resolve) => { releaseReady = resolve; });
    let enteredReady!: () => void;
    const readiness = new Promise<void>((resolve) => { enteredReady = resolve; });
    let releasePoll!: () => void;
    const pollGate = new Promise<void>((resolve) => { releasePoll = resolve; });
    let enteredPoll!: () => void;
    const diagnosing = new Promise<void>((resolve) => { enteredPoll = resolve; });
    let probes = 0;
    mockTransport(async (args, options) => {
      if (args.includes("get_desktop_state")) {
        if (++probes === 1) { enteredReady(); await readyGate; }
        else if (probes === 2) throw new Error("desktop is still starting");
      }
      if (args.includes("tail")) { enteredPoll(); await pollGate; }
      return fake.runner(args, options);
    });
    const provision = vpsComputerAction("provision", cfg, BOT_ID);
    await readiness;
    const stale = vpsComputerStatus(cfg, BOT_ID);
    await diagnosing;
    try {
      releaseReady();
      expect((await provision).ready).toBe(true);
      releasePoll();
      expect((await stale).ready).toBe(false);
      expect((await vpsComputerStatus(cfg, BOT_ID)).ready).toBe(true);
    } finally {
      releaseReady();
      releasePoll();
      await Promise.allSettled([provision, stale]);
      spawnMock.mockReset();
    }
  });

  it("fails cleanly when no VPS alias is configured", async () => {
    await expect(vpsComputerAction("provision", {}, BOT_ID, fixture().runner)).rejects.toThrow(/not configured/);
  });

  it("attributes a transport failure to the link, never to a missing container", async () => {
    const fake = fixture();
    const flaky: VpsCommandRunner = async (args, options) => {
      if (args[2] === "inspect") throw new Error("ssh: connect to host production-vps port 22: Connection timed out");
      return fake.runner(args, options);
    };
    const status = await vpsComputerStatus(CONFIG, BOT_ID, flaky);
    expect(status.daemonUp).toBe(false);
    expect(status.ready).toBe(false);
    expect(status.problem).toMatch(/Docker over SSH failed while checking the VPS/);

    await expect(vpsComputerAction("provision", CONFIG, BOT_ID, flaky)).rejects.toThrow(/Docker over SSH failed/);
    expect(fake.calls.some(({ args }) => args[2] === "run")).toBe(false);

    const imageFlaky: VpsCommandRunner = async (args, options) => {
      if (args[2] === "image") throw new Error("kex_exchange_identification: read: Connection reset by peer");
      return fake.runner(args, options);
    };
    const imageStatus = await vpsComputerStatus(CONFIG, BOT_ID, imageFlaky);
    expect(imageStatus.daemonUp).toBe(false);
    expect(imageStatus.problem).toMatch(/Docker over SSH failed while checking the VPS/);
  });

  it.each(["image", "inspect"])("recovers one transient %s inspection failure without recreating the computer", async (command) => {
    const fake = fixture();
    let attempts = 0;
    const runner: VpsCommandRunner = async (args, options) => {
      if (args[2] === command && ++attempts === 1) throw new Error("Docker-over-SSH command timed out");
      return fake.runner(args, options);
    };
    expect((await vpsComputerAction("provision", CONFIG, BOT_ID, runner)).ready).toBe(true);
    expect(attempts).toBe(2);
    expect(fake.calls.every(({ args }) => ["image", "inspect", "exec"].includes(args[2]!))).toBe(true);
  });

  it("bounds inspection retries and never replays a failed lifecycle command", async () => {
    const unavailable = vi.fn(async () => { throw new Error("Docker-over-SSH command timed out"); });
    const status = await vpsComputerStatus(CONFIG, BOT_ID, unavailable);
    expect(unavailable).toHaveBeenCalledTimes(2);
    expect(status).toMatchObject({ ready: false, daemonUp: false });
    expect(status.problem).toContain("Check that the VPS is online");

    const fake = fixture({ running: false });
    let starts = 0;
    const runner: VpsCommandRunner = async (args, options) => {
      if (args[2] === "start") { starts++; throw new Error("Docker-over-SSH command timed out"); }
      return fake.runner(args, options);
    };
    await expect(vpsComputerAction("start", CONFIG, BOT_ID, runner)).rejects.toThrow("timed out");
    expect(starts).toBe(1);
  });

  it.each(["Permission denied (publickey)", "Host key verification failed", "No such image"])(
    "does not retry non-transient inspection errors: %s", async (message) => {
      const fake = fixture();
      let attempts = 0;
      const runner: VpsCommandRunner = async (args, options) => {
        if (args[2] === "image") { attempts++; throw new Error(message); }
        return fake.runner(args, options);
      };
      expect((await vpsComputerStatus(CONFIG, BOT_ID, runner)).ready).toBe(false);
      expect(attempts).toBe(1);
    },
  );

  it("removes a managed container even when its image is incompatible, then provisions fresh", async () => {
    const stale = fixture({ containerImageId: `sha256:${"c".repeat(64)}` });
    expect((await vpsComputerStatus(CONFIG, BOT_ID, stale.runner)).imageMatches).toBe(false);
    await expect(vpsComputerAction("provision", CONFIG, BOT_ID, stale.runner)).rejects.toThrow(/incompatible|unsafe/);

    const removed = await vpsComputerAction("remove", CONFIG, BOT_ID, stale.runner);
    expect(removed.container).toBe("missing");
    expect(stale.calls.some(({ args }) => args[2] === "rm" && args[3] === "-f" && args[4] === CONTAINER_ID)).toBe(true);

    const rebuilt = await vpsComputerAction("provision", CONFIG, BOT_ID, stale.runner);
    expect(rebuilt.ready).toBe(true);
  });

  it("never removes a container OpenMausBot did not create", async () => {
    const unowned = fixture({ managed: false });
    await expect(vpsComputerAction("remove", CONFIG, BOT_ID, unowned.runner)).rejects.toThrow(/did not create/);
    expect(unowned.calls.some(({ args }) => args[2] === "rm")).toBe(false);

    const foreign = fixture({ environmentId: "11111111-2222-4333-8444-555555555555" });
    expect((await vpsComputerStatus(CONFIG, BOT_ID, foreign.runner)).managed).toBe(false);
    await expect(vpsComputerAction("remove", CONFIG, BOT_ID, foreign.runner)).rejects.toThrow(/did not create/);
    expect(foreign.calls.some(({ args }) => args[2] === "rm")).toBe(false);

    const absent = fixture({ container: false });
    const afterMissing = await vpsComputerAction("remove", CONFIG, BOT_ID, absent.runner);
    expect(afterMissing.container).toBe("missing");
    expect(absent.calls.some(({ args }) => args[2] === "rm")).toBe(false);
  });

  it("stops a managed container even when its image is outdated or missing, while refusing unowned containers", async () => {
    const missingNewImage = fixture({ image: false, environmentId: vpsEnvironmentId() });
    const idleStopped = await vpsComputerAction("stop", CONFIG, BOT_ID, missingNewImage.runner, () => true);
    expect(idleStopped.container).toBe("stopped");
    expect(missingNewImage.calls.some(({ args }) => args[2] === "stop" && args[3] === CONTAINER_ID)).toBe(true);

    const stale = fixture({ containerImageId: `sha256:${"c".repeat(64)}` });
    const manualStopped = await vpsComputerAction("stop", CONFIG, BOT_ID, stale.runner);
    expect(manualStopped.container).toBe("stopped");
    expect(stale.calls.some(({ args }) => args[2] === "stop" && args[3] === CONTAINER_ID)).toBe(true);

    const unowned = fixture({ managed: false });
    await expect(vpsComputerAction("stop", CONFIG, BOT_ID, unowned.runner)).rejects.toThrow(/did not create/);
    expect(unowned.calls.some(({ args }) => args[2] === "stop")).toBe(false);

    const foreign = fixture({ environmentId: "11111111-2222-4333-8444-555555555555" });
    await expect(vpsComputerAction("stop", CONFIG, BOT_ID, foreign.runner)).rejects.toThrow(/did not create/);
    expect(foreign.calls.some(({ args }) => args[2] === "stop")).toBe(false);
  });

  it("surfaces the supervisor error log when the desktop probe fails", async () => {
    const fake = fixture({ desktopProbeFails: true });
    const status = await vpsComputerStatus(CONFIG, BOT_ID, fake.runner);
    expect(status.desktopReady).toBe(false);
    expect(status.desktop_error).toContain("did not become ready");
    expect(status.problem).toContain("desktop failed to start");
    expect(fake.calls.some(({ args }) => args[2] === "exec" && args.includes("tail"))).toBe(true);
  });

  it("waits for readiness with a cheap driver probe and backoff, not full re-inspections", async () => {
    vi.useFakeTimers();
    try {
      const fake = fixture({ container: false });
      let driverProbes = 0;
      const runner: VpsCommandRunner = async (args, options) => {
        if (args[2] === "exec" && args.includes("status")) {
          driverProbes += 1;
          if (driverProbes < 4) throw new Error("driver not up yet");
        }
        return fake.runner(args, options);
      };
      const pending = vpsComputerAction("provision", CONFIG, BOT_ID, runner);
      await vi.advanceTimersByTimeAsync(10_000);
      const status = await pending;
      expect(status.ready).toBe(true);
      const desktopCalls = fake.calls.filter(({ args }) => args.includes("get_desktop_state"));
      expect(desktopCalls).toHaveLength(1);
      const healthCalls = fake.calls.filter(({ args }) => args.includes("health_report"));
      expect(healthCalls).toHaveLength(1);
      expect(driverProbes).toBeGreaterThanOrEqual(4);
    } finally {
      vi.useRealTimers();
    }
  });

  it("bounds readiness checks including slow desktop failures and final diagnostics", async () => {
    vi.useFakeTimers();
    try {
      const fake = fixture({ container: false });
      const desktopTimeouts: number[] = [];
      const runner: VpsCommandRunner = async (args, options) => {
        if (args.includes("get_desktop_state")) {
          const timeoutMs = options?.timeoutMs ?? 120_000;
          desktopTimeouts.push(timeoutMs);
          await new Promise((resolve) => setTimeout(resolve, timeoutMs + 6_000));
          throw new Error("Docker-over-SSH command timed out");
        }
        if (args.includes("tail")) await new Promise((resolve) => setTimeout(resolve, 10_000));
        return fake.runner(args, options);
      };
      const startedAt = Date.now();
      let finishedAt = Infinity;
      const pending = vpsComputerAction("provision", CONFIG, BOT_ID, runner).then((status) => {
        finishedAt = Date.now();
        return status;
      });
      await vi.advanceTimersByTimeAsync(120_000);
      expect((await pending).ready).toBe(false);
      expect(finishedAt - startedAt).toBeLessThanOrEqual(60_000);
      expect(desktopTimeouts).toHaveLength(2);
      expect(desktopTimeouts[1]).toBeLessThan(20_000);
      expect(vpsLifecycleBusy()).toBe(false);
    } finally { vi.useRealTimers(); }
  });

  it.each(["stop", "remove"] as const)("fails %s fast instead of queueing behind a long provision and drains the lock", async (action) => {
    vi.useFakeTimers();
    try {
      let releaseBuild!: () => void;
      const buildGate = new Promise<void>((resolve) => {
        releaseBuild = resolve;
      });
      const fake = fixture({ image: false, container: false });
      const slowRunner: VpsCommandRunner = async (args, options) => {
        if (args[2] === "build") await buildGate;
        return fake.runner(args, options);
      };
      const first = vpsComputerAction("provision", CONFIG, BOT_ID, slowRunner);
      // let the first action reach its (gated) docker build
      await vi.advanceTimersByTimeAsync(0);
      const second = vpsComputerAction(action, CONFIG, BOT_ID, slowRunner);
      const rejection = expect(second).rejects.toThrow(/being prepared/);
      await vi.advanceTimersByTimeAsync(5_000);
      await rejection;

      releaseBuild();
      await vi.advanceTimersByTimeAsync(10_000);
      const status = await first;
      expect(status.ready).toBe(true);
      expect(vpsLifecycleBusy()).toBe(false);
      expect((await inspectVpsForAuto(CONFIG, BOT_ID, fake.runner)).ready).toBe(true);
    } finally {
      vi.useRealTimers();
    }
  });

  it("starts the VPS for explicit Cloud, for opted-in Auto, and for every unattended run", () => {
    expect(vpsStartsForTurn({ wants: "cloud" })).toBe(true);
    expect(vpsStartsForTurn({ wants: undefined })).toBe(false);
    expect(vpsStartsForTurn({ wants: undefined, autoStartVps: true })).toBe(true);
    expect(vpsStartsForTurn({ wants: undefined, automationSource: "schedule" })).toBe(true);
    expect(vpsStartsForTurn({ wants: undefined, automationSource: "manual" })).toBe(true);
    expect(vpsStartsForTurn({ wants: "vm", automationSource: "schedule" })).toBe(false);
    expect(vpsStartsForTurn({ wants: "off", autoStartVps: true })).toBe(false);
  });

  it("names the one way on that fits what Auto's VPS check found", () => {
    const connection = "Check the VPS connection in Settings → AI → Other services.";
    expect(vpsUnavailableHint({ reachable: true })).toBe("Open Computer and enable Start VPS automatically, or choose Cloud computer to start it manually.");
    expect(vpsUnavailableHint({ reachable: false })).toBe(connection);
    expect(vpsUnavailableHint({ autoStartVps: true, reachable: true })).toBe(connection);
    expect(vpsUnavailableHint({ autoStartVps: true })).toBe(connection);
    expect(vpsUnavailableHint({})).toBe("");
    expect(vpsUnavailableHint({ automationSource: "schedule" })).toMatch(/^This scheduled run tried to start the VPS computer/);
  });
});

// A real loopback listener stands in for SSH; no host or remote daemon is used.
describe("remote desktop tunnel ownership", () => {
  function tunnelFixture() {
    const children: ReturnType<typeof fakeTunnel>[] = [];
    function fakeTunnel(args: string[]) {
      const port = Number(args[args.indexOf("-L") + 1].split(":")[1]);
      const server: Server = createServer(socket => socket.end()).listen(port, "127.0.0.1");
      const child = Object.assign(new EventEmitter(), {
        exitCode: null as number | null, killed: false, stderr: new PassThrough(),
        kill: vi.fn(() => { child.killed = true; server.close(); child.emit("close", 0); return true; }),
      });
      return child;
    }
    spawnMock.mockImplementation((_binary, args: string[]) => {
      const child = fakeTunnel(args);
      children.push(child);
      return child;
    });
    return { children, runner: fixture().runner, cleanup: () => {
      closeAllVpsDesktopTunnels();
      for (const child of children) if (!child.killed) child.kill();
    } };
  }

  async function openFixture(onViewerClosed?: () => void) {
    const { children, runner, cleanup } = tunnelFixture();
    try {
      await vpsComputerJoin(CONFIG, BOT_ID, runner, true, onViewerClosed);
      return { child: children[0]!, runner };
    } catch (error) { cleanup(); throw error; }
  }

  it("shares one pending tunnel between concurrent remote and native joins", async () => {
    const { children, runner, cleanup } = tunnelFixture();
    let release!: () => void;
    let entered!: () => void;
    const gate = new Promise<void>(resolve => { release = resolve; });
    const inspecting = new Promise<void>(resolve => { entered = resolve; });
    let inspections = 0;
    const blocked: VpsCommandRunner = async (args, options) => {
      if (args[2] === "image") { inspections++; entered(); await gate; }
      return runner(args, options);
    };
    try {
      const first = vpsComputerJoin(CONFIG, BOT_ID, blocked, true);
      await inspecting;
      const second = vpsComputerJoin(CONFIG, BOT_ID, blocked);
      release();
      const joined = await Promise.all([first, second]);
      expect(joined[0].joinUrl).toBe(joined[1].joinUrl);
      expect(inspections).toBe(1);
      expect(children).toHaveLength(1);
      vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
      const leave = vpsDesktopConnection(BOT_ID)!.retain();
      leave();
      await vi.advanceTimersByTimeAsync(30_001);
      expect(children[0]!.killed).toBe(false);
      closeAllVpsDesktopTunnels();
      expect(children.every(child => child.killed)).toBe(true);
    } finally { release(); cleanup(); vi.useRealTimers(); }
  });

  it("ignores an old tunnel's queued expiry and close after replacement", async () => {
    const { children, runner, cleanup } = tunnelFixture();
    const timers = vi.spyOn(globalThis, "setTimeout");
    const closed = vi.fn();
    try {
      await vpsComputerJoin(CONFIG, BOT_ID, runner, true, closed);
      const expired = timers.mock.calls.find(([, delay]) => delay === 30_000)![0] as () => void;
      closeAllVpsDesktopTunnels();
      await vpsComputerJoin(CONFIG, BOT_ID, runner, true);
      expired();
      children[0]!.emit("close", 0);
      expect(closed).not.toHaveBeenCalled();
      expect(vpsDesktopConnection(BOT_ID)?.live()).toBe(true);
      expect(children[1]!.killed).toBe(false);
    } finally { timers.mockRestore(); cleanup(); }
  });

  it("cancels pending joins when all tunnels close and allows a fresh join", async () => {
    const { children, runner, cleanup } = tunnelFixture();
    let release!: () => void;
    let entered!: () => void;
    const gate = new Promise<void>(resolve => { release = resolve; });
    const inspecting = new Promise<void>(resolve => { entered = resolve; });
    const blocked: VpsCommandRunner = async (args, options) => {
      if (args[2] === "image") { entered(); await gate; }
      return runner(args, options);
    };
    const first = vpsComputerJoin(CONFIG, BOT_ID, blocked, true);
    const rejected = expect(first).rejects.toThrow(/closed|cancel/i);
    try {
      await inspecting;
      closeAllVpsDesktopTunnels();
      release();
      await rejected;
      expect(children).toHaveLength(0);
      await expect(vpsComputerJoin(CONFIG, BOT_ID, runner, true)).resolves.toMatchObject({ state: "running" });
      expect(children).toHaveLength(1);
    } finally { release(); cleanup(); }
  });

  it("retains multiple tabs, survives reconnect, then reclaims the idle tunnel", async () => {
    const { child } = await openFixture();
    try {
      const connection = vpsDesktopConnection(BOT_ID)!;
      expect(connection.password).toBeTruthy();
      const first = connection.retain();
      const second = connection.retain();
      vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
      first(); first();
      await vi.advanceTimersByTimeAsync(30_001);
      expect(child.killed).toBe(false);
      second();
      await vi.advanceTimersByTimeAsync(15_000);
      const reconnected = connection.retain();
      await vi.advanceTimersByTimeAsync(30_001);
      expect(connection.live()).toBe(true);
      reconnected();
      await vi.advanceTimersByTimeAsync(30_001);
      expect(child.kill).toHaveBeenCalledTimes(1);
      expect(connection.live()).toBe(false);
      expect(vpsDesktopConnection(BOT_ID)).toBeUndefined();
    } finally { closeAllVpsDesktopTunnels(); vi.useRealTimers(); }
  });

  it("does not close a native owner's tunnel when a remote tab leaves", async () => {
    const { child, runner } = await openFixture();
    try {
      const release = vpsDesktopConnection(BOT_ID)!.retain();
      vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
      const native = await vpsComputerJoin(CONFIG, BOT_ID, runner);
      expect(native.joinUrl).toMatch(/^http:\/\/127\.0\.0\.1:/);
      release();
      await vi.advanceTimersByTimeAsync(30_001);
      expect(child.killed).toBe(false);
      closeAllVpsDesktopTunnels();
      expect(child.kill).toHaveBeenCalledTimes(1);
    } finally { closeAllVpsDesktopTunnels(); vi.useRealTimers(); }
  });
  it.each(["grace expiry", "SSH exit"])("renews the full VPS idle window after %s", async (end) => {
    const stop = vi.fn(async () => {});
    const timer = new ComputerIdleTimer(300_000, () => Boolean(vpsDesktopConnection(BOT_ID)), stop);
    const { child } = await openFixture(() => timer.touch());
    vi.useFakeTimers();
    try {
      timer.touch();
      const release = vpsDesktopConnection(BOT_ID)!.retain();
      await vi.advanceTimersByTimeAsync(240_000);
      release();
      if (end === "SSH exit") child.kill();
      else await vi.advanceTimersByTimeAsync(30_000);
      expect(vpsDesktopConnection(BOT_ID)).toBeUndefined();
      await vi.advanceTimersByTimeAsync(299_999);
      expect(stop).not.toHaveBeenCalled();
      await vi.advanceTimersByTimeAsync(1);
      expect(stop).toHaveBeenCalledTimes(1);
    } finally { timer.cancel(); closeAllVpsDesktopTunnels(); vi.useRealTimers(); }
  });

  it("waits a full idle window after a short desktop view closes", async () => {
    const stop = vi.fn(async () => {});
    const timer = new ComputerIdleTimer(1000, () => Boolean(vpsDesktopConnection(BOT_ID)), stop);
    await openFixture(() => timer.touch());
    vi.useFakeTimers();
    try {
      timer.touch();
      await vi.advanceTimersByTimeAsync(400);
      expect(closeVpsDesktopTunnel(BOT_ID)).toEqual({ closed: true });
      await vi.advanceTimersByTimeAsync(999);
      expect(stop).not.toHaveBeenCalled();
      await vi.advanceTimersByTimeAsync(1);
      expect(stop).toHaveBeenCalledTimes(1);
    } finally { timer.cancel(); closeAllVpsDesktopTunnels(); vi.useRealTimers(); }
  });

  it("keeps remote tabs connected when the native viewer closes", async () => {
    const { child, runner } = await openFixture();
    try {
      const release = vpsDesktopConnection(BOT_ID)!.retain();
      vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
      await vpsComputerJoin(CONFIG, BOT_ID, runner);
      expect(closeVpsDesktopTunnel(BOT_ID)).toEqual({ closed: false });
      expect(child.killed).toBe(false);
      release();
      await vi.advanceTimersByTimeAsync(30_001);
      expect(child.kill).toHaveBeenCalledTimes(1);
    } finally { closeAllVpsDesktopTunnels(); vi.useRealTimers(); }
  });

  it("stops an open viewer tunnel on a server switch without firing onViewerClosed, so the next join opens a fresh tunnel", async () => {
    const closed = vi.fn();
    const { child, runner } = await openFixture(closed);
    try {
      const release = vpsDesktopConnection(BOT_ID)!.retain();
      expect(stopVpsDesktopTunnel(BOT_ID)).toBe(true);
      expect(child.killed).toBe(true);
      release();
      child.emit("close", 0);
      expect(closed).not.toHaveBeenCalled();
      expect(vpsDesktopConnection(BOT_ID)).toBeUndefined();
      const next = await vpsComputerJoin({ vps: { sshAlias: "alpha-vps" } }, BOT_ID, runner, true);
      expect(next.state).toBe("running");
      expect(vpsDesktopConnection(BOT_ID)?.live()).toBe(true);
    } finally { closeAllVpsDesktopTunnels(); }
  });

  it("checks whether a managed VPS desktop container is running without throwing on unreachable or missing hosts", async () => {
    expect(await vpsComputerRunning(CONFIG, BOT_ID, fixture({ running: true }).runner)).toBe(true);
    expect(await vpsComputerRunning(CONFIG, BOT_ID, fixture({ running: false }).runner)).toBe(false);
    expect(await vpsComputerRunning(CONFIG, BOT_ID, fixture({ container: false }).runner)).toBe(false);
    expect(await vpsComputerRunning(CONFIG, BOT_ID, fixture({ managed: false }).runner)).toBe(false);
    expect(await vpsComputerRunning(CONFIG, BOT_ID, fixture({ environmentId: "another-installation" }).runner)).toBe(false);
    expect(await vpsComputerRunning({}, BOT_ID, fixture().runner)).toBe(false);
    expect(await vpsComputerRunning(CONFIG, BOT_ID, async () => { throw new Error("ssh: connect timeout"); })).toBe(false);
  });
});

describe("a missing Docker CLI", () => {
  it("gives every platform it ships one install line", () => {
    expect(dockerCliInstallCommand("darwin")).toBe("brew install docker");
    expect(dockerCliInstallCommand("win32")).toBe("winget install -e --id Docker.DockerCLI");
    expect(dockerCliInstallCommand("linux")).toBe("sudo apt install docker-ce-cli");
    expect(dockerCliInstallCommand("freebsd")).toBeNull();
  });

  it("names that install line instead of the spawn error, for the inventory and the status", async () => {
    const missing = Object.assign(new Error("Docker-over-SSH could not start: spawn docker ENOENT"), { code: "ENOENT" });
    const runner: VpsCommandRunner = async () => {
      throw missing;
    };
    const command = dockerCliInstallCommand(process.platform)!;
    const inventory = await listManagedVpsComputers(CONFIG, [], runner);
    expect(inventory.available).toBe(false);
    expect(inventory.unreachable).toBeUndefined();
    expect(inventory.problem).toContain(command);
    expect(inventory.problem).not.toMatch(/ENOENT/);

    const status = await vpsComputerStatus(CONFIG, BOT_ID, runner);
    expect(status.problem).toContain(command);
    expect(status.problem).not.toMatch(/ENOENT/);
  });
});

describe("a VPS inventory that fails", () => {
  it("is unreachable only when the host gave no list at all", async () => {
    const silent: VpsCommandRunner = async () => {
      throw new VpsHostUnreachableError("ssh: connect to host fixture port 22: Connection timed out");
    };
    expect(await listManagedVpsComputers(CONFIG, [], silent)).toMatchObject({ available: false, unreachable: true });

    // SSH got through and the daemon said no: the host is there, so its computers may be too.
    const refused: VpsCommandRunner = async () => {
      throw new Error("permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock");
    };
    const refusal = await listManagedVpsComputers(CONFIG, [], refused);
    expect(refusal.available).toBe(false);
    expect(refusal.unreachable).toBeUndefined();

    const garbled: VpsCommandRunner = async () => ({ stdout: "not-a-container-id\n", stderr: "" });
    const unverified = await listManagedVpsComputers(CONFIG, [], garbled);
    expect(unverified.available).toBe(false);
    expect(unverified.unreachable).toBeUndefined();

    const answers: VpsCommandRunner = async () => ({ stdout: "", stderr: "" });
    const both = await listManagedVpsComputers(CONFIG, [], async (args, options) =>
      args.includes("ssh://other") ? garbled(args, options) : silent(args, options), ["fixture", "other"]);
    expect(both.available).toBe(false);
    expect(both.unreachable).toBeUndefined();
    expect((await listManagedVpsComputers(CONFIG, [], answers)).unreachable).toBeUndefined();
  });

  it("tells an SSH failure from a Docker refusal on the real command path", async () => {
    try {
      mockTransport(async () => {
        throw new Error("error during connect: command [ssh -- production-vps docker system dial-stdio] has exited with exit status 255, stderr=ssh: Could not resolve hostname production-vps");
      });
      expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBe(true);

      mockTransport(async () => {
        throw new Error("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?");
      });
      const refused = await listManagedVpsComputers(CONFIG, []);
      expect(refused.available).toBe(false);
      expect(refused.unreachable).toBeUndefined();

      // Windows has no shared SSH master to check first.
      if (process.platform !== "win32") {
        vi.mocked(ensureVpsSshMaster).mockRejectedValueOnce(new Error("ssh: Could not resolve hostname production-vps"));
        expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBe(true);
        // The host answered with a changed key, or the local ssh never started: the host may still be up.
        vi.mocked(ensureVpsSshMaster).mockRejectedValueOnce(new Error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @\nHost key verification failed."));
        expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBeUndefined();
        vi.mocked(ensureVpsSshMaster).mockRejectedValueOnce(new Error("spawn ssh ENOENT"));
        expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBeUndefined();
        vi.mocked(ensureVpsSshMaster).mockRejectedValueOnce(Object.assign(new Error("VPS SSH initialization timed out"), { killed: true }));
        expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBe(true);
      }
    } finally { spawnMock.mockReset(); }
  });
});