Skip to content

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

11.3 KB
Raw Blame
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { chatComputer, runCloudComputerOwner, runComputerPin, TEAM_COMPUTER_REFUSAL } from "./routine-computer.ts";
import { loadRoutine, loadRun } from "./routine-load.ts";
import { RoutineRequestService, type RoutineRequestMessage, type RoutineRequestOptionCard, type RoutineRequestStore } from "./routine-requests.ts";
import { routineRunDefinition } from "./routine-run-definition.ts";
import { RoutineManager, type Routine, type RoutineInput, type RoutineManagerOptions, type RoutineRun } from "./routines.ts";

const dirs: string[] = [];
afterEach(() => {
  for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});

const START = Date.parse("2026-11-29T10:00:00Z");
const daily = { type: "daily" as const, time: "09:00", weekdays: [1] };
const base: RoutineInput = { name: "Inbox sweep", prompt: "Sweep the inbox", botId: "bot-a", schedule: daily };
type Pin = { surface?: "local" | "vm" | "cloud" | "browser"; surfaceSource?: "user" | "auto" };

function manager(teamBots: string[] = []) {
  const dir = mkdtempSync(join(tmpdir(), "omb-routine-computer-"));
  dirs.push(dir);
  const options: RoutineManagerOptions = {
    file: join(dir, "routines.json"),
    now: () => START,
    botState: () => "ready",
    createTask: () => ({ threadId: "thread-1" }),
    startTurn: async () => {},
    teamComputer: (botId) => teamBots.includes(botId),
  };
  return { options, routines: new RoutineManager(options) };
}

class MemoryStore implements RoutineRequestStore {
  private readonly threads = new Map<string, RoutineRequestMessage[]>();
  messagesFor(threadId: string): RoutineRequestMessage[] {
    return this.threads.get(threadId) ?? [];
  }
  appendMessage(threadId: string, message: { card: RoutineRequestOptionCard }): RoutineRequestMessage {
    const stored = { id: `message-${this.messagesFor(threadId).length + 1}`, card: message.card };
    this.threads.set(threadId, [...this.messagesFor(threadId), stored]);
    return stored;
  }
  patchMessage(threadId: string, messageId: string, patch: { card: RoutineRequestOptionCard }): RoutineRequestMessage | null {
    const message = this.messagesFor(threadId).find((candidate) => candidate.id === messageId);
    if (message) message.card = patch.card;
    return message ?? null;
  }
}

function chatCards(pins: Record<string, Pin>, teamBots: string[] = []) {
  const { routines } = manager(teamBots);
  const requests = new RoutineRequestService({
    store: new MemoryStore(),
    routines,
    now: () => START,
    timeZone: () => "UTC",
    autoApply: () => "full-access",
    chatComputer: (botId, threadId) => chatComputer(pins[`${botId}/${threadId}`], teamBots.includes(botId)),
  });
  const create = (threadId: string, forBot?: { botId: string; name: string }) => requests.submit({
    botId: "bot-a",
    threadId,
    proposal: {
      action: "create",
      ...(forBot ? { forBot } : {}),
      routine: { name: `Sweep ${threadId}`, instructions: `Sweep the inbox for ${threadId}`, schedule: { type: "weekly", time: "09:00", weekdays: ["monday"] } },
    },
  });
  return { routines, create };
}

describe("a routine made in a chat keeps that chat's computer", () => {
  it("keeps the computer the person chose for the chat, and nothing for an Auto pick or an unpinned chat", async () => {
    const { routines, create } = chatCards({
      "bot-a/pinned": { surface: "vm", surfaceSource: "user" },
      "bot-a/auto": { surface: "cloud", surfaceSource: "auto" },
    });
    await create("pinned");
    await create("auto");
    await create("plain");
    const byThread = Object.fromEntries(routines.listRoutines().map((routine) => [routine.sourceThreadId, routine.computer]));
    expect(byThread).toEqual({ pinned: "vm", auto: undefined, plain: undefined });
  });

  it("keeps nothing in the chat of a bot on its team's computer, so the card still saves", async () => {
    const { routines, create } = chatCards({ "bot-a/pinned": { surface: "vm", surfaceSource: "user" } }, ["bot-a"]);
    await create("pinned");
    expect(routines.listRoutines()).toHaveLength(1);
    expect(routines.listRoutines()[0]).not.toHaveProperty("computer");
  });

  it("keeps nothing for a routine made for another bot, which works on its own setting", async () => {
    const { routines, create } = chatCards({ "bot-a/pinned": { surface: "local", surfaceSource: "user" } });
    await create("pinned", { botId: "bot-b", name: "Peer" });
    expect(routines.listRoutines()[0]).not.toHaveProperty("computer");
  });
});

describe("a routine's own computer", () => {
  it("is copied to each run, which starts its conversation pinned there", () => {
    const { routines } = manager();
    const routine = routines.create({ ...base, computer: "vm" });
    const run = routines.runNow(routine.id)!;
    expect(run.computer).toBe("vm");
    expect(runComputerPin(run)).toEqual({ surface: "vm", surfaceSource: "user" });
  });

  it("leaves a routine without one exactly as before: no pin on its runs", () => {
    const { routines } = manager();
    const routine = routines.create(base);
    expect(routine).not.toHaveProperty("computer");
    const run = routines.runNow(routine.id)!;
    expect(run.computer).toBeUndefined();
    expect(runComputerPin(run)).toBeUndefined();
  });

  it("survives an unrelated edit and a restart, changes on an edit, and clears on null", () => {
    const { options, routines } = manager();
    const routine = routines.create({ ...base, computer: "local" });
    expect(routines.update(routine.id, { prompt: "Sweep it twice" })?.computer).toBe("local");
    expect(new RoutineManager(options).listRoutines()[0]?.computer).toBe("local");
    expect(routines.update(routine.id, { computer: "browser" })?.computer).toBe("browser");
    expect(routines.update(routine.id, { computer: null })).not.toHaveProperty("computer");
    expect(new RoutineManager(options).listRoutines()[0]).not.toHaveProperty("computer");
  });

  it("refuses an unknown computer and is dropped when the routine runs in the cloud", () => {
    const { routines } = manager();
    // SAFETY: deliberately invalid to exercise the input check.
    expect(() => routines.create({ ...base, computer: "mainframe" as never })).toThrow("Choose a computer");
    expect(routines.create({ ...base, runOn: "cloud", computer: "vm" })).not.toHaveProperty("computer");
    const routine = routines.create({ ...base, computer: "vm" });
    expect(routines.update(routine.id, { runOn: "cloud" })).not.toHaveProperty("computer");
  });

  it("is refused for a bot on its team's computer, which every turn of it uses, but a cloud one and other edits still save", () => {
    const { routines } = manager(["bot-a"]);
    expect(() => routines.create({ ...base, computer: "vm" })).toThrow(TEAM_COMPUTER_REFUSAL);
    expect(() => routines.create({ ...base, computer: "local" })).toThrow(TEAM_COMPUTER_REFUSAL);
    expect(routines.create({ ...base, computer: "cloud" }).computer).toBe("cloud");
    const routine = routines.create(base);
    expect(() => routines.update(routine.id, { computer: "browser" })).toThrow(TEAM_COMPUTER_REFUSAL);
    expect(routines.update(routine.id, { prompt: "Sweep it twice" })?.prompt).toBe("Sweep it twice");
    expect(routines.create({ ...base, botId: "bot-b", computer: "vm" }).computer).toBe("vm");
  });

  it("still lets a routine saved before its bot joined a team computer be edited", () => {
    const team: string[] = [];
    const { routines } = manager(team);
    const routine = routines.create({ ...base, computer: "vm" });
    team.push("bot-a");
    expect(routines.update(routine.id, { prompt: "Sweep it twice" })?.computer).toBe("vm");
    expect(routines.update(routine.id, { computer: null })).not.toHaveProperty("computer");
  });

  it("refuses moving a routine with a kept computer to a bot on its team's computer, unless the move clears it", () => {
    const { routines } = manager(["bot-a"]);
    const routine = routines.create({ ...base, botId: "bot-b", computer: "vm" });
    expect(() => routines.update(routine.id, { botId: "bot-a" })).toThrow(TEAM_COMPUTER_REFUSAL);
    expect(routines.update(routine.id, { botId: "bot-a", computer: null })).not.toHaveProperty("computer");
  });

  it("loads a kept computer and drops one that is unknown or on a room goal", () => {
    const saved: Routine = { ...manager().routines.create(base), computer: "vm" };
    expect(loadRoutine(saved, START)?.computer).toBe("vm");
    // SAFETY: deliberately invalid persisted value.
    expect(loadRoutine({ ...saved, computer: "mainframe" as never }, START)).not.toHaveProperty("computer");
    expect(loadRoutine({ ...saved, target: "room-goal", groupId: "group-1" }, START)).not.toHaveProperty("computer");
    const run: RoutineRun = { ...routineRunDefinition(saved), id: "run-1", routineId: saved.id, scheduledFor: START, status: "running", manual: true, createdAt: START };
    expect(loadRun(run).computer).toBe("vm");
    // SAFETY: deliberately invalid persisted value.
    expect(loadRun({ ...run, computer: "mainframe" as never })).not.toHaveProperty("computer");
  });
});

describe("the start check of a run that keeps a computer", () => {
  type Bot = { id: string; computer: "local" | "vm" | "cloud" };
  const bots: Record<string, Bot> = { cloudy: { id: "cloudy", computer: "cloud" }, plain: { id: "plain", computer: "local" } };
  // Mirrors turnProvider: a cloud run or a cloud place (the kept computer first, else Works on) uses the bot's cloud computer.
  const owner = (run: { botId: string; computer?: "local" | "vm" | "cloud" | "browser"; runOn?: "maus" | "cloud"; target: "bot" }) => runCloudComputerOwner(run, {
    bot: (botId) => bots[botId] ?? null,
    provider: (bot, runOn, pinned) => runOn === "cloud" || (pinned ?? bot.computer) === "cloud" ? "box" : null,
    owner: (bot) => `owner-${bot.id}`,
  });

  it("never waits for the bot's cloud computer when the run keeps another computer", () => {
    expect(owner({ botId: "cloudy", computer: "vm", runOn: "maus", target: "bot" })).toBeNull();
    expect(owner({ botId: "cloudy", computer: "local", target: "bot" })).toBeNull();
  });

  it("checks a run that continues a conversation by that conversation's pin, not the routine's kept computer", () => {
    const pins: Record<string, "vm" | "cloud"> = { "on-vm": "vm", "on-cloud": "cloud" };
    const joined = (run: { botId: string; computer?: "local" | "vm" | "cloud"; target: "bot" }, threadId: string) => runCloudComputerOwner(run, {
      bot: (botId) => bots[botId] ?? null,
      provider: (bot, _runOn, pinned, thread) => (thread ? pins[thread] ?? bot.computer : pinned ?? bot.computer) === "cloud" ? "box" : null,
      owner: (bot) => `owner-${bot.id}`,
    }, threadId);
    expect(joined({ botId: "plain", computer: "cloud", target: "bot" }, "on-vm")).toBeNull();
    expect(joined({ botId: "cloudy", computer: "vm", target: "bot" }, "on-cloud")).toBe("owner-cloudy");
  });

  it("waits for it as before when the run keeps none or keeps the cloud computer", () => {
    expect(owner({ botId: "cloudy", runOn: "maus", target: "bot" })).toBe("owner-cloudy");
    expect(owner({ botId: "plain", computer: "cloud", target: "bot" })).toBe("owner-plain");
    expect(owner({ botId: "plain", target: "bot" })).toBeNull();
    expect(owner({ botId: "gone", target: "bot" })).toBeNull();
  });
});