Skip to content

The open-source app everyone uses to manage agents at work

fix(external-objects): distinguish hidden GitHub repos from genuinely-missing objects (#15906)

Devin Foley3d3b8d437144
diff --git a/server/src/__tests__/external-objects-service.test.ts b/server/src/__tests__/external-objects-service.test.ts
index ba8b118454..76555d88dd 100644
--- a/server/src/__tests__/external-objects-service.test.ts
+++ b/server/src/__tests__/external-objects-service.test.ts
@@ -328,11 +328,6 @@ describe("GitHub external object provider", () => {
}),
{ ok: false, liveness: "unreachable", errorCode: "github_rate_limited" },
],
- [
- "not-found",
- new Response("", { status: 404, headers: { etag: '"missing"' } }),
- { ok: true, snapshot: expect.objectContaining({ displayKey: "GitHub Pull Request", iconKey: "github", statusKey: "not_found", statusIconKey: "archive", statusCategory: "archived", statusTone: "muted" }) },
- ],
])("maps %s responses to provider-safe results", async (_name, githubResponse, expected) => {
const provider = createGitHubExternalObjectProvider({} as any, {
fetch: async () => githubResponse,
@@ -348,6 +343,191 @@ describe("GitHub external object provider", () => {
expect(result).toEqual(expect.objectContaining(expected));
expect(JSON.stringify(result)).not.toContain("http");
});
+
+ it("classifies a 404 as not-found when the repository is visible to the credentials", async () => {
+ const fetch = vi.fn(async (url: string) => {
+ if (url.endsWith("/repos/acme/app")) {
+ return new Response(JSON.stringify({ full_name: "acme/app" }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }
+ return new Response("", { status: 404, headers: { etag: '"missing"' } });
+ });
+ const provider = createGitHubExternalObjectProvider({} as any, { fetch, tokenProvider: null });
+ const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
+
+ const result = await resolver.resolve({
+ companyId: "company-1",
+ object: githubObject("pull/42", "pull_request"),
+ });
+
+ expect(fetch).toHaveBeenCalledWith(
+ "https://api.github.com/repos/acme/app",
+ expect.objectContaining({ headers: expect.not.objectContaining({ authorization: expect.any(String) }) }),
+ );
+ expect(result).toEqual({
+ ok: true,
+ snapshot: expect.objectContaining({
+ displayKey: "GitHub Pull Request",
+ iconKey: "github",
+ statusKey: "not_found",
+ statusIconKey: "archive",
+ statusCategory: "archived",
+ statusTone: "muted",
+ isTerminal: true,
+ data: expect.objectContaining({ provider: "github", notFound: true, probeVerified: true }),
+ }),
+ });
+ expect(JSON.stringify(result)).not.toContain("http");
+ });
+
+ it("caches repository-visibility probes per company and repo", async () => {
+ let probeCalls = 0;
+ const fetch = vi.fn(async (url: string) => {
+ if (url.endsWith("/repos/acme/app")) {
+ probeCalls += 1;
+ return new Response(JSON.stringify({ full_name: "acme/app" }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }
+ return new Response("", { status: 404, headers: { etag: '"missing"' } });
+ });
+ const provider = createGitHubExternalObjectProvider({} as any, { fetch, tokenProvider: null });
+ const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
+
+ await resolver.resolve({ companyId: "company-1", object: githubObject("pull/42", "pull_request") });
+ await resolver.resolve({ companyId: "company-1", object: githubObject("pull/99", "pull_request") });
+
+ expect(probeCalls).toBe(1);
+ expect(fetch.mock.calls.filter(([url]) => String(url).endsWith("/repos/acme/app"))).toHaveLength(1);
+ });
+
+ it("does not reuse a cached probe verdict across credential changes", async () => {
+ const fetch = vi.fn(async (url: string, init?: RequestInit) => {
+ if (url.endsWith("/repos/acme/app")) {
+ const auth = (init?.headers as Record<string, string> | undefined)?.authorization;
+ if (auth === "Bearer token-A" || auth === "Bearer token-B") {
+ return new Response(JSON.stringify({ full_name: "acme/app" }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }
+ return new Response("", { status: 404 });
+ }
+ return new Response("", { status: 404, headers: { etag: '"missing"' } });
+ });
+ let token: string | null = "token-A";
+ const provider = createGitHubExternalObjectProvider({} as any, {
+ fetch,
+ tokenProvider: async () => token,
+ });
+ const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
+
+ const visibleVerdict = await resolver.resolve({ companyId: "company-1", object: githubObject("pull/42", "pull_request") });
+
+ // Same repo, same credentials: probe result is reused.
+ await resolver.resolve({ companyId: "company-1", object: githubObject("pull/99", "pull_request") });
+ const probesUnderTokenA = fetch.mock.calls.filter(([url]) => String(url).endsWith("/repos/acme/app"));
+ expect(probesUnderTokenA).toHaveLength(1);
+
+ // Credential now only has access to a different repo — cache must not
+ // serve the stale "visible" verdict, or this object would be frozen as a
+ // probe-verified not-found forever.
+ token = "other-token";
+ const hiddenVerdict = await resolver.resolve({ companyId: "company-1", object: githubObject("pull/10", "pull_request") });
+
+ expect(visibleVerdict).toEqual(
+ expect.objectContaining({ ok: true, snapshot: expect.objectContaining({ isTerminal: true }) }),
+ );
+ expect(hiddenVerdict).toEqual(
+ expect.objectContaining({ ok: false, liveness: "auth_required", errorCode: "github_repo_not_accessible" }),
+ );
+ expect(fetch.mock.calls.filter(([url]) => String(url).endsWith("/repos/acme/app"))).toHaveLength(2);
+ });
+
+ it("classifies a 404 as auth-required when the repository itself is hidden", async () => {
+ const fetch = vi.fn(async (url: string) => {
+ if (url.endsWith("/repos/acme/app")) {
+ return new Response("", { status: 404 });
+ }
+ return new Response("", { status: 404, headers: { etag: '"missing"' } });
+ });
+ const provider = createGitHubExternalObjectProvider({} as any, { fetch, tokenProvider: null });
+ const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
+
+ const result = await resolver.resolve({
+ companyId: "company-1",
+ object: githubObject("pull/42", "pull_request"),
+ });
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ liveness: "auth_required",
+ errorCode: "github_repo_not_accessible",
+ errorMessage: expect.stringContaining("acme/app"),
+ }),
+ );
+ expect(JSON.stringify(result)).not.toContain("http");
+ });
+
+ it("classifies a 404 as unreachable when the repository probe itself fails", async () => {
+ const fetch = vi.fn(async (url: string) => {
+ if (url.endsWith("/repos/acme/app")) {
+ throw new Error("network down");
+ }
+ return new Response("", { status: 404, headers: { etag: '"missing"' } });
+ });
+ const provider = createGitHubExternalObjectProvider({} as any, { fetch, tokenProvider: null });
+ const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
+
+ const result = await resolver.resolve({
+ companyId: "company-1",
+ object: githubObject("pull/42", "pull_request"),
+ });
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ liveness: "unreachable",
+ errorCode: "github_repo_probe_failed",
+ }),
+ );
+ expect(JSON.stringify(result)).not.toContain("http");
+ });
+
+ it("classifies a 404 as unreachable when the repository probe is rate-limited", async () => {
+ const fetch = vi.fn(async (url: string) => {
+ if (url.endsWith("/repos/acme/app")) {
+ return new Response("", {
+ status: 403,
+ headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(Math.floor(Date.now() / 1000) + 120) },
+ });
+ }
+ return new Response("", { status: 404, headers: { etag: '"missing"' } });
+ });
+ const provider = createGitHubExternalObjectProvider({} as any, { fetch, tokenProvider: null });
+ const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
+
+ const result = await resolver.resolve({
+ companyId: "company-1",
+ object: githubObject("pull/42", "pull_request"),
+ });
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ liveness: "unreachable",
+ errorCode: "github_repo_probe_failed",
+ }),
+ );
+ expect(result).not.toEqual(
+ expect.objectContaining({ ok: false, liveness: "auth_required", errorCode: "github_repo_not_accessible" }),
+ );
+ expect(JSON.stringify(result)).not.toContain("http");
+ });
});
describeEmbeddedPostgres("externalObjectService", () => {
@@ -786,6 +966,183 @@ describeEmbeddedPostgres("externalObjectService", () => {
expect(resolve).toHaveBeenCalledTimes(1);
});
+ it("keeps terminal objects fresh-for-display after their refresh window passes", async () => {
+ const { companyId, issueId } = await createIssue();
+ const resolve = vi.fn(async () => ({
+ ok: true as const,
+ snapshot: {
+ statusCategory: "closed" as const,
+ statusTone: "muted" as const,
+ statusKey: "closed",
+ statusLabel: "Closed",
+ isTerminal: true,
+ ttlSeconds: 1,
+ },
+ }));
+ const svc = externalObjectService(db, {
+ resolvers: [{ providerKey: "url", objectType: "link", resolve }],
+ github: false,
+ });
+ await svc.syncIssue(issueId);
+ const object = await db.select().from(externalObjects).then((rows) => rows[0]!);
+ await svc.refreshObject(object.id, { companyId, force: true });
+ // Expire the refresh window so the display path computes liveness from
+ // scratch. Terminal objects must still show as fresh, never as stale.
+ await db
+ .update(externalObjects)
+ .set({ nextRefreshAt: new Date(0) })
+ .where(eq(externalObjects.id, object.id));
+
+ const summary = await svc.getIssueSummary(issueId);
+ const displayed = summary.objects[0];
+ expect(displayed?.liveness).toBe("fresh");
+ expect(displayed?.isTerminal).toBe(true);
+
+ const summaryLater = await svc.getIssueSummaries(companyId, [issueId]).then((map) => map.get(issueId));
+ expect(summaryLater?.objects[0]?.liveness).toBe("fresh");
+ expect(summaryLater?.staleCount).toBe(0);
+ expect(summaryLater?.byLiveness?.stale ?? 0).toBe(0);
+ });
+
+ it("re-checks previously frozen GitHub not-found objects so they can self-heal", async () => {
+ const { companyId } = await createIssue();
+ const canonical = canonicalizeExternalObjectUrl("https://github.com/acme/app/pull/42");
+ if (!canonical) throw new Error("expected canonical url");
+ const inserted = await db.insert(externalObjects).values({
+ companyId,
+ providerKey: "github",
+ objectType: "pull_request",
+ externalId: "acme/app#pull/42",
+ sanitizedCanonicalUrl: canonical.sanitizedCanonicalUrl,
+ canonicalIdentityHash: canonical.canonicalIdentityHash,
+ displayTitle: "acme/app#42",
+ statusKey: "not_found",
+ statusLabel: "Not found",
+ statusCategory: "archived",
+ statusTone: "muted",
+ liveness: "fresh",
+ isTerminal: true,
+ nextRefreshAt: new Date(0),
+ data: { provider: "github", notFound: true },
+ }).returning();
+ const object = inserted[0]!;
+
+ const snapshot = {
+ statusKey: "open" as const,
+ statusLabel: "Open" as const,
+ statusCategory: "open" as const,
+ statusTone: "info" as const,
+ statusIconKey: "git-pull-request" as const,
+ displayTitle: "acme/app#42",
+ isTerminal: false,
+ ttlSeconds: 300,
+ data: { provider: "github", owner: "acme", repo: "app", number: 42 },
+ };
+ const resolver: ExternalObjectResolver = {
+ providerKey: "github",
+ objectType: "pull_request",
+ resolve: vi.fn(async () => ({ ok: true as const, snapshot })),
+ };
+ const svc = externalObjectService(db, { resolvers: [resolver], github: false });
+ expect(object.isTerminal).toBe(true);
+
+ const refreshed = await svc.refreshDueObjects(companyId);
+ expect(refreshed).toHaveLength(1);
+ expect(refreshed[0]?.refreshed).toBe(true);
+
+ const updated = await db.select().from(externalObjects).then((rows) => rows[0]!);
+ expect(updated.statusLabel).toBe("Open");
+ expect(updated.isTerminal).toBe(false);
+ expect(updated.liveness).toBe("fresh");
+ });
+
+ it("does not re-check probe-verified GitHub not-found objects (deleted references are terminal)", async () => {
+ const { companyId } = await createIssue();
+ const canonical = canonicalizeExternalObjectUrl("https://github.com/acme/app/pull/42");
+ if (!canonical) throw new Error("expected canonical url");
+ await db.insert(externalObjects).values({
+ companyId,
+ providerKey: "github",
+ objectType: "pull_request",
+ externalId: "acme/app#pull/42",
+ sanitizedCanonicalUrl: canonical.sanitizedCanonicalUrl,
+ canonicalIdentityHash: canonical.canonicalIdentityHash,
+ displayTitle: "acme/app#42",
+ statusKey: "not_found",
+ statusLabel: "Not found",
+ statusCategory: "archived",
+ statusTone: "muted",
+ liveness: "fresh",
+ isTerminal: true,
+ nextRefreshAt: new Date(0),
+ data: { provider: "github", notFound: true, probeVerified: true },
+ });
+ const resolver: ExternalObjectResolver = {
+ providerKey: "github",
+ objectType: "pull_request",
+ resolve: vi.fn(async () => ({
+ ok: true as const,
+ snapshot: {
+ statusKey: "open",
+ statusLabel: "Open",
+ statusCategory: "open" as const,
+ statusTone: "info" as const,
+ isTerminal: false,
+ ttlSeconds: 300,
+ },
+ })),
+ };
+ const svc = externalObjectService(db, { resolvers: [resolver], github: false });
+
+ const refreshed = await svc.refreshDueObjects(companyId);
+
+ expect(refreshed).toEqual([]);
+ expect(resolver.resolve).not.toHaveBeenCalled();
+ });
+
+ it("does not re-check terminal objects that are not GitHub not-found verdicts", async () => {
+ const { companyId } = await createIssue();
+ const canonical = canonicalizeExternalObjectUrl("https://github.com/acme/app/pull/42");
+ if (!canonical) throw new Error("expected canonical url");
+ await db.insert(externalObjects).values({
+ companyId,
+ providerKey: "github",
+ objectType: "pull_request",
+ externalId: "acme/app#pull/42",
+ sanitizedCanonicalUrl: canonical.sanitizedCanonicalUrl,
+ canonicalIdentityHash: canonical.canonicalIdentityHash,
+ displayTitle: "acme/app#42",
+ statusKey: "merged",
+ statusLabel: "Merged",
+ statusCategory: "succeeded",
+ statusTone: "success",
+ liveness: "fresh",
+ isTerminal: true,
+ nextRefreshAt: new Date(0),
+ });
+ const resolver: ExternalObjectResolver = {
+ providerKey: "github",
+ objectType: "pull_request",
+ resolve: vi.fn(async () => ({
+ ok: true as const,
+ snapshot: {
+ statusKey: "open",
+ statusLabel: "Open",
+ statusCategory: "open" as const,
+ statusTone: "info" as const,
+ isTerminal: false,
+ ttlSeconds: 300,
+ },
+ })),
+ };
+ const svc = externalObjectService(db, { resolvers: [resolver], github: false });
+
+ const refreshed = await svc.refreshDueObjects(companyId);
+
+ expect(refreshed).toEqual([]);
+ expect(resolver.resolve).not.toHaveBeenCalled();
+ });
+
it("keeps external object identities company-scoped for duplicate urls", async () => {
const first = await createIssue();
const second = await createIssue();
diff --git a/server/src/services/external-objects.ts b/server/src/services/external-objects.ts
index 1312e62d3f..6776cb2530 100644
--- a/server/src/services/external-objects.ts
+++ b/server/src/services/external-objects.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { and, asc, eq, inArray, isNull, lte, or, sql } from "drizzle-orm";
+import { and, asc, eq, inArray, isNull, lte, not, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { companies, documents, externalObjectMentions, externalObjects, issueComments, issueDocuments, issues, plugins } from "@paperclipai/db";
import {
@@ -124,6 +124,9 @@ function addSeconds(date: Date, seconds: number) {
}
function visibleLiveness(object: ExternalObjectRecord, now = new Date()): ExternalObjectLivenessState {
+ // Terminal objects are never refreshed again, so "stale" (refresh overdue) is
+ // misleading — their resolved status is final. Keep the last liveness as-is.
+ if (object.isTerminal) return object.liveness;
if (object.liveness === "fresh" && object.nextRefreshAt && object.nextRefreshAt <= now) {
return "stale";
}
@@ -810,7 +813,7 @@ export function externalObjectService(
const [updated] = await db
.update(externalObjects)
.set({
- liveness: visibleLiveness(object, now) === "fresh" ? "stale" : object.liveness,
+ liveness: object.isTerminal ? object.liveness : visibleLiveness(object, now) === "fresh" ? "stale" : object.liveness,
nextRefreshAt: addSeconds(now, DEFAULT_RETRY_AFTER_SECONDS),
refreshStartedAt: null,
refreshToken: null,
@@ -824,10 +827,15 @@ export function externalObjectService(
const result = pluginResult ?? await resolver!.resolve({ companyId: object.companyId, object });
if (!result.ok) {
+ // A failed refresh means the object's status is currently unknown, not
+ // terminal. Clear a previous terminal verdict so the object keeps being
+ // scheduled for automatic refresh and self-heals (e.g. a GitHub "not
+ // found" that later resolves once repo access improves).
const [updated] = await db
.update(externalObjects)
.set({
liveness: result.liveness,
+ isTerminal: false,
lastErrorAt: now,
lastErrorCode: result.errorCode,
lastErrorMessage: sanitizeErrorMessage(result.errorMessage),
@@ -1024,13 +1032,33 @@ export function externalObjectService(
async function refreshDueObjectsUnchecked(companyId: string, limit = 50, now = new Date()) {
const staleRefreshStartedBefore = new Date(now.getTime() - DEFAULT_REFRESH_LEASE_SECONDS * 1000);
+ // Terminal objects are usually skipped forever, but a GitHub "not found"
+ // verdict is only trustworthy while the repository is actually visible to
+ // the configured credentials. GitHub hides inaccessible (often private)
+ // repos behind a 404, so a not-found object can become resolvable later
+ // when credentials or repo visibility improve. Re-check objects that were
+ // frozen as "not found" before the repository probe existed so they
+ // self-heal instead of freezing. Once the provider has probed the repo and
+ // confirmed it is visible (data.probeVerified = "true"), the not-found
+ // verdict is definitive, so stop re-polling that object to avoid burning
+ // the company's GitHub API budget on deleted references forever.
+ const probeVerifiedNotFound = sql`coalesce(${externalObjects.data}->>'probeVerified', 'false') = 'true'`;
+ const refreshable = or(
+ eq(externalObjects.isTerminal, false),
+ and(
+ eq(externalObjects.isTerminal, true),
+ eq(externalObjects.providerKey, "github"),
+ eq(externalObjects.statusKey, "not_found"),
+ not(probeVerifiedNotFound),
+ ),
+ )!;
const due = await db
.select({ id: externalObjects.id })
.from(externalObjects)
.where(
and(
eq(externalObjects.companyId, companyId),
- eq(externalObjects.isTerminal, false),
+ refreshable,
lte(externalObjects.nextRefreshAt, now),
or(
isNull(externalObjects.refreshStartedAt),
diff --git a/server/src/services/github-external-object-provider.ts b/server/src/services/github-external-object-provider.ts
index 928e8501f5..eeb65ca648 100644
--- a/server/src/services/github-external-object-provider.ts
+++ b/server/src/services/github-external-object-provider.ts
@@ -1,3 +1,4 @@
+import { createHash } from "node:crypto";
import type { Db } from "@paperclipai/db";
import type { ExternalObjectCanonicalUrl } from "@paperclipai/shared";
import { DEFAULT_GITHUB_TOKEN_SECRET_NAMES } from "./git-credentials.js";
@@ -188,10 +189,54 @@ function notFoundSnapshot(identity: GitHubObjectIdentity, etag: string | null):
repo: identity.repo,
number: identity.number,
notFound: true,
+ // The repository was probed with the configured credentials and found
+ // to be visible, so this not-found verdict is definitive, not a stale
+ // guess from a time when credentials could not see the repo. The due
+ // sweep uses this flag to avoid re-polling a confirmed-deleted object
+ // forever and exhausting the company's GitHub API budget.
+ probeVerified: true,
},
};
}
+/**
+ * Probe `/repos/{owner}/{repo}` to classify a 404 on a pull request or issue.
+ *
+ * GitHub returns 404 both when the object does not exist and when the repository
+ * exists but the credentials cannot see it (private repos are deliberately hidden
+ * behind 404). This probes the repo metadata with the same credentials to tell the
+ * two apart:
+ *
+* - "visible": the repo returns 2xx — the referenced object really is gone.
+ * - "hidden": the repo returns 404/403 — the credentials lack access to the repo,
+ * so the object status cannot be determined and should not be frozen as "Not found".
+ * - "uncertain": the probe itself failed (network/rate limit) — retry later.
+ */
+async function probeRepoVisibility(
+ identity: GitHubObjectIdentity,
+ opts: { fetch: FetchLike; headers?: Record<string, string> | undefined },
+): Promise<"visible" | "hidden" | "uncertain"> {
+ try {
+ const probe = await opts.fetch(
+ `${gitHubApiBase(identity.host)}/repos/${encodeURIComponent(identity.owner)}/${encodeURIComponent(identity.repo)}`,
+ { headers: opts.headers },
+ );
+ if (probe.ok) return "visible";
+ if (probe.status === 404) return "hidden";
+ if (probe.status === 403) {
+ // GitHub can return 403 for both "credentials lack access" and "rate limit
+ // reached". A rate-limited probe cannot tell the two apart, so treat it as
+ // uncertain (retry later) instead of implying missing access.
+ const rateLimitRemaining = probe.headers.get("x-ratelimit-remaining");
+ if (rateLimitRemaining === "0") return "uncertain";
+ return "hidden";
+ }
+ return "uncertain";
+ } catch {
+ return "uncertain";
+ }
+}
+
function pullRequestSnapshot(identity: GitHubObjectIdentity, body: Record<string, unknown>, etag: string | null): ExternalObjectResolverSnapshot {
const title = asString(body.title);
const state = asString(body.state) ?? "unknown";
@@ -338,6 +383,30 @@ export function createGitHubExternalObjectProvider(
const tokenProvider = Object.prototype.hasOwnProperty.call(opts, "tokenProvider") && opts.tokenProvider !== undefined
? opts.tokenProvider
: ((companyId: string) => defaultTokenProvider(db, companyId, secretNames));
+// Cache repository-visibility probe results so many objects in the same repo
+ // share a single probe instead of each issuing its own request every refresh
+ // cycle. Only determined outcomes ("visible"/"hidden") are cached; uncertain
+ // probes are retried on the next cycle. The cache is keyed per company+repo+
+ // credential fingerprint so a verdict obtained under one token is never
+ // reused after the company rotates its credentials — that would freeze a
+ // reference as "probe-verified not-found" using an out-of-date result.
+
+ const probeCache = new Map<string, { result: "visible" | "hidden"; expiresAt: number }>();
+ async function cachedProbeRepoVisibility(
+ companyId: string,
+ identity: GitHubObjectIdentity,
+ headers: Record<string, string>,
+ ): Promise<"visible" | "hidden" | "uncertain"> {
+ const credentialFingerprint = createHash("sha256").update(headers.authorization ?? "anonymous").digest("hex");
+ const key = `${companyId}\u0000${credentialFingerprint}\u0000${identity.owner.toLowerCase()}\u0000${identity.repo.toLowerCase()}`;
+ const cached = probeCache.get(key);
+ if (cached && cached.expiresAt > Date.now()) return cached.result;
+ const result = await probeRepoVisibility(identity, { fetch: fetchImpl, headers });
+ if (result !== "uncertain") {
+ probeCache.set(key, { result, expiresAt: Date.now() + GITHUB_OBJECT_TTL_SECONDS * 1000 });
+ }
+ return result;
+ }
const detector: ExternalObjectDetector = {
key: "github",
@@ -414,7 +483,32 @@ export function createGitHubExternalObjectProvider(
const etag = response.headers.get("etag");
if (response.status === 404) {
- return { ok: true, snapshot: notFoundSnapshot(identity, etag) };
+ // GitHub deliberately returns 404 for repositories the credentials cannot
+ // see, to avoid leaking that a private repo exists. A 404 therefore means
+ // either "object deleted/never existed" or "repo private / no access".
+ // Probe the repository metadata to classify: if the repo itself is visible
+ // the object truly is gone; if it is not, surface credentials-needed
+ // instead of permanently freezing a reference as "Not found".
+ const repoVisibility = await cachedProbeRepoVisibility(companyId, identity, headers);
+ if (repoVisibility === "visible") {
+ return { ok: true, snapshot: notFoundSnapshot(identity, etag) };
+ }
+ if (repoVisibility === "hidden") {
+ return {
+ ok: false,
+ liveness: "auth_required",
+ errorCode: "github_repo_not_accessible",
+ errorMessage: `GitHub returned not-found for ${identity.owner}/${identity.repo}. The repository may be private, deleted, or the configured GitHub credentials may lack access to it.`,
+ retryAfterSeconds: GITHUB_OBJECT_TTL_SECONDS,
+ };
+ }
+ return {
+ ok: false,
+ liveness: "unreachable",
+ errorCode: "github_repo_probe_failed",
+ errorMessage: "GitHub could not verify this repository while checking this object.",
+ retryAfterSeconds: GITHUB_OBJECT_TTL_SECONDS,
+ };
}
const failure = failureFromGitHubResponse(response);
diff --git a/ui/src/components/ExternalObjectStatusIcon.tsx b/ui/src/components/ExternalObjectStatusIcon.tsx
index 3c17a941cd..f529ecc8f6 100644
--- a/ui/src/components/ExternalObjectStatusIcon.tsx
+++ b/ui/src/components/ExternalObjectStatusIcon.tsx
@@ -59,7 +59,8 @@ export function ExternalObjectStatusIcon({
const livenessSuffix = liveness === "fresh" || liveness === "unknown"
? ""
: ` (${externalObjectLivenessLabel(liveness)})`;
- const ariaLabel = `${label ?? externalObjectCategoryLabel(category)}${livenessSuffix}`;
+ const baseLabel = label ?? externalObjectCategoryLabel(category);
+ const ariaLabel = `${baseLabel}${baseLabel.includes(externalObjectLivenessLabel(liveness)) ? "" : livenessSuffix}`;
// The clock overlay needs a positioned wrapper. Inline mode keeps the icon
// tight to the surrounding text; pill mode expects to size by sizeClassName.
diff --git a/ui/src/components/MarkdownBody.tsx b/ui/src/components/MarkdownBody.tsx
index e45e93fd9b..9a7b5b34ac 100644
--- a/ui/src/components/MarkdownBody.tsx
+++ b/ui/src/components/MarkdownBody.tsx
@@ -37,7 +37,7 @@ import { StatusIcon } from "./StatusIcon";
import { WorkspaceFileLink } from "./WorkspaceFileLink";
import { ExternalObjectStatusIcon } from "./ExternalObjectStatusIcon";
import {
- externalObjectCategoryLabel,
+ externalObjectDisplayStatusLabel,
externalObjectLivenessLabel,
externalObjectProviderLabel,
} from "../lib/external-objects";
@@ -240,9 +240,10 @@ function MarkdownExternalLink({
}) {
const provider = externalObjectProviderLabel(reference.providerKey);
const displayKey = reference.displayKey?.trim() || provider;
- const statusLabel = reference.statusLabel ?? externalObjectCategoryLabel(reference.statusCategory);
+ const statusLabel = externalObjectDisplayStatusLabel(reference);
const livenessLabel = externalObjectLivenessLabel(reference.liveness);
const livenessSuffix = reference.liveness === "fresh" || reference.liveness === "unknown"
+ || livenessLabel.toLowerCase() === statusLabel.toLowerCase()
? ""
: ` (${livenessLabel})`;
const titleParts = [
diff --git a/ui/src/components/MarkdownExternalLink.test.tsx b/ui/src/components/MarkdownExternalLink.test.tsx
index 173b1c46c3..0f4f934084 100644
--- a/ui/src/components/MarkdownExternalLink.test.tsx
+++ b/ui/src/components/MarkdownExternalLink.test.tsx
@@ -91,4 +91,57 @@ describe("MarkdownBody external object decoration", () => {
});
expect(html).toContain('aria-label="HubSpot Reconnect (Requires auth): Acme deal"');
});
+
+ it("labels detected-but-unresolved GitHub objects as not yet refreshed, not not yet resolved", () => {
+ const html = render("See https://github.com/acme/web/pull/241", {
+ "https://github.com/acme/web/pull/241": {
+ providerKey: "github",
+ objectType: "pull_request",
+ displayKey: "Github Pull Request",
+ iconKey: "github",
+ statusCategory: "unknown",
+ liveness: "unknown",
+ statusLabel: null,
+ displayTitle: "acme/web#241",
+ },
+ });
+ expect(html).toContain("data-external-link=\"resolved\"");
+ expect(html).toContain('aria-label="Github Pull Request Not yet refreshed: acme/web#241"');
+ expect(html).not.toContain("Not yet resolved");
+ });
+
+ it("does not repeat the liveness label when the status label equals it", () => {
+ const html = render("Auth-blocked: https://github.com/acme/web/pull/241", {
+ "https://github.com/acme/web/pull/241": {
+ providerKey: "github",
+ objectType: "pull_request",
+ displayKey: "Github Pull Request",
+ iconKey: "github",
+ statusCategory: "unknown",
+ liveness: "auth_required",
+ statusLabel: null,
+ displayTitle: "acme/web#241",
+ },
+ });
+ expect(html).toContain('aria-label="Github Pull Request Requires auth: acme/web#241"');
+ expect(html).not.toContain("Requires auth (Requires auth)");
+ expect(html).not.toContain("(Requires auth)");
+ });
+
+ it("does not repeat the liveness label when the status label equals it for unreachable", () => {
+ const html = render("Down: https://github.com/acme/web/pull/241", {
+ "https://github.com/acme/web/pull/241": {
+ providerKey: "github",
+ objectType: "pull_request",
+ displayKey: "Github Pull Request",
+ iconKey: "github",
+ statusCategory: "unknown",
+ liveness: "unreachable",
+ statusLabel: null,
+ displayTitle: "acme/web#241",
+ },
+ });
+ expect(html).toContain('aria-label="Github Pull Request Unreachable: acme/web#241"');
+ expect(html).not.toContain("(Unreachable)");
+ });
});