Implement confirm-only PR panel composer with classified error blocking (#9428)

* Clarify PR panel guidance: classify errors and confirm-only composer

Replace the ambiguous GitHub hosted-review boolean with a four-state evidence
model (found/positive_unresolved/not_found/unknown) so "No PR found" never
appears without an accepted lookup result. Classify GitHub refresh failures
into types (rate_limited, auth, network, permission, repo_unavailable,
gh_unavailable, unknown) for stable, honest copy. Confirmed-only composer:
preserve drafts across transient failures; hide Create during hard errors and
positive-unresolved evidence. Hard errors clear only when an eligibility
request starts after the error and returns an accepted outcome. Propagate
error types and unified retry schedule through the store. Sync mobile parity
with shouldOpenChecksPanelCreateComposer gating. Localize all new copy.

* Clarify PR panel guidance: classify errors and confirm-only composer

Add reviewLookupOutcome to hosted-review eligibility and thread it through
the panel so it never claims "No PR found" without accepted evidence. A
failed lookup is unavailable, not a settled no-PR. Fail closed on positive
unresolved evidence, hard refresh errors, and unavailable lookups. Add
structured GitHub refresh-error classification with Retry-After parsing.
Implement confirmed-only composer gating based on fresh, matching-context
eligibility with hard-error clearing. Mobile gates on reviewLookupOutcome
to prevent false Create claims. Surface throwOnFailure variants for each
provider so transport failures cross the RPC boundary instead of collapsing
to null. (Design success criteria 1–4; invariant 8.)

* Add exec-error helpers for subprocess error classification

Extracts stderr/stdout parsing and Retry-After detection into a
lightweight module that can be imported without pulling in the heavier
runner machinery. Supports PR-refresh error classification and proper
rate-limit handling for gh commands.

* test(mobile): include reviewLookupOutcome in create eligibility fixtures

Create / Push & Create now fails closed unless the lookup is not_found.
Update mobile test fixtures so accepted-no-PR cases can still proceed.

* Add OrThrow mock variants to forge-provider test mocks

forge-provider resolves branch reviews via the OrThrow variant so
lookup failures surface as unavailable instead of "no PR found".
This commit is contained in:
Jinjing
2026-07-19 16:32:36 -07:00
committed by GitHub
parent c5d40565af
commit d67ede1594
62 changed files with 4359 additions and 905 deletions
+28
View File
@@ -1268,6 +1268,34 @@ describe('getPRForBranch', () => {
)
})
it('propagates a Retry-After cooldown into the rate-limited retry schedule', async () => {
resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({
candidates: [{ owner: 'stablyai', repo: 'orca' }],
headRepo: null
})
// gh puts the diagnostic on `.stderr`; a secondary limit carries Retry-After.
ghExecFileAsyncMock
.mockRejectedValueOnce(
Object.assign(new Error('gh exited with 1.'), {
stderr: 'HTTP 403: You have exceeded a secondary rate limit\nRetry-After: 120'
})
)
.mockResolvedValueOnce({ stdout: JSON.stringify([]) })
const before = Date.now()
const outcome = await getPRForBranchOutcome('/repo-root', 'feature/test')
expect(outcome.kind).toBe('upstream-error')
if (outcome.kind !== 'upstream-error') {
throw new Error('expected upstream-error')
}
expect(outcome.errorType).toBe('rate_limited')
// ~120s cooldown surfaced as both the manual gate and the auto-retry time.
expect(outcome.retryDisabledUntil).toBeDefined()
expect(outcome.nextAutoRetryAt).toBe(outcome.retryDisabledUntil)
expect(outcome.retryDisabledUntil ?? 0).toBeGreaterThanOrEqual(before + 119_000)
expect(outcome.retryDisabledUntil ?? 0).toBeLessThanOrEqual(Date.now() + 121_000)
})
it('reports no PR when fallback branch discovery cleanly misses', async () => {
resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({
candidates: [{ owner: 'stablyai', repo: 'orca' }],
+20 -47
View File
@@ -39,6 +39,10 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { sliceCheckLogTail } from './check-job-log-tail-slice'
import {
classifyPRRefreshError,
safePRRefreshErrorMessage
} from './pr-refresh-error-classification'
import { getPRConflictSummary } from './conflict-summary'
import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch'
import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths'
@@ -47,7 +51,6 @@ import {
execFileAsync,
ghExecFileAsync,
gitExecFileAsync,
extractExecError,
acquire,
release,
getOwnerRepo,
@@ -63,6 +66,9 @@ import {
type LocalGitExecOptions,
type OwnerRepo
} from './gh-utils'
// Import the pure error-parsing helpers from the lightweight module, not
// `./gh-utils`, so tests that mock gh-utils still resolve the real functions.
import { extractExecError, parseRetryAfterMs } from '../git/exec-error'
import {
isCommitPartOfMergedPR,
type MergedPRCommitMembership
@@ -181,61 +187,28 @@ async function assertRateLimitBudget(bucket: RateLimitBucketKind): Promise<void>
}
}
function classifyPRRefreshError(
err: unknown
): Extract<PRRefreshOutcome, { kind: 'upstream-error' }>['errorType'] {
const message = err instanceof Error ? err.message : String(err)
// Why: GitHub-unreachable buckets (5xx outage / network / rate limit) share
// one detector with the Tasks work-item path so both surfaces attribute an
// outage to GitHub identically. Rate-limit responses also carry "HTTP 403",
// so this must run before the permission check below.
const unavailable = classifyGitHubUnavailable(message)
if (unavailable) {
return unavailable
}
const lower = message.toLowerCase()
if (lower.includes('http 403') || lower.includes('resource not accessible')) {
return 'permission'
}
if (lower.includes('http 404') || lower.includes('could not resolve to a repository')) {
return 'repo_unavailable'
}
return /auth|login|credential/i.test(message) ? 'auth' : 'unknown'
}
function safePRRefreshErrorMessage(
errorType: Extract<PRRefreshOutcome, { kind: 'upstream-error' }>['errorType']
): string {
switch (errorType) {
case 'rate_limited':
return 'GitHub rate limit is low. Try again after the limit resets.'
case 'auth':
return 'GitHub authentication is unavailable. Check your gh login.'
case 'network':
return 'GitHub is unreachable right now. Check your network and try again.'
case 'server_error':
return "GitHub's API is temporarily unavailable (server error). This is a GitHub-side issue."
case 'permission':
return 'GitHub did not allow access to this pull request.'
case 'repo_unavailable':
return 'The GitHub repository is unavailable or cannot be resolved.'
case 'gh_unavailable':
return 'GitHub CLI is unavailable.'
case 'unknown':
return 'GitHub pull request refresh failed.'
}
}
function prRefreshUpstreamError(
err: unknown
): Extract<PRRefreshOutcome, { kind: 'upstream-error' }> {
const errorType = classifyPRRefreshError(err)
return {
const outcome: Extract<PRRefreshOutcome, { kind: 'upstream-error' }> = {
kind: 'upstream-error',
errorType,
message: safePRRefreshErrorMessage(errorType),
fetchedAt: Date.now()
}
// Why: a rate limit that carries a Retry-After is a real cooldown — surface it
// as the retry schedule so the renderer disables manual Retry until the reset
// and shows a truthful auto-retry time, instead of retrying into another 429.
if (errorType === 'rate_limited') {
const retryAfterMs = parseRetryAfterMs(extractExecError(err).stderr)
if (retryAfterMs !== null && retryAfterMs > 0) {
const retryAt = Date.now() + retryAfterMs
outcome.nextAutoRetryAt = retryAt
outcome.retryDisabledUntil = retryAt
}
}
return outcome
}
function isNoPullRequestError(err: unknown): boolean {
+5 -2
View File
@@ -1,11 +1,14 @@
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { gitExecFileAsync, ghExecFileAsync, extractExecError } from '../git/runner'
import { gitExecFileAsync, ghExecFileAsync } from '../git/runner'
// Pure error-parsing helpers come from the lightweight module (not `runner`) so
// tests that mock `../git/runner` still resolve the real implementations.
import { extractExecError, parseRetryAfterMs } from '../git/exec-error'
// Why: legacy generic execFile wrapper - only used by callers that don't need
// WSL-aware routing. Repo-scoped callers should use the runner exports below.
export const execFileAsync = promisify(execFile)
export { ghExecFileAsync, gitExecFileAsync, extractExecError }
export { ghExecFileAsync, gitExecFileAsync, extractExecError, parseRetryAfterMs }
export { classifyGhError, classifyListIssuesError } from './gh-error-classification'
export {
_getOwnerRepoCacheSize,
+148 -15
View File
@@ -83,7 +83,30 @@ const queue = new Map<string, QueueEntry>()
const backgroundStarts: number[] = []
const activeStartsByScope = new Map<string, number[]>()
const errorBackoff = new Map<string, { failures: number; retryAt: number }>()
// Per-key manual-retry cooldown from a real secondary rate limit (Retry-After).
// refreshPRNow refuses a manual retry until this time so a stale renderer cannot
// bypass the gate the client advertised via `retryDisabledUntil`.
const manualRetryGates = new Map<string, number>()
let lastBackgroundStartAt = 0
/**
* Track (or clear) the manual-retry cooldown for a key from a broadcast outcome.
* Only a rate-limit outcome carrying `retryDisabledUntil` sets a gate; any other
* settled outcome clears it.
*/
function noteManualRetryGate(key: string, outcome: PRRefreshOutcome): void {
if (outcome.kind === 'upstream-error' && outcome.retryDisabledUntil !== undefined) {
manualRetryGates.set(key, outcome.retryDisabledUntil)
} else {
manualRetryGates.delete(key)
}
}
/** Reset all per-key retry state (backoff + manual cooldown) when a key resets. */
function resetKeyRetryState(key: string): void {
errorBackoff.delete(key)
manualRetryGates.delete(key)
}
const visibleByWindow = new Map<number, { generation: number; keys: Set<string> }>()
let outcomeObserver: PRRefreshOutcomeObserver | null = null
const diagnosticsCounters = {
@@ -101,7 +124,7 @@ function removeInvisibleVisibleRefreshes(): void {
for (const [key, entry] of queue) {
if (entry.reason === 'visible' && !isVisibleKey(key)) {
queue.delete(key)
errorBackoff.delete(key)
resetKeyRetryState(key)
broadcast({
aliases: Array.from(entry.aliases.values()),
reason: 'visible',
@@ -177,7 +200,7 @@ export function pruneWorktreePRRefreshAliases(worktreeId: string): void {
// No aliases left means no worktree still cares about this refresh.
if (entry.aliases.size === 0) {
queue.delete(key)
errorBackoff.delete(key)
resetKeyRetryState(key)
continue
}
// Keep the entry alive but ensure its representative candidate is not a
@@ -385,7 +408,7 @@ function removeQueuedAliasForInvalidCandidate(key: string, alias: GitHubPRRefres
const replacementAlias = existing.aliases.values().next().value
if (!replacementAlias) {
queue.delete(key)
errorBackoff.delete(key)
resetKeyRetryState(key)
return
}
@@ -405,6 +428,44 @@ function removeQueuedAliasForInvalidCandidate(key: string, alias: GitHubPRRefres
}
}
/**
* Advances the visible-key error backoff and returns the earliest retry time.
* The renderer surfaces this as `nextAutoRetryAt`; only visible keys auto-retry,
* so callers must gate on `isVisibleKey` before computing a schedule.
*/
function nextVisibleErrorRetryAt(key: string): number {
const failures = (errorBackoff.get(key)?.failures ?? 0) + 1
const retryAt =
Date.now() + Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.min(failures - 1, 4))
errorBackoff.set(key, { failures, retryAt })
return retryAt
}
/**
* Stamps the auto-retry time onto an error outcome before broadcast so every
* alias receives identical timing.
*
* Why: this only sets `nextAutoRetryAt` (the "Orca will retry at {time}" hint).
* It must NOT set `retryDisabledUntil` — that field disables *manual* Retry and
* is reserved for a real rate-limit gate (the paused/breaker path in
* `refreshPRNow`, which maps `pausedUntil` into it). Deriving it from ordinary
* exponential backoff would disable a manual Retry that `refreshPRNow` would in
* fact accept.
*/
function withErrorSchedule(outcome: PRRefreshOutcome, retryAt: number): PRRefreshOutcome {
if (outcome.kind !== 'upstream-error') {
return outcome
}
// Why: preserve a real Retry-After cooldown the client already stamped on the
// outcome (`retryDisabledUntil`); auto-retry no earlier than both the backoff
// and that cooldown so we do not retry into an active secondary rate limit.
const cooldownUntil = outcome.retryDisabledUntil
return {
...outcome,
nextAutoRetryAt: cooldownUntil !== undefined ? Math.max(retryAt, cooldownUntil) : retryAt
}
}
function scheduleVisibleFollowUp(
key: string,
candidate: GitHubPRRefreshCandidate,
@@ -412,19 +473,18 @@ function scheduleVisibleFollowUp(
priority: number,
aliases: GitHubPRRefreshAlias[],
windowId?: number,
options?: { pendingMergeabilityDelayMs?: number }
options?: { pendingMergeabilityDelayMs?: number; plannedRetryAt?: number }
): void {
if (!isVisibleKey(key)) {
// Why: manual/active refreshes can remove the queued visible retry after
// its owner window is gone, leaving the retry backoff without an owner.
errorBackoff.delete(key)
resetKeyRetryState(key)
return
}
if (outcome.kind === 'upstream-error') {
const failures = (errorBackoff.get(key)?.failures ?? 0) + 1
const retryAt =
Date.now() + Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.min(failures - 1, 4))
errorBackoff.set(key, { failures, retryAt })
// Why: reuse the retry time already computed for the broadcast schedule so
// the same failure is not counted twice against the backoff.
const retryAt = options?.plannedRetryAt ?? nextVisibleErrorRetryAt(key)
setVisibleFollowUp({
key,
candidate,
@@ -440,7 +500,7 @@ function scheduleVisibleFollowUp(
scheduleDrain(retryAt - Date.now())
return
}
errorBackoff.delete(key)
resetKeyRetryState(key)
const followUpCandidate = visibleCandidateAfterOutcome(candidate, outcome)
const regularDueAt = freshRetryAt(followUpCandidate) ?? Date.now()
const pendingMergeabilityDueAt =
@@ -693,7 +753,7 @@ async function drainQueue(): Promise<void> {
continue
}
if (next.reason === 'visible' && !isVisibleKey(next.key)) {
errorBackoff.delete(next.key)
resetKeyRetryState(next.key)
broadcast({ aliases, reason: next.reason, status: 'skipped', skippedReason: 'fresh' })
continue
}
@@ -748,15 +808,30 @@ async function drainQueue(): Promise<void> {
next.candidate.linkedPRNumber == null ? (next.candidate.fallbackPRNumber ?? null) : null,
...hostedReviewOptionArgs(next.candidate)
)
// Why: compute the retry schedule before broadcasting so the outcome and
// its follow-up retry share one timing; only visible keys auto-retry.
let plannedRetryAt: number | undefined
let broadcastOutcome = outcome
if (outcome.kind === 'upstream-error' && isVisibleKey(next.key)) {
plannedRetryAt = nextVisibleErrorRetryAt(next.key)
broadcastOutcome = withErrorSchedule(outcome, plannedRetryAt)
}
outcomeObserver?.(next.candidate, outcome)
broadcast({ aliases, reason: next.reason, outcome, requestStartedAt }, requestSequence)
noteManualRetryGate(next.key, broadcastOutcome)
broadcast(
{ aliases, reason: next.reason, outcome: broadcastOutcome, requestStartedAt },
requestSequence
)
scheduleVisibleFollowUp(
next.key,
next.candidate,
outcome,
next.priority,
aliases,
next.windowId
next.windowId,
{
plannedRetryAt
}
)
}
} finally {
@@ -893,6 +968,53 @@ export async function refreshPRNow(candidate: GitHubPRRefreshCandidate): Promise
return outcome
}
// Why: enforce the same rate-limit gate main advertises via `retryDisabledUntil`
// so a stale renderer cannot bypass it. A blocked primary bucket means gh would
// 403 anyway; a recorded secondary Retry-After cooldown means gh would 429
// again. Refuse without spending quota until the later of the two and report
// the pause honestly.
const manualBlockedGuard = backgroundRefreshBuckets()
.map((bucket) => rateLimitGuard(bucket))
.find((guard) => guard.blocked)
const secondaryGateUntil = manualRetryGates.get(key)
const gateUntil = Math.max(
manualBlockedGuard?.blocked ? manualBlockedGuard.resetAt * 1000 : 0,
secondaryGateUntil !== undefined ? secondaryGateUntil : 0
)
if (gateUntil > Date.now()) {
const retryAt = gateUntil
// Why: the paused broadcast maps `pausedUntil` into the renderer's
// `nextAutoRetryAt` ("Orca will retry at {time}"), so that auto-retry must be
// real. Requeue this candidate at the reset time and wake the drain then —
// mirroring the background paused path — instead of advertising an automatic
// retry that was never scheduled (finding 12).
queue.set(key, {
key,
candidate,
aliases: aliasMap,
reason: 'manual',
priority: 40,
dueAt: retryAt,
queuedAt: nextQueueOrder()
})
broadcast({
aliases,
reason: 'manual',
status: 'paused',
pausedUntil: retryAt,
skippedReason: 'rate-limit'
})
scheduleDrain(Math.max(1_000, retryAt - Date.now()))
return {
kind: 'upstream-error',
errorType: 'rate_limited',
message: 'GitHub is temporarily limiting requests. Try again after the limit resets.',
fetchedAt: Date.now(),
nextAutoRetryAt: retryAt,
retryDisabledUntil: retryAt
}
}
queue.delete(key)
const requestSequence = nextSequence()
const requestStartedAt = Date.now()
@@ -905,12 +1027,23 @@ export async function refreshPRNow(candidate: GitHubPRRefreshCandidate): Promise
candidate.linkedPRNumber == null ? (candidate.fallbackPRNumber ?? null) : null,
...hostedReviewOptionArgs(candidate)
)
let plannedRetryAt: number | undefined
let broadcastOutcome = outcome
if (outcome.kind === 'upstream-error' && isVisibleKey(key)) {
plannedRetryAt = nextVisibleErrorRetryAt(key)
broadcastOutcome = withErrorSchedule(outcome, plannedRetryAt)
}
outcomeObserver?.(candidate, outcome)
broadcast({ aliases, reason: 'manual', outcome, requestStartedAt }, requestSequence)
noteManualRetryGate(key, broadcastOutcome)
broadcast(
{ aliases, reason: 'manual', outcome: broadcastOutcome, requestStartedAt },
requestSequence
)
scheduleVisibleFollowUp(key, candidate, outcome, 40, aliases, undefined, {
plannedRetryAt,
// Why: GitHub often reports UNKNOWN immediately after `gh pr reopen`;
// do one prompt visible retry so conflicts replace the transient label.
pendingMergeabilityDelayMs: MANUAL_MERGEABILITY_PENDING_REFRESH_MS
})
return outcome
return broadcastOutcome
}
@@ -0,0 +1,144 @@
import { describe, expect, it } from 'vitest'
import {
classifyPRRefreshError,
safePRRefreshErrorMessage
} from './pr-refresh-error-classification'
describe('classifyPRRefreshError', () => {
it('classifies an HTTP 429 as rate_limited even without a rate-limit body', () => {
expect(classifyPRRefreshError(new Error('HTTP 429 Too Many Requests'))).toBe('rate_limited')
})
it('classifies secondary rate limit markers as rate_limited, not permission', () => {
for (const message of [
'You have exceeded a secondary rate limit',
'abuse detection mechanism triggered',
'abuse-rate-limits',
'you have triggered an abuse detection mechanism'
]) {
expect(classifyPRRefreshError(new Error(message))).toBe('rate_limited')
}
})
it('classifies a 403 carrying Retry-After as rate_limited, not permission', () => {
expect(classifyPRRefreshError(new Error('HTTP 403 Forbidden; Retry-After: 60'))).toBe(
'rate_limited'
)
})
it('classifies the primary breaker language as rate_limited', () => {
expect(classifyPRRefreshError(new Error('API rate limit exceeded for user'))).toBe(
'rate_limited'
)
})
it('classifies a plain 403 resource denial as permission', () => {
expect(
classifyPRRefreshError(new Error('HTTP 403: Resource not accessible by integration'))
).toBe('permission')
})
it('classifies network failures', () => {
for (const message of ['ETIMEDOUT', 'could not resolve host github.com', 'network is down']) {
expect(classifyPRRefreshError(new Error(message))).toBe('network')
}
})
it('classifies 404 / could not resolve repository as repo_unavailable', () => {
expect(classifyPRRefreshError(new Error('HTTP 404 Not Found'))).toBe('repo_unavailable')
expect(
classifyPRRefreshError(new Error('Could not resolve to a Repository with the name'))
).toBe('repo_unavailable')
})
it('classifies an ENOENT spawn failure as gh_unavailable', () => {
const err = Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT' })
expect(classifyPRRefreshError(err)).toBe('gh_unavailable')
expect(classifyPRRefreshError(new Error("'gh' is not recognized as an internal command"))).toBe(
'gh_unavailable'
)
})
it('classifies auth failures after rate-limit and permission checks', () => {
expect(classifyPRRefreshError(new Error('authentication failed: bad credentials'))).toBe('auth')
})
it('falls back to unknown', () => {
expect(classifyPRRefreshError(new Error('something unexpected happened'))).toBe('unknown')
})
it('does not classify a message that merely contains "author" as auth', () => {
for (const message of [
'PR author octocat has no write access to the fork',
'authored 3 commits, none pushed',
'unexpected failure from author service'
]) {
expect(classifyPRRefreshError(new Error(message))).toBe('unknown')
}
})
it('does not classify a repository name containing "network" as a network failure', () => {
// A repo/branch called "network-*" is not a connectivity failure; without a
// structured code or a real connectivity phrase this must stay unknown.
expect(classifyPRRefreshError(new Error('operation failed for repo acme/network-tools'))).toBe(
'unknown'
)
})
it('classifies a 404 repository error even when the message mentions network', () => {
// 404 ranks before the network branch so the repo error is not misread.
expect(
classifyPRRefreshError(
new Error('Could not resolve to a Repository named acme/network-proxy (HTTP 404)')
)
).toBe('repo_unavailable')
})
it('classifies a 401 as auth', () => {
expect(classifyPRRefreshError(new Error('HTTP 401 Unauthorized'))).toBe('auth')
})
it('classifies from the real runner error shape where the signal is on .stderr', () => {
// Why: the runner rejects with a generic message and puts the gh diagnostic
// on `.stderr` (string or Buffer). Reading `.message` alone would misclassify
// these hard errors as `unknown` and treat them as transient.
const permission = Object.assign(new Error('gh exited with 1.'), {
stderr: 'HTTP 403: Resource not accessible by integration'
})
expect(classifyPRRefreshError(permission)).toBe('permission')
const repo = Object.assign(new Error('gh exited with 1.'), {
stderr: Buffer.from('HTTP 404: Not Found')
})
expect(classifyPRRefreshError(repo)).toBe('repo_unavailable')
const secondary = Object.assign(new Error('gh exited with 1.'), {
stderr: 'You have exceeded a secondary rate limit'
})
expect(classifyPRRefreshError(secondary)).toBe('rate_limited')
const auth = Object.assign(new Error('gh exited with 1.'), {
stdout: '',
stderr: 'gh auth login required: bad credentials'
})
expect(classifyPRRefreshError(auth)).toBe('auth')
})
})
describe('safePRRefreshErrorMessage', () => {
it('returns non-empty copy for every classified type without leaking raw errors', () => {
for (const type of [
'rate_limited',
'auth',
'network',
'permission',
'repo_unavailable',
'gh_unavailable',
'unknown'
] as const) {
const message = safePRRefreshErrorMessage(type)
expect(message.length).toBeGreaterThan(0)
expect(message).not.toContain('ENOENT')
}
})
})
@@ -0,0 +1,144 @@
import type { PRRefreshErrorType } from '../../shared/types'
import { classifyGitHubUnavailable } from '../../shared/github-api-availability'
import { extractExecError } from '../git/exec-error'
/**
* Sanitization boundary for GitHub PR-refresh failures. Maps a raw runner/CLI
* error to a stable {@link PRRefreshErrorType}; the renderer turns that into
* classified copy so raw stderr / env values never reach the UI.
*
* Classification order (see docs/reference/pr-panel-refresh-guidance.md):
* HTTP 429 / secondary rate limit → primary rate limit → repo_unavailable (404) →
* network → permission (403) → gh_unavailable → auth → unknown. GitHub returns
* 403 OR 429 for both primary and secondary limits, so the http-403 permission
* branch must run only after the rate-limit checks. 404 is matched before the
* network branch so a repository error whose message happens to contain a
* substring like "network" is not misread as a connectivity failure. Auth and
* network detection avoid broad substrings (e.g. "auth" inside "author", or a
* repo name containing "network") in favor of structured codes and full phrases.
*/
export function classifyPRRefreshError(err: unknown): PRRefreshErrorType {
// Why: the git/gh runner keeps diagnostics on `.stderr`/`.stdout` separate
// from `.message` (which can be just "gh exited with 1."). Reading message
// alone would misclassify a real "HTTP 403" / "HTTP 404" as `unknown`, so a
// hard error would be treated as transient. Combine all three for substring
// detection while still preferring the structured spawn `code`.
const { stderr, stdout } = extractExecError(err)
const message = err instanceof Error ? err.message : String(err)
const lower = `${message}\n${stderr}\n${stdout}`.toLowerCase()
const code =
err && typeof err === 'object' && 'code' in err
? String((err as { code?: unknown }).code ?? '').toLowerCase()
: ''
// Rate limits first: a 429 is always a rate-limit signal; secondary limits also
// arrive as abuse-mechanism phrasing or a 403/429 carrying Retry-After, none of
// which contain "rate limit".
const isHttp429 = lower.includes('http 429') || lower.includes('429 too many requests')
const isHttp403 = lower.includes('http 403')
const hasRetryAfter = lower.includes('retry-after')
if (
isHttp429 ||
lower.includes('secondary rate limit') ||
lower.includes('abuse detection') ||
lower.includes('abuse-rate-limits') ||
lower.includes('you have triggered an abuse') ||
((isHttp403 || isHttp429) && hasRetryAfter) ||
lower.includes('api rate limit exceeded') ||
lower.includes('rate limit')
) {
return 'rate_limited'
}
// Repository resolution failures (404) rank before the network branch: a "could
// not resolve to a Repository" message must not be captured by a connectivity
// heuristic, and matching 404 first isolates it from any incidental substring.
if (lower.includes('http 404') || lower.includes('could not resolve to a repository')) {
return 'repo_unavailable'
}
// Why: keep GitHub 5xx/network attribution aligned with other GitHub surfaces.
const unavailable = classifyGitHubUnavailable(lower)
if (unavailable) {
return unavailable
}
// Network: structured error codes and full connectivity phrases only. Never a
// bare "network" substring — a repo/branch/message containing "network" is not
// evidence of a connectivity failure.
const networkCodes = new Set([
'etimedout',
'econnreset',
'econnrefused',
'enotfound',
'eai_again',
'enetunreach',
'enetdown'
])
if (
networkCodes.has(code) ||
lower.includes('etimedout') ||
lower.includes('econnreset') ||
lower.includes('econnrefused') ||
lower.includes('enotfound') ||
lower.includes('eai_again') ||
lower.includes('timed out') ||
lower.includes('timeout') ||
lower.includes('could not resolve host') ||
lower.includes('no such host') ||
lower.includes('network is unreachable') ||
lower.includes('network is down') ||
lower.includes('network error') ||
lower.includes('connection refused') ||
lower.includes('connection reset')
) {
return 'network'
}
if (isHttp403 || lower.includes('resource not accessible')) {
return 'permission'
}
// gh CLI launch failure: prefer the structured spawn error code over a broad
// substring so a repo path merely containing "gh" is not misclassified.
if (
code === 'enoent' ||
lower.includes('spawn gh enoent') ||
lower.includes('gh: command not found') ||
lower.includes("'gh' is not recognized")
) {
return 'gh_unavailable'
}
// Auth last: match full auth phrases and a 401, never a bare "auth" substring
// that also fires on "author"/"authored". "unauthorized"/"authorization" are
// long enough not to collide with "author".
if (
lower.includes('http 401') ||
lower.includes('unauthorized') ||
lower.includes('authorization') ||
lower.includes('authentication') ||
lower.includes('bad credentials') ||
lower.includes('gh auth') ||
/\b(login|credentials?)\b/i.test(lower)
) {
return 'auth'
}
return 'unknown'
}
/** Stable, non-destructive fallback message for a classified refresh error. */
export function safePRRefreshErrorMessage(errorType: PRRefreshErrorType): string {
switch (errorType) {
case 'rate_limited':
return 'GitHub rate limit is low. Try again after the limit resets.'
case 'auth':
return 'GitHub authentication is unavailable. Check your gh login.'
case 'network':
return 'GitHub is unreachable right now. Check your network and try again.'
case 'server_error':
return "GitHub's API is temporarily unavailable (server error). This is a GitHub-side issue."
case 'permission':
return 'GitHub did not allow access to this pull request.'
case 'repo_unavailable':
return 'The GitHub repository is unavailable or cannot be resolved.'
case 'gh_unavailable':
return 'GitHub CLI is unavailable.'
case 'unknown':
return 'GitHub pull request refresh failed.'
}
}