Files
PaperClipAI/server/src/services/chat-github-management.test.ts
T
DottaandPaperclip bc526683c2 fix(github-chat): fix initial repository import and verify UX states (#23760)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The GitHub Code Review Bot setup wizard registers a GitHub App,
discovers its installation repositories, imports initial repository
selections, and verifies access before activation.
> - When a user or agent saves review configuration on a draft before
installing the GitHub App, the wizard skipped initial repository import
because it required `saved.revision === 0`, leaving enabled GitHub
repositories disabled in Paperclip and showing a misleading "Enable at
least one repository from the App installation." error.
> - The wizard also closed initial repository import prematurely when
GitHub returned zero repositories, failed to refresh repositories on
retry, treated removed installations (HTTP 404) as generic 422 failures
and transient repository-sync errors as empty installations, omitted the
direct GitHub App installation link on verification errors, and kept
showing "Checking GitHub access…" while idle on a failed check.
> - This pull request decouples initial repository import from review
configuration revision, recovers verifying endpoints stuck with a
pending initial import, maps removed installations and transient
repository sync errors to structured verification check codes with
validated GitHub URLs, and updates the setup verify screen to show clear
error states, accurate paired links/labels, and active retry feedback.
> - The benefit is that pre-configured GitHub review bots connect
cleanly when the App is installed, and operators get accurate error
diagnostics, direct GitHub installation and Access settings links, and
clear retry feedback when setup checks fail.

## Linked Issues or Issue Description

**What happened?**

During GitHub Code Review Bot setup
(`/apps/chat/connect?provider=github&purpose=chat&resume=...`), the
verify step failed with "Enable at least one repository from the App
installation." even when one repository was already enabled on the
GitHub App installation. The verify screen also kept displaying
"Checking GitHub access…" when idle, did not link to the GitHub App
installation URL, and did not clearly explain whether the problem was on
GitHub or in Paperclip Access settings.

**Expected behavior**

Installing the GitHub App with one or more repositories enabled should
import and enable those repositories during initial setup even if custom
review configuration was saved earlier, while preserving that saved
configuration. When verification genuinely fails for missing
repositories, missing permissions, removed/suspended installations, or
transient GitHub repository sync errors, the screen should stop polling,
replace the checking indicator with a clear error card, pair each GitHub
link with an accurate label, link to Paperclip Access settings, and show
active checking feedback only while a retry or refetch is running.

**Steps to reproduce**

1. Create a GitHub Code Review Bot draft and save custom review
configuration (`PUT /api/chat-endpoints/:id/github/configuration`),
incrementing configuration revision to `1`.
2. Register and install the GitHub App on GitHub with one repository
selected, verify webhook delivery, and link a GitHub identity.
3. Resume
`/apps/chat/connect?provider=github&purpose=chat&resume=<endpointId>`.
4. Observe that `POST /api/chat-endpoints/:id/github/setup` leaves the
repository disabled, marks `initialRepositoriesImported: true` while
leaving `initialRepositoryImportPending: true`, and returns `state:
"verify"` with "Enable at least one repository from the App
installation." and no GitHub installation link.

**Paperclip version or commit**

Reproduced on `master` at commit `e2e2265085`.

**Deployment mode**

Self-hosted server

**Agent adapter(s) involved**

Not adapter-specific (core bug)

## What Changed

- Extract initial GitHub repository import eligibility/transition logic
into `server/src/services/chat-github-initial-import.ts` and decouple
initial repository import in `server/src/services/chat-github-wizard.ts`
from `saved.revision === 0` so pre-saved review configuration no longer
blocks enabling repositories granted during initial App installation,
while keeping `saved.revision === 0` strictly for default review
configuration writes.
- Recover verifying endpoints left in the prior half-state
(`initialRepositoriesImported: true` with
`initialRepositoryImportPending: true` and `repositorySelectionSaved`
unset) without re-enabling repositories after an explicit user save
(`repositorySelectionSaved: true`).
- Keep `initialRepositoryImportPending` open when GitHub returns zero
repositories during initial import
(`server/src/services/chat-github-wizard.ts` and
`server/src/services/chat-channels/resource-reconciliation.ts`), refresh
repository inventory on wizard retry when no enabled available
repository exists, and track transient repository-sync errors so failed
`/installation/repositories` refreshes skip initial import and emit
`repositories_sync_failed` instead of misreporting
`no_installation_repositories`.
- Map HTTP 404 on `/app/installations/:id` in
`server/src/services/chat-github-management.ts` to
`installation_missing` + `managementUrl` (keeping 401/403/5xx and
transient failures separate), and enforce `!permissionsOk` precedence
(`permissions_required`) over cached repository state.
- Preserve `setup.github.managementUrl` and sibling setup fields via
atomic `jsonb_set` in
`server/src/services/chat-channels/github/app-setup.ts`.
- Centralize strict GitHub URL validation
(`safeGitHubInstallationManagementUrl`, `safeGitHubAppInstallUrl`,
`safeGitHubAppUrl`) and structured `GitHubVerificationCheckCode` values
(including `repositories_sync_failed`) in
`packages/shared/src/types/github-app-setup.ts` and
`packages/shared/src/index.ts`, with OpenAPI schema updates in
`server/src/routes/openapi.ts` and UI API types in
`ui/src/api/githubChat.ts`.
- Extract `deriveGitHubVerifyView`, `shouldPollGitHubVerify`, and
`<GitHubVerifyStatus />` into
`ui/src/pages/apps/chat/GitHubVerifyStatus.tsx` and simplify
`ui/src/pages/apps/chat/GitHubChatSetup.tsx` so verification failures
stop 5-second background polling, pair every external GitHub link with
an accurate label (including `installation_missing` fallback to
`managementUrl`), show active checking feedback only while
retrying/refetching, and link to Paperclip Access and Connection
settings.
- Add unit, integration, and UI tests in
`server/src/services/chat-github-initial-import.test.ts`,
`server/src/services/chat-github-management.test.ts`,
`server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`,
`ui/src/pages/apps/chat/GitHubVerifyStatus.test.ts`, and
`ui/src/pages/apps/chat/GitHubChatSetup.test.tsx`.
- Update `tests/runner-e2e/source-sdk-public-inputs.json` for the shared
type and helper exports.

## Verification

Tested on Linux through revision `9a5a949098`:

- Red-green TDD proofs:
- Pre-saved review configuration and stuck verifying endpoint recovery
(`server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`):
confirmed both failed before the wizard fix (`Received: "verify"`,
`Expected: "connected"`) and passed after.
- Removed installation HTTP 404 (`installation_missing` +
`managementUrl`) and `!permissionsOk` precedence
(`server/src/services/chat-github-management.test.ts` + integration
test): confirmed red before fix, green after.
- Transient `/installation/repositories` 503 failure with empty cache
and valid permissions (`repositories_sync_failed`, followed by
successful retry -> `connected`) and UI `installation_missing` fallback
label (`ui/src/pages/apps/chat/GitHubVerifyStatus.test.ts`,
`GitHubChatSetup.test.tsx`,
`github-setup-and-access.integration.test.ts`): confirmed red before
fix, green after.
- Server unit & OpenAPI tests on `9a5a949098`:
- `pnpm --filter @paperclipai/server exec vitest run
src/services/chat-github-management.test.ts
src/services/chat-github-initial-import.test.ts` (47/47 passed: 39
management + 8 initial-import).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/openapi-routes.test.ts` (59/59 passed).
- Server integration tests (`c1f234335f`; full suite running in CI on
merged head `9a5a949098`):
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/chat-channels/github-setup-and-access.integration.test.ts
-t "recovers from an empty initial GitHub repository inventory|keeps
explicitly disabled repositories disabled|imports GitHub App
installation repositories even when review configuration was
pre-saved|recovers a verifying endpoint whose
initialRepositoriesImported|returns installation_missing with
managementUrl when the GitHub installation is removed|surfaces a
retryable repositories_sync_failed check"` (6/6 passed).
- UI tests & typecheck on `9a5a949098`:
- `pnpm --filter @paperclipai/ui exec vitest run
src/pages/apps/chat/GitHubChatSetup.test.tsx
src/pages/apps/chat/GitHubVerifyStatus.test.ts
src/pages/apps/chat/chat-ui-contract.test.ts` (27/27 passed) and
`ui/src/lib/analytics/replay-masking.test.tsx` (236/236 passed).
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/ui
typecheck` (passed).
- `node scripts/check-token-gates.mjs` — zero violations in touched
files.
- Release registry check on `9a5a949098`:
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
9a5a949098 --check` (`changed: false`, 602
inputs).
- Required CI checks (`ci / verify`, `ci / e2e`, `ci / Typecheck +
Release Registry`, `ci / Build`) cover the full matrix on `9a5a949098`.

## Risks

- Low risk. Auto-enabling repositories remains strictly fenced by
`bot.status !== "active"`, `initialRepositoryImportPending === true`,
and `!repositorySelectionSaved`, and is skipped when repository refresh
fails, so active bots, recovered installations, and explicit user
repository disables in Access settings are never overwritten.
- `managementUrl`, `installationUrl`, and `appUrl` are validated by
shared helpers on both server and UI to allow only `https://github.com`
paths matching their expected URL shapes.

## Model Used

- Google Gemini 4 Neon (High) via Antigravity with tool use and code
execution (exact internal model version string and context window are
not exposed in this session).

## 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
- [ ] All Paperclip CI gates are green
- [ ] 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-04 18:43:20 -06:00

577 lines
24 KiB
TypeScript

import type { Db } from "@paperclipai/db";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { githubBotCredentials } from "./chat-github-client.js";
import { githubChatManagementService } from "./chat-github-management.js";
vi.mock("./chat-github-client.js", async (importOriginal) => ({
...await importOriginal<typeof import("./chat-github-client.js")>(),
githubBotCredentials: vi.fn(),
}));
vi.mock("./secrets.js", () => ({ secretService: vi.fn() }));
vi.mock("./tool-access-policy.js", () => ({ toolAccessPolicyService: vi.fn() }));
vi.mock("./chat-github-tools.js", () => ({ GITHUB_BOT_TOOLS: [], syncGitHubBotTools: vi.fn() }));
vi.mock("./tool-access.js", () => ({ toolAccessService: vi.fn() }));
vi.mock("./activity-log.js", () => ({ logActivity: vi.fn() }));
vi.mock("./environments.js", () => ({ environmentService: vi.fn() }));
vi.mock("./instance-settings.js", () => ({ instanceSettingsService: vi.fn() }));
vi.mock("./execution-workspace-policy.js", () => ({ resolveExecutionWorkspaceEnvironmentId: vi.fn() }));
const endpoint = { id: "bot-endpoint", companyId: "bot-company", status: "active" };
const credentials = {
endpoint,
connection: { enabled: true, status: "active" },
credentials: { installationId: "12345" },
appJwt: "app-jwt-not-for-users",
};
function fixture(user: unknown = { id: 1, login: "octocat", type: "User" }) {
const where = vi.fn().mockResolvedValue([endpoint]);
const db = { select: vi.fn(() => ({ from: vi.fn(() => ({ where })) })) } as unknown as Db;
const fetchImpl = vi.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ token: "installation-token-not-for-output" }, { status: 201 }))
.mockResolvedValueOnce(Response.json(user));
const service = githubChatManagementService(db, fetchImpl);
return { db, where, fetchImpl, service };
}
describe("GitHub external contributor lookup", () => {
beforeEach(() => {
vi.mocked(githubBotCredentials).mockReset();
vi.mocked(githubBotCredentials).mockResolvedValue(credentials as never);
});
it("uses only the requested endpoint's installation with metadata permission", async () => {
const { db, fetchImpl, service } = fixture();
expect(await service.lookupPerson(endpoint.id, "octocat")).toEqual({ githubUserId: "1", login: "octocat" });
expect(githubBotCredentials).toHaveBeenCalledExactlyOnceWith(db, endpoint.companyId, endpoint.id);
expect(fetchImpl).toHaveBeenCalledTimes(2);
expect(fetchImpl.mock.calls[0]).toEqual([
"https://api.github.com/app/installations/12345/access_tokens",
expect.objectContaining({
method: "POST",
redirect: "error",
headers: expect.objectContaining({ authorization: "Bearer app-jwt-not-for-users" }),
body: JSON.stringify({ permissions: { metadata: "read" } }),
}),
]);
expect(fetchImpl.mock.calls[1]).toEqual([
"https://api.github.com/users/octocat",
expect.objectContaining({
method: "GET",
redirect: "error",
headers: expect.objectContaining({ authorization: "Bearer installation-token-not-for-output" }),
}),
]);
});
it("accepts bot accounts and keeps the numeric identity", async () => {
const { fetchImpl, service } = fixture({ id: 9001, login: "reviewer[bot]", type: "Bot" });
expect(await service.lookupPerson(endpoint.id, "reviewer[bot]")).toEqual({ githubUserId: "9001", login: "reviewer[bot]" });
expect(fetchImpl.mock.calls[1][0]).toBe("https://api.github.com/users/reviewer%5Bbot%5D");
});
it.each(["../someone", "https://github.com/someone", "", "-name"])("rejects invalid login %j before credentials or network access", async (login) => {
const { fetchImpl, service } = fixture();
await expect(service.lookupPerson(endpoint.id, login)).rejects.toMatchObject({ status: 400 });
expect(githubBotCredentials).not.toHaveBeenCalled();
expect(fetchImpl).not.toHaveBeenCalled();
});
it("does not use another endpoint when the requested bot is absent", async () => {
const { fetchImpl, where, service } = fixture();
where.mockResolvedValue([]);
await expect(service.lookupPerson(endpoint.id, "octocat")).rejects.toMatchObject({ status: 404 });
expect(githubBotCredentials).not.toHaveBeenCalled();
expect(fetchImpl).not.toHaveBeenCalled();
});
it.each([
{ connection: { enabled: false, status: "active" } },
{ connection: { enabled: true, status: "revoked" } },
{ endpoint: { ...endpoint, status: "draft" } },
{ endpoint: { ...endpoint, status: "paused" } },
])("rejects inactive installation state %j without anonymous fallback", async (state) => {
const { fetchImpl, service } = fixture();
vi.mocked(githubBotCredentials).mockResolvedValue({ ...credentials, ...state } as never);
await expect(service.lookupPerson(endpoint.id, "octocat")).rejects.toMatchObject({ status: 409 });
expect(fetchImpl).not.toHaveBeenCalled();
});
it.each(["", "not-an-installation", "123/../../users"])("requires a valid saved installation ID %j", async (installationId) => {
const { fetchImpl, service } = fixture();
vi.mocked(githubBotCredentials).mockResolvedValue({ ...credentials, credentials: { installationId } } as never);
await expect(service.lookupPerson(endpoint.id, "octocat")).rejects.toMatchObject({ status: 409 });
expect(fetchImpl).not.toHaveBeenCalled();
});
it("requires an issued token before it looks up a person", async () => {
const { fetchImpl, service } = fixture();
fetchImpl.mockReset().mockResolvedValue(Response.json({}));
await expect(service.lookupPerson(endpoint.id, "octocat")).rejects.toMatchObject({ status: 422, message: expect.stringContaining("did not issue") });
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
it.each([
{ id: 1, login: "org", type: "Organization" },
{ id: "1", login: "octocat", type: "User" },
{ id: 0, login: "octocat", type: "User" },
{ id: 1, type: "User" },
])("rejects accounts without a valid person identity: %j", async (user) => {
const { service } = fixture(user);
await expect(service.lookupPerson(endpoint.id, "octocat")).rejects.toMatchObject({ status: 400, message: "Choose a GitHub person or bot account" });
});
it.each([403, 429])("reports HTTP %s rate limits and preserves retry metadata", async (status) => {
const { fetchImpl, service } = fixture();
fetchImpl.mockReset()
.mockResolvedValueOnce(Response.json({ token: "installation-token-not-for-output" }))
.mockResolvedValueOnce(Response.json({ message: "secret-provider-response" }, { status, headers: { "retry-after": "60", "x-ratelimit-remaining": "0" } }));
await expect(service.lookupPerson(endpoint.id, "octocat")).rejects.toMatchObject({
message: expect.stringContaining("rate limit"),
details: { code: "github_bot_rate_limited", providerStatus: status, retryable: true, retryAfterMs: 60000 },
});
expect(fetchImpl).toHaveBeenCalledTimes(2);
});
it("distinguishes an unavailable account from an invalid installation", async () => {
const { fetchImpl, service } = fixture();
fetchImpl.mockReset()
.mockResolvedValueOnce(Response.json({ token: "installation-token-not-for-output" }))
.mockResolvedValueOnce(Response.json({ message: "secret-provider-response" }, { status: 404 }));
await expect(service.lookupPerson(endpoint.id, "octocat")).rejects.toMatchObject({
status: 400, message: expect.stringContaining("Check the username"), details: { providerStatus: 404 },
});
});
it.each([401, 403, 404])("reports installation HTTP %s without a user lookup or provider response text", async (status) => {
const { fetchImpl, service } = fixture();
fetchImpl.mockReset().mockResolvedValue(Response.json({ message: "secret-provider-response" }, { status }));
const error = await service.lookupPerson(endpoint.id, "octocat").catch((error: Error) => error);
expect(error).toMatchObject({ status: 422, message: expect.stringContaining("installation"), details: { providerStatus: status, retryable: false } });
expect(JSON.stringify(error)).not.toContain("secret-provider-response");
expect(JSON.stringify(error)).not.toContain("app-jwt-not-for-users");
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
});
describe("GitHub verification check diagnostics and installation links", () => {
beforeEach(() => {
vi.mocked(githubBotCredentials).mockReset();
vi.mocked(githubBotCredentials).mockResolvedValue({
...credentials,
endpoint: {
...endpoint,
botExternalId: "777",
assignedAgentId: "agent-1",
connectionId: "conn-1",
setup: {
webhookVerifiedAt: "2026-10-10T00:00:00Z",
github: {
installationUrl: "https://github.com/apps/maya-reviews/installations/new",
managementUrl: "https://github.com/organizations/acme/settings/installations/12345",
},
},
},
connection: { enabled: true, status: "active", applicationId: "app-1" },
} as never);
});
function verificationFixture(options: {
resources: Array<{
id: string;
type: string;
enabled: boolean;
availability: string;
label: string | null;
providerResourceId: string;
metadata: Record<string, unknown> | null;
}>;
installation?: {
permissions?: Record<string, string>;
suspended_at?: string | null;
html_url?: string;
};
installationStatus?: number;
installationError?: Error;
savedManagementUrl?: string;
installationId?: string;
tokenStatus?: number;
}) {
const endpointRow = {
...endpoint,
botExternalId: "777",
assignedAgentId: "agent-1",
connectionId: "conn-1",
setup: {
webhookVerifiedAt: "2026-10-10T00:00:00Z",
github: {
installationUrl: "https://github.com/apps/maya-reviews/installations/new",
managementUrl:
options.savedManagementUrl ??
"https://github.com/organizations/acme/settings/installations/12345",
},
},
};
if (options.installationId !== undefined) {
vi.mocked(githubBotCredentials).mockResolvedValue({
...credentials,
endpoint: endpointRow,
credentials: { installationId: options.installationId },
connection: { enabled: true, status: "active", applicationId: "app-1" },
} as never);
}
const selectResults = [
[endpointRow],
options.resources,
[{ id: "agent-1", adapterType: "paperclip_runner", permissions: {} }],
[],
[],
];
let selectIndex = 0;
const db = {
select: vi.fn(() => ({
from: vi.fn(() => ({
where: vi.fn(() => Promise.resolve(selectResults[selectIndex++] ?? [])),
})),
})),
} as unknown as Db;
const fetchImpl = vi.fn<typeof fetch>(async (input) => {
const url = String(input);
if (url === "https://api.github.com/app") {
return Response.json({
id: 777,
permissions: { contents: "read", pull_requests: "write", checks: "write" },
events: ["pull_request"],
});
}
if (url === `https://api.github.com/app/installations/${options.installationId ?? "12345"}`) {
if (options.installationError) {
throw options.installationError;
}
if ((options.installationStatus ?? 200) >= 400) {
return Response.json(
{ message: "Installation lookup failed" },
{ status: options.installationStatus },
);
}
return Response.json(
options.installation ?? {
permissions: { contents: "read", pull_requests: "write", checks: "write" },
suspended_at: null,
html_url: "https://github.com/organizations/acme/settings/installations/12345",
},
);
}
if (url === `https://api.github.com/app/installations/${options.installationId ?? "12345"}/access_tokens`) {
if ((options.tokenStatus ?? 201) >= 400) {
return Response.json({ message: "Forbidden" }, { status: options.tokenStatus });
}
return Response.json({ token: "scoped-token" }, { status: 201 });
}
throw new Error(`Unexpected fetch ${url}`);
});
return { service: githubChatManagementService(db, fetchImpl) };
}
it("reports no_installation_repositories and returns the GitHub installation URL when GitHub has zero repositories", async () => {
const { service } = verificationFixture({ resources: [] });
const result = await service.verification(endpoint.id);
const repoCheck = result.checks.find((check) => check.key === "repositories");
expect(repoCheck).toMatchObject({
ok: false,
code: "no_installation_repositories",
});
expect(repoCheck?.detail).toContain("Grant access to at least one repository on GitHub");
expect(result.managementUrl).toBe("https://github.com/organizations/acme/settings/installations/12345");
});
it("reports no_enabled_repositories when GitHub granted repositories but none are enabled in Paperclip", async () => {
const { service } = verificationFixture({
resources: [
{
id: "repo-1",
type: "repository",
enabled: false,
availability: "available",
label: "acme/web",
providerResourceId: "acme/web",
metadata: { providerRepositoryId: "101" },
},
],
});
const result = await service.verification(endpoint.id);
const repoCheck = result.checks.find((check) => check.key === "repositories");
expect(repoCheck).toMatchObject({
ok: false,
code: "no_enabled_repositories",
});
expect(repoCheck?.detail).toContain("1 repository");
expect(repoCheck?.detail).toContain("Access settings");
});
it("reports installation_suspended and avoids mislabeling repositories as missing access", async () => {
const { service } = verificationFixture({
resources: [
{
id: "repo-1",
type: "repository",
enabled: true,
availability: "available",
label: "acme/web",
providerResourceId: "acme/web",
metadata: { providerRepositoryId: "101" },
},
],
installation: {
permissions: { contents: "read", pull_requests: "write", checks: "write" },
suspended_at: "2026-10-10T01:00:00Z",
html_url: "https://github.com/organizations/acme/settings/installations/12345",
},
});
const result = await service.verification(endpoint.id);
expect(result.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "installation_suspended",
});
expect(result.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
});
it("ignores unsafe installation html_url values from GitHub and falls back to saved managementUrl", async () => {
const { service } = verificationFixture({
resources: [],
installation: {
permissions: { contents: "read", pull_requests: "write", checks: "write" },
suspended_at: null,
html_url: "https://evil.example/settings/installations/12345",
},
});
const result = await service.verification(endpoint.id);
expect(result.managementUrl).toBe("https://github.com/organizations/acme/settings/installations/12345");
});
it("maps a removed GitHub installation (HTTP 404) to installation_missing with managementUrl instead of throwing", async () => {
const { service } = verificationFixture({
resources: [],
installationStatus: 404,
});
const result = await service.verification(endpoint.id);
expect(result.ready).toBe(false);
expect(result.connectionReady).toBe(false);
expect(result.managementUrl).toBe("https://github.com/organizations/acme/settings/installations/12345");
expect(result.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "installation_missing",
});
expect(result.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
expect(result.checks.find((check) => check.key === "repositories")?.detail).toContain(
"Install the GitHub App",
);
});
it.each([401, 403, 500])(
"keeps non-404 installation lookup failures (HTTP %s) separate from installation_missing",
async (status) => {
vi.useFakeTimers();
try {
const { service } = verificationFixture({
resources: [],
installationStatus: status,
});
const pending = service.verification(endpoint.id);
const assertion = expect(pending).rejects.toMatchObject({
status: 422,
details: { providerStatus: status },
});
await vi.runAllTimersAsync();
await assertion;
} finally {
vi.useRealTimers();
}
},
);
it("keeps transient network errors during installation lookup separate from installation_missing", async () => {
vi.useFakeTimers();
try {
const { service } = verificationFixture({
resources: [],
installationError: new TypeError("fetch failed"),
});
const pending = service.verification(endpoint.id);
const assertion = expect(pending).rejects.toMatchObject({
status: 422,
details: { code: "github_bot_temporarily_unavailable", retryable: true },
});
await vi.runAllTimersAsync();
await assertion;
} finally {
vi.useRealTimers();
}
});
it("reports permissions_required rather than no_installation_repositories when a suspended installation has zero enabled repositories", async () => {
const { service } = verificationFixture({
resources: [],
installation: {
permissions: { contents: "read", pull_requests: "write", checks: "write" },
suspended_at: "2026-10-10T01:00:00Z",
html_url: "https://github.com/organizations/acme/settings/installations/12345",
},
});
const result = await service.verification(endpoint.id);
expect(result.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "installation_suspended",
});
expect(result.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
});
it("reports permissions_required rather than no_enabled_repositories when permissions are missing and cached repositories are disabled", async () => {
const { service } = verificationFixture({
resources: [
{
id: "repo-1",
type: "repository",
enabled: false,
availability: "available",
label: "acme/web",
providerResourceId: "acme/web",
metadata: { providerRepositoryId: "101" },
},
],
installation: {
permissions: { contents: "read", pull_requests: "write" },
suspended_at: null,
html_url: "https://github.com/organizations/acme/settings/installations/12345",
},
});
const result = await service.verification(endpoint.id);
expect(result.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "permissions_missing",
});
expect(result.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
});
it("reports repositories_sync_failed instead of no_installation_repositories when repository sync failed with valid permissions", async () => {
const { service } = verificationFixture({ resources: [] });
const result = await service.verification(endpoint.id, {
repositorySyncFailed: true,
});
expect(result.ready).toBe(false);
expect(result.connectionReady).toBe(false);
expect(result.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: true,
});
const repoCheck = result.checks.find((check) => check.key === "repositories");
expect(repoCheck).toMatchObject({
ok: false,
code: "repositories_sync_failed",
});
expect(repoCheck?.detail).toContain("Could not refresh repositories from GitHub");
expect(repoCheck?.detail).not.toContain("Grant access to at least one repository");
});
it("preserves typed installation_missing, installation_suspended, and permissions_missing guidance even when repository sync failed", async () => {
const missing = await verificationFixture({
resources: [],
installationStatus: 404,
}).service.verification(endpoint.id, { repositorySyncFailed: true });
expect(missing.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "installation_missing",
});
expect(missing.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
const suspended = await verificationFixture({
resources: [],
installation: {
permissions: { contents: "read", pull_requests: "write", checks: "write" },
suspended_at: "2026-10-10T01:00:00Z",
html_url: "https://github.com/organizations/acme/settings/installations/12345",
},
}).service.verification(endpoint.id, { repositorySyncFailed: true });
expect(suspended.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "installation_suspended",
});
expect(suspended.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
const missingPerms = await verificationFixture({
resources: [],
installation: {
permissions: { contents: "read", pull_requests: "write" },
suspended_at: null,
html_url: "https://github.com/organizations/acme/settings/installations/12345",
},
}).service.verification(endpoint.id, { repositorySyncFailed: true });
expect(missingPerms.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "permissions_missing",
});
expect(missingPerms.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
});
it("validates shared GitHub App and installation management URLs strictly", async () => {
const {
safeGitHubAppInstallUrl,
safeGitHubAppUrl,
safeGitHubInstallationManagementUrl,
} = await import("@paperclipai/shared");
expect(
safeGitHubInstallationManagementUrl(
"https://github.com/organizations/acme/settings/installations/12345",
),
).toBe("https://github.com/organizations/acme/settings/installations/12345");
expect(
safeGitHubInstallationManagementUrl("https://github.com/settings/installations/12345"),
).toBe("https://github.com/settings/installations/12345");
expect(
safeGitHubInstallationManagementUrl(
"https://github.com/apps/maya-reviews/installations/new",
),
).toBeUndefined();
expect(
safeGitHubInstallationManagementUrl(
"https://github.com/settings/installations/12345?next=https://evil.example",
),
).toBeUndefined();
expect(
safeGitHubAppInstallUrl("https://github.com/apps/maya-reviews/installations/new"),
).toBe("https://github.com/apps/maya-reviews/installations/new");
expect(
safeGitHubAppInstallUrl(
"https://github.com/apps/maya-reviews/installations/new?suggested_target_id=1",
),
).toBeUndefined();
expect(
safeGitHubAppUrl("https://evil.example/apps/maya-reviews/installations/new"),
).toBeUndefined();
expect(
safeGitHubAppUrl("https://github.com/apps/maya-reviews/installations/new#frag"),
).toBeUndefined();
});
});