Skip to content

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

Go
10.4 KB
Raw Blame
import { api } from "@multica/core/api";
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { AgentRuntime } from "@multica/core/types";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@multica/core/i18n/react";
import { configStore } from "@multica/core/config";
import enCommon from "../../locales/en/common.json";
import enOnboarding from "../../locales/en/onboarding.json";

import enAgents from "../../locales/en/agents.json";
vi.mock("@multica/core/api", async (importOriginal) => ({
  ...await importOriginal<typeof import("@multica/core/api")>(),
  api: { initiateListModels: vi.fn() },
}));

const TEST_RESOURCES = { en: { common: enCommon, onboarding: enOnboarding, agents: enAgents } };

const mocks = vi.hoisted(() => ({
  pickerState: {
    runtimes: [] as AgentRuntime[],
    selected: null as AgentRuntime | null,
    selectedId: null as string | null,
    setSelectedId: vi.fn<(id: string) => void>(),
    hasRuntimes: false,
  },
}));

// Swap out the runtime picker so tests can drive runtimes / selection
// without a real TanStack Query + WS stack.
vi.mock("../components/use-runtime-picker", () => ({
  useRuntimePicker: () => mocks.pickerState,
}));

import { StepPlatformFork } from "./step-platform-fork";

function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
  return {
    id: "rt_test",
    workspace_id: "ws_test",
    name: "Claude Code",
    provider: "claude",
    status: "online",
    runtime_mode: "local",
    runtime_config: {},
    device_info: "",
    metadata: {},
    daemon_id: null,
    last_seen_at: new Date().toISOString(),
    created_at: new Date().toISOString(),
    updated_at: new Date().toISOString(),
    ...overrides,
  } as unknown as AgentRuntime;
}

function renderFork(
  overrides: Partial<React.ComponentProps<typeof StepPlatformFork>> = {},
) {
  const onNext = vi.fn();
  // The CLI dialog now renders the shared runtime+model chooser, and the model
  // dropdown queries the runtime's model list.
  const qc = new QueryClient({
    defaultOptions: { queries: { retry: false } },
  });
  render(
    <QueryClientProvider client={qc}>
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      <StepPlatformFork
        wsId="ws_test"
        onNext={onNext}
        cliInstructions={<div data-testid="cli-instructions">install me</div>}
        {...overrides}
      />
    </I18nProvider>
    </QueryClientProvider>,
  );
  return { onNext };
}

function resetPicker(patch: Partial<typeof mocks.pickerState> = {}) {
  mocks.pickerState.runtimes = patch.runtimes ?? [];
  mocks.pickerState.selected = patch.selected ?? null;
  mocks.pickerState.selectedId = patch.selectedId ?? null;
  mocks.pickerState.hasRuntimes = patch.hasRuntimes ?? false;
  mocks.pickerState.setSelectedId = vi.fn();
}

describe("StepPlatformFork", () => {
  it("passes the onboarding workspace through the model chooser", async () => {
    const initiate = vi.spyOn(api, "initiateListModels").mockResolvedValue({
      id: "request-1", runtime_id: "rt_1", status: "completed", models: [],
      supported: true, created_at: "2026-10-30T00:00:00Z", updated_at: "2026-10-30T00:00:00Z",
    });
    const rt = makeRuntime();
    mocks.pickerState.runtimes = [rt];
    mocks.pickerState.selected = rt;
    mocks.pickerState.selectedId = rt.id;
    mocks.pickerState.hasRuntimes = true;
    renderFork({ wsSlug: "new-workspace" });
    await userEvent.click(screen.getByRole("button", { name: /show steps/i }));
    expect(initiate).toHaveBeenCalledWith(rt.id, undefined, "new-workspace");
    initiate.mockRestore();
  });

  it("shows one computer for six runtimes on the same daemon", async () => {
    resetPicker({
      runtimes: Array.from({ length: 6 }, (_, i) => makeRuntime({ id: `rt-${i}`, daemon_id: "daemon-1" })),
      hasRuntimes: true,
    });
    renderFork();
    await userEvent.click(screen.getByRole("button", { name: /show steps/i }));
    expect(screen.getByText("1 computer connected")).toBeInTheDocument();
  });

  beforeEach(() => {
    configStore.getState().setDaemonConfig({ daemonSetupTarget: "cloud" });
    resetPicker();
    vi.restoreAllMocks();
  });

  afterEach(() => {
    cleanup();
    vi.useRealTimers();
    configStore.setState({
      daemonConfigStatus: "loading",
      daemonSetupTarget: "unknown",
      daemonServerUrl: "",
      daemonAppUrl: "",
    });
  });

  it("uses the same self-host command throughout the waiting stages", () => {
    vi.useFakeTimers();
    configStore.getState().setDaemonConfig({
      daemonSetupTarget: "self_host",
      daemonServerUrl: "https://api.example.com",
      daemonAppUrl: "https://app.example.com",
    });
    renderFork();
    fireEvent.click(screen.getByRole("button", { name: /show steps/i }));
    const dialog = screen.getByRole("dialog");
    const command = "multica setup self-host --server-url https://api.example.com --app-url https://app.example.com";
    expect(within(dialog).getByText(command)).toBeInTheDocument();
    act(() => vi.advanceTimersByTime(15_000));
    expect(within(dialog).getByText(command)).toBeInTheDocument();
    act(() => vi.advanceTimersByTime(30_000));
    expect(within(dialog).getByText(command)).toBeInTheDocument();
    expect(within(dialog).queryByText("multica setup")).not.toBeInTheDocument();
  });

  it("does not show Cloud waiting guidance while configuration is loading or failed", () => {
    configStore.getState().setDaemonConfigStatus("loading");
    renderFork();
    fireEvent.click(screen.getByRole("button", { name: /show steps/i }));
    const dialog = screen.getByRole("dialog");
    expect(within(dialog).queryByText("multica setup")).not.toBeInTheDocument();
    expect(within(dialog).queryByText(/waiting for your computer/i)).not.toBeInTheDocument();
    act(() => configStore.getState().setDaemonConfigStatus("error"));
    expect(within(dialog).queryByText("multica setup")).not.toBeInTheDocument();
  });

  it("renders the three fork options at rest", () => {
    renderFork();
    expect(screen.getByText(/^use this computer$/i)).toBeInTheDocument();
    expect(screen.getByText(/^connect from the terminal$/i)).toBeInTheDocument();
    expect(screen.getByText(/^use a cloud computer$/i)).toBeInTheDocument();
    // Cloud option is a "Coming soon" preview — not yet wired up.
    expect(screen.getByText(/^coming soon$/i)).toBeInTheDocument();
    expect(
      screen.queryByRole("button", { name: /^coming soon$/i }),
    ).not.toBeInTheDocument();
    // CLI dialog closed at rest → no CLI instructions.
    expect(screen.queryByTestId("cli-instructions")).not.toBeInTheDocument();
  });

  it("footer: Skip only + explanatory hint (no Continue)", () => {
    renderFork();
    expect(
      screen.getByRole("button", { name: /skip for now/i }),
    ).toBeEnabled();
    // Continue is gone — it lived in the footer before; now advancement
    // for the CLI path is owned by the CLI dialog's own button.
    expect(
      screen.queryByRole("button", { name: /^continue$/i }),
    ).not.toBeInTheDocument();
    expect(
      screen.getByText("You can connect later."),
    ).toBeInTheDocument();
  });

  it("Skip is always enabled and calls onNext(null)", async () => {
    const user = userEvent.setup();
    const { onNext } = renderFork();
    await user.click(screen.getByRole("button", { name: /skip for now/i }));
    expect(onNext).toHaveBeenCalledTimes(1);
    expect(onNext).toHaveBeenCalledWith(null);
  });

  it("opens the download page and claims nothing about the outcome", async () => {
    // mockReturnValue(null) is the honest simulation: with `noopener`,
    // window.open returns null by spec whether the tab opened or a popup
    // blocker ate it. The card used to flip to "Opened in a new tab." on
    // this exact path, which it had no way to know.
    const openSpy = vi.spyOn(window, "open").mockReturnValue(null);
    const user = userEvent.setup();
    renderFork();

    await user.click(screen.getByText(/^use this computer$/i));

    // Routes to the new /download page (not GitHub releases) so the
    // user lands on the OS auto-detect surface.
    expect(openSpy).toHaveBeenCalledWith(
      "/download",
      "_blank",
      "noopener,noreferrer",
    );
    // The card states its intent up front and does not change afterwards, so
    // there is no post-click claim to be wrong and no stuck "Opening…" state.
    expect(screen.getByText(/^use this computer$/i)).toBeInTheDocument();
    expect(screen.queryByText(/opening the download page/i)).toBeNull();
    expect(screen.queryByText(/opened in a new tab/i)).toBeNull();
  });

  it("CLI dialog: opens with instructions + 'waiting' and a disabled Connect button", async () => {
    const user = userEvent.setup();
    renderFork();

    await user.click(screen.getByRole("button", { name: /show steps/i }));

    const dialog = await screen.findByRole("dialog");
    expect(within(dialog).getByTestId("cli-instructions")).toBeInTheDocument();
    expect(
      within(dialog).getByText(/waiting for your computer/i),
    ).toBeInTheDocument();
    // Starting with Mika stays disabled while no runtime is selected.
    expect(
      within(dialog).getByRole("button", { name: /start with mika/i }),
    ).toBeDisabled();
  });

  it("CLI dialog with a selected runtime: Connect enables and fires onNext(runtime)", async () => {
    const rt = makeRuntime({ id: "rt_claude", name: "Claude Code" });
    resetPicker({
      runtimes: [rt],
      selected: rt,
      selectedId: rt.id,
      hasRuntimes: true,
    });
    const user = userEvent.setup();
    const { onNext } = renderFork();

    await user.click(screen.getByRole("button", { name: /show steps/i }));

    const dialog = await screen.findByRole("dialog");
    expect(within(dialog).getByText(/1 computer connected/i)).toBeInTheDocument();
    expect(
      within(dialog).getByText(/selected: claude code/i),
    ).toBeInTheDocument();

    const connect = within(dialog).getByRole("button", {
      name: /start with mika/i,
    });
    expect(connect).toBeEnabled();
    await user.click(connect);
    expect(onNext).toHaveBeenCalledTimes(1);
    // The web CLI path now carries a model alongside the runtime, like the
    // desktop step does. Nothing was picked here, so it stays undefined and
    // the runtime's own default applies.
    expect(onNext).toHaveBeenCalledWith(rt, undefined);
  });

});