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 } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Action, Bot, Task } from "@/state/store";
const dispatch = vi.hoisted(() => vi.fn());
const store = vi.hoisted(() => ({ state: {} as Record<string, unknown> }));
vi.mock("@/state/store-select", () => ({ useStoreDispatch: () => dispatch, useStoreSelector: (select: (state: unknown) => unknown) => select(store.state) }));
vi.mock("./Avatar", () => ({ BotAvatar: () => null }));
import { ChatHeadPill } from "./ChatHeadPill";
import { useThreadCycleKeys } from "./thread-cycle";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const task = (threadId: string, title: string, at: number, extra: Partial<Task> = {}): Task => ({ threadId, title, createdAt: at, lastThreadOrderAt: at, ...extra });
const pepper = (tasks: Task[], threadId: string): Bot => ({ id: "pepper", name: "Pepper", threadId, mainThreadId: "sales", tasks, messages: [] } as unknown as Bot);
const THREADS = [task("sales", "Weekly sales", 5, { busy: true }), task("launch", "Launch plan", 1, { pinned: true }), task("trip", "Berlin trip", 3)];
let root: Root | null = null;
const onToggle = vi.fn();
/** Simple mode's header pill, with the app's Ctrl+Tab keys listening as they do in the app. */
function Header({ bot }: { bot: Bot }) {
useThreadCycleKeys();
return createElement(ChatHeadPill, { bot, avatar: {} as never, privacy: null, onToggle, switcher: true });
}
const render = (bot: Bot, settingsOpen = false) => {
store.state = { settingsOpen, pendingQueued: {}, bots: [bot], selectedId: bot.id, activeView: "chat", shortcutsOpen: false, newChat: null };
if (!root) root = createRoot(document.body.appendChild(document.createElement("div")));
act(() => root!.render(createElement(Header, { bot })));
};
const q = <T extends Element = HTMLElement>(selector: string) => document.querySelector<T & HTMLElement>(selector);
const trigger = () => q("[data-chathead-threads]")!.closest("button")!;
const rows = () => [...document.querySelectorAll<HTMLElement>("[role=menuitemradio]")];
const sent = () => dispatch.mock.calls.map(([action]) => action as Action);
const nextFrame = () => act(() => new Promise<void>((done) => requestAnimationFrame(() => done())));
const press = (key: string) => act(() => { document.activeElement!.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })); });
beforeEach(() => { dispatch.mockClear(); onToggle.mockClear(); });
afterEach(() => { act(() => root?.unmount()); root = null; document.body.innerHTML = ""; });
describe("the pill's thread switcher", () => {
it("names the open thread beside the bot, and the bot's name still opens its panel", () => {
render(pepper(THREADS, "launch"));
expect(q("[data-chathead-conversation]")?.textContent).toBe("Launch plan");
act(() => q("[data-chathead-pill]")!.click());
expect(onToggle).toHaveBeenCalledOnce();
expect(q("[role=menu]")).toBeNull();
});
it("opens on a click, never on hover, into a menu under the pill: pinned first, the open one checked", () => {
render(pepper(THREADS, "launch"));
act(() => { trigger().dispatchEvent(new MouseEvent("mouseover", { bubbles: true })); });
expect(q("[role=menu]")).toBeNull();
act(() => trigger().click());
expect(trigger().getAttribute("aria-expanded")).toBe("true");
expect(q("[role=menu]")!.getAttribute("aria-label")).toBe("Pepper threads");
expect(rows().map((row) => row.title)).toEqual(["Launch plan", "Weekly sales", "Berlin trip"]);
expect(rows().map((row) => row.getAttribute("aria-checked"))).toEqual(["true", "false", "false"]);
expect(rows()[1]!.querySelector('[aria-label="Working"]')).not.toBeNull();
expect(rows()[0]!.querySelector('[aria-label="Pinned"]')).not.toBeNull();
expect(rows()[2]!.textContent).toMatch(/ago|yesterday|\//);
});
it("switches to a picked thread and closes; the open one only closes", () => {
render(pepper(THREADS, "launch"));
act(() => trigger().click());
act(() => rows()[2]!.click());
expect(sent()).toEqual([{ type: "switchTask", botId: "pepper", threadId: "trip" }]);
expect(trigger().getAttribute("aria-expanded")).toBe("false");
act(() => trigger().click());
act(() => rows()[0]!.click());
expect(sent()).toHaveLength(1);
expect(trigger().getAttribute("aria-expanded")).toBe("false");
});
it("opens from the keyboard on the open thread, moves with the arrows, and Escape hands focus back to the pill", async () => {
render(pepper(THREADS, "trip"));
act(() => trigger().focus());
act(() => trigger().click());
await nextFrame();
expect(document.activeElement).toBe(rows()[2]);
press("ArrowUp");
expect(document.activeElement).toBe(rows()[1]);
press("Home");
expect(document.activeElement).toBe(rows()[0]);
press("Escape");
expect(q("[role=menu]")?.hasAttribute("inert") ?? true).toBe(true);
expect(document.activeElement).toBe(trigger());
expect(sent()).toEqual([]);
});
it("steps from the pill into a menu the mouse opened, at the open thread", () => {
render(pepper(THREADS, "sales"));
act(() => trigger().focus());
act(() => { trigger().dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 })); });
expect(document.activeElement).toBe(trigger());
press("ArrowDown");
expect(document.activeElement).toBe(rows()[1]);
});
it("finds the open thread while the bot panel is open beside it", async () => {
const panel = document.body.appendChild(document.createElement("div"));
panel.id = "bot-panel";
panel.innerHTML = '<button type="button" role="switch" aria-checked="true">Setting</button>';
render(pepper(THREADS, "sales"), true);
expect(q("[data-chathead-pill]")!.getAttribute("aria-controls")).toBeTruthy();
act(() => trigger().focus());
act(() => trigger().click());
await nextFrame();
expect(document.activeElement).toBe(rows()[1]);
press("Escape");
act(() => { trigger().dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 })); });
press("ArrowDown");
expect(document.activeElement).toBe(rows()[1]);
});
it("starts a new thread from the menu's last row, which a view-only person does not get", () => {
render(pepper(THREADS, "launch"));
act(() => trigger().click());
const start = q('[data-menu-key="new-thread"]')!;
expect(start.textContent).toContain("New thread");
act(() => start.click());
expect(sent()).toEqual([{ type: "newTask", botId: "pepper" }]);
act(() => root?.unmount()); root = null; document.body.innerHTML = "";
render({ ...pepper(THREADS, "launch"), yourAccess: "view" } as Bot);
act(() => trigger().click());
expect(q('[data-menu-key="new-thread"]')).toBeNull();
expect(rows()).toHaveLength(3);
});
it("hides the focus ring after a pointer opens it, and shows it again once a key moves focus", () => {
render(pepper(THREADS, "launch"));
const pill = () => q("[data-chathead-switch]")!;
act(() => { trigger().dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })); });
act(() => trigger().click());
expect(pill().hasAttribute("data-pointer-used")).toBe(true);
act(() => rows()[1]!.focus());
press("a");
press("Shift");
expect(pill().hasAttribute("data-pointer-used")).toBe(true);
press("ArrowDown");
expect(pill().hasAttribute("data-pointer-used")).toBe(false);
expect(document.activeElement).toBe(rows()[2]);
});
it("shows for a bot whose second open thread another bot opened, beside its main thread", () => {
const lead = { botId: "lead", name: "Lead", at: 1 };
render(pepper([task("sales", "Weekly sales", 5), task("brief", "Launch brief", 3, { openedBy: lead })], "sales"));
act(() => trigger().click());
expect(rows().map((row) => row.title)).toEqual(["Weekly sales", "Launch brief"]);
});
it("Ctrl+Tab walks the threads in the order the menu lists them, wrapping", () => {
const helper = task("brief", "Launch brief", 4, { openedBy: { botId: "lead", name: "Lead", at: 1 } });
const threads = [...THREADS, helper];
render(pepper(threads, "launch"));
act(() => trigger().click());
const order = rows().map((row) => row.dataset.menuKey!.replace("thread:", ""));
expect(order).toEqual(["launch", "sales", "brief", "trip"]);
press("Escape");
const visited: string[] = [];
let open = order[0]!;
for (let step = 0; step < order.length; step += 1) {
act(() => { document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", ctrlKey: true, bubbles: true, cancelable: true })); });
const action = sent().at(-1) as Extract<Action, { type: "switchTask" }>;
open = action.threadId;
visited.push(open);
render(pepper(threads, open));
}
expect(visited).toEqual([...order.slice(1), order[0]]);
});
it("stays the plain pill for a bot with one thread", () => {
render(pepper([task("sales", "Weekly sales", 5)], "sales"));
expect(q("[data-chathead-threads]")).toBeNull();
expect(q("[data-chathead-switch]")).toBeNull();
expect(q("[data-chathead-pill]")).not.toBeNull();
});
});