Skip to content

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

2.5 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 { SWITCH_HOLD_MS, useSwitchHold } from "./use-switch-hold";

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

type Chat = { id: string; threadId: string; switchingTo?: string };
let bots: Chat[] = [];
const drawn: string[] = [];
function Pane({ selected }: { selected: Chat | undefined }) {
  const shown = useSwitchHold(selected, (id) => bots.find((bot) => bot.id === id));
  drawn.push(shown ? `${shown.id}:${shown.threadId}` : "none");
  return null;
}

let root: Root;
const show = (selected: Chat | undefined) => act(() => root.render(createElement(Pane, { selected })));
const last = () => drawn.at(-1);

beforeEach(() => {
  vi.useFakeTimers();
  drawn.length = 0;
  bots = [{ id: "a", threadId: "a-1" }, { id: "b", threadId: "b-1" }];
  root = createRoot(document.createElement("div"));
});
afterEach(() => {
  act(() => root.unmount());
  vi.useRealTimers();
});

describe("useSwitchHold", () => {
  it("keeps the chat on screen while another bot's conversation is read, then draws the one asked for", () => {
    show(bots[0]);
    show({ ...bots[1]!, switchingTo: "b-2" });
    expect(drawn).toEqual(["a:a-1", "a:a-1"]);
    // The held chat is read live.
    bots[0] = { ...bots[0]!, threadId: "a-1" };
    show({ id: "b", threadId: "b-2" });
    expect(last()).toBe("b:b-2");
    expect(drawn).not.toContain("b:b-1");
  });

  it("holds no longer than its limit, then draws the selected bot as it is", () => {
    show(bots[0]);
    show({ ...bots[1]!, switchingTo: "b-2" });
    act(() => void vi.advanceTimersByTime(SWITCH_HOLD_MS - 1));
    expect(last()).toBe("a:a-1");
    act(() => void vi.advanceTimersByTime(1));
    expect(last()).toBe("b:b-1");
    show({ id: "b", threadId: "b-2" });
    expect(last()).toBe("b:b-2");
    // The next switch to that conversation holds again.
    show(bots[0]);
    show({ ...bots[1]!, switchingTo: "b-2" });
    expect(last()).toBe("a:a-1");
  });

  it("holds nothing for a switch within the chat on screen, a switch already held, or a first draw", () => {
    show({ ...bots[0]!, switchingTo: "a-2" });
    expect(last()).toBe("a:a-1");
    show(undefined);
    show({ ...bots[1]!, switchingTo: "b-2" });
    expect(last()).toBe("b:b-1");
    show({ ...bots[0]!, switchingTo: "a-1" });
    expect(last()).toBe("a:a-1");
  });
});