Skip to content

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

4.6 KB
Raw Blame
// @vitest-environment happy-dom
import { act, createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";

import { actionView } from "../../../shared/skill-burger/computer";
import type { DraftStepView } from "../../../shared/skill-burger/draft-view";
import type { ComputerAction, Workflow } from "../../../shared/skill-burger/format";
import { RUN_STEP_MARK, type RunMessage } from "../../../shared/skill-burger/layers";

const fixture = vi.hoisted(() => ({ api: vi.fn() }));
vi.mock("@/state/api", () => ({ api: (...args: unknown[]) => fixture.api(...args) }));

const { SkillBurgerSlot } = await import("./SkillBurgerSlot");
const { DraftSteps } = await import("./DraftSteps");

(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
let host: HTMLDivElement;
let root: Root;

const APP = { bundleId: "com.apple.TextEdit", name: "TextEdit" };
const WINDOW = { title: "Untitled" };
const actions: ComputerAction[] = [
  { tool: "type_text", app: APP, window: WINDOW, element: { role: "AXTextArea", label: "Body", path: [] }, text: { $arg: "recipient" } },
  { tool: "click", app: APP, window: WINDOW, element: { role: "AXButton", label: "Save", path: [] } },
  { tool: "hotkey", app: APP, window: WINDOW, keys: ["cmd", "s"] },
];
const workflow: Workflow = {
  version: 1, summary: "Write it", args: { recipient: { default: "Priya" } },
  steps: [
    { id: "s1", kind: "computer", label: "Type {recipient} in “Body”, click “Save” in TextEdit, press ⌘S", on: "yourComputer", where: "yourComputer", actions },
    { id: "s2", kind: "shell", label: "Run echo done", run: "echo done" },
  ],
};

const ask: RunMessage = { id: "u1", role: "user", kind: "text", text: "/write-it" };
let n = 0;
const row = (input: Record<string, unknown>, output?: Record<string, unknown>): RunMessage => ({
  id: `m${++n}`, role: "bot", kind: "activity",
  tool: { name: "x", input: JSON.stringify({ [RUN_STEP_MARK]: "run-1", name: "write-it", ...input }), ...(output ? { ok: output.state !== "failed", output: JSON.stringify(output) } : {}) },
});

const render = async (messages: RunMessage[]) => {
  await act(async () => root.render(createElement(SkillBurgerSlot, { botId: "scout", threadId: "t1", busy: true, canWrite: true, messages, liveTools: new Set<string>(), transcriptKey: "scout:t1" })));
  await act(async () => { await Promise.resolve(); });
};
const rows = () => [...host.querySelectorAll("[data-burger-layer]")].map((one) => `${one.getAttribute("data-status")} ${one.textContent?.replace(/\s+/g, " ").trim()}`);

beforeEach(() => {
  fixture.api.mockReset();
  fixture.api.mockImplementation(async (path: string) => (path.includes("?runner=") ? { workflow } : {}));
  host = document.createElement("div");
  document.body.append(host);
  root = createRoot(host);
});
afterEach(() => {
  act(() => root.unmount());
  host.remove();
});

it("shows a running computer step by its first action, its progress, and never an action row as a step", async () => {
  await render([ask, row({ step: "s1" }), row({ step: "s1", action: 0 }, { state: "done" }), row({ step: "s1", action: 1 })]);
  expect(rows()).toEqual(["running Type {recipient}, and 2 more1 of 3", "waiting Run echo done"]);
});

it("names the action a step stopped at and why, once the bot took the rest over", async () => {
  await render([ask, row({ step: "s1" }), row({ step: "s1", action: 0 }, { state: "done" }), row({ step: "s1", action: 1 }, { state: "failed", error: "no \"Save\" (AXButton) in Untitled" }), row({ step: "s1" }, { state: "done" })]);
  expect(rows()[0]).toBe("done Type {recipient}, and 2 moreStopped at action 2: no \"Save\" (AXButton) in Untitled");
  expect(host.querySelector("[data-burger-stopped]")?.getAttribute("title")).toBe("no \"Save\" (AXButton) in Untitled");
});

it("lists each recorded action on the draft card when the step is opened", async () => {
  const step: DraftStepView = { id: "s1", kind: "computer", label: "ignored", exact: true, needs: [], actions: actions.map((action) => actionView(action, "yourComputer")) };
  await act(async () => root.render(createElement(DraftSteps, { steps: [step], skipped: new Set<string>(), onSkip: () => {}, disabled: false })));
  expect(host.textContent).toContain("Type {recipient}, and 2 more");
  const open = [...host.querySelectorAll("button")].find((button) => button.getAttribute("aria-expanded") === "false")!;
  await act(async () => { open.click(); });
  expect([...host.querySelectorAll("[data-burger-actions] li")].map((li) => li.textContent)).toEqual(["Type {recipient}", "Click “Save” in TextEdit", "Press ⌘S"]);
});