Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
10.1 KB
Raw Blame
// @vitest-environment jsdom

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ComponentProps } from "react";
import { render, screen, fireEvent, cleanup, waitFor } from "@testing-library/react";
import { I18nProvider } from "@multica/core/i18n/react";
import type { RuntimeModelsResult } from "@multica/core/types";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import enAgents from "../../locales/en/agents.json";
import enCommon from "../../locales/en/common.json";
import enIssues from "../../locales/en/issues.json";
import { ModelDropdown } from "./model-dropdown";

const TEST_RESOURCES = {
  en: { common: enCommon, agents: enAgents, issues: enIssues },
};

const CODEX_MODELS: RuntimeModelsResult = {
  models: [
    {
      id: "gpt-5.6-sol",
      label: "GPT-5.6 Sol",
      provider: "openai",
      default: true,
    },
    { id: "gpt-5.6-terra", label: "GPT-5.6 Terra", provider: "openai" },
    { id: "gpt-5.6-luna", label: "GPT-5.6 Luna", provider: "openai" },
  ],
  supported: true,
};

// Discovery outcome for the next render. resolveRuntimeModels rejects with the
// daemon's reported error text, so a failure is modelled as a throwing queryFn.
let discovery: () => Promise<RuntimeModelsResult> = async () => CODEX_MODELS;
const mockRefreshRuntimeModels = vi.hoisted(() => vi.fn());

vi.mock("@multica/core/runtimes", () => ({
  runtimeModelsOptions: (runtimeId: string | null) => ({
    enabled: Boolean(runtimeId),
    queryKey: ["runtime-models", runtimeId, discoveryKey],
    queryFn: () => discovery(),
  }),
  refreshRuntimeModels: (...args: unknown[]) =>
    mockRefreshRuntimeModels(...args),
}));

// Bumped per test so React Query cannot serve a previous case's cached result.
let discoveryKey = 0;

function renderDropdown(props: Partial<ComponentProps<typeof ModelDropdown>> = {}) {
  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: false } },
  });
  const onChange = vi.fn();
  const view = render(
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      <QueryClientProvider client={queryClient}>
        <ModelDropdown
          runtimeId="rt-codex"
          runtimeOnline
          value=""
          onChange={onChange}
          {...props}
        />
      </QueryClientProvider>
    </I18nProvider>,
  );
  return { ...view, onChange };
}

function openDropdown(container: HTMLElement) {
  const trigger = container.querySelector<HTMLButtonElement>(
    '[data-trigger="popover"]',
  );
  if (!trigger) throw new Error("model dropdown trigger not rendered");
  fireEvent.click(trigger);
}

describe("ModelDropdown", () => {
  beforeEach(() => {
    mockRefreshRuntimeModels.mockResolvedValue(CODEX_MODELS);
  });

  afterEach(() => {
    cleanup();
    discovery = async () => CODEX_MODELS;
    mockRefreshRuntimeModels.mockReset();
    discoveryKey += 1;
  });

  it("keeps an overlong model id ellipsized inside the trigger instead of overflowing", () => {
    // Regression: the trigger label sits in a flex row; without min-w-0 the
    // flex item refuses to shrink below its content width, so hex-encoded
    // model ids (e.g. Claude Code custom models) stretched the picker panel.
    const longModel = `anthropic/claude-ccr-h${"3656e6f76612f646565707365656b".repeat(8)}`;
    const { container } = renderDropdown({ value: longModel });
    const trigger = container.querySelector('[data-trigger="popover"]');
    const label = trigger?.querySelector("span.truncate");
    expect(label?.textContent).toBe(longModel);
    expect(label?.className).toContain("min-w-0");
  });

  it("offers the gpt-5.6 Codex models and submits their canonical IDs", async () => {
    const onAutomaticChange = vi.fn();
    const { container, onChange } = renderDropdown({ onAutomaticChange });
    openDropdown(container);

    expect(await screen.findByText("GPT-5.6 Sol")).toBeTruthy();
    expect(screen.getByText("GPT-5.6 Terra")).toBeTruthy();
    expect(screen.getByText("GPT-5.6 Luna")).toBeTruthy();
    expect(screen.getByText("gpt-5.6-sol")).toBeTruthy();
    expect(screen.getByText("gpt-5.6-terra")).toBeTruthy();
    expect(screen.getByText("gpt-5.6-luna")).toBeTruthy();

    fireEvent.click(screen.getByText("GPT-5.6 Terra"));
    expect(onChange).toHaveBeenCalledWith("gpt-5.6-terra");
    expect(onAutomaticChange).not.toHaveBeenCalled();
  });

  it("routes unsupported model cleanup separately from user selections", async () => {
    discovery = async () => ({ models: [], supported: false });
    const onAutomaticChange = vi.fn();
    const { onChange } = renderDropdown({ value: "saved-model", onAutomaticChange });

    await waitFor(() => expect(onAutomaticChange).toHaveBeenCalledWith(""));
    expect(onChange).not.toHaveBeenCalled();
  });

  it("still clears unsupported models for callers with one change handler", async () => {
    discovery = async () => ({ models: [], supported: false });
    const { onChange } = renderDropdown({ value: "saved-model" });

    await waitFor(() => expect(onChange).toHaveBeenCalledWith(""));
  });

  it("treats explicit clearing as a user selection", async () => {
    const onAutomaticChange = vi.fn();
    const { container, onChange } = renderDropdown({ value: "saved-model", onAutomaticChange });
    openDropdown(container);
    fireEvent.click(await screen.findByText(enAgents.model_dropdown.clear_full));

    expect(onChange).toHaveBeenCalledWith("");
    expect(onAutomaticChange).not.toHaveBeenCalled();
  });

  it("offers an explicit refresh that requests the runtime's live catalog", async () => {
    const { container } = renderDropdown({ workspaceSlug: "new-workspace" });
    openDropdown(container);

    await screen.findByText("GPT-5.6 Sol");
    fireEvent.click(
      screen.getByRole("button", { name: enAgents.pickers.model_refresh }),
    );

    expect(mockRefreshRuntimeModels).toHaveBeenCalledWith(
      expect.any(QueryClient),
      "rt-codex",
      "new-workspace",
    );
  });

  // MUL-6606: a runtime that could not enumerate its models used to report an
  // empty catalog with no error, which rendered as an authoritative empty
  // dropdown. The reason has to reach the user, because for hermes it names the
  // exact command that fixes the problem.
  it("shows the runtime's own reason when discovery fails", async () => {
    const reason =
      "ACP model discovery session/new failed: No LLM provider configured. " +
      "Run `hermes model` to select a provider.";
    discovery = async () => {
      throw new Error(reason);
    };

    const { container } = renderDropdown();
    openDropdown(container);

    expect(await screen.findByText(reason)).toBeTruthy();
    // And the picker says so up front, rather than looking like an empty catalog.
    expect(screen.getByText(enAgents.model_dropdown.discovery_failed)).toBeTruthy();
    expect(
      screen.queryByText(enAgents.pickers.model_empty_with_dot),
    ).toBeNull();
  });

  // A reason with no way forward is a dead end: manual entry is the documented
  // fallback for a failed discovery, so it must survive one.
  it("still accepts a manually typed model ID after a failed discovery", async () => {
    discovery = async () => {
      throw new Error("discovery blew up");
    };

    const { container, onChange } = renderDropdown();
    openDropdown(container);

    await screen.findByText("discovery blew up");
    // The popover renders through a portal, so reach it via screen, not container.
    const input = screen.getByPlaceholderText(
      enAgents.pickers.model_search_placeholder,
    );
    fireEvent.change(input, { target: { value: "vertex/gemini-3.1-pro" } });

    fireEvent.click(await screen.findByText(/vertex\/gemini-3\.1-pro/));
    expect(onChange).toHaveBeenCalledWith("vertex/gemini-3.1-pro");
  });

  // MUL-6961: Claude Code reports a model its own version cannot run in a
  // separate list. It must be visible — a missing row reads as "Multica doesn't
  // support Fable 5.1" when the truth is the user's CLI is behind — and it must
  // be impossible to pick, because picking one is a guaranteed 400.
  describe("models the runtime cannot run", () => {
    const WITH_UNAVAILABLE: RuntimeModelsResult = {
      models: [{ id: "claude-fable-5", label: "Fable", provider: "anthropic" }],
      unavailableModels: [
        {
          id: "cc-update-required-1",
          label: "Fable 5.1 (disabled)",
          reason: "Update to 2.1.255+ to use Fable 5.1",
        },
      ],
      supported: true,
    };

    it("shows the row with the runtime's upgrade hint but renders no control for it", async () => {
      discovery = async () => WITH_UNAVAILABLE;
      const { container, onChange } = renderDropdown();
      openDropdown(container);

      const row = await screen.findByText("Fable 5.1 (disabled)");
      expect(
        screen.getByText("Update to 2.1.255+ to use Fable 5.1"),
      ).toBeTruthy();

      // Nothing clickable was rendered for it, so there is no path to select it.
      expect(row.closest("button")).toBeNull();
      fireEvent.click(row);
      expect(onChange).not.toHaveBeenCalled();

      // The model this CLI *can* run is still a normal pick.
      fireEvent.click(screen.getByText("Fable"));
      expect(onChange).toHaveBeenCalledWith("claude-fable-5");
    });

    it("keeps the unavailable id out of the selectable catalog", async () => {
      discovery = async () => WITH_UNAVAILABLE;
      const { container, onChange } = renderDropdown();
      openDropdown(container);
      await screen.findByText("Fable 5.1 (disabled)");

      // Searching the placeholder id must not surface a selectable row for it.
      // Manual entry stays available — that escape hatch accepts any string and
      // is not what this guards — but it must be the only way the text reaches
      // onChange, and only on an explicit second click.
      const input = screen.getByPlaceholderText(
        enAgents.pickers.model_search_placeholder,
      );
      fireEvent.change(input, { target: { value: "cc-update-required-1" } });

      expect(
        screen.queryByRole("button", { name: /cc-update-required-1$/ }),
      ).toBeNull();
      expect(onChange).not.toHaveBeenCalled();
    });
  });
});