Skip to content

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

8.3 KB
Raw Blame
// @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 { RuntimeEvent } from "../../shared/runtime-events";
import { noteLiveReplyEvent, resetLiveReplies, stopLiveReply, useLiveRow } from "./live-reply";
import type { Message } from "@/state/store";

(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

let seq = 0;
let frames = new Map<number, FrameRequestCallback>();
let nextFrame = 1;
let clock = 0;
let renders: Record<string, string[]> = {};
let roots: Root[] = [];

beforeEach(() => {
  frames = new Map();
  nextFrame = 1;
  clock = 0;
  renders = {};
  vi.spyOn(performance, "now").mockImplementation(() => clock);
  vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
    frames.set(nextFrame, callback);
    return nextFrame++;
  });
  vi.stubGlobal("cancelAnimationFrame", (id: number) => void frames.delete(id));
});

afterEach(() => {
  for (const root of roots) act(() => root.unmount());
  roots = [];
  resetLiveReplies();
  vi.restoreAllMocks();
  vi.unstubAllGlobals();
  document.body.innerHTML = "";
});

const delta = (text: string, item = "i1", threadId = "t") => act(() => noteLiveReplyEvent({
  eventId: `e${++seq}`, provider: "claudeAgent", threadId, createdAt: "", turnId: "turn", itemId: item,
  type: "content.delta", streamKind: "assistant_text", delta: text,
} as RuntimeEvent));
const complete = (text: string, item = "i1", threadId = "t") => act(() => noteLiveReplyEvent({
  eventId: `e${++seq}`, provider: "claudeAgent", threadId, createdAt: "", turnId: "turn", itemId: item,
  type: "item.completed", itemType: "assistant_text", text,
} as RuntimeEvent));
const frame = (ms = 1000 / 60) => act(() => {
  clock += ms;
  const batch = [...frames.values()];
  frames.clear();
  for (const callback of batch) callback(clock);
});
const drain = () => {
  for (let i = 0; i < 300 && frames.size; i++) frame();
};

function Row({ id, threadId, label }: { id: string; threadId: string; label: string }) {
  const message = useLiveRow(threadId, { id, role: "bot", kind: "text", text: "", at: 0 } as Message);
  (renders[label] ??= []).push(message.text ?? "");
  return null;
}
function mountRows(rows: Array<{ id: string; threadId?: string; label: string }>) {
  const host = document.createElement("div");
  document.body.appendChild(host);
  const root = createRoot(host);
  roots.push(root);
  const draw = () => act(() => root.render(rows.map((row) => createElement(Row, { key: row.label, threadId: "t", ...row }))));
  draw();
  return { root, draw };
}
const live = (item = "i1") => `live:${item}`;
const last = (label: string) => renders[label]!.at(-1)!;
const loneSurrogate = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
const words = (count: number, from = 0) => Array.from({ length: count }, (_, i) => `word${from + i} `).join("");

describe("a live row drawing a streamed reply", () => {
  it("draws steady deltas as they come: one render each, and no frames of its own", () => {
    delta("Hello ");
    mountRows([{ id: live(), label: "live" }, { id: "m1", label: "settled" }]);
    const before = renders.live!.length;
    for (let i = 0; i < 120; i++) delta(`w${i} `);
    expect(renders.live!.length - before).toBe(120);
    expect(frames.size).toBe(0);
    expect(renders.settled!.length, "a settled row never draws again").toBe(1);
  });

  it("spreads a burst over frames on word boundaries, then goes back to one render per delta", () => {
    delta("Start ");
    mountRows([{ id: live(), label: "live" }, { id: "m1", label: "settled" }]);
    const burst = words(80);
    delta(burst);
    const full = `Start ${burst}`;
    expect(last("live").length, "part of the burst shows at once").toBeGreaterThan("Start ".length);
    expect(last("live").length).toBeLessThan(full.length);
    const during = renders.live!.length;
    drain();
    expect(last("live")).toBe(full);
    const shown = renders.live!.slice(during - 1);
    for (const text of shown) {
      expect(full.startsWith(text)).toBe(true);
      expect(text).toMatch(/\s$/);
    }
    expect(shown.length, "a few frames, not one per character").toBeLessThan(40);

    const settledBefore = renders.settled!.length;
    const afterBurst = renders.live!.length;
    for (let i = 0; i < 50; i++) delta(`s${i} `);
    expect(renders.live!.length - afterBurst, "drained: renders equal deltas").toBe(50);
    expect(frames.size).toBe(0);
    expect(renders.settled!.length).toBe(settledBefore);
  });

  it("asks for at most one frame at a time, however many rows are catching up", () => {
    delta("A ", "i1");
    delta("B ", "i2", "u");
    mountRows([{ id: live("i1"), label: "one" }, { id: live("i2"), threadId: "u", label: "two" }]);
    delta(words(60), "i1");
    delta(words(60), "i2", "u");
    expect(frames.size).toBe(1);
    frame();
    expect(frames.size).toBe(1);
    const oneAt = renders.one!.length, twoAt = renders.two!.length;
    frame();
    expect(renders.one!.length - oneAt).toBeLessThanOrEqual(2);
    expect(renders.two!.length - twoAt).toBeLessThanOrEqual(2);
    drain();
    expect(last("one")).toBe(`A ${words(60)}`);
    expect(last("two")).toBe(`B ${words(60)}`);
  });

  it("never splits a long token: with no space ahead it shows the whole of it", () => {
    delta("See ");
    mountRows([{ id: live(), label: "live" }]);
    const link = `[the docs](https://example.com/${"a".repeat(300)}) `;
    delta(`${link}and more `);
    drain();
    for (const text of renders.live!) {
      expect(text.includes("[the docs](") && !text.includes(link), `cut inside the link: ${text.slice(0, 40)}`).toBe(false);
    }
    expect(last("live")).toBe(`See ${link}and more `);
  });

  it("never splits an emoji or a joined sequence", () => {
    delta("Go ");
    mountRows([{ id: live(), label: "live" }]);
    const family = "\u{1F468}‍\u{1F469}‍\u{1F467}";
    const run = `${"\u{1F600}".repeat(60)} ${family.repeat(20)} ${"é".repeat(50)} ${"\u{1F44D}\u{1F3FD}".repeat(40)} `;
    delta(run);
    drain();
    for (const text of renders.live!) {
      expect(loneSurrogate.test(text)).toBe(false);
      expect(text === "Go " || text.endsWith(" ")).toBe(true);
    }
    expect(last("live")).toBe(`Go ${run}`);
  });

  it("shows everything at once when the reply ends mid-burst", () => {
    delta("Start ");
    mountRows([{ id: live(), label: "live" }]);
    delta(words(80));
    frame();
    complete(`Start ${words(80)}done`);
    expect(last("live")).toBe(`Start ${words(80)}done`);
    frame();
    expect(frames.size).toBe(0);
  });

  it("shows everything at once on Stop", () => {
    delta("Start ");
    mountRows([{ id: live(), label: "live" }]);
    delta(words(80));
    act(() => stopLiveReply("t"));
    expect(last("live")).toBe(`Start ${words(80)}`);
    frame();
    expect(frames.size).toBe(0);
  });

  it("stops asking for frames once its row is gone", () => {
    delta("Start ");
    const { root } = mountRows([{ id: live(), label: "live" }]);
    delta(words(80));
    act(() => root.unmount());
    roots = [];
    frame();
    expect(frames.size).toBe(0);
  });

  it("shows everything at once when the page is hidden, and paces nothing while hidden", () => {
    delta("Start ");
    mountRows([{ id: live(), label: "live" }]);
    delta(words(80));
    Object.defineProperty(document, "hidden", { configurable: true, get: () => true });
    frame();
    expect(last("live")).toBe(`Start ${words(80)}`);
    expect(frames.size).toBe(0);
    delta(words(80, 80));
    expect(last("live")).toBe(`Start ${words(160)}`);
    expect(frames.size).toBe(0);
    delete (document as { hidden?: boolean }).hidden;
  });

  it("shows what waited at once after a long gap between frames (a window in the background)", () => {
    delta("Start ");
    mountRows([{ id: live(), label: "live" }]);
    delta(words(80));
    frame(1_000);
    expect(last("live")).toBe(`Start ${words(80)}`);
    expect(frames.size).toBe(0);
  });

  it("paces nothing under reduced motion", () => {
    document.documentElement.dataset.reducedMotion = "true";
    try {
      delta("Start ");
      mountRows([{ id: live(), label: "live" }]);
      delta(words(80));
      expect(last("live")).toBe(`Start ${words(80)}`);
      expect(frames.size).toBe(0);
    } finally {
      delete document.documentElement.dataset.reducedMotion;
    }
  });
});