From 233b3dc70474180c852ffbb7081da511fcc54f01 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:26:38 -0700 Subject: [PATCH] Make explicit hosted review refresh fetch current provider state (#36522) * Make explicit hosted review refresh read current provider state * Name the right provider and keep GitHub's own copy when a Checks refresh fails A failed manual refresh now names the repo's provider (from the review, its link, or the remote), clears once a newer read lands for the panel, never stops GitHub checks and comments from refreshing, and gives way to GitHub's classified sign-in or rate-limit copy. The copy is one interpolated line in every locale. * Read after the write when Orca merges, closes, reopens or edits a GitLab MR Every GitLab merge request write now drops the host's cached review lookups for the repository, and the Checks panel's follow-up read can't join a poll that began before the write, so merging in Orca shows Merged and Delete Workspace without a manual Refresh. A user refresh also forgets Gitea's shared repository scan before reading. * Clear a failed Checks refresh only on a real provider read The host now tells the desktop store, when asked, whether its answer came from a provider read it stored as current or from a cache or last-good fallback. The Checks panel keeps a failed Refresh until such a read lands, a click succeeds, or the context changes. On GitHub the PR read owns the refresh status, so a failed review-card read no longer raises the generic failure. * Don't let a joined host lookup clear a failed Checks refresh A poll that joins a lookup already running for an earlier request didn't start that read, so its answer can't show the provider recovered after the failure. Only the request that started the stored lookup reports a provider read now. The host read also uses the shared reply outcome directly, and the renderer writes the provider-read generation where it publishes the entry. * Type the Checks refresh breadcrumb for every review provider The breadcrumb already received Bitbucket, Azure DevOps and Gitea values; its annotation now says so. Tests build typed fixtures instead of asserting types. * Test the read-outcome reply at IPC, RPC and runtime, and the post-merge read The flag reaches the runtime, and only a caller that asks gets the envelope, including for a definitive null. After Orca merges, the card read starts after the write, and its failure leaves the merge reported as done. * Use a boolean for the empty-state fixture's remote-operation flag * Trim redundant hosted-review refresh tests * Keep the signed-out GitHub empty-state test --- config/tsconfig.tc.web.json | 8 + .../gitea/client-scan-invalidation.test.ts | 15 +- .../gitea/pull-request-read-forgetting.ts | 18 + src/main/gitea/pull-request-scan-cache.ts | 3 + .../gitlab/client-mr-review-actions.test.ts | 66 +++ .../gitlab/merge-request-state-mutations.ts | 7 + src/main/gitlab/merge-request-update.ts | 3 + src/main/ipc/hosted-review.test.ts | 54 ++- src/main/ipc/hosted-review.ts | 11 +- .../orca-runtime-test-mocks/setup.spec.ts | 7 +- .../hooks-and-hosted-review-part-03.spec.ts | 37 ++ .../runtime/rpc/methods/hosted-review.test.ts | 54 ++- src/main/runtime/rpc/methods/hosted-review.ts | 2 + .../runtime/runtime-hosted-review-commands.ts | 15 +- .../hosted-review-branch-cache.ts | 99 ++-- .../hosted-review-gitea.integration.test.ts | 15 +- ...osted-review-inflight-invalidation.test.ts | 123 +++++ .../hosted-review-inflight-lookups.test.ts | 4 +- .../hosted-review-inflight-lookups.ts | 17 +- .../hosted-review-provider-read.ts | 22 + src/main/source-control/hosted-review.test.ts | 35 ++ src/main/source-control/hosted-review.ts | 36 +- src/preload/api/hosted-review-api.ts | 8 +- .../checks-panel-pr-refresh-breadcrumb.ts | 4 +- .../checks-panel/active-content-props.ts | 2 +- .../checks-panel/active-content.tsx | 15 +- .../checks-panel/empty-content-props.ts | 2 +- .../checks-panel/empty-content.tsx | 22 +- .../hosted-review-manual-refresh.ts | 122 +++++ .../manual-refresh-dependencies.ts | 5 + .../panel-content-rendering.test.tsx | 152 +++++- ...l-entry-refresh-and-title-actions.test.tsx | 141 ++++++ ...-panel-entry-refresh-and-title-actions.tsx | 7 +- ...cks-panel-manual-refresh-recovery.test.tsx | 455 ++++++++++++++++++ .../use-checks-panel-manual-refresh.tsx | 103 ++-- .../github-refresh-error-copy.ts | 16 + src/renderer/src/i18n/locales/de.json | 3 +- src/renderer/src/i18n/locales/en.json | 3 +- src/renderer/src/i18n/locales/es.json | 3 +- src/renderer/src/i18n/locales/fr.json | 3 +- src/renderer/src/i18n/locales/ja.json | 3 +- src/renderer/src/i18n/locales/ko.json | 3 +- src/renderer/src/i18n/locales/pt.json | 3 +- src/renderer/src/i18n/locales/ru.json | 3 +- src/renderer/src/i18n/locales/tr.json | 3 +- src/renderer/src/i18n/locales/zh-Hant.json | 3 +- src/renderer/src/i18n/locales/zh.json | 3 +- .../src/lib/hosted-review-repo-read.ts | 5 +- .../src/store/lookup-generation-sequence.ts | 7 +- ...thub-pr-branch-hosted-review-cache.test.ts | 3 +- .../slices/hosted-review-cache-race.test.ts | 3 +- .../store/slices/hosted-review-cache-state.ts | 48 ++ .../store/slices/hosted-review-cache.test.ts | 86 ++++ .../slices/hosted-review-card-refresh.ts | 2 + .../slices/hosted-review-request-state.ts | 24 +- .../src/store/slices/hosted-review.test.ts | 1 + .../src/store/slices/hosted-review.ts | 52 +- src/shared/hosted-review.ts | 33 ++ .../rpc-contract/hosted-review-params.ts | 2 + 59 files changed, 1805 insertions(+), 199 deletions(-) create mode 100644 src/main/gitea/pull-request-read-forgetting.ts create mode 100644 src/main/source-control/hosted-review-provider-read.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel/hosted-review-manual-refresh.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh-recovery.test.tsx diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index cd97211c3e9..177ad68d65f 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -28,6 +28,14 @@ "../mobile/src/worktree/worktree-agent-child-rows.ts", "../src/packages/process-host/src/__fixtures__/**/*", "../src/main/gitlab/mappers.ts", + "../src/main/source-control/hosted-review-branch-cache.ts", + "../src/main/source-control/hosted-review-active-branch-claims.ts", + "../src/main/source-control/hosted-review-unsettled-lookups.ts", + "../src/main/source-control/hosted-review-inflight-lookups.ts", + "../src/main/source-control/hosted-review-scope-generations.ts", + "../src/main/source-control/hosted-review-lookup-backoff.ts", + "../src/main/source-control/hosted-review-refresh-pacing.ts", + "../src/main/source-control/hosted-review-provider-read.ts", "../src/main/persistence/profile-state-cutover-fixture.ts", "../src/main/runtime/sidebar-inputs/sidebar-clock.ts", "../src/main/runtime/sidebar-inputs/sidebar-retention-owner.ts", diff --git a/src/main/gitea/client-scan-invalidation.test.ts b/src/main/gitea/client-scan-invalidation.test.ts index d25fcd07f24..3c85776408e 100644 --- a/src/main/gitea/client-scan-invalidation.test.ts +++ b/src/main/gitea/client-scan-invalidation.test.ts @@ -18,7 +18,8 @@ import { } from './client' import { createGiteaPullRequest } from './pull-request-creation' import { _resetGiteaRepoRefCache } from './repository-ref' -import { _resetGiteaPullRequestScanCache } from './pull-request-scan-cache' +import { _resetGiteaPullRequestScanCache, scanGiteaPullRequests } from './pull-request-scan-cache' +import { observeProviderRead } from '../source-control/hosted-review-provider-read' const branch = 'feature/gitea' const pullRequest = { @@ -52,6 +53,18 @@ describe('Gitea scan invalidation after creation', () => { vi.unstubAllEnvs() }) + it('reports a scan answered from the shared cache or a running scan as not a fresh read', async () => { + const fetchPage = vi.fn(async () => [pullRequest]) + const scan = () => + observeProviderRead(() => scanGiteaPullRequests('team/repo', fetchPage, 50, 1)) + const [owner, joiner] = await Promise.all([scan(), scan()]) + const cached = await scan() + expect(fetchPage).toHaveBeenCalledTimes(1) + expect(owner.answeredFromProviderCache).toBe(false) + expect(joiner.answeredFromProviderCache).toBe(true) + expect(cached.answeredFromProviderCache).toBe(true) + }) + it('refreshes cached misses in both modes after a successful create and coalesces readers', async () => { let created = false let listCalls = 0 diff --git a/src/main/gitea/pull-request-read-forgetting.ts b/src/main/gitea/pull-request-read-forgetting.ts new file mode 100644 index 00000000000..fb80bc44de9 --- /dev/null +++ b/src/main/gitea/pull-request-read-forgetting.ts @@ -0,0 +1,18 @@ +import type { ExecutionHostId } from '../../shared/execution-host' +import { hostedReviewSshConnectionId } from '../source-control/hosted-review-execution-host' +import type { HostedReviewExecutionOptions } from '../source-control/hosted-review-git-options' +import { getGiteaRepoSlug, invalidateGiteaPullRequestScanForRepo } from './client' + +/** The repository scan is shared by every branch card for 30s; a user refresh must not be answered by one from before the click. */ +export async function forgetGiteaPullRequestReads( + context: HostedReviewExecutionOptions & { repoPath: string; executionHostId: ExecutionHostId } +): Promise { + const repo = await getGiteaRepoSlug( + context.repoPath, + hostedReviewSshConnectionId(context.executionHostId), + context + ) + if (repo) { + invalidateGiteaPullRequestScanForRepo(repo) + } +} diff --git a/src/main/gitea/pull-request-scan-cache.ts b/src/main/gitea/pull-request-scan-cache.ts index 72a3c9a9aa2..85244d30bf9 100644 --- a/src/main/gitea/pull-request-scan-cache.ts +++ b/src/main/gitea/pull-request-scan-cache.ts @@ -1,3 +1,4 @@ +import { noteProviderCacheAnswer } from '../source-control/hosted-review-provider-read' import type { RawGiteaPullRequest } from './pull-request-mappers' export type GiteaPullRequestPageFetcher = (page: number) => Promise @@ -78,10 +79,12 @@ export async function scanGiteaPullRequests( ): Promise { const cached = reusableScanCacheEntry(repoKey) if (cached) { + noteProviderCacheAnswer() return cached.pullRequests } const running = inFlightScans.get(repoKey) if (running) { + noteProviderCacheAnswer() return running } const generation = scanGenerations.get(repoKey) ?? 0 diff --git a/src/main/gitlab/client-mr-review-actions.test.ts b/src/main/gitlab/client-mr-review-actions.test.ts index fbaf9bc4e32..cd905c30170 100644 --- a/src/main/gitlab/client-mr-review-actions.test.ts +++ b/src/main/gitlab/client-mr-review-actions.test.ts @@ -54,6 +54,11 @@ import { updateMRReviewers } from './client' import { resetGitLabMrMocks } from './client-mr-test-harness' +import type { HostedReviewInfo } from '../../shared/hosted-review' +import { + __resetHostedReviewBranchCacheForTests, + withHostedReviewBranchCache +} from '../source-control/hosted-review-branch-cache' import { stripGitLabDraftTitlePrefix } from './merge-request-draft-title' describe('stripGitLabDraftTitlePrefix', () => { @@ -536,3 +541,64 @@ describe('gitlab client — MR operations', () => { }) }) }) + +describe('gitlab client — review lookups after a merge request write', () => { + const projectRef = { host: 'gitlab.example.internal', path: 'g/p' } + const identity = { repoPath: '/repo', executionHostId: 'local' as const, branch: 'feature' } + const open: HostedReviewInfo = { + provider: 'gitlab', + number: 6, + title: 'MR', + state: 'open', + url: 'https://gitlab.example.internal/g/p/-/merge_requests/6', + status: 'neutral', + updatedAt: '', + mergeable: 'UNKNOWN' + } + const writes = { + merge: () => mergeMR('/repo', 6, 'squash', undefined, null, projectRef), + close: () => closeMR('/repo', 6, undefined, null, projectRef), + reopen: () => reopenMR('/repo', 6, undefined, null, projectRef), + title: () => updateMR('/repo', 6, { title: 'Renamed' }, undefined, null, projectRef) + } + + beforeEach(() => { + resetGitLabMrMocks({ + glabExecFileAsyncMock, + glabApiWithHeadersMock, + getGlabKnownHostsMock, + getProjectRefMock, + resolveIssueSourceMock, + acquireMock, + releaseMock, + gitExecFileAsyncMock + }) + __resetHostedReviewBranchCacheForTests() + glabExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + }) + + // Issue #14377: "I press Squash and merge" in Orca, and the card stayed Open while a poll was in flight. + it.each(Object.entries(writes))( + '%s: the follow-up read starts after the write instead of joining an older poll', + async (_name, write) => { + const prePoll = Promise.withResolvers() + const poll = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + () => prePoll.promise + ) + await expect(write()).resolves.toEqual({ ok: true }) + const changed = { ...open, state: 'merged' as const } + const afterWrite = vi.fn(async () => changed) + const followUp = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + afterWrite + ) + prePoll.resolve(open) + await poll + await expect(followUp).resolves.toEqual(changed) + expect(afterWrite).toHaveBeenCalledTimes(1) + } + ) +}) diff --git a/src/main/gitlab/merge-request-state-mutations.ts b/src/main/gitlab/merge-request-state-mutations.ts index bfb6391cd1e..a6beec3e436 100644 --- a/src/main/gitlab/merge-request-state-mutations.ts +++ b/src/main/gitlab/merge-request-state-mutations.ts @@ -10,6 +10,7 @@ import { } from './gl-utils' import { withProjectRef } from './merge-request-project-resolution' import { codeHostFailure } from '../../shared/code-host-failure-copy' +import { invalidateReviewLookupsAfterPRMutation } from '../github/pr-mutation-review-invalidation' // Why: glab's MRCheckErrors refuses a no-op close/reopen with these fixed texts; every other // failure, including "has already been merged", must surface. @@ -45,6 +46,8 @@ export async function closeMR( return { ok: false, error: msg } } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), @@ -81,6 +84,8 @@ export async function reopenMR( return { ok: false, error: msg } } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), @@ -119,6 +124,8 @@ export async function mergeMR( return { ok: false, error: err instanceof Error ? err.message : String(err) } } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), diff --git a/src/main/gitlab/merge-request-update.ts b/src/main/gitlab/merge-request-update.ts index acab47e1424..dbfd63486a6 100644 --- a/src/main/gitlab/merge-request-update.ts +++ b/src/main/gitlab/merge-request-update.ts @@ -15,6 +15,7 @@ import { stripGitLabDraftTitlePrefix } from './merge-request-draft-title' import { withProjectRef } from './merge-request-project-resolution' import { tryMarkMRReady } from './merge-request-ready' import { codeHostFailure, classifiedFailure } from '../../shared/code-host-failure-copy' +import { invalidateReviewLookupsAfterPRMutation } from '../github/pr-mutation-review-invalidation' export async function updateMR( repoPath: string, @@ -133,6 +134,8 @@ export async function updateMR( return classifiedFailure(classifyGlabError(msg)) } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), diff --git a/src/main/ipc/hosted-review.test.ts b/src/main/ipc/hosted-review.test.ts index 3998a1beea2..1daa0127c9a 100644 --- a/src/main/ipc/hosted-review.test.ts +++ b/src/main/ipc/hosted-review.test.ts @@ -51,7 +51,12 @@ vi.mock('../source-control/stacked-hosted-review-creation', () => ({ })) vi.mock('../source-control/hosted-review', () => ({ - getHostedReviewForBranch: getHostedReviewForBranchMock + getHostedReviewForBranch: getHostedReviewForBranchMock, + // Handlers read through this; keep asserting on the one mock. + readHostedReviewForBranch: vi.fn(async (input: unknown) => ({ + review: await getHostedReviewForBranchMock(input), + readOutcome: 'cached' + })) })) vi.mock('./registered-worktree-roots-cache', () => ({ @@ -63,11 +68,31 @@ vi.mock('../repo-worktrees', () => ({ })) import { registerHostedReviewHandlers } from './hosted-review' +import { readHostedReviewForBranch } from '../source-control/hosted-review' +import type { HostedReviewInfo } from '../../shared/hosted-review' import { WslDistroStoppedError } from '../wsl/wsl-unc-access-gate' import { WorktreeCatalogUnavailableError } from '../../shared/worktree/worktree-catalog-availability' type HandlerMap = Record unknown> +const providerReview: HostedReviewInfo = { + provider: 'gitlab', + number: 7, + title: 'MR', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + state: 'open', + status: 'success', + mergeable: 'MERGEABLE', + updatedAt: '2026-10-30' +} +// Only a caller that asks gets the outcome envelope; a definitive null keeps its outcome too. +const READ_OUTCOME_REPLIES = [ + { reportReadOutcome: true, review: providerReview }, + { reportReadOutcome: true, review: null }, + { reportReadOutcome: false, review: providerReview }, + { reportReadOutcome: undefined, review: null } +] + describe('registerHostedReviewHandlers', () => { const handlers: HandlerMap = {} const repoPath = '/remote/workspace/repo' @@ -431,7 +456,7 @@ describe('registerHostedReviewHandlers', () => { expect(getHostedReviewCreationEligibilityMock).toHaveBeenCalledTimes(reads) }) - it('carries a selected-worktree claim and explicit refresh through to the branch lookup', async () => { + it('carries a selected-worktree claim and explicit refresh through, and replies with the outcome only when asked', async () => { getHostedReviewForBranchMock.mockResolvedValueOnce(null) registerHostedReviewHandlers(store as never, stats as never) @@ -440,13 +465,34 @@ describe('registerHostedReviewHandlers', () => { repoId: repo.id, branch: 'feature/selected', active: true, - force: true + force: true, + userRefresh: true }) // Selected-worktree lookups use the faster active tier, unlike O(N) card polling (#11532). expect(getHostedReviewForBranchMock).toHaveBeenCalledWith( - expect.objectContaining({ branch: 'feature/selected', active: true, force: true }) + expect.objectContaining({ + branch: 'feature/selected', + active: true, + force: true, + userRefresh: true + }) ) + + for (const { reportReadOutcome, review } of READ_OUTCOME_REPLIES) { + vi.mocked(readHostedReviewForBranch).mockResolvedValueOnce({ + review, + readOutcome: 'provider' + }) + const reply = await handlers['hostedReview:forBranch'](null, { + repoPath, + repoId: repo.id, + branch: 'feature/selected', + userRefresh: true, + ...(reportReadOutcome === undefined ? {} : { reportReadOutcome }) + }) + expect(reply).toEqual(reportReadOutcome ? { review, readOutcome: 'provider' } : review) + } }) it('uses interactive git admission for an explicit card refresh', async () => { diff --git a/src/main/ipc/hosted-review.ts b/src/main/ipc/hosted-review.ts index 4ebd6c41fa7..91835949086 100644 --- a/src/main/ipc/hosted-review.ts +++ b/src/main/ipc/hosted-review.ts @@ -14,7 +14,8 @@ import { getHostedReviewCreationEligibility } from '../source-control/hosted-review-creation' import { createStackedHostedReview } from '../source-control/stacked-hosted-review-creation' -import { getHostedReviewForBranch } from '../source-control/hosted-review' +import { hostedReviewForBranchReply } from '../../shared/hosted-review' +import { readHostedReviewForBranch } from '../source-control/hosted-review' import { resolveRegisteredWorktreePath } from './registered-worktree-roots-cache' import { listRepoWorktreeGraph } from '../repo-worktrees' import { @@ -115,10 +116,10 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector // Sidebar cards and the checks panel poll this for every provider; gh/glab in WSL boot it (E9). // Only an explicit Refresh may start a stopped distro; admissionTier is priority only, and // the visible scheduler sends 'interactive' for the selected card on a timer. - const review = await guardWslUncPathAccess( + const read = await guardWslUncPathAccess( repo.path, () => - getHostedReviewForBranch({ + readHostedReviewForBranch({ repoPath: repo.path, executionHostId: getStoredRepoExecutionHostId(repo), branch: args.branch, @@ -131,10 +132,12 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector currentHeadOid: args.currentHeadOid ?? null, ...(args.active === true ? { active: true } : {}), ...(args.force === true ? { force: true } : {}), + ...(args.userRefresh === true ? { userRefresh: true } : {}), localGitExecOptions: localGitOptions }), { wake: args.wakeWslDistro === true, wslDistro: localGitOptions.wslDistro } ) + const review = read.review if (review?.provider === 'github' && !stats.hasCountedPR(review.url)) { stats.record({ type: 'pr_created', @@ -143,7 +146,7 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector meta: { prNumber: review.number, prUrl: review.url } }) } - return review + return hostedReviewForBranchReply(read, args.reportReadOutcome) }) ipcMain.handle( diff --git a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts index 9c3c773ae5b..39500eb8bc5 100644 --- a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts +++ b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts @@ -419,7 +419,12 @@ vi.mock('../../source-control/stacked-hosted-review-creation', () => ({ })) vi.mock('../../source-control/hosted-review', () => ({ - getHostedReviewForBranch: getHostedReviewForBranchMock + getHostedReviewForBranch: getHostedReviewForBranchMock, + // Handlers read through this; keep asserting on the one mock. + readHostedReviewForBranch: vi.fn(async (input: unknown) => ({ + review: await getHostedReviewForBranchMock(input), + readOutcome: 'cached' + })) })) vi.mock('../../github/client', async (importOriginal) => { diff --git a/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts index 4ff812e3ba7..d243b99c082 100644 --- a/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts @@ -1,5 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService, gitRunner, setPlatform } from '../orca-runtime-test-mocks.spec' +import { readHostedReviewForBranch } from '../../source-control/hosted-review' +import type { HostedReviewInfo } from '../../../shared/hosted-review' import { TEST_REPO_ID, TEST_REPO_PATH, @@ -113,4 +115,39 @@ describe('OrcaRuntimeService', () => { asyncGitSpy.mockRestore() } }) + + const mr: HostedReviewInfo = { + provider: 'gitlab', + number: 7, + title: 'MR', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + state: 'open', + status: 'success', + mergeable: 'MERGEABLE', + updatedAt: '2026-10-30' + } + it.each([ + { reportReadOutcome: true, review: mr, label: 'a review' }, + { reportReadOutcome: true, review: null, label: 'a definitive null' }, + { reportReadOutcome: false, review: mr, label: 'a review' }, + { reportReadOutcome: undefined, review: null, label: 'a definitive null' } + ])( + 'answers $label with the read outcome only when asked (reportReadOutcome=$reportReadOutcome)', + async ({ reportReadOutcome, review }) => { + vi.mocked(readHostedReviewForBranch).mockResolvedValueOnce({ + review, + readOutcome: 'provider' + }) + const runtime = new OrcaRuntimeService(store) + + const reply = await runtime.getHostedReviewForBranch({ + repoSelector: `id:${TEST_REPO_ID}`, + branch: 'feature', + userRefresh: true, + ...(reportReadOutcome === undefined ? {} : { reportReadOutcome }) + }) + + expect(reply).toEqual(reportReadOutcome ? { review, readOutcome: 'provider' } : review) + } + ) }) diff --git a/src/main/runtime/rpc/methods/hosted-review.test.ts b/src/main/runtime/rpc/methods/hosted-review.test.ts index 33c76089707..4b0e7edb0d0 100644 --- a/src/main/runtime/rpc/methods/hosted-review.test.ts +++ b/src/main/runtime/rpc/methods/hosted-review.test.ts @@ -1,3 +1,6 @@ +import { z } from 'zod' +import { requiredString } from '../../../../shared/rpc-contract/rpc-param-primitives' +import { OptionalGitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' import '../unused-default-rpc-methods.test-fixture' import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from '../dispatcher' @@ -5,11 +8,49 @@ import type { RpcRequest } from '../core' import type { OrcaRuntimeService } from '../../orca-runtime' import { HOSTED_REVIEW_METHODS } from './hosted-review' +// Shipped pre-force host schema at 9905765e3b8; unknown intent must remain ignorable. +const preForceHostParams = z.object({ + repo: requiredString('Missing repo selector'), + branch: requiredString('Missing branch'), + admissionTier: OptionalGitAdmissionTier, + currentHeadOid: z.string().nullable().optional(), + // Only the caller's selected worktree; the host caps how many earn the fast tier. + active: z.boolean().optional(), + linkedGitHubPR: z.number().int().positive().nullable().optional(), + fallbackGitHubPR: z.number().int().positive().nullable().optional(), + linkedGitLabMR: z.number().int().positive().nullable().optional(), + linkedBitbucketPR: z.number().int().positive().nullable().optional(), + linkedAzureDevOpsPR: z.number().int().positive().nullable().optional(), + linkedGiteaPR: z.number().int().positive().nullable().optional() +}) + function makeRequest(method: string, params?: unknown): RpcRequest { return { id: 'req-1', authToken: 'tok', method, params } } describe('hosted review RPC methods', () => { + it('keeps the same operation callable on hosts before intent and before force forwarding', () => { + const request = { + repo: '/repo', + branch: 'feature', + force: true, + userRefresh: true, + linkedGitLabMR: 7 + } + expect(preForceHostParams.parse(request)).toEqual({ + repo: '/repo', + branch: 'feature', + linkedGitLabMR: 7 + }) + const preIntentHostParams = preForceHostParams.extend({ force: z.boolean().optional() }) + expect(preIntentHostParams.parse(request)).toEqual({ + repo: '/repo', + branch: 'feature', + force: true, + linkedGitLabMR: 7 + }) + }) + it('fetches branch review status on the runtime server', async () => { const runtime = { getRuntimeId: () => 'test-runtime', @@ -50,7 +91,7 @@ describe('hosted review RPC methods', () => { }) }) - it('carries a selected-worktree claim and explicit refresh through to the runtime', async () => { + it('carries a selected-worktree claim, explicit refresh and outcome request through to the runtime', async () => { const runtime = { getRuntimeId: () => 'test-runtime', getHostedReviewForBranch: vi.fn().mockResolvedValue(null) @@ -62,13 +103,20 @@ describe('hosted review RPC methods', () => { repo: '/repo', branch: 'feature/selected', active: true, - force: true + force: true, + userRefresh: true, + reportReadOutcome: true }) ) // Mobile PR sidebar refresh must bypass card-list pacing to discover reviews opened elsewhere (#11532). expect(runtime.getHostedReviewForBranch).toHaveBeenCalledWith( - expect.objectContaining({ active: true, force: true }) + expect.objectContaining({ + active: true, + force: true, + userRefresh: true, + reportReadOutcome: true + }) ) }) diff --git a/src/main/runtime/rpc/methods/hosted-review.ts b/src/main/runtime/rpc/methods/hosted-review.ts index 1b177ea4ced..df1878fdbbf 100644 --- a/src/main/runtime/rpc/methods/hosted-review.ts +++ b/src/main/runtime/rpc/methods/hosted-review.ts @@ -22,6 +22,8 @@ export const HOSTED_REVIEW_METHODS = [ currentHeadOid: params.currentHeadOid ?? null, ...(params.active === true ? { active: true } : {}), ...(params.force === true ? { force: true } : {}), + ...(params.userRefresh === true ? { userRefresh: true } : {}), + ...(params.reportReadOutcome === true ? { reportReadOutcome: true } : {}), linkedGitHubPR: params.linkedGitHubPR ?? null, ...(fallbackGitHubPR !== null ? { fallbackGitHubPR } : {}), linkedGitLabMR: params.linkedGitLabMR ?? null, diff --git a/src/main/runtime/runtime-hosted-review-commands.ts b/src/main/runtime/runtime-hosted-review-commands.ts index 72746c4fc5b..7d2d0488f73 100644 --- a/src/main/runtime/runtime-hosted-review-commands.ts +++ b/src/main/runtime/runtime-hosted-review-commands.ts @@ -5,7 +5,7 @@ import type { CreateStackedHostedReviewResult, HostedReviewCreationEligibility, HostedReviewCreationEligibilityArgs, - HostedReviewInfo + HostedReviewForBranchReply } from '../../shared/hosted-review' import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' import type { @@ -21,7 +21,8 @@ import { } from '../github/client' import { admissionTierForRefreshReason } from '../github/pr-refresh-candidate-policy' import type { GitAdmissionTier } from '../git/command-runner/git-exec-options' -import { getHostedReviewForBranch } from '../source-control/hosted-review' +import { hostedReviewForBranchReply } from '../../shared/hosted-review' +import { readHostedReviewForBranch } from '../source-control/hosted-review' import { getStoredRepoExecutionHostId } from '../repo-execution-host' import { hostedReviewSshConnectionId } from '../source-control/hosted-review-execution-host' import { @@ -106,22 +107,25 @@ export class RuntimeHostedReviewCommands { currentHeadOid?: string | null active?: boolean force?: boolean + userRefresh?: boolean + reportReadOutcome?: boolean linkedGitHubPR?: number | null fallbackGitHubPR?: number | null linkedGitLabMR?: number | null linkedBitbucketPR?: number | null linkedAzureDevOpsPR?: number | null linkedGiteaPR?: number | null - }): Promise { + }): Promise { const repo = await this.deps.resolveRepo(args.repoSelector) const executionOptions = this.deps.getExecutionOptions(repo, args.admissionTier ?? 'background') - const review = await getHostedReviewForBranch({ + const read = await readHostedReviewForBranch({ repoPath: repo.path, executionHostId: getStoredRepoExecutionHostId(repo), branch: args.branch, currentHeadOid: args.currentHeadOid ?? null, ...(args.active === true ? { active: true } : {}), ...(args.force === true ? { force: true } : {}), + ...(args.userRefresh === true ? { userRefresh: true } : {}), linkedGitHubPR: args.linkedGitHubPR ?? null, fallbackGitHubPR: args.linkedGitHubPR == null ? (args.fallbackGitHubPR ?? null) : null, linkedGitLabMR: args.linkedGitLabMR ?? null, @@ -130,10 +134,11 @@ export class RuntimeHostedReviewCommands { linkedGiteaPR: args.linkedGiteaPR ?? null, ...executionOptions }) + const review = read.review if (review?.provider === 'github') { this.deps.recordCreated(repo.id, review.number, review.url) } - return review + return hostedReviewForBranchReply(read, args.reportReadOutcome) } async getHostedReviewCreationEligibility( diff --git a/src/main/source-control/hosted-review-branch-cache.ts b/src/main/source-control/hosted-review-branch-cache.ts index eceb5aaeea7..24c8466faf2 100644 --- a/src/main/source-control/hosted-review-branch-cache.ts +++ b/src/main/source-control/hosted-review-branch-cache.ts @@ -1,5 +1,6 @@ import type { ExecutionHostId } from '../../shared/execution-host' -import type { HostedReviewInfo } from '../../shared/hosted-review' +import type { HostedReviewForBranchOutcome, HostedReviewInfo } from '../../shared/hosted-review' +import { cachedHostedReviewOutcome } from '../../shared/hosted-review' import { __resetHostedReviewActiveClaimsForTests, isActiveBranch, @@ -19,6 +20,7 @@ import { getInflightLookup, releaseInflight, retireInflightWithPrefix, + retireInflightLookup, trackInflight, type InflightToken } from './hosted-review-inflight-lookups' @@ -35,6 +37,7 @@ import { dropFailuresWithPrefix, noteFailure } from './hosted-review-lookup-backoff' +import { observeProviderRead } from './hosted-review-provider-read' import { ACTIVE_REFRESH_INTERVAL_MS, HOSTED_REVIEW_LOOKUP_DEADLINE_MS, @@ -79,6 +82,7 @@ export type HostedReviewBranchCacheOptions = { /** Set by surfaces that only ever render the selected worktree. */ active?: boolean force?: boolean + userRefresh?: boolean } export function hostedReviewBranchCacheKey(identity: HostedReviewBranchCacheIdentity): string { @@ -180,16 +184,18 @@ function startLookup( key: string, scope: string, headOid: string | null, + revisionScope: string, lookup: () => Promise -): Promise { +): Promise { const startedAt = Date.now() const generation = scopeGeneration(scope) + const revision = scopeGeneration(revisionScope) const token: InflightToken = {} let timedOut = false let completed = false - let release: (review: HostedReviewInfo | null) => void = () => {} + let release: (read: HostedReviewForBranchOutcome) => void = () => {} let fail: (error: unknown) => void = () => {} - const promise = new Promise((resolve, reject) => { + const promise = new Promise((resolve, reject) => { release = resolve fail = reject }) @@ -209,11 +215,6 @@ function startLookup( } // Detached work remains uninterruptible; count it process-wide until completion. noteDetachedLookup() - const stale = entries.get(key) - if (stale) { - release(stale.review) - return - } fail( new Error( `Hosted review lookup timed out after ${Math.round( @@ -234,10 +235,11 @@ function startLookup( void (async () => { try { - const review = await lookup() + const { value: review, answeredFromProviderCache } = await observeProviderRead(lookup) // Generation invalidates pre-creation answers; without key ownership, stragglers must prove their result still outranks the cache. const stored = generation === scopeGeneration(scope) && + revision === scopeGeneration(revisionScope) && (getInflightLookup(key)?.token === token || canAdoptDetachedAnswer(key, startedAt)) if (stored) { storeEntry(key, { review, fetchedAt: Date.now(), headOid, startedAt }) @@ -246,7 +248,7 @@ function startLookup( if (stored && !timedOut) { clearFailures(key) } - release(review) + release({ review, readOutcome: stored && !answeredFromProviderCache ? 'provider' : 'cached' }) } catch (error) { // Deadline already counted failure; never count late rejection twice. if (timedOut) { @@ -256,12 +258,6 @@ function startLookup( if (getInflightLookup(key)?.token === token) { noteFailure(key) } - // Keep last-good data on failure to avoid blinking cards; invalidation still removes obsolete answers. - const stale = entries.get(key) - if (stale) { - release(stale.review) - return - } fail(error) } finally { completed = true @@ -279,12 +275,18 @@ function startLookup( return promise } -/** Share fresh answers/in-flight lookups across clients and back off failed branches. */ export async function withHostedReviewBranchCache( + ...args: Parameters +): Promise { + return (await readHostedReviewBranchCache(...args)).review +} + +/** Share fresh answers/in-flight lookups across clients and back off failed branches. */ +export async function readHostedReviewBranchCache( identity: HostedReviewBranchCacheIdentity, options: HostedReviewBranchCacheOptions, lookup: () => Promise -): Promise { +): Promise { const key = hostedReviewBranchCacheKey(identity) const headOid = options.headOid // Sweep wall-clock deadlines before joining so suspended timers cannot pin a branch after sleep. @@ -296,28 +298,53 @@ export async function withHostedReviewBranchCache( const active = isActiveBranch(key) const cached = entries.get(key) - if (!options.force && cached && isFresh(cached, headOid, active)) { - return cached.review + if (!options.userRefresh && !options.force && cached && isFresh(cached, headOid, active)) { + return cachedHostedReviewOutcome(cached.review) } - const pending = getInflightLookup(key) - if (pending) { - return pending.promise - } - - const unavailable = lookupUnavailableReason(key) + // Admission is keyed independently of revision; a refused click cannot retire an admitted owner. + const unavailable = options.userRefresh ? lookupCapacityRefusal(key) : null if (unavailable !== null) { - // Serve stale answers on backoff, but without cached evidence report error rather than no review. - if (cached) { - return cached.review - } throw new Error(unavailable) } + const revisionScope = `branch-refresh${KEY_SEPARATOR}${key}` + if (options.userRefresh) { + bumpScopeGeneration(revisionScope) + retireInflightLookup(key) + } - return startLookup( - key, - hostedReviewRepoScope(identity.repoPath, identity.executionHostId), - headOid, - lookup + const settleForCaller = async (promise: Promise) => { + try { + return await promise + } catch (error) { + const stale = entries.get(key) + if (!options.userRefresh && stale) { + return cachedHostedReviewOutcome(stale.review) + } + throw error + } + } + const pending = getInflightLookup(key) + if (pending) { + // The owner began before this caller asked, so its answer can't prove a read after this caller's failure. + return settleForCaller(pending.promise.then(({ review }) => cachedHostedReviewOutcome(review))) + } + + const refusal = options.userRefresh ? null : lookupUnavailableReason(key) + if (refusal !== null) { + if (cached) { + return cachedHostedReviewOutcome(cached.review) + } + throw new Error(refusal) + } + + return settleForCaller( + startLookup( + key, + hostedReviewRepoScope(identity.repoPath, identity.executionHostId), + headOid, + revisionScope, + lookup + ) ) } diff --git a/src/main/source-control/hosted-review-gitea.integration.test.ts b/src/main/source-control/hosted-review-gitea.integration.test.ts index b83e2fd5f34..63ee743aba3 100644 --- a/src/main/source-control/hosted-review-gitea.integration.test.ts +++ b/src/main/source-control/hosted-review-gitea.integration.test.ts @@ -36,6 +36,7 @@ describe('Gitea hosted review integration', () => { it('resolves a Gitea PR through real git remote parsing and HTTP API calls', async () => { const seen: SeenRequest[] = [] + let merged = false const server = createServer((req: IncomingMessage, res: ServerResponse) => { const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`) seen.push({ @@ -49,7 +50,8 @@ describe('Gitea hosted review integration', () => { { number: 9, title: 'Local Gitea branch', - state: 'open', + state: merged ? 'closed' : 'open', + merged, html_url: 'http://127.0.0.1/team/repo/pulls/9', updated_at: '2026-05-15T00:00:00Z', mergeable: true, @@ -107,6 +109,17 @@ describe('Gitea hosted review integration', () => { ]) expect(seen.every((request) => request.authorization === 'token local-token')).toBe(true) expect(new URLSearchParams(seen[0].search).get('state')).toBe('all') + + // Merged on the web: a click inside the 30s repository-scan window still reads the new state. + merged = true + await expect( + getHostedReviewForBranch({ + executionHostId: 'local', + repoPath, + branch: 'refs/heads/feature/gitea', + userRefresh: true + }) + ).resolves.toMatchObject({ provider: 'gitea', number: 9, state: 'merged' }) } finally { await rm(repoPath, { recursive: true, force: true }) await new Promise((resolve, reject) => { diff --git a/src/main/source-control/hosted-review-inflight-invalidation.test.ts b/src/main/source-control/hosted-review-inflight-invalidation.test.ts index 5d68ccb0c89..088e9a02a85 100644 --- a/src/main/source-control/hosted-review-inflight-invalidation.test.ts +++ b/src/main/source-control/hosted-review-inflight-invalidation.test.ts @@ -266,3 +266,126 @@ describe('hosted review in-flight invalidation', () => { expect(freshLookup).toHaveBeenCalledTimes(1) }) }) + +const START = 1_000_000 +const openReview = review +const mergedReview: HostedReviewInfo = { ...review, state: 'merged' } +function stuckLookup() { + const response = Promise.withResolvers() + return { + lookup: vi.fn(() => response.promise), + resolve: response.resolve, + reject: response.reject + } +} +describe('hosted review manual refresh invalidation', () => { + // The branch cache never branches on the forge, so one stands for all of them. + it('starts a post-click read and fences the pre-click answer at the same clock time', async () => { + const old = stuckLookup() + const before = withHostedReviewBranchCache(identity, { headOid: null, force: true }, old.lookup) + const lookup = vi.fn(async () => mergedReview) + const options = { headOid: null, force: true, userRefresh: true } + const click = withHostedReviewBranchCache(identity, options, lookup) + old.resolve(openReview) + await expect(before).resolves.toMatchObject({ state: 'open' }) + await expect(click).resolves.toEqual(mergedReview) + expect(lookup).toHaveBeenCalledOnce() + await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).resolves.toEqual( + mergedReview + ) + }) + + it('fences a pre-click answer that completes after the manual answer', async () => { + const old = stuckLookup() + const before = withHostedReviewBranchCache(identity, { headOid: null }, old.lookup) + await expect( + withHostedReviewBranchCache( + identity, + { headOid: null, force: true, userRefresh: true }, + async () => mergedReview + ) + ).resolves.toEqual(mergedReview) + old.resolve(openReview) + await before + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + ).resolves.toEqual(mergedReview) + }) + + it('reads during failure backoff only for an explicit click, then recovers', async () => { + await withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + const failed = vi.fn(async () => { + throw new Error('offline') + }) + await withHostedReviewBranchCache(identity, { headOid: null, force: true }, failed) + const lookup = vi.fn(async () => mergedReview) + await expect( + withHostedReviewBranchCache(identity, { headOid: null, force: true }, lookup) + ).resolves.toEqual(openReview) + expect(lookup).not.toHaveBeenCalled() + const options = { headOid: null, force: true, userRefresh: true } + await expect(withHostedReviewBranchCache(identity, options, failed)).rejects.toThrow('offline') + await expect(withHostedReviewBranchCache(identity, options, lookup)).resolves.toEqual( + mergedReview + ) + expect(lookup).toHaveBeenCalledOnce() + }) + + it.each(['failure', 'deadline'] as const)( + 'settles a shared manual flight per caller on %s', + async (outcome) => { + await withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + const held = stuckLookup() + const options = { headOid: null, force: true, userRefresh: true } + const click = withHostedReviewBranchCache(identity, options, held.lookup) + const rejection = expect(click).rejects.toThrow( + outcome === 'failure' ? 'offline' : 'timed out' + ) + const ordinary = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + held.lookup + ) + if (outcome === 'failure') { + held.reject(new Error('offline')) + } else { + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + } + await rejection + await expect(ordinary).resolves.toEqual(openReview) + expect(held.lookup).toHaveBeenCalledOnce() + // Failed refreshes cannot renew the old answer's TTL or reset failure escalation. + vi.setSystemTime(START + HOSTED_REVIEW_LOOKUP_DEADLINE_MS + 60_001) + const next = vi.fn(async () => mergedReview) + await withHostedReviewBranchCache(identity, { headOid: null }, next) + expect(next).toHaveBeenCalledOnce() + if (outcome === 'deadline') { + held.resolve(openReview) + } + } + ) + + it('refuses a third live click without retiring the admitted successor', async () => { + const first = stuckLookup() + const second = stuckLookup() + const options = { headOid: null, force: true, userRefresh: true } + const before = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + first.lookup + ) + const admitted = withHostedReviewBranchCache(identity, options, second.lookup) + const third = vi.fn(async () => openReview) + const refused = withHostedReviewBranchCache(identity, options, third) + const rejection = expect(refused).rejects.toThrow('still running') + second.resolve(mergedReview) + first.resolve(openReview) + await rejection + await expect(admitted).resolves.toEqual(mergedReview) + await before + expect(third).not.toHaveBeenCalled() + await expect(withHostedReviewBranchCache(identity, { headOid: null }, third)).resolves.toEqual( + mergedReview + ) + }) +}) diff --git a/src/main/source-control/hosted-review-inflight-lookups.test.ts b/src/main/source-control/hosted-review-inflight-lookups.test.ts index 149de43c097..cf987d3cfdb 100644 --- a/src/main/source-control/hosted-review-inflight-lookups.test.ts +++ b/src/main/source-control/hosted-review-inflight-lookups.test.ts @@ -19,14 +19,14 @@ it.each(['completion', 'deadline'])( trackInflight('repo\0branch', { token: oldToken, startedAt: 0, - promise: Promise.resolve(null), + promise: Promise.resolve({ review: null, readOutcome: 'provider' as const }), expire: oldExpire }) retireInflightWithPrefix('repo\0') const replacement = { token: {}, startedAt: HOSTED_REVIEW_LOOKUP_DEADLINE_MS, - promise: Promise.resolve(null), + promise: Promise.resolve({ review: null, readOutcome: 'provider' as const }), expire: vi.fn() } trackInflight('repo\0branch', replacement) diff --git a/src/main/source-control/hosted-review-inflight-lookups.ts b/src/main/source-control/hosted-review-inflight-lookups.ts index 189dec50798..cfc15a3a9f7 100644 --- a/src/main/source-control/hosted-review-inflight-lookups.ts +++ b/src/main/source-control/hosted-review-inflight-lookups.ts @@ -1,4 +1,4 @@ -import type { HostedReviewInfo } from '../../shared/hosted-review' +import type { HostedReviewForBranchOutcome } from '../../shared/hosted-review' import { HOSTED_REVIEW_LOOKUP_DEADLINE_MS, MAX_INFLIGHT_LOOKUPS @@ -13,7 +13,7 @@ export type InflightRecord = { /** Identity, so a detached lookup can only ever clear its own entry. */ token: InflightToken startedAt: number - promise: Promise + promise: Promise /** Releases the callers and unpins the branch; idempotent. */ expire: () => void } @@ -36,12 +36,19 @@ export function releaseInflight(key: string, token: InflightToken): boolean { return true } +export function retireInflightLookup(key: string): void { + const record = inflight.get(key) + if (record) { + retired.set(record.token, record) + inflight.delete(key) + } +} + /** Retire matching owners without failing their callers. */ export function retireInflightWithPrefix(prefix: string): void { - for (const [key, record] of inflight) { + for (const key of inflight.keys()) { if (key.startsWith(prefix)) { - retired.set(record.token, record) - inflight.delete(key) + retireInflightLookup(key) } } } diff --git a/src/main/source-control/hosted-review-provider-read.ts b/src/main/source-control/hosted-review-provider-read.ts new file mode 100644 index 00000000000..6cce27d8d5d --- /dev/null +++ b/src/main/source-control/hosted-review-provider-read.ts @@ -0,0 +1,22 @@ +import { AsyncLocalStorage } from 'node:async_hooks' + +type ProviderRead = { answeredFromProviderCache: boolean } + +const currentRead = new AsyncLocalStorage() + +/** Runs one hosted-review provider read and reports whether a provider-internal cache answered it, so that answer is never taken as a fresh read. */ +export async function observeProviderRead( + read: () => Promise +): Promise<{ value: T; answeredFromProviderCache: boolean }> { + const observation: ProviderRead = { answeredFromProviderCache: false } + const value = await currentRead.run(observation, read) + return { value, answeredFromProviderCache: observation.answeredFromProviderCache } +} + +/** Provider caches call this when they answer with work that began before the current read. */ +export function noteProviderCacheAnswer(): void { + const observation = currentRead.getStore() + if (observation) { + observation.answeredFromProviderCache = true + } +} diff --git a/src/main/source-control/hosted-review.test.ts b/src/main/source-control/hosted-review.test.ts index dc32b85a2dc..3ee678d94bb 100644 --- a/src/main/source-control/hosted-review.test.ts +++ b/src/main/source-control/hosted-review.test.ts @@ -81,6 +81,41 @@ describe('getHostedReviewForBranch', () => { __resetHostedReviewBranchCacheForTests() }) + it('refreshes a self-managed GitLab MR through the provider while old metadata is pending', async () => { + getProjectSlugMock.mockResolvedValue({ host: 'gitlab.example.test', path: 'g/p' }) + const old = { + number: 7, + title: 'MR', + state: 'opened', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + pipelineStatus: 'success', + updatedAt: '2026-05-10T00:00:00.000Z', + mergeable: 'MERGEABLE' + } + let finishOld: (value: typeof old) => void = () => {} + getMergeRequestForBranchMock + .mockReturnValueOnce( + new Promise((resolve) => { + finishOld = resolve + }) + ) + .mockResolvedValueOnce({ ...old, state: 'merged' }) + const input = { + repoPath: '/repo', + executionHostId: 'ssh:ssh-1', + branch: 'feature', + force: true + } as const + const before = getHostedReviewForBranch(input) + await vi.waitFor(() => expect(getMergeRequestForBranchMock).toHaveBeenCalledTimes(1)) + const click = getHostedReviewForBranch({ ...input, userRefresh: true }) + finishOld(old) + await before + await expect(click).resolves.toMatchObject({ provider: 'gitlab', state: 'merged', number: 7 }) + expect(getMergeRequestForBranchMock).toHaveBeenCalledTimes(2) + expect(getMergeRequestForBranchMock).toHaveBeenLastCalledWith('/repo', 'feature', null, 'ssh-1') + }) + it('maps GitLab merge requests into the hosted review surface', async () => { getProjectSlugMock.mockResolvedValue({ host: 'gitlab.com', path: 'g/p' }) getMergeRequestForBranchMock.mockResolvedValue({ diff --git a/src/main/source-control/hosted-review.ts b/src/main/source-control/hosted-review.ts index 02743851851..d5b0bb03d92 100644 --- a/src/main/source-control/hosted-review.ts +++ b/src/main/source-control/hosted-review.ts @@ -1,17 +1,22 @@ import { githubRepoContext, withGitHubRepoExecution } from '../github/github-repository-identity' import type { ExecutionHostId } from '../../shared/execution-host' -import type { HostedReviewInfo } from '../../shared/hosted-review' +import { + cachedHostedReviewOutcome, + type HostedReviewForBranchOutcome, + type HostedReviewInfo +} from '../../shared/hosted-review' import { assertRemoteUrlReadable } from '../git/remote-url-probe' +import { forgetGiteaPullRequestReads } from '../gitea/pull-request-read-forgetting' import { getForgeProviderForRepository, type ForgeProviderId } from './forge-provider' import { hostedReviewSshConnectionId } from './hosted-review-execution-host' -import { withHostedReviewBranchCache } from './hosted-review-branch-cache' +import { readHostedReviewBranchCache } from './hosted-review-branch-cache' import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions } from './hosted-review-git-options' function reviewLinkForProvider( - input: Parameters[0], + input: Parameters[0], provider: ForgeProviderId ): { linkedReviewNumber?: number | null; fallbackReviewNumber?: number | null } { switch (provider) { @@ -32,6 +37,12 @@ function reviewLinkForProvider( } export async function getHostedReviewForBranch( + input: Parameters[0] +): Promise { + return (await readHostedReviewForBranch(input)).review +} + +export async function readHostedReviewForBranch( input: { repoPath: string executionHostId: ExecutionHostId @@ -46,8 +57,9 @@ export async function getHostedReviewForBranch( /** Selected-worktree surfaces earn per-minute pacing (#11532). */ active?: boolean force?: boolean + userRefresh?: boolean } & HostedReviewExecutionOptions -): Promise { +): Promise { const branchName = input.branch.replace(/^refs\/heads\//, '') // Detached HEAD skips branch lookup but still permits exact provider ids. if ( @@ -59,7 +71,7 @@ export async function getHostedReviewForBranch( input.linkedAzureDevOpsPR == null && input.linkedGiteaPR == null ) { - return null + return cachedHostedReviewOutcome(null) } const connectionId = hostedReviewSshConnectionId(input.executionHostId) @@ -83,15 +95,16 @@ export async function getHostedReviewForBranch( } ) - function lookup(resolvedInput: Parameters[0]) { + function lookup(resolvedInput: Parameters[0]) { const headOid = input.currentHeadOid?.trim() || null // Cache review API results by the resolved account and execution identity (#11532). - return withHostedReviewBranchCache( + return readHostedReviewBranchCache( { ...resolvedInput, branch: branchName }, { headOid, ...(input.active === true ? { active: true } : {}), - ...(input.force === true ? { force: true } : {}) + ...(input.force === true ? { force: true } : {}), + ...(input.userRefresh === true ? { userRefresh: true } : {}) }, async () => { const provider = await getForgeProviderForRepository({ @@ -110,6 +123,13 @@ export async function getHostedReviewForBranch( return null } const providerOptions = provider.id === 'github' ? resolvedInput : input + if (input.userRefresh === true && provider.id === 'gitea') { + await forgetGiteaPullRequestReads({ + repoPath: input.repoPath, + executionHostId: input.executionHostId, + localGitExecOptions: getHostedReviewLocalGitOptions(input) + }) + } return provider.getReviewForBranch({ repoPath: input.repoPath, executionHostId: input.executionHostId, diff --git a/src/preload/api/hosted-review-api.ts b/src/preload/api/hosted-review-api.ts index 65d6667994b..9df1fdaa232 100644 --- a/src/preload/api/hosted-review-api.ts +++ b/src/preload/api/hosted-review-api.ts @@ -11,11 +11,17 @@ import type { HostedReviewCreationEligibility, HostedReviewCreationEligibilityArgs, HostedReviewForBranchArgs, + HostedReviewForBranchReply, HostedReviewInfo } from '../../shared/hosted-review' export type HostedReviewApi = { - forBranch: (args: HostedReviewForBranchArgs) => Promise + forBranch: { + ( + args: HostedReviewForBranchArgs & { reportReadOutcome?: false } + ): Promise + (args: HostedReviewForBranchArgs): Promise + } getCreationEligibility: ( args: HostedReviewCreationEligibilityArgs ) => Promise diff --git a/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts b/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts index c3d4f2b35a8..674d86ed2f7 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts @@ -7,13 +7,13 @@ import type { CrashReportBreadcrumbData, CrashReportDetailValue } from '../../../../shared/crash-reporting' +import type { HostedReviewProvider } from '../../../../shared/hosted-review' type ChecksPanelPRRefreshBreadcrumbEvent = 'start' | 'done' | 'stale_cleared' -type ChecksPanelReviewProvider = 'github' | 'gitlab' type ChecksPanelPRRefreshBreadcrumbArgs = { event: ChecksPanelPRRefreshBreadcrumbEvent - provider: ChecksPanelReviewProvider + provider: HostedReviewProvider repoId?: string | null worktreeId?: string | null branch?: string | null diff --git a/src/renderer/src/components/right-sidebar/checks-panel/active-content-props.ts b/src/renderer/src/components/right-sidebar/checks-panel/active-content-props.ts index b80bf500388..8fb86a0f465 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/active-content-props.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel/active-content-props.ts @@ -86,7 +86,7 @@ export type ChecksPanelActiveContentModel = Pick< | 'handleOpenStackPR' | 'handleUnlinkReview' > & - Pick & + Pick & Pick & Pick & Pick diff --git a/src/renderer/src/components/right-sidebar/checks-panel/active-content.tsx b/src/renderer/src/components/right-sidebar/checks-panel/active-content.tsx index d28efd0c88f..724b2f9585e 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/active-content.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/active-content.tsx @@ -73,6 +73,7 @@ export function ChecksPanelActiveContent({ isRefreshing, isResolvingConflictsWithAI, linkedGitLabMR, + manualRefreshError, pendingCommentResolutionRef, pr, prRefreshState, @@ -100,15 +101,19 @@ export function ChecksPanelActiveContent({ settings, Boolean(activeWorktreeId) ) + // A classified GitHub failure says more than a manual one, so it wins; one banner either way. + const refreshError = + (activeReview.provider === 'github' && prRefreshState?.status === 'error' + ? getChecksPanelRefreshErrorBannerLine(prRefreshState.errorType) + : null) ?? manualRefreshError return (
- {/* Show background GitHub failures above cached PR data so outages cannot look like a healthy panel. */} - {activeReview?.provider === 'github' && prRefreshState?.status === 'error' ? ( + {refreshError ? (
- {getChecksPanelRefreshErrorBannerLine(prRefreshState.errorType)} + {refreshError}
) : null}
@@ -222,7 +227,7 @@ export function ChecksPanelActiveContent({ {!(activeConflictReview && checks.length === 0 && !checksLoading) && ( & Pick & Pick & - Pick & + Pick & Pick diff --git a/src/renderer/src/components/right-sidebar/checks-panel/empty-content.tsx b/src/renderer/src/components/right-sidebar/checks-panel/empty-content.tsx index cacd0ea0aa1..89407d47b89 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/empty-content.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/empty-content.tsx @@ -7,6 +7,7 @@ import { shouldShowChecksPanelPublishBranchAction } from '../checks-panel-empty-state' import { openChecksPanelHostedReviewUrl } from '../checks-panel-hosted-review-click-routing' +import { isRateLimitRefresh } from '../checks-panel-review-state-model' import { isMacPlatform } from '../../terminal-pane/terminal-link-open-hints' import { getIntlLocale, translate } from '@/i18n/i18n' import { localizedHostedReviewCopy } from '@/i18n/hosted-review-localized-copy' @@ -64,6 +65,7 @@ export function ChecksPanelEmptyContent({ linkedGitLabMR, linkedPR, linkedReviewNumber, + manualRefreshError, panelContextKey, prAiGenerationEnabled, prBase, @@ -215,7 +217,17 @@ export function ChecksPanelEmptyContent({ hasUpstream: publishActionRemoteStatus?.hasUpstream, hasCurrentBranch: Boolean(branch) }) - const emptyStateCopy = { title: reviewState.title, description: reviewState.description } + // Classified GitHub states carry the next step (sign in, or wait for the limit), so they win. + const refreshFailure = + emptyRefreshInput?.status === 'error' || isRateLimitRefresh(emptyRefreshInput) + ? null + : manualRefreshError + const emptyStateCopy = refreshFailure + ? { + title: translate('auto.components.status.bar.tooltip.e740f92596', 'Refresh failed'), + description: refreshFailure + } + : { title: reviewState.title, description: reviewState.description } const reviewStateAutoRetryText = reviewState.autoRetryAt !== undefined && reviewState.autoRetryAt > now ? translate( @@ -228,7 +240,9 @@ export function ChecksPanelEmptyContent({ reviewState.retryDisabledUntil !== undefined && now < reviewState.retryDisabledUntil const reviewRecoveryLabelIsRefresh = reviewState.recovery.includes('refresh') const reviewShowRetryOrRefresh = - reviewState.recovery.includes('retry') || reviewRecoveryLabelIsRefresh + Boolean(refreshFailure) || + reviewState.recovery.includes('retry') || + reviewRecoveryLabelIsRefresh const reviewShowOpenReview = reviewState.recovery.includes('open_review') && Boolean(reviewState.openReviewUrl) const reviewShowSyncBranch = reviewState.workflowAction === 'sync_branch' @@ -247,10 +261,10 @@ export function ChecksPanelEmptyContent({ )}
{emptyStateCopy.title}
{emptyStateCopy.description}
- {reviewState.detail ? ( + {!refreshFailure && reviewState.detail ? (
{reviewState.detail}
) : null} - {reviewStateAutoRetryText ? ( + {!refreshFailure && reviewStateAutoRetryText ? (
{reviewStateAutoRetryText}
) : null} {!operationInProgress && createComposerOpen ? ( diff --git a/src/renderer/src/components/right-sidebar/checks-panel/hosted-review-manual-refresh.ts b/src/renderer/src/components/right-sidebar/checks-panel/hosted-review-manual-refresh.ts new file mode 100644 index 00000000000..b292d6ac397 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel/hosted-review-manual-refresh.ts @@ -0,0 +1,122 @@ +import { useCallback, useState } from 'react' +import type { HostedReviewProvider } from '../../../../../shared/hosted-review' +import { useAppStore } from '@/store' +import { latestLookupGeneration } from '@/store/lookup-generation-sequence' +import { refreshHostedReviewCard } from '@/store/slices/hosted-review-card-refresh' +import type { ChecksPanelManualRefreshInput } from './manual-refresh-dependencies' + +/** Reviews and links name the provider first; an unlinked branch falls back to the remote's provider, not GitHub. */ +export function checksPanelManualRefreshProvider( + model: ChecksPanelManualRefreshInput +): HostedReviewProvider { + return ( + model.activeReview?.provider ?? + model.hostedReview?.provider ?? + (model.isGitLabReviewContext + ? 'gitlab' + : model.linkedBitbucketPR != null + ? 'bitbucket' + : model.linkedAzureDevOpsPR != null + ? 'azure-devops' + : model.linkedGiteaPR != null + ? 'gitea' + : model.hostedReviewCreateProvider) + ) +} + +/** A failed click's message, kept until a click succeeds, the context changes or a provider read issued after the failure answers. */ +export function useChecksPanelManualRefreshFailure( + panelContextKey: string, + hostedReviewCacheKey: string +) { + const [failure, setFailure] = useState<{ + contextKey: string + message: string | null + failedAfterGeneration: number + }>({ contextKey: panelContextKey, message: null, failedAfterGeneration: 0 }) + if (failure.contextKey !== panelContextKey) { + setFailure({ contextKey: panelContextKey, message: null, failedAfterGeneration: 0 }) + } + // Last-good fallbacks and cache hits don't move this, so only a real provider read can clear the failure. + const providerReadGeneration = useAppStore((s) => + hostedReviewCacheKey + ? (s.hostedReviewCache[hostedReviewCacheKey]?.providerReadGeneration ?? 0) + : 0 + ) + const setManualFailure = useCallback( + (message: string | null) => + setFailure({ + contextKey: panelContextKey, + message, + failedAfterGeneration: latestLookupGeneration() + }), + [panelContextKey] + ) + return { + manualRefreshError: + failure.contextKey === panelContextKey && + providerReadGeneration <= failure.failedAfterGeneration + ? failure.message + : null, + setManualFailure + } +} + +/** The click's own review read: it never joins a read that began before the click. */ +export function refreshHostedReviewForClick( + model: ChecksPanelManualRefreshInput, + repo: NonNullable, + branch: string, + fallbackGitHubPR: number | null +) { + return refreshHostedReviewCard(model.fetchHostedReviewForBranch, { + repoPath: repo.path, + repoId: repo.id, + branch, + admissionTier: 'interactive', + userRefresh: true, + linkedGitHubPR: model.linkedPR, + fallbackGitHubPR, + linkedGitLabMR: model.linkedGitLabMR, + linkedBitbucketPR: model.linkedBitbucketPR, + linkedAzureDevOpsPR: model.linkedAzureDevOpsPR, + linkedGiteaPR: model.linkedGiteaPR + }) +} + +export async function refreshChecksPanelHostedReview( + model: ChecksPanelManualRefreshInput, + provider: HostedReviewProvider, + isCurrentRequest: () => boolean +): Promise<'review' | 'no-review' | 'superseded'> { + const { repo, branch, activeGitLabReview, fetchGitLabDetails, setChecks, setComments } = model + if (!repo || !branch) { + return 'superseded' + } + const refreshedReview = await refreshHostedReviewForClick( + model, + repo, + branch, + model.fallbackGitHubPRNumber + ) + if (!isCurrentRequest()) { + return 'superseded' + } + if (provider !== 'gitlab') { + return 'review' + } + const refreshedGitLabReview = + refreshedReview?.provider === 'gitlab' ? refreshedReview : activeGitLabReview + if (refreshedGitLabReview) { + await fetchGitLabDetails({ + mrNumberOverride: refreshedGitLabReview.number, + headShaOverride: refreshedGitLabReview.headSha, + commitAsCurrent: true, + isRequestCurrent: isCurrentRequest + }) + return 'review' + } + setChecks([]) + setComments([]) + return 'no-review' +} diff --git a/src/renderer/src/components/right-sidebar/checks-panel/manual-refresh-dependencies.ts b/src/renderer/src/components/right-sidebar/checks-panel/manual-refresh-dependencies.ts index e64b6465817..7cb525aedff 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/manual-refresh-dependencies.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel/manual-refresh-dependencies.ts @@ -2,6 +2,7 @@ import type { ChecksPanelControllerState } from './use-checks-panel-controller-s import type { ChecksPanelContextState } from './use-checks-panel-context-state' import type { ChecksPanelPollingState } from './use-checks-panel-polling' import type { ChecksPanelComposerState } from './use-checks-panel-composer-state' +import type { ChecksPanelReviewState } from './use-checks-panel-review-state' export type ChecksPanelManualRefreshInput = Pick< ChecksPanelControllerState, @@ -38,7 +39,10 @@ export type ChecksPanelManualRefreshInput = Pick< Pick< ChecksPanelContextState, | 'activeGitLabReview' + | 'activeReview' | 'fallbackGitHubPRNumber' + | 'hostedReview' + | 'hostedReviewCacheKey' | 'isFolder' | 'isGitLabReviewContext' | 'linkedAzureDevOpsPR' @@ -50,5 +54,6 @@ export type ChecksPanelManualRefreshInput = Pick< | 'prCacheKey' | 'prNumber' > & + Pick & Pick & Pick diff --git a/src/renderer/src/components/right-sidebar/checks-panel/panel-content-rendering.test.tsx b/src/renderer/src/components/right-sidebar/checks-panel/panel-content-rendering.test.tsx index ddf59d9d720..a84215092e3 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/panel-content-rendering.test.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/panel-content-rendering.test.tsx @@ -10,8 +10,14 @@ vi.mock('../SourceControlAgentActionDialog', () => ({ SourceControlAgentActionDi import { ChecksPanelActiveContent } from './active-content' import { ChecksPanelEmptyContent } from './empty-content' +import { getHostedReviewManualRefreshError } from '../github-refresh-error-copy' +import { localizedHostedReviewCopy } from '@/i18n/hosted-review-localized-copy' +import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures' -afterEach(cleanup) +afterEach(() => { + cleanup() + vi.useRealTimers() +}) describe('checks panel concrete content', () => { it('renders the no-workspace empty state with its guidance', () => { @@ -89,12 +95,126 @@ describe('checks panel concrete content', () => { suppressedGitHubPR: 42 } as ChecksPanelEmptyContentModel - render() + const { rerender } = render() expect(screen.getByText('No pull request found')).toBeTruthy() expect(screen.queryByText('Pull request unlinked')).toBeNull() + rerender( + + ) + expect(screen.getByText('Refresh failed')).toBeTruthy() + expect(screen.getByText("Couldn't refresh from GitLab. Try again.")).toBeTruthy() + expect(screen.getByRole('button', { name: 'Refresh' })).toBeTruthy() }) + it.each([ + [ + 'rate limited', + { status: 'error', errorType: 'rate_limited' }, + 'GitHub refresh paused', + 'Orca will retry at', + true + ], + [ + 'signed out', + { status: 'error', errorType: 'auth' }, + 'GitHub authentication failed', + 'Check the GitHub login', + false + ] + ] as const)( + 'keeps the classified GitHub empty state over a manual failure (%s)', + (_name, refresh, title, nextStep, retryDisabled) => { + const now = Date.parse('2026-10-30T12:00:00Z') + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(now) + const model: ChecksPanelEmptyContentModel = { + activeReview: null, + activeWorktree: makeWorktree({ id: 'worktree-1', repoId: 'repo-1' }), + activeWorktreeId: 'worktree-1', + branch: 'without-pr', + checksPanelHasHardRefreshError: false, + checksPanelReviewLookup: 'unknown', + checksPanelReviewLookupResult: { state: 'unknown', openReviewUrl: null }, + confirmedReadiness: { confirmed: false, needsPush: false }, + conflictOperation: 'unknown', + createComposerOpen: false, + createPrError: null, + createPrPushFirst: false, + detachedHeadDisplay: null, + emptyRefreshing: false, + gitStatusInputs: { hasUncommittedChanges: false, remoteStatus: undefined }, + gitStatusProbeErrorContextKey: null, + handleCancelGeneratePullRequestFields: vi.fn(), + handleCreatePullRequest: vi.fn(), + handleGeneratePullRequestFields: vi.fn(), + handleLinkSuppressedPullRequest: vi.fn(), + handlePrBaseChange: vi.fn(), + handlePrTitleChange: vi.fn(), + handlePublishBranch: vi.fn(), + handleRefresh: vi.fn(async () => {}), + handleSyncBranch: vi.fn(), + hardRefreshError: null, + hostedReviewCreateCopy: localizedHostedReviewCopy('github'), + hostedReviewCreateProvider: 'github', + hostedReviewCreation: null, + isCreatingPr: false, + isFolder: false, + isGitHubReviewContext: true, + isPublishingBranch: false, + isRemoteOperationActive: false, + isSyncingBranch: false, + linkedGitLabMR: null, + linkedPR: null, + linkedReviewNumber: null, + manualRefreshError: getHostedReviewManualRefreshError('github'), + panelContextKey: 'worktree-1::without-pr', + prAiGenerationEnabled: false, + prBase: '', + prBaseQuery: '', + prBaseResults: [], + prBaseSearchError: null, + prBaseSearchPending: false, + prBody: '', + prDraft: false, + prGenerateDisabled: false, + prGenerateDisabledReason: undefined, + prGenerateError: null, + prGenerating: false, + prNumber: null, + prRefreshState: { + ...refresh, + reason: 'manual', + updatedAt: now, + nextAutoRetryAt: now + 600_000, + retryDisabledUntil: retryDisabled ? now + 600_000 : undefined + }, + prRepoDefaultBaseRef: null, + prStackedCreationSupported: false, + prTitle: '', + publishActionHasUncommittedChanges: false, + publishActionRemoteStatus: undefined, + setEmptyRefreshing: vi.fn(), + setPrBaseQuery: vi.fn(), + setPrBaseResults: vi.fn(), + setPrBody: vi.fn(), + setPrDraft: vi.fn(), + sourceControlAiActionsVisible: false, + stackParentReview: null, + suppressedGitHubPR: null + } + + const { container } = render() + + expect(container.textContent).toContain(title) + expect(container.textContent).toContain(nextStep) + expect(container.textContent).not.toContain('Refresh failed') + expect(container.textContent).not.toContain('Try again') + } + ) + it('renders the active review header and empty check/comment sections with accessible actions', () => { const model = { activeConnectionId: null, @@ -140,6 +260,7 @@ describe('checks panel concrete content', () => { handleLoadCheckDetails: vi.fn(), handleOpenPR: vi.fn(), handleRefresh: vi.fn(), + manualRefreshError: null, handleOpenStackPR: vi.fn(), handleReplyToComment: vi.fn(), handleResolve: vi.fn(), @@ -172,7 +293,7 @@ describe('checks panel concrete content', () => { titleSaving: false } satisfies ChecksPanelActiveContentModel - render() + const { rerender } = render() expect(screen.getByText('Preserve mounted panel behavior')).toBeTruthy() expect(screen.getByText('No checks configured')).toBeTruthy() @@ -181,5 +302,30 @@ describe('checks panel concrete content', () => { expect(screen.getByRole('button', { name: '#42' }).getAttribute('title')).toContain( 'Open on GitHub' ) + const failedModel = { + ...model, + checksError: 'Previous detail error', + commentsError: 'Previous detail error', + manualRefreshError: getHostedReviewManualRefreshError('gitlab'), + activeReview: { ...model.activeReview, provider: 'gitlab' as const }, + isRefreshing: true + } + rerender() + expect(screen.getAllByRole('alert')).toHaveLength(1) + expect(screen.getByRole('alert').textContent).toBe("Couldn't refresh from GitLab. Try again.") + expect(screen.getByText('Preserve mounted panel behavior')).toBeTruthy() + expect(screen.queryByText('Previous detail error')).toBeNull() + rerender( + + ) + // The classified GitHub line says more than the manual failure, so it is the one shown. + expect(screen.getAllByRole('alert')).toHaveLength(1) + expect(screen.getByRole('alert').textContent).toContain('GitHub is unreachable right now') }) }) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.test.tsx b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.test.tsx new file mode 100644 index 00000000000..5811b8d1794 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.test.tsx @@ -0,0 +1,141 @@ +// @vitest-environment happy-dom + +import { act, renderHook } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { refreshHostedReviewCard } from '@/store/slices/hosted-review-card-refresh' +import { _clearHostedReviewRequestGenerationsForTest } from '@/store/slices/hosted-review-request-state' +import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures' +import type { HostedReviewInfo } from '../../../../../shared/hosted-review' +import { isGitLabChecksPanelReview } from './gitlab-review-client' +import { useChecksPanelEntryRefreshAndTitleActions } from './use-checks-panel-entry-refresh-and-title-actions' + +type EntryRefreshInput = Parameters[0] + +const repo = { + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0 +} +const gitLabReview: HostedReviewInfo = { + provider: 'gitlab', + number: 7, + title: 'MR', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + state: 'open', + status: 'success', + mergeable: 'MERGEABLE', + updatedAt: '2026-10-30' +} +const bitbucketReview: HostedReviewInfo = { + provider: 'bitbucket', + number: 12, + title: 'PR', + url: 'https://bitbucket.example.test/w/r/pull-requests/12', + state: 'open', + status: 'success', + mergeable: 'MERGEABLE', + updatedAt: '2026-10-30' +} +const original = useAppStore.getState() + +function makeInput(review: HostedReviewInfo): EntryRefreshInput { + return { + activeGitLabReview: isGitLabChecksPanelReview(review) ? review : null, + activeReview: review, + activeWorktree: makeWorktree({ id: 'worktree-1', repoId: repo.id }), + activeWorktreeId: 'worktree-1', + branch: 'main', + checksFetchedAt: undefined, + clearTitleInputFocusTimer: vi.fn(), + commentsFetchedAt: undefined, + enqueueGitHubPRRefresh: vi.fn(), + fallbackGitHubPRNumber: null, + fetchChecks: vi.fn(), + fetchComments: vi.fn(), + fetchGitLabDetails: vi.fn(async () => {}), + fetchHostedReviewForBranch: useAppStore.getState().fetchHostedReviewForBranch, + fetchPRForBranch: vi.fn(async () => null), + hostedReviewCacheKey: 'hosted-review-key', + isFolder: false, + isGitLabReviewContext: review.provider === 'gitlab', + // Hidden, so the tab-entry refresh stays out of the way. + isPanelVisible: false, + linkedAzureDevOpsPR: null, + linkedBitbucketPR: review.provider === 'bitbucket' ? review.number : null, + linkedGiteaPR: null, + linkedGitLabMR: review.provider === 'gitlab' ? review.number : null, + linkedPR: null, + mountedRef: { current: true }, + pollIntervalRef: { current: 30_000 }, + pr: null, + prCacheKey: 'cache', + prFetchedAt: undefined, + prNumber: null, + prevChecksRef: { current: '' }, + repo, + setEditingTitle: vi.fn(), + setTitleDraft: vi.fn(), + setTitleSaving: vi.fn(), + titleDraft: '', + titleInputFocusTimerRef: { current: null }, + titleInputRef: { current: null } + } +} + +afterEach(() => { + _clearHostedReviewRequestGenerationsForTest() + useAppStore.setState(original) + vi.unstubAllGlobals() +}) + +describe('refreshHostedReviewAfterMutation', () => { + // Issue #14377: after Orca merges, the card must not keep the Open answer of a poll started before the merge. + it.each([gitLabReview, bitbucketReview])( + '$provider: reads after the write instead of joining an older poll, and a failed read is not a failed merge', + async (review) => { + const merged: HostedReviewInfo = { ...review, state: 'merged' } + const olderPoll = Promise.withResolvers() + const forBranch = vi + .fn() + .mockReturnValueOnce(olderPoll.promise) + .mockResolvedValueOnce(merged) + .mockRejectedValueOnce(new Error('offline')) + vi.stubGlobal('api', { hostedReview: { forBranch } }) + useAppStore.setState({ repos: [repo], hostedReviewCache: {} }) + const input = makeInput(review) + // The same card read the follow-up used to make, started before the merge landed. + const poll = refreshHostedReviewCard(input.fetchHostedReviewForBranch, { + repoPath: repo.path, + repoId: repo.id, + branch: 'main', + linkedGitLabMR: input.linkedGitLabMR, + linkedBitbucketPR: input.linkedBitbucketPR + }) + const { result } = renderHook(() => useChecksPanelEntryRefreshAndTitleActions(input)) + + await act(async () => result.current.refreshHostedReviewAfterMutation()) + + expect(forBranch).toHaveBeenCalledTimes(2) + expect(forBranch).toHaveBeenLastCalledWith(expect.objectContaining({ userRefresh: true })) + olderPoll.resolve(review) + await act(async () => void (await poll)) + expect(Object.values(useAppStore.getState().hostedReviewCache)[0]?.data?.state).toBe('merged') + if (review.provider === 'gitlab') { + expect(input.fetchGitLabDetails).toHaveBeenCalledWith( + expect.objectContaining({ mrNumberOverride: review.number }) + ) + } else { + expect(input.fetchPRForBranch).toHaveBeenCalledTimes(1) + } + + // The merge action treats a rejection here as its own failure. + await act(async () => + expect(result.current.refreshHostedReviewAfterMutation()).resolves.toBeUndefined() + ) + expect(forBranch).toHaveBeenCalledTimes(3) + } + ) +}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.tsx b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.tsx index ccf19e03e2b..ea00bd132ad 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.tsx @@ -204,18 +204,20 @@ export function useChecksPanelEntryRefreshAndTitleActions( if (!repo || !branch) { return } + // The read must start after the write rather than join an older poll; its failure is not the write's. if (activeReview?.provider === 'gitlab') { const refreshedReview = await refreshHostedReviewCard(fetchHostedReviewForBranch, { repoPath: repo.path, repoId: repo.id, branch, + userRefresh: true, linkedGitHubPR: linkedPR, fallbackGitHubPR: fallbackGitHubPRNumber, linkedGitLabMR, linkedBitbucketPR, linkedAzureDevOpsPR, linkedGiteaPR - }) + }).catch(() => null) const refreshedGitLabReview = refreshedReview?.provider === 'gitlab' ? refreshedReview : activeGitLabReview if (refreshedGitLabReview) { @@ -238,13 +240,14 @@ export function useChecksPanelEntryRefreshAndTitleActions( repoPath: repo.path, repoId: repo.id, branch, + userRefresh: true, linkedGitHubPR: linkedPR, fallbackGitHubPR: refreshedPR?.number ?? fallbackGitHubPRNumber, linkedGitLabMR, linkedBitbucketPR, linkedAzureDevOpsPR, linkedGiteaPR - }) + }).catch(() => null) }, [ activeGitLabReview, activeReview?.provider, diff --git a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh-recovery.test.tsx b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh-recovery.test.tsx new file mode 100644 index 00000000000..ba23e101657 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh-recovery.test.tsx @@ -0,0 +1,455 @@ +// @vitest-environment happy-dom + +import { act, cleanup, render, renderHook, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { getHostedReviewCacheKey } from '@/store/slices/hosted-review-cache-identity' +import { _clearHostedReviewRequestGenerationsForTest } from '@/store/slices/hosted-review-request-state' +import { + hostedReviewForBranchReply, + type HostedReviewForBranchArgs, + type HostedReviewInfo +} from '../../../../../shared/hosted-review' +import type { PRInfo } from '../../../../../shared/github/pull-request-types' +import type { Worktree } from '../../../../../shared/worktree/types' +import { + __resetHostedReviewBranchCacheForTests, + readHostedReviewBranchCache +} from '../../../../../main/source-control/hosted-review-branch-cache' + +vi.mock('@/components/confirmation-dialog-context', () => ({ + useConfirmationDialog: () => vi.fn() +})) + +import HostedReviewActions from '../HostedReviewActions' +import { useChecksPanelManualRefresh } from './use-checks-panel-manual-refresh' + +type RefreshInput = Parameters[0] + +const FAILURE = "Couldn't refresh from GitLab. Try again." +const WITHIN_BACKOFF = new Date('2026-10-30T12:00:05Z') +// An hour on: past the host's failure backoff, so the next poll reaches the provider. +const AFTER_BACKOFF = new Date('2026-10-30T13:00:00Z') +const repo = { + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0 +} +const openMR: HostedReviewInfo & { provider: 'gitlab' } = { + provider: 'gitlab', + number: 7, + title: 'MR', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + state: 'open', + status: 'success', + mergeable: 'UNKNOWN', + updatedAt: '2026-10-30' +} + +const original = useAppStore.getState() +let provider: () => Promise +const lookup = vi.fn(() => provider()) +// An older paired server drops reportReadOutcome and answers with the bare review. +let olderHost = false +// The paired runtime's request timeout: the click gives up while its host lookup runs on. +let clickTimesOut = false + +function cacheKey(): string { + return getHostedReviewCacheKey( + repo.path, + 'main', + useAppStore.getState().settings, + repo.id, + undefined, + undefined, + true + ) +} + +function poll(): Promise { + // The selected card's background poll: forced, never a user refresh. + return useAppStore.getState().fetchHostedReviewForBranch(repo.path, 'main', { + force: true, + repoId: repo.id, + active: true, + admissionTier: 'interactive', + linkedGitLabMR: 7 + }) +} + +function baseInput(): RefreshInput { + return { + activeConnectionId: null, + activeGitLabReview: null, + activeReview: null, + activeWorktreeId: null, + activeWorktreePath: null, + activeWorktreePushTarget: null, + asyncResultKeyRef: { current: 'cache::main::42' }, + branch: 'main', + expireGitHubPRRefreshState: vi.fn(), + fallbackGitHubPRNumber: null, + fetchGitLabDetails: vi.fn(), + fetchHostedReviewForBranch: vi.fn(async () => null), + fetchPRChecks: vi.fn(async () => []), + fetchPRComments: vi.fn(async () => []), + fetchPRForBranch: vi.fn(async () => null), + gitStatusSnapshot: null, + hostedReview: null, + hostedReviewCacheKey: 'hosted-review-key', + hostedReviewCreateProvider: 'github', + isCurrentAsyncResult: () => true, + isFolder: false, + isGitLabReviewContext: false, + linkedAzureDevOpsPR: null, + linkedBitbucketPR: null, + linkedGiteaPR: null, + linkedGitLabMR: null, + linkedPR: null, + ownerCopyHostId: null, + ownerTarget: { kind: 'local' }, + panelContextKey: 'ctx', + panelContextKeyRef: { current: 'ctx' }, + pollIntervalRef: { current: 30_000 }, + pr: null, + prCacheKey: 'cache', + prNumber: 42, + prevChecksRef: { current: '' }, + refreshInFlightRef: { current: false }, + refreshRequestKeyRef: { current: '' }, + repo, + setChecks: vi.fn(), + setChecksLoading: vi.fn(), + setComments: vi.fn(), + setCommentsLoading: vi.fn(), + setEligibilityRefreshNonce: vi.fn(), + setGitStatusSnapshot: vi.fn(), + setIsRefreshing: vi.fn(), + updateWorktreeGitIdentity: vi.fn() + } +} + +// The selected GitLab MR's panel, reading through the real store and host cache. +function gitLabInput(): RefreshInput { + return { + ...baseInput(), + activeGitLabReview: openMR, + activeReview: openMR, + fetchHostedReviewForBranch: useAppStore.getState().fetchHostedReviewForBranch, + hostedReview: openMR, + hostedReviewCacheKey: cacheKey(), + hostedReviewCreateProvider: 'gitlab', + isGitLabReviewContext: true, + linkedGitLabMR: 7, + prNumber: null + } +} + +function renderPanel(input = gitLabInput()) { + const shown: (string | null)[] = [] + const hook = renderHook(() => { + const state = useChecksPanelManualRefresh(input) + shown.push(state.manualRefreshError) + return state + }) + return { ...hook, shown, input } +} + +// Seeds Open, then the provider goes down and the user's Refresh fails. +async function failedClick() { + provider = async () => openMR + await poll() + provider = async () => { + throw new Error('GitLab 503') + } + const panel = renderPanel() + await act(async () => panel.result.current.handleRefresh()) + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + return panel +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(new Date('2026-10-30T12:00:00Z')) + olderHost = false + clickTimesOut = false + lookup.mockClear() + vi.stubGlobal('api', { + // The real host branch cache behind the IPC reply shape. + hostedReview: { + forBranch: async (args: HostedReviewForBranchArgs) => { + const pending = readHostedReviewBranchCache( + { + repoPath: repo.path, + executionHostId: 'local', + branch: args.branch, + linkedGitLabMR: args.linkedGitLabMR ?? null + }, + { headOid: null, force: args.force, userRefresh: args.userRefresh, active: true }, + lookup + ) + if (clickTimesOut && args.userRefresh) { + void pending.catch(() => {}) + throw new Error('Request timed out') + } + const read = await pending + return olderHost ? read.review : hostedReviewForBranchReply(read, args.reportReadOutcome) + } + } + }) + useAppStore.setState({ repos: [repo], hostedReviewCache: {} }) +}) + +afterEach(() => { + cleanup() + _clearHostedReviewRequestGenerationsForTest() + __resetHostedReviewBranchCacheForTests() + useAppStore.setState(original) + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +describe('a failed Checks refresh clears only on a real provider read', () => { + it.each([ + ['answers a poll from last-good during backoff', WITHIN_BACKOFF, 2], + ['serves last-good while the provider still fails', AFTER_BACKOFF, 3] + ])('keeps the failure when the host %s', async (_name, time, lookups) => { + const panel = await failedClick() + vi.setSystemTime(time) + await act(async () => void (await poll())) + expect(lookup).toHaveBeenCalledTimes(lookups) + expect(useAppStore.getState().hostedReviewCache[cacheKey()]?.data?.state).toBe('open') + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + }) + + it.each([ + ['identical data', openMR], + ['a definitive no-review answer', null] + ])('clears the failure when the provider recovers with %s', async (_name, answer) => { + const panel = await failedClick() + vi.setSystemTime(AFTER_BACKOFF) + provider = async () => answer + await act(async () => void (await poll())) + expect(lookup).toHaveBeenCalledTimes(3) + expect(useAppStore.getState().hostedReviewCache[cacheKey()]?.data).toEqual(answer) + expect(panel.result.current.manualRefreshError).toBeNull() + }) + + it('never hides the failure while a retry that then fails is pending', async () => { + const panel = await failedClick() + let failRetry: (error: Error) => void = () => {} + provider = () => + new Promise((_resolve, reject) => { + failRetry = reject + }) + let retry: Promise = Promise.resolve() + let polled: Promise = Promise.resolve(null) + await act(async () => { + retry = panel.result.current.handleRefresh() + await vi.waitFor(() => expect(lookup).toHaveBeenCalledTimes(3)) + polled = poll() + }) + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + await act(async () => { + failRetry(new Error('GitLab 503')) + await Promise.all([retry, polled]) + }) + expect(lookup).toHaveBeenCalledTimes(3) + const afterFirstFailure = panel.shown.slice(panel.shown.indexOf(FAILURE)) + expect(afterFirstFailure.every((message) => message === FAILURE)).toBe(true) + }) + + it('keeps the failure when a later poll joins the timed-out click’s still-running lookup', async () => { + provider = async () => openMR + await poll() + let finishClickLookup: (review: HostedReviewInfo) => void = () => {} + provider = () => + new Promise((resolve) => { + finishClickLookup = resolve + }) + clickTimesOut = true + const panel = renderPanel() + await act(async () => panel.result.current.handleRefresh()) + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + await act(async () => { + const polled = poll() + finishClickLookup(openMR) + await polled + }) + expect(lookup).toHaveBeenCalledTimes(2) + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + provider = async () => openMR + await act(async () => void (await poll())) + expect(lookup).toHaveBeenCalledTimes(3) + expect(panel.result.current.manualRefreshError).toBeNull() + }) + + it('keeps the failure on an older host’s bare answer until a click succeeds', async () => { + const panel = await failedClick() + olderHost = true + vi.setSystemTime(AFTER_BACKOFF) + provider = async () => openMR + await act(async () => void (await poll())) + expect(lookup).toHaveBeenCalledTimes(3) + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + await act(async () => panel.result.current.handleRefresh()) + expect(panel.result.current.manualRefreshError).toBeNull() + }) +}) + +describe('a Checks refresh click', () => { + const foundPR: PRInfo = { + number: 42, + title: 'Current review', + state: 'open', + url: 'https://github.com/orca/app/pull/42', + checksStatus: 'success', + updatedAt: '2026-10-30', + mergeable: 'MERGEABLE', + headSha: 'head-2', + prRepo: { owner: 'orca', repo: 'app', host: 'github.com' } + } + + // Old path: every provider without a GitLab review went through the GitHub branch (PR lookup + lists cleared). + it.each([ + ['unlinked Bitbucket', { hostedReviewCreateProvider: 'bitbucket' }, 'Bitbucket', false], + ['linked Bitbucket', { linkedBitbucketPR: 3 }, 'Bitbucket', false], + ['Azure DevOps', { linkedAzureDevOpsPR: 3 }, 'Azure DevOps', false], + ['GitLab with no MR', { hostedReviewCreateProvider: 'gitlab' }, 'GitLab', false], + ['GitLab with an MR', { linkedGitLabMR: 7, isGitLabReviewContext: true }, 'GitLab', false], + ['GitHub', {}, null, true] + ] as const)( + '%s: routes the click to its provider and names it on a failure it owns', + async (_name, overrides, providerName, readsGitHubPR) => { + const input = Object.assign(baseInput(), overrides) + input.fetchHostedReviewForBranch = vi.fn().mockRejectedValue(new Error('unreachable')) + const { result } = renderPanel(input) + await act(async () => result.current.handleRefresh()) + expect(input.fetchHostedReviewForBranch).toHaveBeenCalledWith( + '/workspace/repo', + 'main', + expect.objectContaining({ force: true, userRefresh: true }) + ) + expect(vi.mocked(input.fetchPRForBranch).mock.calls.length > 0).toBe(readsGitHubPR) + expect(input.fetchGitLabDetails).not.toHaveBeenCalled() + // Only the GitHub path owns checks and comments; it clears them when no PR is found. + expect(vi.mocked(input.setChecks).mock.calls.length > 0).toBe(readsGitHubPR) + expect(vi.mocked(input.setComments).mock.calls.length > 0).toBe(readsGitHubPR) + // GitHub's refresh status comes from its PR read, not this card read. + expect(result.current.manualRefreshError).toBe( + providerName ? `Couldn't refresh from ${providerName}. Try again.` : null + ) + } + ) + + it('on GitHub, a failed review-card read still refreshes the PR’s checks and comments', async () => { + const input = baseInput() + input.pr = foundPR + input.fetchPRForBranch = vi.fn(async () => foundPR) + input.fetchHostedReviewForBranch = vi.fn().mockRejectedValue(new Error('raw provider text')) + const { result } = renderPanel(input) + await act(async () => result.current.handleRefresh()) + expect(input.fetchPRChecks).toHaveBeenCalledTimes(1) + expect(input.fetchPRComments).toHaveBeenCalledTimes(1) + expect(result.current.manualRefreshError).toBeNull() + }) + + it('names GitLab without its raw text, clears on a context change, and ignores the old context’s late failure', async () => { + const input = baseInput() + input.isGitLabReviewContext = true + input.linkedGitLabMR = 7 + input.fetchHostedReviewForBranch = vi + .fn() + .mockRejectedValueOnce(new Error('raw secret provider text')) + const { result, rerender } = renderPanel(input) + await act(async () => { + await expect(result.current.handleRefresh()).resolves.toBeUndefined() + }) + expect(input.refreshInFlightRef.current).toBe(false) + expect(result.current.manualRefreshError).toBe(FAILURE) + expect(JSON.stringify(result.current)).not.toContain('raw secret') + + const late = Promise.withResolvers() + input.fetchHostedReviewForBranch = vi.fn(() => late.promise) + rerender() + let old: Promise = Promise.resolve() + act(() => { + old = result.current.handleRefresh() + }) + expect(result.current.manualRefreshError).toBe(FAILURE) + input.panelContextKey = 'new-context' + input.panelContextKeyRef.current = 'new-context' + rerender() + expect(result.current.manualRefreshError).toBeNull() + await act(async () => { + late.reject(new Error('late failure')) + await old + }) + expect(result.current.manualRefreshError).toBeNull() + }) + + // Issue #14377: Refresh after a merge on GitLab must surface the workspace's delete action. + it('publishes refreshed merged GitLab state to the existing workspace action', async () => { + const review: HostedReviewInfo & { provider: 'gitlab' } = { + ...openMR, + mergeable: 'MERGEABLE' + } + const forBranch = vi + .fn() + .mockResolvedValueOnce(review) + .mockResolvedValueOnce({ ...review, state: 'merged' }) + vi.stubGlobal('api', { hostedReview: { forBranch } }) + const input = baseInput() + input.fetchHostedReviewForBranch = useAppStore.getState().fetchHostedReviewForBranch + input.activeGitLabReview = review + input.activeReview = review + input.isGitLabReviewContext = true + const worktree: Worktree = { + id: 'worktree-1', + repoId: repo.id, + path: '/workspace/worktree', + branch: 'main', + isMainWorktree: false, + head: 'head', + isBare: false, + displayName: 'workspace', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0 + } + await input.fetchHostedReviewForBranch(repo.path, 'main', { repoId: repo.id }) + function Probe() { + const data = useAppStore((state) => Object.values(state.hostedReviewCache)[0]?.data) + const { handleRefresh } = useChecksPanelManualRefresh(input) + return ( + <> + + {data && ( + + )} + + ) + } + render() + expect(screen.queryByRole('button', { name: 'Delete Workspace' })).toBeNull() + await act(async () => screen.getByRole('button', { name: 'Refresh metadata' }).click()) + expect(screen.getByRole('button', { name: 'Delete Workspace' })).toBeTruthy() + expect(input.fetchGitLabDetails).toHaveBeenCalledWith( + expect.objectContaining({ mrNumberOverride: 7 }) + ) + expect(forBranch).toHaveBeenLastCalledWith(expect.objectContaining({ userRefresh: true })) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.tsx b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.tsx index e9187322ca0..b800f06838d 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.tsx @@ -1,7 +1,6 @@ import { useCallback } from 'react' import { useAppStore } from '@/store' import { buildGitHubPRRefreshStateClearToken } from '@/store/github/pr-refresh-state' -import { refreshHostedReviewCard } from '@/store/slices/hosted-review-card-refresh' import { getRuntimeGitStatus } from '@/runtime/runtime-git-status-client' import { getRuntimeGitUpstreamStatus } from '@/runtime/runtime-git-sync-client' import { resolveWorktreeGitCopyNow } from '@/lib/worktree-git-copy' @@ -13,7 +12,14 @@ import { import { checksPanelAsyncResultKey } from '../checks-panel-async-result-key' import { recordChecksPanelPRRefreshBreadcrumb } from '../checks-panel-pr-refresh-breadcrumb' +import { getHostedReviewManualRefreshError } from '../github-refresh-error-copy' import type { PRInfo } from '../../../../../shared/github/pull-request-types' +import { + checksPanelManualRefreshProvider, + refreshChecksPanelHostedReview, + refreshHostedReviewForClick, + useChecksPanelManualRefreshFailure +} from './hosted-review-manual-refresh' import type { ChecksPanelManualRefreshInput } from './manual-refresh-dependencies' // The manual Refresh is a user act: it may start a stopped WSL distro (E9). @@ -29,19 +35,13 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput branch, expireGitHubPRRefreshState, fallbackGitHubPRNumber, - fetchGitLabDetails, - fetchHostedReviewForBranch, fetchPRChecks, fetchPRComments, fetchPRForBranch, gitStatusSnapshot, + hostedReviewCacheKey, isCurrentAsyncResult, isFolder, - isGitLabReviewContext, - linkedAzureDevOpsPR, - linkedBitbucketPR, - linkedGiteaPR, - linkedGitLabMR, linkedPR, ownerCopyHostId, ownerTarget, @@ -64,6 +64,10 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput setIsRefreshing, updateWorktreeGitIdentity } = model + const { manualRefreshError, setManualFailure } = useChecksPanelManualRefreshFailure( + panelContextKey, + hostedReviewCacheKey + ) const handleRefresh = useCallback(async () => { if (!repo || !branch) { return @@ -82,9 +86,11 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput ) const refreshRequestKey = `${activeWorktreeId ?? ''}::${prCacheKey}::${branch}::${Date.now()}::${Math.random()}` refreshRequestKeyRef.current = refreshRequestKey - const isCurrentRequest = (): boolean => refreshRequestKeyRef.current === refreshRequestKey + const isCurrentRequest = (): boolean => + refreshRequestKeyRef.current === refreshRequestKey && + panelContextKeyRef.current === panelContextKey const refreshStartedAt = Date.now() - const refreshProvider = isGitLabReviewContext ? 'gitlab' : 'github' + const refreshProvider = checksPanelManualRefreshProvider(model) let refreshOutcome = 'started' setIsRefreshing(true) recordChecksPanelPRRefreshBreadcrumb({ @@ -177,36 +183,12 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput console.warn('[ChecksPanel] pre-refresh git identity refresh failed', error) } } - if (isGitLabReviewContext) { - const refreshedReview = await refreshHostedReviewCard(fetchHostedReviewForBranch, { - repoPath: repo.path, - repoId: repo.id, - branch, - admissionTier: 'interactive', - linkedGitHubPR: linkedPR, - fallbackGitHubPR: fallbackGitHubPRNumber, - linkedGitLabMR, - linkedBitbucketPR, - linkedAzureDevOpsPR, - linkedGiteaPR - }) - if (!isCurrentRequest()) { - return - } - const refreshedGitLabReview = - refreshedReview?.provider === 'gitlab' ? refreshedReview : activeGitLabReview - if (refreshedGitLabReview) { - await fetchGitLabDetails({ - mrNumberOverride: refreshedGitLabReview.number, - headShaOverride: refreshedGitLabReview.headSha, - commitAsCurrent: true - }) - refreshOutcome = 'review' - } else { - setChecks([]) - setComments([]) - refreshOutcome = 'no-review' - } + if (refreshProvider !== 'github') { + refreshOutcome = await refreshChecksPanelHostedReview( + model, + refreshProvider, + isCurrentRequest + ) return } const refreshStoreState = useAppStore.getState() @@ -234,18 +216,13 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput if (!isCurrentRequest()) { return } - await refreshHostedReviewCard(fetchHostedReviewForBranch, { - repoPath: repo.path, - repoId: repo.id, + // The PR read above owns GitHub's refresh status, checks and comments; the review card read only refreshes the card. + await refreshHostedReviewForClick( + model, + repo, branch, - admissionTier: 'interactive', - linkedGitHubPR: linkedPR, - fallbackGitHubPR: refreshedPR?.number ?? fallbackGitHubPRNumber, - linkedGitLabMR, - linkedBitbucketPR, - linkedAzureDevOpsPR, - linkedGiteaPR - }) + refreshedPR?.number ?? fallbackGitHubPRNumber + ).catch(() => null) if (!isCurrentRequest()) { return } @@ -331,9 +308,12 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput setComments([]) refreshOutcome = 'no-pr' } - } catch (error) { + } catch { refreshOutcome = 'error' - throw error + // GitHub failures surface through the PR store's own classified state, which clears itself. + if (isCurrentRequest() && refreshProvider !== 'github') { + setManualFailure(getHostedReviewManualRefreshError(refreshProvider)) + } } finally { recordChecksPanelPRRefreshBreadcrumb({ event: 'done', @@ -351,6 +331,9 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput currentRequest: isCurrentRequest() }) if (isCurrentRequest()) { + if (['review', 'no-review', 'pr', 'no-pr'].includes(refreshOutcome)) { + setManualFailure(null) + } refreshInFlightRef.current = false setIsRefreshing(false) // Rerun eligibility to clear resolved authentication errors even when Git state is unchanged. @@ -358,6 +341,7 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput } } }, [ + model, repo, branch, activeConnectionId, @@ -373,19 +357,12 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput prCacheKey, linkedPR, fallbackGitHubPRNumber, - fetchGitLabDetails, - linkedAzureDevOpsPR, - linkedBitbucketPR, - linkedGiteaPR, - linkedGitLabMR, isFolder, - isGitLabReviewContext, gitStatusSnapshot, panelContextKey, fetchPRForBranch, fetchPRChecks, fetchPRComments, - fetchHostedReviewForBranch, expireGitHubPRRefreshState, isCurrentAsyncResult, ownerCopyHostId, @@ -402,10 +379,14 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput setChecks, setComments, setGitStatusSnapshot, + setManualFailure, pollIntervalRef, refreshInFlightRef ]) - return { handleRefresh } + return { + handleRefresh, + manualRefreshError + } } export type ChecksPanelRefreshState = ReturnType diff --git a/src/renderer/src/components/right-sidebar/github-refresh-error-copy.ts b/src/renderer/src/components/right-sidebar/github-refresh-error-copy.ts index 25d2b58c0fd..3c197c6eec5 100644 --- a/src/renderer/src/components/right-sidebar/github-refresh-error-copy.ts +++ b/src/renderer/src/components/right-sidebar/github-refresh-error-copy.ts @@ -1,3 +1,8 @@ +import type { HostedReviewProvider } from '../../../../shared/hosted-review' +import { + localizedHostedReviewCopy, + resolveSupportedHostedReviewCopyProvider +} from '@/i18n/hosted-review-localized-copy' import type { PRRefreshUpstreamErrorType } from '../../../../shared/github/pull-request-refresh-types' import { translate } from '@/i18n/i18n' @@ -73,3 +78,14 @@ export function getChecksPanelRefreshErrorBannerLine( "Couldn't refresh from GitHub. Showing the last known status." ) } + +export function getHostedReviewManualRefreshError(provider: HostedReviewProvider): string { + return translate( + 'auto.components.right.sidebar.github.refresh.error.copy.manual_provider', + "Couldn't refresh from {{provider}}. Try again.", + { + provider: localizedHostedReviewCopy(resolveSupportedHostedReviewCopyProvider(provider)) + .providerName + } + ) +} diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 15fad200daa..779e7be825f 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -14592,7 +14592,8 @@ "79aa06bb2c": "Aktualisierung fehlgeschlagen. Die GitHub-API ist vorübergehend nicht verfügbar. Der letzte bekannte Status wird angezeigt.", "6ec12cee0c": "Aktualisierung fehlgeschlagen. GitHub ist derzeit nicht erreichbar. Der letzte bekannte Status wird angezeigt.", "de088015e8": "Aktualisierung fehlgeschlagen. GitHub begrenzt die Anfragerate. Der letzte bekannte Status wird angezeigt.", - "d9dd7c6687": "Die Daten von GitHub konnten nicht aktualisiert werden. Der letzte bekannte Status wird angezeigt." + "d9dd7c6687": "Die Daten von GitHub konnten nicht aktualisiert werden. Der letzte bekannte Status wird angezeigt.", + "manual_provider": "Die Daten von {{provider}} konnten nicht aktualisiert werden. Erneut versuchen." } } }, diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 92c8f501d6e..a5947b368b6 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -14847,7 +14847,8 @@ "79aa06bb2c": "Couldn't refresh. GitHub's API is temporarily unavailable. Showing the last known status.", "6ec12cee0c": "Couldn't refresh. GitHub is unreachable right now. Showing the last known status.", "de088015e8": "Couldn't refresh. GitHub is rate-limiting requests. Showing the last known status.", - "d9dd7c6687": "Couldn't refresh from GitHub. Showing the last known status." + "d9dd7c6687": "Couldn't refresh from GitHub. Showing the last known status.", + "manual_provider": "Couldn't refresh from {{provider}}. Try again." } } }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 4019cb2a852..877e3f5e829 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -14449,7 +14449,8 @@ "79aa06bb2c": "No se pudo actualizar. La API de GitHub no está disponible temporalmente. Mostrando el último estado conocido.", "6ec12cee0c": "No se pudo actualizar. GitHub es inalcanzable en este momento. Mostrando el último estado conocido.", "de088015e8": "No se pudo actualizar. GitHub está limitando las solicitudes. Se muestra el último estado conocido.", - "d9dd7c6687": "No se pudo actualizar desde GitHub. Mostrando el último estado conocido." + "d9dd7c6687": "No se pudo actualizar desde GitHub. Mostrando el último estado conocido.", + "manual_provider": "No se pudo actualizar desde {{provider}}. Vuelve a intentarlo." } } }, diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 1f5ab32df96..278c7272237 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -14673,7 +14673,8 @@ "79aa06bb2c": "Actualisation impossible. L'API de GitHub est temporairement indisponible. Affichage du dernier statut connu.", "6ec12cee0c": "Actualisation impossible. GitHub est injoignable pour le moment. Affichage du dernier statut connu.", "de088015e8": "Actualisation impossible. GitHub limite les requêtes. Affichage du dernier statut connu.", - "d9dd7c6687": "Actualisation depuis GitHub impossible. Affichage du dernier statut connu." + "d9dd7c6687": "Actualisation depuis GitHub impossible. Affichage du dernier statut connu.", + "manual_provider": "Actualisation depuis {{provider}} impossible. Réessayez." } } }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 6223481e93c..277716afe0b 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -14081,7 +14081,8 @@ "79aa06bb2c": "更新できませんでした。GitHub の API を一時的に利用できません。最後に取得した状態を表示しています。", "6ec12cee0c": "更新できませんでした。現在 GitHub に接続できません。最後に取得した状態を表示しています。", "de088015e8": "更新できませんでした。GitHub がリクエストを制限しています。最後に取得した状態を表示しています。", - "d9dd7c6687": "GitHub から更新できませんでした。最後に取得した状態を表示しています。" + "d9dd7c6687": "GitHub から更新できませんでした。最後に取得した状態を表示しています。", + "manual_provider": "{{provider}} から更新できませんでした。もう一度お試しください。" } } }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 9e936c2c0ac..8df7c31f324 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -14081,7 +14081,8 @@ "79aa06bb2c": "새로고침할 수 없습니다. GitHub의 API를 일시적으로 사용할 수 없습니다. 마지막으로 알려진 상태를 표시합니다.", "6ec12cee0c": "새로고침할 수 없습니다. 지금은 GitHub에 연결할 수 없습니다. 마지막으로 알려진 상태를 표시합니다.", "de088015e8": "새로고침할 수 없습니다. GitHub에서 요청 수를 제한하고 있습니다. 마지막으로 확인된 상태를 표시합니다.", - "d9dd7c6687": "GitHub에서 새로고침할 수 없습니다. 마지막으로 알려진 상태를 표시합니다." + "d9dd7c6687": "GitHub에서 새로고침할 수 없습니다. 마지막으로 알려진 상태를 표시합니다.", + "manual_provider": "{{provider}}에서 새로고침할 수 없습니다. 다시 시도하세요." } } }, diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 17d7ac36797..7488a15b297 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -10612,7 +10612,8 @@ "79aa06bb2c": "Não foi possível atualizar. A API do GitHub está temporariamente indisponível. Mostrando o último status conhecido.", "6ec12cee0c": "Não foi possível atualizar. O GitHub está inacessível agora. Mostrando o último status conhecido.", "de088015e8": "Não foi possível atualizar. O GitHub está limitando as requisições. Mostrando o último status conhecido.", - "d9dd7c6687": "Não foi possível atualizar a partir do GitHub. Mostrando o último status conhecido." + "d9dd7c6687": "Não foi possível atualizar a partir do GitHub. Mostrando o último status conhecido.", + "manual_provider": "Não foi possível atualizar a partir do {{provider}}. Tente novamente." } } }, diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 753981c7056..5757e78f9f1 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -15036,7 +15036,8 @@ "79aa06bb2c": "Не удалось обновить. API GitHub временно недоступен. Показан последний известный статус.", "6ec12cee0c": "Не удалось обновить. GitHub сейчас недоступен. Показан последний известный статус.", "de088015e8": "Не удалось обновить. GitHub ограничивает запросы. Показан последний известный статус.", - "d9dd7c6687": "Не удалось получить обновление с GitHub. Показан последний известный статус." + "d9dd7c6687": "Не удалось получить обновление с GitHub. Показан последний известный статус.", + "manual_provider": "Не удалось получить обновление с {{provider}}. Попробуйте снова." } } }, diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 96b858ccd0e..7e65d7a51b9 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -14578,7 +14578,8 @@ "79aa06bb2c": "Yenilenemedi. GitHub'ın API'si geçici olarak kullanılamıyor. Bilinen son durum gösteriliyor.", "6ec12cee0c": "Yenilenemedi. GitHub şu anda erişilemez durumda. Bilinen son durum gösteriliyor.", "de088015e8": "Yenilenemedi. GitHub istekleri sınırlıyor. Bilinen son durum gösteriliyor.", - "d9dd7c6687": "GitHub'dan yenilenemedi. Bilinen son durum gösteriliyor." + "d9dd7c6687": "GitHub'dan yenilenemedi. Bilinen son durum gösteriliyor.", + "manual_provider": "{{provider}} kaynağından yenilenemedi. Tekrar deneyin." } } }, diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index ea0e102dbc7..ce715f10d46 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -14391,7 +14391,8 @@ "79aa06bb2c": "重新整理失敗。GitHub 的 API 暫時不可用。正在顯示上次已知狀態。", "6ec12cee0c": "重新整理失敗。現在無法存取 GitHub。正在顯示上次已知狀態。", "de088015e8": "重新整理失敗。GitHub 正在限制請求頻率。正在顯示上次已知狀態。", - "d9dd7c6687": "無法從 GitHub 重新整理。正在顯示上次已知狀態。" + "d9dd7c6687": "無法從 GitHub 重新整理。正在顯示上次已知狀態。", + "manual_provider": "無法從 {{provider}} 重新整理。請重試。" } } }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index d2a22f3ae40..a5b9b279984 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -14081,7 +14081,8 @@ "79aa06bb2c": "刷新失败。GitHub 的 API 暂时不可用。正在显示上次已知状态。", "6ec12cee0c": "刷新失败。现在无法访问 GitHub。正在显示上次已知状态。", "de088015e8": "刷新失败。GitHub 正在限制请求频率。正在显示上次已知状态。", - "d9dd7c6687": "无法从 GitHub 刷新。正在显示上次已知状态。" + "d9dd7c6687": "无法从 GitHub 刷新。正在显示上次已知状态。", + "manual_provider": "无法从 {{provider}} 刷新。请重试。" } } }, diff --git a/src/renderer/src/lib/hosted-review-repo-read.ts b/src/renderer/src/lib/hosted-review-repo-read.ts index 7367f5d527e..35ce4693cbf 100644 --- a/src/renderer/src/lib/hosted-review-repo-read.ts +++ b/src/renderer/src/lib/hosted-review-repo-read.ts @@ -6,7 +6,10 @@ import type { Repo } from '../../../shared/repo-types' export function readHostedReviewForRepo( repo: Repo, - query: Omit + query: Omit< + HostedReviewForBranchArgs, + 'repoPath' | 'repoId' | 'repoOwnerExecutionHostId' | 'reportReadOutcome' + > ): Promise { const args = { ...query, repoPath: repo.path, repoId: repo.id } const target = hostedReviewRepoOwnerTarget(repo) diff --git a/src/renderer/src/store/lookup-generation-sequence.ts b/src/renderer/src/store/lookup-generation-sequence.ts index ec31f6e47a1..148652c2e0a 100644 --- a/src/renderer/src/store/lookup-generation-sequence.ts +++ b/src/renderer/src/store/lookup-generation-sequence.ts @@ -1,7 +1,12 @@ -/** Use one never-reset process-wide lookup sequence. Per-key counters reused after eviction can let old replies impersonate current owners and discard newer work. Callers compare equality only, so sharing across caches/coordinators is safe. */ +/** Use one never-reset process-wide lookup sequence. Per-key counters reused after eviction can let old replies impersonate current owners and discard newer work. It only grows, so sharing across caches/coordinators is safe for equality and for "issued after" checks. */ let lookupGenerationSequence = 0 export function nextLookupGeneration(): number { lookupGenerationSequence += 1 return lookupGenerationSequence } + +/** Every request issued after this call gets a larger generation. */ +export function latestLookupGeneration(): number { + return lookupGenerationSequence +} diff --git a/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts b/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts index 50850ac19dc..89a558a3f65 100644 --- a/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts +++ b/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts @@ -601,7 +601,8 @@ describe('createGitHubSlice.fetchPRForBranch', () => { linkedGitLabMR: null, linkedGiteaPR: null, repoId, - repoPath + repoPath, + reportReadOutcome: true }) expect(store.getState().hostedReviewCache[hostedReviewCacheKey]).toEqual({ data: gitlabReview, diff --git a/src/renderer/src/store/slices/hosted-review-cache-race.test.ts b/src/renderer/src/store/slices/hosted-review-cache-race.test.ts index f2e41788ffa..ecdc936a634 100644 --- a/src/renderer/src/store/slices/hosted-review-cache-race.test.ts +++ b/src/renderer/src/store/slices/hosted-review-cache-race.test.ts @@ -323,7 +323,8 @@ describe('hosted review cache race protection', () => { linkedGitHubPR: null, linkedGitLabMR: null, linkedGiteaPR: null, - repoPath: '/repo' + repoPath: '/repo', + reportReadOutcome: true }) resolveGitHubLookup(githubReview) diff --git a/src/renderer/src/store/slices/hosted-review-cache-state.ts b/src/renderer/src/store/slices/hosted-review-cache-state.ts index c56becd86b7..2b60699067e 100644 --- a/src/renderer/src/store/slices/hosted-review-cache-state.ts +++ b/src/renderer/src/store/slices/hosted-review-cache-state.ts @@ -3,12 +3,17 @@ import type { CreateHostedReviewInput, CreateStackedHostedReviewInput, HostedReviewCreationEligibility, + HostedReviewForBranchArgs, + HostedReviewForBranchOutcome, + HostedReviewForBranchReply, HostedReviewInfo } from '../../../../shared/hosted-review' +import { hostedReviewForBranchOutcome } from '../../../../shared/hosted-review' import type { Repo } from '../../../../shared/repo-types' import type { PRInfo } from '../../../../shared/github/pull-request-types' import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { ipcOrRuntimeTargetForHostId } from '@/runtime/runtime-client-target' +import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' export type HostedReviewCacheEntry = { @@ -17,6 +22,8 @@ export type HostedReviewCacheEntry = { stale?: boolean linkedReviewHintKey?: string branchLookupGitHubPRNumber?: number + /** Lookup generation of the newest request the host answered from a provider read it stored as current. */ + providerReadGeneration?: number } export type HostedReviewCache = Record> @@ -24,6 +31,7 @@ export type HostedReviewFetchOptions = { /** Source-qualified exact lookup; does not replace the branch’s selected review. */ exactReviewKey?: string force?: boolean + userRefresh?: boolean repoId?: string admissionTier?: 'interactive' | 'status' | 'background' staleWhileRevalidate?: boolean @@ -229,6 +237,9 @@ export function hostedReviewBranchLookupArgs( return { branch, ...(options?.force === true ? { force: true } : {}), + ...(options?.userRefresh === true ? { userRefresh: true } : {}), + // Only this store asks, so the Checks panel can tell a real provider read from a cached answer. + reportReadOutcome: true, ...(options?.admissionTier ? { admissionTier: options.admissionTier } : {}), ...(options?.repoId !== undefined ? { repoId: options.repoId } : {}), currentHeadOid: options?.currentHeadOid ?? null, @@ -241,3 +252,40 @@ export function hostedReviewBranchLookupArgs( linkedGiteaPR: options?.linkedGiteaPR ?? null } } + +export async function requestHostedReviewForBranch( + target: RuntimeClientTarget, + runtimeParams: Record, + ipcArgs: HostedReviewForBranchArgs +): Promise { + return hostedReviewForBranchOutcome( + target.kind === 'environment' + ? await callRuntimeRpc( + target, + 'hostedReview.forBranch', + runtimeParams, + // Remote git/gh, especially Windows paths, can be slow; main queue bounds concurrency so longer timeout cannot cause stampedes. + { timeoutMs: 30_000 } + ) + : await window.api.hostedReview.forBranch(ipcArgs) + ) +} + +export function hostedReviewCallerSettlement( + readPreserved: () => HostedReviewCacheEntry | undefined, + options?: HostedReviewFetchOptions +): (request: Promise) => Promise { + return async (request) => { + try { + return await request + } catch (error) { + if (options?.userRefresh) { + throw error + } + const preserved = readPreserved() + return isStaleMergedGitHubReviewForHead(preserved, options?.currentHeadOid) + ? null + : (preserved?.data ?? null) + } + } +} diff --git a/src/renderer/src/store/slices/hosted-review-cache.test.ts b/src/renderer/src/store/slices/hosted-review-cache.test.ts index 88b51431d1a..4eb54a4a60c 100644 --- a/src/renderer/src/store/slices/hosted-review-cache.test.ts +++ b/src/renderer/src/store/slices/hosted-review-cache.test.ts @@ -68,6 +68,92 @@ describe('hosted review cache revalidation', () => { _clearHostedReviewRequestGenerationsForTest() }) + it('does not let a pre-click forced flight satisfy manual refresh or replace its result', async () => { + let finishOld: (value: HostedReviewInfo) => void = () => {} + mockApi.hostedReview.forBranch + .mockReturnValueOnce( + new Promise((resolve) => { + finishOld = resolve + }) + ) + .mockResolvedValueOnce({ ...review, state: 'merged' }) + const store = makeStore() + const before = store.getState().fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + const options = { force: true, userRefresh: true } + const click = store.getState().fetchHostedReviewForBranch('/repo', 'feature', options) + finishOld(review) + await before + await expect(click).resolves.toMatchObject({ state: 'merged' }) + expect(mockApi.hostedReview.forBranch).toHaveBeenLastCalledWith( + expect.objectContaining({ userRefresh: true }) + ) + expect(Object.values(store.getState().hostedReviewCache)[0]?.data?.state).toBe('merged') + expect(_getHostedReviewRequestGenerationCountForTest()).toBe(0) + }) + + it('retains last-good after refused manual dispatch without restoring a superseded renderer owner', async () => { + const store = makeStore() + mockApi.hostedReview.forBranch.mockResolvedValueOnce(review) + await store.getState().fetchHostedReviewForBranch('/repo', 'feature') + const original = Object.values(store.getState().hostedReviewCache)[0] + let finishOld: (value: HostedReviewInfo) => void = () => {} + mockApi.hostedReview.forBranch + .mockReturnValueOnce( + new Promise((resolve) => { + finishOld = resolve + }) + ) + .mockRejectedValueOnce(new Error('capacity refused')) + const before = store.getState().fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + const options = { force: true, userRefresh: true } + await expect( + store.getState().fetchHostedReviewForBranch('/repo', 'feature', options) + ).rejects.toThrow('capacity refused') + finishOld({ ...review, state: 'merged' }) + await before + expect(Object.values(store.getState().hostedReviewCache)[0]).toEqual(original) + expect(_getHostedReviewRequestGenerationCountForTest()).toBe(0) + mockApi.hostedReview.forBranch.mockResolvedValueOnce({ ...review, state: 'merged' }) + await expect( + store.getState().fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + ).resolves.toMatchObject({ state: 'merged' }) + }) + + it('settles a failed manual runtime flight separately for an ordinary joiner without renewing last-good', async () => { + const store = makeStore() + store.setState((state) => ({ + repos: state.repos.map((repo) => ({ ...repo, executionHostId: 'runtime:paired' })) + })) + runtimeRpc.callRuntimeRpc.mockResolvedValueOnce(review) + await store.getState().fetchHostedReviewForBranch('/repo', 'feature') + const original = Object.values(store.getState().hostedReviewCache)[0] + let reject: (error: Error) => void = () => {} + runtimeRpc.callRuntimeRpc.mockReturnValueOnce( + new Promise((_, fail) => { + reject = fail + }) + ) + const manual = store + .getState() + .fetchHostedReviewForBranch('/repo', 'feature', { force: true, userRefresh: true }) + const failed = expect(manual).rejects.toThrow('offline') + const ordinary = store + .getState() + .fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + reject(new Error('offline')) + await failed + await expect(ordinary).resolves.toEqual(review) + expect(runtimeRpc.callRuntimeRpc).toHaveBeenCalledTimes(2) + expect(runtimeRpc.callRuntimeRpc).toHaveBeenLastCalledWith( + expect.objectContaining({ kind: 'environment', environmentId: 'paired' }), + 'hostedReview.forBranch', + expect.objectContaining({ userRefresh: true }), + { timeoutMs: 30_000 } + ) + expect(Object.values(store.getState().hostedReviewCache)[0]).toEqual(original) + expect(_getHostedReviewRequestGenerationCountForTest()).toBe(0) + }) + it('dedupes repeated linked PR retries while a stronger lookup is in flight', async () => { let resolveLinkedLookup: (value: typeof review) => void = () => {} const linkedLookup = new Promise((resolve) => { diff --git a/src/renderer/src/store/slices/hosted-review-card-refresh.ts b/src/renderer/src/store/slices/hosted-review-card-refresh.ts index e35dad1f50f..5289ae7f98d 100644 --- a/src/renderer/src/store/slices/hosted-review-card-refresh.ts +++ b/src/renderer/src/store/slices/hosted-review-card-refresh.ts @@ -12,6 +12,7 @@ type RefreshHostedReviewCardArgs = { repoPath: string repoId: string branch: string + userRefresh?: boolean admissionTier?: 'interactive' | 'status' | 'background' linkedGitHubPR?: number | null fallbackGitHubPR?: number | null @@ -29,6 +30,7 @@ export function refreshHostedReviewCard( const fallbackGitHubPR = args.linkedGitHubPR == null ? (args.fallbackGitHubPR ?? null) : null return fetchHostedReviewForBranch(args.repoPath, args.branch, { force: true, + ...(args.userRefresh === true ? { userRefresh: true } : {}), repoId: args.repoId, ...(args.admissionTier ? { admissionTier: args.admissionTier } : {}), repoOwnerExecutionHostId: args.repoOwnerExecutionHostId, diff --git a/src/renderer/src/store/slices/hosted-review-request-state.ts b/src/renderer/src/store/slices/hosted-review-request-state.ts index 8b7d225b5d7..fc7a60224d9 100644 --- a/src/renderer/src/store/slices/hosted-review-request-state.ts +++ b/src/renderer/src/store/slices/hosted-review-request-state.ts @@ -176,10 +176,26 @@ export function _clearHostedReviewRequestGenerationsForTest(): void { /** A forced request needs a forced flight; an explicit Refresh (wake) needs one that may start the WSL distro (E9). */ export function canJoinHostedReviewFlight( - inflight: { force: boolean; wakeWslDistro: boolean }, - options: { force?: boolean; wakeWslDistro?: boolean } | undefined + inflight: { force: boolean; wakeWslDistro: boolean; currentHeadOid?: string | null }, + options: + | { + force?: boolean + wakeWslDistro?: boolean + userRefresh?: boolean + currentHeadOid?: string | null + } + | undefined ): boolean { - return (!options?.force || inflight.force) && (!options?.wakeWslDistro || inflight.wakeWslDistro) + return ( + !options?.userRefresh && + !( + options?.currentHeadOid != null && + inflight.currentHeadOid != null && + options.currentHeadOid !== inflight.currentHeadOid + ) && + (!options?.force || inflight.force) && + (!options?.wakeWslDistro || inflight.wakeWslDistro) + ) } /** Records a freshly issued request in the in-flight map and supersedes any queued revalidation for its key. */ @@ -190,7 +206,7 @@ export function registerInflightHostedReviewRequest( ...entry }: { promise: Promise - options: { force?: boolean; wakeWslDistro?: boolean } | undefined + options: { force?: boolean; wakeWslDistro?: boolean; userRefresh?: boolean } | undefined currentHeadOid: string | null generation: number startedAt: number diff --git a/src/renderer/src/store/slices/hosted-review.test.ts b/src/renderer/src/store/slices/hosted-review.test.ts index 636e28b4cda..76d6628aef0 100644 --- a/src/renderer/src/store/slices/hosted-review.test.ts +++ b/src/renderer/src/store/slices/hosted-review.test.ts @@ -104,6 +104,7 @@ describe('hosted review slice', () => { expect(mockApi.hostedReview.forBranch).toHaveBeenCalledWith({ repoPath: '/repo', branch: 'feature/gitlab', + reportReadOutcome: true, currentHeadOid: null, linkedGitHubPR: null, linkedGitLabMR: 5, diff --git a/src/renderer/src/store/slices/hosted-review.ts b/src/renderer/src/store/slices/hosted-review.ts index 58ecad1ac52..b6aa2c56d70 100644 --- a/src/renderer/src/store/slices/hosted-review.ts +++ b/src/renderer/src/store/slices/hosted-review.ts @@ -19,8 +19,10 @@ import { findHostedReviewRepoForFetch, hasNewerHostedReviewCacheEntry, hostedReviewOwnerIpcArgs, + hostedReviewCallerSettlement, hostedReviewBranchLookupArgs, isFreshHostedReview, + requestHostedReviewForBranch, isStaleMergedGitHubReviewForHead, hostedReviewRepoOwnerTarget, shouldRefetchForLinkedHint, @@ -173,6 +175,7 @@ export const createHostedReviewSlice: StateCreator get().hostedReviewCache[cacheKey], + options + ) const startRequest = (): Promise => { const generation = nextLookupGeneration() const requestStartedAt = Date.now() @@ -207,20 +207,11 @@ export const createHostedReviewSlice: StateCreator { try { const args = hostedReviewBranchLookupArgs(branch, options) - const review = - target.kind === 'environment' - ? await callRuntimeRpc( - target, - 'hostedReview.forBranch', - { repo: repo?.id ?? options?.repoId ?? repoPath, repoPath, ...args }, - // Remote git/gh, especially Windows paths, can be slow; main queue bounds concurrency so longer timeout cannot cause stampedes. - { timeoutMs: 30_000 } - ) - : await window.api.hostedReview.forBranch({ - repoPath, - ...hostedReviewOwnerIpcArgs(options), - ...args - }) + const { review, readOutcome } = await requestHostedReviewForBranch( + target, + { repo: repo?.id ?? options?.repoId ?? repoPath, repoPath, ...args }, + { repoPath, ...hostedReviewOwnerIpcArgs(options), ...args } + ) if (requestGenerations.get(cacheKey) === generation) { set((state) => { if ( @@ -251,6 +242,11 @@ export const createHostedReviewSlice: StateCreator