Skip to content

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

17.9 KB
Raw Blame
import { readFileSync } from "node:fs";
import { describe, expect, it, vi } from "vitest";

import { workflowSchema, type ComputerAction, type Workflow } from "../../shared/skill-burger/format.ts";
import type { CallOutcome } from "../saved-steps/resolve.ts";
import { runComputerStep, type ComputerStep } from "./computer-step.ts";
import type { DeskReach, DeskSession } from "./desk-caller.ts";
import { resumeRun, startRun, type RunDeps, type RunState, type StepExecutors } from "./runner.ts";

const APP = { bundleId: "com.apple.TextEdit", name: "TextEdit" };
const WINDOW = { title: "Untitled", width: 800, height: 600 };
const SAVE: ComputerAction = { tool: "click", app: APP, window: WINDOW, element: { role: "AXButton", label: "Save", path: [] } };
const BODY: ComputerAction = { tool: "type_text", app: APP, window: WINDOW, element: { role: "AXTextArea", label: "Body", path: [] }, text: { $arg: "text" } };
const KEYS: ComputerAction = { tool: "hotkey", app: APP, window: WINDOW, keys: ["cmd", "s"] };
const PIXEL: ComputerAction = { tool: "click", app: APP, window: WINDOW, point: { x: 100, y: 50 } };

interface FakeOptions { saves?: number; width?: number; cursor?: boolean | "missing"; failTool?: string }

/** A driver on a screen where TextEdit runs as pid 99 with window 70; each read of the window hands out fresh tokens. */
function fakeDriver(options: FakeOptions = {}) {
  const calls: Array<{ tool: string; args: Record<string, unknown> }> = [];
  let snapshot = 0;
  let cursor = options.cursor === true;
  const cursorTools = options.cursor === "missing" ? [] : ["get_agent_cursor_state", "set_agent_cursor_enabled"];
  const answer = (tool: string, args: Record<string, unknown>): CallOutcome => {
    switch (tool) {
      case "list_apps": return { ok: true, structured: { apps: [{ pid: 99, name: "TextEdit", bundle_id: "com.apple.TextEdit", running: true }] } };
      case "list_windows": return { ok: true, structured: { windows: [{ window_id: 70, pid: 99, title: "Untitled", bounds: { x: 0, y: 0, width: options.width ?? 800, height: 600 } }] } };
      case "get_window_state": {
        snapshot += 1;
        const saves = Array.from({ length: options.saves ?? 1 }, (_, n) => ({ element_index: 2 + n, element_token: `live${snapshot}:${2 + n}`, role: "AXButton", label: "Save", parent_index: 0, depth: 1 }));
        return { ok: true, structured: { pid: 99, window_id: 70, elements_complete: true, elements: [
          { element_index: 0, role: "AXWindow", label: "Untitled", depth: 0 },
          { element_index: 1, element_token: `live${snapshot}:1`, role: "AXTextArea", label: "Body", parent_index: 0, depth: 1, value: "" },
          ...saves,
        ] } };
      }
      case "get_agent_cursor_state": return { ok: true, structured: { enabled: cursor } };
      case "set_agent_cursor_enabled": cursor = args.enabled === true; return { ok: true, structured: {} };
      default: return tool === options.failTool ? { ok: false, error: "the app refused it" } : { ok: true, structured: {} };
    }
  };
  const session: DeskSession = {
    tools: new Set(["list_apps", "list_windows", "get_window_state", "click", "type_text", "hotkey", ...cursorTools]),
    async call(tool, args) { calls.push({ tool, args }); return answer(tool, args); },
    close: async () => {},
  };
  return { calls, session, cursor: () => cursor };
}

const reach = (session: DeskSession, place: DeskReach["place"] = "yourComputer", allowed = true): DeskReach & { opened: number } => {
  const out = { place, opened: 0, allowed: () => allowed, open: async () => { out.opened += 1; return session; } };
  return out;
};
const patience = () => { let now = 0; return { now: () => now, sleep: async (ms: number) => { now += ms; } }; };
const step = (actions: ComputerAction[], on: ComputerStep["on"] = "yourComputer"): ComputerStep => ({ id: "s1", kind: "computer", label: "Save it", on, where: on === "yourComputer" ? "yourComputer" : "vm", actions });
const run = (actions: ComputerAction[], desk: DeskReach | null, on?: ComputerStep["on"]) => {
  const rows: Array<[number, string, unknown]> = [];
  const outcome = runComputerStep(step(actions, on), {
    reach: desk, fill: (text) => (typeof text === "string" ? text : "Hello team"), signal: new AbortController().signal, patience: patience(),
    action: { started: (index, line) => rows.push([index, "started", line]), ended: (index, ok, output) => rows.push([index, ok ? "done" : "failed", output]) },
  });
  return { outcome, rows };
};
const acted = (calls: ReturnType<typeof fakeDriver>["calls"]) => calls.filter((call) => !["list_apps", "list_windows", "get_window_state", "get_agent_cursor_state", "set_agent_cursor_enabled"].includes(call.tool));

describe("a computer step replayed on the live screen", () => {
  it("finds every target again and acts on the fresh pid, window and token, never the recorded ones", async () => {
    const driver = fakeDriver();
    const { outcome, rows } = run([BODY, SAVE, KEYS], reach(driver.session));
    expect(await outcome).toEqual({ ok: true, output: { actions: 3 } });
    expect(acted(driver.calls)).toEqual([
      { tool: "type_text", args: { text: "Hello team", pid: 99, window_id: 70, element_token: "live1:1" } },
      { tool: "click", args: { pid: 99, window_id: 70, element_token: "live2:2" } },
      { tool: "hotkey", args: { keys: ["cmd", "s"], pid: 99, window_id: 70 } },
    ]);
    expect(JSON.stringify(driver.calls)).not.toMatch(/"pid":42|"window_id":7\b|s1:/);
    expect(rows).toEqual([[0, "started", "Type {text} in “Body”"], [0, "done", "done"], [1, "started", "Click “Save” in TextEdit"], [1, "done", "done"], [2, "started", "Press ⌘S"], [2, "done", "done"]]);
  });

  it("sends each driver tool only arguments its 0.41.3 schema takes, with the ones it requires", async () => {
    const schemas = (JSON.parse(readFileSync(new URL("../../electron/fixtures/cua-driver-lent-tool-schemas.json", import.meta.url), "utf8")) as { tools: Record<string, { properties: Record<string, unknown>; required?: string[] }> }).tools;
    const driver = fakeDriver();
    const scroll: ComputerAction = { tool: "scroll", app: APP, window: WINDOW, element: { role: "AXTextArea", label: "Body", path: [] }, direction: "down", amount: 3 };
    const drag: ComputerAction = { tool: "drag", app: APP, window: WINDOW, point: { x: 1, y: 2 }, to: { x: 3, y: 4 } };
    const set: ComputerAction = { tool: "set_value", app: APP, window: WINDOW, element: { role: "AXTextArea", label: "Body", path: [] }, text: "Hi" };
    expect(await run([BODY, SAVE, KEYS, PIXEL, scroll, drag, set, { tool: "press_key", app: APP, window: WINDOW, key: "return", modifiers: ["cmd"] }, { tool: "launch_app", app: APP }], reach(driver.session)).outcome).toMatchObject({ ok: true });
    for (const { tool, args } of driver.calls.filter((call) => !call.tool.includes("cursor"))) {
      const schema = schemas[tool]!;
      expect(schema, tool).toBeDefined();
      expect(Object.keys(args).filter((key) => !(key in schema.properties)), tool).toEqual([]);
      expect((schema.required ?? []).filter((key) => !(key in args)), tool).toEqual([]);
    }
  });

  it("hands the step to the bot when the element is ambiguous or gone, with nothing clicked", async () => {
    for (const saves of [2, 0]) {
      const driver = fakeDriver({ saves });
      const { outcome } = run([SAVE], reach(driver.session));
      const result = await outcome;
      expect(result).toMatchObject({ ok: false, done: 0 });
      if (!result.ok) expect(result.reason).toMatch(saves ? /more than one/ : /no "Save"/);
      expect(acted(driver.calls)).toEqual([]);
    }
  });

  it("clicks a recorded point only in a window of the recorded size", async () => {
    const same = fakeDriver();
    expect(await run([PIXEL], reach(same.session)).outcome).toMatchObject({ ok: true });
    expect(acted(same.calls)).toEqual([{ tool: "click", args: { x: 100, y: 50, pid: 99, window_id: 70 } }]);
    const clicked = same.calls.findIndex((call) => call.tool === "click");
    expect(same.calls[clicked - 1]).toEqual({ tool: "get_window_state", args: { pid: 99, window_id: 70, include_accessibility_tree: false } });
    const resized = fakeDriver({ width: 1024 });
    const result = await run([PIXEL], reach(resized.session)).outcome;
    expect(result).toMatchObject({ ok: false, done: 0 });
    if (!result.ok) expect(result.reason).toContain("1024×600 now, not 800×600");
    expect(acted(resized.calls)).toEqual([]);
  });

  it("shows the agent cursor while it runs and puts it back after success and after a failure", async () => {
    const ok = fakeDriver({ cursor: false });
    await run([SAVE], reach(ok.session)).outcome;
    expect(ok.calls.filter((call) => call.tool === "set_agent_cursor_enabled").map((call) => call.args)).toEqual([{ enabled: true }, { enabled: false }]);
    expect(ok.cursor()).toBe(false);
    const failing = fakeDriver({ cursor: false, failTool: "click" });
    const result = await run([SAVE, KEYS], reach(failing.session)).outcome;
    expect(result).toEqual({ ok: false, done: 0, reason: "the app refused it" });
    expect(failing.cursor()).toBe(false);
    expect(acted(failing.calls).map((call) => call.tool)).toEqual(["click"]);
    const shown = fakeDriver({ cursor: true });
    await run([SAVE], reach(shown.session)).outcome;
    expect(shown.calls.some((call) => call.tool === "set_agent_cursor_enabled")).toBe(false);
    const older = fakeDriver({ cursor: "missing" });
    expect(await run([SAVE], reach(older.session)).outcome).toMatchObject({ ok: true });
    expect(older.calls.some((call) => call.tool.includes("cursor"))).toBe(false);
  });

  it("never opens the computer when the person approves each action, or on another computer than recorded", async () => {
    const driver = fakeDriver();
    const asked = reach(driver.session, "yourComputer", false);
    expect(await run([SAVE], asked).outcome).toMatchObject({ ok: false, done: 0, reason: expect.stringMatching(/approves each computer action/) });
    const elsewhere = reach(driver.session, "localVm");
    expect(await run([SAVE], elsewhere).outcome).toMatchObject({ ok: false, reason: expect.stringMatching(/recorded on the person's own computer/) });
    expect(await run([SAVE], null).outcome).toMatchObject({ ok: false, reason: expect.stringMatching(/no computer/) });
    expect(asked.opened + elsewhere.opened).toBe(0);
    expect(driver.calls).toEqual([]);
  });

  it("clicks on the cloud computer only on a screen of the recorded size", async () => {
    const cloudSession = (size: string) => {
      const calls: Array<{ tool: string; args: Record<string, unknown> }> = [];
      const session: DeskSession = { tools: null, close: async () => {}, async call(tool, args) {
        calls.push({ tool, args });
        return tool === "get_screen_size" ? { ok: true, structured: { ok: true, stdout: `${size}\n` } } : { ok: true, structured: {} };
      } };
      return { calls, session };
    };
    const actions: ComputerAction[] = [{ tool: "click", point: { x: 640, y: 400 }, screen: { width: 1280, height: 800 } }, { tool: "press_key", key: "ctrl+s" }];
    const same = cloudSession("1280 800");
    expect(await run(actions, reach(same.session, "cloud"), "cloud").outcome).toMatchObject({ ok: true });
    expect(same.calls).toEqual([{ tool: "get_screen_size", args: {} }, { tool: "click", args: { x: 640, y: 400 } }, { tool: "key_press", args: { key: "ctrl+s" } }]);
    const other = cloudSession("1920 1080");
    expect(await run(actions, reach(other.session, "cloud"), "cloud").outcome).toMatchObject({ ok: false, done: 0 });
    expect(other.calls.map((call) => call.tool)).toEqual(["get_screen_size"]);
    const later = cloudSession("1280 800");
    const mixed: ComputerAction[] = [actions[0]!, { tool: "click", point: { x: 10, y: 10 }, screen: { width: 1920, height: 1080 } }];
    expect(await run(mixed, reach(later.session, "cloud"), "cloud").outcome).toMatchObject({ ok: false, done: 1, reason: expect.stringContaining("not 1920×1080") });
    expect(later.calls.filter((call) => call.tool === "click")).toHaveLength(1);
  });

  it("stops before the next action once the person stops allowing full access", async () => {
    const driver = fakeDriver();
    let full = true;
    const desk = { ...reach(driver.session), allowed: () => full };
    const rows: string[] = [];
    const outcome = await runComputerStep(step([BODY, SAVE]), {
      reach: desk, fill: () => "Hello team", signal: new AbortController().signal, patience: patience(),
      action: { started: (index) => rows.push(`start ${index}`), ended: (index) => { rows.push(`end ${index}`); full = false; } },
    });
    expect(outcome).toMatchObject({ ok: false, done: 1, reason: expect.stringMatching(/approves each computer action/) });
    expect(acted(driver.calls).map((call) => call.tool)).toEqual(["type_text"]);
  });
});

describe("a computer step in a run", () => {
  const workflow: Workflow = {
    version: 1, summary: "Write and save", args: { text: { default: "Hello team" } },
    steps: [step([BODY, SAVE]), { id: "s2", kind: "shell", label: "Run echo", run: "echo saved" }],
  };
  const harness = (computer: StepExecutors["computer"]) => {
    const saved: RunState[] = [];
    const events: string[] = [];
    const deps: RunDeps = {
      exec: { computer, shell: async () => ({ ok: true, output: "saved" }), app: async () => ({ ok: false, error: "no" }), browser: async () => ({ ok: false, error: "no" }), file: async () => ({ ok: false, error: "no" }) },
      events: { started: (_run, _name, one) => events.push(`start ${one.id}`), ended: (_run, _name, one, result) => events.push(`end ${one.id} ${result.state}`), action: (_run, _name, one, index, update) => events.push(`${one.id}#${index} ${"line" in update ? "start" : update.ok ? "done" : `failed: ${update.output}`}`) },
      save: (state) => saved.push(state),
    };
    return { deps, saved, events };
  };

  it("round-trips through the saved file's schema", () => {
    expect(workflowSchema.parse(JSON.parse(JSON.stringify(workflow)))).toEqual(workflow);
    expect(workflowSchema.safeParse({ ...workflow, steps: [step([{ tool: "click", point: { x: 1, y: 1 } }])] }).success).toBe(false);
    expect(workflowSchema.safeParse({ ...workflow, steps: [step([{ ...SAVE, extra: 1 } as ComputerAction])] }).success).toBe(false);
  });

  it("runs every action itself, then goes on", async () => {
    const driver = fakeDriver();
    const { deps, events } = harness(async (input) => runComputerStep(input.step, { ...input, reach: reach(driver.session), patience: patience() }));
    const envelope = await startRun({ name: "w", botId: "b", threadId: "t", sha256: "x", workflow }, deps);
    expect(envelope).toMatchObject({ ok: true, status: "ok", steps: [{ id: "s1", state: "done" }, { id: "s2", state: "done" }] });
    expect(acted(driver.calls)[0]).toEqual({ tool: "type_text", args: { text: "Hello team", pid: 99, window_id: 70, element_token: "live1:1" } });
    expect(events).toEqual(["start s1", "s1#0 start", "s1#0 done", "s1#1 start", "s1#1 done", "end s1 done", "start s2", "end s2 done"]);
  });

  it("hands what is left to the bot when an action stops, and its resume goes on with the next step", async () => {
    const driver = fakeDriver({ saves: 0 });
    const { deps, saved, events } = harness(async (input) => runComputerStep(input.step, { ...input, reach: reach(driver.session), patience: patience() }));
    const envelope = await startRun({ name: "w", botId: "b", threadId: "t", sha256: "x", workflow, args: { text: "Hi Priya" } }, deps);
    expect(envelope).toMatchObject({ ok: true, status: "needs_input", requiresInput: { type: "ai_step", step: "s1" } });
    expect(envelope.requiresInput!.prompt).toContain("Actions 1–1 of 2 ran");
    expect(envelope.requiresInput!.prompt).toContain("2. Click “Save” in TextEdit");
    expect(events).toContain("s1#1 failed: no \"Save\" (AXButton) in Untitled");
    expect(acted(driver.calls)).toEqual([{ tool: "type_text", args: { text: "Hi Priya", pid: 99, window_id: 70, element_token: "live1:1" } }]);
    const resumed = await resumeRun(saved.at(-1)!, "clicked Save myself", deps);
    expect(resumed).toMatchObject({ ok: true, status: "ok" });
    expect(acted(driver.calls)).toHaveLength(1);
  });

  it("hands the rest to the bot when the step runs past its time limit", async () => {
    vi.useFakeTimers();
    try {
      const driver = fakeDriver();
      const stuck: DeskSession = { ...driver.session, async call(tool, args, signal) {
        if (tool !== "click") return driver.session.call(tool, args, signal);
        return new Promise((done) => signal.addEventListener("abort", () => done({ ok: false, error: "aborted" }), { once: true }));
      } };
      const { deps, events } = harness(async (input) => runComputerStep(input.step, { ...input, reach: reach(stuck), patience: patience() }));
      const slow: Workflow = { ...workflow, steps: [{ ...step([BODY, SAVE]), timeoutMs: 5_000 }, workflow.steps[1]!] };
      const pending = startRun({ name: "w", botId: "b", threadId: "t", sha256: "x", workflow: slow }, deps);
      await vi.advanceTimersByTimeAsync(5_001);
      const envelope = await pending;
      expect(envelope).toMatchObject({ status: "needs_input", requiresInput: { type: "ai_step", step: "s1" } });
      expect(envelope.requiresInput!.prompt).toContain("Actions 1–1 of 2 ran");
      expect(envelope.requiresInput!.prompt).toContain("took longer than 5 s");
      expect(events).toContain("s1#1 failed: it took longer than 5 s");
    } finally {
      vi.useRealTimers();
    }
  });

  it("still runs an older burger whose desktop step is the AI's", async () => {
    const older = workflowSchema.parse({ version: 1, summary: "Old", args: {}, steps: [
      { id: "s1", kind: "ai", deterministic: false, label: "Click, type text", where: "vm", prompt: "Do this step again: Click, type text on the cloud computer. Look at the screen first." },
      { id: "s2", kind: "shell", label: "Run echo", run: "echo ok" },
    ] });
    const { deps } = harness(undefined);
    expect(await startRun({ name: "w", botId: "b", threadId: "t", sha256: "x", workflow: older }, deps)).toMatchObject({ status: "needs_input", requiresInput: { type: "ai_step", step: "s1" } });
  });
});