Skip to content

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

2.4 KB
Raw Blame
import { afterEach, describe, expect, it, vi } from "vitest";
import { ComputerIdleTimer } from "./computer-idle.ts";
import { perBotLocalVmTarget } from "./container-computer.ts";
import { stopIdleLocalVm } from "./local-vm-idle-stop.ts";

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

describe("stopping an idle private desktop", () => {
  it("keeps one bot's desktop running and resumes its idle timer after turning the setting off", async () => {
    vi.useFakeTimers();
    const first = perBotLocalVmTarget("coordinator");
    const second = perBotLocalVmTarget("worker");
    const preferences = new Map([[first.botId, true], [second.botId, false]]);
    const stopped: string[] = [];
    const timer = (target: typeof first) => {
      const keepRunning = () => preferences.get(target.botId) === true;
      return new ComputerIdleTimer(1_000, keepRunning, () => stopIdleLocalVm({
        keepRunning,
        status: async () => ({ container: "running", managed: true }),
        stop: async () => { stopped.push(target.botId!); return {}; },
        record: () => {},
      }));
    };
    const coordinator = timer(first), worker = timer(second);
    coordinator.touch(); worker.touch();
    await vi.advanceTimersByTimeAsync(2_000);
    expect(stopped).toEqual(["worker"]);
    preferences.set(first.botId, false);
    await vi.advanceTimersByTimeAsync(1_100);
    expect(stopped).toEqual(["worker", "coordinator"]);
    coordinator.cancel(); worker.cancel();
  });

  it("checks the bot's current preference after awaiting desktop status", async () => {
    let keepRunning = false;
    let finishStatus!: (status: { container: string; managed: boolean }) => void;
    const status = new Promise<{ container: string; managed: boolean }>((resolve) => { finishStatus = resolve; });
    const stop = vi.fn(async () => ({ stopped_at: "now" }));
    const record = vi.fn();
    const pending = stopIdleLocalVm({ keepRunning: () => keepRunning, status: () => status, stop, record });
    keepRunning = true;
    finishStatus({ container: "running", managed: true });
    expect(await pending).toBe("busy");
    expect(stop).not.toHaveBeenCalled();
    keepRunning = false;
    await stopIdleLocalVm({ keepRunning: () => keepRunning, status: async () => ({ container: "running", managed: true }), stop, record });
    expect(stop).toHaveBeenCalledOnce();
    expect(record).toHaveBeenCalledWith("now");
  });
});