Skip to content

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

Go
21.2 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 enCommon from "../../locales/en/common.json";
import enSettings from "../../locales/en/settings.json";

const mockUpdateWorkspace = vi.hoisted(() => vi.fn());
const mockConnectGitHub = vi.hoisted(() => vi.fn());
const mockNavReplace = vi.hoisted(() => vi.fn());
const mockToastError = vi.hoisted(() => vi.fn());
const workspaceRef = vi.hoisted(() => ({
  current: {
    id: "workspace-1",
    name: "Test Workspace",
    slug: "test-workspace",
    repos: [] as { url: string; description?: string }[],
  },
}));
const roleRef = vi.hoisted(() => ({
  current: "owner" as "owner" | "admin" | "member",
}));
const githubRef = vi.hoisted(() => ({
  current: {
    installations: [] as { id: string; account_login: string }[],
    configured: true,
    repository_browse_configured: true,
    can_manage: true,
  },
}));
const githubQueryStateRef = vi.hoisted(() => ({
  current: { isPending: false, isFetching: false },
}));
const githubRepositoriesRef = vi.hoisted(() => ({
  current: [] as {
    id: number;
    full_name: string;
    html_url: string;
    clone_url: string;
    description: string | null;
    private: boolean;
    archived: boolean;
    default_branch: string;
  }[],
}));
const repositorySelectionRef = vi.hoisted(() => ({ current: "unknown" }));
const searchParamsRef = vi.hoisted(() => ({
  current: new URLSearchParams("tab=code"),
}));

vi.mock("@tanstack/react-query", () => ({
  useQuery: () => ({ data: githubRef.current, ...githubQueryStateRef.current }),
  useInfiniteQuery: () => ({
    data: {
      pages: [
        {
          repository_selection: repositorySelectionRef.current,
          repositories: githubRepositoriesRef.current,
          total_count: githubRepositoriesRef.current.length,
          next_page: null,
        },
      ],
    },
    isPending: false,
    isError: false,
    hasNextPage: false,
    isFetchingNextPage: false,
    fetchNextPage: vi.fn(),
  }),
  useQueryClient: () => ({ setQueryData: vi.fn() }),
  queryOptions: <T,>(options: T) => options,
  infiniteQueryOptions: <T,>(options: T) => options,
}));

vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
vi.mock("@multica/core/permissions", () => ({
  useCurrentMember: () => ({ role: roleRef.current, isLoading: false }),
}));
vi.mock("@multica/core/paths", () => ({
  useCurrentWorkspace: () => workspaceRef.current,
}));
vi.mock("@multica/core/workspace/queries", () => ({
  workspaceKeys: { list: () => ["workspaces"] },
}));
vi.mock("@multica/core/api", () => ({
  api: {
    updateWorkspace: mockUpdateWorkspace,
  },
}));
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: mockToastError } }));
vi.mock("../../navigation", () => ({
  useNavigation: () => ({
    push: vi.fn(),
    replace: mockNavReplace,
    pathname: "/acme/settings",
    searchParams: searchParamsRef.current,
  }),
}));

import { RepositoriesSection, repositoryIdentity } from "./repositories-section";

const connection = {
  connecting: false,
  connect: mockConnectGitHub,
  connectedInstallationID: "",
  reset: vi.fn(),
};

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: "Test Workspace",
    slug: "test-workspace",
    repos: [{ url: "https://github.com/multica-ai/multica", description: "Main app" }],
  };
  roleRef.current = "owner";
  githubRef.current = {
    installations: [],
    configured: true,
    repository_browse_configured: true,
    can_manage: true,
  };
  githubQueryStateRef.current = { isPending: false, isFetching: false };
  githubRepositoriesRef.current = [];
  repositorySelectionRef.current = "unknown";
  searchParamsRef.current = new URLSearchParams("tab=code");
  connection.connectedInstallationID = "";
  mockUpdateWorkspace.mockImplementation(async (_id: string, payload: object) => ({
    ...workspaceRef.current,
    ...payload,
  }));
});

async function openAddMenu(user: ReturnType<typeof userEvent.setup>) {
  await user.click(screen.getByRole("button", { name: /Add repository/ }));
}

describe("RepositoriesSection", () => {
  it("lists repositories as read-only rows with their description", () => {
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });

    expect(screen.getByText("https://github.com/multica-ai/multica")).toBeInTheDocument();
    expect(screen.getByText("Main app")).toBeInTheDocument();
    expect(screen.queryByRole("textbox")).toBeNull();
  });

  it("adds a repository from the dialog in one request", async () => {
    const user = userEvent.setup();
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });

    await openAddMenu(user);
    await user.click(await screen.findByRole("menuitem", { name: "Enter a URL..." }));
    const dialog = await screen.findByRole("dialog", { name: "Add repository" });
    const save = within(dialog).getByRole("button", { name: "Save" });
    expect(save).toBeDisabled();

    await user.type(
      within(dialog).getByRole("textbox", { name: "Repository URL" }),
      "[email protected]:acme/api.git",
    );
    await user.type(
      within(dialog).getByRole("textbox", { name: "Description" }),
      "  Go API  ",
    );
    await user.click(save);

    await waitFor(() => {
      expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
        repos: [
          { url: "https://github.com/multica-ai/multica", description: "Main app" },
          { url: "[email protected]:acme/api.git", description: "Go API" },
        ],
      });
    });
    await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
  });

  it("refuses a repository that is already listed under another URL form", async () => {
    const user = userEvent.setup();
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });

    await openAddMenu(user);
    await user.click(await screen.findByRole("menuitem", { name: "Enter a URL..." }));
    const dialog = await screen.findByRole("dialog", { name: "Add repository" });
    await user.type(
      within(dialog).getByRole("textbox", { name: "Repository URL" }),
      "[email protected]:multica-ai/multica.git",
    );

    expect(within(dialog).getByText("This repository is already added.")).toBeInTheDocument();
    expect(within(dialog).getByRole("button", { name: "Save" })).toBeDisabled();
  });

  it("keeps the dialog open with the input when saving fails", async () => {
    mockUpdateWorkspace.mockRejectedValueOnce(new Error("boom"));
    const user = userEvent.setup();
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });

    await user.click(screen.getByRole("button", { name: /Actions for https:\/\/github.com\/multica-ai\/multica/ }));
    await user.click(await screen.findByRole("menuitem", { name: "Edit" }));
    const dialog = await screen.findByRole("dialog", { name: "Edit repository" });
    const description = within(dialog).getByRole("textbox", { name: "Description" });
    await user.clear(description);
    await user.type(description, "Renamed");
    await user.click(within(dialog).getByRole("button", { name: "Save" }));

    await waitFor(() => expect(mockToastError).toHaveBeenCalledWith("boom"));
    expect(screen.getByRole("dialog", { name: "Edit repository" })).toBeInTheDocument();
    expect(description).toHaveValue("Renamed");
  });

  it("removes a repository only after confirmation", async () => {
    const user = userEvent.setup();
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });

    await user.click(screen.getByRole("button", { name: /Actions for https:\/\/github.com\/multica-ai\/multica/ }));
    await user.click(await screen.findByRole("menuitem", { name: "Delete repository" }));
    expect(mockUpdateWorkspace).not.toHaveBeenCalled();
    await user.click(
      within(await screen.findByRole("alertdialog")).getByRole("button", {
        name: "Delete repository",
      }),
    );

    await waitFor(() => {
      expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", { repos: [] });
    });
  });

  describe("when the list changes while a dialog is open", () => {
    const api = { url: "https://github.com/acme/api", description: "API" };
    const web = { url: "https://github.com/acme/web", description: "Web" };
    const docs = { url: "https://github.com/acme/docs", description: "Docs" };

    async function openRowAction(user: ReturnType<typeof userEvent.setup>, url: string, action: string) {
      await user.click(screen.getByRole("button", { name: `Actions for ${url}` }));
      await user.click(await screen.findByRole("menuitem", { name: action }));
    }

    function replaceRepos(rerender: (ui: ReactNode) => void, repos: typeof workspaceRef.current.repos) {
      workspaceRef.current = { ...workspaceRef.current, repos };
      rerender(<RepositoriesSection connection={connection} />);
    }

    async function saveDescription(user: ReturnType<typeof userEvent.setup>, text: string) {
      const dialog = screen.getByRole("dialog", { name: "Edit repository" });
      const description = within(dialog).getByRole("textbox", { name: "Description" });
      await user.clear(description);
      await user.type(description, text);
      await user.click(within(dialog).getByRole("button", { name: "Save" }));
    }

    beforeEach(() => {
      workspaceRef.current = { ...workspaceRef.current, repos: [api, web, docs] };
    });

    it("edits the repository the dialog was opened for", async () => {
      const user = userEvent.setup();
      const { rerender } = render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
      await openRowAction(user, web.url, "Edit");
      replaceRepos(rerender, [web, docs]);
      await saveDescription(user, "Web app");

      await waitFor(() =>
        expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
          repos: [{ url: web.url, description: "Web app" }, docs],
        }),
      );
    });

    it("saves an edit to a repository that was removed meanwhile", async () => {
      const user = userEvent.setup();
      const { rerender } = render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
      await openRowAction(user, web.url, "Edit");
      replaceRepos(rerender, [api, docs]);
      await saveDescription(user, "Web app");

      await waitFor(() =>
        expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
          repos: [api, docs, { url: web.url, description: "Web app" }],
        }),
      );
    });

    it("removes the repository the confirmation was opened for", async () => {
      const user = userEvent.setup();
      const { rerender } = render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
      await openRowAction(user, web.url, "Delete repository");
      const dialog = await screen.findByRole("alertdialog");
      replaceRepos(rerender, [web, docs]);
      await user.click(within(dialog).getByRole("button", { name: "Delete repository" }));

      await waitFor(() =>
        expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", { repos: [docs] }),
      );
    });
  });

  it("hides every write affordance from members", () => {
    roleRef.current = "member";
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });

    expect(screen.queryByRole("button", { name: /Add repository/ })).toBeNull();
    expect(screen.queryByRole("button", { name: /Actions for/ })).toBeNull();
  });

  it("starts GitHub connection through the shared handler", async () => {
    const user = userEvent.setup();
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
    await openAddMenu(user);
    await user.click(await screen.findByRole("menuitem", { name: /Connect GitHub/ }));
    expect(mockConnectGitHub).toHaveBeenCalledOnce();
  });

  it("keeps both browsing and adding an account available after connecting", async () => {
    githubRef.current.installations = [{ id: "existing", account_login: "alice" }];
    const user = userEvent.setup();
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
    await openAddMenu(user);
    expect(await screen.findByRole("menuitem", { name: "Choose from GitHub" })).toBeInTheDocument();
    await user.click(screen.getByRole("menuitem", { name: "Add account or organization" }));
    expect(mockConnectGitHub).toHaveBeenCalledOnce();
    expect(mockUpdateWorkspace).not.toHaveBeenCalled();
  });

  it("honors can_manage for GitHub even when workspace editing is available", async () => {
    githubRef.current.can_manage = false;
    githubRef.current.installations = [{ id: "existing", account_login: "alice" }];
    const user = userEvent.setup();
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
    await openAddMenu(user);
    expect(await screen.findByRole("menuitem", { name: "Enter a URL..." })).toBeInTheDocument();
    expect(screen.queryByRole("menuitem", { name: /GitHub|Add account/ })).toBeNull();
  });

  it.each([
    ["missing_authorization", /GitHub did not return user authorization/],
    ["installation_not_authorized", /admin access to every authorized repository/],
    ["invalid_state", /expired or is invalid/],
    ["missing_params", /incomplete/],
    ["bad_installation_id", /incomplete/],
    ["bad_workspace", /workspace/],
    ["verification_failed", /verify/],
    ["persist_failed", /save/],
    ["untrusted-value", /Could not connect GitHub/],
  ])("explains a %s callback without altering existing connections", async (code, message) => {
    githubRef.current.installations = [{ id: "existing", account_login: "alice" }];
    searchParamsRef.current = new URLSearchParams(`tab=code&section=github&github_error=${code}`);
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
    await waitFor(() => expect(mockToastError).toHaveBeenCalledWith(expect.stringMatching(message)));
    expect(mockNavReplace).toHaveBeenCalledWith("/acme/settings?tab=code&section=github");
    expect(screen.queryByRole("dialog")).toBeNull();
    expect(mockConnectGitHub).not.toHaveBeenCalled();
    expect(mockUpdateWorkspace).not.toHaveBeenCalled();
  });

  it("explains why GitHub import is unavailable when browsing is not configured", async () => {
    githubRef.current = { ...githubRef.current, repository_browse_configured: false };
    githubRef.current.installations = [{ id: "existing", account_login: "alice" }];
    const user = userEvent.setup();
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });

    await openAddMenu(user);
    const item = await screen.findByRole("menuitem", { name: /Choose from GitHub/ });
    expect(item).toHaveAttribute("aria-disabled", "true");
    expect(item).toHaveTextContent("GITHUB_APP_ID");
    expect(screen.getByRole("menuitem", { name: "Add account or organization" })).not.toHaveAttribute("aria-disabled", "true");
  });

  it("imports selected GitHub repositories and deduplicates HTTPS against SSH", async () => {
    workspaceRef.current = {
      ...workspaceRef.current,
      repos: [{ url: "[email protected]:multica-ai/multica.git" }],
    };
    githubRef.current = {
      ...githubRef.current,
      installations: [{ id: "installation-row-1", account_login: "multica-ai" }],
    };
    githubRepositoriesRef.current = [
      {
        id: 1,
        full_name: "multica-ai/multica",
        html_url: "https://github.com/multica-ai/multica",
        clone_url: "https://github.com/multica-ai/multica.git",
        description: "Existing repository",
        private: false,
        archived: false,
        default_branch: "main",
      },
      {
        id: 2,
        full_name: "multica-ai/console",
        html_url: "https://github.com/multica-ai/console",
        clone_url: "https://github.com/multica-ai/console.git",
        description: "Console app",
        private: true,
        archived: false,
        default_branch: "main",
      },
    ];
    const user = userEvent.setup();
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });

    await openAddMenu(user);
    await user.click(await screen.findByRole("menuitem", { name: /Choose from GitHub/ }));
    const checkboxes = await screen.findAllByRole("checkbox");
    expect(checkboxes).toHaveLength(2);
    expect(
      checkboxes[0]!.hasAttribute("disabled") ||
        checkboxes[0]!.getAttribute("aria-disabled") === "true",
    ).toBe(true);

    await user.click(checkboxes[1]!);
    await user.click(screen.getByRole("button", { name: "Add 1 repository" }));

    await waitFor(() => {
      expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
        repos: [
          { url: "[email protected]:multica-ai/multica.git" },
          { url: "https://github.com/multica-ai/console.git", description: "Console app" },
        ],
      });
    });
  });

  it("opens the picker after returning from a GitHub connection", async () => {
    githubRef.current = {
      ...githubRef.current,
      installations: [{ id: "installation-row-1", account_login: "multica-ai" }],
    };
    searchParamsRef.current = new URLSearchParams("tab=repositories&github_connected=1");

    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });

    expect(
      await screen.findByRole("heading", { name: "Choose GitHub repositories" }),
    ).toBeTruthy();
    expect(mockNavReplace).toHaveBeenCalledWith("/acme/settings?tab=repositories");
  });

  it.each(["selected", "all", "unknown"])("preselects only explicitly selected authorizations (%s) for the returned installation", async (selection) => {
    const user = userEvent.setup();
    githubRef.current.installations = [
      { id: "old-install", account_login: "old-org" },
      { id: "new-install", account_login: "new-org" },
    ];
    repositorySelectionRef.current = selection;
    githubRepositoriesRef.current = [
      { id: 1, full_name: "new-org/api", clone_url: "https://github.com/new-org/api.git", html_url: "https://github.com/new-org/api", description: null, private: true, archived: false, default_branch: "main" },
      { id: 2, full_name: "new-org/archived", clone_url: "https://github.com/new-org/archived.git", html_url: "https://github.com/new-org/archived", description: null, private: true, archived: true, default_branch: "main" },
    ];
    searchParamsRef.current = new URLSearchParams("tab=code&github_connected=1&github_installation=new-install");
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
    const checkbox = await screen.findByRole("checkbox", { name: /new-org\/api/ });
    if (selection === "selected") {
      await waitFor(() => expect(checkbox).toBeChecked());
      expect(mockUpdateWorkspace).not.toHaveBeenCalled();
      await user.click(checkbox);
      expect(checkbox).not.toBeChecked();
      expect(screen.getByRole("button", { name: "Add 0 repositories" })).toBeDisabled();
    } else {
      expect(checkbox).not.toBeChecked();
    }
    expect(screen.getByRole("checkbox", { name: /new-org\/archived/ })).not.toBeChecked();
    expect(mockNavReplace).toHaveBeenCalledWith("/acme/settings?tab=code");
  });

  it("opens the picker for the installation completed in the desktop window", async () => {
    githubRef.current.installations = [{ id: "new-install", account_login: "new-org" }];
    connection.connectedInstallationID = "new-install";
    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
    expect(await screen.findByRole("heading", { name: "Choose GitHub repositories" })).toBeInTheDocument();
    expect(connection.reset).toHaveBeenCalled();
    expect(mockUpdateWorkspace).not.toHaveBeenCalled();
  });

  it("clears the GitHub callback query after an empty installation result", async () => {
    searchParamsRef.current = new URLSearchParams("tab=repositories&github_connected=1");

    render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });

    await waitFor(() => {
      expect(mockNavReplace).toHaveBeenCalledWith("/acme/settings?tab=repositories");
    });
    expect(screen.queryByRole("heading", { name: "Choose GitHub repositories" })).toBeNull();
  });
});

describe("repositoryIdentity", () => {
  it("preserves repository path casing when comparing clone URLs", () => {
    expect(repositoryIdentity("https://GitHub.com/Acme/Repo.git")).toBe("github.com/Acme/Repo");
    expect(repositoryIdentity("[email protected]:acme/repo.git")).toBe("github.com/acme/repo");
  });

  it("keeps a non-default port, since it can name another server", () => {
    expect(repositoryIdentity("https://git.example.com:8443/acme/api.git")).not.toBe(
      repositoryIdentity("https://git.example.com:9443/acme/api.git"),
    );
    expect(repositoryIdentity("https://git.example.com:443/acme/api.git")).toBe(
      repositoryIdentity("[email protected]:acme/api.git"),
    );
    expect(repositoryIdentity("ssh://[email protected]:22/acme/api.git")).toBe(
      repositoryIdentity("[email protected]:acme/api.git"),
    );
  });
});