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
import { act, createElement, type ReactElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const server = vi.hoisted(() => ({ calls: [] as Array<{ path: string; method: string; body?: unknown }>, view: null as null | { rows: Array<{ id: string; tab: string; kind?: string; unread?: boolean }> } }));
vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
vi.mock("../../state/api", () => ({
api: vi.fn(async (path: string, init?: RequestInit) => {
server.calls.push({ path, method: init?.method ?? "GET", ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}) });
const done = /^\/api\/inbox\/([\w-]+)\/done$/.exec(path);
if (done && server.view) server.view = { ...server.view, rows: server.view.rows.map((row) => (row.id === done[1] ? { ...row, tab: "done", unread: false } : row)) };
if (path === "/api/inbox/read-all" && server.view) server.view = { ...server.view, rows: server.view.rows.map((row) => (row.unread && row.kind === "result"
? { ...row, unread: false, tab: "done" }
: { ...row, unread: false })) };
return server.view;
}),
}));
import { initialState, StoreContext, type AppState, type Bot } from "@/state/store";
import { BOT_BUTTON, botButtonTone } from "@/lib/bot-button";
import { closeInbox, currentInbox, currentInboxPanel, inboxVersion, openInbox, setInboxView, useInboxLoader } from "@/state/inbox";
import { approvalRow, INBOX_NOW, inboxView, messageRow, questionRow, reportRow, settledRow } from "@/testing/inbox-fixture";
import type { InboxRow, InboxView } from "../../../shared/inbox";
import { InboxCardSlot } from "./InboxCard";
import { InboxPanel } from "./InboxPanel";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
let root: Root;
const dispatch = vi.fn();
const mount = (child: ReactElement, bots: Bot[] = []) => act(async () => {
root.render(createElement(StoreContext.Provider,
{ value: { state: { ...initialState, bots } as AppState, dispatch, flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn() } as never }, child));
});
const settle = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
const click = (selector: string) => act(async () => { document.querySelector<HTMLElement>(selector)!.click(); });
const shown = (view: InboxView) => { server.view = view; setInboxView(view); };
beforeEach(() => {
root = createRoot(document.body.appendChild(document.createElement("div")));
server.calls.length = 0;
dispatch.mockClear();
shown(inboxView());
});
afterEach(() => {
act(() => root.unmount());
closeInbox();
setInboxView(null);
document.body.innerHTML = "";
vi.unstubAllGlobals();
});
describe("the inbox panel", () => {
it("is one list, newest first, with a dot on what waits on the person and no tabs, and reads one line in full", async () => {
openInbox();
await mount(createElement(InboxPanel));
expect(document.querySelector("[role=tablist], [data-inbox-tab]")).toBeNull();
const listed = () => [...document.querySelectorAll<HTMLElement>("[data-inbox-row]")].map((row) => row.dataset.inboxRow);
expect(listed()).toEqual([approvalRow.id, questionRow.id, messageRow.id, reportRow.id]);
expect(listed(), "a settled line is not listed again").not.toContain(settledRow.id);
expect([...document.querySelectorAll<HTMLElement>("[data-inbox-row] [data-inbox-waits]")].map((dot) => dot.closest<HTMLElement>("[data-inbox-row]")!.dataset.inboxRow)).toEqual([approvalRow.id, questionRow.id]);
expect(document.querySelector(`[data-inbox-row="${approvalRow.id}"]`)!.hasAttribute("data-unread")).toBe(true);
await click(`[data-inbox-row="${messageRow.id}"] button`);
expect(document.querySelector(`[data-inbox-reading="${messageRow.id}"]`)?.textContent).toContain("The launch moved to Friday.");
expect(server.calls, "it is read after a moment on screen, not at once").not.toContainEqual({ path: `/api/inbox/${messageRow.id}/read`, method: "POST" });
expect(document.querySelector("textarea"), "a message that waits on an answer takes a reply").not.toBeNull();
await click('[aria-label="Back to the list"]');
expect(listed()).toEqual([approvalRow.id, questionRow.id, messageRow.id, reportRow.id]);
});
it("answers an ask from its row through the copy's own card, as the chat's buttons do, and marks news done", async () => {
openInbox();
await mount(createElement(InboxPanel));
await click(`[data-inbox-row="${approvalRow.id}"] [data-inbox-action="allow"]`);
expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "inbox", requestId: "req-approval", behavior: "allow" }));
await click(`[data-inbox-row="${questionRow.id}"] [data-inbox-action="close"]`);
expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "inbox", requestId: "req-question", behavior: "answer" }));
await click(`[data-inbox-row="${reportRow.id}"] [data-inbox-action="done"]`);
expect(server.calls).toContainEqual({ path: `/api/inbox/${reportRow.id}/done`, method: "POST" });
expect(document.querySelector(`[data-inbox-row="${reportRow.id}"]`), "it leaves the list at once").toBeNull();
});
it("marks every unread line read from one control that only shows while something is unread, and answers no ask", async () => {
openInbox();
await mount(createElement(InboxPanel));
const rowIds = () => [...document.querySelectorAll<HTMLElement>("[data-inbox-row]")].map((row) => row.dataset.inboxRow);
const unreadIds = () => [...document.querySelectorAll<HTMLElement>("[data-inbox-row][data-unread]")].map((row) => row.dataset.inboxRow);
expect(unreadIds()).toEqual([approvalRow.id, messageRow.id, reportRow.id]);
expect(document.querySelector("[data-inbox-mark-all]")!.textContent).toBe("Mark all as read");
await click("[data-inbox-mark-all]");
expect(server.calls).toContainEqual({ path: "/api/inbox/read-all", method: "POST" });
expect(unreadIds()).toEqual([]);
expect(rowIds(), "the finished work leaves the list, the rest stays").toEqual([approvalRow.id, questionRow.id, messageRow.id]);
expect(document.querySelector(`[data-inbox-row="${approvalRow.id}"] [data-inbox-action="allow"]`), "the ask still waits on its answer").not.toBeNull();
expect(dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest" }));
expect(server.calls.filter((call) => /\/(done)$/.test(call.path))).toEqual([]);
expect(currentInbox()!.rows.map((row) => [row.id, row.tab])).toEqual(server.view!.rows.map((row) => [row.id, row.tab]));
expect(document.querySelector("[data-inbox-mark-all]"), "nothing is unread").toBeNull();
});
it("keeps the control out of an inbox with nothing unread", async () => {
shown(inboxView([{ ...approvalRow, unread: false }, { ...messageRow, unread: false }]));
openInbox();
await mount(createElement(InboxPanel));
expect(document.querySelector("[data-inbox-row]")).not.toBeNull();
expect(document.querySelector("[data-inbox-mark-all]")).toBeNull();
});
it("opens the conversation a finished notice came from when the person clicks it", async () => {
const notice: InboxRow = { ...reportRow, id: "line-notice", origin: { botId: "reporter", threadId: "rep-daily", title: "Daily digest", messageId: "m-report" } };
shown(inboxView([notice]));
openInbox();
await mount(createElement(InboxPanel), [{ id: "reporter", name: "Reporter", color: "orange" } as Bot]);
await click(`[data-inbox-row="${notice.id}"] button`);
expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "revealThread", threadId: "rep-daily" }));
expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "focusMessage", threadId: "rep-daily", messageId: "m-report" }));
expect(document.querySelector(`[data-inbox-reading="${notice.id}"]`), "it is not read in the panel").toBeNull();
});
it("keeps what it took out of the list where the person can find it again", async () => {
shown(inboxView([approvalRow, { ...reportRow, tab: "done" }]));
openInbox();
await mount(createElement(InboxPanel));
const listed = () => [...document.querySelectorAll<HTMLElement>("[data-inbox-row]")].map((row) => row.dataset.inboxRow);
expect(listed(), "a settled line is not listed again").toEqual([approvalRow.id]);
await click("[data-inbox-done-toggle]");
expect(listed()).toEqual([approvalRow.id, reportRow.id]);
});
it("is a sheet at phone width", async () => {
vi.stubGlobal("matchMedia", (query: string) => ({ matches: query.includes("max-width"), addEventListener() {}, removeEventListener() {} }));
openInbox();
await mount(createElement(InboxPanel));
expect(document.querySelector('[data-inbox-panel="sheet"]')).not.toBeNull();
expect(document.querySelector('[data-inbox-panel="side"]')).toBeNull();
});
it("shows a pinned conversation once, and counts none of its finished work", async () => {
const reporter = {
id: "reporter", name: "Reporter", threadId: "rep-main", tasks: [
{ threadId: "rep-daily", title: "Daily digest", createdAt: 0, updatedAt: INBOX_NOW, pinned: true, unread: true },
{ threadId: "rep-old", title: "Older digest", createdAt: 0, updatedAt: INBOX_NOW - 60_000, pinned: true },
],
} as unknown as Bot;
shown(inboxView([{ ...reportRow, unread: true }]));
openInbox();
await mount(createElement(InboxPanel), [reporter]);
expect([...document.querySelectorAll("[data-pinned-title]")].map((el) => el.textContent)).toEqual(["Daily digest", "Older digest"]);
const active = [...document.querySelectorAll("[data-inbox-active] button")].map((button) => button.textContent).join(" ");
expect(active, "the pinned section already shows it").not.toContain("Daily digest");
const finished = [...document.querySelectorAll("[data-inbox-finished] button")].map((button) => button.textContent).join(" ");
expect(finished).not.toContain("Older digest");
expect(document.querySelector("[data-inbox-tab-count]"), "finished work is Activity, which has no number").toBeNull();
});
});
describe("the inbox's card in the chat", () => {
const lines = (ids: string[]) => createElement("div", null, ...ids.map((id) => createElement(InboxCardSlot, { key: id, threadId: "inbox", messageId: id })));
it("sits once, under the newest line that needed the person, and opens the inbox", async () => {
await mount(lines([settledRow.id, reportRow.id, messageRow.id, questionRow.id, approvalRow.id]));
expect(document.querySelectorAll("[data-inbox-card]")).toHaveLength(1);
expect(document.querySelector('[data-inbox-card="open"]')!.getAttribute("aria-label")).toBe("2 need you · 2 for your info");
expect([...document.querySelectorAll("[data-inbox-card] [data-inbox-row]")].map((row) => (row as HTMLElement).dataset.inboxRow)).toEqual([approvalRow.id, questionRow.id]);
expect([...document.querySelectorAll('[data-inbox-card] [data-inbox-action="allow"]')].filter((button) => !button.closest("[data-inbox-row]")),
"the line the card sits under answers on its own card").toEqual([]);
await click('[data-inbox-card] [data-inbox-choice="Pricing"]');
expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "inbox", requestId: "req-question", behavior: "answer", message: "Pricing" }));
await click('[data-inbox-card] header button');
expect(currentInboxPanel()).toMatchObject({ open: true, reading: null });
await mount(createElement(InboxCardSlot, { threadId: "elsewhere", messageId: approvalRow.id }));
expect(document.querySelector("[data-inbox-card]"), "never in another conversation").toBeNull();
});
it("shrinks to one line when nothing waits, and moves under a new ask once it lands", async () => {
const caughtUp = inboxView([messageRow, reportRow, { ...settledRow }]);
shown({ ...caughtUp, anchor: settledRow.id });
await mount(lines([settledRow.id, reportRow.id, messageRow.id]));
expect(document.querySelector('[data-inbox-card="caught-up"]')?.textContent).toContain("All caught up · 2 for your info");
const later = { ...approvalRow, id: "line-later" };
await act(async () => { shown({ ...inboxView([later, messageRow, reportRow, settledRow]), anchor: later.id }); });
await mount(lines([settledRow.id, reportRow.id, messageRow.id, later.id]));
const cards = document.querySelectorAll("[data-inbox-card]");
expect(cards).toHaveLength(1);
expect(cards[0]!.getAttribute("data-inbox-card")).toBe("open");
});
});
describe("answer buttons in the asking bot's colour", () => {
const reporter = { id: "reporter", name: "Reporter", color: "orange" } as Bot;
/** The answer under a line, not the quick action on the row itself. */
const answer = (selector: string) => [...document.querySelectorAll<HTMLElement>(selector)].find((button) => !button.closest("[data-inbox-row]"))!;
const own = (selector: string) => {
const button = answer(selector);
expect(button.className.split(" ")).toContain(BOT_BUTTON);
expect(button.style.getPropertyValue("--bot-button")).toBe(botButtonTone("orange").fill);
expect(button.style.getPropertyValue("--bot-button-ink")).toBe(botButtonTone("orange").ink);
};
it("paints Allow on the chat's card and in the panel in the colour of the bot the line is from", async () => {
shown({ ...inboxView(), anchor: questionRow.id });
await mount(createElement(InboxCardSlot, { threadId: "inbox", messageId: questionRow.id }), [reporter]);
own('[data-inbox-card] [data-inbox-action="allow"]');
expect(answer('[data-inbox-card] [data-inbox-action="deny"]').className.split(" ")).not.toContain(BOT_BUTTON);
openInbox({ reading: approvalRow.id });
await mount(createElement(InboxPanel), [reporter]);
own('[data-inbox-reading] [data-inbox-action="allow"]');
});
it("keeps the plain primary for a teammate's line and for a bot this app does not know", async () => {
openInbox({ reading: messageRow.id });
await mount(createElement(InboxPanel), [reporter]);
const send = document.querySelector<HTMLElement>('[data-inbox-reading] button[type="submit"]')!;
expect(send.className.split(" ")).not.toContain(BOT_BUTTON);
expect(send.className.split(" ")).toContain("bg-accent");
shown({ ...inboxView(), anchor: questionRow.id });
await mount(createElement(InboxCardSlot, { threadId: "inbox", messageId: questionRow.id }));
expect(answer('[data-inbox-card] [data-inbox-action="allow"]').className.split(" ")).not.toContain(BOT_BUTTON);
});
});
describe("keeping the list live", () => {
function Loader({ version }: { version: string }) {
useInboxLoader(version);
return null;
}
it("reads the list again whenever what it depends on changes", async () => {
const task = (inboxChangedAt?: number, openAsks?: number) => [{ id: "bens-chief", tasks: [{ threadId: "inbox", inbox: true as const, ...(inboxChangedAt ? { inboxChangedAt } : {}), ...(openAsks ? { openAsks } : {}) }] }];
expect(inboxVersion([{ id: "solo", tasks: [{ threadId: "t1" }] }]), "nothing is anyone's inbox off a team").toBeNull();
const first = inboxVersion(task(5, 2));
expect(inboxVersion(task(6, 2))).not.toBe(first);
expect(inboxVersion(task(5, 1))).not.toBe(first);
await mount(createElement(Loader, { version: first! }));
await settle();
const reads = () => server.calls.filter((call) => call.path === "/api/inbox").length;
expect(reads()).toBe(1);
await mount(createElement(Loader, { version: first! }));
await settle();
expect(reads(), "the same version reads nothing").toBe(1);
await mount(createElement(Loader, { version: inboxVersion(task(6, 1))! }));
await settle();
expect(reads()).toBe(2);
});
});
describe("the inbox's bot and status filters", () => {
const minutes = (count: number) => INBOX_NOW - count * 60_000;
const ada = {
id: "ada", name: "Ada", threadId: "ada-main", tasks: [
{ threadId: "ada-run", title: "Ada running", createdAt: 0, updatedAt: minutes(1), busy: true },
{ threadId: "ada-ask", title: "Ada asking", createdAt: 0, updatedAt: minutes(2), activity: "waiting-on-you" },
{ threadId: "ada-done", title: "Ada finished", createdAt: 0, updatedAt: minutes(500) },
],
} as unknown as Bot;
const ben = {
id: "ben", name: "Ben", threadId: "ben-main",
tasks: Array.from({ length: 10 }, (_, index) => ({ threadId: `ben-${index}`, title: `Ben finished ${index}`, createdAt: 0, updatedAt: minutes(10 + index) })),
} as unknown as Bot;
const titles = (section: string) => [...document.querySelectorAll<HTMLElement>(`[${section}] button[title]:not([data-inbox-pin])`)].map((row) => row.querySelector("span.min-w-0 > span")?.textContent ?? row.textContent);
const choose = (selector: string, value: string) => act(async () => {
const select = document.querySelector<HTMLSelectElement>(selector)!;
select.value = value;
select.dispatchEvent(new Event("change", { bubbles: true }));
});
it("lists every bot that has a conversation, and keeps the lists whole until the person picks", async () => {
openInbox();
await mount(createElement(InboxPanel), [ada, ben]);
const owners = [...document.querySelectorAll<HTMLOptionElement>("[data-inbox-filter-owner] option")].map((option) => option.textContent);
expect(owners).toEqual(["All bots and rooms", "Ada", "Ben"]);
expect(titles("data-inbox-active")).toEqual(["Ada asking", "Ada running"]);
expect(titles("data-inbox-finished"), "the newest ten").toEqual(Array.from({ length: 10 }, (_, index) => `Ben finished ${index}`));
});
it("shows one bot's conversations, including a finished one older than the newest ten", async () => {
openInbox();
await mount(createElement(InboxPanel), [ada, ben]);
await choose("[data-inbox-filter-owner]", "bot:ada");
expect(titles("data-inbox-active")).toEqual(["Ada asking", "Ada running"]);
expect(titles("data-inbox-finished")).toEqual(["Ada finished"]);
await choose("[data-inbox-filter-status]", "waiting");
expect(titles("data-inbox-active")).toEqual(["Ada asking"]);
expect(document.querySelector("[data-inbox-finished]"), "finished conversations are not waiting").toBeNull();
await choose("[data-inbox-filter-status]", "finished");
expect(document.querySelector("[data-inbox-active] button[title]")).toBeNull();
expect(titles("data-inbox-finished")).toEqual(["Ada finished"]);
});
it("says when nothing matches, and clears both pickers from there", async () => {
openInbox();
await mount(createElement(InboxPanel), [ada, ben]);
await choose("[data-inbox-filter-owner]", "bot:ben");
await choose("[data-inbox-filter-status]", "working");
expect(document.querySelector("[data-inbox-filter-empty]")?.textContent).toContain("No conversations match these filters.");
expect(document.querySelector<HTMLSelectElement>("[data-inbox-filter-owner]")!.value, "the picker shows the choice in force").toBe("bot:ben");
await click("[data-inbox-filter-empty] button");
expect(document.querySelector("[data-inbox-filter-empty]")).toBeNull();
expect(document.querySelector<HTMLSelectElement>("[data-inbox-filter-owner]")!.value).toBe("");
expect(document.querySelector<HTMLSelectElement>("[data-inbox-filter-status]")!.value).toBe("");
expect(titles("data-inbox-active")).toEqual(["Ada asking", "Ada running"]);
});
});