From d67ede15947e59127e061c603ecb2c09651a6ea3 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 19 Jul 2026 16:32:36 -0700 Subject: [PATCH] Implement confirm-only PR panel composer with classified error blocking (#9428) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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". --- ...hosted-review-create-intent-runner.test.ts | 2 + .../mobile-hosted-review-service.ts | 25 +- .../source-control/mobile-pr-create.test.ts | 146 +++++- mobile/src/source-control/mobile-pr-create.ts | 10 +- .../azure-devops/azure-devops-api-request.ts | 19 +- src/main/azure-devops/client.test.ts | 32 ++ src/main/azure-devops/client.ts | 32 +- src/main/bitbucket/client.test.ts | 19 +- src/main/bitbucket/client.ts | 50 +- src/main/git/exec-error.ts | 111 ++++ src/main/git/runner.ts | 108 +--- src/main/gitea/client.test.ts | 14 + src/main/gitea/client.ts | 67 ++- src/main/github/client.test.ts | 28 + src/main/github/client.ts | 67 +-- src/main/github/gh-utils.ts | 7 +- src/main/github/pr-refresh-coordinator.ts | 163 +++++- .../pr-refresh-error-classification.test.ts | 144 +++++ .../github/pr-refresh-error-classification.ts | 144 +++++ src/main/gitlab/client-mr.test.ts | 14 + src/main/gitlab/client.ts | 26 +- src/main/runtime/orca-runtime.test.ts | 18 +- src/main/runtime/orca-runtime.ts | 12 +- .../runtime/rpc/methods/hosted-review.test.ts | 1 + src/main/source-control/forge-provider.ts | 25 +- ...hosted-review-creation-eligibility.test.ts | 92 +++- .../source-control/hosted-review-creation.ts | 53 +- src/main/source-control/hosted-review.test.ts | 12 + .../components/right-sidebar/ChecksPanel.tsx | 437 +++++++++++++++- .../right-sidebar/CommitArea.test.tsx | 6 +- .../right-sidebar/SourceControl.tsx | 6 +- ...ecks-panel-ambiguous-github-review.test.ts | 44 -- .../checks-panel-ambiguous-github-review.ts | 22 - .../checks-panel-blocker-copy.ts | 220 ++++++++ .../checks-panel-empty-state.test.ts | 495 ++++++++---------- .../right-sidebar/checks-panel-empty-state.ts | 335 +++++++----- .../checks-panel-git-status-snapshot.ts | 5 + .../right-sidebar/checks-panel-review-copy.ts | 288 ++++++++++ .../checks-panel-review-creation.test.ts | 397 +++++++++++--- .../checks-panel-review-creation.ts | 168 +++++- ...ecks-panel-review-lookup-authority.test.ts | 130 +++++ .../checks-panel-review-lookup-authority.ts | 120 +++++ .../checks-panel-review-state-model.ts | 165 ++++++ ...urce-control-create-pr-intent-flow.test.ts | 18 +- ...ntrol-create-review-blocked-action.test.ts | 1 + .../source-control-dropdown-items.test.ts | 21 +- ...view-creation-eligibility-snapshot.test.ts | 13 +- ...ed-review-creation-eligibility-snapshot.ts | 12 +- ...ol-primary-action.create-pr-intent.test.ts | 60 ++- .../source-control-primary-action.test.ts | 15 +- .../useCreatePullRequestDialogFields.test.ts | 1 + .../useCreatePullRequestDialogFields.ts | 25 +- src/renderer/src/i18n/locales/en.json | 141 ++++- src/renderer/src/i18n/locales/es.json | 141 ++++- src/renderer/src/i18n/locales/ja.json | 141 ++++- src/renderer/src/i18n/locales/ko.json | 141 ++++- src/renderer/src/i18n/locales/zh.json | 141 ++++- src/renderer/src/store/slices/github.ts | 73 ++- src/shared/hosted-review.ts | 9 + .../source-control-create-review-intent.ts | 5 + ...ce-control-primary-action-decision.test.ts | 6 +- src/shared/types.ts | 21 +- 62 files changed, 4359 insertions(+), 905 deletions(-) create mode 100644 src/main/git/exec-error.ts create mode 100644 src/main/github/pr-refresh-error-classification.test.ts create mode 100644 src/main/github/pr-refresh-error-classification.ts delete mode 100644 src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.test.ts delete mode 100644 src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel-blocker-copy.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel-review-copy.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel-review-lookup-authority.test.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel-review-lookup-authority.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel-review-state-model.ts diff --git a/mobile/src/source-control/mobile-hosted-review-create-intent-runner.test.ts b/mobile/src/source-control/mobile-hosted-review-create-intent-runner.test.ts index c96edaded..b64bb8887 100644 --- a/mobile/src/source-control/mobile-hosted-review-create-intent-runner.test.ts +++ b/mobile/src/source-control/mobile-hosted-review-create-intent-runner.test.ts @@ -35,6 +35,8 @@ function eligibility(overrides: Record) { defaultBaseRef: 'main', title: 'Ship mobile PR create', body: 'Generated body', + // Accepted no-review lookup so Create / Push & Create is allowed unless overridden. + reviewLookupOutcome: 'not_found', ...overrides } } diff --git a/mobile/src/source-control/mobile-hosted-review-service.ts b/mobile/src/source-control/mobile-hosted-review-service.ts index c219586ed..c040b7a2c 100644 --- a/mobile/src/source-control/mobile-hosted-review-service.ts +++ b/mobile/src/source-control/mobile-hosted-review-service.ts @@ -3,6 +3,7 @@ import type { HostedReviewCreationBlockedReason, HostedReviewCreationEligibility, HostedReviewCreationNextAction, + HostedReviewLookupOutcome, HostedReviewProvider } from '../../../src/shared/hosted-review' import type { RpcClient } from '../transport/rpc-client' @@ -62,6 +63,10 @@ export type MobileHostedReviewPrefill = { canCreate?: boolean blockedReason?: HostedReviewCreationBlockedReason nextAction?: HostedReviewCreationNextAction + // Why: mobile lacks the desktop refresh/review-lookup signals, so it fails + // closed on ambiguity. When the host could not prove the branch has no review + // (`unavailable`), create — including the Push & Create path — stays blocked. + reviewLookupOutcome?: HostedReviewLookupOutcome } // Resolve the mobile compose prefill from the same hosted-review eligibility @@ -97,7 +102,14 @@ export async function resolveMobileHostedReviewPrefill( behind: args.behind }) if (!eligibility) { - return { ...fallback, canCreate: false, blockedReason: null, nextAction: null } + // Eligibility itself could not be resolved: the review lookup is unproven. + return { + ...fallback, + canCreate: false, + blockedReason: null, + nextAction: null, + reviewLookupOutcome: 'unavailable' + } } return { provider: eligibility.provider, @@ -106,10 +118,17 @@ export async function resolveMobileHostedReviewPrefill( body: eligibility.body || '', canCreate: eligibility.canCreate, blockedReason: eligibility.blockedReason, - nextAction: eligibility.nextAction + nextAction: eligibility.nextAction, + reviewLookupOutcome: eligibility.reviewLookupOutcome } } catch { - return { ...fallback, canCreate: false, blockedReason: null, nextAction: null } + return { + ...fallback, + canCreate: false, + blockedReason: null, + nextAction: null, + reviewLookupOutcome: 'unavailable' + } } } diff --git a/mobile/src/source-control/mobile-pr-create.test.ts b/mobile/src/source-control/mobile-pr-create.test.ts index 28f2e4b69..deb36b9e9 100644 --- a/mobile/src/source-control/mobile-pr-create.test.ts +++ b/mobile/src/source-control/mobile-pr-create.test.ts @@ -40,6 +40,7 @@ function eligibility( canCreate: true, blockedReason: null, nextAction: null, + reviewLookupOutcome: 'not_found', defaultBaseRef: 'main', title: 'Add feature', body: '', @@ -118,12 +119,115 @@ describe('mobile create form gating parity', () => { body: desktopEligibility.body ?? '', canCreate: desktopEligibility.canCreate, blockedReason: desktopEligibility.blockedReason, - nextAction: desktopEligibility.nextAction + nextAction: desktopEligibility.nextAction, + // Mobile receives the lookup outcome from eligibility; thread it so the + // gate reflects real prefills (current hosts always populate it). + reviewLookupOutcome: desktopEligibility.reviewLookupOutcome }) === null expect(mobileAllowsComposer).toBe(desktopAllowsComposer) }) + it('fails closed when the review-lookup outcome is missing (older host)', () => { + // A host that predates `reviewLookupOutcome` leaves review existence unproven. + // Mobile must not open Create / Push & Create on that ambiguity. + expect( + getMobilePrCreateBlockMessage({ + provider: 'github', + base: 'main', + title: 'Add feature', + body: '', + canCreate: true, + blockedReason: null + }) + ).toBe( + 'Orca could not confirm whether this branch already has a pull request. Try again in a moment.' + ) + expect( + getMobilePrCreateBlockMessage({ + provider: 'github', + base: 'main', + title: 'Add feature', + body: '', + canCreate: false, + blockedReason: 'needs_push' + }) + ).toBe( + 'Orca could not confirm whether this branch already has a pull request. Try again in a moment.' + ) + }) + + it('desktop gate hard-blocks on positive unresolved review evidence', () => { + // Mobile lacks review-lookup signals, so it fails closed on ambiguity: the + // shared desktop gate must return false even when eligibility looks ready. + expect( + shouldOpenChecksPanelCreateComposer({ + activeReview: null, + isFolder: false, + branch: 'feature/x', + hostedReviewCreation: eligibility({ canCreate: true }), + reviewLookup: 'positive_unresolved' + }) + ).toBe(false) + }) + + it('desktop gate hard-blocks during a hard refresh error', () => { + expect( + shouldOpenChecksPanelCreateComposer({ + activeReview: null, + isFolder: false, + branch: 'feature/x', + hostedReviewCreation: eligibility({ canCreate: true }), + hasHardRefreshError: true + }) + ).toBe(false) + }) + + it('fails closed on an unavailable review lookup even when eligibility looks ready', () => { + // The existing-review lookup could not prove there is no PR; mobile has no + // review-lookup signal of its own, so create must be blocked. + expect( + getMobilePrCreateBlockMessage({ + provider: 'github', + base: 'main', + title: 'Add feature', + body: '', + canCreate: true, + blockedReason: null, + reviewLookupOutcome: 'unavailable' + }) + ).toBe( + 'Orca could not confirm whether this branch already has a pull request. Try again in a moment.' + ) + }) + + it('fails closed on unavailable even on the needs_push Push & Create path', () => { + // needs_push would normally be allowed (Push & Create); an unavailable lookup + // must still block it — this is the fail-open gap the parity gate closes. + const mobileBlocked = + getMobilePrCreateBlockMessage({ + provider: 'github', + base: 'main', + title: 'Add feature', + body: '', + canCreate: false, + blockedReason: 'needs_push', + reviewLookupOutcome: 'unavailable' + }) !== null + const desktopAllowsComposer = shouldOpenChecksPanelCreateComposer({ + activeReview: null, + isFolder: false, + branch: 'feature/x', + hostedReviewCreation: eligibility({ + canCreate: false, + blockedReason: 'needs_push', + reviewLookupOutcome: 'unavailable' + }) + }) + expect(mobileBlocked).toBe(true) + expect(desktopAllowsComposer).toBe(false) + }) + it('stays safely blocked for a reason added by a newer desktop contract', () => { expect( getMobilePrCreateBlockMessage({ @@ -158,7 +262,8 @@ describe('resolveMobilePrPrefill', () => { nextAction: null, defaultBaseRef: 'develop', title: 'Add feature', - body: 'Body' + body: 'Body', + reviewLookupOutcome: 'not_found' }) ]) await expect(resolveMobilePrPrefill(client, 'repo-1::/tmp/wt', baseArgs)).resolves.toEqual({ @@ -168,7 +273,8 @@ describe('resolveMobilePrPrefill', () => { body: 'Body', canCreate: true, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' }) }) @@ -182,7 +288,8 @@ describe('resolveMobilePrPrefill', () => { nextAction: 'push', defaultBaseRef: 'main', title: 'Add feature', - body: '' + body: '', + reviewLookupOutcome: 'not_found' }) ]) const prefill = await resolveMobilePrPrefill(client, 'repo-1::/tmp/wt', baseArgs) @@ -198,7 +305,8 @@ describe('resolveMobilePrPrefill', () => { review: null, blockedReason: 'dirty', nextAction: 'commit', - defaultBaseRef: 'main' + defaultBaseRef: 'main', + reviewLookupOutcome: 'not_found' }) ]) const prefill = await resolveMobilePrPrefill(client, 'repo-1::/tmp/wt', baseArgs) @@ -209,15 +317,39 @@ describe('resolveMobilePrPrefill', () => { it('returns a blocked fallback when eligibility is unavailable', async () => { const client = clientWith([fail('nope')]) - await expect(resolveMobilePrPrefill(client, 'repo-1::/tmp/wt', baseArgs)).resolves.toEqual({ + const prefill = await resolveMobilePrPrefill(client, 'repo-1::/tmp/wt', baseArgs) + expect(prefill).toEqual({ provider: 'github', base: 'main', title: 'feature/x', body: '', canCreate: false, blockedReason: null, - nextAction: null + nextAction: null, + // Eligibility could not be resolved, so the review lookup is unproven. + reviewLookupOutcome: 'unavailable' }) + // A prefill Orca could not resolve must not offer create. + expect(getMobilePrCreateBlockMessage(prefill)).not.toBeNull() + }) + + it('threads reviewLookupOutcome from eligibility into the prefill and blocks needs_push', async () => { + const client = clientWith([ + ok({ + provider: 'github', + canCreate: false, + review: null, + blockedReason: 'needs_push', + nextAction: 'push', + defaultBaseRef: 'main', + title: 'Add feature', + body: '', + reviewLookupOutcome: 'unavailable' + }) + ]) + const prefill = await resolveMobilePrPrefill(client, 'repo-1::/tmp/wt', baseArgs) + expect(prefill.reviewLookupOutcome).toBe('unavailable') + expect(getMobilePrCreateBlockMessage(prefill)).not.toBeNull() }) it('blocks without calling the RPC when there is no branch', async () => { diff --git a/mobile/src/source-control/mobile-pr-create.ts b/mobile/src/source-control/mobile-pr-create.ts index b584b86e2..20f908d3d 100644 --- a/mobile/src/source-control/mobile-pr-create.ts +++ b/mobile/src/source-control/mobile-pr-create.ts @@ -43,10 +43,18 @@ export function getMobilePrCreateSuccessWarning( } export function getMobilePrCreateBlockMessage(prefill: MobilePrPrefill): string | null { + const copy = hostedReviewCopy(prefill.provider) if (prefill.canCreate !== false || shouldPushBeforeMobileHostedReviewCreate(prefill)) { + // Fail closed: only an accepted no-review lookup (`not_found`) may open + // Create / Push & Create. `unavailable`, `found`, or a missing outcome (an + // older host that predates the field) all leave review existence unproven — + // mobile has no refresh/review-lookup signal of its own, so it must not + // offer create, or the needs_push Push & Create path would slip through. + if (prefill.reviewLookupOutcome !== 'not_found') { + return `Orca could not confirm whether this branch already has a ${copy.reviewLabel}. Try again in a moment.` + } return null } - const copy = hostedReviewCopy(prefill.provider) switch (prefill.blockedReason) { case 'dirty': return `Commit changes before creating a ${copy.reviewLabel}.` diff --git a/src/main/azure-devops/azure-devops-api-request.ts b/src/main/azure-devops/azure-devops-api-request.ts index 089975cf5..5fc8f2567 100644 --- a/src/main/azure-devops/azure-devops-api-request.ts +++ b/src/main/azure-devops/azure-devops-api-request.ts @@ -73,7 +73,11 @@ function apiUrl( export async function requestAzureDevOpsJsonAtBase( baseUrl: string, path: string, - options: AzureDevOpsRequestOptions = {} + options: AzureDevOpsRequestOptions = {}, + // Why: the existing-review lookup behind Create must distinguish a real + // transport/auth failure from an accepted "no PR". When true, a failed request + // throws instead of collapsing to null so callers never report false not_found. + throwOnFailure = false ): Promise { const config = getAzureDevOpsAuthConfig() try { @@ -86,10 +90,16 @@ export async function requestAzureDevOpsJsonAtBase( }) if (!response.ok) { await cancelUnreadResponseBody(response) + if (throwOnFailure) { + throw new Error(`Azure DevOps request failed: HTTP ${response.status}`) + } return null } return (await response.json()) as T - } catch { + } catch (error) { + if (throwOnFailure) { + throw error + } return null } } @@ -97,7 +107,8 @@ export async function requestAzureDevOpsJsonAtBase( export function requestAzureDevOpsJson( repo: AzureDevOpsRepoRef, path: string, - options: AzureDevOpsRequestOptions = {} + options: AzureDevOpsRequestOptions = {}, + throwOnFailure = false ): Promise { - return requestAzureDevOpsJsonAtBase(configuredApiBaseUrl(repo), path, options) + return requestAzureDevOpsJsonAtBase(configuredApiBaseUrl(repo), path, options, throwOnFailure) } diff --git a/src/main/azure-devops/client.test.ts b/src/main/azure-devops/client.test.ts index d394962fc..8c993a9db 100644 --- a/src/main/azure-devops/client.test.ts +++ b/src/main/azure-devops/client.test.ts @@ -3,6 +3,7 @@ import { cancelTrackingResponse } from '../lib/unread-response-body.test-fixture import { getAzureDevOpsAuthStatus, getAzureDevOpsPullRequestForBranch, + getAzureDevOpsPullRequestForBranchOrThrow, normalizeAzureDevOpsApiBaseUrl } from './client' import { _resetAzureDevOpsRepoRefCache } from './repository-ref' @@ -122,6 +123,37 @@ describe('Azure DevOps client', () => { ]) }) + it('getAzureDevOpsPullRequestForBranchOrThrow surfaces a list failure instead of null (finding 4)', async () => { + gitExecFileAsyncMock.mockResolvedValue({ + stdout: 'https://dev.azure.com/acme/Project/_git/repo\n' + }) + globalThis.fetch = vi.fn(async (input: string | URL | Request) => { + const url = new URL(String(input)) + if (url.pathname === '/acme/Project/_apis/git/repositories/repo') { + return new Response( + JSON.stringify({ + id: 'repo-guid', + webUrl: 'https://dev.azure.com/acme/Project/_git/repo' + }), + { status: 200, headers: { 'Content-Type': 'application/json' } } + ) + } + // The pull-request list lookup fails (auth/transport). + return new Response(JSON.stringify({ message: 'forbidden' }), { status: 403 }) + }) as never + + // The swallowing variant collapses the failure into a false "no PR". + await expect( + getAzureDevOpsPullRequestForBranch('/repo', 'refs/heads/feature/azure') + ).resolves.toBeNull() + _resetAzureDevOpsRepoRefCache() + // The throwing variant makes the failure visible so eligibility records + // `unavailable` rather than a false "No pull request found". + await expect( + getAzureDevOpsPullRequestForBranchOrThrow('/repo', 'refs/heads/feature/azure') + ).rejects.toThrow(/Azure DevOps request failed/) + }) + it('uses the most recent branch PR instead of preferring stale active PRs', async () => { gitExecFileAsyncMock.mockResolvedValue({ stdout: 'https://dev.azure.com/acme/Project/_git/repo\n' diff --git a/src/main/azure-devops/client.ts b/src/main/azure-devops/client.ts index 2bed23c2c..25390ba4b 100644 --- a/src/main/azure-devops/client.ts +++ b/src/main/azure-devops/client.ts @@ -197,7 +197,8 @@ export async function getAzureDevOpsPullRequestForBranch( branch: string, linkedPRNumber?: number | null, connectionId?: string | null, - options: HostedReviewExecutionOptions = {} + options: HostedReviewExecutionOptions = {}, + throwOnFailure = false ): Promise { const branchName = branch.replace(/^refs\/heads\//, '') if (!branchName && linkedPRNumber == null) { @@ -224,7 +225,8 @@ export async function getAzureDevOpsPullRequestForBranch( 'searchCriteria.status': 'all', $top: 10 } - } + }, + throwOnFailure ) const raw = (list?.value ?? []).sort(sortPullRequestsForBranch)[0] if (raw) { @@ -239,11 +241,35 @@ export async function getAzureDevOpsPullRequestForBranch( repo, `/_apis/git/repositories/${encodePathSegment(repository.idOrName)}/pullRequests/${encodePathSegment( String(linkedPRNumber) - )}` + )}`, + {}, + throwOnFailure ) return raw ? normalizePullRequest(repo, repository.idOrName, repository.webBaseUrl, raw) : null } +/** + * Existing-review lookup that surfaces transport/auth failures instead of + * collapsing them to null, so a failed lookup becomes + * `reviewLookupOutcome: 'unavailable'` rather than a false "No pull request found". + */ +export function getAzureDevOpsPullRequestForBranchOrThrow( + repoPath: string, + branch: string, + linkedPRNumber?: number | null, + connectionId?: string | null, + options: HostedReviewExecutionOptions = {} +): Promise { + return getAzureDevOpsPullRequestForBranch( + repoPath, + branch, + linkedPRNumber, + connectionId, + options, + true + ) +} + export async function getAzureDevOpsRepoSlug( repoPath: string, connectionId?: string | null, diff --git a/src/main/bitbucket/client.test.ts b/src/main/bitbucket/client.test.ts index 4e552ab59..7ecfeb641 100644 --- a/src/main/bitbucket/client.test.ts +++ b/src/main/bitbucket/client.test.ts @@ -9,7 +9,11 @@ vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) -import { getBitbucketAuthStatus, getBitbucketPullRequestForBranch } from './client' +import { + getBitbucketAuthStatus, + getBitbucketPullRequestForBranch, + getBitbucketPullRequestForBranchOrThrow +} from './client' import { _resetBitbucketRepoRefCache } from './repository-ref' const OLD_ENV = process.env @@ -93,6 +97,19 @@ describe('Bitbucket client', () => { ) }) + it('getBitbucketPullRequestForBranchOrThrow surfaces a failure instead of null (finding 4)', async () => { + const fetchMock = vi.fn(async () => Response.json({ error: 'forbidden' }, { status: 403 })) + vi.stubGlobal('fetch', fetchMock) + + // The swallowing variant collapses a real failure into a false "no PR". + await expect(getBitbucketPullRequestForBranch('/repo', 'feature/bitbucket')).resolves.toBeNull() + // The throwing variant makes the failure visible so eligibility records + // `unavailable` rather than a false "No pull request found". + await expect( + getBitbucketPullRequestForBranchOrThrow('/repo', 'feature/bitbucket') + ).rejects.toThrow(/Bitbucket request failed/) + }) + it('falls back to a linked PR number when branch lookup misses', async () => { const fetchMock = vi.fn(async (url: string, _init?: RequestInit) => { if (url.includes('/statuses/build')) { diff --git a/src/main/bitbucket/client.ts b/src/main/bitbucket/client.ts index 6dbc11f65..ae4158fa1 100644 --- a/src/main/bitbucket/client.ts +++ b/src/main/bitbucket/client.ts @@ -87,7 +87,14 @@ function apiUrl(path: string, searchParams?: RequestOptions['searchParams']): st return url.toString() } -async function requestJson(path: string, options: RequestOptions = {}): Promise { +async function requestJson( + path: string, + options: RequestOptions = {}, + // Why: the existing-review lookup behind Create must distinguish a real + // transport/auth failure from an accepted "no PR". When true, a failed request + // throws instead of collapsing to null so callers never report false not_found. + throwOnFailure = false +): Promise { const config = getAuthConfig() try { const response = await fetch(apiUrl(path, options.searchParams), { @@ -99,10 +106,16 @@ async function requestJson(path: string, options: RequestOptions = {}): Promi }) if (!response.ok) { await cancelUnreadResponseBody(response) + if (throwOnFailure) { + throw new Error(`Bitbucket request failed: HTTP ${response.status}`) + } return null } return (await response.json()) as T - } catch { + } catch (error) { + if (throwOnFailure) { + throw error + } return null } } @@ -184,7 +197,8 @@ export async function getBitbucketPullRequestForBranch( branch: string, linkedPRNumber?: number | null, connectionId?: string | null, - options: HostedReviewExecutionOptions = {} + options: HostedReviewExecutionOptions = {}, + throwOnFailure = false ): Promise { const branchName = branch.replace(/^refs\/heads\//, '') if (!branchName && linkedPRNumber == null) { @@ -214,7 +228,8 @@ export async function getBitbucketPullRequestForBranch( q: query, state: ALL_PULL_REQUEST_STATES } - } + }, + throwOnFailure ) const raw = list?.values?.[0] if (raw) { @@ -226,11 +241,36 @@ export async function getBitbucketPullRequestForBranch( return null } const raw = await requestJson( - `/repositories/${encodedRepoPath(repo)}/pullrequests/${encodeURIComponent(String(linkedPRNumber))}` + `/repositories/${encodedRepoPath(repo)}/pullrequests/${encodeURIComponent(String(linkedPRNumber))}`, + {}, + throwOnFailure ) return raw ? normalizePullRequest(repo, raw) : null } +/** + * Existing-review lookup that surfaces transport/auth failures instead of + * collapsing them to null. The hosted-review creation preflight uses this so a + * failed lookup becomes `reviewLookupOutcome: 'unavailable'`, never a false + * "No pull request found". + */ +export function getBitbucketPullRequestForBranchOrThrow( + repoPath: string, + branch: string, + linkedPRNumber?: number | null, + connectionId?: string | null, + options: HostedReviewExecutionOptions = {} +): Promise { + return getBitbucketPullRequestForBranch( + repoPath, + branch, + linkedPRNumber, + connectionId, + options, + true + ) +} + export async function getBitbucketRepoSlug( repoPath: string, connectionId?: string | null, diff --git a/src/main/git/exec-error.ts b/src/main/git/exec-error.ts new file mode 100644 index 000000000..fb44e5491 --- /dev/null +++ b/src/main/git/exec-error.ts @@ -0,0 +1,111 @@ +/** + * Pure helpers for reading diagnostics out of a subprocess (git/gh/glab) + * rejection. Kept in a standalone module (not `runner.ts`) so lightweight + * consumers — e.g. PR-refresh error classification — can import them without + * pulling in the runner's heavy execution machinery, and so tests that mock + * `./runner` still get the real implementations. + */ + +/** + * Extract stderr/stdout from an execFile rejection. + * + * Why: Node's execFile rejects with an Error that has `.stdout` and `.stderr` + * fields populated separately from `.message`. Reading `err.message` alone is + * unreliable — it can truncate stderr or omit it entirely depending on Node + * version and maxBuffer behavior. We prefer the explicit fields and fall + * back to `.message` only when neither is present. + */ +export function extractExecError(err: unknown): { stderr: string; stdout: string } { + if (err && typeof err === 'object') { + const e = err as { stderr?: unknown; stdout?: unknown; message?: unknown } + const stderr = + typeof e.stderr === 'string' + ? e.stderr + : Buffer.isBuffer(e.stderr) + ? e.stderr.toString('utf-8') + : '' + const stdout = + typeof e.stdout === 'string' + ? e.stdout + : Buffer.isBuffer(e.stdout) + ? e.stdout.toString('utf-8') + : '' + if (stderr || stdout) { + return { stderr, stdout } + } + if (typeof e.message === 'string') { + return { stderr: e.message, stdout: '' } + } + } + return { stderr: String(err), stdout: '' } +} + +/** + * Detect a Retry-After hint in gh stderr and return the suggested delay in ms, + * or null when the response includes no Retry-After. + * + * Why: gh forwards response headers when verbose, and prints "Retry-After: + * " in error output for primary rate-limit 429s. When present, the + * caller is better served by propagating the error so the UI can surface the + * real wait time — retrying on our own 250ms cadence just earns another 429 + * and burns the retry budget. Also supports HTTP-date Retry-After values. + */ +export function parseRetryAfterMs(stderr: string): number | null { + const raw = findRetryAfterHeaderValue(stderr) + if (raw === null) { + return null + } + if (/^\d+$/.test(raw)) { + const seconds = Number(raw) + return Number.isFinite(seconds) ? seconds * 1000 : null + } + const ts = Date.parse(raw) + if (Number.isNaN(ts)) { + return null + } + return Math.max(0, ts - Date.now()) +} + +function findRetryAfterHeaderValue(stderr: string): string | null { + const headerIndex = indexOfAsciiIgnoreCase(stderr, 'retry-after:', 0) + if (headerIndex === -1) { + return null + } + let valueStart = headerIndex + 'retry-after:'.length + while (valueStart < stderr.length) { + const code = stderr.charCodeAt(valueStart) + if (code !== 9 && code !== 32) { + break + } + valueStart++ + } + let valueEnd = valueStart + while (valueEnd < stderr.length) { + const code = stderr.charCodeAt(valueEnd) + if (code === 10 || code === 13) { + break + } + valueEnd++ + } + const value = stderr.slice(valueStart, valueEnd).trim() + return value.length > 0 ? value : null +} + +function indexOfAsciiIgnoreCase(value: string, search: string, fromIndex: number): number { + const lastStart = value.length - search.length + for (let index = Math.max(0, fromIndex); index <= lastStart; index++) { + let matches = true + for (let offset = 0; offset < search.length; offset++) { + const code = value.charCodeAt(index + offset) + const normalizedCode = code >= 65 && code <= 90 ? code + 32 : code + if (normalizedCode !== search.charCodeAt(offset)) { + matches = false + break + } + } + if (matches) { + return index + } + } + return -1 +} diff --git a/src/main/git/runner.ts b/src/main/git/runner.ts index 27d1e5837..8c70421e3 100644 --- a/src/main/git/runner.ts +++ b/src/main/git/runner.ts @@ -42,6 +42,10 @@ import { } from '../../shared/wsl-login-shell-command' import { UNTRANSLATED_GIT_OUTPUT_ENV } from '../../shared/git-output-locale' import { endSubprocessStdin } from '../../shared/subprocess-stdin-write' +// Re-exported for existing importers; lightweight consumers should import these +// from './exec-error' directly so they do not depend on this heavy module. +import { extractExecError, parseRetryAfterMs } from './exec-error' +export { extractExecError, parseRetryAfterMs } // ─── Core resolution ──────────────────────────────────────────────── @@ -1233,110 +1237,6 @@ function argsLookIdempotent(args: string[]): boolean { return true } -/** - * Extract stderr from an execFile rejection. - * - * Why: Node's execFile rejects with an Error that has `.stdout` and `.stderr` - * fields populated separately from `.message`. Reading `err.message` alone is - * unreliable — it can truncate stderr or omit it entirely depending on Node - * version and maxBuffer behavior. We prefer the explicit fields and fall - * back to `.message` only when neither is present. - */ -export function extractExecError(err: unknown): { stderr: string; stdout: string } { - if (err && typeof err === 'object') { - const e = err as { stderr?: unknown; stdout?: unknown; message?: unknown } - const stderr = - typeof e.stderr === 'string' - ? e.stderr - : Buffer.isBuffer(e.stderr) - ? e.stderr.toString('utf-8') - : '' - const stdout = - typeof e.stdout === 'string' - ? e.stdout - : Buffer.isBuffer(e.stdout) - ? e.stdout.toString('utf-8') - : '' - if (stderr || stdout) { - return { stderr, stdout } - } - if (typeof e.message === 'string') { - return { stderr: e.message, stdout: '' } - } - } - return { stderr: String(err), stdout: '' } -} - -/** - * Detect a Retry-After hint in gh stderr and return the suggested delay in ms, - * or null when the response includes no Retry-After. - * - * Why: gh forwards response headers when verbose, and prints "Retry-After: - * " in error output for primary rate-limit 429s. When present, the - * caller is better served by propagating the error so the UI can surface the - * real wait time — retrying on our own 250ms cadence just earns another 429 - * and burns the retry budget. Also supports HTTP-date Retry-After values. - */ -export function parseRetryAfterMs(stderr: string): number | null { - const raw = findRetryAfterHeaderValue(stderr) - if (raw === null) { - return null - } - if (/^\d+$/.test(raw)) { - const seconds = Number(raw) - return Number.isFinite(seconds) ? seconds * 1000 : null - } - const ts = Date.parse(raw) - if (Number.isNaN(ts)) { - return null - } - return Math.max(0, ts - Date.now()) -} - -function findRetryAfterHeaderValue(stderr: string): string | null { - const headerIndex = indexOfAsciiIgnoreCase(stderr, 'retry-after:', 0) - if (headerIndex === -1) { - return null - } - let valueStart = headerIndex + 'retry-after:'.length - while (valueStart < stderr.length) { - const code = stderr.charCodeAt(valueStart) - if (code !== 9 && code !== 32) { - break - } - valueStart++ - } - let valueEnd = valueStart - while (valueEnd < stderr.length) { - const code = stderr.charCodeAt(valueEnd) - if (code === 10 || code === 13) { - break - } - valueEnd++ - } - const value = stderr.slice(valueStart, valueEnd).trim() - return value.length > 0 ? value : null -} - -function indexOfAsciiIgnoreCase(value: string, search: string, fromIndex: number): number { - const lastStart = value.length - search.length - for (let index = Math.max(0, fromIndex); index <= lastStart; index++) { - let matches = true - for (let offset = 0; offset < search.length; offset++) { - const code = value.charCodeAt(index + offset) - const normalizedCode = code >= 65 && code <= 90 ? code + 32 : code - if (normalizedCode !== search.charCodeAt(offset)) { - matches = false - break - } - } - if (matches) { - return index - } - } - return -1 -} - /** * Classify whether a gh execFile rejection is worth retrying. * diff --git a/src/main/gitea/client.test.ts b/src/main/gitea/client.test.ts index a0ae0b3ce..60f344126 100644 --- a/src/main/gitea/client.test.ts +++ b/src/main/gitea/client.test.ts @@ -12,6 +12,7 @@ vi.mock('../git/runner', () => ({ import { getGiteaAuthStatus, getGiteaPullRequestForBranch, + getGiteaPullRequestForBranchOrThrow, normalizeGiteaApiBaseUrl } from './client' import { _resetGiteaRepoRefCache } from './repository-ref' @@ -172,6 +173,19 @@ describe('Gitea client', () => { } }) + it('surfaces a lookup failure via getGiteaPullRequestForBranchOrThrow instead of null (finding 4)', async () => { + const fetchMock = vi.fn(async () => Response.json({ message: 'unauthorized' }, { status: 403 })) + vi.stubGlobal('fetch', fetchMock) + + // The swallowing variant returns null — indistinguishable from "no PR". + await expect(getGiteaPullRequestForBranch('/repo', 'feature/gitea')).resolves.toBeNull() + // The throwing variant makes the failure visible so eligibility records + // `unavailable` rather than a false "No pull request found". + await expect(getGiteaPullRequestForBranchOrThrow('/repo', 'feature/gitea')).rejects.toThrow( + /Gitea request failed/ + ) + }) + it('expires successful scans and bounds retained repository listings', async () => { vi.useFakeTimers() try { diff --git a/src/main/gitea/client.ts b/src/main/gitea/client.ts index 9889598b6..da6c498d8 100644 --- a/src/main/gitea/client.ts +++ b/src/main/gitea/client.ts @@ -78,7 +78,11 @@ function apiUrl(baseUrl: string, path: string, searchParams?: RequestOptions['se async function requestJsonAtBase( baseUrl: string, path: string, - options: RequestOptions = {} + options: RequestOptions = {}, + // Why: the existing-review lookup behind Create must distinguish a real + // transport/auth failure from an accepted "no PR". When true, a failed request + // throws instead of collapsing to null so callers never report false not_found. + throwOnFailure = false ): Promise { const config = getAuthConfig() try { @@ -91,10 +95,16 @@ async function requestJsonAtBase( }) if (!response.ok) { await cancelUnreadResponseBody(response) + if (throwOnFailure) { + throw new Error(`Gitea request failed: HTTP ${response.status}`) + } return null } return (await response.json()) as T - } catch { + } catch (error) { + if (throwOnFailure) { + throw error + } return null } } @@ -102,9 +112,10 @@ async function requestJsonAtBase( function requestJson( repo: GiteaRepoRef, path: string, - options: RequestOptions = {} + options: RequestOptions = {}, + throwOnFailure = false ): Promise { - return requestJsonAtBase(configuredApiBaseUrl(repo), path, options) + return requestJsonAtBase(configuredApiBaseUrl(repo), path, options, throwOnFailure) } function encodedRepoPath(repo: GiteaRepoRef): string { @@ -227,7 +238,8 @@ export async function getGiteaPullRequestForBranch( branch: string, linkedPRNumber?: number | null, connectionId?: string | null, - options: HostedReviewExecutionOptions = {} + options: HostedReviewExecutionOptions = {}, + throwOnFailure = false ): Promise { const branchName = branch.replace(/^refs\/heads\//, '') if (!branchName && linkedPRNumber == null) { @@ -245,17 +257,25 @@ export async function getGiteaPullRequestForBranch( if (branchName) { const pullRequests = await scanGiteaPullRequests( - giteaPullRequestScanKey(repo), + // Why: throwing scans keep a separate cache namespace so they never reuse a + // prior swallowing scan's cached-empty from a failed page fetch, which would + // otherwise let a real lookup failure masquerade as "no PR". + throwOnFailure ? `${giteaPullRequestScanKey(repo)}::strict` : giteaPullRequestScanKey(repo), (page) => - requestJson(repo, `/repos/${encodedRepoPath(repo)}/pulls`, { - searchParams: { - state: 'all', - sort: 'recentupdate', - page, - limit: PULL_REQUEST_PAGE_LIMIT + requestJson( + repo, + `/repos/${encodedRepoPath(repo)}/pulls`, + { + searchParams: { + state: 'all', + sort: 'recentupdate', + page, + limit: PULL_REQUEST_PAGE_LIMIT + }, + timeoutMs: PULL_REQUEST_LIST_TIMEOUT_MS }, - timeoutMs: PULL_REQUEST_LIST_TIMEOUT_MS - }), + throwOnFailure + ), PULL_REQUEST_PAGE_LIMIT, MAX_PULL_REQUEST_PAGES ) @@ -270,11 +290,28 @@ export async function getGiteaPullRequestForBranch( } const raw = await requestJson( repo, - `/repos/${encodedRepoPath(repo)}/pulls/${encodeURIComponent(String(linkedPRNumber))}` + `/repos/${encodedRepoPath(repo)}/pulls/${encodeURIComponent(String(linkedPRNumber))}`, + {}, + throwOnFailure ) return raw ? normalizePullRequest(repo, raw) : null } +/** + * Existing-review lookup that surfaces transport/auth failures instead of + * collapsing them to null, so a failed lookup becomes + * `reviewLookupOutcome: 'unavailable'` rather than a false "No pull request found". + */ +export function getGiteaPullRequestForBranchOrThrow( + repoPath: string, + branch: string, + linkedPRNumber?: number | null, + connectionId?: string | null, + options: HostedReviewExecutionOptions = {} +): Promise { + return getGiteaPullRequestForBranch(repoPath, branch, linkedPRNumber, connectionId, options, true) +} + export async function getGiteaRepoSlug( repoPath: string, connectionId?: string | null, diff --git a/src/main/github/client.test.ts b/src/main/github/client.test.ts index d403d582f..07a007f7f 100644 --- a/src/main/github/client.test.ts +++ b/src/main/github/client.test.ts @@ -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' }], diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 67d34bef4..d9d41f4f6 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -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 } } -function classifyPRRefreshError( - err: unknown -): Extract['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['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 { const errorType = classifyPRRefreshError(err) - return { + const outcome: Extract = { 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 { diff --git a/src/main/github/gh-utils.ts b/src/main/github/gh-utils.ts index 38b3d23cf..b294e90ac 100644 --- a/src/main/github/gh-utils.ts +++ b/src/main/github/gh-utils.ts @@ -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, diff --git a/src/main/github/pr-refresh-coordinator.ts b/src/main/github/pr-refresh-coordinator.ts index bd59fc77c..700cc32ec 100644 --- a/src/main/github/pr-refresh-coordinator.ts +++ b/src/main/github/pr-refresh-coordinator.ts @@ -83,7 +83,30 @@ const queue = new Map() const backgroundStarts: number[] = [] const activeStartsByScope = new Map() const errorBackoff = new Map() +// 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() 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 }>() 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 { 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 { 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 } diff --git a/src/main/github/pr-refresh-error-classification.test.ts b/src/main/github/pr-refresh-error-classification.test.ts new file mode 100644 index 000000000..549fc10fd --- /dev/null +++ b/src/main/github/pr-refresh-error-classification.test.ts @@ -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') + } + }) +}) diff --git a/src/main/github/pr-refresh-error-classification.ts b/src/main/github/pr-refresh-error-classification.ts new file mode 100644 index 000000000..aa9e22693 --- /dev/null +++ b/src/main/github/pr-refresh-error-classification.ts @@ -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.' + } +} diff --git a/src/main/gitlab/client-mr.test.ts b/src/main/gitlab/client-mr.test.ts index a090ec796..aac5193c1 100644 --- a/src/main/gitlab/client-mr.test.ts +++ b/src/main/gitlab/client-mr.test.ts @@ -41,6 +41,7 @@ import { addMRComment, getMergeRequest, getMergeRequestForBranch, + getMergeRequestForBranchOrThrow, getJobTrace, addMRInlineComment, closeMR, @@ -74,6 +75,19 @@ describe('gitlab client — MR operations', () => { }) }) + it('getMergeRequestForBranchOrThrow surfaces a glab failure instead of null (finding 4)', async () => { + getProjectRefMock.mockResolvedValue({ host: 'gitlab.com', path: 'g/p' }) + glabExecFileAsyncMock.mockRejectedValue(new Error('glab: connection refused')) + + // The swallowing variant collapses a real failure into a false "no MR". + await expect(getMergeRequestForBranch('/repo', 'feature/x')).resolves.toBeNull() + // The throwing variant makes the failure visible so eligibility records + // `unavailable` rather than a false "No merge request found". + await expect(getMergeRequestForBranchOrThrow('/repo', 'feature/x')).rejects.toThrow( + /connection refused/ + ) + }) + it('routes local WSL MR review-management and job actions through project resolution and glab options', async () => { const localGitOptions = { wslDistro: 'Ubuntu' } glabExecFileAsyncMock diff --git a/src/main/gitlab/client.ts b/src/main/gitlab/client.ts index b6b32dfb8..370553db9 100644 --- a/src/main/gitlab/client.ts +++ b/src/main/gitlab/client.ts @@ -313,7 +313,11 @@ export async function getMergeRequestForBranch( branch: string, linkedMRIid?: number | null, connectionId?: string | null, - options: HostedReviewExecutionOptions = {} + options: HostedReviewExecutionOptions = {}, + // Why: the existing-review lookup behind Create must distinguish a real glab + // transport/auth failure from an accepted "no MR". When true, a failed lookup + // throws instead of collapsing to null so callers never report false not_found. + throwOnFailure = false ): Promise { const branchName = branch.replace(/^refs\/heads\//, '') if (!branchName && linkedMRIid == null) { @@ -369,13 +373,31 @@ export async function getMergeRequestForBranch( } const pipelineStatus = derivePipelineStatus(raw.head_pipeline ?? raw.pipeline ?? null) return mapMRInfo(raw, pipelineStatus) - } catch { + } catch (error) { + if (throwOnFailure) { + throw error + } return null } finally { release() } } +/** + * Existing-review lookup that surfaces glab transport/auth failures instead of + * collapsing them to null, so a failed lookup becomes + * `reviewLookupOutcome: 'unavailable'` rather than a false "No merge request found". + */ +export function getMergeRequestForBranchOrThrow( + repoPath: string, + branch: string, + linkedMRIid?: number | null, + connectionId?: string | null, + options: HostedReviewExecutionOptions = {} +): Promise { + return getMergeRequestForBranch(repoPath, branch, linkedMRIid, connectionId, options, true) +} + function mrListStateFlags(state: MRListState): string[] { switch (state) { case 'opened': diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 9e194212d..a3f6e0b2c 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -193,6 +193,7 @@ const { getHostedReviewCreationEligibilityMock, getHostedReviewForBranchMock, getPRForBranchMock, + getPRForBranchOutcomeMock, getRepoSlugMock, getRepoUpstreamMock, getGitHubWorkItemMock, @@ -298,6 +299,7 @@ const { getHostedReviewCreationEligibilityMock: vi.fn(), getHostedReviewForBranchMock: vi.fn(), getPRForBranchMock: vi.fn().mockResolvedValue(null), + getPRForBranchOutcomeMock: vi.fn().mockResolvedValue({ kind: 'no-pr', fetchedAt: 0 }), getRepoSlugMock: vi.fn().mockResolvedValue(null), getRepoUpstreamMock: vi.fn().mockResolvedValue(null), getGitHubWorkItemMock: vi.fn(), @@ -463,6 +465,7 @@ vi.mock('../github/client', async (importOriginal) => { return { ...actual, getPRForBranch: getPRForBranchMock, + getPRForBranchOutcome: getPRForBranchOutcomeMock, getRepoSlug: getRepoSlugMock, getRepoUpstream: getRepoUpstreamMock, getWorkItem: getGitHubWorkItemMock, @@ -671,6 +674,8 @@ function resetRuntimeTestMocks(): void { getHostedReviewForBranchMock.mockResolvedValue(null) getPRForBranchMock.mockReset() getPRForBranchMock.mockResolvedValue(null) + getPRForBranchOutcomeMock.mockReset() + getPRForBranchOutcomeMock.mockResolvedValue({ kind: 'no-pr', fetchedAt: 0 }) getRepoSlugMock.mockReset() getRepoSlugMock.mockResolvedValue(null) getRepoUpstreamMock.mockReset() @@ -5572,9 +5577,16 @@ describe('OrcaRuntimeService', () => { prRepo }) - expect(getPRForBranchMock).toHaveBeenCalledWith(TEST_REPO_PATH, 'feature/wsl', 42, null, null, { - localGitExecOptions: localGitOptions - }) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledWith( + TEST_REPO_PATH, + 'feature/wsl', + 42, + null, + null, + { + localGitExecOptions: localGitOptions + } + ) expect(getGitHubWorkItemMock).toHaveBeenCalledWith( TEST_REPO_PATH, 42, diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 418809d2f..c255a6586 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -378,6 +378,7 @@ import type { BrowserBackend } from '../browser/browser-backend' import { BrowserError } from '../browser/cdp-bridge' import { getPRForBranch, + getPRForBranchOutcome, getRepoSlug, getRepoUpstream, getWorkItem, @@ -456,7 +457,8 @@ import type { GitLabProjectRef, GitLabWorkItem, ListWorkItemsResult, - MRListState + MRListState, + PRRefreshOutcome } from '../../shared/types' import { inspectSetupScriptImportCandidates } from '../../shared/setup-script-imports' import type { @@ -13977,7 +13979,7 @@ export class OrcaRuntimeService { fallbackPRNumber?: number | null, acceptMergedFallbackPR?: boolean, currentHeadOid?: string | null - ): Promise>> { + ): Promise { const repo = await this.resolveRepoSelector(repoSelector) const options: GitHubPRBranchLookupOptions = this.getHostedReviewExecutionOptions(repo) ?? {} const lookupOptions = { ...options } @@ -13989,7 +13991,11 @@ export class OrcaRuntimeService { } const lookupOptionArgs: [] | [GitHubPRBranchLookupOptions] = Object.keys(lookupOptions).length > 0 ? [lookupOptions] : [] - return getPRForBranch( + // Why: return the full classified outcome (not PRInfo|null) so a runtime gh + // auth/network failure crosses the RPC as `upstream-error` instead of + // collapsing to `null`, which the renderer would otherwise cache as a false + // accepted "no PR found" (design success criterion 1). + return getPRForBranchOutcome( repo.path, branch, linkedPRNumber ?? null, diff --git a/src/main/runtime/rpc/methods/hosted-review.test.ts b/src/main/runtime/rpc/methods/hosted-review.test.ts index 5c3c683b6..7c2e3cb7b 100644 --- a/src/main/runtime/rpc/methods/hosted-review.test.ts +++ b/src/main/runtime/rpc/methods/hosted-review.test.ts @@ -58,6 +58,7 @@ describe('hosted review RPC methods', () => { canCreate: true, blockedReason: null, nextAction: null, + reviewLookupOutcome: 'not_found', defaultBaseRef: 'main', head: 'feature/create-pr', title: 'Create PR' diff --git a/src/main/source-control/forge-provider.ts b/src/main/source-control/forge-provider.ts index a7d22ad48..1a6ea4a43 100644 --- a/src/main/source-control/forge-provider.ts +++ b/src/main/source-control/forge-provider.ts @@ -6,24 +6,24 @@ import type { } from '../../shared/hosted-review' import { getAzureDevOpsPullRequest, - getAzureDevOpsPullRequestForBranch, + getAzureDevOpsPullRequestForBranchOrThrow, getAzureDevOpsRepoSlug } from '../azure-devops/client' import { createAzureDevOpsPullRequest } from '../azure-devops/pull-request-creation' import { getBitbucketPullRequest, - getBitbucketPullRequestForBranch, + getBitbucketPullRequestForBranchOrThrow, getBitbucketRepoSlug } from '../bitbucket/client' import { getGiteaPullRequest, - getGiteaPullRequestForBranch, + getGiteaPullRequestForBranchOrThrow, getGiteaRepoSlug } from '../gitea/client' import { createGiteaPullRequest } from '../gitea/pull-request-creation' import { createGitHubPullRequest, getPRForBranchOutcome, getRepoSlug } from '../github/client' import { getEnterpriseGitHubRepoSlug } from '../github/github-enterprise-repository' -import { getMergeRequest, getMergeRequestForBranch, getProjectSlug } from '../gitlab/client' +import { getMergeRequest, getMergeRequestForBranchOrThrow, getProjectSlug } from '../gitlab/client' import { createGitLabMergeRequest } from '../gitlab/merge-request-creation' import { mapAzureDevOpsReview, @@ -86,7 +86,10 @@ const gitLabForgeProvider = { resolveRepository: (context) => getProjectSlug(context.repoPath, context.connectionId, ...hostedReviewExecutionArgs(context)), async getReviewForBranch(input) { - const mr = await getMergeRequestForBranch( + // Why: throw (not null) on a real lookup failure so eligibility records + // `unavailable`, never a false "No merge request found" — same contract the + // GitHub adapter uses so hosted-review callers preserve last-known state. + const mr = await getMergeRequestForBranchOrThrow( input.repoPath, input.branch, input.linkedReviewNumber ?? null, @@ -188,7 +191,9 @@ const bitbucketForgeProvider = { ...hostedReviewExecutionArgs(context) ), async getReviewForBranch(input) { - const pr = await getBitbucketPullRequestForBranch( + // Why: surface a real lookup failure so eligibility records `unavailable` + // instead of a false "No pull request found". + const pr = await getBitbucketPullRequestForBranchOrThrow( input.repoPath, input.branch, input.linkedReviewNumber ?? null, @@ -218,7 +223,9 @@ const azureDevOpsForgeProvider = { ...hostedReviewExecutionArgs(context) ), async getReviewForBranch(input) { - const pr = await getAzureDevOpsPullRequestForBranch( + // Why: surface a real lookup failure so eligibility records `unavailable` + // instead of a false "No pull request found". + const pr = await getAzureDevOpsPullRequestForBranchOrThrow( input.repoPath, input.branch, input.linkedReviewNumber ?? null, @@ -245,7 +252,9 @@ const giteaForgeProvider = { resolveRepository: (context) => getGiteaRepoSlug(context.repoPath, context.connectionId, ...hostedReviewExecutionArgs(context)), async getReviewForBranch(input) { - const pr = await getGiteaPullRequestForBranch( + // Why: surface a real lookup failure so eligibility records `unavailable` + // instead of a false "No pull request found". + const pr = await getGiteaPullRequestForBranchOrThrow( input.repoPath, input.branch, input.linkedReviewNumber ?? null, diff --git a/src/main/source-control/hosted-review-creation-eligibility.test.ts b/src/main/source-control/hosted-review-creation-eligibility.test.ts index 010d950d5..484ede6cb 100644 --- a/src/main/source-control/hosted-review-creation-eligibility.test.ts +++ b/src/main/source-control/hosted-review-creation-eligibility.test.ts @@ -115,7 +115,7 @@ vi.mock('./hosted-review', () => ({ getHostedReviewForBranch: getHostedReviewForBranchMock })) -import { getHostedReviewCreationEligibility } from './hosted-review-creation' +import { createHostedReview, getHostedReviewCreationEligibility } from './hosted-review-creation' function resetMocks(): void { for (const mock of [ @@ -232,6 +232,96 @@ describe('getHostedReviewCreationEligibility', () => { }) }) + it('reports reviewLookupOutcome: found when an existing review is returned', async () => { + getHostedReviewForBranchMock.mockResolvedValue({ number: 7, url: 'https://x/pull/7' }) + await expect( + getHostedReviewCreationEligibility({ + repoPath: '/repo', + branch: 'feature/x', + hasUncommittedChanges: false, + hasUpstream: true, + ahead: 0, + behind: 0 + }) + ).resolves.toMatchObject({ blockedReason: 'existing_review', reviewLookupOutcome: 'found' }) + }) + + it('reports reviewLookupOutcome: not_found when the lookup accepts no review', async () => { + getHostedReviewForBranchMock.mockResolvedValue(null) + await expect( + getHostedReviewCreationEligibility({ + repoPath: '/repo', + branch: 'feature/x', + hasUncommittedChanges: false, + hasUpstream: true, + ahead: 0, + behind: 0 + }) + ).resolves.toMatchObject({ reviewLookupOutcome: 'not_found' }) + }) + + it('reports reviewLookupOutcome: unavailable when a swallowed lookup failure yields a local blocker', async () => { + getHostedReviewForBranchMock.mockRejectedValue(new Error('ssh: connection refused')) + await expect( + getHostedReviewCreationEligibility({ + repoPath: '/repo', + branch: 'feature/x', + hasUncommittedChanges: false, + hasUpstream: false, + ahead: 0, + behind: 0 + }) + ).resolves.toMatchObject({ blockedReason: 'no_upstream', reviewLookupOutcome: 'unavailable' }) + }) + + it('never marks a clean, in-sync branch creatable when the review lookup fails', async () => { + // A failed existing-review lookup leaves review existence unproven, so the + // happy path must not claim canCreate — that would offer Create against a + // branch that might already have a review (finding 4). + getHostedReviewForBranchMock.mockRejectedValue(new Error('gh: could not connect to github.com')) + await expect( + getHostedReviewCreationEligibility({ + repoPath: '/repo', + branch: 'feature/x', + base: 'origin/main', + hasUncommittedChanges: false, + hasUpstream: true, + ahead: 0, + behind: 0 + }) + ).resolves.toMatchObject({ + canCreate: false, + blockedReason: null, + reviewLookupOutcome: 'unavailable' + }) + }) + + it('refuses to create when the existing-review lookup is unavailable (finding 5)', async () => { + getHostedReviewForBranchMock.mockRejectedValue(new Error('glab: connection refused')) + getUpstreamStatusMock.mockResolvedValue({ hasUpstream: true, ahead: 0, behind: 0 }) + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'rev-parse') { + return { stdout: 'feature/x\n', stderr: '' } + } + if (args[0] === 'status') { + return { stdout: '', stderr: '' } + } + // symbolic-ref / for-each-ref resolve the base on the remote. + return { stdout: 'refs/remotes/origin/main\n', stderr: '' } + }) + + const result = await createHostedReview('/repo', { + provider: 'github', + base: 'main', + head: 'feature/x', + title: 'Add feature' + }) + + expect(result).toMatchObject({ ok: false, code: 'validation' }) + // The provider create API must never run on an inconclusive lookup. + expect(createGitHubPullRequestMock).not.toHaveBeenCalled() + }) + // Stacked-worktree base resolution (Change 1/2). `stackedArgs` defaults to a // bare local-only parent; `mockRefs` controls the remote-tracking snapshot. const stackedArgs = ( diff --git a/src/main/source-control/hosted-review-creation.ts b/src/main/source-control/hosted-review-creation.ts index 1e19f1d4f..a0271d0ea 100644 --- a/src/main/source-control/hosted-review-creation.ts +++ b/src/main/source-control/hosted-review-creation.ts @@ -6,6 +6,7 @@ import type { HostedReviewCreationBlockedReason, HostedReviewCreationEligibility, HostedReviewCreationEligibilityArgs, + HostedReviewLookupOutcome, HostedReviewProvider } from '../../shared/hosted-review' import { @@ -435,6 +436,18 @@ async function validateCurrentBranchCanCreateReview( enforceBaseOnRemote: true, ...options }) + // Why: never call the provider create API when the existing-review lookup + // could not prove the branch has no review. An `unavailable` outcome means a + // real MR/PR might exist that a failed lookup could not see; refuse + // inconclusively (design invariant 8 / submission boundary) so we never + // create a duplicate. The composed title/body are preserved by the caller. + if (eligibility.reviewLookupOutcome === 'unavailable') { + return { + ok: false, + code: 'validation', + error: `Create ${copy.shortLabel} failed: Orca could not confirm whether this branch already has a ${copy.reviewLabel}. Retry once the ${copy.providerName} lookup succeeds.` + } + } // Why: renderer eligibility can be stale by submit time; the main process // is the last chance to avoid creating a PR from an out-of-date remote head. return blockedEligibilityToCreateResult(eligibility, submittedBase) @@ -475,6 +488,10 @@ export async function getHostedReviewCreationEligibility( } const baseBranch = defaultBaseRef ? normalizeHostedReviewBaseRef(defaultBaseRef) : null let review: Awaited> = null + // Why: a swallowed lookup failure must not masquerade as authoritative + // no-review evidence. Track it so the renderer can distinguish an accepted + // no-PR result (`not_found`) from a local-blocker fallback (`unavailable`). + let lookupFailed = false try { review = await getHostedReviewForBranch({ repoPath: args.repoPath, @@ -489,23 +506,25 @@ export async function getHostedReviewCreationEligibility( ...hostedReviewExecutionContext(args) }) } catch (error) { - const canReturnLocalBlocker = - branch && - branch !== 'HEAD' && - supportsHostedReviewCreation(provider) && - (!baseBranch || branch.toLowerCase() !== baseBranch.toLowerCase()) && - (args.hasUncommittedChanges || args.hasUpstream !== true || (args.behind ?? 0) > 0) - if (!canReturnLocalBlocker) { - throw error - } - // Why: local blockers still let the UI offer Create PR preparation; a - // flaky existing-review lookup should not hide the affordance entirely. - console.warn('Hosted review lookup failed while resolving local review blocker:', error) + // Why: a failed existing-review lookup can never authorize Create — it might + // be hiding a real PR. Record `unavailable` and fall through so any local + // blocker (dirty/no-upstream/behind) still supplies primary guidance, but the + // clean-branch happy path below is forced to `canCreate: false`. Never rethrow + // here: a thrown lookup must not collapse into a false `not_found` and must + // stay a structured, honest empty state for the renderer. + lookupFailed = true + console.warn('Hosted review lookup failed; treating existing-review as unavailable:', error) } + const reviewLookupOutcome: HostedReviewLookupOutcome = review + ? 'found' + : lookupFailed + ? 'unavailable' + : 'not_found' const baseResult = { provider, review: review ? { number: review.number, url: review.url } : null, + reviewLookupOutcome, defaultBaseRef, head: branch || null } @@ -575,7 +594,15 @@ export async function getHostedReviewCreationEligibility( nextAction: null } } - return { ...baseResult, canCreate: Boolean(baseBranch), blockedReason: null, nextAction: null } + // Why: a lookup that failed leaves review existence unproven, so the clean, + // in-sync happy path must not claim `canCreate` — that would open Create + // against a branch that may already have a review. Stays `unavailable`. + return { + ...baseResult, + canCreate: lookupFailed ? false : Boolean(baseBranch), + blockedReason: null, + nextAction: null + } } export async function createHostedReview( diff --git a/src/main/source-control/hosted-review.test.ts b/src/main/source-control/hosted-review.test.ts index 51c5ee8d9..102ebfebd 100644 --- a/src/main/source-control/hosted-review.test.ts +++ b/src/main/source-control/hosted-review.test.ts @@ -27,6 +27,9 @@ const { vi.mock('../gitlab/client', () => ({ getProjectSlug: getProjectSlugMock, getMergeRequestForBranch: getMergeRequestForBranchMock, + // Why: forge-provider resolves branch reviews via the OrThrow variant so + // lookup failures surface as unavailable instead of "no PR found". + getMergeRequestForBranchOrThrow: getMergeRequestForBranchMock, getMergeRequest: vi.fn() })) @@ -39,18 +42,27 @@ vi.mock('../github/client', () => ({ vi.mock('../bitbucket/client', () => ({ getBitbucketRepoSlug: getBitbucketRepoSlugMock, getBitbucketPullRequestForBranch: getBitbucketPullRequestForBranchMock, + // Why: forge-provider resolves branch reviews via the OrThrow variant so + // lookup failures surface as unavailable instead of "no PR found". + getBitbucketPullRequestForBranchOrThrow: getBitbucketPullRequestForBranchMock, getBitbucketPullRequest: vi.fn() })) vi.mock('../azure-devops/client', () => ({ getAzureDevOpsRepoSlug: getAzureDevOpsRepoSlugMock, getAzureDevOpsPullRequestForBranch: getAzureDevOpsPullRequestForBranchMock, + // Why: forge-provider resolves branch reviews via the OrThrow variant so + // lookup failures surface as unavailable instead of "no PR found". + getAzureDevOpsPullRequestForBranchOrThrow: getAzureDevOpsPullRequestForBranchMock, getAzureDevOpsPullRequest: vi.fn() })) vi.mock('../gitea/client', () => ({ getGiteaRepoSlug: getGiteaRepoSlugMock, getGiteaPullRequestForBranch: getGiteaPullRequestForBranchMock, + // Why: forge-provider resolves branch reviews via the OrThrow variant so + // lookup failures surface as unavailable instead of "no PR found". + getGiteaPullRequestForBranchOrThrow: getGiteaPullRequestForBranchMock, getGiteaPullRequest: vi.fn() })) diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index ac08b19fd..66ff0f85a 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -60,7 +60,8 @@ import type { PRInfo, PRCheckDetail, PRCheckRunDetails, - PRComment + PRComment, + PRRefreshErrorType } from '../../../../shared/types' import { getConnectionId } from '@/lib/connection-context' import { @@ -82,6 +83,7 @@ import type { HostedReviewProvider } from '../../../../shared/hosted-review' import { resolveHostedReviewCreationProvider } from '../../../../shared/hosted-review-creation-providers' +import { normalizeGlobalWindowsRuntimeDefault } from '../../../../shared/project-execution-runtime' import { normalizeHostedReviewHeadRef } from '../../../../shared/hosted-review-refs' import { getHostedReviewCacheKey, refreshHostedReviewCard } from '@/store/slices/hosted-review' import { toast } from 'sonner' @@ -99,11 +101,17 @@ import { } from './pr-comment-thread-resolution' import { installWindowVisibilityTimeoutPoller } from '@/lib/window-visibility-timeout-poller' import { - getChecksPanelEmptyStateCopy, + getChecksPanelReviewState, shouldShowChecksPanelPublishBranchAction } from './checks-panel-empty-state' import { getChecksPanelRefreshErrorBannerLine } from './github-refresh-error-copy' -import { hasAmbiguousGitHubHostedReviewForChecksPanel } from './checks-panel-ambiguous-github-review' +import { resolveChecksPanelReviewLookup } from './checks-panel-review-lookup-authority' +import { + computeChecksPanelConfirmedReadiness, + isChecksPanelHardErrorCleared, + isChecksPanelHardRefreshErrorType, + type ChecksPanelConfirmedReadinessInput +} from './checks-panel-review-creation' import { recordChecksPanelPRRefreshBreadcrumb } from './checks-panel-pr-refresh-breadcrumb' import { cancelRuntimeGeneratePullRequestFields, @@ -181,12 +189,47 @@ const GIT_STATUS_FAILURE_RETRY_MS = 3000 type HostedReviewCreationSnapshot = { requestKey: string + /** Panel context key (repo/worktree/branch/host) at request time. */ + contextKey: string repoId: string worktreeId: string | null branch: string + /** Wall-clock time the eligibility request started (hard-error clear ordering). */ + requestStartedAt: number + /** Wall-clock time the eligibility result settled (confirmed freshness window). */ + completedAt: number + /** Git snapshot fingerprint used for this eligibility (confirmed freshness). */ + gitFingerprint: string data: HostedReviewCreationEligibility } +// Confirmed readiness must drop when HEAD, dirty, upstream, base, or the +// execution host move under the eligibility that produced it. Fingerprint those +// fields so a stale snapshot cannot keep an enabled Create open. +function buildChecksPanelEligibilityGitFingerprint(input: { + headOid: string | null + hasUncommittedChanges: boolean | undefined + hasUpstream: boolean | undefined + ahead: number | undefined + behind: number | undefined + base: string | null + runtimeEnvironmentId: string | null + repoConnectionId: string | null + localExecutionScope: string | null +}): string { + return JSON.stringify({ + headOid: input.headOid ?? null, + hasUncommittedChanges: input.hasUncommittedChanges ?? null, + hasUpstream: input.hasUpstream ?? null, + ahead: input.ahead ?? null, + behind: input.behind ?? null, + base: input.base ?? null, + runtimeEnvironmentId: input.runtimeEnvironmentId ?? null, + repoConnectionId: input.repoConnectionId ?? null, + localExecutionScope: input.localExecutionScope ?? null + }) +} + type ChecksAgentComposerState = { actionId: SourceControlLaunchActionId title: string @@ -416,6 +459,7 @@ export default function ChecksPanel(): React.JSX.Element { ) const isRemoteOperationActive = useAppStore((s) => s.isRemoteOperationActive) const pushBranch = useAppStore((s) => s.pushBranch) + const syncBranch = useAppStore((s) => s.syncBranch) const fetchUpstreamStatus = useAppStore((s) => s.fetchUpstreamStatus) const setRightSidebarOpen = useAppStore((s) => s.setRightSidebarOpen) const setRightSidebarTab = useAppStore((s) => s.setRightSidebarTab) @@ -452,6 +496,7 @@ export default function ChecksPanel(): React.JSX.Element { const [isCreatingPr, setIsCreatingPr] = useState(false) const [createPrError, setCreatePrError] = useState(null) const [isPublishingBranch, setIsPublishingBranch] = useState(false) + const [isSyncingBranch, setIsSyncingBranch] = useState(false) const isResolvingConflictsWithAI = false const [isFixingChecksWithAI, setIsFixingChecksWithAI] = useState(false) const [agentComposerState, setAgentComposerState] = useState( @@ -459,10 +504,28 @@ export default function ChecksPanel(): React.JSX.Element { ) const [hostedReviewCreationSnapshot, setHostedReviewCreationSnapshot] = useState(null) + // Sticky observation of the most recent hard refresh error for the exact + // context. Persisted across queued/in-flight auto-retries so Create cannot + // flap back until a qualifying eligibility request clears it. + const [hardRefreshError, setHardRefreshError] = useState<{ + observedAt: number + errorType: PRRefreshErrorType + contextKey: string + } | null>(null) const [gitStatusSnapshot, setGitStatusSnapshot] = useState( null ) + // Context key whose git-status probe failed with no usable snapshot, so the + // empty state can distinguish "checking branch status" from "could not check". + const [gitStatusProbeErrorContextKey, setGitStatusProbeErrorContextKey] = useState( + null + ) const [gitStatusRefreshNonce, setGitStatusRefreshNonce] = useState(0) + // Bumped by a manual Retry/Refresh so eligibility re-runs even when the Git + // snapshot is unchanged. A hard error can only be cleared by an eligibility + // request that started strictly after the error, so an auth fix followed by + // Retry (which does not change Git state) must still trigger a fresh request. + const [eligibilityRefreshNonce, setEligibilityRefreshNonce] = useState(0) const [editingTitle, setEditingTitle] = useState(false) const [titleDraft, setTitleDraft] = useState('') const [titleSaving, setTitleSaving] = useState(false) @@ -543,6 +606,16 @@ export default function ChecksPanel(): React.JSX.Element { [runtimeEnvironmentId, settings] ) const repoConnectionId = repo?.connectionId?.trim() || null + // Local execution host variant (`wsl:{distro}` vs `host`). WSL is a local-host + // variant, not a runtime/SSH host, so it only applies when execution is local; + // remote contexts are already scoped by runtimeEnvironmentId / connectionId. + const localExecutionScope = useMemo(() => { + if (runtimeEnvironmentId != null || repoConnectionId != null) { + return null + } + const localRuntime = normalizeGlobalWindowsRuntimeDefault(settings?.localWindowsRuntimeDefault) + return localRuntime.kind === 'wsl' ? `wsl:${localRuntime.distro ?? ''}` : 'host' + }, [runtimeEnvironmentId, repoConnectionId, settings?.localWindowsRuntimeDefault]) const sshConnectionStatus = useAppStore((s) => repoConnectionId ? s.sshConnectionStates.get(repoConnectionId)?.status : undefined ) @@ -558,6 +631,7 @@ export default function ChecksPanel(): React.JSX.Element { linkedGiteaPR: activeWorktree?.linkedGiteaPR ?? null, runtimeEnvironmentId, repoConnectionId, + localExecutionScope, pushTarget: activeWorktreePushTarget }) const panelContextKeyRef = useRef(panelContextKey) @@ -607,7 +681,9 @@ export default function ChecksPanel(): React.JSX.Element { setIsPublishingBranch(false) setAgentComposerState(null) setHostedReviewCreationSnapshot(null) + setHardRefreshError(null) setGitStatusSnapshot(null) + setGitStatusProbeErrorContextKey(null) setGitStatusRefreshNonce((value) => value + 1) pollIntervalRef.current = 30_000 prevChecksRef.current = '' @@ -659,11 +735,13 @@ export default function ChecksPanel(): React.JSX.Element { const hostedReview = useAppStore((s) => hostedReviewCacheKey ? (s.hostedReviewCache[hostedReviewCacheKey]?.data ?? null) : null ) - const hasAmbiguousGitHubHostedReview = hasAmbiguousGitHubHostedReviewForChecksPanel({ - hostedReview, - prCacheEntry, - prCacheKey - }) + const linkedReviewNumber = + activeWorktree?.linkedPR ?? + activeWorktree?.linkedGitLabMR ?? + activeWorktree?.linkedBitbucketPR ?? + activeWorktree?.linkedAzureDevOpsPR ?? + activeWorktree?.linkedGiteaPR ?? + null // Fetch PR data when the active worktree/branch changes. // Why: branch lookup is lossy for fork/deleted-head PRs; reuse a known PR // number from metadata or the visible cache whenever we have one. @@ -748,6 +826,25 @@ export default function ChecksPanel(): React.JSX.Element { panelVisibleSinceRef.current = Date.now() }, [isPanelVisible, panelContextKey]) + // Record the latest hard refresh error for the exact context. Kept sticky + // (only cleared via computeChecksPanelConfirmedReadiness) so a background + // queued/in-flight auto-retry — which replaces `status: 'error'` — cannot + // silently re-enable Create while the lookup is still impossible here. + useEffect(() => { + const errorType = prRefreshState?.status === 'error' ? prRefreshState.errorType : undefined + if (!isChecksPanelHardRefreshErrorType(errorType)) { + return + } + const observedAt = prRefreshState?.updatedAt ?? Date.now() + const contextKey = panelContextKeyRef.current + setHardRefreshError((prev) => { + if (prev && prev.contextKey === contextKey && prev.observedAt >= observedAt) { + return prev + } + return { observedAt, errorType: errorType as PRRefreshErrorType, contextKey } + }) + }, [prRefreshState]) + // Why: select only timestamps (not whole cache records) so the entry-refresh // effect doesn't re-run on every cache mutation. See // docs/refresh-on-checks-tab.md. @@ -824,6 +921,27 @@ export default function ChecksPanel(): React.JSX.Element { const gitStatusReadyForPanelContext = gitStatusInputs.hasUncommittedChanges !== undefined const hasUncommittedChanges = gitStatusInputs.hasUncommittedChanges const remoteStatus = gitStatusInputs.remoteStatus + const eligibilityHeadOid = + gitStatusSnapshot?.contextKey === panelContextKey + ? (gitStatusSnapshot.gitIdentity?.head ?? null) + : null + // Read at eligibility request time via a ref so a HEAD move drops confirmed + // (fingerprint mismatch) without re-triggering the eligibility network call. + const eligibilityHeadOidRef = useRef(eligibilityHeadOid) + eligibilityHeadOidRef.current = eligibilityHeadOid + const eligibilityGitFingerprint = gitStatusReadyForPanelContext + ? buildChecksPanelEligibilityGitFingerprint({ + headOid: eligibilityHeadOid, + hasUncommittedChanges, + hasUpstream: remoteStatus?.hasUpstream, + ahead: remoteStatus?.ahead, + behind: remoteStatus?.behind, + base: repo?.worktreeBaseRef ?? null, + runtimeEnvironmentId, + repoConnectionId, + localExecutionScope + }) + : null // Why: Create PR eligibility waits for the stricter panel snapshot, but the // Publish affordance can use the active worktree poller when SSH snapshot // refresh is delayed; publishing is still blocked for dirty fallback status. @@ -843,7 +961,70 @@ export default function ChecksPanel(): React.JSX.Element { const hostedReviewCreateProvider = resolveHostedReviewCreationProvider( hostedReviewCreation?.provider ) + // Only GitHub contexts run the gh-based PR refresh coordinator. Bitbucket / + // Azure DevOps / Gitea / GitLab must never be driven by (or show copy from) a + // GitHub `gh` failure — that would hide a valid composer and mislabel the CLI. + // Prefer the resolved eligibility provider (authoritative); before it resolves, + // treat a non-GitHub linked review as a definite non-GitHub signal and stay + // GitHub-optimistic otherwise so GitHub status is not delayed on initial load. + // (`resolveHostedReviewCreationProvider` defaults null → 'github', so the raw + // value cannot distinguish "unknown" from "GitHub".) + const hasNonGitHubLinkedReview = + activeWorktree?.linkedGitLabMR != null || + activeWorktree?.linkedBitbucketPR != null || + activeWorktree?.linkedAzureDevOpsPR != null || + activeWorktree?.linkedGiteaPR != null + const isGitHubReviewContext = hostedReviewCreation + ? hostedReviewCreation.provider === 'github' + : !hasNonGitHubLinkedReview const hostedReviewCreateCopy = localizedHostedReviewCopy(hostedReviewCreateProvider) + // The PR cache is branch/host scoped but not push-target scoped, so an accepted + // no-PR fetched for a previous push target could alias as `not_found` after the + // push target (or other exact-context field) changes. When an eligibility + // snapshot exists for a *different* context than the current one, the context + // has moved and that branch-scoped no-PR is not authoritative for it — demote + // it to unknown until eligibility re-resolves. Same-context background churn + // (snapshot matches, or no snapshot yet) keeps the sticky no-review intact. + const prCachedHasPRForContext = + hostedReviewCreationSnapshot && hostedReviewCreationSnapshot.contextKey !== panelContextKey + ? null + : prCachedHasPR + // Four-state review evidence: replaces the old ambiguous-GitHub boolean so the + // empty state can never claim "No review found" without accepted evidence. + const checksPanelReviewLookupResult = resolveChecksPanelReviewLookup({ + pr, + prCachedHasPR: prCachedHasPRForContext, + hostedReview, + linkedReviewNumber, + eligibilityReviewLookupOutcome: hostedReviewCreation?.reviewLookupOutcome ?? null, + eligibilityReview: hostedReviewCreation?.review ?? null + }) + const checksPanelReviewLookup = checksPanelReviewLookupResult.state + // Confirmed readiness for the exact context, computed from the last confirmed + // eligibility snapshot rather than live `canCreate` (which would be circular + // and would flap during transient refresh/eligibility failures). This both + // gates the composer and clears the sticky hard-error block below. + const hardErrorObservedAt = + isGitHubReviewContext && hardRefreshError && hardRefreshError.contextKey === panelContextKey + ? hardRefreshError.observedAt + : undefined + const confirmedReadinessInput: ChecksPanelConfirmedReadinessInput = { + contextKeyMatches: hostedReviewCreationSnapshot?.contextKey === panelContextKey, + eligibility: hostedReviewCreationSnapshot?.data ?? null, + eligibilityCompletedAt: hostedReviewCreationSnapshot?.completedAt, + eligibilityRequestStartedAt: hostedReviewCreationSnapshot?.requestStartedAt, + reviewLookup: checksPanelReviewLookup, + hardErrorObservedAt, + gitSnapshotMatches: + eligibilityGitFingerprint !== null && + hostedReviewCreationSnapshot?.gitFingerprint === eligibilityGitFingerprint, + now: Date.now() + } + const confirmedReadiness = computeChecksPanelConfirmedReadiness(confirmedReadinessInput) + // A hard error stays active across auto-retries until a qualifying eligibility + // request clears it, so `status: 'queued' | 'in-flight'` no longer un-hides Create. + const checksPanelHasHardRefreshError = + hardErrorObservedAt !== undefined && !isChecksPanelHardErrorCleared(confirmedReadinessInput) const activePullRequestGenerationKey = getPullRequestGenerationRecordKey({ worktreeId: activeWorktreeId, worktreePath: activeWorktreePath, @@ -919,12 +1100,12 @@ export default function ChecksPanel(): React.JSX.Element { () => (settings ? resolveSourceControlAiEnabled({ settings, repo }) : false), [repo, settings] ) + // Confirmed-only composer gate. Driven by confirmed readiness (context match, + // fresh eligibility, matching git snapshot, cleared hard error) so an + // already-confirmed composer survives transient refresh/eligibility failures + // but a refresh failure never *opens* a never-confirmed Create. const createComposerOpen = - !activeReview && - !isFolder && - Boolean(branch) && - (hostedReviewCreation?.canCreate === true || - hostedReviewCreation?.blockedReason === 'needs_push') + !isFolder && !activeReview && Boolean(branch) && confirmedReadiness.confirmed const handleGeneratePullRequestFieldsForActive = useCallback( async ( fields: PullRequestGenerationFields, @@ -1121,6 +1302,9 @@ export default function ChecksPanel(): React.JSX.Element { submitting: isCreatingPr, prCreationDefaults, sourceControlAiActionsVisible, + // Preserve the draft when a hard refresh error hides the composer so the + // user's title/body/base survive recovery for the same exact context. + retainDraftWhenClosed: true, generation: { generating: activePullRequestGenerationRecord?.status === 'running', generateError: activePullRequestGenerationRecord?.error ?? null, @@ -1232,7 +1416,10 @@ export default function ChecksPanel(): React.JSX.Element { linkedGiteaPR, staleWhileRevalidate: true }) - if (activeWorktreeId && !isGitLabReviewContext) { + // Why: the gh-based PR refresh coordinator is GitHub-only. Running it for + // Bitbucket/Azure/Gitea produced a spurious `gh_unavailable` hard error that + // hid a valid composer; those providers refresh via fetchHostedReviewForBranch. + if (activeWorktreeId && isGitHubReviewContext) { const refreshRequest = resolveChecksPanelPRRefreshRequest({ cachedHasPR: prCachedHasPR, cachedFetchedAt: prFetchedAt ?? null, @@ -1248,7 +1435,7 @@ export default function ChecksPanel(): React.JSX.Element { fallbackGitHubPRNumber, fetchHostedReviewForBranch, isFolder, - isGitLabReviewContext, + isGitHubReviewContext, isPanelVisible, activeWorktree?.head, linkedAzureDevOpsPR, @@ -1382,6 +1569,9 @@ export default function ChecksPanel(): React.JSX.Element { branch: status.branch ?? (status.head ? null : undefined) } }) + // A fresh probe succeeded, so this context is no longer in the failed + // "could not check branch status" state. + setGitStatusProbeErrorContextKey((key) => (key === requestContextKey ? null : key)) } }) .catch((error) => { @@ -1392,6 +1582,13 @@ export default function ChecksPanel(): React.JSX.Element { setGitStatusSnapshot((snapshot) => shouldClearChecksPanelGitStatusSnapshot(snapshot, requestContextKey) ? null : snapshot ) + // Mark the probe as failed so the empty state can show "Could not check + // branch status" instead of an indefinite "Checking branch status". + if ( + shouldCommitChecksPanelGitStatusSnapshot(panelContextKeyRef.current, requestContextKey) + ) { + setGitStatusProbeErrorContextKey(requestContextKey) + } gitStatusSnapshotRetryTimerRef.current = setTimeout(() => { gitStatusSnapshotRetryTimerRef.current = null if ( @@ -1454,6 +1651,19 @@ export default function ChecksPanel(): React.JSX.Element { return } let stale = false + const requestContextKey = panelContextKey + const requestStartedAt = Date.now() + const requestGitFingerprint = buildChecksPanelEligibilityGitFingerprint({ + headOid: eligibilityHeadOidRef.current, + hasUncommittedChanges, + hasUpstream: remoteStatus?.hasUpstream, + ahead: remoteStatus?.ahead, + behind: remoteStatus?.behind, + base: repo.worktreeBaseRef ?? null, + runtimeEnvironmentId, + repoConnectionId, + localExecutionScope + }) void getHostedReviewCreationEligibility({ repoPath: repo.path, repoId: repo.id, @@ -1475,22 +1685,31 @@ export default function ChecksPanel(): React.JSX.Element { if (!stale) { setHostedReviewCreationSnapshot({ requestKey: hostedReviewCreationRequestKey, + contextKey: requestContextKey, repoId: repo.id, worktreeId: activeWorktreeId, branch, + requestStartedAt, + completedAt: Date.now(), + gitFingerprint: requestGitFingerprint, data: result }) } }) .catch(() => { - if (!stale) { - setHostedReviewCreationSnapshot(null) - } + // Why: a transient GitHub outage makes the existing-review lookup inside + // eligibility rethrow. Do NOT tear down the last confirmed snapshot — a + // clean, already-confirmed composer must survive the outage. Confirmed + // readiness still gates it on context + git-fingerprint + freshness, so a + // stale snapshot can never open a never-confirmed Create. }) return () => { stale = true } }, [ + panelContextKey, + runtimeEnvironmentId, + repoConnectionId, activeWorktreeId, activeWorktreePath, branch, @@ -1498,6 +1717,8 @@ export default function ChecksPanel(): React.JSX.Element { gitStatusReadyForPanelContext, hasUncommittedChanges, hostedReviewCreationRequestKey, + eligibilityRefreshNonce, + localExecutionScope, isFolder, isPanelVisible, linkedPR, @@ -2181,6 +2402,10 @@ export default function ChecksPanel(): React.JSX.Element { if (isCurrentRequest()) { refreshInFlightRef.current = false setIsRefreshing(false) + // Why: force a fresh eligibility request whose start time is after any + // current hard-refresh error, so a resolved auth/permission failure can + // clear the sticky hard error even when Git state did not change. + setEligibilityRefreshNonce((value) => value + 1) } } }, [ @@ -3263,6 +3488,51 @@ export default function ChecksPanel(): React.JSX.Element { pushBranch ]) + // Sync the branch with its upstream using the same runtime-scoped operation and + // push target as Source Control, so a `needs_sync` create blocker is actionable + // from the Checks panel instead of showing guidance with no button. + const handleSyncBranch = useCallback(async (): Promise => { + if (!activeWorktreeId || !activeWorktree?.path || isSyncingBranch || isRemoteOperationActive) { + return + } + const connectionId = activeConnectionId ?? undefined + setIsSyncingBranch(true) + try { + await syncBranch( + activeWorktreeId, + activeWorktree.path, + connectionId, + activeWorktree.pushTarget, + { + runtimeTargetSettings: ownerSettings + } + ) + await fetchUpstreamStatus( + activeWorktreeId, + activeWorktree.path, + connectionId, + activeWorktree.pushTarget, + { runtimeTargetSettings: ownerSettings } + ) + } catch { + // Store remote actions already surface the sync failure toast. + } finally { + // Why: syncing changes ahead/behind, which the panel uses to choose between + // Sync, Create PR, and Push & Create PR. + setGitStatusRefreshNonce((value) => value + 1) + setIsSyncingBranch(false) + } + }, [ + activeWorktree, + activeWorktreeId, + activeConnectionId, + fetchUpstreamStatus, + isSyncingBranch, + isRemoteOperationActive, + ownerSettings, + syncBranch + ]) + const handlePullRequestCreated = useCallback( async (result: { provider: HostedReviewProvider @@ -3581,17 +3851,79 @@ export default function ChecksPanel(): React.JSX.Element { hasUpstream: publishActionRemoteStatus?.hasUpstream, hasCurrentBranch: Boolean(branch) })) - const emptyStateCopy = getChecksPanelEmptyStateCopy({ + // Non-GitHub providers (GitLab/Bitbucket/Azure/Gitea) have no typed GitHub + // refresh state; only feed the GitHub refresh classification into the selector + // for GitHub contexts. When a hard error is still active (sticky across + // auto-retries), surface it as the refresh state so the hard-error card and + // composer suppression persist even while a queued/in-flight retry is + // temporarily the live status. + const emptyRefreshInput = !isGitHubReviewContext + ? undefined + : checksPanelHasHardRefreshError && hardRefreshError + ? { status: 'error' as const, errorType: hardRefreshError.errorType } + : prRefreshState + ? { + status: prRefreshState.status, + errorType: prRefreshState.errorType, + skippedReason: prRefreshState.skippedReason, + nextAutoRetryAt: prRefreshState.nextAutoRetryAt, + retryDisabledUntil: prRefreshState.retryDisabledUntil + } + : undefined + const emptyGitStatusPhase: 'loading' | 'ready' | 'error' = + gitStatusInputs.hasUncommittedChanges !== undefined + ? 'ready' + : gitStatusProbeErrorContextKey === panelContextKey + ? 'error' + : 'loading' + const reviewState = getChecksPanelReviewState({ operationLabel, - prRefreshStatus: emptyReviewIsGitLab ? undefined : prRefreshState?.status, - prRefreshErrorType: emptyReviewIsGitLab ? undefined : prRefreshState?.errorType, - hostedReviewBlockedReason: hostedReviewCreation?.blockedReason, - hasUpstream: publishActionRemoteStatus?.hasUpstream, - hasCurrentBranch: Boolean(branch), reviewLabel: emptyReviewLabel, reviewShortLabel: emptyReviewShortLabel, - hasAmbiguousGitHubHostedReview + providerName: hostedReviewCreateCopy.providerName, + isGitHubProvider: hostedReviewCreateProvider === 'github', + reviewLookup: checksPanelReviewLookup, + openReviewUrl: checksPanelReviewLookupResult.openReviewUrl, + eligibilityBlockedReason: hostedReviewCreation?.blockedReason, + // Confirmed readiness (not the live create gate) drives composer mode so + // the selector matches the preserved-composer semantics. + confirmedReadiness: confirmedReadiness.confirmed, + confirmedNeedsPush: confirmedReadiness.needsPush, + refresh: emptyRefreshInput, + gitStatusPhase: emptyGitStatusPhase, + hasUpstream: publishActionRemoteStatus?.hasUpstream, + hasCurrentBranch: Boolean(branch) }) + const emptyStateCopy = { title: reviewState.title, description: reviewState.description } + const reviewStateAutoRetryText = + reviewState.autoRetryAt !== undefined && reviewState.autoRetryAt > Date.now() + ? translate( + 'auto.components.right.sidebar.ChecksPanel.review.auto_retry', + 'Orca will retry at {{time}}.', + { time: new Date(reviewState.autoRetryAt).toLocaleTimeString() } + ) + : null + const reviewRecoveryRetryDisabled = + reviewState.retryDisabledUntil !== undefined && Date.now() < reviewState.retryDisabledUntil + const reviewRecoveryLabelIsRefresh = reviewState.recovery.includes('refresh') + // Only offer Retry/Refresh when the selector's recovery set includes it; + // states like git-status loading, bare, or archived expose no recovery. + const reviewShowRetryOrRefresh = + reviewState.recovery.includes('retry') || reviewRecoveryLabelIsRefresh + const reviewShowOpenReview = + reviewState.recovery.includes('open_review') && Boolean(reviewState.openReviewUrl) + // The selector is the authority for the Sync workflow action; a `needs_sync` + // create blocker must expose Sync Branch, not just guidance copy. + const reviewShowSyncBranch = reviewState.workflowAction === 'sync_branch' + // The action row must render whenever any action is available — recovery + // actions (Retry/Refresh/Open Review) are shown independently of the composer + // so a preserved confirmed composer still exposes a working Retry during a + // transient failure. + const reviewShowActionRow = + canPublishBranch || + reviewShowSyncBranch || + (reviewShowOpenReview && Boolean(reviewState.openReviewUrl)) || + reviewShowRetryOrRefresh return (
{detachedHeadDisplay && ( @@ -3601,6 +3933,12 @@ export default function ChecksPanel(): React.JSX.Element { )}
{emptyStateCopy.title}
{emptyStateCopy.description}
+ {reviewState.detail ? ( +
{reviewState.detail}
+ ) : null} + {reviewStateAutoRetryText ? ( +
{reviewStateAutoRetryText}
+ ) : null} {!operationInProgress && createComposerOpen ? (
) : null} - {!operationInProgress && (!createComposerOpen || canPublishBranch) && ( + {!operationInProgress && reviewShowActionRow && (
{canPublishBranch && ( + )} + {reviewShowOpenReview && reviewState.openReviewUrl ? ( + ) : null} + {reviewShowRetryOrRefresh ? ( + ) : null}
diff --git a/src/renderer/src/components/right-sidebar/CommitArea.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.test.tsx index b360795e6..a34540f78 100644 --- a/src/renderer/src/components/right-sidebar/CommitArea.test.tsx +++ b/src/renderer/src/components/right-sidebar/CommitArea.test.tsx @@ -448,7 +448,8 @@ describe('CommitArea', () => { review: null, canCreate: false, blockedReason: 'dirty', - nextAction: 'commit' + nextAction: 'commit', + reviewLookupOutcome: 'not_found' } }) const markup = renderCommitArea(baseProps(input)) @@ -481,7 +482,8 @@ describe('CommitArea', () => { review: null, canCreate: false, blockedReason: 'needs_push', - nextAction: 'push' + nextAction: 'push', + reviewLookupOutcome: 'not_found' } }) const markup = renderCommitArea(baseProps(input)) diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index 665fd7419..a4eaf4250 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -3333,10 +3333,8 @@ function SourceControlInner(): React.JSX.Element { if (stale) { return } - // Why: a failed/timed-out remote probe must not leave an inert disabled - // button. When the local git status determines a blocker (dirty, no - // upstream, needs push/sync), surface the actionable preparation intent; - // otherwise fall back to the retryable failed state. + // Why: a failed remote probe can provide branch guidance, but it cannot + // authorize hosted-review creation. const localBlocker = buildLocalBlockerHostedReviewCreationEligibility( resolveCurrentHostedReviewCreationProvider(), { diff --git a/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.test.ts b/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.test.ts deleted file mode 100644 index db51fd6ef..000000000 --- a/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { hasAmbiguousGitHubHostedReviewForChecksPanel } from './checks-panel-ambiguous-github-review' - -describe('hasAmbiguousGitHubHostedReviewForChecksPanel', () => { - it('treats missing PR cache as ambiguous when a GitHub hosted review exists', () => { - expect( - hasAmbiguousGitHubHostedReviewForChecksPanel({ - hostedReview: { provider: 'github' }, - prCacheEntry: undefined, - prCacheKey: 'repo::feature' - }) - ).toBe(true) - }) - - it('treats cached no-PR data as ambiguous when a GitHub hosted review exists', () => { - expect( - hasAmbiguousGitHubHostedReviewForChecksPanel({ - hostedReview: { provider: 'github' }, - prCacheEntry: { data: null }, - prCacheKey: 'repo::feature' - }) - ).toBe(true) - }) - - it('does not treat existing PR cache data as ambiguous', () => { - expect( - hasAmbiguousGitHubHostedReviewForChecksPanel({ - hostedReview: { provider: 'github' }, - prCacheEntry: { data: { number: 12 } }, - prCacheKey: 'repo::feature' - }) - ).toBe(false) - }) - - it('does not treat non-GitHub hosted reviews as ambiguous', () => { - expect( - hasAmbiguousGitHubHostedReviewForChecksPanel({ - hostedReview: { provider: 'gitlab' }, - prCacheEntry: { data: null }, - prCacheKey: 'repo::feature' - }) - ).toBe(false) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.ts b/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.ts deleted file mode 100644 index bca25a7a2..000000000 --- a/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.ts +++ /dev/null @@ -1,22 +0,0 @@ -type HostedReviewProviderLike = { - provider?: string | null -} - -type PRCacheEntryLike = { - data?: unknown -} - -/** - * Flags GitHub-hosted review metadata whose matching PR cache may still be unknown. - */ -export function hasAmbiguousGitHubHostedReviewForChecksPanel(input: { - hostedReview: HostedReviewProviderLike | null | undefined - prCacheEntry: PRCacheEntryLike | null | undefined - prCacheKey: string -}): boolean { - return ( - input.hostedReview?.provider === 'github' && - input.prCacheKey !== '' && - input.prCacheEntry?.data == null - ) -} diff --git a/src/renderer/src/components/right-sidebar/checks-panel-blocker-copy.ts b/src/renderer/src/components/right-sidebar/checks-panel-blocker-copy.ts new file mode 100644 index 000000000..1313afa7e --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel-blocker-copy.ts @@ -0,0 +1,220 @@ +import type { HostedReviewCreationBlockedReason } from '../../../../shared/hosted-review' +import { translate } from '@/i18n/i18n' +import { + autoRetrySchedule, + capitalizeReviewLabel, + isHardRefreshError, + type ChecksPanelRecoveryAction, + type ChecksPanelReviewState, + type ChecksPanelReviewStateInput +} from './checks-panel-review-state-model' +import { concurrentLookupDetail } from './checks-panel-review-copy' + +type KeyedCopy = { key: string; fallback: string } + +const SAFETY_COPY: Record< + | 'detached_head' + | 'dirty' + | 'default_branch' + | 'fork_head_unsupported' + | 'base_not_on_remote' + | 'unsupported_provider', + { title: KeyedCopy; body: KeyedCopy } +> = { + detached_head: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.detached.title', + fallback: 'No current branch' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.detached.body', + fallback: 'Check out a branch before creating a {{reviewLabel}}.' + } + }, + dirty: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.dirty.title', + fallback: 'Commit changes first' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.dirty.body', + fallback: 'Commit or stash your changes before creating a {{reviewLabel}}.' + } + }, + default_branch: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.default_branch.title', + fallback: 'On the default branch' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.default_branch.body', + fallback: 'Switch to a feature branch before creating a {{reviewLabel}}.' + } + }, + fork_head_unsupported: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.fork.title', + fallback: 'Fork head unsupported' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.fork.body', + fallback: 'Orca cannot create a {{reviewLabel}} from this fork head here.' + } + }, + base_not_on_remote: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.base_missing.title', + fallback: 'Base branch not on remote' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.base_missing.body', + fallback: + "This branch's base is not on the remote yet, so a {{reviewLabel}} cannot target it." + } + }, + unsupported_provider: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.unsupported.title', + fallback: '{{reviewLabelCap}} not supported here' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.unsupported.body', + fallback: 'This repository provider does not support creating a {{reviewLabel}} from Orca.' + } + } +} + +export function safetyBlockerState( + input: ChecksPanelReviewStateInput, + reason: NonNullable +): ChecksPanelReviewState { + const { reviewLabel } = input + if (reason === 'existing_review') { + // Same family as positive evidence — offer trusted Open Review, never Create. + return { + renderReview: false, + title: translate( + 'auto.components.right.sidebar.checks.panel.review.existing.title', + '{{reviewLabelCap}} already exists', + { reviewLabelCap: capitalizeReviewLabel(reviewLabel) } + ), + description: translate( + 'auto.components.right.sidebar.checks.panel.review.existing.body', + 'Orca found an existing {{reviewLabel}} for this branch.', + { reviewLabel } + ), + composerMode: 'hidden', + workflowAction: null, + recovery: input.openReviewUrl ? ['open_review'] : [], + openReviewUrl: input.openReviewUrl + } + } + const copy = SAFETY_COPY[reason as keyof typeof SAFETY_COPY] ?? SAFETY_COPY.unsupported_provider + const vars = { reviewLabel, reviewLabelCap: capitalizeReviewLabel(reviewLabel) } + return { + renderReview: false, + title: translate(copy.title.key, copy.title.fallback, vars), + description: translate(copy.body.key, copy.body.fallback, vars), + composerMode: 'hidden', + workflowAction: null, + recovery: [] + } +} + +const BRANCH_BLOCKER_COPY: Record< + 'no_upstream' | 'needs_sync' | 'auth_required', + { title: KeyedCopy; body: KeyedCopy; workflow: ChecksPanelReviewState['workflowAction'] } +> = { + no_upstream: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.no_upstream.title', + fallback: 'No upstream configured' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.no_upstream.body', + fallback: 'Publish this branch to set its upstream before creating a {{reviewLabel}}.' + }, + workflow: 'publish_branch' + }, + needs_sync: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.needs_sync.title', + fallback: 'Branch needs to sync' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.needs_sync.body', + fallback: 'Sync this branch with its upstream before creating a {{reviewLabel}}.' + }, + workflow: 'sync_branch' + }, + auth_required: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.auth_required.title', + fallback: 'Connect {{provider}}' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.auth_required.body', + fallback: + '{{provider}} must be connected in this environment before Orca can create a {{reviewLabel}}.' + }, + workflow: null + } +} + +export function branchBlockerState( + input: ChecksPanelReviewStateInput, + reason: NonNullable +): ChecksPanelReviewState { + const { reviewLabel, providerName } = input + const detail = concurrentLookupDetail(input) + const schedule = detail ? autoRetrySchedule(input) : {} + // Positive-unresolved evidence with a trusted URL must still expose Open Review + // beneath the blocker (Create/Push & Create stay suppressed). Retry is offered + // whenever a concurrent lookup failure produced a detail sentence. + const canOpenReview = input.reviewLookup === 'positive_unresolved' && Boolean(input.openReviewUrl) + const lookupRecovery: ChecksPanelRecoveryAction[] = [ + ...(canOpenReview ? (['open_review'] as ChecksPanelRecoveryAction[]) : []), + ...(detail ? (['retry'] as ChecksPanelRecoveryAction[]) : []) + ] + const openReviewUrl = canOpenReview ? input.openReviewUrl : undefined + const vars = { reviewLabel, provider: providerName } + + if (reason === 'needs_push') { + // Push & Create unless review evidence or a hard error blocks create. + const blocked = + input.reviewLookup === 'positive_unresolved' || + isHardRefreshError(input.refresh) || + !input.confirmedReadiness + return { + renderReview: false, + title: translate( + 'auto.components.right.sidebar.checks.panel.review.needs_push.title', + 'Branch has unpushed commits' + ), + description: translate( + 'auto.components.right.sidebar.checks.panel.review.needs_push.body', + 'Push the latest commits before creating a {{reviewLabel}}.', + { reviewLabel } + ), + detail, + composerMode: blocked ? 'hidden' : 'needs_push_open', + workflowAction: blocked ? null : 'push_and_create', + recovery: lookupRecovery, + openReviewUrl, + ...schedule + } + } + + const copy = BRANCH_BLOCKER_COPY[reason as keyof typeof BRANCH_BLOCKER_COPY] + return { + renderReview: false, + title: translate(copy.title.key, copy.title.fallback, vars), + description: translate(copy.body.key, copy.body.fallback, vars), + detail, + composerMode: 'hidden', + workflowAction: copy.workflow, + recovery: lookupRecovery, + openReviewUrl, + ...schedule + } +} diff --git a/src/renderer/src/components/right-sidebar/checks-panel-empty-state.test.ts b/src/renderer/src/components/right-sidebar/checks-panel-empty-state.test.ts index 7e3f8ca3c..941012d7a 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-empty-state.test.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-empty-state.test.ts @@ -1,281 +1,263 @@ import { describe, expect, it } from 'vitest' import { - getChecksPanelEmptyStateCopy, - shouldShowChecksPanelPublishBranchAction + getChecksPanelReviewState, + shouldShowChecksPanelPublishBranchAction, + type ChecksPanelReviewStateInput } from './checks-panel-empty-state' -describe('getChecksPanelEmptyStateCopy', () => { - it('shows a local-only branch message instead of a refresh error', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - hostedReviewBlockedReason: 'no_upstream', - hasUpstream: false - }) - ).toEqual({ - title: 'Branch not published', - description: 'Publish this branch before creating a pull request.' - }) +function input(overrides: Partial = {}): ChecksPanelReviewStateInput { + return { + operationLabel: null, + reviewLabel: 'pull request', + reviewShortLabel: 'PR', + providerName: 'GitHub', + isGitHubProvider: true, + reviewLookup: 'unknown', + openReviewUrl: null, + eligibilityBlockedReason: undefined, + confirmedReadiness: false, + confirmedNeedsPush: false, + refresh: undefined, + gitStatusPhase: 'ready', + hasUpstream: true, + hasCurrentBranch: true, + ...overrides + } +} + +describe('getChecksPanelReviewState — no-review honesty', () => { + it('only renders "No pull request found" for an accepted no-review result', () => { + expect(getChecksPanelReviewState(input({ reviewLookup: 'not_found' })).title).toBe( + 'No pull request found' + ) }) - it('uses remote status as a fallback before eligibility finishes', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - hostedReviewBlockedReason: undefined, - hasUpstream: false - }).title - ).toBe('Branch not published') + it('never says "No pull request found" for a missing/unknown lookup', () => { + const state = getChecksPanelReviewState(input({ reviewLookup: 'unknown' })) + expect(state.title).not.toContain('No pull request found') + expect(state.title).toBe('Pull request status unavailable') }) - it('does not show unpublished branch copy when HEAD is detached', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - hostedReviewBlockedReason: 'no_upstream', - hasUpstream: false, - hasCurrentBranch: false - }).title - ).toBe('Could not refresh pull request') + it('never says "No pull request found" for a paused refresh', () => { + const state = getChecksPanelReviewState( + input({ reviewLookup: 'unknown', refresh: { status: 'paused' } }) + ) + expect(state.title).toBe('GitHub refresh paused') }) - it('uses remote status as a fallback when eligibility has no concrete blocker', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - hostedReviewBlockedReason: null, - hasUpstream: false - }).title - ).toBe('Branch not published') + it('never says "No pull request found" for a skipped refresh', () => { + const state = getChecksPanelReviewState( + input({ reviewLookup: 'unknown', refresh: { status: 'skipped', skippedReason: 'bare' } }) + ) + expect(state.title).toBe('Bare repository') }) - it('shows unpushed commits before a refresh error', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - hostedReviewBlockedReason: 'needs_push', - hasUpstream: true - }) - ).toEqual({ - title: 'Branch has unpushed commits', - description: 'Push your branch before creating a pull request.' - }) - }) - - it('shows unpublished branch copy even when PR provider eligibility has another blocker', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - hostedReviewBlockedReason: 'unsupported_provider', - hasUpstream: false - }).title - ).toBe('Branch not published') - }) - - it('keeps the generic refresh error when no local branch action is known', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - hostedReviewBlockedReason: null, - hasUpstream: true - }).title - ).toBe('Could not refresh pull request') - }) - - it('uses merge request copy for GitLab review contexts', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: undefined, - hostedReviewBlockedReason: 'unsupported_provider', - hasUpstream: true, + it('uses merge request wording for GitLab', () => { + const state = getChecksPanelReviewState( + input({ reviewLabel: 'merge request', - reviewShortLabel: 'MR' + reviewShortLabel: 'MR', + providerName: 'GitLab', + isGitHubProvider: false, + reviewLookup: 'not_found' }) - ).toEqual({ - title: 'No merge request found', - description: 'Create a merge request to start checks and review.' - }) + ) + expect(state.title).toBe('No merge request found') + }) +}) + +describe('getChecksPanelReviewState — precedence', () => { + it('operation in progress wins', () => { + expect( + getChecksPanelReviewState(input({ operationLabel: 'Rebase', reviewLookup: 'not_found' })) + .title + ).toBe('Rebase in progress') }) - it('uses neutral copy when GitHub hosted-review data exists without PR cache', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: undefined, - hostedReviewBlockedReason: null, - hasUpstream: true, - hasAmbiguousGitHubHostedReview: true + it('renderReview for found lookup', () => { + expect(getChecksPanelReviewState(input({ reviewLookup: 'found' })).renderReview).toBe(true) + }) + + it('positive_unresolved blocks create and offers Open Review', () => { + const state = getChecksPanelReviewState( + input({ reviewLookup: 'positive_unresolved', openReviewUrl: 'https://x/pull/1' }) + ) + expect(state.title).toBe('Pull request details unavailable') + expect(state.composerMode).toBe('hidden') + expect(state.workflowAction).toBeNull() + expect(state.recovery).toContain('open_review') + expect(state.openReviewUrl).toBe('https://x/pull/1') + }) + + it('offers Open Review under a branch blocker when positive evidence has a trusted URL', () => { + // A concurrent branch blocker owns the copy but must not swallow the known + // review: Open Review is exposed while Create / Push & Create stay suppressed. + const state = getChecksPanelReviewState( + input({ + reviewLookup: 'positive_unresolved', + openReviewUrl: 'https://x/pull/7', + eligibilityBlockedReason: 'no_upstream', + hasUpstream: false }) - ).toEqual({ - title: 'Pull request status unavailable', - description: 'Refresh GitHub status for this branch to load checks and review.' - }) + ) + expect(state.title).toBe('No upstream configured') + expect(state.workflowAction).toBe('publish_branch') + expect(state.composerMode).toBe('hidden') + expect(state.recovery).toContain('open_review') + expect(state.openReviewUrl).toBe('https://x/pull/7') }) - it('does not show no-PR copy for paused ambiguous GitHub hosted-review data', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'paused', - hostedReviewBlockedReason: null, - hasUpstream: true, - hasAmbiguousGitHubHostedReview: true - }).title - ).toBe('Pull request status unavailable') + it('needs_sync emits a sync_branch workflow action for the renderer', () => { + const state = getChecksPanelReviewState(input({ eligibilityBlockedReason: 'needs_sync' })) + expect(state.title).toBe('Branch needs to sync') + expect(state.workflowAction).toBe('sync_branch') }) - it('keeps refresh errors for ambiguous GitHub hosted-review data', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - hostedReviewBlockedReason: null, - hasUpstream: true, - hasAmbiguousGitHubHostedReview: true - }).title - ).toBe('Could not refresh pull request') - }) - - it('uses neutral copy for ambiguous GitHub hosted-review data before unpublished branch copy', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: undefined, - hostedReviewBlockedReason: 'no_upstream', + it('branch blocker (no_upstream) ranks above a refresh error', () => { + const state = getChecksPanelReviewState( + input({ + eligibilityBlockedReason: 'no_upstream', hasUpstream: false, - hasAmbiguousGitHubHostedReview: true - }).title - ).toBe('Pull request status unavailable') - }) - - it('uses neutral copy for ambiguous GitHub hosted-review data before remote fallback publish copy', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: undefined, - hostedReviewBlockedReason: undefined, - hasUpstream: false, - hasAmbiguousGitHubHostedReview: true - }).title - ).toBe('Pull request status unavailable') - }) - - it('uses neutral copy for ambiguous GitHub hosted-review data before unpushed commit copy', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: undefined, - hostedReviewBlockedReason: 'needs_push', - hasUpstream: true, - hasAmbiguousGitHubHostedReview: true - }).title - ).toBe('Pull request status unavailable') - }) - - // Regression: a local-only branch with an ambiguous GitHub hosted-review card - // flip-flopped between "Branch not published" (during an active PR refresh) and - // "Pull request status unavailable" (while idle) as background refreshes cycled - // the status. The ambiguous copy must stay stable across the whole lifecycle. - it('keeps stable ambiguous copy while a PR refresh is queued on an unpublished branch', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'queued', - hostedReviewBlockedReason: 'no_upstream', - hasUpstream: false, - hasAmbiguousGitHubHostedReview: true - }).title - ).toBe('Pull request status unavailable') - }) - - it('keeps stable ambiguous copy while a PR refresh is in-flight on an unpublished branch', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'in-flight', - hostedReviewBlockedReason: undefined, - hasUpstream: false, - hasAmbiguousGitHubHostedReview: true - }).title - ).toBe('Pull request status unavailable') - }) - - it('does not fall back to unpublished-branch copy on refresh error for ambiguous data', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - hostedReviewBlockedReason: 'no_upstream', - hasUpstream: false, - hasAmbiguousGitHubHostedReview: true - }).title - ).toBe('Could not refresh pull request') - }) - - it('attributes a 5xx outage to GitHub instead of the generic refresh error', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - prRefreshErrorType: 'server_error', - hostedReviewBlockedReason: null, - hasUpstream: true + refresh: { status: 'error', errorType: 'auth' } }) - ).toEqual({ + ) + expect(state.title).toBe('No upstream configured') + expect(state.workflowAction).toBe('publish_branch') + // Hard error concurrent with the blocker: detail appended, create suppressed. + expect(state.detail).toBe( + 'Orca also could not confirm whether this branch already has a pull request.' + ) + }) + + it('hard refresh error hides the composer', () => { + const state = getChecksPanelReviewState( + input({ refresh: { status: 'error', errorType: 'auth' } }) + ) + expect(state.title).toBe('GitHub authentication failed') + expect(state.composerMode).toBe('hidden') + expect(state.workflowAction).toBeNull() + }) + + it('hard refresh error overrides an accepted no-review', () => { + const state = getChecksPanelReviewState( + input({ reviewLookup: 'not_found', refresh: { status: 'error', errorType: 'permission' } }) + ) + expect(state.title).toBe('GitHub access denied') + }) +}) + +describe('getChecksPanelReviewState — composer preserve', () => { + it('accepted no-review with confirmed readiness opens the composer', () => { + const state = getChecksPanelReviewState( + input({ reviewLookup: 'not_found', confirmedReadiness: true }) + ) + expect(state.composerMode).toBe('confirmed_open') + expect(state.workflowAction).toBe('create') + }) + + it('transient error preserves a confirmed composer', () => { + const state = getChecksPanelReviewState( + input({ confirmedReadiness: true, refresh: { status: 'error', errorType: 'network' } }) + ) + expect(state.composerMode).toBe('confirmed_open') + expect(state.title).toBe('Could not reach GitHub') + }) + + it('attributes a transient 5xx outage to GitHub and preserves a confirmed composer', () => { + const state = getChecksPanelReviewState( + input({ confirmedReadiness: true, refresh: { status: 'error', errorType: 'server_error' } }) + ) + expect(state).toMatchObject({ title: 'GitHub is unavailable', description: - "GitHub's API is temporarily unavailable. This panel reloads automatically once it recovers." + "GitHub's API is temporarily unavailable. This panel reloads automatically once it recovers.", + composerMode: 'confirmed_open', + workflowAction: 'create' }) }) - it('attributes a network failure to GitHub in the ambiguous hosted-review branch', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - prRefreshErrorType: 'network', - hostedReviewBlockedReason: null, - hasUpstream: true, - hasAmbiguousGitHubHostedReview: true - }).title - ).toBe("Can't reach GitHub") - }) - - it('keeps the generic refresh error for non-outage error types', () => { - expect( - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus: 'error', - prRefreshErrorType: 'auth', - hostedReviewBlockedReason: null, - hasUpstream: true - }).title - ).toBe('Could not refresh pull request') - }) - - it('renders a single stable title across a full ambiguous refresh cycle', () => { - const cycle = ['queued', 'in-flight', undefined, 'skipped', 'paused'] as const - const titles = new Set( - cycle.map( - (prRefreshStatus) => - getChecksPanelEmptyStateCopy({ - operationLabel: null, - prRefreshStatus, - hostedReviewBlockedReason: 'no_upstream', - hasUpstream: false, - hasAmbiguousGitHubHostedReview: true - }).title - ) + it('transient error without confirmed readiness never opens a composer', () => { + const state = getChecksPanelReviewState( + input({ confirmedReadiness: false, refresh: { status: 'error', errorType: 'network' } }) ) - expect([...titles]).toEqual(['Pull request status unavailable']) + expect(state.composerMode).toBe('hidden') + }) + + it('needs_push with positive_unresolved never exposes Push & Create', () => { + const state = getChecksPanelReviewState( + input({ + eligibilityBlockedReason: 'needs_push', + reviewLookup: 'positive_unresolved', + confirmedReadiness: true, + confirmedNeedsPush: true + }) + ) + expect(state.composerMode).toBe('hidden') + expect(state.workflowAction).toBeNull() + }) + + it('needs_push with confirmed readiness offers Push & Create', () => { + const state = getChecksPanelReviewState( + input({ + eligibilityBlockedReason: 'needs_push', + reviewLookup: 'not_found', + confirmedReadiness: true, + confirmedNeedsPush: true + }) + ) + expect(state.composerMode).toBe('needs_push_open') + expect(state.workflowAction).toBe('push_and_create') + }) +}) + +describe('getChecksPanelReviewState — schedule', () => { + it('carries auto-retry schedule on the paused row', () => { + const state = getChecksPanelReviewState( + input({ refresh: { status: 'paused', nextAutoRetryAt: 123, retryDisabledUntil: 123 } }) + ) + expect(state.autoRetryAt).toBe(123) + expect(state.retryDisabledUntil).toBe(123) + }) + + it('carries auto-retry schedule on a transient network error', () => { + const state = getChecksPanelReviewState( + input({ refresh: { status: 'error', errorType: 'network', nextAutoRetryAt: 456 } }) + ) + expect(state.autoRetryAt).toBe(456) + expect(state.retryDisabledUntil).toBeUndefined() + }) +}) + +describe('getChecksPanelReviewState — git status', () => { + it('shows loading copy when upstream is unknown', () => { + expect( + getChecksPanelReviewState(input({ gitStatusPhase: 'loading', hasUpstream: undefined })).title + ).toBe('Checking branch status') + }) + + it('shows failed copy when the probe failed and upstream is unknown', () => { + const state = getChecksPanelReviewState( + input({ gitStatusPhase: 'error', hasUpstream: undefined }) + ) + expect(state.title).toBe('Could not check branch status') + expect(state.recovery).toContain('retry') + expect(state.composerMode).toBe('hidden') + }) +}) + +describe('getChecksPanelReviewState — active and skipped', () => { + it('queued shows checking copy', () => { + expect(getChecksPanelReviewState(input({ refresh: { status: 'queued' } })).title).toBe( + 'Checking pull request status' + ) + }) + + it('disconnected host row', () => { + expect( + getChecksPanelReviewState( + input({ refresh: { status: 'skipped', skippedReason: 'disconnected' } }) + ).title + ).toBe('Host disconnected') }) }) @@ -289,21 +271,6 @@ describe('shouldShowChecksPanelPublishBranchAction', () => { ).toBe(true) }) - it('uses remote status even when provider eligibility has a separate blocker', () => { - expect( - shouldShowChecksPanelPublishBranchAction({ - hostedReviewBlockedReason: undefined, - hasUpstream: false - }) - ).toBe(true) - expect( - shouldShowChecksPanelPublishBranchAction({ - hostedReviewBlockedReason: 'unsupported_provider', - hasUpstream: false - }) - ).toBe(true) - }) - it('does not show publish when HEAD is detached', () => { expect( shouldShowChecksPanelPublishBranchAction({ diff --git a/src/renderer/src/components/right-sidebar/checks-panel-empty-state.ts b/src/renderer/src/components/right-sidebar/checks-panel-empty-state.ts index 78dd6610a..6679a57fa 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-empty-state.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-empty-state.ts @@ -1,40 +1,49 @@ import type { HostedReviewCreationBlockedReason } from '../../../../shared/hosted-review' -import type { PRRefreshUpstreamErrorType } from '../../../../shared/types' import { translate } from '@/i18n/i18n' -import { getGitHubUnavailableEmptyStateCopy } from './github-refresh-error-copy' +import { + autoRetrySchedule, + capitalizeReviewLabel, + confirmedComposerMode, + ELIGIBILITY_SAFETY_BLOCKERS, + isBranchBlocker, + isHardRefreshError, + isTransientRefreshFailure, + workflowActionForComposer, + type ChecksPanelReviewState, + type ChecksPanelReviewStateInput +} from './checks-panel-review-state-model' +import { + concurrentLookupDetail, + hardRefreshErrorState, + skippedRefreshState, + transientRefreshState +} from './checks-panel-review-copy' +import { branchBlockerState, safetyBlockerState } from './checks-panel-blocker-copy' -type PRRefreshStatus = 'queued' | 'in-flight' | 'paused' | 'error' | 'skipped' | undefined - -type ChecksPanelEmptyStateInput = { - operationLabel: string | null - prRefreshStatus: PRRefreshStatus - // Why: lets the error empty-state attribute a GitHub outage (5xx/network/rate - // limit) instead of showing generic "could not refresh" copy that reads like - // an Orca bug. - prRefreshErrorType?: PRRefreshUpstreamErrorType - hostedReviewBlockedReason: HostedReviewCreationBlockedReason | undefined - hasUpstream: boolean | undefined - hasCurrentBranch?: boolean - reviewLabel?: 'pull request' | 'merge request' - reviewShortLabel?: 'PR' | 'MR' - hasAmbiguousGitHubHostedReview?: boolean -} - -type ChecksPanelEmptyStateCopy = { - title: string - description: string -} +export type { + ChecksPanelComposerMode, + ChecksPanelWorkflowAction, + ChecksPanelRecoveryAction, + ChecksPanelReviewState, + ChecksPanelRefreshInput, + ChecksPanelReviewStateInput +} from './checks-panel-review-state-model' /** - * Chooses neutral empty-state copy when GitHub review status is still ambiguous. + * One exhaustive selector for the Checks-panel empty state. Copy, composer mode, + * workflow action, and recovery actions are decided together — never in separate + * branches — so an error, pause, skip, or unknown state can never be rendered as + * "No {reviewLabel} found." See docs/design/pr-panel-refresh-guidance.md. */ -export function getChecksPanelEmptyStateCopy( - input: ChecksPanelEmptyStateInput -): ChecksPanelEmptyStateCopy { - const reviewLabel = input.reviewLabel ?? 'pull request' - const reviewShortLabel = input.reviewShortLabel ?? 'PR' +export function getChecksPanelReviewState( + input: ChecksPanelReviewStateInput +): ChecksPanelReviewState { + const { reviewLabel, reviewShortLabel, providerName } = input + + // 0. Operation in progress — never overridden by refresh copy. if (input.operationLabel) { return { + renderReview: false, title: translate( 'auto.components.right.sidebar.checks.panel.empty.state.d77c513c1e', '{{value0}} in progress', @@ -44,142 +53,186 @@ export function getChecksPanelEmptyStateCopy( 'auto.components.right.sidebar.checks.panel.empty.state.05e4aec17b', '{{value0}} checks will be available after the operation completes', { value0: reviewShortLabel } - ) + ), + composerMode: 'hidden', + workflowAction: null, + recovery: [] } } - const blockedReason = input.hostedReviewBlockedReason - // Why: a GitHub hosted-review card with no cached PR is ambiguous. Resolve the - // whole empty state here so the copy stays stable across a background PR - // refresh's lifecycle (idle/queued/in-flight/paused/skipped). Previously only - // the idle statuses were handled and active ones fell through to the - // publish-branch branch, so the panel flip-flopped between "Branch not - // published" and "Pull request status unavailable" as refreshes cycled. Only a - // hard refresh error still surfaces a distinct — but equally stable — message. - if (input.hasAmbiguousGitHubHostedReview === true) { - if (input.prRefreshStatus === 'error') { - return ( - getGitHubUnavailableEmptyStateCopy(input.prRefreshErrorType) ?? { - title: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.5f478ab3d3', - 'Could not refresh pull request' - ), - description: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.2bdd7aaf2d', - 'GitHub status could not be refreshed. Existing cached data was preserved.' - ) - } - ) - } + // 1. Renderable review wins over every empty state. + if (input.reviewLookup === 'found') { return { + renderReview: true, + title: '', + description: '', + composerMode: 'hidden', + workflowAction: null, + recovery: [] + } + } + + const blockedReason = input.eligibilityBlockedReason + + // 2. Eligibility safety states own their guidance (existing_review is a hard + // create block in the positive-evidence family). + if (blockedReason && ELIGIBILITY_SAFETY_BLOCKERS.has(blockedReason)) { + return safetyBlockerState(input, blockedReason) + } + + // 3. Positive unresolved review evidence: never offer Create / Push & Create. + if (input.reviewLookup === 'positive_unresolved' && !isBranchBlocker(blockedReason)) { + return { + renderReview: false, title: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.3322603418', - 'Pull request status unavailable' + 'auto.components.right.sidebar.checks.panel.review.positive.title', + '{{reviewLabelCap}} details unavailable', + { reviewLabelCap: capitalizeReviewLabel(reviewLabel) } ), description: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.b597440265', - 'Refresh GitHub status for this branch to load checks and review.' - ) + 'auto.components.right.sidebar.checks.panel.review.positive.body', + 'Orca has saved {{reviewLabel}} information for this branch but could not confirm its current status.', + { reviewLabel } + ), + composerMode: 'hidden', + workflowAction: null, + recovery: input.openReviewUrl ? ['open_review', 'retry'] : ['retry'], + openReviewUrl: input.openReviewUrl } } - if ( - shouldShowChecksPanelPublishBranchAction({ - hostedReviewBlockedReason: blockedReason, - hasUpstream: input.hasUpstream, - hasCurrentBranch: input.hasCurrentBranch - }) - ) { - // Why: a local-only branch cannot have GitHub PR status yet; surfacing a - // refresh error here makes a normal pre-publish state look broken. + // 4. Actionable creation blockers (publish / sync / auth / needs_push). + if (isBranchBlocker(blockedReason)) { + return branchBlockerState( + input, + blockedReason as NonNullable + ) + } + // A ready Git status reporting no upstream is a publish state even before + // eligibility resolves. `hasUpstream === undefined` is unknown, never false. + if (input.gitStatusPhase === 'ready' && input.hasUpstream === false && input.hasCurrentBranch) { + return branchBlockerState(input, 'no_upstream') + } + + // 5. Hard refresh error with no blocker above → hide composer until cleared. + if (isHardRefreshError(input.refresh)) { + return hardRefreshErrorState(input) + } + + // 6. Accepted no-review for the exact context. + if (input.reviewLookup === 'not_found') { + const detail = isTransientRefreshFailure(input.refresh) + ? concurrentLookupDetail(input) + : undefined + const mode = confirmedComposerMode(input) return { + renderReview: false, title: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.41252bc53f', - 'Branch not published' + 'auto.components.right.sidebar.checks.panel.review.no_review.title', + 'No {{reviewLabel}} found', + { reviewLabel } ), description: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.f8543140cc', - 'Publish this branch before creating a {{value0}}.', - { value0: reviewLabel } - ) + 'auto.components.right.sidebar.checks.panel.review.no_review.body', + 'Create a {{reviewLabel}} to start checks and review.', + { reviewLabel } + ), + detail, + composerMode: mode, + workflowAction: workflowActionForComposer(mode), + recovery: detail ? ['retry'] : ['refresh'], + ...(detail ? autoRetrySchedule(input) : {}) } } - if (blockedReason === 'needs_push') { + // 7. Transient classified error / rate-limit pause with no accepted result. + if (isTransientRefreshFailure(input.refresh)) { + const mode = confirmedComposerMode(input) + return transientRefreshState(input, mode, workflowActionForComposer(mode)) + } + + // 8. Active refresh (queued / in-flight) with no accepted result. + if (input.refresh?.status === 'queued' || input.refresh?.status === 'in-flight') { + const mode = confirmedComposerMode(input) return { + renderReview: false, title: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.76e15946a9', - 'Branch has unpushed commits' + 'auto.components.right.sidebar.checks.panel.review.active.title', + 'Checking {{reviewLabel}} status', + { reviewLabel } ), description: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.6ce9d4e069', - 'Push your branch before creating a {{value0}}.', - { value0: reviewLabel } - ) + 'auto.components.right.sidebar.checks.panel.review.active.body', + 'Orca is checking {{provider}} for a {{reviewLabel}} on this branch.', + { reviewLabel, provider: providerName } + ), + composerMode: mode, + workflowAction: workflowActionForComposer(mode), + recovery: [] } } - switch (input.prRefreshStatus) { - case 'error': - return ( - getGitHubUnavailableEmptyStateCopy(input.prRefreshErrorType) ?? { - title: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.5f478ab3d3', - 'Could not refresh pull request' - ), - description: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.2bdd7aaf2d', - 'GitHub status could not be refreshed. Existing cached data was preserved.' - ) - } - ) - case 'queued': - return { - title: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.938b5606a6', - 'Checking for pull request' - ), - description: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.6ba2440770', - 'Waiting to refresh GitHub status for this branch' - ) - } - case 'in-flight': - return { - title: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.938b5606a6', - 'Checking for pull request' - ), - description: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.3d4af82ff4', - 'Refreshing GitHub status for this branch' - ) - } - case 'paused': - return { - title: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.7c299df37b', - 'No pull request found' - ), - description: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.d372072df1', - 'GitHub refresh is paused by the current rate-limit budget' - ) - } - case 'skipped': - case undefined: - return { - title: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.13e1c7d5ed', - 'No {{value0}} found', - { value0: reviewLabel } - ), - description: translate( - 'auto.components.right.sidebar.checks.panel.empty.state.5b0cfae9a5', - 'Create a {{value0}} to start checks and review.', - { value0: reviewLabel } - ) - } + // 9. Git status loading / failure when upstream is still unknown. + if (input.gitStatusPhase === 'loading' && input.hasUpstream === undefined) { + return { + renderReview: false, + title: translate( + 'auto.components.right.sidebar.checks.panel.review.git_loading.title', + 'Checking branch status' + ), + description: translate( + 'auto.components.right.sidebar.checks.panel.review.git_loading.body', + 'Orca is checking this branch before showing create or publish actions.' + ), + composerMode: 'hidden', + workflowAction: null, + recovery: [] + } + } + if (input.gitStatusPhase === 'error' && input.hasUpstream === undefined) { + return { + renderReview: false, + title: translate( + 'auto.components.right.sidebar.checks.panel.review.git_error.title', + 'Could not check branch status' + ), + description: translate( + 'auto.components.right.sidebar.checks.panel.review.git_error.body', + "Orca could not confirm this branch's upstream from this environment. Retry before publishing or creating a {{reviewLabel}}.", + { reviewLabel } + ), + composerMode: 'hidden', + workflowAction: null, + recovery: ['retry'] + } + } + + // 10. Skipped structural reasons and missing / unknown — status unavailable. + if (input.refresh?.status === 'skipped' && input.refresh.skippedReason) { + if (input.refresh.skippedReason === 'rate-limit') { + const mode = confirmedComposerMode(input) + return transientRefreshState(input, mode, workflowActionForComposer(mode)) + } + const skipped = skippedRefreshState(input, input.refresh.skippedReason) + if (skipped) { + return skipped + } + } + return { + renderReview: false, + title: translate( + 'auto.components.right.sidebar.checks.panel.review.unknown.title', + '{{reviewLabelCap}} status unavailable', + { reviewLabelCap: capitalizeReviewLabel(reviewLabel) } + ), + description: translate( + 'auto.components.right.sidebar.checks.panel.review.unknown.body', + 'Orca has not confirmed the {{reviewLabel}} status for this branch. Retry to check again.', + { reviewLabel } + ), + composerMode: 'hidden', + workflowAction: null, + recovery: ['retry'] } } diff --git a/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.ts b/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.ts index 897b93b3e..78063f3b2 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.ts @@ -13,6 +13,10 @@ export type ChecksPanelGitStatusContextInput = { runtimeEnvironmentId: string | null repoConnectionId: string | null pushTarget: GitPushTarget | null | undefined + // Local execution host variant (`wsl:{distro}` vs `host`) so a Windows-host + // result never authorizes a WSL context (or another distro), and vice versa. + // Null for SSH/runtime contexts, which are already scoped by their host ids. + localExecutionScope?: string | null } export type ChecksPanelGitStatusSnapshot = { @@ -60,6 +64,7 @@ export function buildChecksPanelGitStatusContextKey( linkedGiteaPR: input.linkedGiteaPR ?? null, runtimeEnvironmentId: input.runtimeEnvironmentId ?? '', repoConnectionId: input.repoConnectionId ?? '', + localExecutionScope: input.localExecutionScope ?? null, pushTarget: input.pushTarget ? { remoteName: input.pushTarget.remoteName, diff --git a/src/renderer/src/components/right-sidebar/checks-panel-review-copy.ts b/src/renderer/src/components/right-sidebar/checks-panel-review-copy.ts new file mode 100644 index 000000000..b4486bec7 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel-review-copy.ts @@ -0,0 +1,288 @@ +import type { GitHubPRRefreshSkippedReason } from '../../../../shared/types' +import { translate } from '@/i18n/i18n' +import { getGitHubUnavailableEmptyStateCopy } from './github-refresh-error-copy' +import { + autoRetrySchedule, + capitalizeReviewLabel, + isHardRefreshError, + isRateLimitRefresh, + type ChecksPanelRecoveryAction, + type ChecksPanelReviewState, + type ChecksPanelReviewStateInput +} from './checks-panel-review-state-model' + +type KeyedCopy = { key: string; fallback: string } + +/** + * Muted sentence appended beneath a blocker or accepted-no-review body when a + * concurrent lookup failure or positive-unresolved evidence is also current. + */ +export function concurrentLookupDetail(input: ChecksPanelReviewStateInput): string | undefined { + const { reviewLabel, providerName, refresh } = input + if (input.reviewLookup === 'positive_unresolved') { + return translate( + 'auto.components.right.sidebar.checks.panel.review.detail.positive', + 'Orca also has saved {{reviewLabel}} information that it could not verify.', + { reviewLabel } + ) + } + if (isRateLimitRefresh(refresh)) { + return translate( + 'auto.components.right.sidebar.checks.panel.review.detail.rate_limited', + 'Orca also could not check {{reviewLabel}} status because {{provider}} is temporarily limiting requests.', + { reviewLabel, provider: providerName } + ) + } + if (refresh?.errorType === 'network') { + return translate( + 'auto.components.right.sidebar.checks.panel.review.detail.network', + 'Orca also could not check {{reviewLabel}} status because this environment could not reach {{provider}}.', + { reviewLabel, provider: providerName } + ) + } + if (refresh?.status === 'error' || isHardRefreshError(refresh)) { + return translate( + 'auto.components.right.sidebar.checks.panel.review.detail.untyped', + 'Orca also could not confirm whether this branch already has a {{reviewLabel}}.', + { reviewLabel } + ) + } + return undefined +} + +export function transientRefreshState( + input: ChecksPanelReviewStateInput, + composerMode: ChecksPanelReviewState['composerMode'], + workflowAction: ChecksPanelReviewState['workflowAction'] +): ChecksPanelReviewState { + const { reviewLabel, providerName, refresh } = input + const schedule = autoRetrySchedule(input) + const base = { + renderReview: false as const, + composerMode, + workflowAction, + recovery: ['retry'] as ChecksPanelRecoveryAction[], + ...schedule + } + // Why: preserve the upstream GitHub-attributed 5xx copy in the unified state model. + const githubUnavailableCopy = + refresh?.errorType === 'server_error' + ? getGitHubUnavailableEmptyStateCopy(refresh.errorType) + : null + if (githubUnavailableCopy) { + return { ...base, ...githubUnavailableCopy } + } + if (isRateLimitRefresh(refresh)) { + return { + ...base, + title: translate( + 'auto.components.right.sidebar.checks.panel.review.paused.title', + '{{provider}} refresh paused', + { provider: providerName } + ), + description: translate( + 'auto.components.right.sidebar.checks.panel.review.paused.body', + '{{provider}} is temporarily limiting requests. This can happen even when the displayed API quota is not exhausted.', + { provider: providerName } + ) + } + } + if (refresh?.errorType === 'network') { + return { + ...base, + title: translate( + 'auto.components.right.sidebar.checks.panel.review.network.title', + 'Could not reach {{provider}}', + { provider: providerName } + ), + description: translate( + 'auto.components.right.sidebar.checks.panel.review.network.body', + 'This environment could not reach {{provider}}. Check its connection, then retry.', + { provider: providerName } + ) + } + } + if (refresh?.errorType === 'unknown') { + return { + ...base, + title: translate( + 'auto.components.right.sidebar.checks.panel.review.unknown_error.title', + 'Could not check {{reviewLabel}} status', + { reviewLabel } + ), + description: translate( + 'auto.components.right.sidebar.checks.panel.review.unknown_error.body', + 'The lookup failed, so Orca could not confirm whether this branch already has a {{reviewLabel}}.', + { reviewLabel } + ) + } + } + return { + ...base, + title: translate( + 'auto.components.right.sidebar.checks.panel.review.untyped.title', + '{{reviewLabelCap}} status unavailable', + { reviewLabelCap: capitalizeReviewLabel(reviewLabel) } + ), + description: translate( + 'auto.components.right.sidebar.checks.panel.review.untyped.body', + 'Orca could not confirm whether this branch already has a {{reviewLabel}}. Retry to check again.', + { reviewLabel } + ) + } +} + +const HARD_ERROR_COPY: Record< + 'auth' | 'permission' | 'repo_unavailable' | 'gh_unavailable', + { + title: KeyedCopy + body: KeyedCopy + } +> = { + auth: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.auth.title', + fallback: '{{provider}} authentication failed' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.auth.body', + fallback: + '{{provider}} could not authenticate the credentials available in this environment. Check the {{provider}} login or environment token, then retry.' + } + }, + permission: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.permission.title', + fallback: '{{provider}} access denied' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.permission.body', + fallback: + "The current {{provider}} credentials cannot read this repository's {{reviewLabel}}s. Check the account, token scopes, and repository access, then retry." + } + }, + repo_unavailable: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.repo.title', + fallback: '{{provider}} repository unavailable' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.repo.body', + fallback: + '{{provider}} could not resolve or access the repository for the current remote and account. Check the remote and repository access, then retry.' + } + }, + gh_unavailable: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.cli.title', + fallback: '{{provider}} CLI unavailable' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.cli.body', + fallback: + 'Orca could not run {{provider}} CLI in this environment. Set it up here, then retry.' + } + } +} + +export function hardRefreshErrorState(input: ChecksPanelReviewStateInput): ChecksPanelReviewState { + const { reviewLabel, providerName, refresh } = input + const copy = + HARD_ERROR_COPY[(refresh?.errorType as keyof typeof HARD_ERROR_COPY) ?? 'gh_unavailable'] ?? + HARD_ERROR_COPY.gh_unavailable + const vars = { provider: providerName, reviewLabel } + return { + renderReview: false, + title: translate(copy.title.key, copy.title.fallback, vars), + description: translate(copy.body.key, copy.body.fallback, vars), + composerMode: 'hidden', + workflowAction: null, + recovery: ['retry'] + } +} + +const SKIPPED_COPY: Partial< + Record< + GitHubPRRefreshSkippedReason, + { title: KeyedCopy; body: KeyedCopy; recovery: ChecksPanelRecoveryAction[] } + > +> = { + disconnected: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.skipped.disconnected.title', + fallback: 'Host disconnected' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.skipped.disconnected.body', + fallback: + "This repository's execution host is disconnected, so Orca cannot refresh {{reviewLabel}} status." + }, + recovery: ['retry'] + }, + bare: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.skipped.bare.title', + fallback: 'Bare repository' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.skipped.bare.body', + fallback: 'This repository is bare, so {{reviewLabel}} status is not available here.' + }, + recovery: [] + }, + archived: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.skipped.archived.title', + fallback: 'Repository archived' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.skipped.archived.body', + fallback: 'This repository is archived, so Orca is not refreshing {{reviewLabel}} status.' + }, + recovery: [] + }, + 'not-git': { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.skipped.not_git.title', + fallback: 'Not a Git repository' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.skipped.not_git.body', + fallback: 'Orca could not treat this folder as a Git repository for {{reviewLabel}} status.' + }, + recovery: [] + }, + remote: { + title: { + key: 'auto.components.right.sidebar.checks.panel.review.skipped.remote.title', + fallback: 'Remote-only context' + }, + body: { + key: 'auto.components.right.sidebar.checks.panel.review.skipped.remote.body', + fallback: + 'Orca could not refresh {{reviewLabel}} status for this remote context. Retry after the host is available.' + }, + recovery: ['retry'] + } +} + +/** Returns the skipped-reason row, or `null` to defer to the missing/unknown row. */ +export function skippedRefreshState( + input: ChecksPanelReviewStateInput, + skippedReason: GitHubPRRefreshSkippedReason +): ChecksPanelReviewState | null { + const copy = SKIPPED_COPY[skippedReason] + if (!copy) { + // `fresh` (and any unknown skip) with no accepted result → missing/unknown. + return null + } + const vars = { reviewLabel: input.reviewLabel } + return { + renderReview: false, + title: translate(copy.title.key, copy.title.fallback, vars), + description: translate(copy.body.key, copy.body.fallback, vars), + composerMode: 'hidden', + workflowAction: null, + recovery: copy.recovery + } +} diff --git a/src/renderer/src/components/right-sidebar/checks-panel-review-creation.test.ts b/src/renderer/src/components/right-sidebar/checks-panel-review-creation.test.ts index 69d1dc326..4a53eab87 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-review-creation.test.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-review-creation.test.ts @@ -1,9 +1,33 @@ import { describe, expect, it } from 'vitest' +import type { + HostedReviewCreationBlockedReason, + HostedReviewCreationEligibility, + HostedReviewLookupOutcome +} from '../../../../shared/hosted-review' import { + computeChecksPanelConfirmedReadiness, + isChecksPanelCreateEligibilityConfirmable, + isChecksPanelHardErrorCleared, + isChecksPanelHardRefreshErrorType, resolveChecksPanelHostedReviewBaseRef, - shouldOpenChecksPanelCreateComposer + shouldOpenChecksPanelCreateComposer, + type ChecksPanelConfirmedReadinessInput } from './checks-panel-review-creation' +function eligibility( + overrides: Partial = {} +): HostedReviewCreationEligibility { + return { + provider: 'github', + review: null, + canCreate: true, + blockedReason: null, + nextAction: null, + reviewLookupOutcome: 'not_found', + ...overrides + } +} + describe('resolveChecksPanelHostedReviewBaseRef', () => { it('prefers the worktree base ref over the repo default', () => { expect( @@ -14,66 +38,70 @@ describe('resolveChecksPanelHostedReviewBaseRef', () => { ).toBe('release/1.4') }) - it('falls back to the repo base ref when the worktree has no override', () => { - expect( - resolveChecksPanelHostedReviewBaseRef({ - worktreeBaseRef: null, - repoBaseRef: ' main ' - }) - ).toBe('main') - }) - it('returns null when both inputs are null', () => { expect( - resolveChecksPanelHostedReviewBaseRef({ - worktreeBaseRef: null, - repoBaseRef: null - }) + resolveChecksPanelHostedReviewBaseRef({ worktreeBaseRef: null, repoBaseRef: null }) ).toBe(null) }) +}) - it('returns null when worktree base ref is whitespace-only', () => { +describe('isChecksPanelCreateEligibilityConfirmable (shared desktop/mobile floor)', () => { + const base = { reviewLookup: 'not_found' as const, hasHardRefreshError: false } + + it('allows canCreate and needs_push when nothing hard-blocks', () => { + expect(isChecksPanelCreateEligibilityConfirmable({ ...base, eligibility: eligibility() })).toBe( + true + ) expect( - resolveChecksPanelHostedReviewBaseRef({ - worktreeBaseRef: ' ', - repoBaseRef: null + isChecksPanelCreateEligibilityConfirmable({ + ...base, + eligibility: eligibility({ canCreate: false, blockedReason: 'needs_push' }) }) - ).toBe(null) + ).toBe(true) }) - it('strips origin prefix from the worktree base ref', () => { + it('fails closed on every hard-block: null, existing_review, positive, hard error, unavailable', () => { + expect(isChecksPanelCreateEligibilityConfirmable({ ...base, eligibility: null })).toBe(false) expect( - resolveChecksPanelHostedReviewBaseRef({ - worktreeBaseRef: 'origin/main', - repoBaseRef: 'develop' + isChecksPanelCreateEligibilityConfirmable({ + ...base, + eligibility: eligibility({ canCreate: false, blockedReason: 'existing_review' }) }) - ).toBe('main') - }) - - it('strips upstream prefix from the repo base ref', () => { + ).toBe(false) expect( - resolveChecksPanelHostedReviewBaseRef({ - worktreeBaseRef: null, - repoBaseRef: 'upstream/develop' + isChecksPanelCreateEligibilityConfirmable({ + ...base, + eligibility: eligibility(), + reviewLookup: 'positive_unresolved' }) - ).toBe('develop') + ).toBe(false) + expect( + isChecksPanelCreateEligibilityConfirmable({ + ...base, + eligibility: eligibility(), + hasHardRefreshError: true + }) + ).toBe(false) + expect( + isChecksPanelCreateEligibilityConfirmable({ + ...base, + eligibility: eligibility({ + blockedReason: 'needs_push', + reviewLookupOutcome: 'unavailable' + }) + }) + ).toBe(false) }) }) describe('shouldOpenChecksPanelCreateComposer', () => { - it('opens for GitLab MR creation eligibility', () => { + it('opens for creation eligibility', () => { expect( shouldOpenChecksPanelCreateComposer({ activeReview: null, isFolder: false, - branch: 'feature/gitlab-mr', - hostedReviewCreation: { - provider: 'gitlab', - review: null, - canCreate: true, - blockedReason: null, - nextAction: null - } + branch: 'feature/x', + hostedReviewCreation: eligibility({ canCreate: true }) }) ).toBe(true) }) @@ -83,66 +111,281 @@ describe('shouldOpenChecksPanelCreateComposer', () => { shouldOpenChecksPanelCreateComposer({ activeReview: null, isFolder: false, - branch: 'feature/gitlab-mr', - hostedReviewCreation: { - provider: 'gitlab', - review: null, - canCreate: false, - blockedReason: 'needs_push', - nextAction: 'push' - } + branch: 'feature/x', + hostedReviewCreation: eligibility({ canCreate: false, blockedReason: 'needs_push' }) }) ).toBe(true) }) - it('does not open when an active review exists', () => { + it('does not open on positive unresolved review evidence', () => { expect( shouldOpenChecksPanelCreateComposer({ - activeReview: { provider: 'github', number: 123 }, + activeReview: null, isFolder: false, - branch: 'feature/test', - hostedReviewCreation: { - provider: 'github', - review: null, - canCreate: true, - blockedReason: null, - nextAction: null - } + branch: 'feature/x', + hostedReviewCreation: eligibility({ canCreate: false, blockedReason: 'needs_push' }), + reviewLookup: 'positive_unresolved' }) ).toBe(false) }) - it('does not open for folder repos', () => { + it('does not open during a hard refresh error', () => { + expect( + shouldOpenChecksPanelCreateComposer({ + activeReview: null, + isFolder: false, + branch: 'feature/x', + hostedReviewCreation: eligibility({ canCreate: true }), + hasHardRefreshError: true + }) + ).toBe(false) + }) + + it('does not open when a review already exists', () => { + expect( + shouldOpenChecksPanelCreateComposer({ + activeReview: null, + isFolder: false, + branch: 'feature/x', + hostedReviewCreation: eligibility({ canCreate: false, blockedReason: 'existing_review' }) + }) + ).toBe(false) + }) + + it('does not open for folders or empty branches', () => { expect( shouldOpenChecksPanelCreateComposer({ activeReview: null, isFolder: true, - branch: 'feature/test', - hostedReviewCreation: { - provider: 'github', - review: null, - canCreate: true, - blockedReason: null, - nextAction: null - } + branch: 'feature/x', + hostedReviewCreation: eligibility() }) ).toBe(false) - }) - - it('does not open when branch is empty', () => { expect( shouldOpenChecksPanelCreateComposer({ activeReview: null, isFolder: false, branch: '', - hostedReviewCreation: { - provider: 'github', - review: null, - canCreate: true, - blockedReason: null, - nextAction: null - } + hostedReviewCreation: eligibility() }) ).toBe(false) }) }) + +describe('isChecksPanelHardRefreshErrorType', () => { + it('flags the four hard error types', () => { + for (const t of ['auth', 'permission', 'repo_unavailable', 'gh_unavailable']) { + expect(isChecksPanelHardRefreshErrorType(t)).toBe(true) + } + }) + it('does not flag transient types or undefined', () => { + for (const t of ['rate_limited', 'network', 'unknown']) { + expect(isChecksPanelHardRefreshErrorType(t)).toBe(false) + } + expect(isChecksPanelHardRefreshErrorType(undefined)).toBe(false) + }) +}) + +describe('computeChecksPanelConfirmedReadiness', () => { + const NOW = 1_000_000 + function readiness( + overrides: Partial = {} + ): ChecksPanelConfirmedReadinessInput { + return { + contextKeyMatches: true, + eligibility: { canCreate: true, blockedReason: null, reviewLookupOutcome: 'not_found' }, + eligibilityCompletedAt: NOW - 1_000, + eligibilityRequestStartedAt: NOW - 2_000, + reviewLookup: 'not_found', + hardErrorObservedAt: undefined, + gitSnapshotMatches: true, + now: NOW, + ...overrides + } + } + + it('confirms fresh, matching eligibility', () => { + expect(computeChecksPanelConfirmedReadiness(readiness())).toEqual({ + confirmed: true, + needsPush: false + }) + }) + + it('confirms needs_push as the Push & Create path', () => { + expect( + computeChecksPanelConfirmedReadiness( + readiness({ + eligibility: { + canCreate: false, + blockedReason: 'needs_push', + reviewLookupOutcome: 'not_found' + } + }) + ) + ).toEqual({ confirmed: true, needsPush: true }) + }) + + it('drops confirmed when the context key does not match', () => { + expect( + computeChecksPanelConfirmedReadiness(readiness({ contextKeyMatches: false })).confirmed + ).toBe(false) + }) + + it('drops confirmed on positive unresolved and existing_review', () => { + expect( + computeChecksPanelConfirmedReadiness(readiness({ reviewLookup: 'positive_unresolved' })) + .confirmed + ).toBe(false) + expect( + computeChecksPanelConfirmedReadiness( + readiness({ + eligibility: { + canCreate: false, + blockedReason: 'existing_review', + reviewLookupOutcome: 'found' + } + }) + ).confirmed + ).toBe(false) + }) + + it('drops confirmed when eligibility is older than 5 minutes', () => { + expect( + computeChecksPanelConfirmedReadiness( + readiness({ eligibilityCompletedAt: NOW - 5 * 60_000 - 1 }) + ).confirmed + ).toBe(false) + }) + + it('drops confirmed when the git snapshot no longer matches', () => { + expect( + computeChecksPanelConfirmedReadiness(readiness({ gitSnapshotMatches: false })).confirmed + ).toBe(false) + }) + + it('preserves confirmed across a transient refresh failure once past the error', () => { + // The panel keeps the last confirmed eligibility snapshot; a transient + // failure (no hard error observed) must not drop confirmed. + expect( + computeChecksPanelConfirmedReadiness( + readiness({ hardErrorObservedAt: undefined, reviewLookup: 'not_found' }) + ) + ).toEqual({ confirmed: true, needsPush: false }) + }) + + describe('hard error clearing', () => { + it('clears when the request started strictly after the error with an accepted outcome', () => { + expect( + computeChecksPanelConfirmedReadiness( + readiness({ + hardErrorObservedAt: NOW - 3_000, + eligibilityRequestStartedAt: NOW - 2_000, + eligibility: { canCreate: true, blockedReason: null, reviewLookupOutcome: 'not_found' } + }) + ).confirmed + ).toBe(true) + }) + + it('does not clear for an in-flight request that started before the error', () => { + expect( + computeChecksPanelConfirmedReadiness( + readiness({ hardErrorObservedAt: NOW - 1_500, eligibilityRequestStartedAt: NOW - 2_000 }) + ).confirmed + ).toBe(false) + }) + + it('does not clear on a late unavailable fallback', () => { + expect( + computeChecksPanelConfirmedReadiness( + readiness({ + hardErrorObservedAt: NOW - 3_000, + eligibilityRequestStartedAt: NOW - 2_000, + eligibility: { + canCreate: false, + blockedReason: 'no_upstream', + reviewLookupOutcome: 'unavailable' + } + }) + ).confirmed + ).toBe(false) + }) + }) +}) + +describe('isChecksPanelHardErrorCleared', () => { + const NOW = 1_000_000 + function cleared( + overrides: Partial = {} + ): ChecksPanelConfirmedReadinessInput { + return { + contextKeyMatches: true, + eligibility: { canCreate: true, blockedReason: null, reviewLookupOutcome: 'not_found' }, + eligibilityCompletedAt: NOW - 1_000, + eligibilityRequestStartedAt: NOW - 2_000, + reviewLookup: 'not_found', + hardErrorObservedAt: NOW - 3_000, + gitSnapshotMatches: true, + now: NOW, + ...overrides + } + } + + it('is cleared (true) when no hard error is observed', () => { + expect(isChecksPanelHardErrorCleared(cleared({ hardErrorObservedAt: undefined }))).toBe(true) + }) + + it('stays blocked while only a queued/in-flight retry replaced the error', () => { + // No request that both started after the error and settled with an accepted + // outcome, so Create must not flap back. + expect(isChecksPanelHardErrorCleared(cleared({ eligibilityRequestStartedAt: undefined }))).toBe( + false + ) + }) + + it('stays blocked for a request that started before the error', () => { + expect( + isChecksPanelHardErrorCleared( + cleared({ hardErrorObservedAt: NOW - 1_000, eligibilityRequestStartedAt: NOW - 2_000 }) + ) + ).toBe(false) + }) + + it('stays blocked when the clearing request is for a different context', () => { + expect(isChecksPanelHardErrorCleared(cleared({ contextKeyMatches: false }))).toBe(false) + }) + + it('stays blocked on an unavailable outcome even if the request started after', () => { + expect( + isChecksPanelHardErrorCleared( + cleared({ + eligibility: { + canCreate: false, + blockedReason: 'no_upstream', + reviewLookupOutcome: 'unavailable' + } + }) + ) + ).toBe(false) + }) + + it('clears when a later request settles found or not_found', () => { + expect(isChecksPanelHardErrorCleared(cleared())).toBe(true) + expect( + isChecksPanelHardErrorCleared( + cleared({ + eligibility: { + canCreate: false, + blockedReason: 'existing_review', + reviewLookupOutcome: 'found' + } + }) + ) + ).toBe(true) + }) +}) + +// Type-only usage to keep the imports meaningful across refactors. +const _blocked: HostedReviewCreationBlockedReason = null +const _outcome: HostedReviewLookupOutcome = 'not_found' +void _blocked +void _outcome diff --git a/src/renderer/src/components/right-sidebar/checks-panel-review-creation.ts b/src/renderer/src/components/right-sidebar/checks-panel-review-creation.ts index 11e42d40f..95c9ccfde 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-review-creation.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-review-creation.ts @@ -1,5 +1,14 @@ -import type { HostedReviewCreationEligibility } from '../../../../shared/hosted-review' +import type { + HostedReviewCreationBlockedReason, + HostedReviewCreationEligibility, + HostedReviewLookupOutcome +} from '../../../../shared/hosted-review' +import type { PRRefreshErrorType } from '../../../../shared/types' import { normalizeHostedReviewBaseRef } from '../../../../shared/hosted-review-refs' +import type { ChecksPanelReviewLookup } from './checks-panel-review-lookup-authority' +// Single source of truth for the hard-refresh error set, shared with the +// review-state model so the composer gate and empty-state selector cannot drift. +import { HARD_REFRESH_ERROR_TYPES } from './checks-panel-review-state-model' export function resolveChecksPanelHostedReviewBaseRef(input: { worktreeBaseRef?: string | null @@ -14,17 +23,160 @@ function normalizeChecksPanelHostedReviewBaseRef(ref: string | null | undefined) return normalizedRef || null } +/** + * Shared create-eligibility floor for the desktop confirmed gate and the + * mobile-shared composer gate. Create / Push & Create is impossible when review + * existence cannot be proven no-review: positive unresolved evidence, a current + * hard refresh error, `existing_review`, or an `unavailable` existing-review + * lookup all fail closed. Otherwise it allows the `canCreate` / `needs_push` + * paths. Both callers route through this so their hard-block semantics cannot + * drift; the desktop confirmed gate layers freshness/context checks on top. + */ +export function isChecksPanelCreateEligibilityConfirmable(input: { + eligibility: Pick< + HostedReviewCreationEligibility, + 'canCreate' | 'blockedReason' | 'reviewLookupOutcome' + > | null + reviewLookup: ChecksPanelReviewLookup + hasHardRefreshError: boolean +}): boolean { + const eligibility = input.eligibility + if (!eligibility || eligibility.blockedReason === 'existing_review') { + return false + } + if (input.reviewLookup === 'positive_unresolved' || input.hasHardRefreshError) { + return false + } + // An `unavailable` existing-review lookup could be hiding a real PR. Block even + // the Push & Create (needs_push) path, which would otherwise slip through the + // canCreate check below with review existence unproven. + if (eligibility.reviewLookupOutcome === 'unavailable') { + return false + } + return eligibility.canCreate === true || eligibility.blockedReason === 'needs_push' +} + +/** + * Confirmed-only composer gate shared with mobile. Delegates the hard-block + * decision to {@link isChecksPanelCreateEligibilityConfirmable} so the desktop + * confirmed gate and this mobile-shared gate cannot drift. Phase 1 adds no + * provisional or draft-preserve path. + */ export function shouldOpenChecksPanelCreateComposer(input: { activeReview: unknown | null isFolder: boolean branch: string hostedReviewCreation: HostedReviewCreationEligibility | null + reviewLookup?: ChecksPanelReviewLookup + hasHardRefreshError?: boolean }): boolean { - return ( - !input.activeReview && - !input.isFolder && - Boolean(input.branch) && - (input.hostedReviewCreation?.canCreate === true || - input.hostedReviewCreation?.blockedReason === 'needs_push') - ) + if (input.activeReview || input.isFolder || !input.branch) { + return false + } + return isChecksPanelCreateEligibilityConfirmable({ + eligibility: input.hostedReviewCreation, + reviewLookup: input.reviewLookup ?? 'unknown', + hasHardRefreshError: input.hasHardRefreshError === true + }) } + +const CONFIRMED_ELIGIBILITY_MAX_AGE_MS = 5 * 60_000 + +export function isChecksPanelHardRefreshErrorType(errorType: string | undefined): boolean { + return errorType != null && HARD_REFRESH_ERROR_TYPES.has(errorType as PRRefreshErrorType) +} + +export type ChecksPanelConfirmedReadiness = { + confirmed: boolean + /** The confirmed path is Push & Create rather than plain Create. */ + needsPush: boolean +} + +export type ChecksPanelConfirmedReadinessInput = { + /** The eligibility result's context key equals the panel's current context. */ + contextKeyMatches: boolean + eligibility: Pick< + HostedReviewCreationEligibility, + 'canCreate' | 'blockedReason' | 'reviewLookupOutcome' + > | null + /** Wall-clock time the eligibility result settled. */ + eligibilityCompletedAt?: number + /** Wall-clock time the eligibility request that produced the result started. */ + eligibilityRequestStartedAt?: number + reviewLookup: ChecksPanelReviewLookup + /** + * Observation time of the most recent hard refresh error for this context, or + * undefined when no hard error is current. + */ + hardErrorObservedAt?: number + /** + * Whether the Git snapshot used for the eligibility still matches current HEAD, + * branch, upstream/ahead/behind/dirty, base, and execution-host fields. + */ + gitSnapshotMatches: boolean + now: number +} + +const NOT_CONFIRMED: ChecksPanelConfirmedReadiness = { confirmed: false, needsPush: false } + +/** + * A hard error is cleared only by an eligibility request that started strictly + * after the error was observed, completed for the same exact context with a + * `found` / `not_found` lookup outcome, with no newer hard error since. A late + * `unavailable` fallback or an already-in-flight request cannot clear it. + * + * Exported so the panel can keep the hard-error block sticky across + * `queued` / `in-flight` auto-retries (which drop `status: 'error'` and would + * otherwise let Create flap back) until this predicate says it is cleared. + */ +export function isChecksPanelHardErrorCleared(input: ChecksPanelConfirmedReadinessInput): boolean { + if (input.hardErrorObservedAt === undefined) { + return true + } + const startedAt = input.eligibilityRequestStartedAt + if (startedAt === undefined || !(startedAt > input.hardErrorObservedAt)) { + return false + } + if (!input.contextKeyMatches) { + return false + } + const outcome: HostedReviewLookupOutcome | undefined = input.eligibility?.reviewLookupOutcome + return outcome === 'found' || outcome === 'not_found' +} + +/** + * Confirmed readiness for the exact context. Any failed check drops confirmed + * immediately; transient refresh failures never appear here (the caller only + * passes a hard error observation, never a transient one). + */ +export function computeChecksPanelConfirmedReadiness( + input: ChecksPanelConfirmedReadinessInput +): ChecksPanelConfirmedReadiness { + const eligibility = input.eligibility + if (!input.contextKeyMatches) { + return NOT_CONFIRMED + } + // Share the hard-block floor with the mobile-shared gate; an uncleared hard + // error is folded in as the `hasHardRefreshError` input so the two cannot drift. + if ( + !isChecksPanelCreateEligibilityConfirmable({ + eligibility, + reviewLookup: input.reviewLookup, + hasHardRefreshError: !isChecksPanelHardErrorCleared(input) + }) + ) { + return NOT_CONFIRMED + } + // Freshness: eligibility must be recent and its Git snapshot must still match. + if ( + input.eligibilityCompletedAt === undefined || + input.now - input.eligibilityCompletedAt > CONFIRMED_ELIGIBILITY_MAX_AGE_MS || + !input.gitSnapshotMatches + ) { + return NOT_CONFIRMED + } + return { confirmed: true, needsPush: eligibility?.blockedReason === 'needs_push' } +} + +// Re-exported for callers that need the blocker type alongside the gate. +export type { HostedReviewCreationBlockedReason } diff --git a/src/renderer/src/components/right-sidebar/checks-panel-review-lookup-authority.test.ts b/src/renderer/src/components/right-sidebar/checks-panel-review-lookup-authority.test.ts new file mode 100644 index 000000000..36a814a93 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel-review-lookup-authority.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from 'vitest' +import { + isRenderableChecksPanelReviewDetails, + normalizeTrustedReviewUrl, + resolveChecksPanelReviewLookup +} from './checks-panel-review-lookup-authority' + +const EMPTY = { + pr: null, + prCachedHasPR: null, + hostedReview: null +} as const + +describe('resolveChecksPanelReviewLookup', () => { + it('returns found with a trusted URL when PR details are renderable', () => { + expect( + resolveChecksPanelReviewLookup({ + ...EMPTY, + pr: { number: 42, url: 'https://github.com/o/r/pull/42' } + }) + ).toEqual({ state: 'found', openReviewUrl: 'https://github.com/o/r/pull/42' }) + }) + + it('does not treat a summary without a positive number as found', () => { + expect( + resolveChecksPanelReviewLookup({ + ...EMPTY, + pr: { number: 0, url: 'https://github.com/o/r/pull/0' }, + hostedReview: { provider: 'github', url: 'https://github.com/o/r/pull/1', number: 1 } + }).state + ).toBe('positive_unresolved') + }) + + it('classifies a github hosted-review card with no PR cache as positive_unresolved', () => { + // Replaces the old hasAmbiguousGitHubHostedReview boolean. + expect( + resolveChecksPanelReviewLookup({ + ...EMPTY, + prCachedHasPR: null, + hostedReview: { provider: 'github', number: 7, url: 'https://github.com/o/r/pull/7' } + }) + ).toEqual({ state: 'positive_unresolved', openReviewUrl: 'https://github.com/o/r/pull/7' }) + }) + + it('keeps positive evidence over an accepted null no-PR entry (conflict)', () => { + expect( + resolveChecksPanelReviewLookup({ + ...EMPTY, + prCachedHasPR: false, + linkedReviewNumber: 5 + }).state + ).toBe('positive_unresolved') + }) + + it('returns not_found for an accepted no-PR cache entry', () => { + expect(resolveChecksPanelReviewLookup({ ...EMPTY, prCachedHasPR: false })).toEqual({ + state: 'not_found', + openReviewUrl: null + }) + }) + + it('returns not_found for eligibility not_found', () => { + expect( + resolveChecksPanelReviewLookup({ + ...EMPTY, + eligibilityReviewLookupOutcome: 'not_found' + }).state + ).toBe('not_found') + }) + + it('treats eligibility found as positive_unresolved when no renderable details', () => { + expect( + resolveChecksPanelReviewLookup({ + ...EMPTY, + eligibilityReviewLookupOutcome: 'found', + eligibilityReview: { url: 'https://gitlab.com/o/r/-/merge_requests/3' } + }) + ).toEqual({ + state: 'positive_unresolved', + openReviewUrl: 'https://gitlab.com/o/r/-/merge_requests/3' + }) + }) + + it('returns unknown for a missing entry and unavailable eligibility', () => { + expect( + resolveChecksPanelReviewLookup({ + ...EMPTY, + prCachedHasPR: null, + eligibilityReviewLookupOutcome: 'unavailable' + }).state + ).toBe('unknown') + }) + + it('does not offer Open Review for a non-http url', () => { + expect( + resolveChecksPanelReviewLookup({ + ...EMPTY, + hostedReview: { provider: 'github', number: 9, url: 'javascript:alert(1)' } + }) + ).toEqual({ state: 'positive_unresolved', openReviewUrl: null }) + }) +}) + +describe('normalizeTrustedReviewUrl', () => { + it('accepts http and https', () => { + expect(normalizeTrustedReviewUrl(' https://x.test/pull/1 ')).toBe('https://x.test/pull/1') + expect(normalizeTrustedReviewUrl('http://x.test/pull/1')).toBe('http://x.test/pull/1') + }) + + it('rejects empty and non-web schemes', () => { + expect(normalizeTrustedReviewUrl(null)).toBe(null) + expect(normalizeTrustedReviewUrl('')).toBe(null) + expect(normalizeTrustedReviewUrl('ftp://x.test')).toBe(null) + expect(normalizeTrustedReviewUrl('file:///etc/passwd')).toBe(null) + expect(normalizeTrustedReviewUrl('not a url')).toBe(null) + }) + + it('rejects credential-bearing URLs so tokens never reach the browser/shell', () => { + expect(normalizeTrustedReviewUrl('https://user:token@git.test/repo/pull/1')).toBe(null) + expect(normalizeTrustedReviewUrl('https://user@git.test/repo/pull/1')).toBe(null) + }) +}) + +describe('isRenderableChecksPanelReviewDetails', () => { + it('requires a positive number', () => { + expect(isRenderableChecksPanelReviewDetails({ number: 1 })).toBe(true) + expect(isRenderableChecksPanelReviewDetails({ number: 0 })).toBe(false) + expect(isRenderableChecksPanelReviewDetails(null)).toBe(false) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel-review-lookup-authority.ts b/src/renderer/src/components/right-sidebar/checks-panel-review-lookup-authority.ts new file mode 100644 index 000000000..55d24fefd --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel-review-lookup-authority.ts @@ -0,0 +1,120 @@ +import type { HostedReviewLookupOutcome } from '../../../../shared/hosted-review' +import { isPositiveHostedReviewNumber } from '../../../../shared/hosted-review' + +/** + * Four-state review evidence model for the Checks panel. Replaces the single + * `hasAmbiguousGitHubHostedReview` Boolean, which collapsed materially different + * states (missing lookup, failed lookup, positive-but-unrenderable evidence). + * + * - `found`: current review details are renderable — leave the empty state. + * - `positive_unresolved`: a review is known to exist but details are not + * renderable. Never offer Create / Push & Create; prefer trusted Open Review. + * - `not_found`: an accepted no-review result for the exact context. + * - `unknown`: no accepted positive or no-review result (missing entry, failed + * or skipped lookup, in-flight). + */ +export type ChecksPanelReviewLookup = 'found' | 'positive_unresolved' | 'not_found' | 'unknown' + +type ReviewLookupNumberLike = number | null | undefined + +export type ChecksPanelReviewLookupInput = { + /** + * Renderable review details for the exact context (GitHub `PRInfo` payload or + * equivalent). Treated as renderable only when it carries a usable identity. + */ + pr: { number?: ReviewLookupNumberLike; url?: string | null } | null | undefined + /** + * Tri-state from the PR cache entry: `true` = has PR, `false` = accepted + * no-PR, `null` = no accepted entry (missing / never fetched). Distinguishes an + * accepted no-review outcome from a missing lookup. + */ + prCachedHasPR: boolean | null + /** Positive hosted-review cache for the exact context, when present. */ + hostedReview: + | { provider?: string | null; number?: ReviewLookupNumberLike; url?: string | null } + | null + | undefined + /** Durable linked review number for the exact context. */ + linkedReviewNumber?: ReviewLookupNumberLike + /** Settled eligibility lookup outcome for the exact context. */ + eligibilityReviewLookupOutcome?: HostedReviewLookupOutcome | null + /** Eligibility review summary (may be summary-only). */ + eligibilityReview?: { number?: ReviewLookupNumberLike; url?: string | null } | null +} + +export type ChecksPanelReviewLookupResult = { + state: ChecksPanelReviewLookup + /** Trusted http(s) URL for Open Review, when one is known; else null. */ + openReviewUrl: string | null +} + +/** + * Returns the URL only when it is a plain http(s) link with no embedded + * credentials, so a credential-bearing or non-web value never reaches an Open + * Review affordance (and never lands in browser history / shell logs). + */ +export function normalizeTrustedReviewUrl(url: string | null | undefined): string | null { + if (!url) { + return null + } + const trimmed = url.trim() + let parsed: URL + try { + parsed = new URL(trimmed) + } catch { + return null + } + // Reject non-web schemes and any userinfo (`user:token@host`) — a prefix regex + // alone would forward embedded credentials to the browser/shell. + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + return null + } + if (parsed.username !== '' || parsed.password !== '') { + return null + } + return trimmed +} + +/** + * Review details render the normal review chrome only with a usable identity: a + * positive review number. A provider-neutral summary without renderable details + * maps to `positive_unresolved`, not `found`. + */ +export function isRenderableChecksPanelReviewDetails( + pr: { number?: ReviewLookupNumberLike } | null | undefined +): boolean { + return pr != null && isPositiveHostedReviewNumber(pr.number) +} + +export function resolveChecksPanelReviewLookup( + input: ChecksPanelReviewLookupInput +): ChecksPanelReviewLookupResult { + if (isRenderableChecksPanelReviewDetails(input.pr)) { + return { + state: 'found', + openReviewUrl: normalizeTrustedReviewUrl(input.pr?.url) + } + } + + // Positive evidence wins over an accepted null no-PR entry: a conflict must + // stay `positive_unresolved` until a newer accepted result clears it, never + // collapse to "no PR." + const openReviewUrl = + normalizeTrustedReviewUrl(input.hostedReview?.url) ?? + normalizeTrustedReviewUrl(input.eligibilityReview?.url) + const hasPositiveEvidence = + isPositiveHostedReviewNumber(input.linkedReviewNumber) || + isPositiveHostedReviewNumber(input.hostedReview?.number) || + isPositiveHostedReviewNumber(input.eligibilityReview?.number) || + input.eligibilityReviewLookupOutcome === 'found' || + (input.hostedReview != null && openReviewUrl !== null) + if (hasPositiveEvidence) { + return { state: 'positive_unresolved', openReviewUrl } + } + + if (input.prCachedHasPR === false || input.eligibilityReviewLookupOutcome === 'not_found') { + return { state: 'not_found', openReviewUrl: null } + } + + return { state: 'unknown', openReviewUrl: null } +} diff --git a/src/renderer/src/components/right-sidebar/checks-panel-review-state-model.ts b/src/renderer/src/components/right-sidebar/checks-panel-review-state-model.ts new file mode 100644 index 000000000..4b43615eb --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel-review-state-model.ts @@ -0,0 +1,165 @@ +import type { HostedReviewCreationBlockedReason } from '../../../../shared/hosted-review' +import type { GitHubPRRefreshSkippedReason, PRRefreshErrorType } from '../../../../shared/types' +import type { ChecksPanelReviewLookup } from './checks-panel-review-lookup-authority' + +/** + * Composer visibility the panel should render. Phase 1 never *opens* a new + * composer from a refresh failure — `confirmed_open` / `needs_push_open` mean an + * already-confirmed composer stays open. (Phase 2's disabled draft-preserve mode + * is intentionally absent until that phase ships.) + */ +export type ChecksPanelComposerMode = 'hidden' | 'confirmed_open' | 'needs_push_open' + +export type ChecksPanelWorkflowAction = + | 'create' + | 'push_and_create' + | 'publish_branch' + | 'sync_branch' + | 'authenticate' + | null + +export type ChecksPanelRecoveryAction = 'retry' | 'refresh' | 'open_review' + +export type ChecksPanelReviewState = { + /** True only for `reviewLookup: found` — the caller renders review chrome. */ + renderReview: boolean + title: string + description: string + /** One muted sentence appended beneath the body (concurrent lookup failure). */ + detail?: string + composerMode: ChecksPanelComposerMode + workflowAction: ChecksPanelWorkflowAction + recovery: ChecksPanelRecoveryAction[] + openReviewUrl?: string | null + /** Drives "Orca will retry at {time}"; only when a future auto-retry exists. */ + autoRetryAt?: number + /** Retry button stays disabled while now < retryDisabledUntil. */ + retryDisabledUntil?: number +} + +export type ChecksPanelRefreshInput = { + status?: 'queued' | 'in-flight' | 'paused' | 'error' | 'skipped' + errorType?: PRRefreshErrorType + skippedReason?: GitHubPRRefreshSkippedReason + nextAutoRetryAt?: number + retryDisabledUntil?: number +} + +export type ChecksPanelReviewStateInput = { + operationLabel: string | null + reviewLabel: 'pull request' | 'merge request' + reviewShortLabel: 'PR' | 'MR' + /** Localized provider display name, e.g. "GitHub". */ + providerName: string + /** GitHub gets typed error rows; other providers use neutral copy. */ + isGitHubProvider: boolean + reviewLookup: ChecksPanelReviewLookup + openReviewUrl: string | null + eligibilityBlockedReason: HostedReviewCreationBlockedReason | undefined + /** Confirmed readiness held for the exact context (see review-creation). */ + confirmedReadiness: boolean + /** The confirmed path is the Push & Create workflow rather than plain Create. */ + confirmedNeedsPush: boolean + refresh?: ChecksPanelRefreshInput + gitStatusPhase: 'loading' | 'ready' | 'error' + hasUpstream: boolean | undefined + hasCurrentBranch: boolean +} + +export const HARD_REFRESH_ERROR_TYPES = new Set([ + 'auth', + 'permission', + 'repo_unavailable', + 'gh_unavailable' +]) + +/** Eligibility blockers that own their own guidance and outrank refresh copy. */ +export const ELIGIBILITY_SAFETY_BLOCKERS = new Set>([ + 'detached_head', + 'dirty', + 'default_branch', + 'existing_review', + 'fork_head_unsupported', + 'base_not_on_remote', + 'unsupported_provider' +]) + +export function isHardRefreshError(refresh: ChecksPanelRefreshInput | undefined): boolean { + return ( + refresh?.status === 'error' && + refresh.errorType != null && + HARD_REFRESH_ERROR_TYPES.has(refresh.errorType) + ) +} + +export function isRateLimitRefresh(refresh: ChecksPanelRefreshInput | undefined): boolean { + return ( + refresh?.status === 'paused' || + refresh?.errorType === 'rate_limited' || + (refresh?.status === 'skipped' && refresh.skippedReason === 'rate-limit') + ) +} + +export function isTransientRefreshFailure(refresh: ChecksPanelRefreshInput | undefined): boolean { + if (!refresh) { + return false + } + if (isRateLimitRefresh(refresh)) { + return true + } + if (refresh.status === 'error') { + // Untyped and typed-transient errors only pause background refresh; they do + // not prove a fresh user-initiated lookup would fail. + return ( + refresh.errorType == null || + refresh.errorType === 'network' || + refresh.errorType === 'server_error' || + refresh.errorType === 'unknown' + ) + } + return false +} + +export function isBranchBlocker(reason: HostedReviewCreationBlockedReason | undefined): boolean { + return ( + reason === 'no_upstream' || + reason === 'needs_sync' || + reason === 'auth_required' || + reason === 'needs_push' + ) +} + +export function confirmedComposerMode( + input: Pick +): ChecksPanelComposerMode { + if (!input.confirmedReadiness) { + return 'hidden' + } + return input.confirmedNeedsPush ? 'needs_push_open' : 'confirmed_open' +} + +export function workflowActionForComposer( + mode: ChecksPanelComposerMode +): ChecksPanelWorkflowAction { + if (mode === 'confirmed_open') { + return 'create' + } + if (mode === 'needs_push_open') { + return 'push_and_create' + } + return null +} + +export function autoRetrySchedule(input: ChecksPanelReviewStateInput): { + autoRetryAt?: number + retryDisabledUntil?: number +} { + return { + autoRetryAt: input.refresh?.nextAutoRetryAt, + retryDisabledUntil: input.refresh?.retryDisabledUntil + } +} + +export function capitalizeReviewLabel(value: string): string { + return value.length > 0 ? value[0].toUpperCase() + value.slice(1) : value +} diff --git a/src/renderer/src/components/right-sidebar/source-control-create-pr-intent-flow.test.ts b/src/renderer/src/components/right-sidebar/source-control-create-pr-intent-flow.test.ts index 4f1409738..a1f6459dc 100644 --- a/src/renderer/src/components/right-sidebar/source-control-create-pr-intent-flow.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control-create-pr-intent-flow.test.ts @@ -190,7 +190,8 @@ describe('source-control Create PR intent flow helpers', () => { review: null, canCreate: false, blockedReason: 'no_upstream', - nextAction: 'publish' + nextAction: 'publish', + reviewLookupOutcome: 'not_found' } }) ).toBe('publish') @@ -204,7 +205,8 @@ describe('source-control Create PR intent flow helpers', () => { review: null, canCreate: false, blockedReason: 'needs_push', - nextAction: 'push' + nextAction: 'push', + reviewLookupOutcome: 'not_found' } }) ).toBe('push') @@ -224,7 +226,8 @@ describe('source-control Create PR intent flow helpers', () => { review: null, canCreate: false, blockedReason: 'needs_sync', - nextAction: 'sync' + nextAction: 'sync', + reviewLookupOutcome: 'not_found' } }) ).toBe('force_push') @@ -242,7 +245,8 @@ describe('source-control Create PR intent flow helpers', () => { review: null, canCreate: false, blockedReason: 'needs_sync', - nextAction: 'sync' + nextAction: 'sync', + reviewLookupOutcome: 'not_found' } }) ).toBe('blocked') @@ -257,7 +261,8 @@ describe('source-control Create PR intent flow helpers', () => { review: null, canCreate: false, blockedReason: 'needs_sync', - nextAction: 'sync' + nextAction: 'sync', + reviewLookupOutcome: 'not_found' } }) ).toBe('sync') @@ -272,7 +277,8 @@ describe('source-control Create PR intent flow helpers', () => { review: null, canCreate: false, blockedReason: 'no_upstream', - nextAction: 'publish' + nextAction: 'publish', + reviewLookupOutcome: 'not_found' } }) ).toBe('blocked') diff --git a/src/renderer/src/components/right-sidebar/source-control-create-review-blocked-action.test.ts b/src/renderer/src/components/right-sidebar/source-control-create-review-blocked-action.test.ts index 10419bad3..e2bd937f1 100644 --- a/src/renderer/src/components/right-sidebar/source-control-create-review-blocked-action.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control-create-review-blocked-action.test.ts @@ -14,6 +14,7 @@ function eligibility( canCreate: false, blockedReason: 'needs_push', nextAction: 'push', + reviewLookupOutcome: 'not_found', ...overrides } } diff --git a/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts b/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts index 86af5bafd..d97707dd2 100644 --- a/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts @@ -183,7 +183,8 @@ describe('resolveDropdownItems', () => { review: null, canCreate: false, blockedReason: 'needs_sync', - nextAction: 'sync' + nextAction: 'sync', + reviewLookupOutcome: 'not_found' } }) ) @@ -360,7 +361,8 @@ describe('resolveDropdownItems', () => { review: null, canCreate: true, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' } }) ) @@ -671,7 +673,8 @@ describe('resolveDropdownItems', () => { review: null, canCreate: false, blockedReason: 'needs_push', - nextAction: 'push' + nextAction: 'push', + reviewLookupOutcome: 'not_found' } }) ) @@ -693,7 +696,8 @@ describe('resolveDropdownItems', () => { review: null, canCreate: false, blockedReason: 'needs_push', - nextAction: 'push' + nextAction: 'push', + reviewLookupOutcome: 'not_found' } }) ) @@ -719,7 +723,8 @@ describe('resolveDropdownItems', () => { review: null, canCreate: false, blockedReason: 'needs_push', - nextAction: 'push' + nextAction: 'push', + reviewLookupOutcome: 'not_found' } }) ) @@ -747,7 +752,8 @@ describe('resolveDropdownItems', () => { review: null, canCreate: false, blockedReason: 'auth_required', - nextAction: 'authenticate' + nextAction: 'authenticate', + reviewLookupOutcome: 'not_found' } }) ) @@ -766,7 +772,8 @@ describe('resolveDropdownItems', () => { review: null, canCreate: false, blockedReason: 'auth_required', - nextAction: 'authenticate' + nextAction: 'authenticate', + reviewLookupOutcome: 'not_found' } }) ) diff --git a/src/renderer/src/components/right-sidebar/source-control-hosted-review-creation-eligibility-snapshot.test.ts b/src/renderer/src/components/right-sidebar/source-control-hosted-review-creation-eligibility-snapshot.test.ts index ae6dceadc..13d7bc5da 100644 --- a/src/renderer/src/components/right-sidebar/source-control-hosted-review-creation-eligibility-snapshot.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control-hosted-review-creation-eligibility-snapshot.test.ts @@ -32,7 +32,7 @@ describe('resolveHostedReviewCreationProviderForTarget', () => { }) describe('buildLocalBlockerHostedReviewCreationEligibility', () => { - it('reports dirty when there are uncommitted changes', () => { + it('reports dirty without offering create intent when the review lookup failed', () => { const eligibility = buildLocalBlockerHostedReviewCreationEligibility('github', { ...featureBranch, hasUncommittedChanges: true, @@ -40,9 +40,12 @@ describe('buildLocalBlockerHostedReviewCreationEligibility', () => { ahead: 0, behind: 0 }) - expect(eligibility).toMatchObject({ blockedReason: 'dirty', nextAction: 'commit' }) - // The synthesized blocker must drive the actionable Create PR intent so a - // failed remote probe still offers commit/publish preparation. + expect(eligibility).toMatchObject({ + blockedReason: 'dirty', + nextAction: 'commit', + reviewLookupOutcome: 'unavailable' + }) + // Why: branch guidance can remain specific, but a failed lookup cannot authorize creation. expect( resolveCreatePrIntentEligibility({ stagedCount: 1, @@ -53,7 +56,7 @@ describe('buildLocalBlockerHostedReviewCreationEligibility', () => { hostedReviewCreation: eligibility, branchCommitsAhead: 0 }) - ).toEqual({ eligible: true, kind: 'dirty' }) + ).toEqual({ eligible: false, kind: null }) }) it('prefers dirty over no_upstream when both apply, matching main-process ordering', () => { diff --git a/src/renderer/src/components/right-sidebar/source-control-hosted-review-creation-eligibility-snapshot.ts b/src/renderer/src/components/right-sidebar/source-control-hosted-review-creation-eligibility-snapshot.ts index f951af458..0857f94f6 100644 --- a/src/renderer/src/components/right-sidebar/source-control-hosted-review-creation-eligibility-snapshot.ts +++ b/src/renderer/src/components/right-sidebar/source-control-hosted-review-creation-eligibility-snapshot.ts @@ -13,7 +13,9 @@ export function buildLoadingHostedReviewCreationEligibility( review: null, canCreate: false, blockedReason: null, - nextAction: null + nextAction: null, + // Why: a loading placeholder has no authoritative existing-review result. + reviewLookupOutcome: 'unavailable' } } @@ -36,8 +38,8 @@ export function resolveHostedReviewCreationProviderForTarget( /** * Local-status-only eligibility used when the remote creation probe fails or - * times out, so a failed probe still offers the actionable commit/publish/sync - * preparation action instead of leaving an inert disabled button. + * times out, so the UI can show branch guidance without treating the failed + * lookup as authority to create a review. * * Mirrors the main process's own lookup-failure fallback exactly — both its * `canReturnLocalBlocker` guard and its blocker ordering @@ -77,7 +79,9 @@ export function buildLocalBlockerHostedReviewCreationEligibility( review: null, canCreate: false as const, defaultBaseRef: null, - head: branch + head: branch, + // Why: local Git blockers cannot prove that a hosted review does not exist. + reviewLookupOutcome: 'unavailable' as const } if (status.hasUncommittedChanges) { return { ...base, blockedReason: 'dirty', nextAction: 'commit' } diff --git a/src/renderer/src/components/right-sidebar/source-control-primary-action.create-pr-intent.test.ts b/src/renderer/src/components/right-sidebar/source-control-primary-action.create-pr-intent.test.ts index 086f86565..5d5f249a3 100644 --- a/src/renderer/src/components/right-sidebar/source-control-primary-action.create-pr-intent.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control-primary-action.create-pr-intent.test.ts @@ -39,7 +39,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'no_upstream', - nextAction: 'publish' + nextAction: 'publish', + reviewLookupOutcome: 'not_found' } }) ) @@ -63,7 +64,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'needs_sync', - nextAction: 'sync' + nextAction: 'sync', + reviewLookupOutcome: 'not_found' } }) ) @@ -84,7 +86,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'needs_sync', - nextAction: 'sync' + nextAction: 'sync', + reviewLookupOutcome: 'not_found' } }) const result = resolvePrimaryAction(input) @@ -106,7 +109,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'needs_push', - nextAction: 'push' + nextAction: 'push', + reviewLookupOutcome: 'not_found' } }) const result = resolvePrimaryAction(input) @@ -137,7 +141,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'dirty', - nextAction: 'commit' + nextAction: 'commit', + reviewLookupOutcome: 'not_found' } }) ) @@ -159,7 +164,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'dirty', - nextAction: 'commit' + nextAction: 'commit', + reviewLookupOutcome: 'not_found' } }) ) @@ -181,7 +187,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'dirty', - nextAction: 'commit' + nextAction: 'commit', + reviewLookupOutcome: 'not_found' } }) const result = resolvePrimaryAction(input) @@ -206,7 +213,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'default_branch', - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' } }) ) @@ -229,7 +237,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'dirty', - nextAction: 'commit' + nextAction: 'commit', + reviewLookupOutcome: 'not_found' } }) ) @@ -250,7 +259,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'dirty', - nextAction: 'commit' + nextAction: 'commit', + reviewLookupOutcome: 'not_found' } }) ) @@ -270,7 +280,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'dirty', - nextAction: 'commit' + nextAction: 'commit', + reviewLookupOutcome: 'not_found' } }) @@ -299,7 +310,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'needs_push', - nextAction: 'push' + nextAction: 'push', + reviewLookupOutcome: 'not_found' } }) ) @@ -321,7 +333,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'no_upstream', - nextAction: 'publish' + nextAction: 'publish', + reviewLookupOutcome: 'not_found' } }) @@ -354,7 +367,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'needs_sync', - nextAction: 'sync' + nextAction: 'sync', + reviewLookupOutcome: 'not_found' } }) @@ -387,7 +401,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'needs_sync', - nextAction: 'sync' + nextAction: 'sync', + reviewLookupOutcome: 'not_found' } }) @@ -409,7 +424,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: true, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' } }) ) @@ -430,7 +446,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' }, isHostedReviewCreationLoading: true }) @@ -452,7 +469,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: true, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' }, isHostedReviewCreationLoading: true }) @@ -474,7 +492,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: true, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' }, isHostedReviewCreationLoading: true }) @@ -498,7 +517,8 @@ describe('resolvePrimaryAction Create PR intent', () => { review: null, canCreate: false, blockedReason: 'no_upstream', - nextAction: 'publish' + nextAction: 'publish', + reviewLookupOutcome: 'not_found' } }) ) diff --git a/src/renderer/src/components/right-sidebar/source-control-primary-action.test.ts b/src/renderer/src/components/right-sidebar/source-control-primary-action.test.ts index b71ae5218..f03f1e490 100644 --- a/src/renderer/src/components/right-sidebar/source-control-primary-action.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control-primary-action.test.ts @@ -429,7 +429,8 @@ describe('resolvePrimaryAction', () => { review: null, canCreate: false, blockedReason: 'dirty', - nextAction: 'commit' + nextAction: 'commit', + reviewLookupOutcome: 'not_found' } }) @@ -455,7 +456,8 @@ describe('resolvePrimaryAction', () => { review: null, canCreate: false, blockedReason: 'dirty', - nextAction: 'commit' + nextAction: 'commit', + reviewLookupOutcome: 'not_found' } }) @@ -542,7 +544,8 @@ describe('resolvePrimaryAction', () => { review: null, canCreate: true, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' } }) ) @@ -563,7 +566,8 @@ describe('resolvePrimaryAction', () => { review: null, canCreate: true, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' } }) ) @@ -586,7 +590,8 @@ describe('resolvePrimaryAction', () => { review: null, canCreate: true, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' } }) ) diff --git a/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.test.ts b/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.test.ts index d09fc41cc..8017aea44 100644 --- a/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.test.ts +++ b/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.test.ts @@ -51,6 +51,7 @@ function createEligibility( canCreate: true, blockedReason: null, nextAction: null, + reviewLookupOutcome: 'not_found', defaultBaseRef: 'refs/remotes/origin/main', title: 'Review title', body: 'Review body', diff --git a/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.ts b/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.ts index 08a3b311d..815a18abb 100644 --- a/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.ts +++ b/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.ts @@ -48,6 +48,11 @@ type UseCreatePullRequestDialogFieldsOptions = { submitting: boolean prCreationDefaults?: SourceControlAiPrCreationDefaults sourceControlAiActionsVisible?: boolean + // When the composer is hidden by a temporary policy (a hard refresh error) for + // the same context rather than dismissed, retain the in-memory draft so + // recovery does not discard the user's title/body/base edits. Reopening a + // different context still reseeds (guarded by the eligibility key). + retainDraftWhenClosed?: boolean onBranchChangedByGeneration?: () => Promise generation?: { generating: boolean @@ -131,6 +136,7 @@ export function useCreatePullRequestDialogFields({ submitting, prCreationDefaults, sourceControlAiActionsVisible = true, + retainDraftWhenClosed = false, onBranchChangedByGeneration, generation }: UseCreatePullRequestDialogFieldsOptions) { @@ -254,12 +260,18 @@ export function useCreatePullRequestDialogFields({ } } generateInFlightRef.current = false - generationSeedRef.current = null - initializedFromEligibilityRef.current = null - syncedDefaultBaseRef.current = null - baseEditedByUserRef.current = false - setInitializedEligibilityKey(null) - autoGeneratedForKeyRef.current = null + // Why: retain the draft + init marker across a temporary policy hide so a + // hard-error recovery reopening the same context does not reseed and wipe + // edits. A genuine context change still reseeds (the eligibility key on + // reopen differs from the retained marker). + if (!retainDraftWhenClosed) { + generationSeedRef.current = null + initializedFromEligibilityRef.current = null + syncedDefaultBaseRef.current = null + baseEditedByUserRef.current = false + setInitializedEligibilityKey(null) + autoGeneratedForKeyRef.current = null + } setGenerating(false) setGenerateError(null) } @@ -316,6 +328,7 @@ export function useCreatePullRequestDialogFields({ repoId, resolvedDefaultBaseRef, resolvedPrDefaults.draft, + retainDraftWhenClosed, worktreeId, worktreePath ]) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 06fe05685..23cfccec7 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -9292,7 +9292,16 @@ "f273f2271c": "Started the agent. Marked {{value0}} resolved, skipped {{value1}}, failed {{value2}}.", "aa95b81a3a": "Started the agent. Marked {{value0}} resolved, skipped {{value1}}, failed {{value2}}.", "495b2f8c4b": "Started the agent, but could not mark the selected comments resolved.", - "3c3ad3a1d2": "Started the agent. No selected comments can be marked resolved on the host." + "3c3ad3a1d2": "Started the agent. No selected comments can be marked resolved on the host.", + "review": { + "auto_retry": "Orca will retry at {{time}}.", + "open_review": "Open Review", + "retry": "Retry" + }, + "sync": { + "pending": "Syncing…", + "branch": "Sync Branch" + } }, "CreatePullRequestDialog": { "2bc1b4345e": "Cancel", @@ -9908,6 +9917,136 @@ "d77c513c1e": "{{value0}} in progress", "b597440265": "Refresh GitHub status for this branch to load checks and review." } + }, + "review": { + "detail": { + "positive": "Orca also has saved {{reviewLabel}} information that it could not verify.", + "rate_limited": "Orca also could not check {{reviewLabel}} status because {{provider}} is temporarily limiting requests.", + "network": "Orca also could not check {{reviewLabel}} status because this environment could not reach {{provider}}.", + "untyped": "Orca also could not confirm whether this branch already has a {{reviewLabel}}." + }, + "positive": { + "title": "{{reviewLabelCap}} details unavailable", + "body": "Orca has saved {{reviewLabel}} information for this branch but could not confirm its current status." + }, + "no_review": { + "title": "No {{reviewLabel}} found", + "body": "Create a {{reviewLabel}} to start checks and review." + }, + "active": { + "title": "Checking {{reviewLabel}} status", + "body": "Orca is checking {{provider}} for a {{reviewLabel}} on this branch." + }, + "git_loading": { + "title": "Checking branch status", + "body": "Orca is checking this branch before showing create or publish actions." + }, + "git_error": { + "title": "Could not check branch status", + "body": "Orca could not confirm this branch's upstream from this environment. Retry before publishing or creating a {{reviewLabel}}." + }, + "unknown": { + "title": "{{reviewLabelCap}} status unavailable", + "body": "Orca has not confirmed the {{reviewLabel}} status for this branch. Retry to check again." + }, + "paused": { + "title": "{{provider}} refresh paused", + "body": "{{provider}} is temporarily limiting requests. This can happen even when the displayed API quota is not exhausted." + }, + "network": { + "title": "Could not reach {{provider}}", + "body": "This environment could not reach {{provider}}. Check its connection, then retry." + }, + "unknown_error": { + "title": "Could not check {{reviewLabel}} status", + "body": "The lookup failed, so Orca could not confirm whether this branch already has a {{reviewLabel}}." + }, + "untyped": { + "title": "{{reviewLabelCap}} status unavailable", + "body": "Orca could not confirm whether this branch already has a {{reviewLabel}}. Retry to check again." + }, + "auth": { + "title": "{{provider}} authentication failed", + "body": "{{provider}} could not authenticate the credentials available in this environment. Check the {{provider}} login or environment token, then retry." + }, + "permission": { + "title": "{{provider}} access denied", + "body": "The current {{provider}} credentials cannot read this repository's {{reviewLabel}}s. Check the account, token scopes, and repository access, then retry." + }, + "repo": { + "title": "{{provider}} repository unavailable", + "body": "{{provider}} could not resolve or access the repository for the current remote and account. Check the remote and repository access, then retry." + }, + "cli": { + "title": "{{provider}} CLI unavailable", + "body": "Orca could not run {{provider}} CLI in this environment. Set it up here, then retry." + }, + "skipped": { + "disconnected": { + "title": "Host disconnected", + "body": "This repository's execution host is disconnected, so Orca cannot refresh {{reviewLabel}} status." + }, + "bare": { + "title": "Bare repository", + "body": "This repository is bare, so {{reviewLabel}} status is not available here." + }, + "archived": { + "title": "Repository archived", + "body": "This repository is archived, so Orca is not refreshing {{reviewLabel}} status." + }, + "not_git": { + "title": "Not a Git repository", + "body": "Orca could not treat this folder as a Git repository for {{reviewLabel}} status." + }, + "remote": { + "title": "Remote-only context", + "body": "Orca could not refresh {{reviewLabel}} status for this remote context. Retry after the host is available." + } + }, + "no_upstream": { + "title": "No upstream configured", + "body": "Publish this branch to set its upstream before creating a {{reviewLabel}}." + }, + "needs_sync": { + "title": "Branch needs to sync", + "body": "Sync this branch with its upstream before creating a {{reviewLabel}}." + }, + "auth_required": { + "title": "Connect {{provider}}", + "body": "{{provider}} must be connected in this environment before Orca can create a {{reviewLabel}}." + }, + "needs_push": { + "title": "Branch has unpushed commits", + "body": "Push the latest commits before creating a {{reviewLabel}}." + }, + "existing": { + "title": "{{reviewLabelCap}} already exists", + "body": "Orca found an existing {{reviewLabel}} for this branch." + }, + "detached": { + "title": "No current branch", + "body": "Check out a branch before creating a {{reviewLabel}}." + }, + "dirty": { + "title": "Commit changes first", + "body": "Commit or stash your changes before creating a {{reviewLabel}}." + }, + "default_branch": { + "title": "On the default branch", + "body": "Switch to a feature branch before creating a {{reviewLabel}}." + }, + "fork": { + "title": "Fork head unsupported", + "body": "Orca cannot create a {{reviewLabel}} from this fork head here." + }, + "base_missing": { + "title": "Base branch not on remote", + "body": "This branch's base is not on the remote yet, so a {{reviewLabel}} cannot target it." + }, + "unsupported": { + "title": "{{reviewLabelCap}} not supported here", + "body": "This repository provider does not support creating a {{reviewLabel}} from Orca." + } } } }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index fe010cb30..fe3ac1620 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -9269,7 +9269,16 @@ "f273f2271c": "Agente iniciado. Marcados como resueltos: {{value0}}; omitidos: {{value1}}; con error: {{value2}}.", "aa95b81a3a": "Agente iniciado. Marcados como resueltos: {{value0}}; omitidos: {{value1}}; con error: {{value2}}.", "495b2f8c4b": "Agente iniciado, pero no se pudieron marcar los comentarios seleccionados como resueltos.", - "3c3ad3a1d2": "Agente iniciado. No se puede marcar ningún comentario seleccionado como resuelto en el host." + "3c3ad3a1d2": "Agente iniciado. No se puede marcar ningún comentario seleccionado como resuelto en el host.", + "review": { + "auto_retry": "Orca reintentará a las {{time}}.", + "open_review": "Abrir revisión", + "retry": "Reintentar" + }, + "sync": { + "pending": "Syncing…", + "branch": "Sync Branch" + } }, "CreatePullRequestDialog": { "2bc1b4345e": "Cancelar", @@ -9885,6 +9894,136 @@ "d77c513c1e": "{{value0}} en progreso", "b597440265": "Actualiza el estado de GitHub de esta rama para cargar checks y revisión." } + }, + "review": { + "detail": { + "positive": "Orca también tiene información de {{reviewLabel}} guardada que no pudo verificar.", + "rate_limited": "Orca también no pudo verificar el estado de {{reviewLabel}} porque {{provider}} está limitando temporalmente las solicitudes.", + "network": "Orca también no pudo verificar el estado de {{reviewLabel}} porque este entorno no pudo conectar con {{provider}}.", + "untyped": "Orca también no pudo confirmar si esta rama ya tiene un {{reviewLabel}}." + }, + "positive": { + "title": "Detalles de {{reviewLabelCap}} no disponibles", + "body": "Orca ha guardado información de {{reviewLabel}} para esta rama pero no pudo confirmar su estado actual." + }, + "no_review": { + "title": "No se encontró ningún {{reviewLabel}}", + "body": "Crea un {{reviewLabel}} para iniciar las verificaciones y la revisión." + }, + "active": { + "title": "Verificando estado de {{reviewLabel}}", + "body": "Orca está verificando {{provider}} para un {{reviewLabel}} en esta rama." + }, + "git_loading": { + "title": "Verificando estado de la rama", + "body": "Orca está verificando esta rama antes de mostrar las acciones de creación o publicación." + }, + "git_error": { + "title": "No se pudo verificar el estado de la rama", + "body": "Orca no pudo confirmar el upstream de esta rama desde este entorno. Reintenta antes de publicar o crear un {{reviewLabel}}." + }, + "unknown": { + "title": "Estado de {{reviewLabelCap}} no disponible", + "body": "Orca no ha confirmado el estado de {{reviewLabel}} para esta rama. Reintenta para verificar de nuevo." + }, + "paused": { + "title": "Actualización de {{provider}} pausada", + "body": "{{provider}} está limitando temporalmente las solicitudes. Esto puede ocurrir incluso cuando la cuota de API mostrada no está agotada." + }, + "network": { + "title": "No se pudo conectar con {{provider}}", + "body": "Este entorno no pudo conectar con {{provider}}. Verifica su conexión y reintenta." + }, + "unknown_error": { + "title": "No se pudo verificar el estado de {{reviewLabel}}", + "body": "La búsqueda falló, por lo que Orca no pudo confirmar si esta rama ya tiene un {{reviewLabel}}." + }, + "untyped": { + "title": "Estado de {{reviewLabelCap}} no disponible", + "body": "Orca no pudo confirmar si esta rama ya tiene un {{reviewLabel}}. Reintenta para verificar de nuevo." + }, + "auth": { + "title": "Autenticación de {{provider}} fallida", + "body": "{{provider}} no pudo autenticar las credenciales disponibles en este entorno. Verifica el inicio de sesión de {{provider}} o el token del entorno y reintenta." + }, + "permission": { + "title": "Acceso denegado por {{provider}}", + "body": "Las credenciales actuales de {{provider}} no pueden leer los {{reviewLabel}} de este repositorio. Verifica la cuenta, los alcances del token y el acceso al repositorio, luego reintenta." + }, + "repo": { + "title": "Repositorio de {{provider}} no disponible", + "body": "{{provider}} no pudo resolver o acceder al repositorio del remote y cuenta actuales. Verifica el remote y el acceso al repositorio, luego reintenta." + }, + "cli": { + "title": "CLI de {{provider}} no disponible", + "body": "Orca no pudo ejecutar la CLI de {{provider}} en este entorno. Configúrala aquí y reintenta." + }, + "skipped": { + "disconnected": { + "title": "Host desconectado", + "body": "El host de ejecución de este repositorio está desconectado, por lo que Orca no puede actualizar el estado de {{reviewLabel}}." + }, + "bare": { + "title": "Repositorio bare", + "body": "Este repositorio es bare, por lo que el estado de {{reviewLabel}} no está disponible aquí." + }, + "archived": { + "title": "Repositorio archivado", + "body": "Este repositorio está archivado, por lo que Orca no está actualizando el estado de {{reviewLabel}}." + }, + "not_git": { + "title": "No es un repositorio Git", + "body": "Orca no pudo tratar esta carpeta como un repositorio Git para el estado de {{reviewLabel}}." + }, + "remote": { + "title": "Contexto solo remoto", + "body": "Orca no pudo actualizar el estado de {{reviewLabel}} para este contexto remoto. Reintenta cuando el host esté disponible." + } + }, + "no_upstream": { + "title": "Sin upstream configurado", + "body": "Publica esta rama para configurar su upstream antes de crear un {{reviewLabel}}." + }, + "needs_sync": { + "title": "La rama necesita sincronizarse", + "body": "Sincroniza esta rama con su upstream antes de crear un {{reviewLabel}}." + }, + "auth_required": { + "title": "Conecta {{provider}}", + "body": "{{provider}} debe estar conectado en este entorno antes de que Orca pueda crear un {{reviewLabel}}." + }, + "needs_push": { + "title": "La rama tiene commits sin enviar", + "body": "Envía los últimos commits antes de crear un {{reviewLabel}}." + }, + "existing": { + "title": "{{reviewLabelCap}} ya existe", + "body": "Orca encontró un {{reviewLabel}} existente para esta rama." + }, + "detached": { + "title": "Sin rama actual", + "body": "Selecciona una rama antes de crear un {{reviewLabel}}." + }, + "dirty": { + "title": "Primero confirma los cambios", + "body": "Confirma o guarda tus cambios antes de crear un {{reviewLabel}}." + }, + "default_branch": { + "title": "En la rama por defecto", + "body": "Cambia a una rama de características antes de crear un {{reviewLabel}}." + }, + "fork": { + "title": "Fork head no soportado", + "body": "Orca no puede crear un {{reviewLabel}} desde este fork head aquí." + }, + "base_missing": { + "title": "La rama base no está en el remote", + "body": "La base de esta rama aún no está en el remote, por lo que un {{reviewLabel}} no puede apuntar a ella." + }, + "unsupported": { + "title": "{{reviewLabelCap}} no soportado aquí", + "body": "Este proveedor de repositorio no soporta la creación de un {{reviewLabel}} desde Orca." + } } } }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 326b87d99..eaf4518cc 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -9269,7 +9269,16 @@ "f273f2271c": "agent を開始しました。{{value0}} 件を解決済みにし、{{value1}} 件をスキップ、{{value2}} 件が失敗しました。", "aa95b81a3a": "agent を開始しました。{{value0}} 件を解決済みにし、{{value1}} 件をスキップ、{{value2}} 件が失敗しました。", "495b2f8c4b": "agent を開始しましたが、選択したコメントを解決済みにできませんでした。", - "3c3ad3a1d2": "agent を開始しました。選択したコメントにホスト上で解決済みにできるものはありません。" + "3c3ad3a1d2": "agent を開始しました。選択したコメントにホスト上で解決済みにできるものはありません。", + "review": { + "auto_retry": "Orca は {{time}} に再試行します。", + "open_review": "レビューを開く", + "retry": "再試行" + }, + "sync": { + "pending": "Syncing…", + "branch": "Sync Branch" + } }, "CreatePullRequestDialog": { "2bc1b4345e": "キャンセル", @@ -9885,6 +9894,136 @@ "d77c513c1e": "{{value0}} が進行中です", "b597440265": "Refresh GitHub status for this branch to load checks and review." } + }, + "review": { + "detail": { + "positive": "Orca は保存された {{reviewLabel}} 情報を持っていますが、検証できませんでした。", + "rate_limited": "Orca は {{provider}} がリクエストを一時的に制限しているため、{{reviewLabel}} ステータスを確認できませんでした。", + "network": "Orca はこの環境から {{provider}} に接続できないため、{{reviewLabel}} ステータスを確認できませんでした。", + "untyped": "Orca はこのブランチに {{reviewLabel}} が既に存在するかどうかを確認できませんでした。" + }, + "positive": { + "title": "{{reviewLabelCap}} の詳細が利用できません", + "body": "Orca はこのブランチの {{reviewLabel}} 情報を保存しましたが、現在のステータスを確認できませんでした。" + }, + "no_review": { + "title": "{{reviewLabel}} が見つかりません", + "body": "{{reviewLabel}} を作成して、チェックとレビューを開始します。" + }, + "active": { + "title": "{{reviewLabel}} ステータスを確認中", + "body": "Orca はこのブランチの {{provider}} 上の {{reviewLabel}} を確認しています。" + }, + "git_loading": { + "title": "ブランチのステータスを確認中", + "body": "Orca はこのブランチの作成または公開アクションを表示する前に確認しています。" + }, + "git_error": { + "title": "ブランチのステータスを確認できませんでした", + "body": "Orca はこの環境からこのブランチのアップストリームを確認できませんでした。公開または {{reviewLabel}} の作成前に再試行してください。" + }, + "unknown": { + "title": "{{reviewLabelCap}} ステータスが利用できません", + "body": "Orca はこのブランチの {{reviewLabel}} ステータスを確認していません。再試行して再度確認してください。" + }, + "paused": { + "title": "{{provider}} の更新が一時停止されています", + "body": "{{provider}} がリクエストを一時的に制限しています。表示された API クォータが枯渇していない場合でも発生する可能性があります。" + }, + "network": { + "title": "{{provider}} に接続できませんでした", + "body": "この環境から {{provider}} に接続できませんでした。接続を確認して再試行してください。" + }, + "unknown_error": { + "title": "{{reviewLabel}} ステータスを確認できませんでした", + "body": "検索に失敗したため、Orca はこのブランチに {{reviewLabel}} が既に存在するかどうかを確認できませんでした。" + }, + "untyped": { + "title": "{{reviewLabelCap}} ステータスが利用できません", + "body": "Orca はこのブランチに {{reviewLabel}} が既に存在するかどうかを確認できませんでした。再試行して再度確認してください。" + }, + "auth": { + "title": "{{provider}} の認証に失敗しました", + "body": "{{provider}} はこの環境で使用可能な資格情報を認証できませんでした。{{provider}} のログインまたは環境トークンを確認して再試行してください。" + }, + "permission": { + "title": "{{provider}} のアクセスが拒否されました", + "body": "現在の {{provider}} の資格情報ではこのリポジトリの {{reviewLabel}} を読み取れません。アカウント、トークンスコープ、リポジトリのアクセス権を確認して再試行してください。" + }, + "repo": { + "title": "{{provider}} リポジトリが利用できません", + "body": "{{provider}} は現在のリモートとアカウントのリポジトリを解決またはアクセスできませんでした。リモートとリポジトリのアクセス権を確認して再試行してください。" + }, + "cli": { + "title": "{{provider}} CLI が利用できません", + "body": "Orca はこの環境で {{provider}} CLI を実行できませんでした。ここでセットアップして再試行してください。" + }, + "skipped": { + "disconnected": { + "title": "ホストが切断されました", + "body": "このリポジトリの実行ホストが切断されたため、Orca は {{reviewLabel}} ステータスを更新できません。" + }, + "bare": { + "title": "ベアリポジトリ", + "body": "このリポジトリはベアリポジトリであるため、{{reviewLabel}} ステータスはここでは利用できません。" + }, + "archived": { + "title": "リポジトリがアーカイブされています", + "body": "このリポジトリはアーカイブされているため、Orca は {{reviewLabel}} ステータスを更新しません。" + }, + "not_git": { + "title": "Git リポジトリではありません", + "body": "Orca はこのフォルダを {{reviewLabel}} ステータス用の Git リポジトリとして扱えませんでした。" + }, + "remote": { + "title": "リモートのみのコンテキスト", + "body": "Orca はこのリモートコンテキストの {{reviewLabel}} ステータスを更新できませんでした。ホストが利用可能になった後に再試行してください。" + } + }, + "no_upstream": { + "title": "アップストリームが設定されていません", + "body": "このブランチを公開してアップストリームを設定してから {{reviewLabel}} を作成してください。" + }, + "needs_sync": { + "title": "ブランチの同期が必要です", + "body": "{{reviewLabel}} を作成する前に、このブランチをアップストリームと同期してください。" + }, + "auth_required": { + "title": "{{provider}} を接続してください", + "body": "Orca が {{reviewLabel}} を作成する前に、この環境で {{provider}} を接続する必要があります。" + }, + "needs_push": { + "title": "ブランチに未プッシュのコミットがあります", + "body": "{{reviewLabel}} を作成する前に、最新のコミットをプッシュしてください。" + }, + "existing": { + "title": "{{reviewLabelCap}} は既に存在します", + "body": "Orca はこのブランチの既存の {{reviewLabel}} を見つけました。" + }, + "detached": { + "title": "現在のブランチがありません", + "body": "{{reviewLabel}} を作成する前にブランチをチェックアウトしてください。" + }, + "dirty": { + "title": "まず変更をコミットしてください", + "body": "{{reviewLabel}} を作成する前に、変更をコミットまたはスタッシュしてください。" + }, + "default_branch": { + "title": "デフォルトブランチ上です", + "body": "{{reviewLabel}} を作成する前に、フィーチャーブランチに切り替えてください。" + }, + "fork": { + "title": "フォークヘッドはサポートされていません", + "body": "Orca はここからこのフォークヘッドの {{reviewLabel}} を作成できません。" + }, + "base_missing": { + "title": "ベースブランチがリモートにありません", + "body": "このブランチのベースがまだリモートにないため、{{reviewLabel}} をターゲットにできません。" + }, + "unsupported": { + "title": "ここでは {{reviewLabelCap}} はサポートされていません", + "body": "このリポジトリプロバイダーは、Orca からの {{reviewLabel}} の作成をサポートしていません。" + } } } }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 0de35bc77..742d8531e 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -9269,7 +9269,16 @@ "f273f2271c": "agent를 시작했습니다. {{value0}}개 해결됨으로 표시, {{value1}}개 건너뜀, {{value2}}개 실패.", "aa95b81a3a": "agent를 시작했습니다. {{value0}}개 해결됨으로 표시, {{value1}}개 건너뜀, {{value2}}개 실패.", "495b2f8c4b": "agent를 시작했지만 선택한 댓글을 해결됨으로 표시할 수 없습니다.", - "3c3ad3a1d2": "agent를 시작했습니다. 호스트에서 해결됨으로 표시할 수 있는 선택된 댓글이 없습니다." + "3c3ad3a1d2": "agent를 시작했습니다. 호스트에서 해결됨으로 표시할 수 있는 선택된 댓글이 없습니다.", + "review": { + "auto_retry": "Orca가 {{time}}에 다시 시도합니다.", + "open_review": "검토 열기", + "retry": "다시 시도" + }, + "sync": { + "pending": "Syncing…", + "branch": "Sync Branch" + } }, "CreatePullRequestDialog": { "2bc1b4345e": "취소", @@ -9885,6 +9894,136 @@ "d77c513c1e": "{{value0}} 진행 중", "b597440265": "검사와 리뷰를 불러오려면 이 브랜치의 GitHub 상태를 새로 고치세요." } + }, + "review": { + "detail": { + "positive": "Orca에는 확인할 수 없는 저장된 {{reviewLabel}} 정보가 있습니다.", + "rate_limited": "{{provider}}가 요청을 일시적으로 제한하고 있어 Orca도 {{reviewLabel}} 상태를 확인할 수 없었습니다.", + "network": "이 환경에서 {{provider}}에 연결할 수 없어 Orca도 {{reviewLabel}} 상태를 확인할 수 없었습니다.", + "untyped": "Orca는 이 브랜치에 이미 {{reviewLabel}}가 있는지 확인할 수 없었습니다." + }, + "positive": { + "title": "{{reviewLabelCap}} 세부 정보를 사용할 수 없음", + "body": "Orca는 이 브랜치의 {{reviewLabel}} 정보를 저장했지만 현재 상태를 확인할 수 없었습니다." + }, + "no_review": { + "title": "{{reviewLabel}}를 찾을 수 없음", + "body": "{{reviewLabel}}를 만들어 검사와 리뷰를 시작하세요." + }, + "active": { + "title": "{{reviewLabel}} 상태 확인 중", + "body": "Orca는 이 브랜치의 {{provider}}에서 {{reviewLabel}}를 확인하고 있습니다." + }, + "git_loading": { + "title": "브랜치 상태 확인 중", + "body": "Orca는 생성 또는 게시 작업을 표시하기 전에 이 브랜치를 확인하고 있습니다." + }, + "git_error": { + "title": "브랜치 상태를 확인할 수 없음", + "body": "Orca는 이 환경에서 이 브랜치의 업스트림을 확인할 수 없었습니다. 게시하거나 {{reviewLabel}}를 만들기 전에 다시 시도하세요." + }, + "unknown": { + "title": "{{reviewLabelCap}} 상태를 사용할 수 없음", + "body": "Orca가 이 브랜치의 {{reviewLabel}} 상태를 확인하지 못했습니다. 다시 시도하여 확인하세요." + }, + "paused": { + "title": "{{provider}} 새로고침 일시 중지됨", + "body": "{{provider}}가 요청을 일시적으로 제한하고 있습니다. 표시된 API 할당량이 소진되지 않은 경우에도 발생할 수 있습니다." + }, + "network": { + "title": "{{provider}}에 연결할 수 없음", + "body": "이 환경에서 {{provider}}에 연결할 수 없었습니다. 연결을 확인한 후 다시 시도하세요." + }, + "unknown_error": { + "title": "{{reviewLabel}} 상태를 확인할 수 없음", + "body": "조회에 실패하여 Orca는 이 브랜치에 이미 {{reviewLabel}}가 있는지 확인할 수 없었습니다." + }, + "untyped": { + "title": "{{reviewLabelCap}} 상태를 사용할 수 없음", + "body": "Orca는 이 브랜치에 이미 {{reviewLabel}}가 있는지 확인할 수 없었습니다. 다시 시도하여 확인하세요." + }, + "auth": { + "title": "{{provider}} 인증 실패", + "body": "{{provider}}는 이 환경에서 사용 가능한 자격 증명을 인증할 수 없었습니다. {{provider}} 로그인 또는 환경 토큰을 확인한 후 다시 시도하세요." + }, + "permission": { + "title": "{{provider}} 접근 거부됨", + "body": "현재 {{provider}} 자격 증명으로는 이 리포지토리의 {{reviewLabel}}를 읽을 수 없습니다. 계정, 토큰 범위 및 리포지토리 접근 권한을 확인한 후 다시 시도하세요." + }, + "repo": { + "title": "{{provider}} 리포지토리를 사용할 수 없음", + "body": "{{provider}}는 현재 리모트와 계정의 리포지토리를 확인하거나 접근할 수 없었습니다. 리모트와 리포지토리 접근 권한을 확인한 후 다시 시도하세요." + }, + "cli": { + "title": "{{provider}} CLI를 사용할 수 없음", + "body": "Orca는 이 환경에서 {{provider}} CLI를 실행할 수 없었습니다. 여기에서 설정한 후 다시 시도하세요." + }, + "skipped": { + "disconnected": { + "title": "호스트 연결 끊김", + "body": "이 리포지토리의 실행 호스트가 연결 해제되어 Orca가 {{reviewLabel}} 상태를 새로고칠 수 없습니다." + }, + "bare": { + "title": "베어 리포지토리", + "body": "이 리포지토리는 베어 리포지토리이므로 여기에서 {{reviewLabel}} 상태를 사용할 수 없습니다." + }, + "archived": { + "title": "리포지토리가 보관됨", + "body": "이 리포지토리가 보관되어 있으므로 Orca가 {{reviewLabel}} 상태를 새로고치지 않습니다." + }, + "not_git": { + "title": "Git 리포지토리가 아님", + "body": "Orca는 {{reviewLabel}} 상태용으로 이 폴더를 Git 리포지토리로 처리할 수 없었습니다." + }, + "remote": { + "title": "리모트 전용 컨텍스트", + "body": "Orca는 이 리모트 컨텍스트의 {{reviewLabel}} 상태를 새로고칠 수 없었습니다. 호스트를 사용할 수 있을 때 다시 시도하세요." + } + }, + "no_upstream": { + "title": "업스트림이 설정되지 않음", + "body": "{{reviewLabel}}를 만들기 전에 이 브랜치를 게시하여 업스트림을 설정하세요." + }, + "needs_sync": { + "title": "브랜치 동기화 필요", + "body": "{{reviewLabel}}를 만들기 전에 이 브랜치를 업스트림과 동기화하세요." + }, + "auth_required": { + "title": "{{provider}} 연결", + "body": "Orca가 {{reviewLabel}}를 만들려면 이 환경에서 {{provider}}가 연결되어 있어야 합니다." + }, + "needs_push": { + "title": "브랜치에 푸시하지 않은 커밋이 있음", + "body": "{{reviewLabel}}를 만들기 전에 최신 커밋을 푸시하세요." + }, + "existing": { + "title": "{{reviewLabelCap}}이(가) 이미 존재함", + "body": "Orca는 이 브랜치의 기존 {{reviewLabel}}를 찾았습니다." + }, + "detached": { + "title": "현재 브랜치가 없음", + "body": "{{reviewLabel}}를 만들기 전에 브랜치를 체크아웃하세요." + }, + "dirty": { + "title": "먼저 변경 사항을 커밋하세요", + "body": "{{reviewLabel}}를 만들기 전에 변경 사항을 커밋하거나 스태시하세요." + }, + "default_branch": { + "title": "기본 브랜치 위에 있음", + "body": "{{reviewLabel}}를 만들기 전에 기능 브랜치로 전환하세요." + }, + "fork": { + "title": "포크 헤드 지원되지 않음", + "body": "Orca는 여기에서 이 포크 헤드의 {{reviewLabel}}를 만들 수 없습니다." + }, + "base_missing": { + "title": "기본 브랜치가 리모트에 없음", + "body": "이 브랜치의 기본이 아직 리모트에 없으므로 {{reviewLabel}}가 이를 대상으로 할 수 없습니다." + }, + "unsupported": { + "title": "여기서 {{reviewLabelCap}}이(가) 지원되지 않음", + "body": "이 리포지토리 제공자는 Orca에서 {{reviewLabel}}를 만드는 것을 지원하지 않습니다." + } } } }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 6a8e1bd94..657a353bd 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -9269,7 +9269,16 @@ "f273f2271c": "已启动智能体。已标记 {{value0}} 个为已解决,跳过 {{value1}} 个,失败 {{value2}} 个。", "aa95b81a3a": "已启动智能体。已标记 {{value0}} 个为已解决,跳过 {{value1}} 个,失败 {{value2}} 个。", "495b2f8c4b": "已启动智能体,但无法将选中的评论标记为已解决。", - "3c3ad3a1d2": "已启动智能体。选中的评论中没有可在托管平台上标记为已解决的评论。" + "3c3ad3a1d2": "已启动智能体。选中的评论中没有可在托管平台上标记为已解决的评论。", + "review": { + "auto_retry": "Orca 将在 {{time}} 重试。", + "open_review": "打开评审", + "retry": "重试" + }, + "sync": { + "pending": "Syncing…", + "branch": "Sync Branch" + } }, "CreatePullRequestDialog": { "2bc1b4345e": "取消", @@ -9885,6 +9894,136 @@ "d77c513c1e": "{{value0}} 正在进行中", "b597440265": "刷新此分支的 GitHub 状态以加载检查和审核。" } + }, + "review": { + "detail": { + "positive": "Orca 也有已保存的 {{reviewLabel}} 信息但无法验证。", + "rate_limited": "Orca 无法检查 {{reviewLabel}} 状态,因为 {{provider}} 正在临时限制请求。", + "network": "Orca 无法检查 {{reviewLabel}} 状态,因为当前环境无法连接到 {{provider}}。", + "untyped": "Orca 无法确认此分支是否已有 {{reviewLabel}}。" + }, + "positive": { + "title": "{{reviewLabelCap}} 详细信息不可用", + "body": "Orca 已为此分支保存了 {{reviewLabel}} 信息,但无法确认其当前状态。" + }, + "no_review": { + "title": "未找到 {{reviewLabel}}", + "body": "创建 {{reviewLabel}} 以开始检查和评审。" + }, + "active": { + "title": "正在检查 {{reviewLabel}} 状态", + "body": "Orca 正在检查 {{provider}} 上此分支的 {{reviewLabel}}。" + }, + "git_loading": { + "title": "正在检查分支状态", + "body": "Orca 正在检查此分支,然后显示创建或发布操作。" + }, + "git_error": { + "title": "无法检查分支状态", + "body": "Orca 无法从当前环境确认此分支的上游。请在发布或创建 {{reviewLabel}} 之前重试。" + }, + "unknown": { + "title": "{{reviewLabelCap}} 状态不可用", + "body": "Orca 尚未确认此分支的 {{reviewLabel}} 状态。请重试以再次检查。" + }, + "paused": { + "title": "{{provider}} 刷新已暂停", + "body": "{{provider}} 正在临时限制请求。即使显示的 API 配额未用完,也可能发生这种情况。" + }, + "network": { + "title": "无法连接到 {{provider}}", + "body": "当前环境无法连接到 {{provider}}。请检查连接后重试。" + }, + "unknown_error": { + "title": "无法检查 {{reviewLabel}} 状态", + "body": "查询失败,Orca 无法确认此分支是否已有 {{reviewLabel}}。" + }, + "untyped": { + "title": "{{reviewLabelCap}} 状态不可用", + "body": "Orca 无法确认此分支是否已有 {{reviewLabel}}。请重试以再次检查。" + }, + "auth": { + "title": "{{provider}} 身份验证失败", + "body": "{{provider}} 无法验证当前环境中的凭据。请检查 {{provider}} 登录或环境令牌后重试。" + }, + "permission": { + "title": "{{provider}} 访问被拒绝", + "body": "当前 {{provider}} 凭据无法读取此仓库的 {{reviewLabel}}。请检查账户、令牌范围和仓库访问权限后重试。" + }, + "repo": { + "title": "{{provider}} 仓库不可用", + "body": "{{provider}} 无法解析或访问当前远程和账户的仓库。请检查远程和仓库访问权限后重试。" + }, + "cli": { + "title": "{{provider}} CLI 不可用", + "body": "Orca 无法在当前环境中运行 {{provider}} CLI。请在此处设置后重试。" + }, + "skipped": { + "disconnected": { + "title": "主机已断开连接", + "body": "此仓库的执行主机已断开连接,Orca 无法刷新 {{reviewLabel}} 状态。" + }, + "bare": { + "title": "裸仓库", + "body": "此仓库是裸仓库,因此此处无法使用 {{reviewLabel}} 状态。" + }, + "archived": { + "title": "仓库已归档", + "body": "此仓库已归档,Orca 不会刷新 {{reviewLabel}} 状态。" + }, + "not_git": { + "title": "不是 Git 仓库", + "body": "Orca 无法将此文件夹作为 Git 仓库来获取 {{reviewLabel}} 状态。" + }, + "remote": { + "title": "仅远程上下文", + "body": "Orca 无法刷新此远程上下文的 {{reviewLabel}} 状态。请在主机可用后重试。" + } + }, + "no_upstream": { + "title": "未配置上游", + "body": "请在创建 {{reviewLabel}} 之前发布此分支以设置其上游。" + }, + "needs_sync": { + "title": "分支需要同步", + "body": "请在创建 {{reviewLabel}} 之前将此分支与其上游同步。" + }, + "auth_required": { + "title": "连接 {{provider}}", + "body": "Orca 创建 {{reviewLabel}} 之前,必须在当前环境中连接 {{provider}}。" + }, + "needs_push": { + "title": "分支有未推送的提交", + "body": "请在创建 {{reviewLabel}} 之前推送最新提交。" + }, + "existing": { + "title": "{{reviewLabelCap}} 已存在", + "body": "Orca 找到了此分支的现有 {{reviewLabel}}。" + }, + "detached": { + "title": "没有当前分支", + "body": "请在创建 {{reviewLabel}} 之前检出分支。" + }, + "dirty": { + "title": "请先提交更改", + "body": "请在创建 {{reviewLabel}} 之前提交或暂存更改。" + }, + "default_branch": { + "title": "在默认分支上", + "body": "请在创建 {{reviewLabel}} 之前切换到功能分支。" + }, + "fork": { + "title": "不支持 Fork 头", + "body": "Orca 无法从此处的 Fork 头创建 {{reviewLabel}}。" + }, + "base_missing": { + "title": "基础分支不在远程上", + "body": "此分支的基础尚未在远程上,因此无法将 {{reviewLabel}} 定向到它。" + }, + "unsupported": { + "title": "此处不支持 {{reviewLabelCap}}", + "body": "此仓库提供程序不支持从 Orca 创建 {{reviewLabel}}。" + } } } }, diff --git a/src/renderer/src/store/slices/github.ts b/src/renderer/src/store/slices/github.ts index 322fc8568..7a6527e46 100644 --- a/src/renderer/src/store/slices/github.ts +++ b/src/renderer/src/store/slices/github.ts @@ -12,7 +12,9 @@ import type { GitHubPRRefreshCandidate, GitHubPRRefreshEvent, GitHubPRRefreshReason, - PRRefreshUpstreamErrorType, + GitHubPRRefreshSkippedReason, + PRRefreshErrorType, + PRRefreshOutcome, GitHubCommentResult, IssueInfo, PRCheckDetail, @@ -676,10 +678,11 @@ export type PRRefreshState = { updatedAt: number pausedUntil?: number message?: string - // Why: lets error surfaces render translated, GitHub-attributed copy keyed on - // the failure kind (e.g. a 5xx outage vs. a rate limit) rather than showing - // the main process's English `message` verbatim. - errorType?: PRRefreshUpstreamErrorType + // Why: classified errors drive stable copy without exposing raw upstream messages. + errorType?: PRRefreshErrorType + skippedReason?: GitHubPRRefreshSkippedReason + nextAutoRetryAt?: number + retryDisabledUntil?: number } export type PRRefreshStateClearToken = { @@ -2171,6 +2174,24 @@ export type GitHubSlice = { patchProjectRowContent: (cacheKey: string, rowId: string, patch: ProjectRowContentPatch) => void } +/** + * Normalizes the `github.prForBranch` runtime RPC result into a + * {@link PRRefreshOutcome}. Current hosts return the full outcome (with a + * `kind`), so a runtime `upstream-error` is preserved instead of collapsing to a + * false accepted "no PR". A legacy host that still returns `PRInfo | null` is + * mapped to `found` / `no-pr` to preserve backward behavior on that host only. + */ +function normalizeRuntimePRForBranchOutcome( + result: PRRefreshOutcome | PRInfo | null +): PRRefreshOutcome { + if (result && typeof result === 'object' && 'kind' in result) { + return result + } + return result + ? { kind: 'found', pr: result, fetchedAt: Date.now() } + : { kind: 'no-pr', fetchedAt: Date.now() } +} + export const createGitHubSlice: StateCreator = (set, get) => ({ prCache: {}, issueCache: {}, @@ -3202,7 +3223,7 @@ export const createGitHubSlice: StateCreator = (s : null const requestHeadOid = candidateWorktree?.head ?? null const outcome = runtimeRepo - ? await callRuntimeRpc( + ? await callRuntimeRpc( runtimeRepo.target, 'github.prForBranch', { @@ -3215,11 +3236,7 @@ export const createGitHubSlice: StateCreator = (s : {}) }, { timeoutMs: 30_000 } - ).then((pr) => - pr - ? ({ kind: 'found', pr, fetchedAt: Date.now() } as const) - : ({ kind: 'no-pr', fetchedAt: Date.now() } as const) - ) + ).then((result) => normalizeRuntimePRForBranchOutcome(result)) : await (async () => { const candidate: GitHubPRRefreshCandidate = { repoId: repoId ?? '', @@ -3263,6 +3280,27 @@ export const createGitHubSlice: StateCreator = (s const pr: PRInfo | null = outcome.kind === 'found' ? outcome.pr : outcome.kind === 'no-pr' ? null : null if (outcome.kind === 'upstream-error') { + // Why: the runtime RPC path does not flow through the coordinator + // broadcast that populates prRefreshStates on native execution, so a + // runtime/SSH gh failure would otherwise show generic "checking" copy. + // Record the classified error + schedule here so the Checks panel shows + // the same classified failure copy as native (design criterion 2). + if (runtimeRepo && prRequestGenerations.get(cacheKey) === generation) { + set((s) => { + const nextStates = { ...s.prRefreshStates } + delete nextStates[cacheKey] + nextStates[cacheKey] = { + status: 'error', + reason: 'swr', + updatedAt: Date.now(), + message: outcome.message, + errorType: outcome.errorType, + nextAutoRetryAt: outcome.nextAutoRetryAt, + retryDisabledUntil: outcome.retryDisabledUntil + } + return { prRefreshStates: nextStates } + }) + } return cached?.data ?? null } if (prRequestGenerations.get(cacheKey) === generation) { @@ -4155,7 +4193,9 @@ export const createGitHubSlice: StateCreator = (s reason: event.reason, updatedAt: Date.now(), message: event.outcome.message, - errorType: event.outcome.errorType + errorType: event.outcome.errorType, + nextAutoRetryAt: event.outcome.nextAutoRetryAt, + retryDisabledUntil: event.outcome.retryDisabledUntil } continue } @@ -4347,11 +4387,18 @@ export const createGitHubSlice: StateCreator = (s // Why: delete-then-set moves this key to the end of insertion order so // capRecordByInsertionOrder evicts genuinely idle keys, not active ones. delete nextStates[alias.cacheKey] + const isPaused = event.status === 'paused' nextStates[alias.cacheKey] = { status: event.status, reason: event.reason, updatedAt: Date.now(), - pausedUntil: event.pausedUntil + pausedUntil: event.pausedUntil, + skippedReason: event.skippedReason, + // Why: a paused refresh is a rate-limit gate. Map its pausedUntil into + // the unified schedule so the panel shows the auto-retry time and + // disables manual Retry until the limit resets. + nextAutoRetryAt: isPaused ? event.pausedUntil : undefined, + retryDisabledUntil: isPaused ? event.pausedUntil : undefined } } } diff --git a/src/shared/hosted-review.ts b/src/shared/hosted-review.ts index 04094cf07..23cfa6558 100644 --- a/src/shared/hosted-review.ts +++ b/src/shared/hosted-review.ts @@ -119,12 +119,21 @@ export type HostedReviewCreationNextAction = | 'open_existing_review' | null +/** + * Records whether the eligibility result observed an authoritative existing-review + * lookup. `found` / `not_found` come only from an accepted provider lookup; + * `unavailable` marks a local-blocker fallback returned after a swallowed or + * skipped lookup, so it can never masquerade as authoritative no-review evidence. + */ +export type HostedReviewLookupOutcome = 'found' | 'not_found' | 'unavailable' + export type HostedReviewCreationEligibility = { provider: HostedReviewProvider review: HostedReviewSummary | null canCreate: boolean blockedReason: HostedReviewCreationBlockedReason nextAction: HostedReviewCreationNextAction + reviewLookupOutcome: HostedReviewLookupOutcome defaultBaseRef?: string | null head?: string | null title?: string | null diff --git a/src/shared/source-control-create-review-intent.ts b/src/shared/source-control-create-review-intent.ts index f3cb5854f..880fce177 100644 --- a/src/shared/source-control-create-review-intent.ts +++ b/src/shared/source-control-create-review-intent.ts @@ -41,6 +41,11 @@ export function resolveCreateReviewIntentEligibility({ !hasCurrentBranch || !hostedReviewCreation || hostedReviewCreation.canCreate || + // Fail closed when the existing-review lookup could not prove there is no + // review: a local blocker (e.g. needs_push) returned after a failed lookup + // must not offer a Create PR intent that would push under a false promise — + // the main preflight would refuse the create anyway (invariant 8). + hostedReviewCreation.reviewLookupOutcome === 'unavailable' || !supportsHostedReviewCreation(hostedReviewCreation.provider) ) { return { eligible: false, kind: null } diff --git a/src/shared/source-control-primary-action-decision.test.ts b/src/shared/source-control-primary-action-decision.test.ts index 1cdcc1193..6f153d74b 100644 --- a/src/shared/source-control-primary-action-decision.test.ts +++ b/src/shared/source-control-primary-action-decision.test.ts @@ -151,7 +151,8 @@ describe('source-control primary action decision', () => { review: null, canCreate: true, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' } }) expect(resolveSourceControlPrimaryActionDecision(input).kind).toBe('create_pr') @@ -167,7 +168,8 @@ describe('source-control primary action decision', () => { review: null, canCreate: false, blockedReason: null, - nextAction: null + nextAction: null, + reviewLookupOutcome: 'not_found' }, isHostedReviewCreationLoading: true }) diff --git a/src/shared/types.ts b/src/shared/types.ts index 405d9ed5b..ec80f68b6 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1202,9 +1202,13 @@ export type PRInfo = { conflictSummary?: PRConflictSummary } -// server_error covers GitHub-side HTTP 5xx outages (githubstatus.com incidents), -// distinct from a transport-level `network` failure or a `rate_limited` budget. -export type PRRefreshUpstreamErrorType = +/** + * Discriminates a classified GitHub PR-refresh failure. The renderer maps these + * to stable, non-destructive empty-state copy; a `hard` subset (auth, permission, + * repo_unavailable, gh_unavailable) means the existing-review lookup is currently + * impossible and must hide the Create composer. + */ +export type PRRefreshErrorType = | 'rate_limited' | 'auth' | 'network' @@ -1214,14 +1218,23 @@ export type PRRefreshUpstreamErrorType = | 'server_error' | 'unknown' +// Backward-compatible name used by outage-copy consumers added on main. +export type PRRefreshUpstreamErrorType = PRRefreshErrorType + export type PRRefreshOutcome = | { kind: 'found'; pr: PRInfo; fetchedAt: number } | { kind: 'no-pr'; fetchedAt: number } | { kind: 'upstream-error' - errorType: PRRefreshUpstreamErrorType + errorType: PRRefreshErrorType message: string fetchedAt: number + // Unified retry schedule (see docs/reference/pr-panel-refresh-guidance.md). + // `nextAutoRetryAt`: earliest time main expects to auto-retry this key. + // `retryDisabledUntil`: earliest time a manual Retry / refreshPRNow is + // accepted (rate-limit gates only, never ordinary network/auth backoff). + nextAutoRetryAt?: number + retryDisabledUntil?: number } export type GitHubPRRefreshReason = 'visible' | 'active' | 'post-push' | 'manual' | 'swr'