Skip to content

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

Go
13.6 KB
Raw Blame
import type { ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { I18nProvider } from "@multica/core/i18n/react";
import { configStore } from "@multica/core/config";
import enCommon from "../../locales/en/common.json";
import enSettings from "../../locales/en/settings.json";

const mockUpdateWorkspace = vi.hoisted(() => vi.fn());
const mockDeleteInstallation = vi.hoisted(() => vi.fn());
const mockConnectGitHub = vi.hoisted(() => vi.fn());
const mockInvalidate = vi.hoisted(() => vi.fn());

const workspaceRef = vi.hoisted(() => ({
  current: {
    id: "workspace-1",
    name: "Acme",
    slug: "acme",
    issue_prefix: "ACM",
    settings: {} as Record<string, unknown>,
  },
}));
const roleRef = vi.hoisted(() => ({
  current: "owner" as "owner" | "admin" | "member",
}));
const installationsRef = vi.hoisted(() => ({
  current: {
    installations: [] as { id: string; account_login: string; connected_by?: string }[],
    configured: true,
    can_manage: true as boolean,
  },
}));

vi.mock("@tanstack/react-query", () => ({
  useQuery: (opts: { queryKey: unknown[] }) =>
    JSON.stringify(opts.queryKey).includes("installations")
      ? { data: installationsRef.current }
      : { data: [] },
  useQueryClient: () => ({ setQueryData: vi.fn(), invalidateQueries: mockInvalidate }),
  queryOptions: <T,>(opts: T) => opts,
}));
vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
vi.mock("@multica/core/paths", () => ({ useCurrentWorkspace: () => workspaceRef.current }));
vi.mock("@multica/core/permissions", () => ({
  useCurrentMember: () => ({
    role: roleRef.current,
    member: { role: roleRef.current },
    isLoading: false,
  }),
}));
vi.mock("@multica/core/workspace/queries", () => ({
  memberListOptions: () => ({ queryKey: ["members"] }),
  workspaceKeys: { list: () => ["workspaces"] },
}));
vi.mock("@multica/core/github", async () => {
  const actual = await vi.importActual<typeof import("@multica/core/github")>(
    "@multica/core/github",
  );
  return {
    ...actual,
    githubInstallationsOptions: () => ({ queryKey: ["github", "installations"] }),
  };
});
vi.mock("@multica/core/api", () => ({
  api: {
    updateWorkspace: mockUpdateWorkspace,
    deleteGitHubInstallation: mockDeleteInstallation,
    getGitHubConnectURL: mockConnectGitHub,
  },
}));
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
// The repository list and self-hosted rows have their own tests.
vi.mock("./use-connect-github", () => ({
  useConnectGitHub: () => ({ connecting: false, connect: mockConnectGitHub, connectedInstallationID: "", reset: vi.fn() }),
}));
vi.mock("./repositories-section", () => ({ RepositoriesSection: () => null }));
vi.mock("./code-vcs", () => ({ VCSConnectionRows: () => <div>VCS rows</div> }));
// The merge rule editor has its own test on the statuses it offers.
vi.mock("./pr-merge-status-row", () => ({
  PRMergeStatusRow: ({ canManage }: { canManage: boolean }) => (
    <div>{canManage ? "merge rule editable" : "merge rule read-only"}</div>
  ),
}));

import { CodeTab } from "./code-tab";

const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };

function Wrapper({ children }: { children: ReactNode }) {
  return (
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      {children}
    </I18nProvider>
  );
}

beforeEach(() => {
  vi.clearAllMocks();
  workspaceRef.current = {
    id: "workspace-1",
    name: "Acme",
    slug: "acme",
    issue_prefix: "ACM",
    settings: { pr_merge_status: "done" },
  };
  roleRef.current = "owner";
  installationsRef.current = { installations: [], configured: true, can_manage: true };
  configStore
    .getState()
    .setAuthConfig({ allowSignup: true, vcsIntegrationAvailable: false });
  mockUpdateWorkspace.mockImplementation(async (_id: string, payload: object) => ({
    ...workspaceRef.current,
    ...payload,
  }));
});

function connect() {
  installationsRef.current = {
    installations: [{ id: "inst-1", account_login: "acme", connected_by: "Ada" }],
    configured: true,
    can_manage: true,
  };
}

describe("CodeTab — GitHub", () => {
  it("offers to connect GitHub through the shared connection action", async () => {
    const user = userEvent.setup();
    render(<CodeTab />, { wrapper: Wrapper });
    expect(screen.getByText("Not connected")).toBeInTheDocument();
    await user.click(screen.getByRole("button", { name: "Connect GitHub" }));
    expect(mockConnectGitHub).toHaveBeenCalledOnce();
  });

  it("names the account and who connected it", () => {
    connect();
    render(<CodeTab />, { wrapper: Wrapper });

    expect(screen.getByText("Connected")).toBeInTheDocument();
    expect(screen.getByText("Connected to acme")).toBeInTheDocument();
    expect(screen.getByText("Connected by Ada")).toBeInTheDocument();
  });

  it("keeps adding available with two connections and attributes each connection", async () => {
    connect();
    installationsRef.current.installations.push({ id: "inst-2", account_login: "other-org", connected_by: "Grace" });
    const user = userEvent.setup();
    render(<CodeTab />, { wrapper: Wrapper });

    expect(screen.getByText("Connected by Ada")).toBeInTheDocument();
    expect(screen.getByText("Connected by Grace")).toBeInTheDocument();
    await user.click(screen.getByRole("button", { name: "Add account or organization" }));
    expect(mockConnectGitHub).toHaveBeenCalledOnce();
    expect(mockDeleteInstallation).not.toHaveBeenCalled();
    expect(mockUpdateWorkspace).not.toHaveBeenCalled();
  });

  it.each([["acme", "inst-1"], ["other-org", "inst-2"]])(
    "disconnects only %s and leaves the other connection and workspace settings intact",
    async (login, id) => {
      connect();
      installationsRef.current.installations.push({ id: "inst-2", account_login: "other-org", connected_by: "Grace" });
      const user = userEvent.setup();
      const { rerender } = render(<CodeTab />, { wrapper: Wrapper });

      await user.click(screen.getByRole("button", { name: `Disconnect ${login}` }));
      const dialog = await screen.findByRole("alertdialog");
      expect(dialog).toHaveTextContent(login!);
      expect(mockDeleteInstallation).not.toHaveBeenCalled();
      await user.click(within(dialog).getByRole("button", { name: "Disconnect" }));
      await waitFor(() => expect(mockDeleteInstallation).toHaveBeenCalledExactlyOnceWith("workspace-1", id));
      expect(mockUpdateWorkspace).not.toHaveBeenCalled();
      installationsRef.current.installations = installationsRef.current.installations.filter((installation) => installation.id !== id);
      rerender(<CodeTab />);
      expect(screen.getByText(id === "inst-1" ? "Connected to other-org" : "Connected to acme")).toBeInTheDocument();
    },
  );

  it("shows both connections without management controls when can_manage is false", () => {
    connect();
    installationsRef.current.installations.push({ id: "inst-2", account_login: "other-org", connected_by: "Grace" });
    installationsRef.current.can_manage = false;
    render(<CodeTab />, { wrapper: Wrapper });
    expect(screen.getByText("Connected to acme")).toBeInTheDocument();
    expect(screen.getByText("Connected to other-org")).toBeInTheDocument();
    expect(screen.queryByRole("button", { name: /Disconnect|Add account|GitHub actions/ })).toBeNull();
  });

  it("pauses GitHub from the row menu, keeping the other settings", async () => {
    connect();
    workspaceRef.current.settings = { pr_merge_status: "done", co_authored_by_enabled: false };
    const user = userEvent.setup();
    render(<CodeTab />, { wrapper: Wrapper });

    await user.click(screen.getByRole("button", { name: "GitHub actions" }));
    await user.click(await screen.findByRole("menuitem", { name: "Pause GitHub features" }));

    await waitFor(() => {
      expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
        settings: {
          pr_merge_status: "done",
          co_authored_by_enabled: false,
          github_enabled: false,
        },
      });
    });
  });

  it("disables the PR switches while GitHub is paused", () => {
    connect();
    workspaceRef.current.settings = { github_enabled: false };
    render(<CodeTab />, { wrapper: Wrapper });

    expect(screen.getByText("Paused")).toBeInTheDocument();
    for (const name of ["Pull Request sidebar", "Auto-link issues and PRs", "Co-authored-by trailer"]) {
      expect(screen.getByRole("switch", { name })).toHaveAttribute("aria-disabled", "true");
    }
  });

  // A pause outlives a disconnect. Resuming must not need an App, or an
  // unconfigured deployment could never turn Co-authored-by back on.
  it("resumes paused GitHub features without an installation", async () => {
    installationsRef.current = { installations: [], configured: false, can_manage: true };
    workspaceRef.current.settings = { github_enabled: false };
    const user = userEvent.setup();
    render(<CodeTab />, { wrapper: Wrapper });

    expect(screen.getByText("Not connected")).toBeInTheDocument();
    expect(screen.getByText(/GitHub features are paused/)).toBeInTheDocument();
    await user.click(screen.getByRole("button", { name: "GitHub actions" }));
    expect(screen.queryByRole("menuitem", { name: "Disconnect" })).toBeNull();
    await user.click(await screen.findByRole("menuitem", { name: "Resume GitHub features" }));

    await waitFor(() => {
      expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
        settings: { github_enabled: true },
      });
    });
  });

  it("disconnects only after confirmation", async () => {
    connect();
    mockDeleteInstallation.mockResolvedValue(undefined);
    const user = userEvent.setup();
    render(<CodeTab />, { wrapper: Wrapper });

    await user.click(screen.getByRole("button", { name: "Disconnect acme" }));
    expect(mockDeleteInstallation).not.toHaveBeenCalled();
    const dialog = await screen.findByRole("alertdialog");
    await user.click(within(dialog).getByRole("button", { name: "Disconnect" }));

    await waitFor(() =>
      expect(mockDeleteInstallation).toHaveBeenCalledWith("workspace-1", "inst-1"),
    );
  });

  it.each(["cancel", "confirm"])("keeps the account name in the outgoing confirmation on %s", async (action) => {
    connect();
    installationsRef.current.installations.push({ id: "inst-2", account_login: "other-org" });
    mockDeleteInstallation.mockResolvedValue(undefined);
    const user = userEvent.setup();
    render(<CodeTab />, { wrapper: Wrapper });

    await user.click(screen.getByRole("button", { name: "Disconnect acme" }));
    const dialog = await screen.findByRole("alertdialog");
    // Keep the outgoing node: jsdom does not run the dialog's exit animation.
    const description = within(dialog).getByText(/^Disconnect acme from this workspace\?/);
    await user.click(within(dialog).getByRole("button", { name: action === "cancel" ? "Cancel" : "Disconnect" }));
    await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());

    expect(description).toHaveTextContent("Disconnect acme from this workspace?");
    if (action === "cancel") {
      expect(mockDeleteInstallation).not.toHaveBeenCalled();
    } else {
      expect(mockDeleteInstallation).toHaveBeenCalledExactlyOnceWith("workspace-1", "inst-1");
    }

    await user.click(screen.getByRole("button", { name: "Disconnect other-org" }));
    expect(await screen.findByRole("alertdialog")).toHaveTextContent("Disconnect other-org from this workspace?");
  });

  it("shows members the connection read-only and who can change it", () => {
    connect();
    roleRef.current = "member";
    installationsRef.current.can_manage = false;
    render(<CodeTab />, { wrapper: Wrapper });

    expect(screen.getByRole("note")).toHaveTextContent("View only");
    expect(screen.queryByRole("button", { name: "GitHub actions" })).toBeNull();
    expect(screen.getByRole("switch", { name: "Pull Request sidebar" })).toHaveAttribute(
      "aria-disabled",
      "true",
    );
  });
});

describe("CodeTab — pull requests", () => {
  it("saves a PR switch into the workspace settings", async () => {
    connect();
    const user = userEvent.setup();
    render(<CodeTab />, { wrapper: Wrapper });

    await user.click(screen.getByRole("switch", { name: "Co-authored-by trailer" }));

    await waitFor(() => {
      expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
        settings: { pr_merge_status: "done", co_authored_by_enabled: false },
      });
    });
  });

  it("uses the workspace prefix in the auto-link example", () => {
    render(<CodeTab />, { wrapper: Wrapper });
    expect(screen.getByText(/ACM-123/)).toBeInTheDocument();
  });

  it("edits the merge rule here, even while GitHub features are paused", () => {
    connect();
    workspaceRef.current.settings = { pr_merge_status: "done", github_enabled: false };
    const { unmount } = render(<CodeTab />, { wrapper: Wrapper });
    // Self-hosted Git merges follow the same rule, so pausing GitHub keeps it.
    expect(screen.getByText("merge rule editable")).toBeInTheDocument();
    unmount();

    roleRef.current = "member";
    render(<CodeTab />, { wrapper: Wrapper });
    expect(screen.getByText("merge rule read-only")).toBeInTheDocument();
  });

  it("lists self-hosted Git only where the deployment supports it", () => {
    const { unmount } = render(<CodeTab />, { wrapper: Wrapper });
    expect(screen.queryByText("VCS rows")).toBeNull();
    unmount();

    configStore
      .getState()
      .setAuthConfig({ allowSignup: true, vcsIntegrationAvailable: true });
    render(<CodeTab />, { wrapper: Wrapper });
    expect(screen.getByText("VCS rows")).toBeInTheDocument();
  });
});