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
// A bot's page inline in the chat, with its tools. happy-dom runs no script in the frame, so the page is played by
// message events from the frame's window.
import { act, createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BotEditorStore, type Message, type useStore } from "@/state/store";
import { setAdvancedMode } from "@/lib/interface-mode";
import { addPointedChip, forgetPointedChips, setPointedNote, takePointedChips, usePointedChips } from "@/lib/pointed-chips";
import { setWebPanels } from "@/lib/web-panel-preferences";
import { MAX_WEB_PANELS } from "@/lib/web-panels";
import type { AppPayload } from "../../../shared/app";
import type { PublishedPageCard } from "../../../shared/published-page";
import { botHtmlDocument } from "../../../shared/app-frame/document";
import { marksMessage, POINT_LIMITS, POINT_SELECTION_METHOD, POINTED_METHOD } from "../../../shared/app-frame/point";
import { createAppPool, type AppPool } from "./app-pool";
import { AppMessage, forgetAppRows } from "./AppMessage";
import { PAGE_HEIGHT } from "./PageTools";
import { PointedChips } from "./PointedChips";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const payload = (more: Partial<AppPayload> = {}): AppPayload => ({
v: 1, source: "html", title: "Pricing", doc: "d0", rev: 0, bytes: 900, border: true, network: { connect: [], resources: [] }, ...more,
});
const row = (app: AppPayload, publishedPage?: PublishedPageCard): Message => ({ id: "a1", role: "bot", kind: "app", at: 1, text: "[App] Pricing", app,
...(publishedPage ? { publishedPage } : {}) });
const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
const fetchMock = vi.fn<(path: string, init?: RequestInit) => Promise<Response>>();
const openExternal = vi.fn(async () => true);
const store = { state: {}, dispatch: vi.fn(), flushBotPatches: vi.fn(async () => null) } as unknown as ReturnType<typeof useStore>;
const LINK = "https://page000000000000000000001.mausbot.page/";
const LIVE: PublishedPageCard = { state: "live", title: "Pricing", pageId: "page000000000000000000001", url: LINK, usage: { pages: 1, limit: 5 } };
const OWNER: PublishedPageCard = { state: "live", title: "Pricing", pageId: "page000000000000000000001",
url: "https://cloud.example.test/api/published-pages/page000000000000000000001/", visibility: "owner" };
let host: HTMLDivElement;
let root: Root;
let pool: AppPool;
let newestRev: number;
function Chips() {
const chips = usePointedChips("t1");
return createElement("output", { "data-chips": JSON.stringify(chips.map(({ id: _id, ...chip }) => chip)) });
}
const render = async (message: Message) => {
newestRev = message.app?.rev ?? 0;
await act(async () => {
root.render(createElement(BotEditorStore, { value: store, children: [
createElement(AppMessage, { key: "row", botId: "pepper", botName: "Pepper", threadId: "t1", message, pool }),
createElement(Chips, { key: "chips" }),
createElement(PointedChips, { key: "points", threadId: "t1" }),
] }));
});
await settle();
};
const settle = () => act(async () => { for (let i = 0; i < 8; i += 1) await new Promise((resolve) => setTimeout(resolve, 0)); });
const card = () => host.querySelector<HTMLElement>("[data-app=a1]")!;
const overlay = () => document.querySelector<HTMLElement>("[data-page-fullscreen]");
const inlineFrame = () => card().querySelector<HTMLIFrameElement>("iframe")!;
const wideFrame = () => overlay()!.querySelector<HTMLIFrameElement>("iframe")!;
const button = (label: string, within: ParentNode = document) => Array.from(within.querySelectorAll<HTMLButtonElement>("button"))
.find((element) => element.textContent?.trim() === label || element.getAttribute("aria-label") === label)!;
const click = (label: string, within?: ParentNode) => act(async () => { button(label, within).click(); await new Promise((resolve) => setTimeout(resolve, 0)); });
const chips = () => JSON.parse(host.querySelector("[data-chips]")!.getAttribute("data-chips")!) as unknown[];
const documents = () => fetchMock.mock.calls.map(([path]) => new URL(path, "http://omb.test")).filter((url) => url.pathname.endsWith("/app"));
const posts = (ending: string) => fetchMock.mock.calls.filter(([path, init]) => path.endsWith(ending) && init?.method === "POST").map(([, init]) => JSON.parse(String(init!.body)));
const fromFrame = (data: unknown, source: unknown) => act(async () => {
window.dispatchEvent(new MessageEvent("message", { data, source: source as MessageEventSource }));
await new Promise((resolve) => setTimeout(resolve, 0));
});
const PICK = { jsonrpc: "2.0", method: POINTED_METHOD, params: { tag: "button", role: "button", text: "Choose Pro", selector: "main > section:nth-of-type(2) > button", html: "<button>Choose Pro</button>" } };
beforeEach(() => {
fetchMock.mockReset();
fetchMock.mockImplementation(async (path, init) => {
const url = new URL(path, "http://omb.test");
if (url.pathname.endsWith("/app/publish")) {
const asked = JSON.parse(String(init?.body ?? "{}")) as { visibility?: string };
return json(200, { ok: true, card: asked.visibility === "owner" ? OWNER : LIVE });
}
if (url.pathname.endsWith("/unpublish")) return json(200, { ok: true, card: { ...LIVE, state: "unpublished" } });
const rev = url.searchParams.get("rev");
return json(200, botHtmlDocument({ messageId: "a1", rev: rev === null ? newestRev : Number(rev), html: `<p>${rev === null ? "newest" : `version ${Number(rev) + 1}`}</p>` }));
});
vi.stubGlobal("fetch", fetchMock);
vi.stubGlobal("ogb", { openExternal });
vi.stubGlobal("IntersectionObserver", undefined);
pool = createAppPool({ limit: 3 });
forgetAppRows();
forgetPointedChips();
host = document.createElement("div");
document.body.appendChild(host);
root = createRoot(host);
});
afterEach(() => {
act(() => root.unmount());
host.remove();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("a bot's page in the chat", () => {
it("draws inline at the page height, with its version, Point, Share, Open in new tab and Full screen", async () => {
await render(row(payload()));
expect(card().querySelector("[data-page-version]")?.textContent).toBe("v1");
expect(inlineFrame().getAttribute("sandbox")).toBe("allow-scripts allow-forms");
expect(card().querySelector<HTMLElement>("[data-app-box]")!.style.height).toBe(`${PAGE_HEIGHT.start}px`);
for (const label of ["Point", "Share", "Full screen"]) expect(button(label, card()).disabled, label).toBe(false);
expect(button("Open in new tab", card()).disabled).toBe(true);
expect(button("Open in new tab", card()).title).toBe("Share the page to open it in a new tab");
expect(documents()[0]!.searchParams.get("origin")).toBe(window.location.origin);
});
it("refreshes the same card on update_html with Updated, and steps back to the versions it keeps", async () => {
await render(row(payload()));
await render(row(payload({ doc: "d1", rev: 1, history: ["d0"] })));
expect(host.querySelectorAll("[data-app]")).toHaveLength(1);
expect(card().querySelector("[data-page-version]")?.textContent).toBe("v2");
expect(card().querySelector("[data-page-updated]")?.textContent).toBe("Updated");
await click("Earlier version", card());
expect(card().querySelector("[data-page-version]")?.textContent).toBe("v1 of 2");
expect(documents().at(-1)!.searchParams.get("rev")).toBe("0");
expect(inlineFrame().srcdoc).toContain("<p>version 1</p>");
expect(button("Earlier version", card()).disabled).toBe(true);
await click("Back to the latest", card());
expect(card().querySelector("[data-page-version]")?.textContent).toBe("v2");
expect(inlineFrame().srcdoc).toContain("<p>newest</p>");
});
it("points inline: only the page's own frame, only while Point is on, and the pick becomes a chip for the version on screen", async () => {
await render(row(payload()));
const posted = vi.spyOn(inlineFrame().contentWindow!, "postMessage").mockImplementation(() => {});
await fromFrame(PICK, inlineFrame().contentWindow);
expect(chips()).toEqual([]);
await click("Point", card());
expect(posted).toHaveBeenCalledWith({ jsonrpc: "2.0", method: "mausbot/point", params: { on: true } }, "*");
expect(card().textContent).toContain("or select text, to point at it");
await fromFrame(PICK, window);
expect(chips()).toEqual([]);
await fromFrame(PICK, inlineFrame().contentWindow);
expect(chips()).toEqual([{ appId: "a1", rev: 0, title: "Pricing", tag: "button", role: "button", text: "Choose Pro",
selector: "main > section:nth-of-type(2) > button", html: "<button>Choose Pro</button>" }]);
expect(posted).toHaveBeenCalledWith(marksMessage(["main > section:nth-of-type(2) > button"]), "*");
expect(button("Point", card()).getAttribute("aria-pressed")).toBe("true");
await fromFrame({ ...PICK, params: { ...PICK.params, text: "Terms", selector: "footer > a" } }, inlineFrame().contentWindow);
expect(chips()).toHaveLength(2);
expect(posted).toHaveBeenLastCalledWith(marksMessage(["main > section:nth-of-type(2) > button", "footer > a"]), "*");
posted.mockClear();
await act(async () => { inlineFrame().dispatchEvent(new Event("load")); });
expect(posted).toHaveBeenCalledWith(marksMessage(["main > section:nth-of-type(2) > button", "footer > a"]), "*");
await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); });
expect(button("Point", card()).getAttribute("aria-pressed")).toBe("false");
expect(posted).toHaveBeenCalledWith({ jsonrpc: "2.0", method: "mausbot/point", params: { on: false } }, "*");
});
it("sends highlights and their notes with element picks and clears or restores marks with the visible version", async () => {
const page = payload({ doc: "d1", rev: 1, history: ["d0"] });
await render(row(page));
await click("Point", card());
// A selection becomes a highlight in the page itself as the pointer lifts: there is no button for it here.
const tooLong = { jsonrpc: "2.0", method: POINT_SELECTION_METHOD, params: { state: "too-long" } };
const posted = vi.spyOn(inlineFrame().contentWindow!, "postMessage").mockImplementation(() => {});
expect(button("Highlight selection", card())).toBeUndefined();
await fromFrame(tooLong, window);
expect(card().textContent).not.toContain("too long");
await fromFrame(tooLong, inlineFrame().contentWindow);
expect(card().textContent).toContain("This selection is too long");
const first = { start: 0, end: 2, fingerprint: 7 };
const second = { start: 6, end: 8, fingerprint: 7 };
const { selector } = PICK.params;
const highlightPick = (range: typeof first) => ({ ...PICK, params: { ...PICK.params, range, text: "42", html: "" } });
await fromFrame(PICK, inlineFrame().contentWindow);
await fromFrame(highlightPick(first), inlineFrame().contentWindow);
await fromFrame(highlightPick(second), inlineFrame().contentWindow);
await fromFrame(highlightPick(first), inlineFrame().contentWindow);
expect(chips()).toHaveLength(3);
expect(posted).toHaveBeenLastCalledWith(marksMessage([selector, { selector, range: first }, { selector, range: second }]), "*");
await click("Earlier version", card());
await settle();
const older = vi.spyOn(inlineFrame().contentWindow!, "postMessage").mockImplementation(() => {});
await act(async () => { inlineFrame().dispatchEvent(new Event("load")); });
expect(older).toHaveBeenLastCalledWith(marksMessage(["", "", ""]), "*");
await click("Later version", card());
await settle();
const newer = vi.spyOn(inlineFrame().contentWindow!, "postMessage").mockImplementation(() => {});
await act(async () => { inlineFrame().dispatchEvent(new Event("load")); });
expect(newer).toHaveBeenLastCalledWith(marksMessage([selector, { selector, range: first }, { selector, range: second }]), "*");
await click("Remove “42”", host);
expect(newer).toHaveBeenLastCalledWith(marksMessage([selector, { selector, range: second }]), "*");
await click("Write a note on “42”", host);
const note = host.querySelector<HTMLInputElement>("[data-pointed-note]")!;
act(() => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(note, "Wrong total");
note.dispatchEvent(new Event("input", { bubbles: true }));
});
const sent = await act(async () => takePointedChips("t1")!);
expect(sent.pointed).toMatchObject([{ selector }, { selector, rev: 1, text: "42", range: second, note: "Wrong total" }]);
expect(newer).toHaveBeenLastCalledWith(marksMessage([]), "*");
await act(async () => { sent.restore(); });
expect(newer).toHaveBeenLastCalledWith(marksMessage([selector, { selector, range: second }]), "*");
});
it("sends Point and the numbered outlines again to the frame a reload puts in place", async () => {
await render(row(payload()));
await click("Point", card());
await fromFrame(PICK, inlineFrame().contentWindow);
const before = inlineFrame();
await click("Reload app", card());
expect(inlineFrame()).not.toBe(before);
const posted = vi.spyOn(inlineFrame().contentWindow!, "postMessage").mockImplementation(() => {});
await act(async () => { inlineFrame().dispatchEvent(new Event("load")); });
// The new page starts with Point off, so it is told Point is still on before it gets the outlines.
expect(posted.mock.calls.map(([message]) => message)).toEqual([
{ jsonrpc: "2.0", method: "mausbot/point", params: { on: true } },
marksMessage(["main > section:nth-of-type(2) > button"]),
]);
});
it("shares the version on screen; the card the server patches shows the link with Copy, opens it, and unpublishes it", async () => {
await render(row(payload()));
await click("Share", card());
await settle();
expect(posts("/app/publish")).toEqual([{ rev: 0, visibility: "public" }]);
await render(row(payload(), LIVE));
expect(card().querySelector("[data-page-link]")?.textContent).toContain(LINK);
expect(button("Copy link", card())).toBeDefined();
expect(button("Open in new tab", card()).disabled).toBe(false);
await click("Open in new tab", card());
expect(openExternal).toHaveBeenCalledWith(LINK);
await click("Update link", card());
await settle();
expect(card().querySelector("[data-page-link]")?.textContent).toContain("Updated at the same link");
await click("Unpublish", card());
await settle();
expect(fetchMock.mock.calls.some(([path, init]) => path === `/api/published-pages/${LIVE.pageId}/unpublish` && init?.method === "POST")).toBe(true);
await render(row(payload(), { ...LIVE, state: "unpublished" }));
expect(card().querySelector("[data-page-link]")).toBeNull();
expect(card().textContent).toContain("Unpublished. The link no longer opens.");
expect(button("Open in new tab", card()).disabled).toBe(true);
});
it("chooses only you before sharing, and shares it that way", async () => {
await render(row(payload()));
await click("Anyone with the link", card());
expect(button("Only you", card()).getAttribute("aria-pressed")).toBe("true");
await click("Share", card());
await settle();
expect(posts("/app/publish")).toEqual([{ rev: 0, visibility: "owner" }]);
});
it("switches a published page between anyone with the link and only you", async () => {
await render(row(payload(), LIVE));
const chip = () => card().querySelector<HTMLElement>("[data-page-visibility]")!;
expect(chip().textContent).toContain("Anyone with the link");
expect(chip().getAttribute("aria-pressed")).toBe("false");
await click("Anyone with the link", card());
await settle();
expect(posts("/app/publish")).toEqual([{ rev: 0, visibility: "owner" }]);
expect(chip().textContent).toContain("Only you");
expect(chip().getAttribute("aria-pressed")).toBe("true");
await render(row(payload(), OWNER));
expect(card().querySelector("[data-page-link]")?.textContent).toContain("Published for you");
await click("Only you", card());
await settle();
expect(posts("/app/publish")).toEqual([{ rev: 0, visibility: "owner" }, { rev: 0, visibility: "public" }]);
});
it("shows publish_page's link on the page it published", async () => {
await render(row(payload(), LIVE));
expect(card().querySelector("[data-page-link]")?.textContent).toContain("Published");
expect(button("Open in new tab", card()).disabled).toBe(false);
expect(fetchMock.mock.calls.some(([path]) => path.includes("/publish"))).toBe(false);
});
it("opens Full screen over the chat, points there too, and closes on Escape or when Point ends after a pick", async () => {
await render(row(payload()));
await click("Full screen", card());
expect(overlay()?.getAttribute("role")).toBe("dialog");
expect(wideFrame().style.height).toBe("100%");
expect(card().querySelector("iframe")).toBeNull();
await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); });
expect(overlay()).toBeNull();
await settle();
expect(inlineFrame()).toBeTruthy();
await click("Full screen", card());
vi.spyOn(wideFrame().contentWindow!, "postMessage").mockImplementation(() => {});
await click("Point", overlay()!);
await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); });
expect(overlay()).not.toBeNull();
await click("Point", overlay()!);
await fromFrame(PICK, wideFrame().contentWindow);
expect(chips()).toHaveLength(1);
expect(overlay()).not.toBeNull();
await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); });
expect(overlay()).toBeNull();
});
it("pins the page to the sidebar and unpins it, only in Advanced mode, where pinned panels show", async () => {
setWebPanels([]);
setAdvancedMode(false);
await render(row(payload()));
expect(card().querySelector("[data-page-pin]")).toBeNull();
act(() => setAdvancedMode(true));
await click("Pin to sidebar", card());
expect(JSON.parse(localStorage.getItem("omb-web-panels")!)).toEqual([
{ id: "panel-1", name: "Pricing", page: { botId: "pepper", threadId: "t1", messageId: "a1" } },
]);
expect(button("Unpin", card()).getAttribute("aria-pressed")).toBe("true");
await click("Unpin", card());
expect(JSON.parse(localStorage.getItem("omb-web-panels")!)).toEqual([]);
act(() => setWebPanels(Array.from({ length: MAX_WEB_PANELS }, (_, i) => ({ id: `p${i}`, name: `P${i}`, url: `https://p${i}.example/` }))));
expect(button("Pin to sidebar", card()).disabled).toBe(true);
expect(card().querySelector("[data-page-pin-full]")?.textContent).toContain(`maximum of ${MAX_WEB_PANELS} pages`);
act(() => { setWebPanels([]); setAdvancedMode(false); });
});
it("keeps a page another window pinned a moment ago when this one pins", async () => {
setWebPanels([]);
setAdvancedMode(true);
await render(row(payload()));
// Another window's write whose storage event hasn't arrived yet.
localStorage.setItem("omb-web-panels", JSON.stringify([{ id: "panel-9", name: "Other", url: "https://other.example/" }]));
await click("Pin to sidebar", card());
expect(JSON.parse(localStorage.getItem("omb-web-panels")!).map((panel: { name: string }) => panel.name)).toEqual(["Other", "Pricing"]);
// The other window unpins everything; Unpin here must not pin the page again.
localStorage.setItem("omb-web-panels", "[]");
await click("Unpin", card());
expect(localStorage.getItem("omb-web-panels")).toBe("[]");
act(() => { setWebPanels([]); setAdvancedMode(false); });
});
it("gives an MCP app none of a page's tools", async () => {
await render(row(payload({ source: "mcp", mcp: { server: "excalidraw", tool: "create_view", resourceUri: "ui://excalidraw/app.html" } })));
expect(card().querySelector("[data-page-tools]")).toBeNull();
expect(card().querySelector("[data-page-link]")).toBeNull();
});
});
describe("pointed chips", () => {
const chip = (selector: string) => ({ appId: "a1", rev: 0, title: "Pricing", tag: "div", role: "", text: selector, selector, html: "<div></div>" });
it("keep one chip per part, refuse a part past the limit, and go with one send or come back when it fails", () => {
for (const selector of ["a", "b", "a"]) addPointedChip("t1", chip(selector));
expect(takePointedChips("t2")).toBeNull();
const taken = takePointedChips("t1")!;
expect(taken.pointed.map((element) => element.selector)).toEqual(["a", "b"]);
expect(taken.pointed[0]).not.toHaveProperty("title");
expect(takePointedChips("t1")).toBeNull();
taken.restore();
expect(takePointedChips("t1")!.pointed).toHaveLength(2);
const added = Array.from({ length: POINT_LIMITS.perMessage + 2 }, (_, n) => addPointedChip("t1", chip(`s${n}`)));
expect(POINT_LIMITS.perMessage).toBeGreaterThanOrEqual(20);
expect(added.filter(Boolean)).toHaveLength(POINT_LIMITS.perMessage);
expect(added.slice(-2)).toEqual([false, false]);
const kept = takePointedChips("t1")!.pointed.map((element) => element.selector);
expect(kept).toHaveLength(POINT_LIMITS.perMessage);
expect(kept[0]).toBe("s0");
});
it("carry the person's note on a part, trimmed and clipped, and keep it when the same part is picked again", () => {
for (const selector of ["a", "b"]) addPointedChip("t1", chip(selector));
act(() => root.render(createElement(PointedChips, { threadId: "t1" })));
expect(Array.from(host.querySelectorAll("[data-pointed-chip]"), (each) => each.textContent)).toEqual(["1“a”<div>", "2“b”<div>"]);
act(() => button("Write a note on “b”", host).click());
const input = host.querySelector<HTMLInputElement>("[data-pointed-note]")!;
expect(input.getAttribute("aria-label")).toBe("Note on “b” for the bot (optional)");
act(() => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, ` make it bolder ${"x".repeat(POINT_LIMITS.note)}`);
input.dispatchEvent(new Event("input", { bubbles: true }));
});
act(() => { input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); });
expect(host.querySelector("[data-pointed-note]")).toBeNull();
addPointedChip("t1", { ...chip("b"), rev: 1 });
const taken = takePointedChips("t1")!.pointed;
expect(taken.map((element) => [element.selector, element.rev])).toEqual([["a", 0], ["b", 1]]);
expect(taken[0]).not.toHaveProperty("note");
expect(taken[1]!.note!.startsWith("make it bolder x")).toBe(true);
expect(Array.from(taken[1]!.note!).length).toBeLessThanOrEqual(POINT_LIMITS.note);
setPointedNote("t1", "no-such-chip", "ignored");
});
});