Skip to content

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

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

import { describe, it, expect, vi, beforeEach } from "vitest";
import type { ComponentProps, ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
import type { AgentRuntime, RuntimeProfile } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
import enLayout from "../../locales/en/layout.json";
import enRuntimes from "../../locales/en/runtimes.json";
import enAgents from "../../locales/en/agents.json";

const TEST_RESOURCES = {
  en: { common: enCommon, layout: enLayout, runtimes: enRuntimes, agents: enAgents },
};

const mockUpdateRuntime = vi.hoisted(() => vi.fn());
const mockUpdateRuntimeError = vi.hoisted(() => ({ value: null as unknown }));
const mockDeleteRuntimeProfile = vi.hoisted(() => vi.fn());
const mockQueryData = vi.hoisted(() => ({
  members: [] as Array<Record<string, unknown>>,
  profiles: [] as RuntimeProfile[],
}));

vi.mock("@multica/core/hooks", () => ({
  useWorkspaceId: () => "ws-1",
}));

vi.mock("@multica/core/api", async (importOriginal) => ({
  ...await importOriginal<typeof import("@multica/core/api")>(),
  api: {
    updateRuntime: (...args: unknown[]) => mockUpdateRuntime(...args),
    revokeRuntimeWorkspaceAccess: vi.fn(),
    deleteRuntime: vi.fn(),
    unbindAgentsAndDeleteRuntime: vi.fn(),
    deleteRuntimeProfile: (...args: unknown[]) =>
      mockDeleteRuntimeProfile(...args),
  },
}));

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

// Pull the bits we want to test directly from the detail file. They aren't
// exported, so we exercise them through RuntimeDetail's DiagnosticsCard.
// Easier path: import the inner components by re-exporting them from a
// shared module. They live in the same file as RuntimeDetail; rather than
// touching the prod file just to ease testing, we test by rendering
// `RuntimeDetail` with a runtime fixture and asserting on the visibility
// UI. To avoid pulling in the entire detail page (which would need
// presence maps, member lists, paths, agents queries, etc.) we stub the
// heavy queries below.
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?: readonly unknown[] }) => {
      const key = options?.queryKey;
      if (key?.[0] === "runtime-profiles") {
        return { data: mockQueryData.profiles, isLoading: false };
      }
      if (key?.[0] === "workspaces" && key?.[2] === "members") {
        return { data: mockQueryData.members, isLoading: false };
      }
      return { data: [], isLoading: false };
    }),
  };
});

vi.mock("@multica/core/auth", () => ({
  useAuthStore: (sel: (s: { user: { id: string } }) => unknown) =>
    sel({ user: { id: "user-me" } }),
}));

// isRuntimeUsableForUser is the shared owner/public rule the component reads
// runtime access from, so the real implementation is kept rather than stubbed —
// a stub here would just re-derive the rule this test is meant to pin down.
vi.mock("@multica/core/runtimes", async () => ({
  isRuntimeUsableForUser: (
    await vi.importActual<typeof import("@multica/core/runtimes")>(
      "@multica/core/runtimes",
    )
  ).isRuntimeUsableForUser,
  deriveRuntimeHealth: () => "online",
  runtimeDisplayName: (rt: { name: string; custom_name?: string | null }) =>
    rt.custom_name?.trim() || rt.name,
  runtimeDisplayLabel: (rt: { name: string; custom_name?: string | null }) =>
    rt.custom_name?.trim() || rt.name,
  runtimeProfileListOptions: (wsId: string) => ({
    queryKey: ["runtime-profiles", wsId],
  }),
  parseRuntimeProfileBoundConflict: () => null,
  useDeleteRuntimeProfile: () => ({
    mutate: vi.fn(),
    isPending: false,
    mutateAsync: (...args: unknown[]) => mockDeleteRuntimeProfile(...args),
  }),
}));

vi.mock("@multica/core/agents", () => ({
  useWorkspacePresenceMap: () => ({ byAgent: new Map() }),
  AGENT_MAX_CONCURRENT_TASKS_MIN: 1,
  AGENT_MAX_CONCURRENT_TASKS_MAX: 50,
}));

vi.mock("@multica/core/paths", () => ({
  useWorkspacePaths: () => ({
    runtimes: () => "/runtimes",
    agentDetail: () => "/agents",
  }),
}));

vi.mock("@multica/core/runtimes/mutations", () => ({
  useUpdateRuntime: () => ({
    mutate: (
      args: { runtimeId: string; patch: Record<string, unknown> },
      opts?: { onSuccess?: () => void; onError?: (error: unknown) => void },
    ) => {
      mockUpdateRuntime(args.runtimeId, args.patch);
      if (mockUpdateRuntimeError.value) {
        opts?.onError?.(mockUpdateRuntimeError.value);
      } else {
        opts?.onSuccess?.();
      }
    },
    isPending: false,
  }),
  useRevokeRuntimeWorkspaceAccess: () => ({
    mutate: vi.fn(),
    isPending: false,
  }),
  useDeleteRuntime: () => ({ mutate: vi.fn(), isPending: false, mutateAsync: vi.fn() }),
  useUnbindAgentsAndDeleteRuntime: () => ({
    mutate: vi.fn(),
    isPending: false,
    mutateAsync: vi.fn(),
  }),
}));

// Stubbing ProviderLogo / UsageSection avoids dragging in chart libs and
// additional query keys we don't care about here.
vi.mock("./provider-logo", () => ({ ProviderLogo: () => null }));
vi.mock("./usage-section", () => ({
  UsageSection: () => <div data-testid="usage-section" />,
}));
vi.mock("./shared", async (importOriginal) => ({
  ...(await importOriginal<typeof import("./shared")>()),
  HealthBadge: () => null,
}));
vi.mock("../../agents/presence", () => ({
  availabilityConfig: { offline: { dotClass: "", textClass: "" } },
  workloadConfig: { idle: { icon: () => null, textClass: "" } },
}));
vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
vi.mock("../../navigation", () => ({
  AppLink: ({ href, children }: { href: string; children: ReactNode }) => (
    <a href={href}>{children}</a>
  ),
  useNavigation: () => ({ push: vi.fn(), replace: vi.fn() }),
}));

import { RuntimeDetail } from "./runtime-detail";
import { ApiError } from "@multica/core/api";

function makeRuntime(overrides: Partial<AgentRuntime>): AgentRuntime {
  return {
    id: "rt-1",
    workspace_id: "ws-1",
    daemon_id: null,
    name: "Local Runtime",
    runtime_mode: "local",
    provider: "claude",
    launch_header: "",
    status: "online",
    device_info: "host.local",
    metadata: {},
    owner_id: "user-me",
    visibility: "private",
    last_seen_at: "2026-04-27T11:59:50Z",
    created_at: "2026-04-01T00:00:00Z",
    updated_at: "2026-04-01T00:00:00Z",
    ...overrides,
  };
}

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

function renderDetail(
  runtime: AgentRuntime,
  props: Pick<
    ComponentProps<typeof RuntimeDetail>,
    "machineHref" | "machineLabel"
  > = {},
) {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return render(
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      <QueryClientProvider client={qc}>
        <RuntimeDetail runtime={runtime} {...props} />
      </QueryClientProvider>
    </I18nProvider>,
  );
}

describe("RuntimeDetail visibility section", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockQueryData.members = [];
    mockQueryData.profiles = [];
    mockUpdateRuntimeError.value = null;
    mockDeleteRuntimeProfile.mockResolvedValue(undefined);
  });

  it("shows owner-editable visibility choices when the caller owns the runtime", () => {
    renderDetail(makeRuntime({ owner_id: "user-me" }));
    expect(screen.getByRole("group", { name: "Visibility" })).toBeInTheDocument();
    for (const name of ["Private", "Public", "Members"]) {
      expect(screen.getByRole("button", { name })).toBeInTheDocument();
    }
  });

  it("opens a reviewed revocation plan instead of silently making an in-use public runtime private", async () => {
    mockUpdateRuntimeError.value = new ApiError("conflict", 409, "Conflict", {
      code: "runtime_has_nonowner_dependents",
      nonowner_agents: [{ id: "00000000-0000-4000-8000-000000000001", name: "Teammate Agent" }],
      active_task_ids: ["00000000-0000-4000-8000-000000000002"],
    });
    renderDetail(makeRuntime({ visibility: "public" }));

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

    expect(await screen.findByText("Restrict runtime access?")).toBeInTheDocument();
    expect(screen.getByText("Teammate Agent")).toBeInTheDocument();
    expect(screen.getByText(/Agents and runs that keep access are unaffected/)).toBeInTheDocument();
    expect(screen.getByText(/pause active autopilots assigned to those agents/)).toBeInTheDocument();
  });

  it("keeps daemon CLI version details without rendering update controls", () => {
    renderDetail(
      makeRuntime({
        metadata: { cli_version: "0.3.17" },
        runtime_mode: "local",
      }),
    );

    expect(screen.getByText("Daemon CLI")).toBeInTheDocument();
    expect(screen.getByText("0.3.17")).toBeInTheDocument();
    expect(
      screen.queryByRole("button", { name: "Update" }),
    ).not.toBeInTheDocument();
  });

  it("lays the runtime out as one header, body sections and a properties panel", () => {
    renderDetail(
      makeRuntime({ device_info: "host.local · 2.1.121 (Claude Code)" }),
      { machineHref: "/runtimes/local:daemon-1", machineLabel: "Studio Mac" },
    );

    expect(screen.getAllByRole("banner")).toHaveLength(1);
    expect(screen.getByRole("link", { name: "Runtimes" })).toHaveAttribute("href", "/runtimes");
    expect(screen.getByRole("link", { name: "Studio Mac" })).toHaveAttribute(
      "href",
      "/runtimes/local:daemon-1",
    );
    expect(screen.getByRole("heading", { level: 1 })).toBeInTheDocument();
    expect(screen.getByRole("heading", { level: 2, name: /Agents/ })).toBeInTheDocument();
    expect(screen.getByRole("heading", { level: 2, name: "Usage" })).toBeInTheDocument();
    expect(screen.getByText("No agents are bound to this runtime yet.")).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Properties" })).toBeInTheDocument();
    expect(screen.getByText("host.local")).toBeInTheDocument();
    expect(screen.getByText("2.1.121 (Claude Code)")).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Toggle right sidebar" })).toBeInTheDocument();
  });

  it("uses the provider name when the runtime alias is the machine name", () => {
    renderDetail(
      makeRuntime({
        name: "Pi (Studio Mac)",
        custom_name: "Studio Mac",
        provider: "pi",
      }),
      { machineHref: "/runtimes/local:daemon-1", machineLabel: "Studio Mac" },
    );

    expect(screen.getAllByText("Pi")).toHaveLength(2);
    expect(screen.getByRole("banner")).toHaveTextContent("Studio Mac");
  });

  it("preserves a runtime-specific alias that differs from the machine name", () => {
    renderDetail(
      makeRuntime({
        name: "Pi (Studio Mac)",
        custom_name: "Research Pi",
        provider: "pi",
      }),
      { machineHref: "/runtimes/local:daemon-1", machineLabel: "Studio Mac" },
    );

    expect(screen.getAllByText("Research Pi")).toHaveLength(2);
  });

  it("applies Public in one click, without a separate Save step", async () => {
    renderDetail(makeRuntime({ owner_id: "user-me", visibility: "private" }));
    expect(screen.getByRole("button", { name: "Private" })).toHaveAttribute("aria-pressed", "true");
    fireEvent.click(screen.getByRole("button", { name: "Public" }));
    await waitFor(() =>
      expect(mockUpdateRuntime).toHaveBeenCalledWith("rt-1", { visibility: "public", shared_with: [] }),
    );
  });

  it("does not send a request when the active scope is clicked again", () => {
    renderDetail(makeRuntime({ owner_id: "user-me", visibility: "private" }));
    fireEvent.click(screen.getByRole("button", { name: "Private" }));
    expect(mockUpdateRuntime).not.toHaveBeenCalled();
  });

  it("saves the selected members only after explicit confirmation", async () => {
    mockQueryData.members = [
      { user_id: "user-me", role: "member", name: "Me" },
      { user_id: "user-alice", role: "member", name: "Alice" },
      { user_id: "user-bob", role: "member", name: "Bob" },
    ];
    renderDetail(makeRuntime({}));
    fireEvent.click(screen.getByRole("button", { name: "Members" }));
    expect(await screen.findByText("Share with members")).toBeInTheDocument();
    // The owner is never offered as a recipient.
    expect(screen.queryByRole("checkbox", { name: "Me" })).not.toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
    fireEvent.click(screen.getByRole("checkbox", { name: "Alice" }));
    expect(mockUpdateRuntime).not.toHaveBeenCalled();
    fireEvent.click(screen.getByRole("button", { name: "Save" }));
    await waitFor(() => expect(mockUpdateRuntime).toHaveBeenCalledWith("rt-1", {
      visibility: "private", shared_with: ["user-alice"],
    }));
  });

  it("discards the member draft on Cancel", async () => {
    mockQueryData.members = [
      { user_id: "user-me", role: "member", name: "Me" },
      { user_id: "user-alice", role: "member", name: "Alice" },
    ];
    renderDetail(makeRuntime({}));
    fireEvent.click(screen.getByRole("button", { name: "Members" }));
    fireEvent.click(await screen.findByRole("checkbox", { name: "Alice" }));
    fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
    await waitFor(() => expect(screen.queryByText("Share with members")).not.toBeInTheDocument());
    expect(mockUpdateRuntime).not.toHaveBeenCalled();
  });

  it("summarizes current recipients and reopens the picker with them selected", async () => {
    mockQueryData.members = [
      { user_id: "user-me", role: "member", name: "Me" },
      { user_id: "user-alice", role: "member", name: "Alice" },
      { user_id: "user-bob", role: "member", name: "Bob" },
    ];
    renderDetail(makeRuntime({ shared_with: ["user-alice"] }));
    expect(screen.getByRole("button", { name: "Members" })).toHaveAttribute("aria-pressed", "true");
    fireEvent.click(screen.getByRole("button", { name: /Alice.*Edit/ }));
    expect(await screen.findByRole("checkbox", { name: "Alice" })).toBeChecked();
    expect(screen.getByRole("checkbox", { name: "Bob" })).not.toBeChecked();
    // An unchanged selection is not saveable.
    expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
  });

  it("filters a long member list by name", async () => {
    mockQueryData.members = [
      { user_id: "user-me", role: "member", name: "Me" },
      ...["Alice", "Bob", "Carol", "Dave", "Erin", "Frank", "Grace"].map((name) => ({
        user_id: `user-${name.toLowerCase()}`, role: "member", name,
      })),
    ];
    renderDetail(makeRuntime({}));
    fireEvent.click(screen.getByRole("button", { name: "Members" }));
    fireEvent.change(await screen.findByRole("textbox", { name: "Search members" }), { target: { value: "gr" } });
    expect(screen.getByRole("checkbox", { name: "Grace" })).toBeInTheDocument();
    expect(screen.queryByRole("checkbox", { name: "Alice" })).not.toBeInTheDocument();
  });

  it("shows a shared recipient the read-only scope and runtime usage", () => {
    renderDetail(makeRuntime({ owner_id: "someone-else", shared_with: ["user-me"] }));
    expect(screen.getByText("Specific members")).toBeInTheDocument();
    expect(screen.queryByRole("button", { name: "Save" })).not.toBeInTheDocument();
    expect(screen.getByTestId("usage-section")).toBeInTheDocument();
  });

  it("renders a read-only visibility chip when the caller cannot edit", () => {
    renderDetail(makeRuntime({ owner_id: "someone-else", visibility: "public" }));
    expect(screen.getByText("Public")).toBeInTheDocument();
    // The editor's "Private" choice button must not render in read-only mode.
    expect(screen.queryByText("Private")).not.toBeInTheDocument();
  });

  // MUL-6126: a workspace admin may rename or delete someone else's runtime,
  // but not share it — sharing is the owner's consent to lend their machine,
  // and the PATCH refuses an admin regardless of what this UI renders.
  it("keeps visibility read-only for a workspace admin who does not own the runtime", () => {
    mockQueryData.members = [
      { user_id: "user-me", role: "admin" },
      { user_id: "someone-else", role: "member" },
    ];
    renderDetail(
      makeRuntime({ owner_id: "someone-else", visibility: "private" }),
    );
    expect(screen.getByText("Private")).toBeInTheDocument();
    expect(screen.queryByText("Public")).not.toBeInTheDocument();
  });

  it("hides usage from a workspace admin viewing another member's private runtime", async () => {
    mockQueryData.members = [
      { user_id: "user-me", role: "admin" },
      { user_id: "someone-else", role: "member" },
    ];

    renderDetail(
      makeRuntime({ owner_id: "someone-else", visibility: "private" }),
    );

    expect(screen.queryByTestId("usage-section")).not.toBeInTheDocument();
    expect(await openDeleteItem()).toBeInTheDocument();
  });

  it("shows usage to a workspace admin viewing another member's public runtime", () => {
    mockQueryData.members = [
      { user_id: "user-me", role: "admin" },
      { user_id: "someone-else", role: "member" },
    ];

    renderDetail(
      makeRuntime({ owner_id: "someone-else", visibility: "public" }),
    );

    expect(screen.getByTestId("usage-section")).toBeInTheDocument();
  });

  // An ownerless runtime is unreadable server-side (the read gate reuses
  // canUseRuntimeForAgent, which is fail-closed without an owner), so the
  // page must not render a Usage section that can only 404.
  it("hides usage for an ownerless runtime even when it is public", () => {
    mockQueryData.members = [{ user_id: "user-me", role: "admin" }];

    renderDetail(makeRuntime({ owner_id: null, visibility: "public" }));

    expect(screen.queryByTestId("usage-section")).not.toBeInTheDocument();
  });

  // MUL-3352: an owner viewing an online local (self-healing) runtime
  // used to see a disabled Delete button with only a hover tooltip
  // explaining why. The new contract: the action is always clickable
  // for owner/admin; the dialog now carries the self-heal warning.
  it("offers an enabled Delete runtime action for an owner on a self-healing local runtime", async () => {
    renderDetail(
      makeRuntime({
        owner_id: "user-me",
        runtime_mode: "local",
        status: "online",
      }),
    );
    expect(await openDeleteItem()).not.toHaveAttribute("aria-disabled", "true");
  });

  it("hides the Delete runtime action entirely for callers who cannot edit", () => {
    renderDetail(
      makeRuntime({
        owner_id: "someone-else",
        runtime_mode: "local",
        status: "online",
      }),
    );
    expect(
      within(screen.getByRole("banner")).queryByRole("button", { name: "More actions" }),
    ).not.toBeInTheDocument();
    expect(screen.queryByText("Delete runtime")).not.toBeInTheDocument();
    expect(screen.getByText("Read-only")).toBeInTheDocument();
  });

  it("routes custom runtime deletion through the profile delete dialog for admins", async () => {
    const profile = makeProfile();
    mockQueryData.members = [
      { user_id: "user-me", role: "owner", name: "Me" },
    ];
    mockQueryData.profiles = [profile];

    renderDetail(
      makeRuntime({
        owner_id: "someone-else",
        profile_id: profile.id,
      }),
    );

    fireEvent.click(await openDeleteItem());
    expect(
      await screen.findByText("Delete custom runtime from workspace?"),
    ).toBeInTheDocument();
    expect(
      screen.getByRole("alertdialog", {
        name: "Delete custom runtime from workspace?",
      }),
    ).toBeInTheDocument();

    fireEvent.click(
      screen.getByRole("button", { name: "Delete from workspace" }),
    );
    await waitFor(() =>
      expect(mockDeleteRuntimeProfile).toHaveBeenCalledWith(profile.id),
    );
  });

  it("hides custom runtime delete for non-admin runtime owners", () => {
    const profile = makeProfile();
    mockQueryData.profiles = [profile];

    renderDetail(
      makeRuntime({
        owner_id: "user-me",
        profile_id: profile.id,
      }),
    );

    expect(
      within(screen.getByRole("banner")).queryByRole("button", { name: "More actions" }),
    ).not.toBeInTheDocument();
  });
});

async function openDeleteItem() {
  fireEvent.click(
    within(screen.getByRole("banner")).getByRole("button", { name: "More actions" }),
  );
  return screen.findByRole("menuitem", { name: /Delete runtime/i });
}