Skip to content

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

16.9 KB
Raw Blame
import { describe, expect, it } from "vitest";

import { draftWorkflow } from "../../shared/skill-burger/draft.ts";
import { renderWorkflowSkillMd, workflowSchema, type WorkflowStep } from "../../shared/skill-burger/format.ts";
import type { RunMessage } from "../../shared/skill-burger/layers.ts";
import { slimResponse, type SlimStructured } from "../saved-steps/driver-wire.ts";
import { toolDetailPreview } from "../tool-summary.ts";
import { deskRecording } from "./desk-record.ts";
import type { DeskCall, DeskSnapshot } from "./desk.ts";

const ASK = 'Write "Hello team" to [email protected] in TextEdit';
const TREE: SlimStructured = {
  pid: 42, window_id: 7, app_name: "TextEdit", bundle_id: "com.apple.TextEdit", window_title: "Untitled", elements_complete: true,
  elements: [
    { element_index: 0, role: "AXWindow", label: "Untitled", depth: 0 },
    { element_index: 1, element_token: "s1:1", role: "AXTextArea", label: "Body", parent_index: 0, depth: 1 },
    { element_index: 2, element_token: "s1:2", role: "AXButton", label: "Save", parent_index: 0, depth: 1 },
    { element_index: 3, element_token: "s1:3", role: "AXTextField", label: "To", parent_index: 0, depth: 1 },
    { element_index: 4, element_token: "s1:4", role: "AXSecureTextField", label: "Password", parent_index: 0, depth: 1 },
  ],
};
const LOOKS: Array<[string, Record<string, unknown>, SlimStructured]> = [
  ["list_apps", {}, { apps: [{ pid: 42, name: "TextEdit", bundle_id: "com.apple.TextEdit" }] }],
  ["list_windows", { pid: 42 }, { windows: [{ window_id: 7, pid: 42, title: "Untitled", app_name: "TextEdit", bounds: { x: 0, y: 0, width: 800, height: 600 } }] }],
  ["get_window_state", { pid: 42, window_id: 7 }, TREE],
];
const WIN = { pid: 42, window_id: 7 };


function run(actions: Array<[string, Record<string, unknown>]>, options: { place?: DeskCall["place"]; looks?: typeof LOOKS; server?: string } = {}) {
  let n = 0;
  const ask: RunMessage = { id: "ask", role: "user", kind: "text", text: ASK };
  const calls: Array<[string, Record<string, unknown>, SlimStructured]> = [...(options.looks ?? LOOKS), ...actions.map(([tool, args]): [string, Record<string, unknown>, SlimStructured] => [tool, args, {}])];
  const rows: RunMessage[] = calls.map(([tool, args]) => ({ id: `r${++n}`, role: "bot", kind: "activity", tool: { name: `mcp__${options.server ?? "computer"}__${tool}`, ok: true, itemId: `i${n}`, input: toolDetailPreview(args) } }));
  const shell: RunMessage = { id: "sh", role: "bot", kind: "activity", tool: { name: "Bash", ok: true, itemId: "ish", input: JSON.stringify({ command: "cp notes.txt backup.txt" }), summary: "cp notes.txt backup.txt" } };
  const snapshot: DeskSnapshot = {
    requestId: "ask", complete: true, tainted: false,
    calls: calls.map(([tool, args, structured]) => ({ tool, arguments: args, result: { isError: false, structured }, place: options.place ?? "yourComputer", generation: "g1" })),
  };
  return { messages: [ask, shell, ...rows], snapshot };
}

function computerStep(messages: RunMessage[], snapshot: DeskSnapshot | null): WorkflowStep {
  const desk = deskRecording(messages, snapshot);
  const draft = draftWorkflow(messages, desk ? { desk } : {});
  expect(workflowSchema.safeParse(draft!.workflow).success).toBe(true);
  return draft!.workflow.steps[1]!;
}

describe("desktop actions recorded from what the computer saw", () => {
  it("saves clicks, typing, keys, a pixel click and a drag as one computer step with inputs", () => {
    const { messages, snapshot } = run([
      ["click", { ...WIN, element_token: "s1:2" }],
      ["set_value", { element_token: "s1:3", value: "[email protected]" }],
      ["type_text", { element_token: "s1:1", text: "Hello team" }],
      ["hotkey", { ...WIN, keys: ["cmd", "s"] }],
      ["click", { ...WIN, x: 100, y: 50 }],
      ["drag", { ...WIN, from_x: 10, from_y: 20, to_x: 300, to_y: 40 }],
    ]);
    const draft = draftWorkflow(messages, { desk: deskRecording(messages, snapshot)! })!;
    const step = draft.workflow.steps[1]!;
    expect(step.kind).toBe("computer");
    if (step.kind !== "computer") return;
    const app = { bundleId: "com.apple.TextEdit", name: "TextEdit" };
    const window = { title: "Untitled", width: 800, height: 600 };
    expect(step.on).toBe("yourComputer");
    expect(step.where).toBe("yourComputer");
    expect(step.actions).toEqual([
      { tool: "click", app, window, element: { role: "AXButton", label: "Save", path: [] } },
      { tool: "set_value", app, window, element: { role: "AXTextField", label: "To", path: [] }, text: { $arg: "email" } },
      { tool: "type_text", app, window, element: { role: "AXTextArea", label: "Body", path: [] }, text: { $arg: "text" } },
      { tool: "hotkey", app, window, keys: ["cmd", "s"] },
      { tool: "click", app, window, point: { x: 100, y: 50 } },
      { tool: "drag", app, window, point: { x: 10, y: 20 }, to: { x: 300, y: 40 } },
    ]);
    expect(draft.workflow.args).toMatchObject({ email: { default: "[email protected]" }, text: { default: "Hello team" } });
    expect(step.label).toBe("Click “Save” in TextEdit, fill “To” with {email}, type {text} in “Body”, press ⌘S, and 2 more");
    expect(JSON.stringify(step)).not.toContain("s1:");
    expect(JSON.stringify(step)).not.toContain("\"pid\"");
    const md = renderWorkflowSkillMd("write-it", draft.workflow);
    expect(md).toContain("Computer on the person's own computer:");
    expect(md).toContain("   - Press ⌘S");
    expect(md).toContain("   - Type {text} in “Body”");
  });

  it("keeps the AI step when the calls weren't all seen, a call was refused, or the rows don't match", () => {
    const actions: Array<[string, Record<string, unknown>]> = [["click", { ...WIN, element_token: "s1:2" }], ["hotkey", { ...WIN, keys: ["cmd", "s"] }]];
    const { messages, snapshot } = run(actions);
    expect(computerStep(messages, { ...snapshot, complete: false }).kind).toBe("ai");
    expect(computerStep(messages, { ...snapshot, tainted: true }).kind).toBe("ai");
    expect(computerStep(messages, null).kind).toBe("ai");
    expect(computerStep(messages, { ...snapshot, requestId: "older-ask" }).kind).toBe("ai");
    expect(computerStep(messages, { ...snapshot, calls: snapshot.calls.slice(1) }).kind).toBe("ai");
    const swapped = snapshot.calls.map((call) => (call.tool === "hotkey" ? { ...call, arguments: { ...call.arguments, window_id: 8 } } : call));
    expect(computerStep(messages, { ...snapshot, calls: swapped }).kind).toBe("ai");
    expect(computerStep(messages, snapshot).kind).toBe("computer");
  });

  it("never keeps a step that touched a secret field, typed into one, or typed a secret", () => {
    const secret = run([["click", { ...WIN, element_token: "s1:2" }], ["click", { ...WIN, element_token: "s1:4" }], ["type_text", { ...WIN, text: "hunter2" }]]);
    const typed = computerStep(secret.messages, secret.snapshot);
    expect(typed).toMatchObject({ kind: "ai", prompt: expect.stringContaining("It used a secret, so it isn't saved here.") });
    expect(JSON.stringify(typed)).not.toContain("hunter2");
    const set = run([["set_value", { element_token: "s1:4", value: "hunter2" }]]);
    const filled = computerStep(set.messages, set.snapshot);
    expect(filled.kind).toBe("ai");
    expect(JSON.stringify(filled)).not.toContain("hunter2");
    const key = run([["type_text", { element_token: "s1:1", text: "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJ" }]]);
    const step = computerStep(key.messages, key.snapshot);
    expect(step.kind).toBe("ai");
    expect(JSON.stringify(step)).not.toContain("abcdefghijklmnop");
    const refused = run([["click", { ...WIN, element_token: "s1:2" }]]);
    refused.snapshot.calls = refused.snapshot.calls.map((call) => (call.tool === "click" ? { ...call, result: { isError: false, structured: { refusal: { code: "background_unavailable" } } } } : call));
    expect(computerStep(refused.messages, refused.snapshot).kind).toBe("ai");
  });

  describe("text typed where the focus can't be named is kept only as an input", () => {
    const hidden = (step: WorkflowStep) => {
      expect(step).toMatchObject({ kind: "ai", prompt: expect.stringContaining("It used a secret, so it isn't saved here.") });
      expect(JSON.stringify(step)).not.toContain("hunter2");
    };
    const SHEET: typeof LOOKS = [
      LOOKS[0]!,
      ["list_windows", { pid: 42 }, { windows: [
        { window_id: 7, pid: 42, title: "Untitled", app_name: "TextEdit", bounds: { x: 0, y: 0, width: 800, height: 600 } },
        { window_id: 8, pid: 42, title: "Sign in", app_name: "TextEdit", bounds: { x: 0, y: 0, width: 400, height: 200 } },
      ] }],
      LOOKS[2]!,
    ];

    it("keeps text typed right after a click on a plain text field in the same window", () => {
      const { messages, snapshot } = run([["click", { ...WIN, element_token: "s1:3" }], ["type_text", { ...WIN, text: "alice" }]]);
      const step = computerStep(messages, snapshot);
      expect(step).toMatchObject({ kind: "computer", actions: [{ tool: "click", element: { label: "To" } }, { tool: "type_text", text: "alice" }] });
    });

    it("saves none of the calls when the text follows a Tab, a pixel click, nothing, or a click in another window", () => {
      hidden(computerStep(...Object.values(run([["click", { ...WIN, element_token: "s1:3" }], ["type_text", { ...WIN, text: "alice" }], ["press_key", { ...WIN, key: "tab" }], ["type_text", { ...WIN, text: "hunter2" }]])) as [RunMessage[], DeskSnapshot]));
      hidden(computerStep(...Object.values(run([["click", { ...WIN, x: 100, y: 50 }], ["type_text", { ...WIN, text: "hunter2" }]])) as [RunMessage[], DeskSnapshot]));
      hidden(computerStep(...Object.values(run([["type_text", { ...WIN, text: "hunter2" }]])) as [RunMessage[], DeskSnapshot]));
      hidden(computerStep(...Object.values(run([["click", { ...WIN, element_token: "s1:3" }], ["type_text", { pid: 42, window_id: 8, text: "hunter2" }]], { looks: SHEET })) as [RunMessage[], DeskSnapshot]));
      hidden(computerStep(...Object.values(run([["click", { ...WIN, element_token: "s1:2" }], ["type_text", { ...WIN, text: "hunter2" }]])) as [RunMessage[], DeskSnapshot]));
      const cloud = run([["click", { x: 640, y: 400 }], ["type_text", { text: "hunter2" }]], { place: "cloud", looks: [["screenshot", {}, {}]] });
      cloud.snapshot.calls = cloud.snapshot.calls.map((call) => ({ ...call, screen: { width: 1280, height: 800 } }));
      hidden(computerStep(cloud.messages, cloud.snapshot));
    });

    it("keeps such text as the ask's input when the ask holds it", () => {
      const { messages, snapshot } = run([["press_key", { ...WIN, key: "tab" }], ["type_text", { ...WIN, text: "Hello team" }]]);
      expect(computerStep(messages, snapshot)).toMatchObject({ kind: "computer", actions: [{ tool: "press_key" }, { tool: "type_text", text: { $arg: "text" } }] });
    });
  });

  it("leaves a step that sends, deletes or pays to the bot, with none of its calls", () => {
    const send = { element_index: 6, element_token: "s1:6", role: "AXButton", label: "Send", parent_index: 0, depth: 1 };
    const looks: typeof LOOKS = [...LOOKS.slice(0, 2), ["get_window_state", WIN, { ...TREE, elements: [...TREE.elements!, send] }]];
    for (const action of [["click", { ...WIN, element_token: "s1:6" }], ["hotkey", { ...WIN, keys: ["cmd", "return"] }], ["press_key", { ...WIN, key: "delete", modifiers: ["cmd"] }]] as Array<[string, Record<string, unknown>]>) {
      const { messages, snapshot } = run([["click", { ...WIN, element_token: "s1:2" }], action], { looks });
      const step = computerStep(messages, snapshot);
      expect(step, action[0]).toMatchObject({ kind: "ai", prompt: expect.stringContaining("can't be undone") });
      expect(JSON.stringify(step)).not.toContain("Last time");
    }
    const cloud = run([["click", { x: 640, y: 400 }], ["key_press", { key: "ctrl+return" }]], { place: "cloud", looks: [["screenshot", {}, {}]] });
    cloud.snapshot.calls = cloud.snapshot.calls.map((call) => ({ ...call, screen: { width: 1280, height: 800 } }));
    expect(computerStep(cloud.messages, cloud.snapshot)).toMatchObject({ kind: "ai", prompt: expect.stringContaining("can't be undone") });
  });

  it("names the place from the computer, not the tool's server: own computer, Local VM, cloud", () => {
    const own = run([["click", { ...WIN, element_token: "s1:2" }]]);
    expect(computerStep(own.messages, own.snapshot)).toMatchObject({ kind: "computer", on: "yourComputer", where: "yourComputer" });
    const vm = run([["click", { ...WIN, element_token: "s1:2" }]], { place: "localVm" });
    expect(computerStep(vm.messages, vm.snapshot)).toMatchObject({ kind: "computer", on: "localVm", where: "vm" });
    const cloud = run([["click", { x: 640, y: 400 }], ["key_press", { key: "ctrl+s" }], ["type_text", { text: "Hello team" }]], { place: "cloud", looks: [["screenshot", {}, {}]] });
    cloud.snapshot.calls = cloud.snapshot.calls.map((call) => ({ ...call, screen: { width: 1280, height: 800 } }));
    const step = computerStep(cloud.messages, cloud.snapshot);
    expect(step).toMatchObject({ kind: "computer", on: "cloud", where: "vm" });
    if (step.kind === "computer") {
      expect(step.actions).toEqual([
        { tool: "click", point: { x: 640, y: 400 }, screen: { width: 1280, height: 800 } },
        { tool: "press_key", key: "ctrl+s" },
        { tool: "type_text", text: { $arg: "text" } },
      ]);
    }
  });

  it("leaves a cloud click whose screen size was never seen, and a pixel click in a window of unknown size, to the AI", () => {
    const cloud = run([["click", { x: 640, y: 400 }]], { place: "cloud", looks: [] });
    expect(computerStep(cloud.messages, cloud.snapshot).kind).toBe("ai");
    const looks = LOOKS.map(([tool, args, data]): typeof LOOKS[number] => (tool === "list_windows" ? [tool, args, { windows: [{ window_id: 7, pid: 42, title: "Untitled" }] }] : [tool, args, data]));
    const pixel = run([["click", { ...WIN, x: 100, y: 50 }]], { looks });
    expect(computerStep(pixel.messages, pixel.snapshot).kind).toBe("ai");
  });

  it("records a Linux desktop as the driver answers it: markdown tree, flat elements, the process's name, foreground retries", () => {
    // Shapes as Cua Driver 0.41.3 on X11 answered them.
    const tree = slimResponse({ id: 1, result: { content: [], structuredContent: {
      pid: 871, window_id: 8388611, app_name: "Proofapp.py", window_title: "Burger Proof", snapshot_id: "s00000007", tree_format: "markdown",
      elements_complete: true, element_count: 2, returned_element_count: 2, total_element_count: 2,
      tree_markdown: "- frame = \"Burger Proof\"\n      - [1] push button \"Save\" [actions=[click]]\n      - [5] text \"Name\" [actions=[activate]]\n      - label = \"Name\"\n",
    } } }).structured!;
    const win = { pid: 871, window_id: 8388611 };
    const looks: typeof LOOKS = [
      ["list_windows", { pid: 871 }, { windows: [{ window_id: 8388611, pid: 871, title: "Burger Proof", app_name: "Proofapp.py", bounds: { x: 61, y: 80, width: 480, height: 360 } }] }],
      ["list_apps", {}, { apps: [{ pid: 871, name: "python3" }] }],
      ["get_window_state", win, tree],
    ];
    const background = { ...win, element_token: "s00000007:5" };
    const { messages, snapshot } = run([
      ["click", background], ["click", { ...background, delivery_mode: "foreground" }],
      ["type_text", { ...background, text: "Ada Lovelace" }],
      ["click", { ...win, x: 240, y: 300 }], ["click", { delivery_mode: "foreground", ...win, x: 240, y: 300 }],
    ], { looks });
    const refusedAt = new Set([3, 6]);
    snapshot.calls = snapshot.calls.map((call, index) => (refusedAt.has(index) ? { ...call, result: { isError: true } } : call));
    messages.forEach((message) => { if (message.tool && refusedAt.has(Number(message.id.slice(1)) - 1)) message.tool.ok = false; });
    const step = computerStep(messages, snapshot);
    const app = { name: "python3" };
    const window = { title: "Burger Proof", width: 480, height: 360 };
    expect(step).toMatchObject({ kind: "computer", actions: [
      { tool: "click", app, window, element: { role: "text", label: "Name", path: [] }, foreground: true },
      { tool: "type_text", app, window, element: { role: "text", label: "Name", path: [] }, text: "Ada Lovelace" },
      { tool: "click", app, window, point: { x: 240, y: 300 }, foreground: true },
    ] });
  });

  it("leaves an action it can't repeat as recorded to the AI: a toggle, an unknown argument, a desktop-wide point", () => {
    const toggle = run([["click", { ...WIN, element_token: "s1:5" }]], { looks: [...LOOKS.slice(0, 2), ["get_window_state", WIN, { ...TREE, elements: [...TREE.elements!, { element_index: 5, element_token: "s1:5", role: "AXCheckBox", label: "Bold", parent_index: 0, depth: 1 }] }]] });
    expect(computerStep(toggle.messages, toggle.snapshot).kind).toBe("ai");
    const odd = run([["click", { ...WIN, element_token: "s1:2", capture_id: "c1" }]]);
    expect(computerStep(odd.messages, odd.snapshot).kind).toBe("ai");
    const desktop = run([["click", { x: 5, y: 5, scope: "desktop", pid: 42 }]]);
    expect(computerStep(desktop.messages, desktop.snapshot).kind).toBe("ai");
  });
});