Skip to content

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

8.9 KB
Raw Blame
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { expect, it } from "vitest";
import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
import { nextCronRuns } from "../shared/routine-schedule.ts";

it("takes cron through the real routine tools, applying the bot's own routine at once, preserving its zone and rejecting invalid API input", async () => {
  const fixture = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });
  const evidence: unknown[] = [{ fixture: fixture.info }];
  const planPath = join(fixture.info.dataDir, "room-plan.json");
  const providerEvidence = () => existsSync(`${planPath}.evidence.jsonl`)
    ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map(line => JSON.parse(line))
    : [];
  const api = async (method: string, path: string, body?: unknown, status = 200) => {
    const response = await fetch(`${fixture.info.url}${path}`, {
      method, headers: { "content-type": "application/json", origin: fixture.info.url },
      ...(body === undefined ? {} : { body: JSON.stringify(body) }),
    });
    const value = await response.json() as any;
    expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBe(status);
    if (method !== "GET") evidence.push({ method, path, body, status: response.status, result: value });
    return value;
  };
  const cli = (...args: string[]) => runControlOmb([...args, "--url", fixture.info.url]) as Promise<any>;
  try {
    expect((await cli("doctor")).ok).toBe(true);
    const { bot } = await cli("new-bot", "--name", "Cron fixture");
    const threadId = bot.activeTaskId;
    const messages = async () => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];
    const proposal = async (tool: string, args: unknown, text: string, expectError = false) => {
      const previousTurns = providerEvidence().length;
      writeFileSync(planPath, JSON.stringify({ [bot.id]: {
        expectSystemIncludes: ["a five-field cron with an explicit IANA timezone", "never daily AI date checks or an approximate weekly schedule", "configured computer (its VPS too)"],
        steps: [{ tool: "list_triggers", arguments: {} }, { tool, arguments: args, expectError }],
        reply: expectError ? "That invalid schedule was refused." : "The routine change is applied.",
      } }));
      await cli("send", "--bot", bot.id, "--task", threadId, "--text", text);
      await expect.poll(() => providerEvidence().length, { timeout: 20_000 }).toBe(previousTurns + 1);
      await cli("wait", "--bot", bot.id, "--task", threadId, "--timeout", "20");
      const turn = providerEvidence().at(-1);
      const toolResponse = turn.evidence.find((entry: any) => entry.step?.tool === tool).response;
      expect(toolResponse.error).toBeUndefined();
      expect(Boolean(toolResponse.result.isError)).toBe(expectError);
      evidence.push({ turn });
      return (await messages()).findLast(message => message.card?.routineRequest)?.card;
    };
    const applied = (card: any) => {
      expect(card).toMatchObject({ answered: "allow", autoApplied: true, options: [] });
      return { resultId: card.routineRequest.resultId as string };
    };
    const schedule = { type: "cron" as const, expression: "0 9 1 * *", timeZone: "America/New_York" };
    const create = await proposal("create_trigger", { when: "schedule",
      name: "Monthly report", instructions: "Summarize last month's fixture activity; no external services.", schedule, overlap: "queue", run_on_startup: true,
    }, "Schedule a report at 9am New York time on the first of each month, and also whenever the app starts.");
    expect(create.routineRequest).toMatchObject({ version: 1, operation: { action: "create", routine: { schedule } }, undo: { name: "Monthly report", schedule } });
    expect(create.subtitle).toContain("Next 3 runs (Eastern time)");
    expect(create.subtitle).toContain("Cron: 0 9 1 * *");
    const { resultId: routineId } = applied(create);
    const current = async () => (await api("GET", "/api/routines")).routines.find((routine: any) => routine.id === routineId);
    expect(await current()).toMatchObject({ schedule, enabled: true, runOn: "maus", overlap: "queue", runOnStartup: true });
    expect(create.subtitle).toContain("Queue one scheduled run");
    expect(create.subtitle).toContain("On startup: Also runs once each time OpenMausBot starts");
    expect((await current()).nextRunAt).toBe(nextCronRuns(schedule, create.routineRequest.createdAt, 1)[0]);

    const cardCount = (await messages()).filter(message => message.card?.routineRequest).length;
    await proposal("create_trigger", { when: "schedule",
      name: "Renamed monthly report", instructions: "Summarize last month's fixture activity; no external services.", schedule, overlap: "queue", run_on_startup: true,
    }, "Try scheduling the same work again under a different name.", true);
    const duplicateResponse = providerEvidence().at(-1).evidence.find((entry: any) => entry.step?.tool === "create_trigger").response;
    expect(duplicateResponse.result.content[0].text).toContain(routineId);
    expect(duplicateResponse.result.content[0].text).toContain("already exists");
    expect((await messages()).filter(message => message.card?.routineRequest)).toHaveLength(cardCount);
    expect((await api("GET", "/api/routines")).routines).toHaveLength(1);

    const lastDay = { ...schedule, expression: "0 9 L * *" };
    const update = await proposal("manage_trigger", {
      action: "update", trigger_id: routineId, changes: { schedule: lastDay, overlap: "skip", run_on_startup: false },
    }, "Change that report to the last day of each month at the same time and zone.");
    const listed = providerEvidence().at(-1).evidence.find((entry: any) => entry.step?.tool === "list_triggers").response.result.content[0].text;
    expect(listed).toContain('"type": "cron"');
    expect(listed).toContain('"timeZone": "America/New_York"');
    expect(listed).toContain('"overlap": "queue"');
    expect(listed).toContain('"runOnStartup": true');
    expect(listed).toContain('"failureStreak": 0');
    applied(update);
    expect(update.routineRequest.undo.before).toMatchObject({ schedule, overlap: "queue", runOnStartup: true });
    expect(update.subtitle).toContain("On startup: Runs only on its schedule");
    expect((await current()).schedule).toEqual(lastDay);
    expect((await current()).overlap).toBeUndefined();
    expect((await current()).runOnStartup).toBeUndefined();
    const pause = await proposal("manage_trigger", { action: "pause", trigger_id: routineId }, "Pause the monthly report.");
    applied(pause);
    expect(await current()).toMatchObject({ enabled: false, nextRunAt: null, schedule: lastDay });
    const resume = await proposal("manage_trigger", { action: "resume", trigger_id: routineId }, "Resume the monthly report.");
    expect(resume.subtitle).toContain("Next 3 runs (Eastern time)");
    applied(resume);
    expect(await current()).toMatchObject({ enabled: true, schedule: lastDay });

    await proposal("create_trigger", { when: "schedule", name: "Impossible date", instructions: "Must not run.", schedule: { ...schedule, expression: "0 9 31 2 *" } }, "Try an invalid calendar rule.", true);
    await proposal("create_trigger", { when: "schedule",
      name: "Explicit Boat", instructions: "Run on the Boat-hosted agent.", schedule, run_on: "box",
    }, "Try the separate Boat runner without a Boat account.", true);
    const boatResponse = providerEvidence().at(-1).evidence.find((entry: any) => entry.step?.tool === "create_trigger").response;
    expect(boatResponse.result.content[0].text).toContain('run_on="maus"');
    expect(boatResponse.result.content[0].text).toContain("self-hosted VPS");
    const before = await current();
    for (const invalid of [
      { type: "cron", expression: "0 9 1 * *" },
      { ...schedule, timeZone: "Not/AZone" },
      { ...schedule, expression: "0 0 9 1 * *" },
      { ...schedule, expression: "0 9 31 2 *" },
    ]) {
      await api("POST", "/api/routines", { botId: bot.id, name: "Invalid", prompt: "Must not persist", schedule: invalid }, 400);
      await api("PATCH", `/api/routines/${routineId}`, { schedule: invalid }, 400);
    }
    expect(await current()).toEqual(before);
    expect((await api("GET", "/api/routines")).routines).toHaveLength(1);
    const persisted = JSON.parse(readFileSync(join(fixture.info.dataDir, "routines.json"), "utf8"));
    expect(persisted.routines.find((routine: any) => routine.id === routineId).schedule).toEqual(lastDay);
    evidence.push({ final: await api("GET", "/api/routines"), persisted });
  } finally {
    const evidencePath = `${fixture.info.logPath}.cron.json`;
    writeFileSync(evidencePath, JSON.stringify(evidence, null, 2));
    console.info(JSON.stringify({ logPath: fixture.info.logPath, evidencePath }));
    await fixture.close();
  }
}, 90_000);