Skip to content

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

8.2 KB
Raw Blame
// @vitest-environment happy-dom
import { createElement, type ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Bot, Group, Message } from "@/state/store";

const fixture = vi.hoisted(() => ({ dispatch: vi.fn(), canWrite: true as boolean | null, config: null as { tts: { configured: boolean; ready: boolean; voice: string } } | null }));
vi.mock("@/state/store", async (importOriginal) => {
  const original = await importOriginal<typeof import("@/state/store")>();
  return { ...original, useStore: () => ({
    state: { ...original.initialState, bots: [] as Bot[], config: fixture.config as typeof original.initialState.config },
    dispatch: fixture.dispatch,
  }) };
});
vi.mock("./DesktopCapabilities", async (importOriginal) => ({
  ...await importOriginal<typeof import("./DesktopCapabilities")>(),
  useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false, reasonCode: "x", message: "" } }, ready: true }),
  useCaptionChrome: () => ({}),
}));
vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => fixture.canWrite, useReactor: () => "user" }));

const { Transcript } = await import("./GroupView");
const { MESSAGE_ROW } = await import("./MessageActions");
const { MessageBoundary } = await import("./ChatView");

const lead = { id: "lead", name: "Lead", color: "blue", voice: "verse" } as Bot;
const room = {
  id: "room", threadId: "room-thread", name: "Launch", memberIds: ["lead"],
  defaultResponder: { kind: "member", botId: "lead" }, bulletin: "", unread: false,
  createdAt: 1, messages: [] as Message[],
} as Group;

const text = (id: string, role: "user" | "bot", body: string): Message => ({
  id, role, kind: "text", at: 1, text: body,
  ...(role === "bot" ? { from: { botId: "lead", name: "Lead", color: "blue" as const } } : {}),
});

/** The room as drawn with the pointer over each message, which is when a message's own buttons mount. */
const markup = (messages: Message[]) => {
  vi.unstubAllGlobals();
  flushSync(() => root.render(createElement(Transcript, {
    group: { ...room, messages }, members: [lead], locale: "en", messages, transcript: messages, onReply: () => {},
  })));
  hover();
  return host.innerHTML;
};
const hover = () => {
  for (const row of host.querySelectorAll(`[${MESSAGE_ROW}]`)) flushSync(() => row.dispatchEvent(new PointerEvent("pointerenter", { pointerType: "mouse" })));
};

function Boom(): ReactNode {
  throw new Error("markdown failed");
}

let host: HTMLDivElement;
let root: Root;

beforeEach(() => {
  vi.stubGlobal("window", {});
  fixture.dispatch.mockClear();
  fixture.canWrite = true;
  fixture.config = null;
  host = document.createElement("div");
  document.body.append(host);
  root = createRoot(host);
});
afterEach(() => {
  flushSync(() => root.unmount());
  host.remove();
  vi.unstubAllGlobals();
});

describe("room message actions", () => {
  it("gives a bot reply the same tray as a 1:1 answer", () => {
    const html = markup([text("a", "bot", "The build is green")]);
    expect(html).toContain('data-testid="message-actions"');
    expect(html).toContain("Copy message");
    expect(html).toContain("Reply to message");
    expect(html).toContain('aria-haspopup="menu"');
    expect(html).not.toContain("Show raw markdown");
    expect(html).not.toContain("Pin message");
  });

  it("offers reactions only to a viewer who may write in the room: one who may not sees who reacted, as labels", () => {
    const asked: Message = { ...text("a", "bot", "Shall I post it?"), reactions: [{ emoji: "👍", by: "p_ada", name: "Ada" }] };
    const open = markup([asked]);
    expect(open).toContain('aria-label="Add reaction"');
    expect(open).toMatch(/<button[^>]*aria-label="Thumbs up: yes, go ahead: Ada"/);
    fixture.canWrite = false;
    const closed = markup([asked]);
    expect(closed).not.toContain("Add reaction");
    expect(closed).not.toMatch(/<button[^>]*aria-label="Thumbs up: yes, go ahead: Ada"/);
    expect(closed).toMatch(/<span role="img" aria-label="Thumbs up: yes, go ahead: Ada"/);
  });

  it("puts read aloud (with its setup hint while no voice is set up), raw markdown and pin in a room reply's more menu", () => {
    vi.unstubAllGlobals();
    const messages = [text("a", "bot", "The build is green")];
    flushSync(() => root.render(createElement(Transcript, {
      group: { ...room, messages }, members: [lead], locale: "en", messages, transcript: messages, onReply: () => {},
    })));
    hover();
    flushSync(() => host.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!.click());
    const items = [...host.querySelectorAll<HTMLButtonElement>("[role=menuitem]")];
    expect(items.map((item) => item.textContent)).toEqual(expect.arrayContaining(["Read this aloud", "Show raw markdown", "Pin message", "Copy message ID"]));
    const speak = items.find((item) => item.textContent === "Read this aloud");
    expect(speak?.title).toBe("Add an ElevenLabs key in an agent profile to read messages aloud");
    expect(speak?.disabled).toBe(true);
    expect(host.querySelector('[data-testid="message-actions"] > button[aria-label="Read this aloud"]')).toBeNull();
  });

  it("gives a room reply its own Read this aloud button once a voice is set up, out of the more menu", () => {
    vi.unstubAllGlobals();
    fixture.config = { tts: { configured: true, ready: true, voice: "Ada" } };
    const messages = [text("a", "bot", "The build is green")];
    flushSync(() => root.render(createElement(Transcript, {
      group: { ...room, messages }, members: [lead], locale: "en", messages, transcript: messages, onReply: () => {},
    })));
    hover();
    const bar = host.querySelector('[data-testid="message-actions"]')!;
    const button = bar.querySelector<HTMLButtonElement>('button[aria-label="Read this aloud"]');
    expect(button?.disabled).toBe(false);
    flushSync(() => host.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!.click());
    const items = [...host.querySelectorAll<HTMLButtonElement>("[role=menuitem]")].map((item) => item.textContent);
    expect(items).toEqual(expect.arrayContaining(["Show raw markdown", "Pin message"]));
    expect(items).not.toContain("Read this aloud");
  });

  it("copies a person's message and folds a long one", () => {
    const html = markup([text("u", "user", "word ".repeat(200))]);
    expect(html).toContain("Copy message");
    expect(html).toContain("Show full message");
    expect(html).not.toContain("Show raw markdown");
  });

  it("keeps delivered files beneath the reply alongside its quiet actions", () => {
    const reply: Message = {
      ...text("a", "bot", "See [notes.md](/work/notes.md). The report is attached."),
      attachments: [
        { kind: "file", path: "/store/notes.md", name: "notes.md", mime: "text/markdown" },
        { kind: "file", path: "/store/report.pdf", name: "report.pdf", mime: "application/pdf" },
      ],
    };
    const html = markup([reply]);
    expect(html.match(/title="Preview: notes\.md"/g)).toHaveLength(1);
    expect(html).toContain(">notes.md<");
    expect(html.match(/aria-label="Save a copy of notes\.md"/g)).toHaveLength(1);
    expect(html).toContain('aria-label="1 attachment"');
    expect(html.match(/aria-label="Save a copy of report\.pdf"/g)).toHaveLength(1);
    expect(html).toMatch(/<section[^>]*class="mt-2\.5 /);
    expect(html).toContain('data-testid="message-actions"');
    expect(html).toContain("Reply to message");
    expect(html).toContain('aria-haspopup="menu"');
  });
});

describe("room message boundary", () => {
  it("keeps the rest of the transcript when one row throws", () => {
    vi.spyOn(console, "error").mockImplementation(() => {});
    flushSync(() => root.render(createElement("div", null,
      createElement(MessageBoundary, { fallbackText: "plain words", children: createElement(Boom) }),
      createElement("p", null, "still here"),
    )));
    expect(host.textContent).toContain("plain words");
    expect(host.querySelector(".chat-text")?.className).toMatch(/max-w-\[min\(var\(--chat-bubble-max\),var\(--chat-bubble-pct\)/);
    expect(host.textContent).toContain("still here");
  });
});