Skip to content

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

GET /api/computers/bots: each bot's computer from what the server already holds (#7154)

Milind Soni77f41d352221
diff --git a/server/computer-frames.ts b/server/computer-frames.ts
index 85e315b7b6..2c9b23f769 100644
--- a/server/computer-frames.ts
+++ b/server/computer-frames.ts
@@ -203,6 +203,8 @@ export function createComputerFrames(options: ComputerFramesOptions) {
return machine ? newest(machine.boxId) : undefined;
},
available: () => available,
+ /** When the machines were last listed; null before the first listing. */
+ listedAt: (): number | null => (listedAt === -Infinity ? null : listedAt),
watching: () => timer !== null,
captures: () => captures,
tick,
diff --git a/server/container-computer.ts b/server/container-computer.ts
index 214543fe68..92112188c8 100644
--- a/server/container-computer.ts
+++ b/server/container-computer.ts
@@ -1003,7 +1003,7 @@ export async function containerComputerScreenshot(
const screenshotStatusCache = new Map<
string,
{ status: ContainerComputerStatus; expiresAt: number }
->();
+>(); /** The status a Local VM's last screen capture read, however old, and when: never a new one. */ export function lastLocalVmStatus(target: LocalVmTarget): { status: ContainerComputerStatus; at: number } | null { const hit = screenshotStatusCache.get(target.key); return hit ? { status: hit.status, at: hit.expiresAt - SCREENSHOT_STATUS_TTL_MS } : null; }
const containerMcpPath = SPAWNED_PROXIES.containerMcp;
diff --git a/server/index.ts b/server/index.ts
index 59e37f4bee..1157980893 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12267,7 +12267,7 @@ ROUTES.push(createComputerRoutes({
managedBoatOwners, providerTransitionMessage, botHasActiveTurn, localVmLeaseKey: sharedVm.leaseKey, botComputerControlSnapshot: sharedVm.snapshot,
computerPreviewBot, computerPreviewSurface, claimTeamComputerLifecycle, claimBotComputerLifecycle,
claimBoatInventoryRequest, claimManagedBoatMutation, claimManagedVpsMutation, cloudComputerUsed: owner => cloudComputerPower.used(owner), boatRecovery, cloudComputerOwner: botComputerControlKey,
-}));
+ botComputers: { surfacePlan: (bot, threadId) => turnSurfacePlan(bot, undefined, threadId), visibleFor: (auth) => visibleTo(viewerFor(auth)), engineCapabilities: (bot) => registry.get(bot.modelSelection.instanceId)?.adapter.capabilities, cloudHome: Boolean(CLOUD_HOME), thisComputerConnected: () => desktopComputer.connection() !== null } }));
ROUTES.push(createStatusRoutes({
store, cfg,
staticDir: STATIC_DIR,
diff --git a/server/routes/bot-computers.test.ts b/server/routes/bot-computers.test.ts
new file mode 100644
index 0000000000..07fd6e73aa
--- /dev/null
+++ b/server/routes/bot-computers.test.ts
@@ -0,0 +1,238 @@
+// Every export of the provider, VPS and Local VM modules, and every way to start a process, is a counting stand-in here:
+// the only calls this route may make are the reads of what the server already holds.
+import { mkdtempSync, rmSync } from "node:fs";
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { BotComputersPayload } from "../../shared/bot-computers.ts";
+import * as boat from "../boat.ts";
+import { boatHealth } from "../boat-health.ts";
+import { teamRoleScopes, type TeamRole } from "../cloud-team.ts";
+import { createComputerFrames } from "../computer-frames.ts";
+import * as container from "../container-computer.ts";
+import { requiredScope, resolveRequestAuth, type RequestAuth } from "../request-auth.ts";
+import { SessionRegistry } from "../sessions.ts";
+import { resolveSurface } from "../surface.ts";
+import type { BotRecord, TaskRecord } from "../store.ts";
+import { teamComputerOwner } from "../team-computers.ts";
+import * as vps from "../vps-computer.ts";
+import { BOT_COMPUTERS_PATH, botComputerRows, createBotComputersRoute, type BotComputersHost, type BotComputersRouteDeps } from "./bot-computers.ts";
+import { createComputerRoutes, type ComputerRouteDeps } from "./computers.ts";
+import { PASS, type RouteContext } from "./table.ts";
+
+const seams = vi.hoisted(() => {
+ const calls: string[] = [];
+ const reads = new Set(["boat.boatIdOf", "boat.deadBoatOf", "vps.lastVpsStatus", "vps.vpsContainerName", "container.lastLocalVmStatus"]);
+ const isClass = (fn: unknown) => typeof fn === "function" && /^class\b/.test(Function.prototype.toString.call(fn));
+ const counted = (name: string, mod: Record<string, unknown>, allowed: (key: string) => boolean) => Object.fromEntries(Object.entries(mod).map(([key, value]) => {
+ if (typeof value !== "function" || isClass(value)) return [key, value];
+ return [key, vi.fn((...args: unknown[]) => {
+ calls.push(`${name}.${key}`);
+ if (!allowed(`${name}.${key}`)) throw new Error(`${name}.${key} looks at a computer`);
+ return (value as (...a: unknown[]) => unknown)(...args);
+ })];
+ }));
+ return { calls, reads, counted };
+});
+
+vi.mock("../boat.ts", async (actual) => seams.counted("boat", await actual(), (key) => seams.reads.has(key)));
+vi.mock("../vps-computer.ts", async (actual) => seams.counted("vps", await actual(), (key) => seams.reads.has(key)));
+vi.mock("../container-computer.ts", async (actual) => seams.counted("container", await actual(), (key) => seams.reads.has(key)));
+vi.mock("node:child_process", async (actual) => {
+ const real = await actual<typeof import("node:child_process")>();
+ const names = ["spawn", "spawnSync", "exec", "execSync", "execFile", "execFileSync", "fork"] as const;
+ return { ...real, default: { ...real, ...seams.counted("child_process", Object.fromEntries(names.map((n) => [n, real[n]])), () => false) },
+ ...seams.counted("child_process", Object.fromEntries(names.map((n) => [n, real[n]])), () => false) };
+});
+
+const fetchCalls = vi.fn(async () => { throw new Error("fetch looks at a computer"); });
+beforeEach(() => { seams.calls.length = 0; fetchCalls.mockClear(); vi.stubGlobal("fetch", fetchCalls); });
+afterEach(() => { vi.unstubAllGlobals(); boatHealth.clear(); vi.mocked(boat.boatIdOf).mockReset(); vi.mocked(vps.lastVpsStatus).mockReset(); vi.mocked(container.lastLocalVmStatus).mockReset(); });
+
+const TEAM = { id: "11111111-1111-4111-8111-111111111111", name: "Design desktop", section: "Design" };
+const SEEN_VM = "bot:seen";
+
+const bot = (id: string, fields: Partial<BotRecord> = {}, tasks: Partial<TaskRecord>[] = []): BotRecord =>
+ ({ id, name: id, threadId: `${id}-main`, tasks: tasks.map((task, i) => ({ threadId: `${id}-t${i}`, ...task })), ...fields }) as unknown as BotRecord;
+
+/** turnSurfacePlan's answer: a chat's pin, else Works on; a team bot always the cloud, as index.ts forces it. */
+const surfacePlan: BotComputersHost["surfacePlan"] = (b, threadId) => {
+ const team = b.section === "Design" && b.computer === undefined;
+ const task = team || !threadId ? undefined : b.tasks?.find((one) => one.threadId === threadId);
+ return resolveSurface({ destination: team ? "cloud" : b.computer, pinnedSurface: task?.surface, browserOn: b.browser !== false });
+};
+
+function fixture(bots: BotRecord[], over: Partial<BotComputersHost> = {}) {
+ const host: BotComputersHost = {
+ surfacePlan, visibleFor: () => ({ bot: () => true, thread: () => true }),
+ engineCapabilities: () => ({ computerMcp: true, localComputerMcp: true }), cloudHome: false, thisComputerConnected: () => true, ...over,
+ };
+ const frames = createComputerFrames({
+ listMachines: vi.fn(async () => { throw new Error("listing looks at the provider"); }),
+ capture: vi.fn(async () => { throw new Error("capture looks at a screen"); }),
+ turnFrame: () => undefined, working: () => false, held: () => false, tickMs: 1e9,
+ });
+ const deps: BotComputersRouteDeps = {
+ cfg: { vps: { sshAlias: "hetz" }, vpsServers: [{ name: "Big box", sshAlias: "hetz" }], computerName: "Studio Mac" } as BotComputersRouteDeps["cfg"],
+ store: { bots, tasks: (id: string) => bots.find((b) => b.id === id)?.tasks ?? [] },
+ teamComputers: { forBot: (b) => (b.section === "Design" && b.computer === undefined && b.cloudBackend !== "vps" ? { ...TEAM, createdAt: 0, requestId: "r" } as never : undefined) },
+ frames, localVmSeen: new Set([SEEN_VM]), localVmActiveThreads: new Map(),
+ localVmTargetForStatus: (botId, threadId) => ({ key: threadId === "pool-t0" ? "pool:2" : botId === "seen" ? SEEN_VM : "shared", containerName: "c", workspaceDir: "/w", viewerPort: null, label: "l" }),
+ botComputers: host, now: () => 1_000, platform: "darwin",
+ };
+ return { deps, frames };
+}
+
+const call = async (handler: ReturnType<typeof createBotComputersRoute>, auth: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] }) => {
+ const sent: Array<{ status: number; body: BotComputersPayload }> = [];
+ const out = await handler({
+ req: { headers: {} } as IncomingMessage, res: { setHeader: () => {} } as unknown as ServerResponse,
+ url: new URL(`http://127.0.0.1${BOT_COMPUTERS_PATH}`), path: BOT_COMPUTERS_PATH, method: "GET", auth,
+ json: ((_res: ServerResponse, status: number, body: BotComputersPayload) => { sent.push({ status, body }); }) as RouteContext["json"],
+ readBody: (async () => ({})) as RouteContext["readBody"],
+ });
+ return { out, sent };
+};
+
+const everyKind = () => [
+ bot("own", { computer: "cloud" }),
+ bot("ted", { section: "Design" }, [{ surface: "vm" }]),
+ bot("vee", { computer: "cloud", cloudBackend: "vps" }),
+ bot("vm", { computer: "vm" }, [{ surface: "local" }, { surface: "local", archivedAt: 5 }]),
+ bot("loc", { computer: "local" }),
+ bot("web", { computer: "browser" }),
+ bot("nil", { computer: "off" }),
+ bot("auto"),
+ bot("seen"),
+ bot("gone", { computer: "cloud", hidden: true }),
+];
+
+describe("GET /api/computers/bots", () => {
+ it("reads only what the server holds: no provider, VPS, Docker, SSH, process or screen call", async () => {
+ const { deps } = fixture(everyKind());
+ // The real wiring, with the map's own frames cache: every other dependency records the call and refuses it.
+ const asked: string[] = [];
+ const real = { ...deps, computerControl: { snapshot: () => ({ held: false }) }, managedBoatOwners: () => [], computerProviderConfigTransitions: new Set(),
+ teamComputers: { ...deps.teamComputers, list: () => [TEAM] }, botHasActiveTurn: () => false, teamComputerInUse: () => false };
+ const handler = createComputerRoutes(new Proxy(real, {
+ get: (target, key) => (key in target ? target[key as keyof typeof target] : (...args: unknown[]) => { asked.push(String(key)); throw new Error(`${String(key)}(${args.length})`); }),
+ }) as unknown as ComputerRouteDeps);
+ asked.length = 0;
+ seams.calls.length = 0;
+ const { out, sent } = await call(handler);
+ expect(out).not.toBe(PASS);
+ expect(sent[0]!.status).toBe(200);
+ expect(sent[0]!.body.rows.length).toBeGreaterThan(8);
+ expect(seams.calls.filter((name) => !seams.reads.has(name))).toEqual([]);
+ expect(fetchCalls).not.toHaveBeenCalled();
+ expect(asked).toEqual([]);
+ });
+
+ it("names each bot's computer, a chat with its own place, and Auto only where it needs no look", async () => {
+ const { deps } = fixture(everyKind());
+ boatHealth.answered("box_own");
+ vi.mocked(boat.boatIdOf).mockImplementation((owner) => (owner === "own" ? "box_own" : null));
+ vi.mocked(vps.lastVpsStatus).mockImplementation(() => ({ status: { daemonUp: true, container: "stopped", desktopReady: false, ready: false } as never, at: 700 }));
+ const { sent } = await call(createBotComputersRoute(deps));
+ const rows = sent[0]!.body.rows;
+ expect(sent[0]!.body.now).toBe(1_000);
+ const by = (botId: string, threadId?: string) => rows.find((row) => row.botId === botId && row.threadId === threadId);
+ expect(by("own")).toMatchObject({ kind: "cloud", computerId: "cloud:own", boxId: "box_own", state: "ready", name: null });
+ expect(by("ted")).toMatchObject({ kind: "cloud", computerId: `cloud:${teamComputerOwner(TEAM.id)}`, teamComputerId: TEAM.id, name: "Design desktop", state: "unknown", stateAt: null });
+ expect(by("ted", "ted-t0")).toBeUndefined();
+ expect(by("vee")).toEqual({ botId: "vee", kind: "vps", computerId: `vps:hetz/${vps.vpsContainerName("vee")}`, name: "Big box", state: "asleep", stateAt: 700,
+ vps: { serverId: "vps:hetz", alias: "hetz", container: vps.vpsContainerName("vee") } });
+ expect(by("vm")).toMatchObject({ kind: "vm", computerId: "vm:shared", state: "unknown" });
+ expect(by("vm", "vm-t0")).toMatchObject({ kind: "local", computerId: "local", name: "Studio Mac", state: "ready", stateAt: 1_000 });
+ expect(by("vm", "vm-t1")).toBeUndefined();
+ expect(by("loc")).toMatchObject({ kind: "local", computerId: "local" });
+ expect(by("web")).toMatchObject({ kind: "browser", computerId: null, state: "unknown" });
+ expect(by("nil")).toMatchObject({ kind: "off", computerId: null, state: "none" });
+ expect(by("auto")).toMatchObject({ kind: "auto", autoKind: "local", computerId: "local" });
+ expect(by("seen")).toEqual({ botId: "seen", kind: "auto", computerId: null, name: null, state: "unknown", stateAt: null });
+ expect(by("gone")).toBeUndefined();
+ });
+
+ it("resolves Auto to the VPS or the browser when nothing else could be picked, and keeps a pool seat per chat", async () => {
+ const bots = [bot("vee", { cloudBackend: "vps" }), bot("web"), bot("pool", { computer: "vm" }, [{ threadId: "pool-t0" } as Partial<TaskRecord>])];
+ const { deps } = fixture(bots, { thisComputerConnected: () => false });
+ vi.mocked(container.lastLocalVmStatus).mockImplementation((target) => (target.key === "pool:2" ? { status: { daemonUp: true, container: "running", desktopReady: true, ready: true } as never, at: 900 } : null));
+ const rows = botComputerRows(deps, { bot: () => true, thread: () => true });
+ expect(rows.find((row) => row.botId === "vee")).toMatchObject({ kind: "auto", autoKind: "vps", vps: { alias: "hetz" }, state: "unknown" });
+ expect(rows.find((row) => row.botId === "web")).toMatchObject({ kind: "auto", autoKind: "browser" });
+ expect(rows.find((row) => row.threadId === "pool-t0")).toMatchObject({ kind: "vm", computerId: "vm:pool:2", state: "ready", stateAt: 900 });
+ expect(botComputerRows(fixture(bots, { cloudHome: true }).deps, { bot: () => true, thread: () => true })
+ .find((row) => row.botId === "web")).toMatchObject({ autoKind: "browser" });
+ });
+
+ it("reads a cloud desktop from the map's last listing, and one that stopped answering as unreachable", async () => {
+ const { deps, frames } = fixture([bot("own", { computer: "cloud" }), bot("new", { computer: "cloud" })]);
+ const listed = createComputerFrames({
+ listMachines: async () => [{ owner: "own", boxId: "box_own", state: "archived" }],
+ capture: async () => ({ data: "", mime: "image/jpeg" }), turnFrame: () => undefined, working: () => false, held: () => false, tickMs: 1e9,
+ });
+ await listed.refresh();
+ const rows = botComputerRows({ ...deps, frames: listed }, { bot: () => true, thread: () => true });
+ expect(rows[0]).toMatchObject({ computerId: "cloud:own", boxId: "box_own", state: "asleep" });
+ expect(rows[1]).toMatchObject({ computerId: "cloud:new", state: "none" });
+ expect(rows[1]!.stateAt).toBe(listed.listedAt());
+ vi.useFakeTimers({ toFake: ["Date"] });
+ try {
+ for (const at of [10_000, 40_000, 71_000]) { vi.setSystemTime(at); boatHealth.unanswered("box_own"); }
+ } finally { vi.useRealTimers(); }
+ expect(botComputerRows({ ...deps, frames: listed }, { bot: () => true, thread: () => true })[0]).toMatchObject({ state: "unreachable", stateAt: 10_000 });
+ expect(frames.watching()).toBe(false);
+ });
+
+ it("shows a person only the bots and chats they can see", async () => {
+ const bots = [bot("mine", { computer: "vm" }, [{ surface: "local" }]), bot("theirs", { computer: "cloud" })];
+ const { deps } = fixture(bots, { visibleFor: (auth) => ({ bot: (id) => auth.kind === "loopback" || id === "mine", thread: () => auth.kind === "loopback" }) });
+ const member = { kind: "session", scopes: ["admin", "client"], via: "bearer", session: { id: "s" } } as unknown as RequestAuth;
+ const { sent } = await call(createBotComputersRoute(deps), member);
+ expect(sent[0]!.body.rows).toEqual([expect.objectContaining({ botId: "mine", kind: "vm" })]);
+ expect((await call(createBotComputersRoute(deps))).sent[0]!.body.rows.map((row) => row.threadId ?? row.botId)).toEqual(["mine", "mine-t0", "theirs"]);
+ });
+});
+
+describe("who may read it", () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-bot-computers-"));
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+ it("is an admin's, like every computer route: a member's or a chat-only session is refused at the gate", () => {
+ expect(requiredScope("GET", BOT_COMPUTERS_PATH)).toBe("admin");
+ expect(requiredScope("GET", BOT_COMPUTERS_PATH, { sharedComputers: true })).toBe("admin");
+ const sessions = new SessionRegistry({ file: join(dir, "sessions.json") });
+ const ask = (token: string) => resolveRequestAuth({ method: "GET", headers: { host: "127.0.0.1:1", authorization: `Bearer ${token}` }, socket: { remoteAddress: "127.0.0.1" } } as unknown as IncomingMessage,
+ { sessions, cookieName: "c", streamPath: "/api/events", url: new URL(`http://127.0.0.1:1${BOT_COMPUTERS_PATH}`) });
+ const teamSession = (role: TeamRole) => {
+ const opened = sessions.openPairing({ scopes: teamRoleScopes(role), member: { email: `${role}@acme.test`, role }, memberCheckedAt: Date.now() });
+ const paired = sessions.exchange({ code: opened.code, label: "Device", source: "203.0.113.9" });
+ if (!paired.ok) throw new Error(paired.error);
+ return paired.token;
+ };
+ const chatOnly = sessions.issue({ label: "Phone", scopes: ["client"] }).token;
+ expect(sessions.hasChatOnlyAccess()).toBe(true);
+ expect(ask(teamSession("member"))).toMatchObject({ auth: null, status: 403 });
+ expect(ask(chatOnly)).toMatchObject({ auth: null, status: 403 });
+ expect(ask(teamSession("admin")).auth).toMatchObject({ kind: "session" });
+ expect(ask(sessions.issue({ label: "Mac", scopes: ["admin", "client"] }).token).auth).toMatchObject({ kind: "session" });
+ });
+});
+
+describe("cost", () => {
+ it("answers for 200 bots well inside a 5 s poll", async () => {
+ const bots = Array.from({ length: 200 }, (_, i) => bot(`b${i}`, [{ computer: "cloud" }, { section: "Design" }, { computer: "cloud", cloudBackend: "vps" }, { computer: "vm" }, {}][i % 5] as Partial<BotRecord>,
+ Array.from({ length: 30 }, (_, t) => (t % 6 === 0 ? { surface: "local" as const } : {}))));
+ const { deps } = fixture(bots);
+ const handler = createBotComputersRoute(deps);
+ await call(handler);
+ const runs = 50;
+ const started = performance.now();
+ let bytes = 0;
+ for (let i = 0; i < runs; i++) bytes = JSON.stringify((await call(handler)).sent[0]!.body).length;
+ const perCall = (performance.now() - started) / runs;
+ console.info(`GET ${BOT_COMPUTERS_PATH}: 200 bots, 6,000 chats: ${perCall.toFixed(2)} ms a call, ${bytes} bytes`);
+ expect(perCall).toBeLessThan(50);
+ });
+});
diff --git a/server/routes/bot-computers.ts b/server/routes/bot-computers.ts
new file mode 100644
index 0000000000..379267e93b
--- /dev/null
+++ b/server/routes/bot-computers.ts
@@ -0,0 +1,171 @@
+// Polled every few seconds by a devices map, so it reads only what this server already holds: the bots, the
+// config, and the last answers other code got. It never looks at a computer, a provider, Docker, SSH or a screen.
+import type { BotComputerKind, BotComputerRow, BotComputersPayload, BotComputerState } from "../../shared/bot-computers.ts";
+import { boatIdOf, deadBoatOf } from "../boat.ts";
+import { boatHealth } from "../boat-health.ts";
+import { mapComputerState, type ComputerFrames } from "../computer-frames.ts";
+import type { AppConfig } from "../config.ts";
+import { lastLocalVmStatus, type LocalVmTarget } from "../container-computer.ts";
+import { answerAsleep, backgroundWhileAsleep } from "../cloud-power.ts";
+import { shouldMountLocalComputer } from "../local-routing.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import type { BotRecord, Store } from "../store.ts";
+import type { SurfacePlan } from "../surface.ts";
+import { teamComputerOwner, type TeamComputers } from "../team-computers.ts";
+import { lastVpsStatus, vpsContainerName } from "../vps-computer.ts";
+import { vpsConfigForBot, vpsSshAliasForBot } from "../vps-hosts.ts";
+import { PASS, type RouteHandler } from "./table.ts";
+
+export const BOT_COMPUTERS_PATH = "/api/computers/bots";
+
+/** What index.ts knows about a bot's turns; every member answers from memory. */
+export interface BotComputersHost {
+ /** The place a turn in this chat (or the bot's own) would get, as turnSurfacePlan says. */
+ surfacePlan(bot: BotRecord, threadId?: string): Pick<SurfacePlan, "computer" | "browser">;
+ visibleFor(auth: RequestAuth): { bot(botId: string): boolean; thread(threadId: string): boolean };
+ engineCapabilities(bot: BotRecord): { computerMcp?: boolean; localComputerMcp?: boolean } | undefined;
+ cloudHome: boolean;
+ /** The desktop app handed this server its computer's driver. */
+ thisComputerConnected(): boolean;
+}
+
+export interface BotComputersRouteDeps {
+ cfg: AppConfig;
+ store: Pick<Store, "bots" | "tasks">;
+ teamComputers: Pick<TeamComputers, "forBot">;
+ frames: Pick<ComputerFrames, "machine" | "available" | "listedAt">;
+ localVmSeen: Pick<Set<string>, "has">;
+ localVmActiveThreads: Pick<Map<string, string>, "has">;
+ localVmTargetForStatus(botId: string, threadId?: string): LocalVmTarget;
+ botComputers: BotComputersHost;
+ now?(): number;
+ platform?: NodeJS.Platform;
+}
+
+type Place = Omit<BotComputerRow, "botId" | "threadId">;
+type Reading = { state: BotComputerState; at: number | null };
+
+const UNKNOWN: Reading = { state: "unknown", at: null };
+
+function newest(readings: readonly Reading[]): Reading {
+ return readings.reduce<Reading | null>((best, one) => (!best || (one.at ?? -1) > (best.at ?? -1) ? one : best), null) ?? UNKNOWN;
+}
+
+/** A desktop container, a Local VM's or a VPS computer's, by the last status read of it. */
+export function containerState(status: { daemonUp: boolean; container: "running" | "stopped" | "missing"; desktopReady: boolean; ready: boolean }): BotComputerState {
+ if (!status.daemonUp) return "unreachable";
+ if (status.container === "missing") return "none";
+ if (status.container === "stopped") return "asleep";
+ if (status.ready) return "ready";
+ return status.desktopReady ? "unreachable" : "starting";
+}
+
+const CLOUD_STATES: Record<ReturnType<typeof mapComputerState>, BotComputerState> = {
+ idle: "ready", working: "ready", starting: "starting", asleep: "asleep", problem: "unreachable", off: "unknown",
+};
+
+export function botComputerRows(deps: BotComputersRouteDeps, visible: ReturnType<BotComputersHost["visibleFor"]>): BotComputerRow[] {
+ const { cfg, store, teamComputers, frames, botComputers: host } = deps;
+ const now = deps.now?.() ?? Date.now();
+ let connected: boolean | undefined;
+ const thisComputer = () => (connected ??= host.thisComputerConnected());
+
+ const cloudReading = (owner: string, boxId: string | undefined): Reading => {
+ const since = boxId ? boatHealth.notRespondingSince(boxId) : null;
+ if (since !== null) return { state: "unreachable", at: since };
+ const readings: Reading[] = [];
+ const listedAt = frames.available() ? frames.listedAt() : null;
+ if (listedAt !== null) {
+ const machine = frames.machine(owner);
+ readings.push({ state: machine ? CLOUD_STATES[mapComputerState(machine, false)] : "none", at: listedAt });
+ }
+ const answeredAt = boxId ? boatHealth.lastAnsweredAt(boxId) : null;
+ if (answeredAt !== null) readings.push({ state: "ready", at: answeredAt });
+ if (!readings.length && deadBoatOf(owner)) return { state: "unreachable", at: null };
+ return newest(readings);
+ };
+
+ const describe = (kind: Exclude<BotComputerKind, "auto">, bot: BotRecord, threadId: string | undefined): Place => {
+ if (kind === "cloud") {
+ const team = teamComputers.forBot(bot);
+ const owner = team ? teamComputerOwner(team.id) : bot.id;
+ const boxId = boatIdOf(owner) ?? frames.machine(owner)?.boxId;
+ const reading = cloudReading(owner, boxId);
+ return {
+ kind, computerId: `cloud:${owner}`, name: team?.name ?? null, state: reading.state, stateAt: reading.at,
+ ...(team ? { teamComputerId: team.id } : {}), ...(boxId ? { boxId } : {}),
+ };
+ }
+ if (kind === "vps") {
+ const alias = vpsSshAliasForBot(cfg, bot);
+ if (!alias) return { kind, computerId: null, name: null, state: "none", stateAt: null };
+ const container = vpsContainerName(bot.id);
+ const last = lastVpsStatus(vpsConfigForBot(cfg, bot), bot.id);
+ return {
+ kind, computerId: `vps:${alias}/${container}`, name: cfg.vpsServers?.find((server) => server.sshAlias === alias)?.name ?? null,
+ state: last ? containerState(last.status) : "unknown", stateAt: last?.at ?? null,
+ vps: { serverId: `vps:${alias}`, alias, container },
+ };
+ }
+ if (kind === "vm") {
+ const target = deps.localVmTargetForStatus(bot.id, threadId);
+ const last = lastLocalVmStatus(target);
+ const reading: Reading = deps.localVmActiveThreads.has(target.key) ? { state: "ready", at: now }
+ : last ? { state: containerState(last.status), at: last.at } : UNKNOWN;
+ return { kind, computerId: `vm:${target.key}`, name: null, state: reading.state, stateAt: reading.at };
+ }
+ if (kind === "local") {
+ const ready = thisComputer();
+ return { kind, computerId: "local", name: cfg.computerName?.trim() || null, state: ready ? "ready" : "unreachable", stateAt: ready ? now : null };
+ }
+ return { kind, computerId: null, name: null, state: kind === "off" ? "none" : "unknown", stateAt: null };
+ };
+
+ /** Auto's own order (computerPreviewSurface), resolved only where no step would have to look at a computer. */
+ const autoKind = (bot: BotRecord, threadId: string | undefined, browser: boolean): Exclude<BotComputerKind, "auto"> | null => {
+ const caps = host.engineCapabilities(bot);
+ const vps = bot.cloudBackend === "vps";
+ const vmMaybe = !host.cloudHome && caps?.computerMcp === true && deps.localVmSeen.has(deps.localVmTargetForStatus(bot.id, threadId).key);
+ const local = !host.cloudHome && shouldMountLocalComputer({ requested: undefined, hostPlatform: deps.platform ?? process.platform,
+ providerSupportsLocal: caps?.localComputerMcp === true }) && thisComputer();
+ if (vmMaybe || (vps && local)) return null;
+ if (local) return "local";
+ if (vps) return "vps";
+ return browser ? "browser" : "off";
+ };
+
+ const place = (bot: BotRecord, threadId?: string): Place => {
+ const plan = host.surfacePlan(bot, threadId);
+ if (plan.computer === undefined) {
+ const resolved = autoKind(bot, threadId, plan.browser);
+ return resolved ? { ...describe(resolved, bot, threadId), kind: "auto", autoKind: resolved }
+ : { kind: "auto", computerId: null, name: null, state: "unknown", stateAt: null };
+ }
+ if (plan.computer === "off") return describe(plan.browser ? "browser" : "off", bot, threadId);
+ if (plan.computer === "cloud") return describe(bot.cloudBackend === "vps" && !teamComputers.forBot(bot) ? "vps" : "cloud", bot, threadId);
+ return describe(plan.computer, bot, threadId);
+ };
+
+ return store.bots.filter((bot) => !bot.hidden && visible.bot(bot.id)).flatMap((bot) => {
+ const own = place(bot);
+ const chats = store.tasks(bot.id).flatMap((task): BotComputerRow[] => {
+ // Only a pin, or a pool seat for a bot on the Local VM, gives a chat a place of its own.
+ if (task.archivedAt !== undefined || (task.surface === undefined && own.kind !== "vm" && own.autoKind !== "vm")) return [];
+ if (!visible.thread(task.threadId)) return [];
+ const chat = place(bot, task.threadId);
+ return chat.kind === own.kind && chat.computerId === own.computerId ? [] : [{ botId: bot.id, threadId: task.threadId, ...chat }];
+ });
+ return [{ botId: bot.id, ...own }, ...chats];
+ });
+}
+
+/** GET /api/computers/bots → BotComputersPayload. Admin-only like every computer route; rows only for what the caller sees. */
+export function createBotComputersRoute(deps: BotComputersRouteDeps): RouteHandler {
+ return async ({ req, res, path, method, auth, json }) => {
+ if (method !== "GET" || path !== BOT_COMPUTERS_PATH) return PASS;
+ if (backgroundWhileAsleep(path, req.headers)) return answerAsleep(res, json);
+ res.setHeader("cache-control", "private, no-store");
+ const payload: BotComputersPayload = { now: deps.now?.() ?? Date.now(), rows: botComputerRows(deps, deps.botComputers.visibleFor(auth)) };
+ return json(res, 200, payload);
+ };
+}
diff --git a/server/routes/computer-frames.ts b/server/routes/computer-frames.ts
index 1ac75176a0..1b027ca599 100644
--- a/server/routes/computer-frames.ts
+++ b/server/routes/computer-frames.ts
@@ -80,15 +80,18 @@ async function captureThumbnail(cfg: AppConfig, boxId: string, signal: AbortSign
return { data, mime: "image/jpeg" };
}
-/** GET /api/computers/frames?have=ID:VERSION,… → `{ configured, available, now, computers }`. Admin-only like every computer route. */
-export function createComputerFramesRoutes(deps: ComputerFramesRouteDeps, frames?: ComputerFrames): RouteHandler {
- const { cfg, store, teamComputers, computerControl } = deps;
- const teamFor = (owner: string) => teamComputers.list().find((computer) => teamComputerOwner(computer.id) === owner);
- const working = (owner: string) => {
- const team = teamFor(owner);
+function workingFor(deps: Pick<ComputerFramesRouteDeps, "teamComputers" | "teamComputerInUse" | "botHasActiveTurn">) {
+ return (owner: string) => {
+ const team = deps.teamComputers.list().find((computer) => teamComputerOwner(computer.id) === owner);
return team ? deps.teamComputerInUse(team) : deps.botHasActiveTurn(owner);
};
- const cache = frames ?? createComputerFrames({
+}
+
+/** The Team map's cloud computers and frames, listed and captured only while a map watches. */
+export function createMapFrames(deps: ComputerFramesRouteDeps): ComputerFrames {
+ const { cfg, computerControl } = deps;
+ const working = workingFor(deps);
+ return createComputerFrames({
listMachines: async () => {
const inventory = await boat.listManagedBoats(cfg, deps.managedBoatOwners(), { adoptLegacy: false });
if (!inventory.available) return null;
@@ -104,6 +107,12 @@ export function createComputerFramesRoutes(deps: ComputerFramesRouteDeps, frames
held: (owner) => computerControl.snapshot(owner).held,
paused: () => deps.computerProviderConfigTransitions.has("box") || !boat.boatConfigured(cfg),
});
+}
+
+/** GET /api/computers/frames?have=ID:VERSION,… → `{ configured, available, now, computers }`. Admin-only like every computer route. */
+export function createComputerFramesRoutes(deps: ComputerFramesRouteDeps, cache: ComputerFrames = createMapFrames(deps)): RouteHandler {
+ const { cfg, store, teamComputers } = deps;
+ const working = workingFor(deps);
return async ({ res, url, path, method, json }) => {
if (method !== "GET" || path !== "/api/computers/frames") return PASS;
res.setHeader("cache-control", "private, no-store");
diff --git a/server/routes/computers.ts b/server/routes/computers.ts
index caf242504b..3fe161194f 100644
--- a/server/routes/computers.ts
+++ b/server/routes/computers.ts
@@ -27,8 +27,9 @@ import { teamComputerAssignment, teamComputerCreate, teamComputerOwner, type Tea
import * as vps from "../vps-computer.ts";
import { vpsAliasesInPlay } from "../vps-hosts.ts";
import type { BusyFlag, RemoteComputerProvider } from "./config.ts";
+import { createBotComputersRoute, type BotComputersHost } from "./bot-computers.ts";
import { createCloudComputerRecoveryRoutes, type CloudComputerRecoveryRouteDeps } from "./cloud-computer-recovery.ts";
-import { createComputerFramesRoutes } from "./computer-frames.ts";
+import { createComputerFramesRoutes, createMapFrames } from "./computer-frames.ts";
import { createComputerUsageRoutes } from "./computer-usage.ts";
import { PASS, type RouteHandler } from "./table.ts";
@@ -39,10 +40,10 @@ async function keepSignInsBeforeRemove(target: LocalVmTarget): Promise<void> {
}
export interface ComputerRouteDeps {
- store: Pick<Store, "bot" | "bots" | "sections">;
+ store: Pick<Store, "bot" | "bots" | "sections" | "tasks">;
cfg: AppConfig;
sessions: Pick<SessionRegistry, "isLive">;
- teamComputers: Pick<TeamComputers, "get" | "create" | "assign" | "setProblem" | "list">;
+ teamComputers: Pick<TeamComputers, "get" | "create" | "assign" | "setProblem" | "list" | "forBot">;
computerControl: Pick<ComputerControl, "snapshot" | "take" | "release" | "acquireLease" | "releaseLease" | "beat">;
routines(): Pick<RoutineManager, "activeRunForBot"> | null;
controlLeaseIdSchema: ZodString;
@@ -50,7 +51,7 @@ export interface ComputerRouteDeps {
computerProviderConfigTransitions: Pick<Set<RemoteComputerProvider>, "has">;
localVmActiveThreads: Pick<Map<string, string>, "has">;
localVmLifecycleBusy: Pick<Set<string>, "has" | "add" | "delete">;
- localVmSeen: Pick<Set<string>, "add">;
+ localVmSeen: Pick<Set<string>, "add" | "has">;
localVmImageBusy: BusyFlag;
localVmProvisionBusy: BusyFlag;
localVmModeChangeBusy: Pick<BusyFlag, "get">;
@@ -84,6 +85,7 @@ export interface ComputerRouteDeps {
boatRecovery: CloudComputerRecoveryRouteDeps["boatRecovery"];
/** Whose cloud computer a bot uses: its own id, or its team computer's key. */
cloudComputerOwner(bot: BotRecord): string;
+ botComputers: BotComputersHost;
}
export function createComputerRoutes(deps: ComputerRouteDeps): RouteHandler {
@@ -99,11 +101,15 @@ export function createComputerRoutes(deps: ComputerRouteDeps): RouteHandler {
} = deps;
const usage = createComputerUsageRoutes(deps);
// A map owner is a bot id or a team computer's key; a bot's hold may sit on the shared desktop's key.
- const frames = createComputerFramesRoutes({ ...deps, computerControl: { snapshot: botComputerControlSnapshot } });
+ const frameDeps = { ...deps, computerControl: { snapshot: botComputerControlSnapshot } };
+ const mapFrames = createMapFrames(frameDeps);
+ const frames = createComputerFramesRoutes(frameDeps, mapFrames);
+ const botComputers = createBotComputersRoute({ ...deps, frames: mapFrames });
const recovery = createCloudComputerRecoveryRoutes({ ...deps, botComputerControlKey: deps.cloudComputerOwner });
return async (context) => {
if (await usage(context) !== PASS) return;
if (await frames(context) !== PASS) return;
+ if (await botComputers(context) !== PASS) return;
if (await recovery(context) !== PASS) return;
const { req, res, url, path, method, auth, json, readBody } = context;
const routines = deps.routines();
diff --git a/server/vps-computer.ts b/server/vps-computer.ts
index 31c9d4c036..13fe3cead4 100644
--- a/server/vps-computer.ts
+++ b/server/vps-computer.ts
@@ -73,7 +73,7 @@ export function vpsLifecycleBusy(): boolean {
}
const LOCK_ACQUIRE_TIMEOUT_MS = 5_000;
const STATUS_CACHE_TTL_MS = 10_000;
-const statusCache = new Map<string, { status: VpsComputerStatus; expiresAt: number }>();
+const statusCache = new Map<string, { status: VpsComputerStatus; expiresAt: number }>(); /** The last inspection of a bot's VPS computer, however old, and when it ran: never a new one. */ export function lastVpsStatus(cfg: AppConfig, botId: string): { status: VpsComputerStatus; at: number } | null { const key = vpsLockKey(snapshotVpsConfig(cfg), botId), hit = key ? statusCache.get(key) : undefined; return hit ? { status: hit.status, at: hit.expiresAt - STATUS_CACHE_TTL_MS } : null; }
const pendingStatuses = new Map<string, Promise<VpsComputerStatus>>();
const pendingProvisions = new Map<string, Promise<VpsComputerStatus>>();
const SCREENSHOT_BUDGET_MS = 45_000;
diff --git a/shared/bot-computers.ts b/shared/bot-computers.ts
new file mode 100644
index 0000000000..478bd9d40d
--- /dev/null
+++ b/shared/bot-computers.ts
@@ -0,0 +1,39 @@
+/** Where a bot works. `cloud`: a cloud desktop, the bot's own or its team's. `vps`: a desktop container on a server the
+ * person reaches over SSH. `vm`: a Local VM. `local`: this computer. `browser`: the built-in browser alone. `off`: no
+ * screen at all. `auto`: Auto picks a place per turn. */
+export type BotComputerKind = "cloud" | "vps" | "vm" | "local" | "browser" | "off" | "auto";
+
+/** The last state this server already knew, never a fresh look. `none`: the last look found no computer. `unknown`:
+ * nothing this server holds says. */
+export type BotComputerState = "ready" | "asleep" | "starting" | "unreachable" | "none" | "unknown";
+
+/** One line from a bot to the computer it works on: the bot's own place, or a chat's place when that chat has its own. */
+export interface BotComputerRow {
+ botId: string;
+ /** Present on a chat whose place differs from its bot's. */
+ threadId?: string;
+ kind: BotComputerKind;
+ /** On `auto`: the place Auto would use, when the server can tell without looking at any computer. The fields below then
+ * describe that place. */
+ autoKind?: Exclude<BotComputerKind, "auto">;
+ /** Stable across reads and the same for every bot sharing one computer: `cloud:<owner>` (a bot id, or a team computer's
+ * owner key), `vps:<alias>/<container>`, `vm:<target>`, `local`. Null for `browser`, `off` and an unresolved `auto`. */
+ computerId: string | null;
+ /** A name the person gave it (a team computer, a named VPS server, this computer); null: call it by its kind. */
+ name: string | null;
+ state: BotComputerState;
+ /** Epoch ms of the reading `state` comes from; null when that reading has no time. */
+ stateAt: number | null;
+ /** A team's shared cloud desktop: its id in `/api/team-computers`. */
+ teamComputerId?: string;
+ /** The cloud desktop's provider id, when this server holds it. */
+ boxId?: string;
+ /** A VPS computer is always one container on its server: `serverId` is `vps:<alias>`, the server's own device id. */
+ vps?: { serverId: string; alias: string; container: string };
+}
+
+/** GET /api/computers/bots. `now` is the server's clock, for the age of each state. */
+export interface BotComputersPayload {
+ now: number;
+ rows: BotComputerRow[];
+}
diff --git a/src/lib/bot-computers.ts b/src/lib/bot-computers.ts
new file mode 100644
index 0000000000..8de50f5d0c
--- /dev/null
+++ b/src/lib/bot-computers.ts
@@ -0,0 +1,16 @@
+import { api } from "@/state/api";
+import type { BotComputerRow, BotComputersPayload } from "../../shared/bot-computers";
+
+export type { BotComputerKind, BotComputerRow, BotComputersPayload, BotComputerState } from "../../shared/bot-computers";
+
+/** Which computer each bot (and each chat with a place of its own) works on, from what the server already holds. A
+ * poll is `background`, so it never wakes a Cloud home that went to sleep. */
+export function fetchBotComputers(init: { signal?: AbortSignal; background?: boolean } = {}): Promise<BotComputersPayload> {
+ return api<BotComputersPayload>("/api/computers/bots", { signal: init.signal ?? AbortSignal.timeout(15_000), background: init.background ?? true });
+}
+
+/** The row for a bot's own place, or for one of its chats when that chat has its own. */
+export function botComputerFor(rows: readonly BotComputerRow[], botId: string, threadId?: string): BotComputerRow | undefined {
+ return (threadId ? rows.find((row) => row.botId === botId && row.threadId === threadId) : undefined)
+ ?? rows.find((row) => row.botId === botId && row.threadId === undefined);
+}