Skip to content

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

Go
6.8 KB
Raw Blame
import { cloneElement, type ReactElement, type ReactNode } from "react";
import { fireEvent, render as rtlRender, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { configStore } from "@multica/core/config";
import { githubStarsOptions } from "@multica/core/github/stars";
import { markStarPromptStarred } from "@multica/core/star-prompt";
import enLayout from "../locales/en/layout.json";
import { isDesktopShell } from "../platform/local-directory";
import { HelpLauncher } from "./help-launcher";

// The download entry is gated on the desktop-shell probe, which reads a
// preload-injected bridge that jsdom never has. Mock it so both platforms are
// reachable from the same suite.
vi.mock("../platform/local-directory", () => ({
  isDesktopShell: vi.fn(() => false),
}));

vi.mock("@multica/core/star-prompt", () => ({
  markStarPromptStarred: vi.fn(() => Promise.resolve()),
}));

// The What's new entry is covered with the real menu in whats-new-menu-panel.test.tsx.
vi.mock("../whats-new/whats-new-menu-panel", () => ({
  useWhatsNewMenuPanel: () => ({ available: false }),
  WhatsNewMenuPanel: () => null,
}));

// The UI language the mocked i18n instance reports; drives locale-aware links.
const i18nState = vi.hoisted(() => ({ language: "en" }));

// react-i18next isn't initialised in the views test env, so resolve the
// selector against the real en/layout.json to assert on actual copy.
vi.mock("../i18n", () => ({
  useT: () => ({
    i18n: i18nState,
    t: (
      sel: (r: typeof enLayout) => string,
      vars?: Record<string, string>,
    ) => {
      const template = sel(enLayout);
      return vars
        ? template.replace(/\{\{(\w+)\}\}/g, (_, key) => String(vars[key] ?? ""))
        : template;
    },
  }),
}));

// Follows the app-sidebar.test.tsx convention of flattening the Base UI
// dropdown primitives to plain children so the menu content is always in
// the DOM, instead of exercising the real portal/open-state interaction.
//
// The mock deliberately preserves ONE real invariant: DropdownMenuLabel wraps
// Base UI's Menu.GroupLabel, whose useMenuGroupRootContext() throws when it has
// no Menu.Group ancestor. A plain-<div> mock silently swallowed that contract,
// which is exactly how MUL-4819 shipped — a version row rendered outside a
// DropdownMenuGroup crashed the whole app (no error boundary above the sidebar)
// the moment the Help menu opened. Mirroring the throw here keeps the guard.
// The group context lives inside the factory so it survives vi.mock hoisting.
vi.mock("@multica/ui/components/ui/dropdown-menu", async () => {
  const { createContext, useContext } = await import("react");
  const GroupContext = createContext(false);
  return {
    DropdownMenu: ({ children }: { children: ReactNode }) => <>{children}</>,
    DropdownMenuContent: ({ children }: { children: ReactNode }) => <>{children}</>,
    // Base UI's `render` prop swaps in a caller-supplied element (here the
    // <a>) and adopts the item's children. Flattening it to a bare fragment —
    // as this mock originally did — would drop the anchor entirely and make an
    // href assertion silently unfalsifiable.
    DropdownMenuItem: ({
      children,
      render,
      onClick,
    }: {
      children: ReactNode;
      render?: ReactElement;
      onClick?: () => void;
    }) => (render ? cloneElement(render, { onClick } as object, children) : <>{children}</>),
    DropdownMenuGroup: ({ children }: { children: ReactNode }) => (
      <GroupContext.Provider value={true}>{children}</GroupContext.Provider>
    ),
    DropdownMenuLabel: ({ children }: { children: ReactNode }) => {
      if (!useContext(GroupContext)) {
        throw new Error(
          "Base UI: MenuGroupRootContext is missing. Menu group parts must be used within <Menu.Group>.",
        );
      }
      return <div>{children}</div>;
    },
    DropdownMenuSeparator: () => null,
    DropdownMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
  };
});

let qc: QueryClient;

function render(ui: ReactElement) {
  return rtlRender(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);
}

beforeEach(() => {
  qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  vi.mocked(isDesktopShell).mockReturnValue(false);
  i18nState.language = "en";
});

afterEach(() => {
  configStore.getState().setServerVersion("");
  qc.clear();
});

describe("HelpLauncher", () => {
  it("does not show a version row when the server omits it", () => {
    render(<HelpLauncher />);
    expect(screen.queryByText(/Server version/)).not.toBeInTheDocument();
  });

  it("shows the server version once /api/config resolves it", () => {
    configStore.getState().setServerVersion("1.2.3");
    render(<HelpLauncher />);
    expect(screen.getByText("Server version 1.2.3")).toBeInTheDocument();
  });

  // MUL-6462: after web onboarding the desktop download CTA was unreachable —
  // no entry anywhere in the app, so users had to remember the URL or detour
  // through the marketing site. The Help menu is the persistent home for it.
  it("links to the download page on web", () => {
    render(<HelpLauncher />);
    const link = screen.getByRole("link", { name: /Desktop app/ });
    expect(link).toHaveAttribute("href", "https://multica.ai/download");
  });

  it.each([
    ["en", "https://multica.ai/docs"],
    ["zh-Hans", "https://multica.ai/docs/zh"],
    ["zh-Hant", "https://multica.ai/docs/zh-Hant"],
    ["fr", "https://multica.ai/docs/fr"],
  ])("links Docs to the %s docs", (language, href) => {
    i18nState.language = language;
    render(<HelpLauncher />);
    expect(screen.getByRole("link", { name: /Documentation/ })).toHaveAttribute(
      "href",
      href,
    );
  });

  // AppSidebar is shared: apps/desktop renders the same component tree. Without
  // this gate the desktop app would offer to download the desktop app.
  it("hides the download entry inside the desktop shell", () => {
    vi.mocked(isDesktopShell).mockReturnValue(true);
    render(<HelpLauncher />);
    expect(screen.queryByText("Desktop app")).not.toBeInTheDocument();
    // The rest of the menu is unaffected by the gate.
    expect(screen.getByText("Documentation")).toBeInTheDocument();
  });

  it("links to the GitHub repo and retires the star prompt on click", () => {
    render(<HelpLauncher />);
    const link = screen.getByRole("link", { name: /Star on GitHub/ });
    expect(link).toHaveAttribute("href", "https://github.com/multica-ai/multica");
    fireEvent.click(link);
    expect(markStarPromptStarred).toHaveBeenCalledTimes(1);
  });

  it("shows the star count once it is known", () => {
    qc.setQueryData(githubStarsOptions().queryKey, 37_612);
    render(<HelpLauncher />);
    expect(screen.getByRole("link", { name: /Star on GitHub/ })).toHaveTextContent("37.6k");
  });
});