Skip to content

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

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

import { describe, expect, it, beforeEach, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { I18nProvider } from "@multica/core/i18n/react";
import { ApiError } from "@multica/core/api";
import type { AgentRuntime, RuntimeProfile } from "@multica/core/types";
import enCommon from "../../locales/en/common.json";
import enRuntimes from "../../locales/en/runtimes.json";

const queryState = vi.hoisted(() => ({
  profiles: [] as RuntimeProfile[],
  runtimes: [] as AgentRuntime[],
  isLoading: false,
}));
const mutationState = vi.hoisted(() => ({
  createProfile: vi.fn(),
  updateProfile: vi.fn(),
}));

vi.mock("@tanstack/react-query", async () => {
  const actual = await vi.importActual<typeof import("@tanstack/react-query")>(
    "@tanstack/react-query",
  );
  return {
    ...actual,
    useQuery: vi.fn((options: { queryKey: string[] }) => ({
      data: options.queryKey[0] === "runtimes" ? queryState.runtimes : queryState.profiles,
      isLoading: queryState.isLoading,
    })),
  };
});

vi.mock("sonner", () => ({
  toast: { error: vi.fn(), success: vi.fn() },
}));

vi.mock("@multica/core/runtimes", () => ({
  deriveRuntimeHealth: () => "online",
  runtimeProfileListOptions: vi.fn((wsId: string) => ({
    queryKey: ["runtime-profiles", wsId, "list"],
  })),
  useCreateRuntimeProfile: vi.fn(() => ({
    isPending: false,
    mutateAsync: mutationState.createProfile,
  })),
  useUpdateRuntimeProfile: vi.fn(() => ({
    isPending: false,
    mutateAsync: mutationState.updateProfile,
  })),
}));

vi.mock("./delete-runtime-profile-dialog", () => ({
  DeleteRuntimeProfileDialog: () => null,
}));

vi.mock("./provider-logo", () => ({
  ProviderLogo: () => null,
}));

import { RuntimeProfilesDialog } from "./runtime-profiles-dialog";

const TEST_RESOURCES = { en: { common: enCommon, runtimes: enRuntimes } };

function profile(overrides: Partial<RuntimeProfile> = {}): RuntimeProfile {
  return {
    id: "prof-1",
    workspace_id: "ws-1",
    daemon_id: "daemon-target",
    display_name: "Team Codex",
    protocol_family: "codex",
    command_name: "codex",
    description: null,
    fixed_args: [],
    visibility: "workspace",
    created_by: "user-1",
    enabled: true,
    created_at: "2026-01-01T00:00:00Z",
    updated_at: "2026-01-02T00:00:00Z",
    ...overrides,
  };
}

function renderDialog({
  intent,
  machineName,
  initialProfile,
  onClose = vi.fn(),
  onProfileCreated,
}: {
  intent?: "create" | "edit" | "manage";
  machineName?: string;
  initialProfile?: RuntimeProfile;
  onClose?: () => void;
  onProfileCreated?: (profile: RuntimeProfile) => void;
} = {}) {
  const view = render(
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      <RuntimeProfilesDialog
        wsId="ws-1"
        intent={intent}
        daemonId="daemon-target"
        machineName={machineName}
        initialProfile={initialProfile}
        onClose={onClose}
        onProfileCreated={onProfileCreated}
      />
    </I18nProvider>,
  );
  return { ...view, onClose };
}

describe("RuntimeProfilesDialog", () => {
  beforeEach(() => {
    queryState.profiles = [];
    queryState.runtimes = [];
    queryState.isLoading = false;
    vi.clearAllMocks();
    mutationState.createProfile.mockResolvedValue(
      profile({
        command_name: "agent",
        fixed_args: ["--model", "composer-2.5"],
      }),
    );
    mutationState.updateProfile.mockResolvedValue(profile());
  });

  it.each([false, true])("binds an existing profile and surfaces usage conflicts (%s)", async (conflict) => {
    const user = userEvent.setup();
    queryState.runtimes = [{
      id: "rt-1", workspace_id: "ws-1", daemon_id: "keep-machine",
      name: "Codex (Studio Mac)", runtime_mode: "local", provider: "codex",
      status: "online", owner_id: "user-1", visibility: "private", metadata: {},
      launch_header: "codex", device_info: "Studio Mac", profile_id: null,
      last_seen_at: new Date().toISOString(), created_at: "", updated_at: "",
    }];
    if (conflict) mutationState.updateProfile.mockRejectedValueOnce(new ApiError(
      "Finish pending tasks on the other machine first.", 409, "Conflict", { code: "runtime_profile_machine_conflict" },
    ));
    const { onClose } = renderDialog({ intent: "edit", initialProfile: profile({ daemon_id: null }) });
    await user.click(screen.getByLabelText("Machine (optional)"));
    await user.click(await screen.findByRole("option", { name: "Studio Mac" }));
    await user.click(screen.getByRole("button", { name: "Save changes" }));
    await waitFor(() => expect(mutationState.updateProfile).toHaveBeenCalledWith({
      profileId: "prof-1", patch: expect.objectContaining({ daemon_id: "keep-machine" }),
    }));
    if (conflict) {
      expect(await screen.findByRole("alert")).toHaveTextContent("Finish pending tasks");
      expect(screen.queryByText("A runtime with this display name already exists.")).not.toBeInTheDocument();
      expect(onClose).not.toHaveBeenCalled();
    } else await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
  });

  it.each([false, true])("edits a legacy profile without binding a machine (reset selection: %s)", async (resetSelection) => {
    const user = userEvent.setup();
    queryState.runtimes = [{
      id: "rt-1", workspace_id: "ws-1", daemon_id: "keep-machine",
      name: "Codex (Studio Mac)", runtime_mode: "local", provider: "codex",
      status: "online", owner_id: "user-1", visibility: "private", metadata: {},
      launch_header: "codex", device_info: "Studio Mac", profile_id: null,
      last_seen_at: new Date().toISOString(), created_at: "", updated_at: "",
    }];
    const { onClose } = renderDialog({ intent: "edit", initialProfile: profile({ daemon_id: null }) });
    if (resetSelection) {
      await user.click(screen.getByLabelText("Machine (optional)"));
      await user.click(await screen.findByRole("option", { name: "Studio Mac" }));
      await user.click(screen.getByLabelText("Machine (optional)"));
      await user.click(await screen.findByRole("option", { name: "Keep current machines" }));
    }
    fireEvent.change(screen.getByLabelText("Display name"), { target: { value: "Renamed legacy runtime" } });
    fireEvent.change(screen.getByLabelText("Command"), { target: { value: "wrapper --model custom" } });
    fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
    await waitFor(() => expect(mutationState.updateProfile).toHaveBeenCalledWith({
      profileId: "prof-1", patch: {
        display_name: "Renamed legacy runtime", command_name: "wrapper",
        fixed_args: ["--model", "custom"], description: null,
      },
    }));
    await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
  });

  it("shows the custom empty state and keeps built-in protocols collapsed", () => {
    renderDialog();

    expect(
      screen.getByText("Create your first custom runtime"),
    ).toBeInTheDocument();
    expect(screen.getByText(/Pick a compatible base runtime/)).toBeInTheDocument();

    const builtinsToggle = screen.getByRole("button", {
      name: /Built-in runtimes/,
    });
    expect(builtinsToggle).toHaveAttribute("aria-expanded", "false");
    expect(screen.queryByText("claude")).not.toBeInTheDocument();
    expect(
      screen.getAllByRole("button", { name: "New custom runtime" }),
    ).toHaveLength(1);
  });

  it("renders custom profiles before the collapsed built-in reference section", () => {
    queryState.profiles = [profile()];

    renderDialog();

    const customTitle = screen.getByText("Custom runtimes (1)");
    const customRow = screen.getByText("Team Codex");
    const builtinsToggle = screen.getByRole("button", {
      name: /Built-in runtimes/,
    });

    expect(customRow).toBeInTheDocument();
    expect(builtinsToggle).toHaveAttribute("aria-expanded", "false");
    expect(
      customTitle.compareDocumentPosition(builtinsToggle) &
        Node.DOCUMENT_POSITION_FOLLOWING,
    ).toBeTruthy();
    expect(screen.queryByText("claude")).not.toBeInTheDocument();

    fireEvent.click(builtinsToggle);

    expect(builtinsToggle).toHaveAttribute("aria-expanded", "true");
    expect(screen.getByText("claude")).toBeInTheDocument();
  });

  it("clears built-in detail when the built-in reference section collapses", () => {
    queryState.profiles = [profile()];

    renderDialog();

    const builtinsToggle = screen.getByRole("button", {
      name: /Built-in runtimes/,
    });
    fireEvent.click(builtinsToggle);
    fireEvent.click(screen.getByRole("option", { name: /claude/i }));

    expect(
      screen.getByText(/claude is a built-in runtime/),
    ).toBeInTheDocument();

    fireEvent.click(builtinsToggle);

    expect(screen.getByText("Select a runtime")).toBeInTheDocument();
    expect(
      screen.queryByText(/claude is a built-in runtime/),
    ).not.toBeInTheDocument();
  });

  it("creates an Oh-My-Pi compatibility target without a client protocol mapping", async () => {
    renderDialog({ intent: "create" });
    fireEvent.click(screen.getByRole("button", { name: "Oh-My-Pi" }));
    fireEvent.change(screen.getByLabelText("Display name"), {
      target: { value: "Custom OMP" },
    });
    fireEvent.change(screen.getByLabelText("Command"), {
      target: { value: "wrapper launch" },
    });
    fireEvent.click(screen.getByRole("button", { name: "Create runtime" }));
    await waitFor(() =>
      expect(mutationState.createProfile).toHaveBeenCalledWith({
        daemon_id: "daemon-target",
        display_name: "Custom OMP",
        runtime_type: "omp",
        command_name: "wrapper",
        fixed_args: ["launch"],
      }),
    );
  });

  it("creates a custom Devin runtime from the protocol picker", async () => {
    renderDialog({ intent: "create" });
    fireEvent.click(screen.getByRole("button", { name: /^devin$/i }));
    fireEvent.change(screen.getByLabelText("Display name"), {
      target: { value: "Team Devin" },
    });
    fireEvent.change(screen.getByLabelText("Command"), {
      target: { value: "team-devin" },
    });
    fireEvent.click(screen.getByRole("button", { name: "Create runtime" }));
    await waitFor(() =>
      expect(mutationState.createProfile).toHaveBeenCalledWith({
        daemon_id: "daemon-target",
        display_name: "Team Devin",
        runtime_type: "devin",
        command_name: "team-devin",
        fixed_args: [],
      }),
    );
  });

  it("parses a pasted command line into fixed_args on create", async () => {
    renderDialog();

    const newRuntimeButtons = screen.getAllByRole("button", {
      name: "New custom runtime",
    });
    expect(newRuntimeButtons[0]).toBeDefined();
    fireEvent.click(newRuntimeButtons[0]!);
    fireEvent.click(screen.getByRole("button", { name: /codex/i }));
    fireEvent.change(screen.getByLabelText("Display name"), {
      target: { value: "Composer Agent" },
    });
    fireEvent.change(screen.getByLabelText("Command"), {
      target: { value: "agent --model composer-2.5" },
    });

    expect(screen.getByText("Executable:")).toBeInTheDocument();
    expect(screen.getByText("agent")).toBeInTheDocument();
    expect(screen.getByText("--model")).toBeInTheDocument();
    expect(screen.getByText("composer-2.5")).toBeInTheDocument();

    fireEvent.click(screen.getByRole("button", { name: "Create runtime" }));

    await waitFor(() =>
      expect(mutationState.createProfile).toHaveBeenCalledWith({
        daemon_id: "daemon-target",
        display_name: "Composer Agent",
        runtime_type: "codex",
        command_name: "agent",
        fixed_args: ["--model", "composer-2.5"],
      }),
    );
  });

  it("opens the focused create flow from a machine and closes after creation", async () => {
    const onClose = vi.fn();
    const onProfileCreated = vi.fn();
    renderDialog({
      intent: "create",
      machineName: "Studio Mac",
      onClose,
      onProfileCreated,
    });

    expect(
      screen.getByRole("heading", { name: "New custom runtime" }),
    ).toBeInTheDocument();
    expect(screen.getByText("Only Studio Mac will register this custom command.")).toBeInTheDocument();
    expect(
      screen.getByRole("link", { name: "View setup guide" }),
    ).toHaveAttribute(
      "href",
      "https://multica.ai/docs/daemon-runtimes#custom-runtime-profiles",
    );
    expect(screen.getByText("Step 1 of 2")).toBeInTheDocument();
    expect(
      screen.queryByText("Create your first custom runtime"),
    ).not.toBeInTheDocument();
    expect(
      screen.queryByRole("button", { name: "Back" }),
    ).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole("button", { name: /codex/i }));
    expect(screen.getByText("Step 2 of 2")).toBeInTheDocument();
    fireEvent.change(screen.getByLabelText("Display name"), {
      target: { value: "Composer Agent" },
    });
    fireEvent.change(screen.getByLabelText("Command"), {
      target: { value: "agent --model composer-2.5" },
    });
    fireEvent.click(screen.getByRole("button", { name: "Create runtime" }));

    await waitFor(() => {
      expect(onProfileCreated).toHaveBeenCalledWith(
        expect.objectContaining({ id: "prof-1" }),
      );
      expect(onClose).toHaveBeenCalledTimes(1);
    });
  });

  it("opens a custom runtime directly in edit mode", () => {
    renderDialog({
      intent: "edit",
      initialProfile: profile(),
    });

    expect(
      screen.getByRole("heading", { name: "Edit custom runtime" }),
    ).toBeInTheDocument();
    expect(screen.getByLabelText("Display name")).toHaveValue("Team Codex");
    expect(screen.getByLabelText("Command")).toHaveValue("codex");
    expect(
      screen.queryByText("Create your first custom runtime"),
    ).not.toBeInTheDocument();
  });
});