Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

8.5 KB
Raw Blame
// @vitest-environment happy-dom
// The real provider and two chats the app holds: a switch draws them at their end with no entrance replayed, and a send
// is one row from Enter to the server's copy, its status line drawn with it.
import { act, createElement } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import type { BotAnnouncement, InstanceInfo, Message } from "@/state/store";

vi.mock("./DesktopCapabilities", async (importOriginal) => ({
  ...await importOriginal<typeof import("./DesktopCapabilities")>(),
  useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),
}));
vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
const painted = vi.hoisted(() => [] as (() => void)[]);
vi.mock("@/lib/after-paint", () => ({ afterPaint: (callback: () => void) => {
  painted.push(callback);
  return () => {
    const at = painted.indexOf(callback);
    if (at >= 0) painted.splice(at, 1);
  };
} }));
vi.mock("@/lib/cloud-guest", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/cloud-guest")>(), useReactor: () => "user" }));
vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => false, setAdvancedMode: vi.fn() }));

class FixtureEventSource {
  static opened: FixtureEventSource[] = [];
  onopen: (() => void) | null = null;
  onerror: (() => void) | null = null;
  onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;
  constructor(readonly url: string) { FixtureEventSource.opened.push(this); }
  close() {}
  send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }
}

const announced = (id: string, name: string): BotAnnouncement => ({
  id, threadId: `${id}-thread`, name, title: "", description: "", notifications: true, unread: false, color: "green",
  modelSelection: { instanceId: "test", model: "m" }, tasks: [{ threadId: `${id}-thread`, title: "Chat", createdAt: 1, approvalMode: "ask" }],
});
const start = Date.UTC(2026, 10, 1, 9);
function transcript(bot: string): Message[] {
  const rows: Message[] = [];
  for (let turn = 0; turn < 12; turn++) {
    const at = start + turn * 600_000;
    rows.push({ id: `${bot}-ask-${turn}`, role: "user", kind: "text", at, text: `Question ${turn}`, sendId: `${bot}-send-${turn}` });
    rows.push({ id: `${bot}-answer-${turn}`, role: "bot", kind: "text", at: at + 9_000, turnTerminal: true, text: `Answer ${turn}` });
  }
  return rows;
}
const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));
const answers: Record<string, unknown> = {
  "/api/instances": { instances: [{ instanceId: "test", driverKind: "codex", displayName: "Test", snapshot: { state: "available" }, models: { options: [{ id: "m", label: "Model" }] } } as unknown as InstanceInfo] },
  "/api/config": { features: { showToolCalls: true } },
  "/api/routines": { routines: [], runs: [] },
  "/api/webhooks": { webhooks: [], attempts: [] },
};

const { StoreProvider, useStore } = await import("@/state/store");
const { useStoreSelector } = await import("@/state/store-select");
const { ChatView } = await import("./ChatView");

let dispatch!: ReturnType<typeof useStore>["dispatch"];
function Shown() {
  dispatch = useStore().dispatch;
  return null;
}
function Shell() {
  const bot = useStoreSelector((state) => state.bots.find((candidate) => candidate.id === state.selectedId));
  return bot ? createElement(ChatView, { bot }) : null;
}

let root: Root;
const task = () => new Promise((resolve) => setTimeout(resolve, 0));
const settle = async () => { for (let i = 0; i < 6; i++) await task(); };
const frames = async () => { for (let i = 0; i < 4; i++) { await new Promise((resolve) => requestAnimationFrame(resolve)); await settle(); } };
async function paint() {
  const flag = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
  flag.IS_REACT_ACT_ENVIRONMENT = true;
  try {
    await act(async () => { for (const run of painted.splice(0)) run(); });
  } finally {
    flag.IS_REACT_ACT_ENVIRONMENT = false;
  }
}
let answerSend: (body: unknown) => void = () => {};
const scroller = () => document.querySelector<HTMLElement>(".glass-scroller")!;
const bubbles = () => [...document.querySelectorAll<HTMLElement>('[role="log"] [data-look="message-user"]')];
const bubbleOf = (id: string) => document.querySelector<HTMLElement>(`[data-mid="${id}"] [data-look="message-user"]`);

beforeAll(async () => {
  const isScroller = (el: Element) => el.classList.contains("glass-scroller");
  Object.defineProperty(HTMLElement.prototype, "clientHeight", { configurable: true, get() { return isScroller(this) ? 900 : 0; } });
  Object.defineProperty(HTMLElement.prototype, "scrollHeight", { configurable: true, get() { return isScroller(this) ? 120 * this.querySelectorAll("[data-mid]").length : 0; } });
  vi.stubGlobal("EventSource", FixtureEventSource);
  // A send's POST is answered when the test says, as the server's reply lands before its live frames.
  vi.stubGlobal("fetch", (path: string, init?: RequestInit) => path.startsWith("/api/bots?")
    ? json({ bots: [{ ...announced("a", "Ada"), messages: transcript("a") }, { ...announced("b", "Bea"), messages: transcript("b") }], groups: [] })
    : init?.method === "POST" && path.endsWith("/messages") ? new Promise<Response>((done) => { answerSend = (body) => done(new Response(JSON.stringify(body), { status: 202 })); })
    : json(answers[path.replace(/\?.*$/, "")] ?? {}));
  const container = document.createElement("div");
  document.body.append(container);
  root = createRoot(container);
  flushSync(() => root.render(createElement(StoreProvider, null, createElement(Shown), createElement(Shell))));
  await settle();
  FixtureEventSource.opened[0]!.send({ kind: "hello", resumed: false, cursor: "run:0" });
  await settle();
  flushSync(() => dispatch({ type: "select", id: "a" }));
  await paint();
  await frames();
});
afterAll(() => {
  flushSync(() => root.unmount());
  vi.unstubAllGlobals();
});

describe("a switch to a chat the app holds", () => {
  it("draws it at its end, with the person's messages already in place, in the click's commit", async () => {
    flushSync(() => dispatch({ type: "select", id: "b" }));
    expect(bubbles().length).toBeGreaterThan(0);
    expect(bubbleOf("b-ask-11")).not.toBeNull();
    expect(scroller().scrollTop, "at the end before the paint").toBe(scroller().scrollHeight);
    for (const bubble of bubbles()) expect(bubble.className, bubble.closest("[data-mid]")?.getAttribute("data-mid") ?? "").not.toContain("animate-msg-in");
    await paint();
    await frames();
    for (const bubble of bubbles()) expect(bubble.className).not.toContain("animate-msg-in");
  });
});

describe("a send", () => {
  it("is one row from Enter to the server's copy, entering once, with its status line from the start", async () => {
    flushSync(() => dispatch({ type: "send", botId: "b", threadId: "b-thread", text: "One more thing", sendId: "feel-1" }));
    const sent = bubbleOf("optimistic-feel-1");
    expect(sent).not.toBeNull();
    expect(sent!.className).toContain("animate-msg-in");
    const presence = () => document.querySelector('[role="log"] .turn-presence');
    expect(presence(), "the status line arrives with the bubble").not.toBeNull();
    // The send's reply carries the server's copy before any live frame says the bot is busy.
    const copy = { id: "server-feel-1", role: "user", kind: "text", at: Date.now(), text: "One more thing", sendId: "feel-1", parentId: "b-answer-11" };
    await settle();
    answerSend({ ok: true, threadId: "b-thread", message: copy });
    await frames();
    expect(bubbleOf("optimistic-feel-1")).toBeNull();
    expect(bubbleOf("server-feel-1"), "the same element, not a new row replaying its entrance").toBe(sent);
    expect(presence(), "the status line holds until the bot is busy").not.toBeNull();
    expect(document.querySelector('[role="log"] .turn-mascot-out'), "and does not start to leave").toBeNull();
    expect(document.querySelector('[role="log"] [data-turn-status]')).not.toBeNull();
    FixtureEventSource.opened[0]!.send({ kind: "bot", bot: { ...announced("b", "Bea"), busy: true, activity: "working", turnStartedAt: Date.now() } });
    FixtureEventSource.opened[0]!.send({ kind: "message", threadId: "b-thread", message: copy });
    await frames();
    expect(bubbleOf("server-feel-1")).toBe(sent);
    expect(document.querySelector('[role="log"] .turn-mascot-out')).toBeNull();
    expect(presence()).not.toBeNull();
  });
});