Skip to content

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

19.7 KB
Raw Blame
// The container boundary is the group-local-vm fixture; the provider is an in-process stub recording the tool list per request.
import { spawn, type ChildProcess } from "node:child_process";
import { createServer, type Server } from "node:http";
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { tmpdir } from "node:os";
import { delimiter, dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { writeFileAtomic } from "./atomic.ts";
import { freePortBlock } from "./testing/ports.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { isTitleCall } from "./testing/title-call.ts";

const ROOT = fileURLToPath(new URL("..", import.meta.url));
let child: ChildProcess;
let fixtureHome = "";
let base = "";
let stateFile = "";
let dumpFile = "";
let nativeDir = "";
let stderr = "";
let fakebin = "";
let upstream: Server;

type ChatMessage = { role: string; content?: unknown; tool_call_id?: string; tool_calls?: Array<{ id: string }> };
type ChatRequest = { messages: ChatMessage[]; tools?: Array<{ function: { name: string } }> };
const requests: ChatRequest[] = [];
let pendingSelect: { surface: string } | null = null;
let pendingCall: { name: string; arguments: unknown } | null = null;

const frame = (delta: unknown, finish_reason: string | null) =>
  `data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason }] })}\n\n`;

const FAKE_PODMAN = `#!/usr/bin/env node
'use strict';
const readline = require('node:readline');
const { existsSync } = require('node:fs');
const TOOLS = [
  { name: 'screenshot', description: 'Capture the VM screen', inputSchema: { type: 'object', properties: {}, additionalProperties: false } },
  { name: 'click', description: 'Click at a point', inputSchema: { type: 'object', properties: { x: { type: 'number' }, y: { type: 'number' } }, required: ['x', 'y'], additionalProperties: false } },
  { name: 'type_text', description: 'Type text', inputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: false } },
  { name: 'open_url', description: 'Open a URL in the VM browser', inputSchema: { type: 'object', properties: { url: { type: 'string' } }, required: ['url'], additionalProperties: false } },
];
const rl = readline.createInterface({ input: process.stdin });
rl.on('line', (line) => {
  let request;
  try { request = JSON.parse(line); } catch { return; }
  if (request.id === undefined) return;
  let result;
  if (request.method === 'initialize') result = { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'fake-vm', version: '1' } };
  else if (request.method === 'tools/list') result = { tools: existsSync(__dirname + '/empty-tools') ? [] : TOOLS };
  else if (request.method === 'tools/call') result = { content: [{ type: 'text', text: 'fake vm ran ' + String(request.params?.name) }] };
  else result = { content: [{ type: 'text', text: 'unsupported call' }], isError: true };
  process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\\n');
});
rl.on('close', () => process.exit(0));
`;

const vmState = (state: Record<string, unknown> = {}) => writeFileAtomic(stateFile, JSON.stringify(state));
const api = async (method: string, path: string, body?: unknown, expectedStatus?: number) => {
  const r = await fetch(base + path, { method, headers: { "content-type": "application/json", origin: base },
    ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
  const result = await r.json() as any;
  if (expectedStatus !== undefined) expect(r.status, `${method} ${path}: ${JSON.stringify(result)}`).toBe(expectedStatus);
  else expect(r.ok, `${method} ${path}: ${JSON.stringify(result)}`).toBe(true);
  return result;
};
async function until<T>(read: () => T | Promise<T>, accept: (value: T) => boolean): Promise<T> {
  const end = Date.now() + 20_000;
  for (;;) {
    const value = await read();
    if (accept(value)) return value;
    if (Date.now() >= end) throw new Error(`Fixture wait expired: ${JSON.stringify(value)}\n${stderr}`);
    await new Promise(r => setTimeout(r, 50));
  }
}
const toolNames = (request: ChatRequest | undefined) => (request?.tools ?? []).map(tool => tool.function.name);
// The native tee is what a person pastes into a bug report, so its "out" line must carry the request's tool names.
const nativeToolNames = (threadId: string): string[] => {
  const file = join(nativeDir, `${threadId}.ndjson`);
  if (!existsSync(file)) return [];
  const names = new Set<string>();
  for (const line of readFileSync(file, "utf8").split("\n")) {
    if (!line.trim()) continue;
    const entry = JSON.parse(line) as { dir?: string; msg?: { tools?: string[] } };
    if (entry.dir === "out") for (const name of entry.msg?.tools ?? []) names.add(name);
  }
  return [...names];
};
const idle = (botId: string) => until(() => api("GET", "/api/bots?messages=0"), s => !s.bots.find((b: any) => b.id === botId)?.busy);

beforeAll(async () => {
  fixtureHome = mkdtempSync(join(tmpdir(), "omb-openai-vm-"));
  stateFile = join(fixtureHome, "vm.json");
  dumpFile = join(fixtureHome, "dump.json");
  vmState({ containers: [] });
  fakebin = join(fixtureHome, "fakebin");
  mkdirSync(fakebin);
  writeFileSync(join(fakebin, "podman"), FAKE_PODMAN, { mode: 0o700 });
  chmodSync(join(fakebin, "podman"), 0o700);

  upstream = createServer(async (req, res) => {
    res.setHeader("content-type", "application/json");
    if (req.url === "/v1/models") return res.end(JSON.stringify({ data: [{ id: "fixture-model" }] }));
    // The chat engine asks a local server whether it is Ollama (/api/version); this one is not.
    if (req.method === "GET") { res.statusCode = 404; return res.end(); }
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const request = JSON.parse(raw || "{}") as ChatRequest;
    if (isTitleCall(request)) { res.statusCode = 500; return res.end(); }
    requests.push(request);
    const toolResult = request.messages?.some(message => message.role === "tool");
    res.writeHead(200, { "content-type": "text/event-stream" });
    if (toolResult) {
      res.end(frame({ content: "Selection acknowledged; waiting for the new surface." }, "stop") + "data: [DONE]\n\n");
    } else if (pendingCall) {
      const call = { index: 0, id: "pending-call", type: "function", function: { name: pendingCall.name, arguments: JSON.stringify(pendingCall.arguments) } };
      pendingCall = null;
      res.end(frame({ tool_calls: [call] }, "tool_calls") + "data: [DONE]\n\n");
    } else if (pendingSelect) {
      const call = { index: 0, id: "select-call", type: "function", function: { name: "agents_select_computer", arguments: JSON.stringify({ surface: pendingSelect.surface }) } };
      pendingSelect = null;
      res.end(frame({ tool_calls: [call] }, "tool_calls") + "data: [DONE]\n\n");
    } else {
      res.end(frame({ content: "Done." }, "stop") + "data: [DONE]\n\n");
    }
  });
  await new Promise<void>(resolve => upstream.listen(0, "127.0.0.1", resolve));
  const upstreamPort = (upstream.address() as { port: number }).port;

  const data = join(fixtureHome, "data");
  nativeDir = join(data, "native");
  const ui = join(fixtureHome, "static");
  mkdirSync(data);
  mkdirSync(join(ui, "assets"), { recursive: true });
  writeFileSync(join(ui, "index.html"), "<title>openai-compat VM tools</title>");
  writeFileSync(join(ui, "assets", "test.css"), "body{}");
  writeFileSync(join(data, "config.json"), JSON.stringify({
    // Per-bot isolation: a fresh bot's VM is unseen until touched, so the strict pin cannot hide behind a warm cache entry.
    localVm: { mode: "per-bot" },
    instances: { claude: {
      driver: "claudeAgent",
      config: { cli: join(ROOT, "server/testing/fake-claude-cli.ts") },
      environment: { FAKE_CLAUDE_DUMP: dumpFile },
    } },
  }));

  const port = await freePortBlock([0, 1]);
  base = `http://127.0.0.1:${port}`;
  child = spawn(process.execPath, [
    "--experimental-strip-types",
    "--import", pathToFileURL(join(ROOT, "server/testing/group-local-vm-hooks.mjs")).href,
    join(ROOT, "server/index.ts"),
  ], {
    cwd: ROOT,
    env: {
      PATH: [fakebin, dirname(process.execPath), "/usr/bin", "/bin"].join(delimiter),
      HOME: fixtureHome, USERPROFILE: fixtureHome, OMB_DATA_DIR: data,
      OMB_AGENTS_TOOL_BRIDGE: "0",
      APPDATA: join(fixtureHome, "appdata"), LOCALAPPDATA: join(fixtureHome, "localappdata"),
      TEMP: fixtureHome, TMP: fixtureHome, TMPDIR: fixtureHome,
      OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1), OMB_STATIC_DIR: ui,
      OMB_TEST_VM_STATE: stateFile, OMB_EXTRA_PATH: fakebin,
      OMB_USER_DATA: join(fixtureHome, "user-data"),
      ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
    },
    stdio: ["ignore", "pipe", "pipe"],
  });
  child.stdout!.on("data", () => {});
  child.stderr!.on("data", c => { stderr += c; });
  await until(async () => {
    if (child.exitCode !== null) throw new Error(stderr);
    try { return (await fetch(base + "/api/health")).ok; } catch { return false; }
  }, Boolean);
  await api("PATCH", "/api/config", { openaiCompat: { key: "fixture-key", url: `http://127.0.0.1:${upstreamPort}/v1`, model: "fixture-model" } });
  // Chief first makes the seeded bot its team's Chief, which answers a teammate's failed run with a Problems to look at turn
  // of its own on Claude: its dump would stand in for the turn under test. Stepped down, each dump is the test's own.
  const seeded = (await api("GET", "/api/bots?messages=0")).bots.find((bot: any) => bot.chiefOfStaff);
  await api("PATCH", `/api/bots/${seeded.id}`, { chiefOfStaff: false });
});

afterAll(async () => {
  await waitForExit(child, { signal: "SIGTERM" });
  if (upstream) await new Promise<void>(resolve => upstream.close(() => resolve()));
  if (fixtureHome) await removeTempDir(fixtureHome);
});

describe("openai-compat Local VM tools", () => {
  it("mounts the Local VM tools on a strict Works on: Local VM turn", async () => {
    vmState({ containers: [] });
    requests.length = 0;
    const { bot } = await api("POST", "/api/bots", { name: "openai strict vm" });
    await api("PATCH", `/api/bots/${bot.id}`, { computer: "vm" });
    await api("PATCH", `/api/bots/${bot.id}/model`, { instanceId: "openaiCompat", model: "fixture-model" });
    await api("POST", `/api/bots/${bot.id}/messages`, { text: "Take a screenshot of the desktop." });
    await until(() => requests.length, count => count >= 1);
    await idle(bot.id);
    expect(toolNames(requests[0])).toContain("computer_screenshot");
    expect(toolNames(requests[0])).toContain("agents_select_computer");
    await until(() => nativeToolNames(bot.threadId), names => names.length > 0);
    expect(nativeToolNames(bot.threadId)).toContain("computer_screenshot");
  }, 60_000);

  it("lists project skills by their guest path only on the VM that mounts them", async () => {
    vmState({ containers: [] });
    const { bot } = await api("POST", "/api/bots", { name: "VM project skills" });
    const seat = createHash("sha256").update(bot.id).digest("hex").slice(0, 16);
    const project = join(fixtureHome, "data", "vm-homes", seat, "project");
    const skill = join(".agents", "skills", "vm-fixture", "SKILL.md");
    mkdirSync(join(project, dirname(skill)), { recursive: true });
    mkdirSync(join(project, ".git"));
    writeFileSync(join(project, skill), "Read the project's VM fixture.\n");
    const outside = join(fixtureHome, "outside-project");
    mkdirSync(join(outside, dirname(skill)), { recursive: true });
    writeFileSync(join(outside, skill), "This host-only description must stay out.\n");
    await api("PATCH", `/api/bots/${bot.id}/model`, { instanceId: "openaiCompat", model: "fixture-model" });
    const send = async (text: string) => {
      requests.length = 0;
      await api("POST", `/api/bots/${bot.id}/messages`, { text });
      await until(() => requests.length, count => count > 0);
      await idle(bot.id);
      return requests[0]!.messages.map(message => message.content).join("\n");
    };
    await api("PATCH", `/api/bots/${bot.id}`, { computer: "vm", cwd: project });
    const vmPrompt = await send("Use the project skills.");
    expect(toolNames(requests[0])).toContain("agents_vm_exec");
    expect(vmPrompt).toContain('/workspace/project/.agents/skills/vm-fixture/SKILL.md');
    expect(vmPrompt).toContain("with vm_exec");
    expect(vmPrompt).not.toContain(join(project, skill));
    const { skills } = await api("GET", `/api/bots/${bot.id}/skills`);
    expect(skills).toContainEqual(expect.objectContaining({ name: "vm-fixture", origin: "project", editable: false }));

    await api("PATCH", `/api/bots/${bot.id}`, { cwd: outside });
    expect(await send("Work on the host folder.")).not.toContain("host-only description");
    await api("PATCH", `/api/bots/${bot.id}`, { computer: "off", cwd: project });
    expect(await send("Work without the desktop.")).not.toContain("vm-fixture");
  }, 60_000);

  it("mounts the Local VM tools on the select_computer continuation", async () => {
    vmState({ containers: [] });
    requests.length = 0;
    pendingSelect = null;
    const { bot } = await api("POST", "/api/bots", { name: "openai select vm" });
    await api("PATCH", `/api/bots/${bot.id}/model`, { instanceId: "openaiCompat", model: "fixture-model" });
    pendingSelect = { surface: "vm" };
    await api("POST", `/api/bots/${bot.id}/messages`, { text: "Open a browser on my Local VM." });
    try {
      await until(() => requests.length, count => count >= 3);
    } catch (error) {
      const state = await api("GET", "/api/bots");
      const current = state.bots.find((item: any) => item.id === bot.id);
      console.error("CONTINUATION MISSING", JSON.stringify({
        requests: requests.map(r => ({ tools: toolNames(r), roles: r.messages?.map(m => m.role) })),
        messages: current?.messages?.map((m: any) => ({ role: m.role, kind: m.kind, text: m.text, tool: m.tool, error: m.error })),
      }, null, 2));
      throw error;
    }
    await idle(bot.id);
    const continuation = requests[2];
    expect(toolNames(continuation), JSON.stringify({ tools: toolNames(continuation), requests: requests.length })).toContain("computer_screenshot");
    expect(toolNames(requests[0])).toContain("agents_select_computer");
    // The continuation is listed the agents tools its request was, select_computer too: the route refuses a second pick.
    const agentsTools = (request: ChatRequest | undefined) => toolNames(request).filter((name) => name.startsWith("agents_"));
    expect(agentsTools(continuation)).toEqual(agentsTools(requests[0]));
    expect(toolNames(continuation)).toContain("agents_select_computer");
    const shown = (await api("GET", "/api/bots")).bots.find((item: any) => item.id === bot.id).messages;
    expect(shown.filter((message: any) => message.card)).toEqual([]);
  }, 60_000);

  // An API model on its Private desktop, asked for the person's OneDrive folder, sent them to a settings screen that does not exist.
  it("offers an API model on its Private desktop the switch to This computer for the person's own files", async () => {
    // The command runs as written; only its failure carries the switch.
    vmState({ containers: [], execResult: { exitCode: 1, stdout: "", stderr: "mkdir: cannot create directory: Permission denied", timedOut: false } });
    requests.length = 0;
    const hostPath = process.platform === "win32" ? "C:\\Users\\ana\\OneDrive\\Reports"
      : process.platform === "darwin" ? "/Users/ana/OneDrive/Reports" : "/home/ana/OneDrive/Reports";
    const { bot } = await api("POST", "/api/bots", { name: "Ada" });
    await api("PATCH", `/api/bots/${bot.id}`, { computer: "vm" });
    await api("PATCH", `/api/bots/${bot.id}/model`, { instanceId: "openaiCompat", model: "fixture-model" });
    pendingCall = { name: "agents_vm_exec", arguments: { command: `mkdir -p "${hostPath}"` } };
    await api("POST", `/api/bots/${bot.id}/messages`, { text: `Save the report into ${hostPath}.` });
    await until(() => requests.length, count => count >= 2);
    await idle(bot.id);
    const text = (content: unknown) => typeof content === "string" ? content : JSON.stringify(content);
    // The place rules change turn to turn, so they ride the person's message as its context note, not the system message.
    const system = requests[0]!.messages.map(message => text(message.content)).join("\n");
    expect(toolNames(requests[0])).toContain("agents_select_computer");
    expect(system).toContain("A file or folder on the person's own computer");
    expect(system).toContain("This bot works on its Private desktop, not on this computer. To use files on this computer, switch it to This computer: say so in one line, call select_computer with surface \"local\"");
    expect(system).not.toContain("Settings → Computers");
    const answer = JSON.parse(text(requests[1]!.messages.find(message => message.role === "tool")?.content)) as { ok: boolean; result: string };
    expect(answer.ok).toBe(false);
    const result = answer.result;
    expect(result).toContain("exit code 1");
    expect(result).toContain("mkdir: cannot create directory");
    expect(result).toContain("--- note ---\nThat path is on this computer, and vm_exec runs only inside this bot's Private desktop. This bot works on its Private desktop, not on this computer. To use files on this computer, switch it to This computer: say so in one line, call select_computer with surface \"local\", then end your turn");
    expect(result).toContain(`When the person asks you to keep using this computer, also keep it there: app_settings set, id "bots.settings", value {"botId":"${bot.id}","computer":"local"}`);
    expect(result).toContain("open Bot's screen in this chat and choose This computer under “Where Ada works”");
    vmState({ containers: [] });
  }, 60_000);

  it("fails the turn when the Local VM lists no tools, instead of running without them", async () => {
    vmState({ containers: [] });
    requests.length = 0;
    writeFileSync(join(fakebin, "empty-tools"), "");
    try {
      const { bot } = await api("POST", "/api/bots", { name: "openai empty vm" });
      await api("PATCH", `/api/bots/${bot.id}`, { computer: "vm" });
      await api("PATCH", `/api/bots/${bot.id}/model`, { instanceId: "openaiCompat", model: "fixture-model" });
      await api("POST", `/api/bots/${bot.id}/messages`, { text: "Take a screenshot of the desktop." });
      const messages = async () => (await api("GET", "/api/bots")).bots.find((item: any) => item.id === bot.id).messages;
      const shown = await until(messages, list => list.some((message: any) => message.kind === "digest"));
      expect(requests.map(toolNames), "no provider round may run without the VM tools").toEqual([]);
      expect(shown.find((message: any) => message.tool?.terminal)?.tool).toMatchObject({ ok: false, name: expect.stringMatching(/Local VM listed no tools/) });
    } finally {
      rmSync(join(fakebin, "empty-tools"), { force: true });
    }
  }, 60_000);

  it("mounts the Local VM for a claudeAgent control on the same surface", async () => {
    vmState({ containers: [] });
    const { bot } = await api("POST", "/api/bots", { name: "claude strict vm" });
    await api("PATCH", `/api/bots/${bot.id}`, { computer: "vm" });
    await api("POST", `/api/bots/${bot.id}/messages`, { text: "Take a screenshot of the desktop." });
    const dump = await until((): { mcpConfig?: { mcpServers?: Record<string, { env?: Record<string, string> }> } } | null => {
      if (!existsSync(dumpFile)) return null;
      try { return JSON.parse(readFileSync(dumpFile, "utf8")); } catch { return null; }
    }, Boolean);
    await idle(bot.id);
    expect(dump!.mcpConfig?.mcpServers?.computer).toBeTruthy();
    expect(String(dump!.mcpConfig!.mcpServers!.computer.env?.OMB_CONTROL_URL ?? "")).toContain("127.0.0.1");
  }, 60_000);
});