Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

13.4 KB
Raw Blame
import { makeShellSnapshot } from "../test-support/fixtures";
import { Match } from "effect";
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import {
  EnvironmentId,
  MessageId,
  RoutineId,
  ThreadId,
  type OrchestrationMessage,
  type OrchestrationShellSnapshot,
} from "@akeru/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { Bot, Group } from "./types";

const mocks = vi.hoisted(() => ({
  groups: [] as Group[],
  bots: [] as Bot[],
  messages: [] as OrchestrationMessage[],
  mediaBlocked: false,
  setContext: vi.fn(),
  clearContextIf: vi.fn(),
  observe: vi.fn(),
  landing: vi.fn(),
  refreshHistory: vi.fn(),
  queryData: { inbox: [], runs: [], nextCursor: null },
  snapshot: null as OrchestrationShellSnapshot | null,
  rosterLoadState: { kind: "loading" } as { kind: "loading" } | { kind: "failed"; message: string },
}));

vi.mock("@tanstack/react-router", () => ({ useNavigate: () => vi.fn() }));

vi.mock("../../hooks/useSettings", () => ({ usePrimarySettings: () => ({}) }));

vi.mock("../../modelSelection", () => ({
  getCustomModelOptionsByInstance: () => new Map(),
  resolveAppModelSelectionState: () => null,
}));

vi.mock("../../providerInstances", () => ({
  applyProviderInstanceSettings: () => [],
  deriveProviderInstanceEntries: () => [],
  sortProviderInstanceEntries: () => [],
}));

vi.mock("../../state/session", () => ({
  useEnvironmentSessionState: () => ({ data: null, isPending: false }),
}));

vi.mock("./useBotEngineAvailability", () => ({
  useBotEngineAvailability: () => ({
    instanceEntries: [],
    selection: null,
    unavailability: null,
    blocked: false,
  }),
}));

vi.mock("./useServerRoster", () => ({
  useRosterLoadState: () => mocks.rosterLoadState,
  useEnableBotAutoReview: () => vi.fn(),
}));

vi.mock("@effect/atom-react", () => ({
  useAtomValue: (atom: string) =>
    Match.value(atom).pipe(
      Match.when("people", () => ({ current: null, host: null })),
      Match.when("snapshot", () => mocks.snapshot),
      Match.when("bots", () => []),
      Match.orElse(() => null),
    ),
}));

vi.mock("../../state/bots", () => ({
  environmentPeopleAtom: () => "people",
  environmentBotsAtom: () => "bots",
  botEnvironment: { update: null },
}));

vi.mock("../../state/environments", () => ({
  usePrimaryEnvironmentId: () => EnvironmentId.make("environment-1"),
  useEnvironmentConnectionState: () => ({ data: null }),
}));

vi.mock("./detailsPanelOpen", () => ({
  useBotDetailsOpen: () => [false, () => undefined],
  useGroupDetailsOpen: () => [false, () => undefined],
}));

vi.mock("../chat/ChatActionsMenu", () => ({
  ChatActionsMenu: () => null,
  useMarkChatVisited: () => undefined,
}));

vi.mock("../../state/entities", () => ({ useThreadActivities: () => [] }));

vi.mock("../../state/query", () => ({
  useEnvironmentQuery: () => ({ data: mocks.queryData, refresh: mocks.refreshHistory }),
}));

vi.mock("../settings/ProvidersPanel", () => ({
  useSubscriptionStatuses: () => ({ statusByProvider: new Map() }),
}));

vi.mock("../../state/server", () => ({
  primaryServerProvidersAtom: null,
  serverEnvironment: { subscriptionAuth: () => null, routineThreadRuns: () => null },
}));

vi.mock("../../state/shell", () => ({ environmentSnapshotAtom: () => "snapshot" }));

vi.mock("../../state/threads", () => ({ threadEnvironment: { setMessageReaction: null } }));

vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));

vi.mock("../../settingsDialogStore", () => ({ openSettings: vi.fn() }));

vi.mock("../voice/VoiceCall", () => ({
  BotVoiceCallButton: () => null,
  useVoiceCall: () => ({ activeCall: mocks.mediaBlocked, startingBotId: null }),
  useOptionalVoiceCall: () => ({ activeCall: mocks.mediaBlocked, startingBotId: null }),
  voiceEnvironmentConnectionLost: () => false,
}));

vi.mock("../chat/ReplyPlaybackProvider", () => {
  const synthesis = { provider: "test-provider", voice: "test-voice" };

  const session = {
    synthesisFor: () => synthesis,
    subscribeSynthesis: () => () => {},
    getSynthesisSnapshot: () => synthesis,
    setContext: mocks.setContext,
    clearContextIf: mocks.clearContextIf,
    observe: mocks.observe,
    actionFor: () => undefined,
  };

  return { useOptionalReplyPlayback: () => session };
});

vi.mock("../ui/sidebar", () => ({
  SidebarInset: (
    props: import("react").ComponentProps<typeof import("../ui/sidebar").SidebarInset>,
  ) => {
    mocks.landing(props);

    return null;
  },
}));

vi.mock("./botPresence", () => ({
  useBotPresence: () => "idle",
  useGroupPresence: () => "idle",
}));

vi.mock("./rosterStore", () => {
  const useRosterStore = <T,>(
    selector: (state: { groups: Group[]; bots: Bot[]; environmentId: string }) => T,
  ) => selector({ groups: mocks.groups, bots: mocks.bots, environmentId: "environment-1" });

  useRosterStore.getState = () => ({ selectBot: vi.fn() });

  return { useRosterStore };
});

vi.mock("./useBotThreadRuntime", () => ({
  useBotThreadRuntime: () => ({
    sending: false,
    respondingRequestIds: [],
    messages: mocks.messages,
    error: null,
    latestTurn: null,
    defaultProject: null,
    botReady: true,
    bootstrapped: true,
    linkedThreadRef: {
      environmentId: EnvironmentId.make("environment-1"),
      threadId: ThreadId.make("thread-bot"),
    },
    pendingUserInputs: [],
    send: vi.fn(),
  }),
}));

vi.mock("./useRosterPendingApproval", () => ({
  useRosterPendingApproval: () => ({ pendingApproval: null }),
}));

vi.mock("./useGroupThreadRuntime", () => ({
  useGroupThreadRuntime: () => ({
    sending: false,
    respondingRequestIds: [],
    messages: mocks.messages,
    error: null,
    defaultProject: null,
    groupReady: true,
    bootstrapped: true,
    respondingBotId: null,
    linkedThreadRef: {
      environmentId: EnvironmentId.make("environment-1"),
      threadId: ThreadId.make("thread-group"),
    },
    pendingUserInputs: [],
    send: vi.fn(),
  }),
}));

import { GroupThreadLanding } from "./GroupThreadLanding";
import { BotThreadLanding } from "./BotThreadLanding";

// Minimal ReactDOM host, matching DesktopOnboarding's unit tests.
class TestNode {
  parentNode: TestNode | null = null;
  childNodes: TestNode[] = [];
  readonly nodeName: string;
  readonly tagName: string;
  readonly namespaceURI = "http://www.w3.org/1999/xhtml";
  readonly style = {};
  constructor(
    name: string,
    readonly ownerDocument: TestNode | null = null,
    readonly nodeType = 1,
  ) {
    this.nodeName = name.toUpperCase();
    this.tagName = this.nodeName;
  }
  set textContent(_value: string) {
    this.childNodes = [];
  }
  appendChild(child: TestNode) {
    child.parentNode = this;
    this.childNodes.push(child);

    return child;
  }
  removeChild(child: TestNode) {
    this.childNodes.splice(this.childNodes.indexOf(child), 1);
    child.parentNode = null;

    return child;
  }
  insertBefore(child: TestNode, before: TestNode) {
    child.parentNode = this;
    this.childNodes.splice(this.childNodes.indexOf(before), 0, child);

    return child;
  }
  createElement(name: string) {
    return new TestNode(name, this);
  }
  createElementNS(_namespace: string, name: string) {
    return this.createElement(name);
  }
  createTextNode() {
    return new TestNode("#text", this, 3);
  }
  addEventListener() {}
  removeEventListener() {}
  setAttribute() {}
  removeAttribute() {}
}

const group: Group = {
  id: "perf-group",
  name: "Performance",
  bossBotId: null,
  members: [],
  createdAt: "2026-09-08T00:00:00.000Z",
  updatedAt: "2026-09-08T00:00:00.000Z",
};

const bot: Bot = {
  id: "bot-1",
  name: "Akeru",
  title: "Teammate",
  label: null,
  description: null,
  disabledMcpServerIds: [],
  avatar: { kind: "dither", seed: "bot-1" },
  engine: null,
  sandbox: "local",
  runtimeMode: "approval-required",
  voiceEnabled: false,
  groupId: null,
  pinned: false,
  archivedAt: null,
  createdAt: group.createdAt,
  updatedAt: group.updatedAt,
};

const message: OrchestrationMessage = {
  id: MessageId.make("reply-1"),
  role: "assistant",
  text: "Here is the group reply.",
  turnId: null,
  streaming: false,
  createdAt: "2026-09-08T00:00:00.000Z",
  updatedAt: "2026-09-08T00:00:00.000Z",
};

let root: Root;

beforeEach(() => {
  vi.clearAllMocks();
  mocks.groups = [];
  mocks.bots = [];
  mocks.messages = [];
  mocks.mediaBlocked = false;
  mocks.snapshot = null;
  mocks.rosterLoadState = { kind: "loading" };
  const document = new TestNode("#document", null, 9);
  vi.stubGlobal("document", document);
  vi.stubGlobal("window", {
    document,
    HTMLIFrameElement: TestNode,
    addEventListener() {},
    removeEventListener() {},
  });
  vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
  root = createRoot(globalThis.document.createElement("div"));
});

afterEach(async () => {
  await act(async () => root.unmount());
  vi.unstubAllGlobals();
});

async function render() {
  await act(async () => root.render(<GroupThreadLanding groupId={group.id} />));
}

describe("thread landing reply playback hook order", () => {
  it("refreshes routine history when an open chat receives a new run", async () => {
    mocks.bots = [bot];

    const source = {
      id: RoutineId.make("routine-1"),
      targetThreadId: ThreadId.make("thread-bot"),
      job: "Daily report",
      createdAt: "2026-09-29T09:00:00.000Z",
    };

    mocks.snapshot = makeShellSnapshot({
      routineReceiptSources: [source],
      routineRuns: [],
      delegations: [],
    });

    const renderBot = async () => {
      await act(async () => root.render(<BotThreadLanding botId={bot.id} />));
    };

    await renderBot();
    expect(mocks.refreshHistory).not.toHaveBeenCalled();

    mocks.snapshot = makeShellSnapshot({
      routineReceiptSources: [source],
      delegations: [],
      routineRuns: [
        {
          id: "run-1",
          routineId: source.id,
          status: "queued",
          startedAt: null,
          updatedAt: "2026-09-29T09:01:00.000Z",
        },
      ],
    });
    await renderBot();
    expect(mocks.refreshHistory).toHaveBeenCalledTimes(1);
  });

  it.each(["missing", "archived"] as const)(
    "renders an initially %s bot then its available bot without a hook ordering error",
    async (state) => {
      const unavailableBots = state === "missing" ? [] : [{ ...bot, archivedAt: bot.updatedAt }];
      mocks.bots = unavailableBots;
      mocks.messages = [message];

      const renderBot = async () => {
        await act(async () => root.render(<BotThreadLanding botId={bot.id} />));
      };

      await renderBot();
      expect(mocks.landing).not.toHaveBeenCalled();
      expect(mocks.setContext).toHaveBeenLastCalledWith(null);
      expect(mocks.observe).toHaveBeenLastCalledWith([]);

      mocks.bots = [bot];
      mocks.messages = [message];
      await expect(renderBot()).resolves.toBeUndefined();
      expect(mocks.landing).toHaveBeenCalled();
      expect(mocks.observe).toHaveBeenLastCalledWith([message]);
      expect(mocks.setContext).toHaveBeenLastCalledWith(
        expect.objectContaining({ threadId: "thread-bot", mediaBlocked: false }),
      );

      mocks.bots = unavailableBots;
      mocks.landing.mockClear();
      await expect(renderBot()).resolves.toBeUndefined();
      expect(mocks.landing).not.toHaveBeenCalled();
      expect(mocks.setContext).toHaveBeenLastCalledWith(null);
      expect(mocks.observe).toHaveBeenLastCalledWith([]);
      mocks.messages = [...mocks.messages, { ...message, id: MessageId.make("later-reply") }];
      await renderBot();
      expect(mocks.setContext).toHaveBeenLastCalledWith(null);
      expect(mocks.observe).toHaveBeenLastCalledWith([]);
    },
  );
  it("offers the roster failure page for a missing group when the first load failed", async () => {
    mocks.rosterLoadState = { kind: "failed", message: "Snapshot failed" };
    await render();
    expect(mocks.landing).toHaveBeenCalledWith(
      expect.objectContaining({ "aria-label": "Could not load bots" }),
    );
  });

  it("renders an initially missing group then its hydrated group without a hook ordering error", async () => {
    mocks.messages = [message];
    await render();
    expect(mocks.landing).not.toHaveBeenCalled();
    expect(mocks.setContext).toHaveBeenLastCalledWith(null);
    expect(mocks.observe).toHaveBeenLastCalledWith([]);

    mocks.groups = [group];
    mocks.messages = [message];
    await expect(render()).resolves.toBeUndefined();
    expect(mocks.landing).toHaveBeenCalledWith(
      expect.objectContaining({ "aria-label": "Performance group chat" }),
    );
    expect(mocks.observe).toHaveBeenLastCalledWith([message]);
    expect(mocks.setContext).toHaveBeenLastCalledWith({
      environmentId: "environment-1",
      threadId: "thread-group",
      provider: "test-provider",
      voice: "test-voice",
      connected: true,
      mediaBlocked: false,
    });

    mocks.mediaBlocked = true;
    await render();
    expect(mocks.setContext).toHaveBeenLastCalledWith(
      expect.objectContaining({ mediaBlocked: true }),
    );

    mocks.groups = [];
    mocks.landing.mockClear();
    await expect(render()).resolves.toBeUndefined();
    expect(mocks.landing).not.toHaveBeenCalled();
    expect(mocks.setContext).toHaveBeenLastCalledWith(null);
    expect(mocks.observe).toHaveBeenLastCalledWith([]);
    mocks.messages = [...mocks.messages, { ...message, id: MessageId.make("later-reply") }];
    await render();
    expect(mocks.setContext).toHaveBeenLastCalledWith(null);
    expect(mocks.observe).toHaveBeenLastCalledWith([]);
  });
});