Skip to content

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

9.5 KB
Raw Blame
import { spawn } from "node:child_process";
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";

import { CONTAINER, CUA_EXECUTABLE, CUA_SOCKET } from "./container-computer.ts";
import { omittedFromErrorNote } from "./mcp-error-result.ts";

const temporary: string[] = [];

afterEach(async () => {
  await Promise.all(temporary.splice(0).map((path) => rm(path, { recursive: true, force: true })));
});

// The fake Docker executable below is a POSIX shell script. The production
// bridge remains portable; only this byte-for-byte process fixture is gated.
const posixOnly = describe.skipIf(process.platform === "win32");

posixOnly("Local VM Cua MCP bridge", () => {
  it("passes MCP bytes unchanged to cua-driver mcp over the container runtime", async () => {
    const bin = await mkdtemp(join(tmpdir(), "openmausbot-container-mcp-"));
    temporary.push(bin);
    const fakeDocker = join(bin, "docker");
    await writeFile(
      fakeDocker,
      "#!/bin/sh\nprintf 'ARGS:%s\\n' \"$*\" >&2\ncat\n",
      { mode: 0o700 },
    );
    await chmod(fakeDocker, 0o700);

    const input = '{"jsonrpc":"2.0","id":1,"method":"tools/list"}\n';
    const result = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
      const child = spawn(
        process.execPath,
        [fileURLToPath(new URL("./container-mcp.ts", import.meta.url)), "docker", CONTAINER, CUA_SOCKET],
        {
          env: { ...process.env, OMB_EXTRA_PATH: bin, NODE_NO_WARNINGS: "1" },
          stdio: ["pipe", "pipe", "pipe"],
        },
      );
      let stdout = "";
      let stderr = "";
      child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
      child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString()));
      child.on("error", reject);
      child.on("close", (code) => resolve({ code, stdout, stderr }));
      child.stdin.end(input);
    });

    expect(result.code, result.stderr).toBe(0);
    expect(result.stdout).toBe(input);
    expect(result.stderr).toContain(
      `ARGS: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 ${CONTAINER} ` +
        `${CUA_EXECUTABLE} mcp --socket ${CUA_SOCKET}`,
    );
  });

  it("answers ping locally so the bundled cua-driver is not invoked", async () => {
    const bin = await mkdtemp(join(tmpdir(), "openmausbot-container-mcp-ping-"));
    temporary.push(bin);
    const fakeDocker = join(bin, "docker");
    await writeFile(
      fakeDocker,
      `#!/bin/sh\n` +
        `printf 'ARGS:%s\\n' "$*" >&2\n` +
        `while IFS= read -r line; do\n` +
        `  case "$line" in\n` +
        `    *'"method":"ping"'* ) printf 'PING-RECEIVED:%s\\n' "$line" >&2 ;;\n` +
        `    *'"method":"tools/list"'* ) printf '{"jsonrpc":"2.0","id":1,"result":{"tools":[]}}\\n' ;;\n` +
        `  esac\n` +
        `done\n`,
      { mode: 0o700 },
    );
    await chmod(fakeDocker, 0o700);

    const input =
      '{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}\n' +
      '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}\n';

    const result = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
      const child = spawn(
        process.execPath,
        [fileURLToPath(new URL("./container-mcp.ts", import.meta.url)), "docker", CONTAINER, CUA_SOCKET],
        {
          env: { ...process.env, OMB_EXTRA_PATH: bin, NODE_NO_WARNINGS: "1" },
          stdio: ["pipe", "pipe", "pipe"],
        },
      );
      let stdout = "";
      let stderr = "";
      child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
      child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString()));
      child.on("error", reject);
      child.on("close", (code) => resolve({ code, stdout, stderr }));
      child.stdin.end(input);
    });

    expect(result.code, result.stderr).toBe(0);
    const lines = result.stdout.trim().split("\n").filter(Boolean).map((line) => JSON.parse(line));
    expect(lines).toEqual([
      { jsonrpc: "2.0", id: 2, result: {} },
      { jsonrpc: "2.0", id: 1, result: { tools: [] } },
    ]);
    expect(result.stderr).not.toContain("PING-RECEIVED");
    expect(result.stderr).toContain(
      `ARGS: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 ${CONTAINER} ` +
        `${CUA_EXECUTABLE} mcp --socket ${CUA_SOCKET}`,
    );
  });
  it("explains unconfirmed accessibility input without changing other tool results", async () => {
    const bin = await mkdtemp(join(tmpdir(), "openmausbot-container-mcp-input-"));
    temporary.push(bin);
    const receipts = [
      ["Typed 14 character(s) (via targeted AT-SPI).", "unverifiable", "accessibility"],
      ["Set value of element [42] to 'VM funcionando' (path=ax); but the element reads back ''.", "suspected_noop", "accessibility"],
      ["Clicked element [43] (pid 245).", "unverifiable", "accessibility"],
      ["Typed 14 character(s) as real key events (delivery_mode=foreground, focus_after=target); not verified — confirm with a screenshot.", "unverifiable", "global_input"],
    ].map(([text, effect, route], id) => ({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text }], structuredContent: { effect, route } } }));
    const script = ["#!/bin/sh", ...receipts.map((receipt) => `IFS= read -r line && printf '%s\\n' '${JSON.stringify(receipt).replaceAll("'", "'\\''")}'`), ""].join("\n");
    await writeFile(join(bin, "docker"), script, { mode: 0o700 });
    const child = spawn(
      process.execPath,
      [fileURLToPath(new URL("./container-mcp.ts", import.meta.url)), "docker", CONTAINER, CUA_SOCKET],
      { env: { ...process.env, OMB_EXTRA_PATH: bin, NODE_NO_WARNINGS: "1" }, stdio: ["pipe", "pipe", "pipe"] },
    );
    const calls = ["type_text", "set_value", "click", "type_text"].map((name, id) => JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: {} } }));
    let stdout = "";
    let stderr = "";
    child.stdout.setEncoding("utf8").on("data", (chunk) => { stdout += chunk; });
    child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr += chunk; });
    const closed = new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); });
    child.stdin.end(calls.join("\n") + "\n");
    expect(await closed, stderr).toBe(0);
    const results = stdout.trim().split("\n").map((line) => JSON.parse(line));
    expect(results).toHaveLength(4);
    for (const [index, receipt] of receipts.slice(0, 2).entries()) {
      expect(results[index]).toEqual({
        ...receipt,
        result: { ...receipt.result, content: [{ type: "text", text: expect.stringMatching(/could not confirm.*type_text.*foreground.*clipboard_write/s) }] },
      });
      expect(results[index].result.content[0].text.startsWith(receipt.result.content[0]!.text), "keeps the driver's own line").toBe(true);
    }
    expect(results.slice(2)).toEqual(receipts.slice(2));
  });

  it("never hands an engine an error result that carries a screenshot", async () => {
    const bin = await mkdtemp(join(tmpdir(), "openmausbot-container-mcp-error-"));
    temporary.push(bin);
    const fakeDocker = join(bin, "docker");
    // cua-driver 0.37.0 answers a refused action with its error text plus a screenshot; success keeps its screenshot.
    await writeFile(
      fakeDocker,
      `#!/bin/sh\n` +
        `while IFS= read -r line; do\n` +
        `  case "$line" in\n` +
        `    *'"id":1'* ) printf '%s\\n' '{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"refused"},{"type":"image","data":"iVBORw0KGgo=","mimeType":"image/png"}],"isError":true}}' ;;\n` +
        `    *'"id":2'* ) printf '%s\\n' '{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"image","data":"iVBORw0KGgo=","mimeType":"image/png"}]}}' ;;\n` +
        `  esac\n` +
        `done\n`,
      { mode: 0o700 },
    );
    await chmod(fakeDocker, 0o700);

    const input =
      '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"click","arguments":{}}}\n' +
      '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_desktop_state","arguments":{}}}\n';
    const result = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
      const child = spawn(
        process.execPath,
        [fileURLToPath(new URL("./container-mcp.ts", import.meta.url)), "docker", CONTAINER, CUA_SOCKET],
        {
          env: { ...process.env, OMB_EXTRA_PATH: bin, NODE_NO_WARNINGS: "1" },
          stdio: ["pipe", "pipe", "pipe"],
        },
      );
      let stdout = "";
      let stderr = "";
      child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
      child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString()));
      child.on("error", reject);
      child.on("close", (code) => resolve({ code, stdout, stderr }));
      child.stdin.end(input);
    });

    expect(result.code, result.stderr).toBe(0);
    expect(result.stdout.trim().split("\n").map((line) => JSON.parse(line))).toEqual([
      {
        jsonrpc: "2.0",
        id: 1,
        result: { content: [{ type: "text", text: "refused" }, { type: "text", text: omittedFromErrorNote(1) }], isError: true },
      },
      { jsonrpc: "2.0", id: 2, result: { content: [{ type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" }] } },
    ]);
  });
});