Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
import { createElement, type ReactElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BotEditorStore, initialState, StoreProvider, type AppState, type Bot } from "@/state/store";
import { endCall } from "@/lib/call";
import { configureLiveMedia, resetLiveMedia, startLiveCall } from "@/lib/live-call-media";
import { LiveCallBar } from "./LiveCallBar";
import { LiveCallSettings } from "./LiveCallSettings";
import { LiveKeySetup } from "./LiveKeySetup";
import type { LiveSettings } from "../../shared/wire";
const mode = vi.hoisted(() => ({ advanced: false }));
vi.mock("@/lib/interface-mode", async (importOriginal) => ({
...await importOriginal<typeof import("@/lib/interface-mode")>(),
useAdvancedMode: () => mode.advanced,
}));
const bot: Bot = {
id: "atlas",
threadId: "thread-atlas",
name: "Atlas",
title: "",
description: "",
notifications: true,
color: "green",
unread: false,
modelSelection: { instanceId: "claude", model: "test" },
messages: [],
};
const render = (element: ReturnType<typeof createElement>) =>
renderToStaticMarkup(createElement(StoreProvider, null, element));
const renderOnCloud = (element: ReturnType<typeof createElement>) => {
const config = { cloudHome: true, live: { configured: true, voice: "marin", readTypedReplies: true, idleMinutes: 5 } } as AppState["config"];
const value = { state: { ...initialState, config }, dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
return renderToStaticMarkup(createElement(BotEditorStore, { value, children: element }));
};
const CLOUD_DISCLOSURE = `A Live call sends your voice to OpenAI, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. The OpenAI key stays in the Cloud.`;
afterEach(() => {
mode.advanced = false;
resetLiveMedia();
endCall();
vi.unstubAllGlobals();
});
describe("LiveCallBar", () => {
it("renders nothing without a call", () => {
expect(render(createElement(LiveCallBar, { bot }))).toBe("");
});
it("shows the hint when the window blocked the call's audio", async () => {
vi.stubGlobal("window", { ogb: { speechStop: vi.fn(async () => {}) } });
const track = { enabled: true, stop: () => {} };
const peer = {
ontrack: null as ((event: { track: unknown }) => void) | null,
localDescription: { sdp: "v=0\r\n" },
iceGatheringState: "complete",
addTrack: () => {},
createDataChannel: () => ({ readyState: "connecting", close: () => {} }),
createOffer: async () => ({ type: "offer", sdp: "v=0\r\n" }),
setLocalDescription: async () => {},
close: () => {},
};
configureLiveMedia({
getUserMedia: async () => ({ getTracks: () => [track], getAudioTracks: () => [track] }) as unknown as MediaStream,
createPeer: () => peer as unknown as RTCPeerConnection,
request: () => new Promise(() => {}),
playRemote: async () => { throw new Error("autoplay blocked"); },
});
void startLiveCall({ botId: bot.id, threadId: bot.threadId });
await vi.waitFor(() => expect(peer.ontrack).not.toBeNull());
peer.ontrack!({ track: {} });
await vi.waitFor(() => expect(render(createElement(LiveCallBar, { bot }))).toContain("Click anywhere in the window to hear the call."));
});
it("shows the call's controls while this window connects", () => {
vi.stubGlobal("window", { ogb: { speechStop: vi.fn(async () => {}) } });
configureLiveMedia({ getUserMedia: () => new Promise<MediaStream>(() => {}) });
void startLiveCall({ botId: bot.id, threadId: bot.threadId });
const markup = render(createElement(LiveCallBar, { bot }));
expect(markup).toContain("Live with Atlas · Connecting…");
expect(markup).toContain('aria-label="Call settings"');
expect(markup).toContain('aria-label="Mute"');
expect(markup).toContain('aria-label="Hang up"');
});
it("takes clicks itself, inside the composer dock that lets them through", () => {
vi.stubGlobal("window", { ogb: { speechStop: vi.fn(async () => {}) } });
configureLiveMedia({ getUserMedia: () => new Promise<MediaStream>(() => {}) });
void startLiveCall({ botId: bot.id, threadId: bot.threadId });
const markup = render(createElement(LiveCallBar, { bot }));
expect(markup).toMatch(/^<div role="region"[^>]* class="pointer-events-auto /);
});
it.each([
["refused", "The app didn't let this page use the microphone. Open it in your web browser to make the Live call.", "Open in browser", "Try again"],
["allowed", "Allow microphone access for this app in your computer's privacy settings, then try again.", "Try again", "Open in browser"],
] as const)("shows a microphone the app %s with its one action", async (pageMic, text, action, other) => {
vi.stubGlobal("window", { ogb: { speechStop: vi.fn(async () => {}) } });
configureLiveMedia({
getUserMedia: async () => { throw new DOMException("denied", "NotAllowedError"); },
capabilities: () => ({ dictation: { available: false, engine: "none", onDevice: false, reasonCode: "remote-server" } }) as DesktopCapabilities,
pageMicrophone: async () => pageMic,
});
await startLiveCall({ botId: bot.id, threadId: bot.threadId });
const markup = render(createElement(LiveCallBar, { bot }));
expect(markup).toContain(text);
expect(markup).toContain(`aria-label="${action}"`);
expect(markup).not.toContain(`aria-label="${other}"`);
});
it("offers Open System Settings with a microphone this computer refused", async () => {
const permOpenSettings = vi.fn(async () => {});
vi.stubGlobal("window", { ogb: { speechStop: vi.fn(async () => {}), permOpenSettings } });
configureLiveMedia({
getUserMedia: async () => { throw new DOMException("denied", "NotAllowedError"); },
capabilities: () => ({ dictation: { available: true, engine: "none", onDevice: false } }) as unknown as DesktopCapabilities,
pageMicrophone: async () => undefined,
});
await startLiveCall({ botId: bot.id, threadId: bot.threadId });
const markup = render(createElement(LiveCallBar, { bot }));
expect(markup).toContain('data-open-system-settings="mic"');
expect(markup).toContain("Open System Settings");
});
it("names the keyboard chords on the mute and hang-up buttons", () => {
vi.stubGlobal("window", { ogb: { platform: "darwin", speechStop: vi.fn(async () => {}) } });
configureLiveMedia({ getUserMedia: () => new Promise<MediaStream>(() => {}) });
void startLiveCall({ botId: bot.id, threadId: bot.threadId });
const markup = render(createElement(LiveCallBar, { bot }));
expect(markup).toContain('title="Mute (⌘⇧M)"');
expect(markup).toContain('aria-keyshortcuts="Meta+Shift+M"');
expect(markup).toContain('title="Hang up (⌘⇧H)"');
expect(markup).toContain('aria-keyshortcuts="Meta+Shift+H"');
});
});
describe("LiveCallSettings", () => {
it("offers voice, typed replies, idle minutes and the key, defaulting to 5 minutes", () => {
const markup = render(createElement(LiveCallSettings, { onClose: vi.fn() }));
expect(markup).toContain('aria-label="Call settings"');
expect(markup).toContain("Marin (default)");
expect(markup).toContain("Read replies to typed messages");
expect(markup).not.toContain("standby");
expect(markup).toContain(`When this is off, messages you type during a call and the bot's answers to them are not sent to OpenAI.`);
expect(markup).toContain(`A Live call sends your voice to OpenAI, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. The OpenAI key stays on your computer.`);
expect(markup).toMatch(/<option value="5" selected="">5<\/option>/);
expect(markup).toContain("Change key");
expect(markup).not.toContain("Remove key");
expect(markup).toMatch(/role="dialog" tabindex="-1"/);
});
it("says which key Live calls use, and removes only a separate Live key", () => {
const withLive = (live: LiveSettings) => {
const value = { state: { ...initialState, config: { live } as AppState["config"] }, dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
return renderToStaticMarkup(createElement(BotEditorStore, { value, children: createElement(LiveCallSettings, { onClose: vi.fn() }) }));
};
const base = { voice: "marin", readTypedReplies: true, idleMinutes: 5 };
const fromApiKeys = withLive({ ...base, configured: true, keySource: "openai" });
expect(fromApiKeys).toContain("Uses your OpenAI API key from Settings → AI → Other services.");
expect(fromApiKeys).not.toContain("Remove key");
const own = withLive({ ...base, configured: true, keySource: "live" });
expect(own).toContain("Remove key");
expect(own).not.toContain("Settings → API keys");
const none = withLive({ ...base, configured: false });
expect(none).toContain("Live calls use your own OpenAI key. Add it in Settings → AI → Other services.");
expect(none).not.toContain("Remove key");
});
it("offers Gemini's own voices for Gemini calls, not GPT-Live's", () => {
const withLive = (live: LiveSettings) => {
const value = { state: { ...initialState, config: { live } as AppState["config"] }, dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
return renderToStaticMarkup(createElement(BotEditorStore, { value, children: createElement(LiveCallSettings, { onClose: vi.fn() }) }));
};
const base = { configured: true, provider: "gemini" as const, keySource: "gemini" as const, voice: "marin", readTypedReplies: true, idleMinutes: 5 };
const plain = withLive(base);
expect(plain).toMatch(/<option value="Puck" selected="">Puck — upbeat \(default\)<\/option>/);
expect(plain).toContain("Charon — informative");
expect(plain).not.toContain("Marin (default)");
expect(plain).not.toContain("gemini-3.8-live");
expect(withLive({ ...base, geminiVoice: "Kore" })).toMatch(/<option value="Kore" selected="">/);
});
it("offers the bot on the call a voice of its own beside the default for every other bot", () => {
const withBot = (liveVoice?: string) => render(createElement(LiveCallSettings, { bot: { id: "atlas", name: "Atlas", liveVoice }, onClose: vi.fn() }));
const unset = withBot();
expect(unset).toContain("Voice for Atlas");
expect(unset).toContain("Default voice");
expect(unset).toMatch(/<option value="" selected="">Same as the default<\/option>/);
expect(withBot("cedar")).toMatch(/<option value="cedar" selected="">/);
expect(withBot("Kore")).toMatch(/<option value="" selected="">Same as the default<\/option>/);
const plain = render(createElement(LiveCallSettings, { onClose: vi.fn() }));
expect(plain).not.toContain("Voice for");
expect(plain).not.toContain("Default voice");
});
it("says the key stays on the Cloud when the chat is on the person's Cloud", () => {
const markup = renderOnCloud(createElement(LiveCallSettings, { onClose: vi.fn() }));
expect(markup).toContain(CLOUD_DISCLOSURE);
expect(markup).not.toContain("stays on your computer");
});
it("takes focus when it opens, so Escape closes it", () => {
const onClose = vi.fn();
let tree!: ReactElement<{ ref: (node: unknown) => void; onKeyDown: (event: unknown) => void }>;
function Capture() {
tree = LiveCallSettings({ onClose }) as typeof tree;
return tree;
}
render(createElement(Capture));
const first = { focus: vi.fn() };
const querySelector = vi.fn(() => first);
tree.props.ref({ querySelector });
expect(querySelector).toHaveBeenCalledWith("select, input, button");
expect(first.focus).toHaveBeenCalledOnce();
const stopPropagation = vi.fn();
tree.props.onKeyDown({ key: "Escape", stopPropagation });
expect(onClose).toHaveBeenCalledOnce();
expect(stopPropagation).toHaveBeenCalledOnce();
});
});
describe("LiveKeySetup", () => {
it("says what the key is for, in the app's language", () => {
const markup = render(createElement(LiveKeySetup, { onSaved: vi.fn() }));
expect(markup).toContain("Live calls use OpenAI GPT-Live");
expect(markup).toContain(`A Live call sends your voice to OpenAI, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. The OpenAI key stays on your computer.`);
expect(markup).toContain('aria-label="OpenAI API key for Live calls"');
expect(markup).toContain("Save and start the call");
expect(render(createElement(LiveKeySetup, { onSaved: vi.fn(), compact: true }))).toContain(">Save<");
});
it("says the key stays on the Cloud when the chat is on the person's Cloud", () => {
const markup = renderOnCloud(createElement(LiveKeySetup, { onSaved: vi.fn() }));
expect(markup).toContain(CLOUD_DISCLOSURE);
expect(markup).not.toContain("stays on your computer");
});
});
describe("LiveCallSettings history limits", () => {
function renderWithLive(live: LiveSettings) {
const config = { cloudHome: false, live } as AppState["config"];
const value = { state: { ...initialState, config }, dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
return renderToStaticMarkup(createElement(BotEditorStore, { value, children: createElement(LiveCallSettings, { onClose: vi.fn() }) }));
}
it("keeps the history limits in Advanced mode", () => {
const simple = renderWithLive({ configured: true, provider: "openai", voice: "marin", readTypedReplies: true, idleMinutes: 5 });
expect(simple).not.toContain("Chat messages a call starts with");
expect(simple).not.toContain("Characters per message");
});
it("shows configurable history selects capped by the active provider", () => {
mode.advanced = true;
const openai = renderWithLive({ configured: true, provider: "openai", voice: "marin", readTypedReplies: true, idleMinutes: 5 });
expect(openai).toContain("Chat messages a call starts with");
expect(openai).toContain("Characters per message");
expect(openai).toContain("Characters in all");
const messagesSelect = /Chat messages a call starts with[\s\S]*?<select[\s\S]*?<\/select>/.exec(openai)?.[0] ?? "";
expect(messagesSelect).toContain('value="128"');
expect(messagesSelect).not.toContain('value="200"');
expect(messagesSelect).toMatch(/<option value="8" selected="">8<\/option>/);
const totalSelect = /Characters in all[\s\S]*?<select[\s\S]*?<\/select>/.exec(openai)?.[0] ?? "";
expect(totalSelect).toMatch(/<option value="6000" selected="">/);
expect(totalSelect).not.toContain('value="12000"');
const gemini = renderWithLive({ configured: true, provider: "gemini", voice: "marin", readTypedReplies: true, idleMinutes: 5, historyMessages: 200, historyMessageChars: 12_000, historyTotalChars: 60_000 });
const geminiMessagesSelect = /Chat messages a call starts with[\s\S]*?<select[\s\S]*?<\/select>/.exec(gemini)?.[0] ?? "";
expect(geminiMessagesSelect).toContain('value="200"');
expect(gemini).toContain('value="60000"');
});
});