Skip to content

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

9.9 KB
Raw Blame
import { afterEach, describe, expect, it, vi } from "vitest";
import { api, persistBotUpdate, type Bot } from "@/state/store";
import { BotCreationDraft, EMPTY_BOT_DEFAULTS } from "./bot-creation-draft";
import { createConfiguredBot } from "./create-configured-bot";

afterEach(() => vi.unstubAllGlobals());

describe("configured bot creation", () => {
  function fixture(mode: "ask" | "auto" | "full" | "custom", fail = 0, selection?: Bot["modelSelection"]) {
    const draft = new BotCreationDraft(EMPTY_BOT_DEFAULTS, vi.fn());
    draft.patch({ name: "Fixture", approvalMode: mode, notifications: false });
    let bot = { ...draft.bot, id: "created", threadId: "initial", approvalMode: "ask" } as Bot;
    if (selection) bot.modelSelection = selection;
    const events: string[] = [];
    const bodies: unknown[] = [];
    const request = vi.fn(async (path: string, init?: RequestInit) => {
      events.push(`${init?.method} ${path}`);
      const body = JSON.parse(String(init?.body ?? "{}"));
      bodies.push(body);
      if (init?.method === "PATCH") bot = { ...bot, ...body };
      return { bot };
    }) as unknown as typeof api;
    let grants = 0;
    const approvals = { setMode: vi.fn(async (_id: string, grant: string, options?: { threadId?: string }) => {
      events.push(`grant ${options?.threadId ?? "bot"}`);
      if (++grants === fail) throw new Error("Grant rejected");
      bot = { ...bot, approvalMode: grant } as Bot;
      return bot;
    }) };
    return { draft, events, bodies, request, approvals };
  }

  it("sets the chosen audience in the first creation request", async () => {
    const f = fixture("ask");
    await createConfiguredBot(f.draft, f.request, persistBotUpdate, f.approvals, "admins");
    expect(f.events[0]).toBe("POST /api/bots");
    expect(f.bodies[0]).toMatchObject({ visibility: "admins", useDefaults: false });
  });

  it("names who a new team bot reports to in the creation request, and nobody anywhere else", async () => {
    const team = fixture("ask");
    await createConfiguredBot(team.draft, team.request, persistBotUpdate, team.approvals, undefined, "[email protected]");
    expect(team.bodies[0]).toMatchObject({ reportsTo: "[email protected]" });
    const solo = fixture("ask");
    await createConfiguredBot(solo.draft, solo.request, persistBotUpdate, solo.approvals);
    expect(solo.bodies[0]).not.toHaveProperty("reportsTo");
  });

  it("applies tool restrictions atomically before a new bot is published", async () => {
    const f = fixture("ask");
    f.draft.patch({ toolScope: { allow: [], deny: ["mcp:mail:send"] } });
    await createConfiguredBot(f.draft, f.request, persistBotUpdate, f.approvals);
    expect(f.bodies[0]).toMatchObject({ settings: { toolScope: { allow: [], deny: ["mcp:mail:send"] } } });
    expect(f.bodies[1]).not.toHaveProperty("toolScope");
  });

  it("keeps the server-completed workspace effort when applying draft settings", async () => {
    const selection = { instanceId: "claude", model: "sonnet", effort: "high" as const };
    const f = fixture("ask", 0, selection);
    f.draft.setModel({ instanceId: selection.instanceId, model: selection.model });
    const result = await createConfiguredBot(f.draft, f.request, persistBotUpdate, f.approvals);
    expect(f.bodies[0]).toMatchObject({ modelSelection: { instanceId: "claude", model: "sonnet" }, requireAvailableModel: true });
    expect(f.bodies[1]).not.toHaveProperty("modelSelection");
    expect(result.bot.modelSelection).toEqual(selection);
  });

  it("asks for no AI when none is set up, so the server makes the bot without one", async () => {
    const f = fixture("ask");
    f.draft.setModel({ instanceId: "", model: "" });
    await createConfiguredBot(f.draft, f.request, persistBotUpdate, f.approvals);
    expect(f.bodies[0]).not.toHaveProperty("modelSelection");
    expect(f.bodies[0]).not.toHaveProperty("requireAvailableModel");
    expect(f.events).not.toContain("DELETE /api/bots/created");
  });

  for (const mode of ["ask", "auto", "full", "custom"] as const) {
    it(`commits ${mode} settings without reapplying the template`, async () => {
      const f = fixture(mode);
      const result = await createConfiguredBot(f.draft, f.request, persistBotUpdate, f.approvals);
      expect(f.bodies[0]).toMatchObject({ useDefaults: false, name: "Fixture" });
      expect(result.bot).toMatchObject({ approvalMode: mode, notifications: false });
      expect(result.warnings).toEqual([]);
      expect(f.events.filter(event => event.startsWith("grant"))).toEqual(
        mode === "full" || mode === "custom" ? ["grant bot", "grant initial"] : [],
      );
      expect(f.events).not.toContain("DELETE /api/bots/created");
    });
  }

  it("applies Full to the bot and its first thread over the API when there is no desktop bridge", async () => {
    const f = fixture("full");
    const result = await createConfiguredBot(f.draft, f.request, persistBotUpdate, undefined);
    expect(result.bot).toMatchObject({ approvalMode: "full" });
    expect(f.events).toEqual(["POST /api/bots", "PATCH /api/bots/created", "PATCH /api/bots/created/tasks/initial"]);
    expect(f.bodies[1]).toMatchObject({ approvalMode: "full" });
    expect(f.bodies[2]).toEqual({ approvalMode: "full", acknowledgeLocalAuto: false });
    for (const body of f.bodies) expect(body).not.toHaveProperty("confirmFullAccess");
  });

  it("still refuses Custom without the desktop bridge and removes the half-made bot", async () => {
    const f = fixture("custom");
    await expect(createConfiguredBot(f.draft, f.request, persistBotUpdate, undefined)).rejects.toThrow("packaged desktop app");
    expect(f.events).toEqual(["POST /api/bots", "DELETE /api/bots/created"]);
  });

  for (const fail of [1, 2]) {
    it(`rolls back when native grant ${fail} fails`, async () => {
      const f = fixture("full", fail);
      await expect(createConfiguredBot(f.draft, f.request, persistBotUpdate, f.approvals)).rejects.toThrow("Grant rejected");
      expect(f.events.at(-1)).toBe("DELETE /api/bots/created");
    });
  }

  it("does not grant the initial thread when the native bot grant returns the wrong mode", async () => {
    const f = fixture("full");
    f.approvals.setMode.mockImplementation(async () => ({ ...f.draft.bot, id: "created", threadId: "initial", approvalMode: "ask" }));
    await expect(createConfiguredBot(f.draft, f.request, persistBotUpdate, f.approvals)).rejects.toThrow("was not granted");
    expect(f.approvals.setMode).toHaveBeenCalledTimes(1);
    expect(f.events.at(-1)).toBe("DELETE /api/bots/created");
  });

  describe("a template with memory, skills and a routine", () => {
    const skill = (name: string) => ({ name, description: "", warnings: [], source: `local:${name}`, text: `---\nname: ${name}\n---\n`, enabled: true });
    const routine = { name: "Morning check", prompt: "Check the inbox", schedule: { type: "daily" as const, time: "09:00", weekdays: [1, 2, 3, 4, 5] } };
    function templated(failing?: string) {
      const draft = new BotCreationDraft({
        profile: { name: "Fixture" },
        memory: { "MEMORY.md": "index", "memory/notes.md": "notes" },
        skills: [skill("first-skill"), skill("second-skill")],
        routines: [routine],
      }, vi.fn());
      const events: string[] = [];
      const open = new Set<string>();
      let widest = 0;
      const request = vi.fn(async (path: string, init?: RequestInit) => {
        const body = JSON.parse(String(init?.body ?? "{}"));
        const event = `${init?.method} ${path}${body.path ? ` ${body.path}` : path.endsWith("/skill-template") ? ` ${body.name}` : ""}`;
        events.push(event);
        open.add(event);
        widest = Math.max(widest, open.size);
        await new Promise((resolve) => setTimeout(resolve, 0));
        open.delete(event);
        if (event === failing) throw new Error("Refused");
        if (path === "/api/routines") return { routine: { id: "routine-1" } };
        return { bot: { ...draft.bot, id: "created", threadId: "initial", approvalMode: "ask" } };
      }) as unknown as typeof api;
      return { draft, events, request, widest: () => widest };
    }
    const setup = ["PUT /api/bots/created/memory/file MEMORY.md", "PUT /api/bots/created/memory/file memory/notes.md",
      "POST /api/bots/created/skill-template first-skill", "POST /api/bots/created/skill-template second-skill", "POST /api/routines"];

    it("sends each file once, each kind in its own order, the kinds side by side", async () => {
      const f = templated();
      const result = await createConfiguredBot(f.draft, f.request, persistBotUpdate, undefined);
      expect(result.warnings).toEqual([]);
      expect(f.events.slice(0, 2)).toEqual(["POST /api/bots", "PATCH /api/bots/created"]);
      expect(f.events.at(-1)).toBe("PATCH /api/routines/routine-1");
      expect(f.events.slice(2, -1).sort()).toEqual([...setup].sort());
      const at = (event: string) => f.events.indexOf(event);
      expect(at(setup[0]!)).toBeLessThan(at(setup[1]!));
      expect(at(setup[2]!)).toBeLessThan(at(setup[3]!));
      expect(f.events.slice(2, 5).sort()).toEqual([setup[0]!, setup[2]!, setup[4]!].sort());
      expect(f.widest()).toBe(3);
    });

    it("removes the routine and the bot when a skill is refused, after every other request has answered", async () => {
      const f = templated(setup[2]);
      await expect(createConfiguredBot(f.draft, f.request, persistBotUpdate, undefined)).rejects.toThrow("Refused");
      expect(f.events.slice(-2)).toEqual(["DELETE /api/routines/routine-1", "DELETE /api/bots/created"]);
      expect(f.events).not.toContain(setup[3]);
      expect(f.events).toContain(setup[1]);
      expect(f.events).not.toContain("PATCH /api/routines/routine-1");
    });

    it("removes the bot when a memory file is refused", async () => {
      const f = templated(setup[0]);
      await expect(createConfiguredBot(f.draft, f.request, persistBotUpdate, undefined)).rejects.toThrow("Refused");
      expect(f.events.slice(-2)).toEqual(["DELETE /api/routines/routine-1", "DELETE /api/bots/created"]);
      expect(f.events).not.toContain(setup[1]);
    });
  });
});