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 { 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 { Bot, Message, Task } from "@/state/store";
import { setAdvancedMode } from "@/lib/interface-mode";
const fixture = vi.hoisted(() => ({
dispatch: vi.fn(),
wide: true,
api: vi.fn(),
admin: true as boolean | null,
}));
vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.admin }));
vi.mock("@/state/store", async (importOriginal) => {
const original = await importOriginal<typeof import("@/state/store")>();
return {
...original,
api: (...args: unknown[]) => fixture.api(...args),
useStore: () => ({ state: original.initialState, dispatch: fixture.dispatch }),
};
});
vi.mock("@/lib/use-media-query", async (importOriginal) => ({
...await importOriginal<typeof import("@/lib/use-media-query")>(),
useMediaQuery: () => fixture.wide,
}));
const { BotConversations, CONVERSATIONS_SHOWN, forgetConversationLines } = await import("./Conversations");
const now = Date.now();
const task = (threadId: string, title: string, order: number, extra: Partial<Task> = {}): Task =>
({ threadId, title, createdAt: now - 86_400_000, updatedAt: now - order * 60_000, lastThreadOrderAt: now - order * 60_000, ...extra });
const tasks: Task[] = [
task("launch", "Translate the launch post", 1, { unread: true }),
task("who", "Who am I?", 2),
task("pricing", "Competitor pricing", 3, { busy: true, activity: "working", turnStartedAt: now - 72_000 }),
task("deck", "Summarise the board deck", 4),
task("podcasts", "Find three podcasts about agents", 5),
task("hiring", "Draft the hiring post", 6, { pinned: true }),
task("compare", "Compare two note apps", 7),
task("trip", "Plan the Lisbon trip", 8),
task("taxes", "Sort the tax receipts", 9),
task("gift", "Birthday gift ideas", 10),
task("run", "Morning brief run", 0, { routineRunId: "run-1" }),
];
const reply = (threadId: string, text: string): Message => ({ id: `${threadId}-reply`, role: "bot", kind: "text", text, at: now });
const lines: Record<string, string> = {
launch: "Done. Want me to translate another post?",
pricing: "Pricing compared, table attached",
deck: "Five key points and two risks",
podcasts: "Three shows with episode links",
hiring: "Draft ready for review",
compare: "One extracts, the other decides",
};
const research = (extra: Partial<Bot> = {}): Bot => ({
id: "research", threadId: "who", name: "Research", title: "", description: "", notifications: true, color: "green",
unread: true, modelSelection: { instanceId: "fake", model: "fake" }, tasks, messages: [reply("who", "You're the owner of this install")],
...extra,
});
let host: HTMLDivElement;
let root: Root;
const render = (bot: Bot) => flushSync(() => root.render(createElement(BotConversations, { bot })));
const settle = async () => {
for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0));
};
const listed = () => [...host.querySelectorAll("[data-conversation]")].map((row) => row.getAttribute("data-conversation"));
const row = (threadId: string) => host.querySelector(`[data-conversation="${threadId}"]`)!;
const click = (element: Element | null) => {
if (!element) throw new Error("nothing to click");
flushSync(() => element.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 })));
};
const more = () => host.querySelector("[data-conversations-more]");
const type = (input: HTMLInputElement, value: string) => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
flushSync(() => input.dispatchEvent(new Event("input", { bubbles: true })));
};
beforeEach(() => {
fixture.dispatch.mockReset();
fixture.wide = true;
fixture.api.mockReset();
forgetConversationLines();
fixture.api.mockImplementation((path: string) => {
const threadId = decodeURIComponent(path.split("/")[3]!);
return Promise.resolve({ messages: lines[threadId] ? [reply(threadId, lines[threadId])] : [], activeLeafId: null });
});
document.documentElement.dataset.reducedMotion = "true";
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
});
afterEach(() => {
flushSync(() => root.unmount());
host.remove();
});
describe("a bot's conversations in its panel", () => {
it("offers the public web conversation link alongside the app link in Advanced mode, and copies its exact address", async () => {
setAdvancedMode(true);
const writeText = vi.fn(() => Promise.resolve());
vi.stubGlobal("navigator", { clipboard: { writeText } });
const previous = fixture.api.getMockImplementation()!;
fixture.api.mockImplementation((path: string) => path === "/api/settings/custom-domain"
? Promise.resolve({ publicUrl: "https://chat.example/" }) : previous(path));
try {
render(research());
click(host.querySelector('[aria-label="Actions for Translate the launch post"]'));
await vi.waitFor(() => expect(document.querySelector("[data-thread-overlay]")?.textContent).toContain("Copy link (HTTPS)"));
const buttons = [...document.querySelector("[data-thread-overlay]")!.querySelectorAll("button")];
expect(buttons.some((button) => button.textContent === "Copy link")).toBe(true);
click(buttons.find((button) => button.textContent === "Copy link (HTTPS)")!);
expect(writeText).toHaveBeenCalledWith("https://chat.example/?thread=launch&bot=research");
} finally { vi.unstubAllGlobals(); setAdvancedMode(false); }
});
it("keeps the app link available in Advanced mode when the public-address request fails", async () => {
setAdvancedMode(true);
const previous = fixture.api.getMockImplementation()!;
fixture.api.mockImplementation((path: string) => path === "/api/settings/custom-domain"
? Promise.reject(new Error("not permitted")) : previous(path));
render(research());
click(host.querySelector('[aria-label="Actions for Translate the launch post"]'));
await Promise.resolve();
const menu = document.querySelector("[data-thread-overlay]")!;
expect([...menu.querySelectorAll("button")].some((button) => button.textContent === "Copy link")).toBe(true);
expect(menu.textContent).not.toContain("Copy link (HTTPS)");
setAdvancedMode(false);
});
it("lists three, newest first, with the open one marked, and Show N more opens the rest", () => {
render(research());
expect(CONVERSATIONS_SHOWN).toBe(3);
expect(listed()).toEqual(["hiring", "launch", "who"]);
expect(row("who").querySelector('[data-sidebar-thread-row="who"]')!.getAttribute("aria-current")).toBe("page");
expect(row("launch").querySelector("[aria-current]")).toBeNull();
expect(listed()).not.toContain("run");
expect(more()!.textContent).toBe("Show 7 more");
expect(more()!.getAttribute("aria-expanded")).toBe("false");
click(more());
expect(listed()).toEqual(["hiring", "launch", "who", "pricing", "deck", "podcasts", "compare", "trip", "taxes", "gift"]);
expect(more()!.textContent).toBe("Show fewer");
click(more());
expect(listed()).toHaveLength(3);
});
it("keeps the open conversation listed when it is older than the first three", () => {
render(research({ threadId: "gift", messages: [] }));
expect(listed()).toEqual(["hiring", "launch", "who", "gift"]);
expect(more()!.textContent).toBe("Show 6 more");
});
it("lists the main thread first, above a pinned one, however old it is, folded or not", () => {
render(research({ mainThreadId: "gift" }));
expect(listed()).toEqual(["gift", "hiring", "launch", "who"]);
click(more());
expect(listed().slice(0, 3)).toEqual(["gift", "hiring", "launch"]);
expect(listed()).toHaveLength(10);
render(research({ mainThreadId: "hiring" }));
expect(listed().slice(0, 2)).toEqual(["hiring", "launch"]);
});
it("keeps the main thread listed, with its mark, when it is older than the first three", () => {
render(research({ mainThreadId: "gift" }));
expect(listed()).toEqual(["gift", "hiring", "launch", "who"]);
expect(row("gift").querySelector('[aria-label="Main thread"]')).not.toBeNull();
expect(more()!.textContent).toBe("Show 6 more");
});
it("offers only New conversation while the open one is the bot's only conversation", () => {
render(research({ tasks: [task("who", "Who am I?", 2)] }));
expect(host.querySelector("[data-conversations-new]")).not.toBeNull();
expect(host.querySelector("[data-conversations-search]")).toBeNull();
expect(host.querySelector('[role="list"]')).toBeNull();
expect(listed()).toEqual([]);
});
it("sets the rows in the panel's type: never bolder than medium, a 12px time and a larger unread dot", () => {
render(research());
const list = host.querySelector('[role="list"]')!.className.split(" ");
expect(list).toEqual(expect.arrayContaining(["[&_.font-semibold]:font-medium", "[&_time]:text-[12px]", "[&_time]:text-ink-tertiary", "[&_span.bg-accent]:size-2"]));
});
it("puts New conversation first, as a labelled button, with search on the section's label line", () => {
render(research());
const add = host.querySelector("[data-conversations-new]")!;
expect(add.textContent).toBe("New conversation");
expect(add.compareDocumentPosition(host.querySelector("[data-conversation]")!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(host.querySelector("[data-conversations-search]")!.compareDocumentPosition(add) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("shows no Show more when every conversation fits", () => {
render(research({ tasks: tasks.slice(0, 3) }));
expect(listed()).toHaveLength(3);
expect(more()).toBeNull();
});
it("marks an unread reply with a dot, a pinned conversation with a pin, and a running one with how long it has worked", async () => {
render(research());
await settle();
expect(row("launch").querySelector('[aria-label="Unread"]')).not.toBeNull();
expect(row("who").querySelector('[aria-label="Unread"]')).toBeNull();
expect(row("hiring").querySelector('svg[aria-label="Pin"]')).not.toBeNull();
expect(row("launch").querySelector('svg[aria-label="Pin"]')).toBeNull();
expect(row("pricing")).toBeNull();
click(more());
expect(row("pricing").querySelector("[data-thread-working]")!.textContent).toMatch(/^Working·1m 1[23]s$/);
expect(host.querySelectorAll("[data-thread-working]")).toHaveLength(1);
});
it("marks the bot's main thread with the same star as the sidebar's thread list, and no other row", () => {
render(research({ mainThreadId: "launch" }));
const star = row("launch").querySelector('[role="img"][aria-label="Main thread"]');
expect(star?.getAttribute("title")).toBe("Main thread");
expect(star?.querySelector("svg")).not.toBeNull();
expect(star?.textContent).toBe("Main");
expect(row("who").querySelector('[aria-label="Main thread"]')).toBeNull();
render(research({ mainThreadId: "who" }));
expect(row("who").querySelector('[aria-label="Main thread"]')).not.toBeNull();
expect(row("launch").querySelector('[aria-label="Main thread"]')).toBeNull();
render(research());
expect(host.querySelector('[aria-label="Main thread"]')).toBeNull();
});
it("shows each listed conversation's last line, fetching only the listed ones that are not open", async () => {
render(research());
await settle();
expect(row("who").textContent).toContain("You're the owner of this install");
expect(row("launch").textContent).toContain("Done. Want me to translate another post?");
expect(row("hiring").textContent).toContain("Draft ready for review");
expect(fixture.api.mock.calls.map(([path]) => path).sort()).toEqual([
"/api/threads/hiring/messages?limit=8",
"/api/threads/launch/messages?limit=8",
]);
expect(fixture.api.mock.calls[0]![1]).toEqual({ background: true });
});
it("searches titles and last lines, and says when nothing matches", async () => {
render(research());
expect(host.querySelector("[data-conversations-query]")).toBeNull();
click(host.querySelector("[data-conversations-search]"));
const input = host.querySelector<HTMLInputElement>("[data-conversations-query]")!;
expect(input.getAttribute("placeholder")).toBe("Search Research's conversations");
type(input, "post");
expect(listed()).toEqual(["hiring", "launch"]);
expect(more()).toBeNull();
await settle();
type(input, "episode");
await settle();
expect(listed()).toEqual(["podcasts"]);
type(input, "zebra");
expect(listed()).toEqual([]);
expect(host.textContent).toContain("Nothing matches “zebra”");
const escape = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });
flushSync(() => input.dispatchEvent(escape));
expect(escape.defaultPrevented).toBe(true);
expect(host.querySelector("[data-conversations-query]")).toBeNull();
expect(listed()).toHaveLength(3);
});
it("opens a conversation, and leaves the open one alone", () => {
render(research());
click(row("launch").querySelector('[data-sidebar-thread-row="launch"]'));
expect(fixture.dispatch.mock.calls).toEqual([[{ type: "switchTask", botId: "research", threadId: "launch" }]]);
fixture.dispatch.mockReset();
click(row("who").querySelector('[data-sidebar-thread-row="who"]'));
expect(fixture.dispatch).not.toHaveBeenCalled();
});
it("closes the panel after opening or starting a conversation at phone width", () => {
fixture.wide = false;
render(research());
click(row("launch").querySelector('[data-sidebar-thread-row="launch"]'));
expect(fixture.dispatch.mock.calls).toEqual([
[{ type: "switchTask", botId: "research", threadId: "launch" }],
[{ type: "toggleSettings", open: false }],
]);
fixture.dispatch.mockReset();
click(host.querySelector("[data-conversations-new]"));
expect(fixture.dispatch.mock.calls).toEqual([[{ type: "newTask", botId: "research" }], [{ type: "toggleSettings", open: false }]]);
});
it("starts a new conversation from +, keeping the panel open on a wide window", () => {
render(research());
const add = host.querySelector("[data-conversations-new]")!;
expect(add.getAttribute("aria-label")).toBe("New conversation");
click(add);
expect(fixture.dispatch.mock.calls).toEqual([[{ type: "newTask", botId: "research" }]]);
});
it("pins, archives, renames and deletes through the thread menu the sidebar uses", () => {
render(research());
const menuFor = (title: string) => {
click(host.querySelector(`[aria-label="Actions for ${title}"]`));
return [...document.querySelector(`[data-thread-overlay][aria-label="Actions for ${title}"]`)!.querySelectorAll("button")];
};
const items = menuFor("Translate the launch post");
expect(items.map((button) => button.textContent)).toEqual(["Rename thread", "Memory", "Pin", "Set as main thread", "Archive", "Delete thread"]);
click(items.find((button) => button.textContent === "Pin")!);
expect(fixture.dispatch.mock.calls).toEqual([[{ type: "updateTask", botId: "research", threadId: "launch", patch: { pinned: true } }]]);
fixture.dispatch.mockReset();
click(menuFor("Translate the launch post").find((button) => button.textContent === "Archive")!);
expect(fixture.dispatch.mock.calls).toEqual([[{ type: "updateTask", botId: "research", threadId: "launch", patch: { archivedAt: expect.any(Number) } }]]);
});
it("sets the row's own thread as the main one from its menu, and not the one that already is, an archived one, or for a member", () => {
const toggle = (title: string) => click(host.querySelector(`[aria-label="Actions for ${title}"]`));
const item = (title: string) => [...document.querySelector(`[data-thread-overlay][aria-label="Actions for ${title}"]`)!.querySelectorAll("button")]
.find((button) => button.textContent === "Set as main thread");
const archived = [...tasks, task("old", "Old notes", 11, { archivedAt: now })];
render(research({ mainThreadId: "launch", threadId: "old", tasks: archived }));
toggle("Who am I?");
click(item("Who am I?")!);
expect(fixture.dispatch.mock.calls).toEqual([[{ type: "updateBot", botId: "research", patch: { mainThreadChoice: "who" } }]]);
toggle("Translate the launch post");
const already = item("Translate the launch post")!;
expect([already.disabled, already.title]).toEqual([true, "This is already the main thread"]);
toggle("Translate the launch post");
toggle("Old notes");
expect(item("Old notes")).toBeUndefined();
toggle("Old notes");
fixture.admin = false;
render(research({ mainThreadId: "launch", threadId: "deck" }));
toggle("Who am I?");
expect(item("Who am I?")).toBeUndefined();
fixture.admin = true;
});
it("keeps the search open when archiving leaves one conversation listed", () => {
const two = [task("who", "Who am I?", 2), task("deck", "Summarise the board deck", 4)];
render(research({ tasks: two }));
click(host.querySelector("[data-conversations-search]"));
type(host.querySelector<HTMLInputElement>("[data-conversations-query]")!, "deck");
render(research({ tasks: [two[0]!, { ...two[1]!, archivedAt: now - 1000 }] }));
expect(host.querySelector("[data-conversations-query]")).not.toBeNull();
expect(host.querySelector("[data-conversations-search]")).not.toBeNull();
expect(host.textContent).toContain("Nothing matches “deck”");
});
it("keeps the open conversation listed when it is archived and the only one left", () => {
const two = [task("who", "Who am I?", 2, { archivedAt: now - 1000 }), task("deck", "Summarise the board deck", 4, { archivedAt: now - 2000 })];
render(research({ tasks: two }));
expect(listed()).toEqual(["who"]);
expect(host.querySelector("[data-conversations-archived]")!.textContent).toBe("Archived (1)");
});
it("lists archived conversations under Archived (N), where they can be unarchived", () => {
render(research({ tasks: tasks.map((task) => task.threadId === "launch" || task.threadId === "deck" ? { ...task, archivedAt: now - 1000 } : task) }));
expect(listed()).toEqual(["hiring", "who", "pricing"]);
const archivedToggle = host.querySelector("[data-conversations-archived]")!;
expect(archivedToggle.textContent).toBe("Archived (2)");
expect(archivedToggle.getAttribute("aria-expanded")).toBe("false");
click(archivedToggle);
expect(listed()).toEqual(["hiring", "who", "pricing", "launch", "deck"]);
click(host.querySelector('[aria-label="Actions for Summarise the board deck"]'));
const unarchive = [...document.querySelector('[data-thread-overlay][aria-label="Actions for Summarise the board deck"]')!.querySelectorAll("button")]
.find((button) => button.textContent === "Unarchive")!;
click(unarchive);
expect(fixture.dispatch.mock.calls).toEqual([[{ type: "updateTask", botId: "research", threadId: "deck", patch: { archivedAt: null } }]]);
});
it("moves ended conversations out of the list into Ended (N), folded under the active ones", () => {
const lead = { botId: "lead", name: "Lead", at: now };
const endedTasks = tasks.map((task) => task.threadId === "launch" || task.threadId === "pricing" ? { ...task, busy: false, activity: undefined, closedBy: lead } : task);
render(research({ tasks: endedTasks }));
expect(listed()).toEqual(["hiring", "who", "deck"]);
const toggle = host.querySelector("[data-conversations-ended]")!;
expect(toggle.textContent).toBe("Ended (2)");
expect(toggle.getAttribute("aria-expanded")).toBe("false");
expect(host.querySelector("[data-conversations-more]")!.textContent).toBe("Show 5 more");
click(toggle);
expect(toggle.getAttribute("aria-expanded")).toBe("true");
expect(listed()).toEqual(["hiring", "who", "deck", "launch", "pricing"]);
click(toggle);
expect(listed()).toEqual(["hiring", "who", "deck"]);
});
it("keeps an ended conversation in the list while it is open or the main one, and finds ended ones in search", () => {
const lead = { botId: "lead", name: "Lead", at: now };
const endedTasks = tasks.map((task) => ["who", "gift", "deck"].includes(task.threadId) ? { ...task, closedBy: lead } : task);
render(research({ mainThreadId: "gift", tasks: endedTasks }));
expect(listed()).toEqual(["gift", "hiring", "launch", "who"]);
expect(host.querySelector("[data-conversations-ended]")!.textContent).toBe("Ended (1)");
click(host.querySelector("[data-conversations-search]"));
type(host.querySelector<HTMLInputElement>("[data-conversations-query]")!, "board");
expect(listed()).toEqual(["deck"]);
expect(host.querySelector("[data-conversations-ended]")).toBeNull();
});
it("keeps search when the only other conversation has ended, and finds it", () => {
const lead = { botId: "lead", name: "Lead", at: now };
render(research({ tasks: [task("who", "Who am I?", 2), task("deck", "Summarise the board deck", 4, { closedBy: lead })] }));
expect(listed()).toEqual(["who"]);
expect(host.querySelector("[data-conversations-ended]")!.textContent).toBe("Ended (1)");
click(host.querySelector("[data-conversations-search]"));
type(host.querySelector<HTMLInputElement>("[data-conversations-query]")!, "board");
expect(listed()).toEqual(["deck"]);
});
});