fix(github-chat): distinguish repository sync failures and pair verify fallback labels

This commit is contained in:
cryppadotta committed 2026-12-05 00:26:52 +00:00
1 parent b1dc6e0f48
commit c1f234335f
9 files changed
+1047 -224

No files matched your search

@@ -21,6 +21,7 @@ export type GitHubVerificationCheckCode =
| "permissions_required"
| "no_installation_repositories"
| "no_enabled_repositories"
| "repositories_sync_failed"
| "repositories_inaccessible"
| "runtime_unsupported"
| "sandbox_required"
@@ -3880,6 +3880,143 @@ describeEmbeddedPostgres("chat channels: github setup and access", () => {
await service.shutdown();
});
it("surfaces a retryable repository sync error instead of no_installation_repositories on transient inventory 503 and recovers on retry", async () => {
const fixture = await seedCompany();
const appRegistrationId = Number.parseInt(
fixture.companyId.replaceAll("-", "").slice(0, 8),
16,
);
const privateKey = generateKeyPairSync("rsa", { modulusLength: 2048 })
.privateKey.export({ type: "pkcs8", format: "pem" })
.toString();
const installationId = 78902;
let inventoryStatus = 200;
let repositories: Array<{
id: number;
full_name: string;
html_url: string;
owner: { id: number; login: string };
private: boolean;
}> = [];
const providerFetch = (async (input: string | URL | Request) => {
const url = String(input);
if (url === "https://api.github.com/app") {
return Response.json({
id: appRegistrationId,
slug: `maya-503-${fixture.companyId.slice(0, 8)}`,
name: "Maya Transient Inventory",
owner: { login: "paperclipai", type: "Organization" },
permissions: { contents: "read", checks: "write", issues: "write", metadata: "read", pull_requests: "write" },
events: ["pull_request", "github_app_authorization", "installation", "installation_repositories", "issue_comment", "pull_request_review_comment"],
});
}
if (url === "https://api.github.com/app/installations?per_page=100") {
return Response.json([{
id: installationId,
html_url: `https://github.com/organizations/paperclipai/settings/installations/${installationId}`,
account: { id: 1357, login: "paperclipai", type: "Organization" },
permissions: { contents: "read", checks: "write", issues: "write", metadata: "read", pull_requests: "write" },
suspended_at: null,
}]);
}
if (url === `https://api.github.com/app/installations/${installationId}`) {
return Response.json({
id: installationId,
html_url: `https://github.com/organizations/paperclipai/settings/installations/${installationId}`,
account: { id: 1357, login: "paperclipai", type: "Organization" },
permissions: { contents: "read", checks: "write", issues: "write", metadata: "read", pull_requests: "write" },
suspended_at: null,
});
}
if (url === `https://api.github.com/app/installations/${installationId}/access_tokens`) {
return Response.json({ token: "installation-token" }, { status: 201 });
}
if (url === "https://api.github.com/installation/repositories?per_page=100&page=1") {
if (inventoryStatus >= 400) {
return Response.json({ message: "Service Unavailable" }, { status: inventoryStatus });
}
return Response.json({ repositories });
}
if (url === "https://api.github.com/app/hook/deliveries?per_page=20") {
return Response.json([]);
}
throw new Error(`Unexpected provider request: ${url}`);
}) as typeof globalThis.fetch;
const { service } = createService(new FakeChatSdkRuntime(), providerFetch);
const endpoint = await service.create(
fixture.companyId,
{ provider: "github", assignedAgentId: fixture.assignedAgentId, name: "Maya Transient Inventory" },
"owner-user",
);
const { webhookSecret } = await service.generateSetupSecret(endpoint.id, "owner-user");
await service.storeGitHubApp(
endpoint.id,
"owner-user",
{ appId: String(appRegistrationId), privateKey, webhookSecret },
"existing_app",
);
await recordGitHubWebhookVerification(service, endpoint.publicId, webhookSecret);
const management = (await import("../../services/chat-github-management.js")).githubChatManagementService(db, providerFetch);
await management.linkObservedIdentity(endpoint.id, "owner-user", {
githubUserId: "42",
login: "octocat",
avatarUrl: null,
});
// Move the endpoint into verifying state with an empty cache first.
const initialVerify = await service.githubWizard.advance(endpoint.id, "owner-user");
expect(initialVerify.state).toBe("verify");
expect(initialVerify.verification?.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "no_installation_repositories",
});
// Now GitHub's /installation/repositories endpoint returns a transient 503
// while /app and /app/installations/:id continue returning valid permissions.
inventoryStatus = 503;
const failedSync = await service.githubWizard.advance(endpoint.id, "owner-user");
expect(failedSync.state).toBe("verify");
expect(failedSync.managementUrl).toBe(
`https://github.com/organizations/paperclipai/settings/installations/${installationId}`,
);
expect(failedSync.verification?.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: true,
});
expect(failedSync.verification?.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "repositories_sync_failed",
});
expect(failedSync.verification?.checks.find((check) => check.key === "repositories")?.detail).not.toContain(
"Grant access to at least one repository",
);
const afterFailedSync = await service.get(endpoint.id);
expect(afterFailedSync.setup.github?.initialRepositoryImportPending).toBe(true);
expect(afterFailedSync.setup.github?.repositorySelectionSaved).not.toBe(true);
// Follow up with a successful retry once GitHub recovers.
inventoryStatus = 200;
repositories = [{
id: 97532,
full_name: "paperclipai/paperclip",
html_url: "https://github.com/paperclipai/paperclip",
owner: { id: 1357, login: "paperclipai" },
private: false,
}];
const recovered = await service.githubWizard.advance(endpoint.id, "owner-user");
expect(recovered.state).toBe("connected");
const resources = await service.listResources(endpoint.id);
expect(resources).toEqual([
expect.objectContaining({
providerResourceId: "paperclipai/paperclip",
enabled: true,
availability: "available",
}),
]);
await service.shutdown();
});
it("strips workspace overrides from GitHub execution defaults on read, write, and task creation while preserving project defaults", async () => {
const previousExperimental = await instanceSettingsService(db).getExperimental();
onTestFinished(async () => {
@@ -465,6 +465,74 @@ describe("GitHub verification check diagnostics and installation links", () => {
});
});
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,
+24 -13
View File
@@ -383,7 +383,11 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
}
return {
linkObservedIdentity,
verification: async (endpointId: string) => {
verification: async (
endpointId: string,
options?: { repositorySyncFailed?: boolean },
) => {
const repositorySyncFailed = options?.repositorySyncFailed === true;
const bot = await endpoint(endpointId);
const checks: GitHubVerificationCheck[] = [];
checks.push({
@@ -500,7 +504,7 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
);
const resources = allResources.filter((resource) => resource.enabled);
const inaccessible: string[] = [];
if (permissionsOk) {
if (permissionsOk && !repositorySyncFailed) {
// Ask GitHub to authorize the selected repository IDs now. A cached
// inventory alone cannot prove access after an installation is changed.
const verifiable = resources.filter((resource) => {
@@ -551,16 +555,21 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
}
}
const repositoriesOk =
permissionsOk && resources.length > 0 && inaccessible.length === 0;
permissionsOk &&
!repositorySyncFailed &&
resources.length > 0 &&
inaccessible.length === 0;
const repositoriesCode = repositoriesOk
? undefined
: !permissionsOk
? ("permissions_required" as const)
: resources.length === 0
? availableResources.length > 0
? ("no_enabled_repositories" as const)
: ("no_installation_repositories" as const)
: ("repositories_inaccessible" as const);
: repositorySyncFailed
? ("repositories_sync_failed" as const)
: resources.length === 0
? availableResources.length > 0
? ("no_enabled_repositories" as const)
: ("no_installation_repositories" as const)
: ("repositories_inaccessible" as const);
const repositoriesDetail = repositoriesOk
? `GitHub confirmed review access to ${resources.length === 1 ? "1 enabled repository" : `all ${resources.length} enabled repositories`}.`
: repositoriesCode === "permissions_required"
@@ -569,11 +578,13 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
: installationSuspended
? "Unsuspend the GitHub App installation before verifying repository access."
: "Approve the required GitHub App installation permissions before verifying repository access."
: repositoriesCode === "no_enabled_repositories"
? `${availableResources.length} ${availableResources.length === 1 ? "repository is" : "repositories are"} synced from GitHub, but none are enabled in Paperclip. Enable at least one repository in Access settings, then try again.`
: repositoriesCode === "no_installation_repositories"
? "No repositories are accessible to this GitHub App installation. Grant access to at least one repository on GitHub, then try again."
: `GitHub could not authorize access to: ${inaccessible.join(", ")}. Restore installation access on GitHub, then try again.`;
: repositoriesCode === "repositories_sync_failed"
? "Could not refresh repositories from GitHub right now. Try again in a moment."
: repositoriesCode === "no_enabled_repositories"
? `${availableResources.length} ${availableResources.length === 1 ? "repository is" : "repositories are"} synced from GitHub, but none are enabled in Paperclip. Enable at least one repository in Access settings, then try again.`
: repositoriesCode === "no_installation_repositories"
? "No repositories are accessible to this GitHub App installation. Grant access to at least one repository on GitHub, then try again."
: `GitHub could not authorize access to: ${inaccessible.join(", ")}. Restore installation access on GitHub, then try again.`;
checks.push({
key: "repositories",
label: "Enabled repositories",
+16 -6
View File
@@ -21,7 +21,7 @@ import {
type GitHubAppWizardState,
type GitHubAppCloudState,
} from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound } from "../errors.js";
import { HttpError, badRequest, conflict, forbidden, notFound } from "../errors.js";
import { logActivity } from "./activity-log.js";
import {
githubBotCredentials,
@@ -895,10 +895,14 @@ export function githubChatWizardService(
(resource) => resource.enabled && resource.availability === "available",
);
}
let repositorySyncFailed = false;
if (shouldRefreshRepositories) {
try {
await options.refreshRepositories(id, userId, managementContext);
} catch (error) {
if (error instanceof HttpError && [401, 403, 404].includes(error.status)) {
throw error;
}
if (needsInitialInstall || bot.status !== "verifying") {
const installationUrl = safeGitHubAppInstallUrl(
bot.setup.github?.installationUrl,
@@ -913,13 +917,17 @@ export function githubChatWizardService(
: "Waiting for installation or administrator approval on GitHub.",
};
}
// An already-configured App whose installation was suspended or lost
// permissions falls through to verification so the user sees the
// specific check failure and GitHub App installation link.
// An already-configured App whose installation was suspended, removed,
// lost permissions, or hit a transient repository sync failure falls
// through to verification so installation checks confirm the cause or
// surface a retryable repositories_sync_failed diagnostic.
repositorySyncFailed = true;
}
}
bot = await endpoint(id, userId);
await importInitialRepositories(bot, userId, !!session, managementContext);
if (!repositorySyncFailed) {
await importInitialRepositories(bot, userId, !!session, managementContext);
}
// Installation callbacks can precede the separately delivered signed ping.
// Keep the same vaulted App in the wizard instead of throwing JSON from
// the browser callback or relaxing the configure action's signature gate.
@@ -1006,7 +1014,9 @@ export function githubChatWizardService(
: undefined,
};
}
const verification = await management.verification(id);
const verification = await management.verification(id, {
repositorySyncFailed,
});
const connectionChecks = verification.checks.filter(
(check) => !["runtime", "isolation"].includes(check.key),
);
@@ -443,4 +443,79 @@ describe("GitHubChatSetup verify UX", () => {
});
expect(container.textContent).not.toContain("Checking GitHub access…");
});
it("uses the management label when installation_missing falls back to managementUrl without a safe installationUrl", async () => {
mocks.getEndpoint.mockResolvedValue({
...baseEndpoint,
setup: {
...baseEndpoint.setup,
github: {
...baseEndpoint.setup.github,
installationUrl: "https://evil.example/apps/maya-reviews/installations/new",
managementUrl: "https://github.com/organizations/acme/settings/installations/12345",
},
},
});
mocks.advance.mockResolvedValue({
endpointId: "endpoint-1",
state: "verify",
managementUrl: "https://github.com/organizations/acme/settings/installations/12345",
installationUrl: undefined,
verification: {
ready: false,
checks: [
{
key: "permissions",
label: "Review installation permissions",
ok: false,
code: "installation_missing",
detail: "This GitHub App is not installed on an accessible account. Install the App on GitHub, then try again.",
},
],
},
} satisfies GitHubAppWizardState);
await renderWizard();
await vi.waitFor(() => {
expect(container.textContent).toContain("GitHub App installation is missing");
});
const githubLink = [...container.querySelectorAll("a")].find(
(link) =>
link.getAttribute("href") ===
"https://github.com/organizations/acme/settings/installations/12345",
);
expect(githubLink).toBeDefined();
expect(githubLink?.textContent).toContain("Manage GitHub App installation");
expect(container.textContent).not.toContain("Install App on GitHub");
});
it("shows a retryable repository sync error instead of empty-installation guidance when GitHub inventory sync fails", async () => {
mocks.advance.mockResolvedValue({
endpointId: "endpoint-1",
state: "verify",
managementUrl: "https://github.com/organizations/acme/settings/installations/12345",
verification: {
ready: false,
checks: [
{
key: "repositories",
label: "Enabled repositories",
ok: false,
code: "repositories_sync_failed",
detail: "Could not refresh repositories from GitHub right now. Try again in a moment.",
},
],
},
} satisfies GitHubAppWizardState);
await renderWizard();
await vi.waitFor(() => {
expect(container.textContent).toContain("Could not load repositories from GitHub");
});
expect(container.textContent).toContain("Could not refresh repositories from GitHub right now");
expect(container.textContent).not.toContain("No repositories granted on GitHub");
expect(container.textContent).not.toContain("Checking GitHub access…");
expect(container.querySelector('[role="alert"]')).not.toBeNull();
});
});
+16 -205
View File
@@ -2,12 +2,10 @@ import { useAuthorizationWindow } from "@/hooks/useAuthorizationWindow";
import { useEffect, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { AlertCircle, ExternalLink, Loader2 } from "lucide-react";
import { ExternalLink, Loader2 } from "lucide-react";
import {
safeGitHubAppInstallUrl,
safeGitHubInstallationManagementUrl,
type GitHubAppWizardState,
type GitHubVerificationCheck,
} from "@paperclipai/shared";
import { agentsApi } from "@/api/agents";
import { chatEndpointsApi } from "@/api/chatEndpoints";
@@ -30,6 +28,11 @@ import { useNavigate, useSearchParams, Link } from "@/lib/router";
import { buildPermissionsForTrustPreset } from "@/lib/trust-policy-ui";
import { queryKeys } from "@/lib/queryKeys";
import { GITHUB_APP_CREDENTIAL_FIELDS, GitHubAppRecovery } from "./GitHubConnectionRecovery";
import {
GitHubVerifyStatus,
deriveGitHubVerifyView,
shouldPollGitHubVerify,
} from "./GitHubVerifyStatus";
import type { GitHubConnectionCompleteLocationState } from "./GitHubConnectionComplete";
import { describeError } from "@/api/errors";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
@@ -50,26 +53,6 @@ export function gitHubAppManifestAction(
throw new Error("GitHub returned an invalid registration address");
return url.toString();
}
function verifyIssueHeading(checks: GitHubVerificationCheck[]): string {
if (checks.length !== 1) return "Action needed to finish GitHub setup";
switch (checks[0]!.code) {
case "no_installation_repositories":
return "No repositories granted on GitHub";
case "no_enabled_repositories":
return "No repositories enabled in Paperclip";
case "installation_suspended":
return "GitHub App installation is suspended";
case "installation_missing":
return "GitHub App installation is missing";
case "permissions_missing":
return "GitHub App permissions need approval";
case "repositories_inaccessible":
return "GitHub denied access to selected repositories";
default:
return checks[0]!.label;
}
}
function GitHubAppManifestForm({
registration, onSaveExit, disabled, autoSubmit, onSubmit,
}: {
@@ -149,22 +132,8 @@ export function GitHubChatSetup() {
queryKey: ["github-wizard", resume],
queryFn: () => githubChatApi.advance(resume!),
enabled: !!bot && !existing && !identityOnly,
refetchInterval: (query) => {
const data = query.state.data;
if (!data) return 5000;
if (data.state === "install") return 5000;
if (data.state === "verify") {
const failed = data.verification?.checks.filter((check) => !check.ok) ?? [];
const waitingOnly =
failed.length === 0 ||
failed.every(
(check) =>
check.code === "webhook_pending" || check.key === "webhook",
);
return waitingOnly ? 5000 : false;
}
return false;
},
refetchInterval: (query) =>
shouldPollGitHubVerify(query.state.data) ? 5000 : false,
});
const progressView = useQueryView(progress);
const accounts = useQuery({
@@ -211,57 +180,11 @@ export function GitHubChatSetup() {
const knownOwner = organizations.get(ownerLogin.toLowerCase());
const accountChoice = ownerType === "personal" ? "personal"
: !customOrganization && knownOwner ? `organization:${knownOwner}` : "organization";
const deliveryVerifiedWhileChecking =
state?.state === "verify" &&
!!bot?.setup?.webhookVerifiedAt &&
state.verification?.checks.some(
(check) => !check.ok && ["webhook", "delivery"].includes(check.key),
);
const failedVerifyChecks =
state?.state === "verify"
? (state.verification?.checks.filter(
(check) =>
!check.ok &&
!(
deliveryVerifiedWhileChecking &&
["webhook", "delivery"].includes(check.key)
),
) ?? [])
: [];
const waitingForWebhook =
state?.state === "verify" &&
(deliveryVerifiedWhileChecking ||
(failedVerifyChecks.length > 0 &&
failedVerifyChecks.every(
(check) =>
check.code === "webhook_pending" || check.key === "webhook",
)));
const hasVerifyIssues =
state?.state === "verify" &&
!waitingForWebhook &&
failedVerifyChecks.length > 0;
const checkingVerify =
state?.state === "verify" &&
(busy || (progress.isFetching && !waitingForWebhook));
const verifyGitHubManagementUrl =
safeGitHubInstallationManagementUrl(state?.managementUrl) ??
safeGitHubInstallationManagementUrl(bot?.setup?.github?.managementUrl);
const verifyGitHubInstallUrl =
safeGitHubAppInstallUrl(state?.installationUrl) ??
safeGitHubAppInstallUrl(bot?.setup?.github?.installationUrl);
const installStateGitHubUrl = safeGitHubAppInstallUrl(state?.installationUrl);
const needsInstallationOnly = failedVerifyChecks.some(
(check) => check.code === "installation_missing",
);
const verifyGitHubUrl = needsInstallationOnly
? (verifyGitHubInstallUrl ?? verifyGitHubManagementUrl)
: (verifyGitHubManagementUrl ?? verifyGitHubInstallUrl);
const hasRepositoryIssue = failedVerifyChecks.some(
(check) => check.key === "repositories",
);
const hasPaperclipEnableIssue = failedVerifyChecks.some(
(check) => check.code === "no_enabled_repositories",
);
const verifyView =
bot && state?.state === "verify"
? deriveGitHubVerifyView(state, bot, progress.isFetching, busy)
: null;
const existingIdentityMethod =
identityOnly || state?.identityMethod === "existing_connection";
const connected = state?.state === "connected" && !existing;
@@ -663,126 +586,14 @@ export function GitHubChatSetup() {
}, !appNotCreated)
: footer("Try again", refresh)}
</>
) : state?.state === "verify" ? (
) : verifyView ? (
<>
{checkingVerify ? (
<p
role="status"
className="flex items-center gap-2 text-sm text-muted-foreground"
>
<Loader2 className="size-4 shrink-0 animate-spin" />
Checking GitHub access…
</p>
) : hasVerifyIssues ? (
<div
role="alert"
className="space-y-3 rounded-md border border-destructive/30 bg-destructive/5 p-4"
>
<div className="flex items-start gap-2.5">
<AlertCircle className="mt-0.5 size-4 shrink-0 text-destructive" />
<div className="min-w-0 space-y-2">
<p className="text-sm font-medium text-foreground">
{verifyIssueHeading(failedVerifyChecks)}
</p>
<div className="space-y-2">
{failedVerifyChecks.map((check) => (
<div key={check.key} className="space-y-0.5 text-sm">
{failedVerifyChecks.length > 1 && (
<p className="font-medium text-foreground">
{check.label}
</p>
)}
<p className="text-muted-foreground">{check.detail}</p>
</div>
))}
</div>
</div>
</div>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 pl-6">
{hasPaperclipEnableIssue ? (
<>
<Link
className="text-sm font-medium underline underline-offset-4"
to={`/apps/chat/${bot.id}/access`}
>
Open Access settings
</Link>
{verifyGitHubUrl && (
<a
className="inline-flex items-center gap-1 text-sm text-muted-foreground underline underline-offset-4 hover:text-foreground"
href={verifyGitHubUrl}
target="_blank"
rel="noopener noreferrer"
>
{needsInstallationOnly
? "Install App on GitHub"
: "Manage GitHub App installation"}
<ExternalLink className="size-3.5" />
</a>
)}
</>
) : (
<>
{verifyGitHubUrl && (
<a
className="inline-flex items-center gap-1 text-sm font-medium underline underline-offset-4"
href={verifyGitHubUrl}
target="_blank"
rel="noopener noreferrer"
>
{needsInstallationOnly
? "Install App on GitHub"
: "Manage GitHub App installation"}
<ExternalLink className="size-3.5" />
</a>
)}
{hasRepositoryIssue && (
<Link
className="text-sm text-muted-foreground underline underline-offset-4 hover:text-foreground"
to={`/apps/chat/${bot.id}/access`}
>
Access settings
</Link>
)}
</>
)}
<Link
className="text-sm text-muted-foreground underline underline-offset-4 hover:text-foreground"
to={`/apps/chat/${bot.id}/settings`}
>
Connection settings
</Link>
</div>
</div>
) : (
<>
<p
role="status"
className="flex items-center gap-2 text-sm text-muted-foreground"
>
<Loader2 className="size-4 shrink-0 animate-spin" />
{deliveryVerifiedWhileChecking
? "GitHub delivery verified. Checking App and repository access…"
: state.message ?? "Checking GitHub access…"}
</p>
{failedVerifyChecks.map((check) => (
<p key={check.key} className="text-sm text-muted-foreground">
{check.detail}
</p>
))}
<Link
className="text-sm underline underline-offset-4"
to={`/apps/chat/${bot.id}/settings`}
>
Connection settings
</Link>
</>
)}
<GitHubVerifyStatus view={verifyView} />
{footer(
checkingVerify ? "Checking…" : "Try again",
verifyView.mode === "checking" ? "Checking…" : "Try again",
refresh,
false,
checkingVerify,
verifyView.mode === "checking",
)}
</>
) : (
@@ -0,0 +1,430 @@
import { describe, expect, it } from "vitest";
import type {
GitHubAppWizardState,
GitHubVerificationCheckCode,
} from "@paperclipai/shared";
import {
deriveGitHubVerifyView,
shouldPollGitHubVerify,
type GitHubVerifyBotContext,
} from "./GitHubVerifyStatus";
const baseBot: GitHubVerifyBotContext = {
id: "endpoint-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",
},
},
};
function makeState(
overrides: Partial<GitHubAppWizardState>,
): GitHubAppWizardState {
return {
endpointId: "endpoint-1",
state: "verify",
installationUrl: "https://github.com/apps/maya-reviews/installations/new",
managementUrl:
"https://github.com/organizations/acme/settings/installations/12345",
verification: { ready: false, checks: [] },
...overrides,
};
}
describe("deriveGitHubVerifyView", () => {
it("handles every GitHubVerificationCheckCode explicitly", () => {
const cases: Record<
GitHubVerificationCheckCode,
{
key: string;
label: string;
expectedMode: "waiting" | "error";
expectedHeading?: string;
expectedPrimaryHref?: string;
expectedPrimaryLabel?: string;
botOverride?: GitHubVerifyBotContext;
}
> = {
webhook_pending: {
key: "webhook",
label: "Signed webhook delivery",
expectedMode: "waiting",
botOverride: {
...baseBot,
setup: { ...baseBot.setup, webhookVerifiedAt: null },
},
},
delivery_unverified: {
key: "delivery",
label: "Signed webhook delivery",
expectedMode: "error",
expectedHeading: "Signed webhook delivery",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
botOverride: {
...baseBot,
setup: { ...baseBot.setup, webhookVerifiedAt: null },
},
},
app_identity_mismatch: {
key: "app",
label: "GitHub App identity",
expectedMode: "error",
expectedHeading: "GitHub App identity",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
},
installation_missing: {
key: "permissions",
label: "Review installation permissions",
expectedMode: "error",
expectedHeading: "GitHub App installation is missing",
expectedPrimaryHref:
"https://github.com/apps/maya-reviews/installations/new",
expectedPrimaryLabel: "Install App on GitHub",
},
installation_suspended: {
key: "permissions",
label: "Review installation permissions",
expectedMode: "error",
expectedHeading: "GitHub App installation is suspended",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
},
permissions_missing: {
key: "permissions",
label: "Review installation permissions",
expectedMode: "error",
expectedHeading: "GitHub App permissions need approval",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
},
permissions_required: {
key: "repositories",
label: "Enabled repositories",
expectedMode: "error",
expectedHeading: "GitHub App permissions need approval",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
},
no_installation_repositories: {
key: "repositories",
label: "Enabled repositories",
expectedMode: "error",
expectedHeading: "No repositories granted on GitHub",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
},
no_enabled_repositories: {
key: "repositories",
label: "Enabled repositories",
expectedMode: "error",
expectedHeading: "No repositories enabled in Paperclip",
expectedPrimaryHref: "/apps/chat/endpoint-1/access",
expectedPrimaryLabel: "Open Access settings",
},
repositories_sync_failed: {
key: "repositories",
label: "Enabled repositories",
expectedMode: "error",
expectedHeading: "Could not load repositories from GitHub",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
},
repositories_inaccessible: {
key: "repositories",
label: "Enabled repositories",
expectedMode: "error",
expectedHeading: "GitHub denied access to selected repositories",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
},
runtime_unsupported: {
key: "runtime",
label: "Agent runtime supports bot tools",
expectedMode: "error",
expectedHeading: "Agent runtime supports bot tools",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
},
sandbox_required: {
key: "isolation",
label: "Isolated sandbox",
expectedMode: "error",
expectedHeading: "Isolated sandbox",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
},
tools_missing: {
key: "tools",
label: "Assigned agent tools",
expectedMode: "error",
expectedHeading: "Assigned agent tools",
expectedPrimaryHref:
"https://github.com/organizations/acme/settings/installations/12345",
expectedPrimaryLabel: "Manage GitHub App installation",
},
};
for (const [code, spec] of Object.entries(cases) as Array<
[GitHubVerificationCheckCode, (typeof cases)[GitHubVerificationCheckCode]]
>) {
const view = deriveGitHubVerifyView(
makeState({
verification: {
ready: false,
checks: [
{
key: spec.key,
label: spec.label,
ok: false,
code,
detail: `Detail for ${code}`,
},
],
},
}),
spec.botOverride ?? baseBot,
false,
false,
);
expect(view.mode, `code=${code}`).toBe(spec.expectedMode);
if (view.mode === "error") {
expect(view.heading, `code=${code}`).toBe(spec.expectedHeading);
expect(view.links[0]?.href, `code=${code}`).toBe(spec.expectedPrimaryHref);
expect(view.links[0]?.label, `code=${code}`).toBe(
spec.expectedPrimaryLabel,
);
}
}
});
it("pairs the management label with managementUrl when installation_missing has no safe installUrl", () => {
const view = deriveGitHubVerifyView(
makeState({
installationUrl: "https://evil.example/apps/maya-reviews/installations/new",
managementUrl:
"https://github.com/organizations/acme/settings/installations/12345",
verification: {
ready: false,
checks: [
{
key: "permissions",
label: "Review installation permissions",
ok: false,
code: "installation_missing",
detail: "Install the App on GitHub, then try again.",
},
],
},
}),
{
id: "endpoint-1",
setup: {
webhookVerifiedAt: "2026-10-10T00:00:00Z",
github: {
installationUrl: null,
managementUrl:
"https://github.com/organizations/acme/settings/installations/12345",
},
},
},
false,
false,
);
expect(view.mode).toBe("error");
if (view.mode === "error") {
expect(view.links[0]).toEqual({
href: "https://github.com/organizations/acme/settings/installations/12345",
label: "Manage GitHub App installation",
external: true,
primary: true,
});
}
});
it("pairs the install label with installationUrl when a non-missing error has no safe managementUrl", () => {
const view = deriveGitHubVerifyView(
makeState({
managementUrl: "https://evil.example/settings/installations/12345",
installationUrl: "https://github.com/apps/maya-reviews/installations/new",
verification: {
ready: false,
checks: [
{
key: "repositories",
label: "Enabled repositories",
ok: false,
code: "no_installation_repositories",
detail: "Grant access on GitHub.",
},
],
},
}),
{
id: "endpoint-1",
setup: {
webhookVerifiedAt: "2026-10-10T00:00:00Z",
github: {
installationUrl:
"https://github.com/apps/maya-reviews/installations/new",
managementUrl: null,
},
},
},
false,
false,
);
expect(view.mode).toBe("error");
if (view.mode === "error") {
expect(view.links[0]).toEqual({
href: "https://github.com/apps/maya-reviews/installations/new",
label: "Install App on GitHub",
external: true,
primary: true,
});
}
});
it("omits external GitHub links when neither installationUrl nor managementUrl is safe", () => {
const view = deriveGitHubVerifyView(
makeState({
installationUrl: "https://evil.example/apps/maya/installations/new",
managementUrl: "https://evil.example/settings/installations/12345",
verification: {
ready: false,
checks: [
{
key: "permissions",
label: "Review installation permissions",
ok: false,
code: "installation_missing",
detail: "Install the App on GitHub.",
},
],
},
}),
{
id: "endpoint-1",
setup: { webhookVerifiedAt: "2026-10-10T00:00:00Z", github: {} },
},
false,
false,
);
expect(view.mode).toBe("error");
if (view.mode === "error") {
expect(view.links.some((link) => link.external)).toBe(false);
expect(view.links).toEqual([
{
href: "/apps/chat/endpoint-1/settings",
label: "Connection settings",
external: false,
primary: false,
},
]);
}
});
it("enters checking mode while retrying or refetching a failed verification state", () => {
const state = makeState({
verification: {
ready: false,
checks: [
{
key: "repositories",
label: "Enabled repositories",
ok: false,
code: "repositories_sync_failed",
detail: "Could not refresh repositories from GitHub right now.",
},
],
},
});
expect(deriveGitHubVerifyView(state, baseBot, true, false)).toEqual({
mode: "checking",
statusText: "Checking GitHub access…",
});
expect(deriveGitHubVerifyView(state, baseBot, false, true)).toEqual({
mode: "checking",
statusText: "Checking GitHub access…",
});
});
it("polls only while waiting for install or webhook delivery and stops on failed checks", () => {
expect(shouldPollGitHubVerify(undefined)).toBe(true);
expect(
shouldPollGitHubVerify({ endpointId: "endpoint-1", state: "install" }),
).toBe(true);
expect(
shouldPollGitHubVerify(
makeState({
verification: {
ready: false,
checks: [
{
key: "webhook",
label: "Signed webhook delivery",
ok: false,
code: "webhook_pending",
detail: "Waiting…",
},
],
},
}),
),
).toBe(true);
expect(
shouldPollGitHubVerify(
makeState({
verification: {
ready: false,
checks: [
{
key: "repositories",
label: "Enabled repositories",
ok: false,
code: "repositories_sync_failed",
detail: "Could not refresh repositories.",
},
],
},
}),
),
).toBe(false);
expect(
shouldPollGitHubVerify(
makeState({
verification: {
ready: false,
checks: [
{
key: "repositories",
label: "Enabled repositories",
ok: false,
code: "no_installation_repositories",
detail: "Grant access on GitHub.",
},
],
},
}),
),
).toBe(false);
});
});
@@ -0,0 +1,280 @@
import { AlertCircle, ExternalLink, Loader2 } from "lucide-react";
import {
safeGitHubAppInstallUrl,
safeGitHubInstallationManagementUrl,
type GitHubAppWizardState,
type GitHubVerificationCheck,
} from "@paperclipai/shared";
import { Link } from "@/lib/router";
export type GitHubVerifyBotContext = {
id: string;
setup?: {
webhookVerifiedAt?: string | null;
github?: {
installationUrl?: string | null;
managementUrl?: string | null;
} | null;
} | null;
};
export type GitHubVerifyLink = {
href: string;
label: string;
external: boolean;
primary: boolean;
};
export type GitHubVerifyView =
| {
mode: "checking";
statusText: string;
}
| {
mode: "waiting";
statusText: string;
details: string[];
settingsHref: string;
}
| {
mode: "error";
heading: string;
checks: GitHubVerificationCheck[];
links: GitHubVerifyLink[];
};
function verifyIssueHeading(checks: GitHubVerificationCheck[]): string {
if (checks.length !== 1) return "Action needed to finish GitHub setup";
switch (checks[0]!.code) {
case "no_installation_repositories":
return "No repositories granted on GitHub";
case "no_enabled_repositories":
return "No repositories enabled in Paperclip";
case "repositories_sync_failed":
return "Could not load repositories from GitHub";
case "installation_suspended":
return "GitHub App installation is suspended";
case "installation_missing":
return "GitHub App installation is missing";
case "permissions_missing":
case "permissions_required":
return "GitHub App permissions need approval";
case "repositories_inaccessible":
return "GitHub denied access to selected repositories";
default:
return checks[0]!.label;
}
}
export function shouldPollGitHubVerify(
data: GitHubAppWizardState | undefined,
): boolean {
if (!data || data.state === "install") return true;
if (data.state !== "verify") return false;
const failed = data.verification?.checks.filter((check) => !check.ok) ?? [];
return (
failed.length === 0 ||
failed.every(
(check) => check.code === "webhook_pending" || check.key === "webhook",
)
);
}
export function deriveGitHubVerifyView(
state: GitHubAppWizardState,
bot: GitHubVerifyBotContext,
isFetching: boolean,
busy: boolean,
): GitHubVerifyView {
const checks = state.verification?.checks ?? [];
const deliveryVerifiedWhileChecking =
!!bot.setup?.webhookVerifiedAt &&
checks.some(
(check) => !check.ok && ["webhook", "delivery"].includes(check.key),
);
const failedChecks = checks.filter(
(check) =>
!check.ok &&
!(
deliveryVerifiedWhileChecking &&
["webhook", "delivery"].includes(check.key)
),
);
const waitingForWebhook =
deliveryVerifiedWhileChecking ||
(failedChecks.length > 0 &&
failedChecks.every(
(check) => check.code === "webhook_pending" || check.key === "webhook",
));
if (busy || (isFetching && !waitingForWebhook)) {
return {
mode: "checking",
statusText: "Checking GitHub access…",
};
}
if (!waitingForWebhook && failedChecks.length > 0) {
const managementUrl =
safeGitHubInstallationManagementUrl(state.managementUrl) ??
safeGitHubInstallationManagementUrl(bot.setup?.github?.managementUrl);
const installUrl =
safeGitHubAppInstallUrl(state.installationUrl) ??
safeGitHubAppInstallUrl(bot.setup?.github?.installationUrl);
const installLink = installUrl
? { href: installUrl, label: "Install App on GitHub" }
: null;
const managementLink = managementUrl
? { href: managementUrl, label: "Manage GitHub App installation" }
: null;
const needsInstallationOnly = failedChecks.some(
(check) => check.code === "installation_missing",
);
const githubLink = needsInstallationOnly
? (installLink ?? managementLink)
: (managementLink ?? installLink);
const hasRepositoryIssue = failedChecks.some(
(check) => check.key === "repositories",
);
const hasPaperclipEnableIssue = failedChecks.some(
(check) => check.code === "no_enabled_repositories",
);
const links: GitHubVerifyLink[] = [];
if (hasPaperclipEnableIssue) {
links.push({
href: `/apps/chat/${bot.id}/access`,
label: "Open Access settings",
external: false,
primary: true,
});
if (githubLink) {
links.push({ ...githubLink, external: true, primary: false });
}
} else {
if (githubLink) {
links.push({ ...githubLink, external: true, primary: true });
}
if (hasRepositoryIssue) {
links.push({
href: `/apps/chat/${bot.id}/access`,
label: "Access settings",
external: false,
primary: false,
});
}
}
links.push({
href: `/apps/chat/${bot.id}/settings`,
label: "Connection settings",
external: false,
primary: false,
});
return {
mode: "error",
heading: verifyIssueHeading(failedChecks),
checks: failedChecks,
links,
};
}
return {
mode: "waiting",
statusText: deliveryVerifiedWhileChecking
? "GitHub delivery verified. Checking App and repository access…"
: state.message ?? "Checking GitHub access…",
details: failedChecks.map((check) => check.detail),
settingsHref: `/apps/chat/${bot.id}/settings`,
};
}
export function GitHubVerifyStatus({ view }: { view: GitHubVerifyView }) {
if (view.mode === "checking") {
return (
<p
role="status"
className="flex items-center gap-2 text-sm text-muted-foreground"
>
<Loader2 className="size-4 shrink-0 animate-spin" />
{view.statusText}
</p>
);
}
if (view.mode === "error") {
return (
<div
role="alert"
className="space-y-3 rounded-md border border-destructive/30 bg-destructive/5 p-4"
>
<div className="flex items-start gap-2.5">
<AlertCircle className="mt-0.5 size-4 shrink-0 text-destructive" />
<div className="min-w-0 space-y-2">
<p className="text-sm font-medium text-foreground">{view.heading}</p>
<div className="space-y-2">
{view.checks.map((check) => (
<div key={check.key} className="space-y-0.5 text-sm">
{view.checks.length > 1 && (
<p className="font-medium text-foreground">{check.label}</p>
)}
<p className="text-muted-foreground">{check.detail}</p>
</div>
))}
</div>
</div>
</div>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 pl-6">
{view.links.map((link) => {
const linkClassName = link.primary
? "text-sm font-medium underline underline-offset-4"
: "text-sm text-muted-foreground underline underline-offset-4 hover:text-foreground";
return link.external ? (
<a
key={`${link.href}:${link.label}`}
className={`inline-flex items-center gap-1 ${linkClassName}`}
href={link.href}
target="_blank"
rel="noopener noreferrer"
>
{link.label}
<ExternalLink className="size-3.5" />
</a>
) : (
<Link
key={`${link.href}:${link.label}`}
className={linkClassName}
to={link.href}
>
{link.label}
</Link>
);
})}
</div>
</div>
);
}
return (
<>
<p
role="status"
className="flex items-center gap-2 text-sm text-muted-foreground"
>
<Loader2 className="size-4 shrink-0 animate-spin" />
{view.statusText}
</p>
{view.details.map((detail, index) => (
<p key={`${index}:${detail}`} className="text-sm text-muted-foreground">
{detail}
</p>
))}
<Link
className="text-sm underline underline-offset-4"
to={view.settingsHref}
>
Connection settings
</Link>
</>
);
}