Skip to content

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

2.1 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 } from "vitest";

import { optimisticUserMessage } from "@/state/optimistic-send";
import type { Message } from "@/state/store";
import { useAwaitingTurn } from "./use-awaiting-turn";

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

const seen: boolean[] = [];
function Probe({ threadId, last, busy }: { threadId: string; last: Message | undefined; busy: boolean }) {
  seen.push(useAwaitingTurn(threadId, last, busy));
  return null;
}
let root: Root;
const show = (last: Message | undefined, busy = false, threadId = "t") => act(() => root.render(createElement(Probe, { threadId, last, busy })));
const now = () => seen.at(-1);
const sent = optimisticUserMessage("hi", "s1");
const copy: Message = { ...sent, id: "server-1" };
const reply: Message = { id: "r1", role: "bot", kind: "text", at: 2, text: "ok" };

beforeEach(() => {
  seen.length = 0;
  root = createRoot(document.createElement("div"));
});
afterEach(() => act(() => root.unmount()));

describe("useAwaitingTurn", () => {
  it("waits from the send through its server copy until the bot is seen busy, then never again for that send", () => {
    show(sent);
    expect(now()).toBe(true);
    show(copy);
    expect(now(), "the reply's copy lands before the busy frame").toBe(true);
    show(copy, true);
    expect(now()).toBe(false);
    show(copy, false);
    expect(now(), "a turn that ended with no row after the send").toBe(false);
  });

  it("ends when a row follows the send, the send is taken back, or another conversation opens", () => {
    show(sent);
    show(reply);
    expect(now()).toBe(false);
    show(copy);
    expect(now()).toBe(false);
    show(sent);
    show(undefined);
    expect(now()).toBe(false);
    show(sent);
    show(copy, false, "other");
    expect(now()).toBe(false);
  });

  it("never waits for an old message of the person's that it did not see sent", () => {
    show(copy);
    expect(now()).toBe(false);
  });
});