Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
// @vitest-environment happy-dom
// The engines' usage limits on screen: the warning with "Move to after reset", the usage bars in the model button with
// their card, the stopped turn's Continue button, and the calendar's reset marker that a bot or an automation is dropped on.
import { createElement } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { EngineLimit } from "../../shared/limit-reset";
import { failedTurnTool } from "../../shared/failed-turn";
import type { Routine } from "@/lib/routines";
import type { Bot, InstanceInfo } from "@/state/store";
const fixture = vi.hoisted(() => ({
state: {} as Record<string, unknown>,
dispatch: vi.fn(),
api: vi.fn(async (..._args: unknown[]) => ({}) as unknown),
}));
vi.mock("@/state/store", async (importOriginal) => ({
...await importOriginal<typeof import("@/state/store")>(),
useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch, refreshInstances: vi.fn(), refreshModels: vi.fn() }),
api: (...args: unknown[]) => fixture.api(...args),
}));
vi.mock("./DesktopCapabilities", async (importOriginal) => ({
...await importOriginal<typeof import("./DesktopCapabilities")>(),
useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "darwin" }, localComputer: { available: true } }, ready: true }),
useCaptionChrome: () => ({}),
}));
vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => null }));
vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
const { setLocale } = await import("@/lib/i18n");
const limits = await import("@/lib/limit-resets");
const { automationSentence, isDone, statusLine } = await import("@/lib/automations");
const { LimitWarnings } = await import("./automations/LimitWarnings");
const { UsageAlert, UsageBars, UsageRows } = await import("./EngineUsage");
const { FailedTurnRow } = await import("./ChatView");
const { CalendarGrid } = await import("./RoutineCalendarPage");
const NOW = new Date(2026, 9, 19, 10, 0, 0).getTime();
const RESET = new Date(2026, 9, 19, 15, 40, 0).getTime();
const MONDAY = new Date(2026, 9, 26, 9, 0, 0).getTime();
const HOVER_MS = 300;
const HOUR = 3_600_000;
const claude = (used: number, blocked = false): EngineLimit => ({ engine: "claude", name: "Claude", driver: "claude", window: "5-hour", usedPercent: used, resetsAt: RESET, blocked });
const bot = { id: "scout", name: "Scout", hidden: false, threadId: "t-main", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" }, tasks: [] } as unknown as Bot;
const routine = (id: string, nextRunAt: number, extra: Partial<Routine> = {}): Routine => ({
id, name: id, prompt: "Finish the report.", target: "bot", botId: "scout", runOn: "maus", enabled: true,
schedule: { type: "daily", time: "11:00", weekdays: [0, 1, 2, 3, 4, 5, 6] }, durationMinutes: 30, nextRunAt, createdAt: 0, updatedAt: 0, ...extra,
});
let root: Root | null = null;
function mount(element: ReturnType<typeof createElement>) {
const container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
flushSync(() => root!.render(element));
return container;
}
const button = (container: HTMLElement, label: string) => {
const found = [...container.querySelectorAll("button")].find((candidate) => candidate.textContent?.trim() === label);
if (!found) throw new Error(`no ${label} button in ${container.innerHTML}`);
return found;
};
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
/** What the app already knows and what the next poll answers. */
const serve = (engines: EngineLimit[]) => {
fixture.api.mockImplementation(async () => ({ checkedAt: NOW, engines }));
limits.rememberLimits({ checkedAt: NOW, engines });
};
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const hover = (target: Element, pointerType: string) => flushSync(() => target.dispatchEvent(new PointerEvent("pointerover", { bubbles: true, pointerType })));
const leave = (target: Element) => flushSync(() => target.dispatchEvent(new PointerEvent("pointerout", { bubbles: true, pointerType: "mouse" })));
beforeEach(() => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(NOW);
setLocale("en");
fixture.dispatch.mockReset();
fixture.api.mockReset();
fixture.api.mockImplementation(async () => ({ checkedAt: NOW, engines: [claude(92)] }));
fixture.state = { bots: [bot], routines: [], instances: [] as InstanceInfo[], config: {}, groups: [] };
limits.rememberLimits({ checkedAt: NOW, engines: [claude(92)] });
});
afterEach(() => {
root?.unmount();
root = null;
document.body.innerHTML = "";
vi.useRealTimers();
});
describe("the words", () => {
it("say how full an engine is and when it resets", () => {
expect(limits.limitLine(claude(92), NOW)).toBe("Claude: 92% used · resets 3:40 PM");
expect(limits.limitLine(claude(100, true), NOW)).toBe("Claude: at its limit · resets 3:40 PM");
expect(limits.nearLimitEngines([claude(89), { ...claude(90), engine: "codex" }]).map((limit) => limit.engine)).toEqual(["codex"]);
});
it("read a limit-reset automation as a sentence, and say when its time is not known", () => {
const automation = { kind: "schedule" as const, name: "Report", instructions: "Finish the report.", schedule: { type: "limit_reset" as const, engine: "claude", repeat: "once" as const, at: null } };
expect(automationSentence(automation, "Scout")).toBe("When your Claude limit resets, Scout finishes the report");
expect(automationSentence({ ...automation, schedule: { ...automation.schedule, repeat: "every_reset" } }, "Scout")).toBe("Each time your Claude limit resets, Scout finishes the report");
expect(statusLine({ ...automation, id: "r", botId: "scout", enabled: true, nextRunAt: null, runs: [] }, NOW)).toContain("runs when the limit resets (time not known yet)");
expect(isDone({ schedule: { ...automation.schedule, at: NOW - 1 } }, NOW)).toBe(true);
expect(isDone({ schedule: { ...automation.schedule, at: null } }, NOW)).toBe(false);
});
it("find the automations due before a reset on a bot that uses that engine", () => {
const due = limits.dueBeforeReset([
routine("before", NOW + HOUR), routine("after", RESET + 2 * 60_000), routine("paused", NOW + HOUR, { enabled: false }),
routine("other-bot", NOW + HOUR, { botId: "codex-bot" }), routine("limit", NOW + HOUR, { schedule: { type: "limit_reset", engine: "claude", repeat: "once", at: null } }),
], (botId) => botId === "scout" ? "claude" : "codex", claude(92), NOW);
expect(due.map((candidate) => candidate.id)).toEqual(["before"]);
});
it("name Antigravity's windows as Gemini's, and keep them out of the automations, which wait for the engine's own reset", () => {
const gemini: EngineLimit = { ...claude(95), engine: "antigravity", name: "Antigravity", driver: "antigravity", meter: "Gemini" };
expect(limits.limitLine(gemini, NOW)).toBe("Antigravity (Gemini): 95% used · resets 3:40 PM");
expect(limits.nearLimitEngines([claude(92), gemini]).map((limit) => limit.engine)).toEqual(["claude"]);
expect(limits.resetMarkers([claude(92), gemini], NOW, NOW + 24 * HOUR, NOW).map((marker) => marker.engine)).toEqual(["claude"]);
});
it("put each known reset in the calendar's range", () => {
expect(limits.resetMarkers([claude(92), { ...claude(10), engine: "codex", name: "Codex", resetsAt: null }], NOW, NOW + 24 * HOUR, NOW))
.toEqual([{ engine: "claude", name: "Claude", at: RESET }]);
expect(limits.resetMarkers([claude(92)], RESET + 1, RESET + HOUR, NOW)).toEqual([]);
});
});
describe("the Automations page warning", () => {
it("shows the engine near its limit and moves just the next run of what is due before the reset", async () => {
fixture.state = { ...fixture.state, routines: [routine("brief", NOW + HOUR)] };
const moved = routine("brief", RESET + 60_000);
fixture.api.mockImplementation(async (path: unknown) => String(path).startsWith("/api/limit-resets/after-reset") ? { routine: moved } : { checkedAt: NOW, engines: [claude(92)] });
const container = mount(createElement(LimitWarnings));
const warning = container.querySelector('[data-limit-warning="claude"]')!;
expect(warning.textContent).toContain("Claude: 92% used · resets 3:40 PM");
expect(warning.textContent).toContain("1 automation runs before then");
flushSync(() => button(container, "Move to after reset").click());
await settle();
expect(fixture.api).toHaveBeenCalledWith("/api/limit-resets/after-reset", { method: "POST", body: JSON.stringify({ routineId: "brief", engine: "claude" }) });
expect(fixture.dispatch).toHaveBeenCalledWith({ type: "routinePatched", routine: moved });
});
it("stays away while every engine has room", () => {
limits.rememberLimits({ checkedAt: NOW, engines: [claude(40)] });
fixture.api.mockImplementation(async () => ({ checkedAt: NOW, engines: [claude(40)] }));
expect(mount(createElement(LimitWarnings)).innerHTML).toBe("");
});
});
describe("the bars", () => {
const windows = (fiveHour: number, weekly: number, extra: Partial<EngineLimit> = {}): EngineLimit => ({
...claude(Math.max(fiveHour, weekly)), window: fiveHour >= weekly ? "5-hour" : "weekly",
windows: [{ window: "5-hour", usedPercent: fiveHour, resetsAt: RESET }, { window: "weekly", usedPercent: weekly, resetsAt: MONDAY }], ...extra,
});
it("fill for the usage left, with one bar exactly while near the limit and none at it", () => {
const bars = (used: number, blocked = false) => limits.usageBars({ usedPercent: used, blocked });
expect([0, 29, 30, 31, 59, 60, 61, 89, 89.9, 90, 99, 100].map((used) => bars(used))).toEqual([4, 4, 3, 3, 3, 2, 2, 2, 2, 1, 1, 0]);
expect(bars(40, true)).toBe(0);
for (const used of [0, 45, 89, 90, 95, 100]) expect(bars(used) === 1).toBe(limits.nearLimit({ usedPercent: used, blocked: false }) && used < 100);
expect([limits.usageTone({ usedPercent: 89, blocked: false }), limits.usageTone({ usedPercent: 90, blocked: false }), limits.usageTone({ usedPercent: 10, blocked: true })])
.toEqual(["fine", "near", "out"]);
});
it("show nothing for an engine that reports no usage", () => {
expect(limits.reportsUsage({ ...claude(0), usedPercent: null })).toBe(false);
expect(limits.reportsUsage({ ...claude(0), usedPercent: null, blocked: true })).toBe(true);
serve([{ ...claude(0), engine: "codex", name: "Codex", usedPercent: null, window: null, resetsAt: null }]);
expect(mount(createElement(UsageBars, { engine: "codex" })).innerHTML).toBe("");
expect(mount(createElement(UsageBars, { engine: "openai" })).innerHTML).toBe("");
});
it("list each window, or the deciding one alone from a server that sends no list", () => {
expect(limits.usageRows(windows(38, 80))).toEqual([
{ window: "5-hour", left: 62, resetsAt: RESET, tone: "fine" }, { window: "weekly", left: 20, resetsAt: MONDAY, tone: "fine" },
]);
expect(limits.usageRows(claude(92))).toEqual([{ window: "5-hour", left: 8, resetsAt: RESET, tone: "near" }]);
expect(limits.usageRows({ ...claude(0), usedPercent: null })).toEqual([]);
});
it("put a blocked engine's deciding window at its limit until the engine's own reset", () => {
const refused = windows(70, 20, { blocked: true, usedPercent: 100, resetsAt: RESET + HOUR });
expect(limits.usageRows(refused)).toEqual([
{ window: "5-hour", left: 0, resetsAt: RESET + HOUR, tone: "out" }, { window: "weekly", left: 80, resetsAt: MONDAY, tone: "fine" },
]);
expect(limits.usageRows({ ...claude(100, true), window: null, windows: [] })).toEqual([{ window: "other", left: 0, resetsAt: RESET, tone: "out" }]);
});
it("say the deciding window's use and reset to a screen reader, and draw a struck-through empty set at the limit", () => {
serve([windows(38, 10)]);
const fine = mount(createElement(UsageBars, { engine: "claude" }));
expect(fine.querySelector("[data-usage-bars]")?.getAttribute("data-usage-bars")).toBe("fine");
expect(fine.querySelector("[data-usage-glyph]")?.getAttribute("data-usage-glyph")).toBe("3");
expect(fine.querySelector("[data-usage-warn]")).toBeNull();
expect(fine.querySelector(".sr-only")?.textContent).toBe("Claude: 38% used, resets 3:40 PM");
expect(fine.querySelector("svg path")).toBeNull();
root!.unmount();
serve([claude(100, true)]);
const out = mount(createElement(UsageBars, { engine: "claude" }));
expect(out.querySelector("[data-usage-glyph]")?.getAttribute("data-usage-glyph")).toBe("0");
expect(out.querySelector("[data-usage-warn]")).not.toBeNull();
expect(out.querySelector("svg path")).not.toBeNull();
expect(out.querySelector(".sr-only")?.textContent).toBe("Claude: at its limit, resets 3:40 PM");
});
it("keep the bars and each window's track grey with room left, orange near the limit and red at it", () => {
const glyph = (limit: EngineLimit) => {
serve([limit]);
const ink = mount(createElement(UsageBars, { engine: "claude" })).querySelector("[data-usage-glyph]")?.getAttribute("class");
root!.unmount();
return ink;
};
expect([glyph(windows(38, 10)), glyph(claude(92)), glyph(claude(100, true))]).toEqual([
expect.stringContaining("text-ink-tertiary"), expect.stringContaining("text-warning"), expect.stringContaining("text-danger"),
]);
const tracks = (limit: EngineLimit) => {
const fills = [...mount(createElement(UsageRows, { limit })).querySelectorAll("[data-usage-track]")].map((track) => track.className.match(/bg-[\w-]+/)?.[0]);
root!.unmount();
return fills;
};
expect(tracks(windows(92, 20, { blocked: true, usedPercent: 100 }))).toEqual(["bg-danger", "bg-ink-tertiary"]);
expect(tracks(windows(95, 20))).toEqual(["bg-warning", "bg-ink-tertiary"]);
});
it("open every window in a card on a mouse hover, never on a touch, and keep the card's clicks from the model button", async () => {
serve([windows(38, 80)]);
const opened = vi.fn();
const container = mount(createElement("button", { type: "button", onClick: opened }, createElement(UsageBars, { engine: "claude" })));
const spot = container.querySelector("[data-usage-bars]")!;
hover(spot, "touch");
await wait(HOVER_MS);
expect(document.querySelector("[data-usage-card]")).toBeNull();
hover(spot, "mouse");
await wait(HOVER_MS);
const card = document.querySelector<HTMLElement>("[data-usage-card]")!;
expect(card.querySelector("[data-usage-rows] > div")?.textContent).toBe("Claude usagechecked just now");
expect([...card.querySelectorAll("[data-usage-row]")].map((row) => row.textContent)).toEqual(["5-hour62% left · resets 3:40 PM", "Weekly20% left · resets Mon 9:00 AM"]);
expect([...card.querySelectorAll<HTMLElement>("[data-usage-track]")].map((track) => track.style.width)).toEqual(["38%", "80%"]);
expect(card.textContent).not.toContain("Check again");
leave(spot);
await wait(HOVER_MS);
expect(document.querySelector("[data-usage-card]")).toBeNull();
flushSync(() => serve([windows(100, 80, { blocked: true })]));
hover(spot, "mouse");
await wait(HOVER_MS);
const blocked = document.querySelector<HTMLElement>("[data-usage-card]")!;
expect(blocked.querySelector('[data-usage-row="5-hour"]')?.textContent).toBe("5-hourAt its limit · resets 3:40 PM");
expect(blocked.querySelector<HTMLElement>('[data-usage-row="5-hour"] [data-usage-track]')?.style.width).toBe("100%");
expect(blocked.textContent).toContain("Clears by itself once Claude replies again.");
fixture.api.mockClear();
flushSync(() => blocked.querySelector<HTMLButtonElement>("[data-usage-check]")!.click());
await settle();
expect(fixture.api).toHaveBeenCalledWith("/api/limit-resets?refresh=1");
expect(blocked.querySelector("[data-usage-release]"), "a full window: Try again now could not unblock it").toBeNull();
leave(spot);
await wait(HOVER_MS);
flushSync(() => serve([windows(100, 80, { blocked: true, held: true })]));
hover(spot, "mouse");
await wait(HOVER_MS);
const held = document.querySelector<HTMLElement>("[data-usage-card]")!;
fixture.api.mockClear();
fixture.api.mockImplementation(async () => ({ checkedAt: NOW, engines: [windows(100, 80)] }));
// the check above keeps both buttons busy until its read settles
await vi.waitFor(() => expect(held.querySelector<HTMLButtonElement>("[data-usage-release]")!.disabled).toBe(false));
flushSync(() => held.querySelector<HTMLButtonElement>("[data-usage-release]")!.click());
await settle();
expect(fixture.api, "Try again now ends the hold (emails 1a1c2500, 1a1c136d)").toHaveBeenCalledWith("/api/limit-resets/release", { method: "POST", body: JSON.stringify({ engine: "claude" }) });
expect(opened).not.toHaveBeenCalled();
});
it("say how long ago the usage was read", () => {
limits.rememberLimits({ checkedAt: NOW - 3 * 60_000, engines: [windows(38, 80)] });
expect(mount(createElement(UsageRows, { limit: windows(38, 80) })).querySelector("[data-usage-checked]")?.textContent).toBe("checked 3 min ago");
});
it("say when the usage shown was read, when the latest read failed and kept the one before", () => {
limits.rememberLimits({ checkedAt: NOW, engines: [{ ...windows(38, 80), checkedAt: NOW - 12 * 60_000 }] });
expect(mount(createElement(UsageRows, { limit: { ...windows(38, 80), checkedAt: NOW - 12 * 60_000 } })).querySelector("[data-usage-checked]")?.textContent).toBe("checked 12 min ago");
});
it("read limits on their own as a background poll, so a sleeping Cloud home stays asleep", async () => {
fixture.api.mockClear();
mount(createElement(UsageBars, { engine: "claude" }));
await settle();
expect(fixture.api).toHaveBeenCalledWith("/api/limit-resets", { background: true });
expect(fixture.api).not.toHaveBeenCalledWith("/api/limit-resets");
});
it("stand alone in a phone's header only while near or at the limit, and open the bot's model there", () => {
const alert = mount(createElement(UsageAlert, { engine: "claude" })).querySelector<HTMLButtonElement>("[data-usage-alert]")!;
expect(alert.getAttribute("aria-label")).toBe("Claude: 92% used, resets 3:40 PM");
flushSync(() => alert.click());
expect(fixture.dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "toggleSettings", open: true, section: "model" }));
root!.unmount();
serve([claude(60)]);
expect(mount(createElement(UsageAlert, { engine: "claude" })).innerHTML).toBe("");
});
});
describe("the chat", () => {
it("offers Continue on a turn its limit stopped, which sets up the automation in this conversation", async () => {
const created = routine("continue", RESET + 60_000, { schedule: { type: "limit_reset", engine: "claude", repeat: "once", at: RESET + 60_000 } });
fixture.api.mockImplementation(async (path: unknown) => String(path) === "/api/limit-resets/continue" ? { routine: created } : { checkedAt: NOW, engines: [claude(100, true)] });
const tool = failedTurnTool("This Claude account has reached its 5-hour limit, which resets Oct 19, 3:40 PM (UTC).", { limitResetsAt: RESET });
const container = mount(createElement(FailedTurnRow, { tool, engine: undefined, botId: "scout", threadId: "t-1", onRetry: vi.fn() }));
expect([...container.querySelectorAll("button")].map((candidate) => candidate.textContent?.trim())).toEqual(["Continue at 3:40 PM when your limit resets"]);
flushSync(() => button(container, "Continue at 3:40 PM when your limit resets").click());
await settle();
expect(fixture.api).toHaveBeenCalledWith("/api/limit-resets/continue", { method: "POST", body: JSON.stringify({ botId: "scout", threadId: "t-1" }) });
expect(fixture.dispatch).toHaveBeenCalledWith({ type: "routinePatched", routine: created });
// The button goes once React renders the update its answer set, which a busy runner can schedule after any one tick.
await vi.waitFor(() => expect(container.textContent).not.toContain("Continue at"));
});
it("offers Retry as before once the reset has passed, or when the engine named no reset", () => {
const passed = mount(createElement(FailedTurnRow, { tool: failedTurnTool("limit", { limitResetsAt: NOW - 1 }), engine: undefined, botId: "scout", threadId: "t-1", onRetry: vi.fn() }));
expect(passed.textContent).toContain("Retry");
expect(passed.textContent).not.toContain("Continue at");
});
});
describe("the calendar", () => {
const marker = { engine: "claude", name: "Claude", at: RESET };
const grid = (onDropOnReset = vi.fn(), onCreate = vi.fn()) => mount(createElement(CalendarGrid, {
anchor: new Date(2026, 9, 19).getTime(), days: 1, items: [], bots: [bot], groups: [], markers: [marker],
onOpen: vi.fn(), onCreate, onMove: vi.fn(), onResize: vi.fn(), onDropOnReset,
}));
const drop = (target: Element, type: string, value: string) => {
const transfer = { types: [type], getData: (asked: string) => asked === type ? value : "", dropEffect: "none" };
for (const name of ["dragover", "drop"]) {
const event = new Event(name, { bubbles: true, cancelable: true });
Object.defineProperty(event, "dataTransfer", { value: transfer });
flushSync(() => target.dispatchEvent(event));
}
};
it("draws each engine's next reset as a labelled marker", () => {
const container = grid();
const shown = container.querySelector('[data-limit-marker="claude"]')!;
expect(shown.textContent).toBe("Claude resets 3:40 PM");
expect(shown.getAttribute("title")).toBe("Drop a bot or an automation here to run it when Claude's limit resets");
});
it("turns a bot or an automation dropped on the marker into a limit-reset automation, not a fixed time", () => {
const onDropOnReset = vi.fn();
const onCreate = vi.fn();
const container = grid(onDropOnReset, onCreate);
const shown = container.querySelector('[data-limit-marker="claude"]')!;
drop(shown, "application/x-openmaus-bot", "scout");
expect(onDropOnReset).toHaveBeenLastCalledWith({ botId: "scout" }, marker);
drop(shown, "application/x-openmaus-calendar-event", JSON.stringify({ kind: "routine", id: "brief", at: NOW + HOUR }));
expect(onDropOnReset).toHaveBeenLastCalledWith({ event: { kind: "routine", id: "brief", at: NOW + HOUR } }, marker);
expect(onCreate).not.toHaveBeenCalled();
});
});