Files
PaperClipAI/ui/src/components/ProjectGitAuthorization.test.tsx
T
Nicky LeachandPaperclip 828b8c2a2a Hide background GitHub authorization until a project has a private repository (#23421)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Project settings let a project editor manage GitHub repositories.
> - The settings page offers a GitHub credential for background
repository work.
> - Projects with only public repositories or no repositories also see
the consent form.
> - This pull request shows the form when a saved repository is known to
be private.
> - The form disappears when the editor removes the last private
repository.

## Linked Issues or Issue Description

**What happened?**

Project settings showed Background GitHub authorization for every
project.

**Expected behavior**

Show the section only while the project has a private GitHub repository.

**Steps to reproduce**

Open settings for a project with no repositories or only public
repositories. The authorization form appeared on master.

**Paperclip version or commit**

Reproduced at `07af22c57f`. The original authorization form shipped in
#17798.

## What Changed

- Reuse the repository picker’s catalog query to check visibility for
saved workspace URLs. Fall back to saved visibility when it belongs to
the same URL.
- Mount the consent form and load its authorization data only when a
saved repository is private.

## Verification

- The UI typecheck and all three authorization component tests passed
locally on macOS at `d5332c47a5`. The tests cover legacy Git URLs and
bound catalog reads across repeated renders with 502 repositories. The
regression tests failed before their fixes.
- GitHub CI passed the typecheck, build, selected tests, and browser
shards for the same commit. [CI
run](https://github.com/paperclipai/paperclip/actions/runs/46757316515)
- Before the rebase, the UI typecheck and all 249 selected UI test files
passed. The broader local verifier failed in CLI tests, including
embedded Postgres startup, CLI profile selection, and the tailnet bind
address.

## Risks

- A repository with unknown visibility keeps the section hidden until
the catalog or saved metadata confirms it is private.
- Removing the last private repository hides the revoke button along
with the form. The existing grant stays in place.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex (GPT-6), with repository editing, shell execution, and
local test tools.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 22:24:35 +00:00

173 lines
8.0 KiB
TypeScript

// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Project } from "@paperclipai/shared";
import { describe, expect, it, vi } from "vitest";
import { projectsApi } from "@/api/projects";
import { ProjectGitAuthorization } from "./ProjectGitAuthorization";
import { repositoryOptionsKey } from "./ProjectRepositoryInput";
import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
vi.mock("@/api/projects", () => ({
projectsApi: {
gitAuthorization: vi.fn(),
repositoryOptions: vi.fn(async () => ({ repositories: [], connectionCount: 0, failedConnectionCount: 0 })),
setGitAuthorization: vi.fn(),
},
}));
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
describe("ProjectGitAuthorization", () => {
const repoUrl = "https://github.com/team/source";
type SavedWorkspace = Pick<Project["workspaces"][number], "repoUrl" | "metadata">;
const privateWorkspace: SavedWorkspace = { repoUrl, metadata: { githubRepositoryUrl: repoUrl, githubRepositoryPrivate: true } };
const project = { id: "project-a", companyId: "company-a", workspaces: [privateWorkspace] } as Project;
it("shows and loads authorization only while a saved repository is known to be private", async () => {
const client = new QueryClient();
const container = document.createElement("div");
const root = createRoot(container);
const catalogUrl = "https://github.com/team/older";
const publicUrl = "https://github.com/team/public";
const catalogSize = 500;
let catalogUrlReads = 0;
const otherRepositories = Array.from({ length: catalogSize }, (_, index) => ({
id: String(index), fullName: `team/repo-${index}`, private: true, connections: [],
get url() {
if (++catalogUrlReads > catalogSize) throw new Error("Repeated catalog scan");
return `https://github.com/team/repo-${index}`;
},
}));
client.setQueryData(repositoryOptionsKey(project.companyId), {
connectionCount: 1, failedConnectionCount: 0,
repositories: [
...otherRepositories,
{ id: "older", fullName: "team/older", url: catalogUrl, private: true, connections: [] },
{ id: "public", fullName: "team/public", url: publicUrl, private: false, connections: [] },
],
});
vi.mocked(projectsApi.gitAuthorization).mockClear().mockResolvedValue({ grantId: null, authorizedByUserId: null, options: [] });
const render = async (workspaces: SavedWorkspace[]) => {
await act(async () => root.render(<QueryClientProvider client={client}>
<ProjectGitAuthorization project={{ ...project, workspaces } as Project} />
</QueryClientProvider>));
return container.querySelector('section[aria-label="Background GitHub authorization"]');
};
try {
expect(await render([])).toBeNull();
const publicWorkspace = { repoUrl: publicUrl, metadata: { githubRepositoryUrl: publicUrl, githubRepositoryPrivate: true } };
expect(await render([publicWorkspace, { repoUrl, metadata: null }])).toBeNull();
expect(projectsApi.gitAuthorization).not.toHaveBeenCalled();
expect(await render([publicWorkspace, { repoUrl: catalogUrl + ".git", metadata: null }])).not.toBeNull();
expect(projectsApi.gitAuthorization).toHaveBeenCalledWith(project.id);
expect(await render([{ ...privateWorkspace, repoUrl: repoUrl + ".git/" }])).not.toBeNull();
expect(await render([{ ...privateWorkspace, repoUrl: "https://github.com/team/another" }])).toBeNull();
expect(await render([{ ...privateWorkspace, repoUrl: null }, publicWorkspace])).toBeNull();
expect(catalogUrlReads).toBe(catalogSize);
} finally {
await act(async () => root.unmount());
client.clear();
}
});
it("explains standing credential consent and revokes without retaining task context", async () => {
const saved = {
grantId: "grant-a",
authorizedByUserId: "user-a",
options: [
{
grantId: "grant-a",
connectionName: "Work GitHub",
login: "fixture-login",
},
],
};
vi.mocked(projectsApi.gitAuthorization).mockResolvedValue(saved);
vi.mocked(projectsApi.setGitAuthorization).mockResolvedValue({
...saved,
grantId: null,
authorizedByUserId: null,
});
const client = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
});
client.setQueryData(["project-git-authorization", "company-a", "project-a"], saved);
const container = document.createElement("div"),
root = createRoot(container);
document.body.appendChild(container);
try {
await act(async () =>
root.render(
<QueryClientProvider client={client}>
<ProjectGitAuthorization project={project} />
</QueryClientProvider>,
),
);
expect(container.textContent).toContain("existing GitHub permissions");
expect(container.textContent).toContain("Project repository editors can add repositories covered by this connection");
expect(container.textContent).toContain("Manage repository access in the GitHub connection");
expect(container.textContent).toContain("Task runs continue to use their own identity");
expect(container.textContent).toContain("fixture-login");
const authorize = [...container.querySelectorAll("button")].find(
(button) => button.textContent === "Authorize project",
)!;
expect(authorize.disabled).toBe(true);
const revoke = [...container.querySelectorAll("button")].find(
(button) => button.textContent === "Revoke authorization",
)!;
await act(async () => {
revoke.click();
await new Promise((resolve) => setTimeout(resolve, 10));
});
expect(projectsApi.setGitAuthorization).toHaveBeenCalledWith("project-a", null);
expect(client.getQueryData(["project-git-authorization", "company-a", "project-a"])).toMatchObject({
grantId: null,
});
expect(container.textContent).not.toContain("Revoke authorization");
} finally {
await act(async () => root.unmount());
container.remove();
client.clear();
}
});
it("masks GitHub logins in session replay", async () => {
const saved = {
grantId: "grant-a",
authorizedByUserId: "user-a",
options: [
{ grantId: "grant-a", connectionName: "Work GitHub", login: "saved-octo-quillon" },
{ grantId: "grant-b", connectionName: "Side GitHub", login: "picked-octo-varnell" },
],
};
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
client.setQueryData(["project-git-authorization", "company-a", "project-b"], saved);
const container = document.createElement("div"),
root = createRoot(container);
document.body.appendChild(container);
try {
await act(async () =>
root.render(
<QueryClientProvider client={client}>
<ProjectGitAuthorization project={{ ...project, id: "project-b" }} />
</QueryClientProvider>,
),
);
expect(replayLeaks("saved-octo-quillon", container)).toEqual({ rendered: true, recorded: false });
const trigger = container.querySelector<HTMLElement>('[role="combobox"]')!;
await act(async () => {
trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
});
expect(replayLeaks("picked-octo-varnell", document.body)).toEqual({ rendered: true, recorded: false });
const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((item) => item.textContent?.includes("picked-octo-varnell"))!;
await act(async () => option.click());
expect(replayLeaks("picked-octo-varnell", trigger)).toEqual({ rendered: true, recorded: false });
} finally {
await act(async () => root.unmount());
container.remove();
client.clear();
}
});
});