From e55ff64d98cb84cdf83867b3c207bfadce06afee Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:43:52 -0800 Subject: [PATCH] Fix hosted review selection, conversations and optional job failures Co-authored-by: Mahedi Hasan Emon Co-authored-by: Victor GALISSON --- mobile/src/tasks/gitlab-check-summary.ts | 12 +- .../mobile-tasks-provider-detail-types.ts | 1 + .../tasks/task-item-detail-reply-schema.ts | 1 + .../client-pr-conversation-requests.test.ts | 117 ++++++++++- .../client-pr-rest-revalidation.test.ts | 53 +++++ .../github/client/fetch/get-pr-comments.ts | 104 ++++++++-- .../fetch/pr-conversation-pagination.ts | 111 +++++++++++ .../client/fetch/pr-conversation-response.ts | 134 ++++++++----- .../client/fetch/pr-review-threads-query.ts | 115 ++++------- .../github/client/lookup/pr-branch-lookup.ts | 87 ++++++--- .../client/lookup/pull-request-lookup-data.ts | 29 ++- .../client/lookup/tracked-upstream-branch.ts | 137 +++++++++---- .../client/lookup/tracked-upstream-cache.ts | 3 + .../github/github-read-execution-scope.ts | 20 +- .../github/merged-pr-commit-membership.ts | 139 +++++--------- .../gitlab/branch-review-discovery.test.ts | 93 +++++++++ src/main/gitlab/branch-review-discovery.ts | 143 ++++++++++++++ src/main/gitlab/branch-review-source.ts | 42 ++++ .../gitlab/client-mr-branch-lookup.test.ts | 139 +++++++++++++- src/main/gitlab/gitlab-paginated-list.ts | 2 +- src/main/gitlab/glab-error-classification.ts | 17 ++ src/main/gitlab/mappers.ts | 22 +-- src/main/gitlab/merge-request-lookup.ts | 173 ++++++++++++++--- .../merged-mr-commit-membership.test.ts | 82 ++++++++ .../gitlab/merged-mr-commit-membership.ts | 93 +++++++++ src/main/gitlab/mr-discussion-notes.test.ts | 120 ++++++++++++ src/main/gitlab/mr-discussion-notes.ts | 20 +- src/main/gitlab/pipeline-job-graph.test.ts | 29 +++ src/main/gitlab/pipeline-job-graph.ts | 4 + src/main/gitlab/pipeline-job-mutations.ts | 2 + .../gitlab/review-project-identity.test.ts | 71 +++++++ src/main/gitlab/review-project-identity.ts | 113 +++++++++++ src/main/gitlab/work-item-details.test.ts | 26 +++ .../source-control/branch-review-selection.ts | 29 +++ .../code-host-read-execution-scope.ts | 18 ++ src/main/source-control/forge-provider.ts | 8 +- src/main/source-control/hosted-review.ts | 2 +- .../merged-review-membership-memo.ts | 92 +++++++++ .../source-control/review-current-head.ts | 23 +++ .../panel/CheckRunDetailsPanel.tsx | 4 + .../checks-tab-check-row.tsx | 6 +- .../github/pr-check-presentation.ts | 3 + .../components/gitlab-item-dialog-parts.tsx | 16 +- .../presentation/check-presentation.tsx | 9 + .../checks-panel/presentation/checks-list.tsx | 4 +- src/renderer/src/i18n/locales/de.json | 3 + src/renderer/src/i18n/locales/en.json | 1 + src/renderer/src/i18n/locales/fr.json | 3 + .../gitlab-job-trace-client.test.ts | 26 +++ .../commands/git-config-snapshot-runner.ts | 12 +- .../remotes/git-review-branch-source.test.ts | 63 ++++++ .../git/remotes/git-review-branch-source.ts | 181 ++++++++++++++++++ src/shared/github/check-types.ts | 1 + src/shared/gitlab-types.ts | 1 + .../gitlab/gitlab-allowed-failure.test.ts | 51 +++++ .../gitlab/gitlab-job-trace-check-details.ts | 6 +- .../checks/gitlab/gitlab-pipeline-checks.ts | 16 +- .../checks/pr-check-status-label.ts | 3 + .../checks/provider-check-summary.ts | 9 +- 59 files changed, 2419 insertions(+), 425 deletions(-) create mode 100644 src/main/github/client/fetch/pr-conversation-pagination.ts create mode 100644 src/main/gitlab/branch-review-discovery.test.ts create mode 100644 src/main/gitlab/branch-review-discovery.ts create mode 100644 src/main/gitlab/branch-review-source.ts create mode 100644 src/main/gitlab/merged-mr-commit-membership.test.ts create mode 100644 src/main/gitlab/merged-mr-commit-membership.ts create mode 100644 src/main/gitlab/mr-discussion-notes.test.ts create mode 100644 src/main/gitlab/review-project-identity.test.ts create mode 100644 src/main/gitlab/review-project-identity.ts create mode 100644 src/main/source-control/branch-review-selection.ts create mode 100644 src/main/source-control/code-host-read-execution-scope.ts create mode 100644 src/main/source-control/merged-review-membership-memo.ts create mode 100644 src/main/source-control/review-current-head.ts create mode 100644 src/renderer/src/runtime/repository-gitlab/gitlab-job-trace-client.test.ts create mode 100644 src/shared/git/remotes/git-review-branch-source.test.ts create mode 100644 src/shared/git/remotes/git-review-branch-source.ts create mode 100644 src/shared/source-control/checks/gitlab/gitlab-allowed-failure.test.ts diff --git a/mobile/src/tasks/gitlab-check-summary.ts b/mobile/src/tasks/gitlab-check-summary.ts index b97d1998125..ca1e1319b05 100644 --- a/mobile/src/tasks/gitlab-check-summary.ts +++ b/mobile/src/tasks/gitlab-check-summary.ts @@ -1,13 +1,12 @@ import { gitLabPipelineToPRCheck, - mapGitLabPipelineJobStatusToCheckStatus, - mapGitLabPipelineJobStatusToConclusion + gitLabPipelineJobOutcome } from '../../../src/shared/source-control/checks/gitlab/gitlab-pipeline-checks' import { summarizeProviderChecks } from '../../../src/shared/source-control/checks/provider-check-summary' import type { ProviderCheckSummary } from '../../../src/shared/github/pull-request-types' import type { GitLabPipeline } from '../../../src/shared/gitlab-types' -type GitLabPipelineJobLike = { status: string } +type GitLabPipelineJobLike = { status: string; allowFailure?: boolean } export function buildGitLabCheckSummary( jobs: GitLabPipelineJobLike[], @@ -20,10 +19,5 @@ export function buildGitLabCheckSummary( scope: 'pipeline' } } - return summarizeProviderChecks( - jobs.map((job) => ({ - status: mapGitLabPipelineJobStatusToCheckStatus(job.status), - conclusion: mapGitLabPipelineJobStatusToConclusion(job.status) - })) - ) + return summarizeProviderChecks(jobs.map(gitLabPipelineJobOutcome)) } diff --git a/mobile/src/tasks/mobile-tasks-provider-detail-types.ts b/mobile/src/tasks/mobile-tasks-provider-detail-types.ts index c0ff759eaa2..bb2ed8bbada 100644 --- a/mobile/src/tasks/mobile-tasks-provider-detail-types.ts +++ b/mobile/src/tasks/mobile-tasks-provider-detail-types.ts @@ -251,6 +251,7 @@ export type DetailPayload = name: string stage: string status: string + allowFailure?: boolean webUrl?: string | null duration?: number | null }> diff --git a/mobile/src/tasks/task-item-detail-reply-schema.ts b/mobile/src/tasks/task-item-detail-reply-schema.ts index 951a41ab2be..e58a0ee5058 100644 --- a/mobile/src/tasks/task-item-detail-reply-schema.ts +++ b/mobile/src/tasks/task-item-detail-reply-schema.ts @@ -74,6 +74,7 @@ export const gitlabWorkItemDetailSchema = z name: z.string(), stage: z.string(), status: z.string(), + allowFailure: salvagedOptional('allowFailure', z.boolean()), webUrl: prNullableText('webUrl'), duration: salvagedOptional('duration', z.number().finite().nullable()) }) diff --git a/src/main/github/client-pr-conversation-requests.test.ts b/src/main/github/client-pr-conversation-requests.test.ts index 84d729a97ec..c5f8abb9644 100644 --- a/src/main/github/client-pr-conversation-requests.test.ts +++ b/src/main/github/client-pr-conversation-requests.test.ts @@ -53,7 +53,13 @@ const comment = { url: 'https://example.test/comment' } function response(pr: unknown, errors?: unknown): { stdout: string } { - return { stdout: JSON.stringify({ data: { repository: { pullRequest: pr } }, errors }) } + return { + stdout: JSON.stringify({ data: { repository: { pullRequest: pr } }, errors }, (_key, value) => + value && typeof value === 'object' && Array.isArray(value.nodes) + ? { pageInfo: { hasNextPage: false, endCursor: null }, ...value } + : value + ) + } } describe('PR conversation request reuse', () => { @@ -83,6 +89,7 @@ describe('PR conversation request reuse', () => { ) ghExecFileAsyncMock .mockRejectedValueOnce(Object.assign(new Error('GraphQL error'), partial)) + .mockResolvedValueOnce({ stdout: 'me' }) .mockResolvedValueOnce({ stdout: JSON.stringify([ { @@ -96,13 +103,13 @@ describe('PR conversation request reuse', () => { }) const comments = await getPRComments('/repo', 7, { ...options, noCache: true }) expect(comments.map((c) => c.body)).toEqual(['Conversation', 'Review summary']) - expect(ghExecFileAsyncMock.mock.calls[1][0]).toEqual([ + expect(ghExecFileAsyncMock.mock.calls[2][0]).toEqual([ 'api', '-H', 'Accept: application/vnd.github.full+json', 'repos/acme/widgets/pulls/7/reviews?per_page=100' ]) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(3) }) it('retains the successful REST source when GraphQL and the other REST source fail', async () => { @@ -301,4 +308,108 @@ describe('PR conversation request reuse', () => { }) expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) }) + it('pages independent sources and nested replies without rereading completed sources', async () => { + const thread = { + id: 'T1', + isResolved: true, + line: 4, + startLine: null, + originalLine: 4, + originalStartLine: null, + rootHunk: { nodes: [{ diffHunk: '@@ -1 +1 @@\n-old\n+new' }] }, + comments: { + nodes: [{ ...comment, id: 'ROOT', databaseId: 11, path: 'a.ts' }], + pageInfo: { hasNextPage: true, endCursor: 'reply-1' } + } + } + ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args.includes('threadId=T1')) { + return { + stdout: JSON.stringify({ + data: { + node: { + ...thread, + comments: { + nodes: [{ ...comment, id: 'REPLY', databaseId: 12, body: 'Reply', path: 'a.ts' }], + pageInfo: { hasNextPage: false, endCursor: null } + } + } + } + }) + } + } + if (args.includes('cursor=comment-1')) { + return response({ + comments: { nodes: [{ ...comment, id: 'IC_13', databaseId: 13, body: 'Newest' }] } + }) + } + return response({ + comments: { nodes: [comment], pageInfo: { hasNextPage: true, endCursor: 'comment-1' } }, + reviews: { nodes: [] }, + reviewThreads: { nodes: [thread] } + }) + }) + const result = await getPRComments('/repo', 7, { ...options, noCache: true }) + expect(result.map((c) => c.id)).toEqual([10, 13, 11, 12]) + expect(result.find((c) => c.id === 11)).toMatchObject({ + threadId: 'T1', + isResolved: true, + path: 'a.ts', + line: 4, + diffHunk: '-old\n+new' + }) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(3) + const continuation = ghExecFileAsyncMock.mock.calls[1][0].join(' ') + expect(continuation).not.toContain('reviewThreads(') + expect(continuation).not.toContain('reviews(') + }) + + it.each(['failure', 'repeated cursor'])( + 'rejects an incomplete conversation after %s', + async (mode) => { + const first = response({ + comments: { nodes: [comment], pageInfo: { hasNextPage: true, endCursor: 'same' } }, + reviews: { nodes: [] }, + reviewThreads: { nodes: [] } + }) + ghExecFileAsyncMock.mockResolvedValueOnce(first) + if (mode === 'failure') { + ghExecFileAsyncMock.mockRejectedValueOnce(new Error('offline')) + } else { + ghExecFileAsyncMock.mockResolvedValueOnce(first) + } + await expect(getPRComments('/repo', 7, { ...options, noCache: true })).rejects.toThrow( + /pagination|cursor/ + ) + } + ) + + it('pages raw REST review rows even when the first 100 bodies are hidden', async () => { + const review = (id: number, body: string) => ({ + id, + body, + user: null, + submitted_at: '2026-04-01T00:00:00Z', + html_url: 'https://example.test/review' + }) + ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args.includes('graphql')) { + return response({ comments: { nodes: [] }, reviews: null, reviewThreads: { nodes: [] } }) + } + if (args.includes('user')) { + return { stdout: 'me' } + } + return { + stdout: JSON.stringify( + args.at(-1)?.includes('&page=2') + ? [review(101, 'Latest summary')] + : Array.from({ length: 100 }, (_, i) => review(i, '')) + ) + } + }) + await expect(getPRComments('/repo', 7, { ...options, noCache: true })).resolves.toMatchObject([ + { id: 101, body: 'Latest summary' } + ]) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(4) + }) }) diff --git a/src/main/github/client-pr-rest-revalidation.test.ts b/src/main/github/client-pr-rest-revalidation.test.ts index 217346571d4..debd54ff22a 100644 --- a/src/main/github/client-pr-rest-revalidation.test.ts +++ b/src/main/github/client-pr-rest-revalidation.test.ts @@ -37,6 +37,7 @@ vi.mock('./github-api-repository', async (importOriginal) => ) ) +import { getFallbackPRListForBranch, getRestPRForBranch } from './client/lookup/pr-branch-lookup' import { getPRForBranchOutcome } from './client/lookup/pr-for-branch-outcome' import { resetPRForBranchMocks } from './client-test-harness' @@ -70,4 +71,56 @@ describe('PR lookup conditional REST reads', () => { ]) expect(noteRateLimitSpendMock.mock.calls).toEqual([['core']]) }) + it('revalidates both mixed and active discovery responses before falling back to history', async () => { + const repo = { owner: 'acme', repo: 'widgets', host: 'github.com' } + const old = Array.from({ length: 10 }, (_, i) => ({ + number: i + 1, + state: 'closed', + title: 'Old', + head: { ref: 'feature' } + })) + const open = { number: 11, state: 'open', title: 'Active', head: { ref: 'feature' } } + const http = (data: unknown, etag: string) => ({ + stdout: `HTTP/2.0 200 OK\nEtag: "${etag}"\r\n\r\n${JSON.stringify(data)}` + }) + ghExecFileAsyncMock + .mockResolvedValueOnce(http(old, 'recent')) + .mockResolvedValueOnce(http([open], 'active')) + .mockRejectedValueOnce( + Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' }) + ) + .mockRejectedValueOnce( + Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' }) + ) + await expect( + getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' }) + ).resolves.toMatchObject({ number: 11 }) + await expect( + getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' }) + ).resolves.toMatchObject({ number: 11 }) + expect(ghExecFileAsyncMock.mock.calls[2][0]).toContain('If-None-Match: "recent"') + expect(ghExecFileAsyncMock.mock.calls[3][0]).toContain('If-None-Match: "active"') + }) + it('uses the same saturated-page rule for the CLI fallback', async () => { + ghExecFileAsyncMock + .mockResolvedValueOnce({ + stdout: JSON.stringify( + Array.from({ length: 10 }, (_, i) => ({ number: i + 1, state: 'CLOSED' })) + ) + }) + .mockResolvedValueOnce({ stdout: '[{"number":11,"state":"OPEN"}]' }) + await expect( + getFallbackPRListForBranch( + { owner: 'acme', repo: 'widgets', host: 'github.com' }, + 'feature', + { cwd: '/repo' } + ) + ).resolves.toMatchObject({ number: 11 }) + expect(ghExecFileAsyncMock.mock.calls[0][0]).toEqual( + expect.arrayContaining(['--state', 'all', '--limit', '10']) + ) + expect(ghExecFileAsyncMock.mock.calls[1][0]).toEqual( + expect.arrayContaining(['--state', 'open', '--limit', '1']) + ) + }) }) diff --git a/src/main/github/client/fetch/get-pr-comments.ts b/src/main/github/client/fetch/get-pr-comments.ts index be44913966c..5caf7b6320a 100644 --- a/src/main/github/client/fetch/get-pr-comments.ts +++ b/src/main/github/client/fetch/get-pr-comments.ts @@ -9,7 +9,12 @@ import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../gith import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../rate-limit' import { assertRateLimitBudget } from './../lookup/pr-lookup-rate-limit' import { REVIEW_THREADS_QUERY } from './pr-review-threads-query' -import { parsePRConversationResponse, parseRestPRComments } from './pr-conversation-response' +import type { parsePRConversationResponse } from './pr-conversation-response' +import { parseRestPRCommentPage } from './pr-conversation-response' +import { + readCompletePRConversation, + IncompletePRConversationError +} from './pr-conversation-pagination' import { readViewerLogin } from './authenticated-viewer' /** Combine conversation comments, review summaries and GraphQL threads with resolution metadata. */ async function readPRComments( @@ -68,31 +73,106 @@ async function readPRComments( let conversation: ReturnType = { reviewComments: [] } if (threadsResult) { try { - conversation = parsePRConversationResponse(threadsResult.stdout) - } catch { + conversation = await readCompletePRConversation( + threadsResult.stdout, + async (query, variables) => { + await assertRateLimitBudget('graphql', ownerRepo, ghOptions) + noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions) + const args = ['api', 'graphql', '-f', `query=${query}`] + if (!('threadId' in variables)) { + args.push( + '-f', + `owner=${ownerRepo.owner}`, + '-f', + `repo=${ownerRepo.repo}`, + '-F', + `pr=${prNumber}` + ) + } + for (const [key, value] of Object.entries(variables)) { + args.push('-f', `${key}=${value}`) + } + try { + return (await ghExecFileAsync(args, ghOptions)).stdout + } catch (error) { + const { stdout } = extractExecError(error) + if (stdout) { + return stdout + } + throw error + } + } + ) + } catch (error) { + if (error instanceof IncompletePRConversationError) { + throw error + } console.warn('Invalid review threads response; falling back to REST') } } const { issueComments, reviewSummaries, reviewComments } = conversation // REST has no viewerDidAuthor, so conversation comments match the reading account's login instead. + let restViewer: Promise | undefined const readRestSource = async (endpoint: string, reviews: boolean): Promise => { await assertRateLimitBudget('core', ownerRepo, ghOptions).catch((error: unknown) => { restBudgetFailed = true throw error }) + const comments: PRComment[] = [] + const ids = new Set() + const rawIds = new Set() + let page = 1 try { - noteRepositoryRateLimitSpend(ownerRepo, 'core', reviews ? 1 : 2, ghOptions) - const [{ stdout }, viewerLogin] = await Promise.all([ - ghExecFileAsync(['api', '-H', GITHUB_BODY_MEDIA_TYPE, endpoint], ghOptions), - reviews ? null : readViewerLogin(ghOptions) - ]) - return parseRestPRComments(stdout, reviews, viewerLogin) + while (true) { + if (page > 1) { + await assertRateLimitBudget('core', ownerRepo, ghOptions) + } + const needsViewer = !restViewer + restViewer ??= readViewerLogin(ghOptions) + noteRepositoryRateLimitSpend(ownerRepo, 'core', needsViewer ? 2 : 1, ghOptions) + const [{ stdout }, viewer] = await Promise.all([ + ghExecFileAsync( + [ + 'api', + '-H', + GITHUB_BODY_MEDIA_TYPE, + page === 1 ? endpoint : `${endpoint}&page=${page}` + ], + ghOptions + ), + restViewer + ]) + const result = parseRestPRCommentPage(stdout, reviews, viewer) + const advanced = result.rawIds.some((id) => !rawIds.has(id)) + for (const id of result.rawIds) { + rawIds.add(id) + } + for (const comment of result.comments) { + if (!ids.has(comment.id)) { + ids.add(comment.id) + comments.push(comment) + } + } + if (!result.hasMore) { + return comments + } + if (!advanced) { + throw new Error('GitHub REST conversation page did not advance') + } + page += 1 + } } catch (error) { + if (page > 1) { + throw new IncompletePRConversationError('GitHub REST conversation pagination failed', { + cause: error + }) + } console.warn('Failed to fetch PR conversation fallback:', extractExecError(error).stderr) return [] } } + const [issueResult, reviewsResult] = await Promise.all([ issueComments === undefined ? readRestSource(`${base}/issues/${prNumber}/comments?per_page=100`, false) @@ -106,8 +186,10 @@ async function readPRComments( ...reviewComments, ...(reviewSummaries ?? reviewsResult ?? []) ] - all.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()) return all + .map((comment) => ({ comment, time: Date.parse(comment.createdAt) })) + .sort((a, b) => a.time - b.time) + .map(({ comment }) => comment) } // Legacy local fallback returns issue-level comments only. @@ -135,7 +217,7 @@ async function readPRComments( ...(c.viewerDidAuthor === true ? { viewerDidAuthor: true } : {}) })) } catch (err) { - if (restBudgetFailed) { + if (restBudgetFailed || err instanceof IncompletePRConversationError) { throw err } console.warn('getPRComments failed:', err) diff --git a/src/main/github/client/fetch/pr-conversation-pagination.ts b/src/main/github/client/fetch/pr-conversation-pagination.ts new file mode 100644 index 00000000000..66b46051ef8 --- /dev/null +++ b/src/main/github/client/fetch/pr-conversation-pagination.ts @@ -0,0 +1,111 @@ +import { + mapPRConversationSources, + parsePRConversationSources, + parsePRReviewThreadResponse +} from './pr-conversation-response' +import { + reviewConversationQuery, + REVIEW_THREAD_REPLIES_QUERY, + type PRConversationSource +} from './pr-review-threads-query' + +export class IncompletePRConversationError extends Error {} + +type PageInfo = { hasNextPage: boolean; endCursor: string | null } | undefined + +function nextCursor(info: PageInfo, seen: Set): string | null { + if (!info) { + throw new IncompletePRConversationError('Missing GitHub conversation page information') + } + if (!info.hasNextPage) { + return null + } + if (!info.endCursor || seen.has(info.endCursor)) { + throw new IncompletePRConversationError('GitHub conversation cursor did not advance') + } + seen.add(info.endCursor) + return info.endCursor +} + +function appendNodes( + target: T[], + nodes: T[], + ids: Set +): void { + for (const node of nodes) { + if (node && !ids.has(node.id)) { + ids.add(node.id) + target.push(node) + } + } +} + +/** Complete independent sources once, then each unfinished thread, before normalizing/sorting. */ +export async function readCompletePRConversation( + initial: string, + read: (query: string, variables: Record) => Promise +): Promise> { + const sources = parsePRConversationSources(initial) + try { + const readSource = async (name: PRConversationSource, cursor: string) => + parsePRConversationSources(await read(reviewConversationQuery(name), { cursor }), name) + await finishSource( + sources.comments, + async (cursor) => (await readSource('comments', cursor)).comments + ) + await finishSource( + sources.reviews, + async (cursor) => (await readSource('reviews', cursor)).reviews + ) + await finishSource( + sources.reviewThreads, + async (cursor) => (await readSource('reviewThreads', cursor)).reviewThreads + ) + for (const thread of sources.reviewThreads?.nodes ?? []) { + if (!thread) { + continue + } + const seen = new Set() + const ids = new Set(thread.comments.nodes.flatMap((node) => (node ? [node.id] : []))) + let cursor = nextCursor(thread.comments.pageInfo, seen) + while (cursor) { + const page = parsePRReviewThreadResponse( + await read(REVIEW_THREAD_REPLIES_QUERY, { threadId: thread.id, cursor }) + ) + if (page.id !== thread.id) { + throw new Error('Unexpected GitHub review thread') + } + appendNodes(thread.comments.nodes, page.comments.nodes, ids) + cursor = nextCursor(page.comments.pageInfo, seen) + } + } + return mapPRConversationSources(sources) + } catch (cause) { + if (cause instanceof IncompletePRConversationError) { + throw cause + } + throw new IncompletePRConversationError('GitHub conversation pagination failed', { cause }) + } +} + +async function finishSource( + connection: { nodes: T[]; pageInfo?: Exclude } | undefined, + read: ( + cursor: string + ) => Promise<{ nodes: T[]; pageInfo?: Exclude } | undefined> +): Promise { + if (!connection) { + return + } + const seen = new Set() + const ids = new Set(connection.nodes.flatMap((node) => (node ? [node.id] : []))) + let cursor = nextCursor(connection.pageInfo, seen) + while (cursor) { + const page = await read(cursor) + if (!page) { + throw new Error('Incomplete GitHub conversation source') + } + appendNodes(connection.nodes, page.nodes, ids) + cursor = nextCursor(page.pageInfo, seen) + } +} diff --git a/src/main/github/client/fetch/pr-conversation-response.ts b/src/main/github/client/fetch/pr-conversation-response.ts index 1593a486f82..4dd0a251d2e 100644 --- a/src/main/github/client/fetch/pr-conversation-response.ts +++ b/src/main/github/client/fetch/pr-conversation-response.ts @@ -30,30 +30,32 @@ const commentSchema = z.object({ ) .nullish() }) -const commentConnection = z.object({ nodes: z.array(commentSchema.nullable()) }) -const threadConnection = z.object({ - nodes: z.array( - z - .object({ - id: z.string(), - isResolved: z.boolean(), - line: z.number().nullable(), - startLine: z.number().nullable(), - originalLine: z.number().nullable(), - originalStartLine: z.number().nullable(), - diffSide: z.string().nullish().catch(undefined), - // Optional so a failed or trimmed field never drops the thread. - rootHunk: z - .object({ nodes: z.array(z.object({ diffHunk: z.string().nullish() }).nullable()) }) - .nullish() - .catch(undefined), - comments: z.object({ - nodes: z.array(commentSchema.extend({ path: z.string() }).nullable()) - }) - }) - .nullable() - ) +const pageInfo = z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }).optional() +const commentConnection = z.object({ nodes: z.array(commentSchema.nullable()), pageInfo }) +const threadSchema = z.object({ + id: z.string(), + isResolved: z.boolean(), + line: z.number().nullable(), + startLine: z.number().nullable(), + originalLine: z.number().nullable(), + originalStartLine: z.number().nullable(), + diffSide: z.string().nullish().catch(undefined), + rootHunk: z + .object({ nodes: z.array(z.object({ diffHunk: z.string().nullish() }).nullable()) }) + .nullish() + .catch(undefined), + comments: z.object({ + nodes: z.array(commentSchema.extend({ path: z.string() }).nullable()), + pageInfo + }) }) +const threadConnection = z.object({ nodes: z.array(threadSchema.nullable()), pageInfo }) +export type PRConversationSources = { + comments?: z.infer + reviews?: z.infer + reviewThreads?: z.infer +} +export type PRReviewThread = z.infer const envelopeSchema = z.object({ data: z .object({ @@ -121,11 +123,10 @@ function hasVisibleReviewBody(body: string | null | undefined): boolean { return reviewMarkdown.parse(body).children.some(hasVisibleNode) } -export function parsePRConversationResponse(stdout: string): { - issueComments?: PRComment[] - reviewSummaries?: PRComment[] - reviewComments: PRComment[] -} { +export function parsePRConversationSources( + stdout: string, + strictSource?: string +): PRConversationSources { const envelope = envelopeSchema.parse(JSON.parse(stdout)) const errors = removeFailedGitHubBodyHtml(envelope.data, envelope.errors) const pr = envelope.data?.repository?.pullRequest @@ -136,23 +137,56 @@ export function parsePRConversationResponse(stdout: string): { !error.path?.length || !error.path.includes('pullRequest') || error.path[2] === source ) ) + if (strictSource && failed(strictSource)) { + throw new Error('Incomplete GitHub conversation source') + } const comments = commentConnection.safeParse(pr?.comments) const reviews = commentConnection.safeParse(pr?.reviews) const threads = threadConnection.safeParse(pr?.reviewThreads) return { - issueComments: - comments.success && !failed('comments') - ? comments.data.nodes.filter(hasDatabaseId).map(mapGraphQLComment) - : undefined, - reviewSummaries: - reviews.success && !failed('reviews') - ? reviews.data.nodes - .filter(hasDatabaseId) - .filter((c) => hasVisibleReviewBody(c.body)) - .map(mapGraphQLComment) - : undefined, - reviewComments: threads.success - ? threads.data.nodes.flatMap((thread) => + ...(comments.success && !failed('comments') ? { comments: comments.data } : {}), + ...(reviews.success && !failed('reviews') ? { reviews: reviews.data } : {}), + ...(threads.success ? { reviewThreads: threads.data } : {}) + } +} + +export function parsePRReviewThreadResponse(stdout: string): PRReviewThread { + const envelope = z + .object({ data: z.object({ node: z.unknown() }), errors: envelopeSchema.shape.errors }) + .parse(JSON.parse(stdout)) + const errors = removeFailedGitHubBodyHtml(envelope.data, envelope.errors) + if (errors?.length) { + throw new Error('Incomplete GitHub review thread replies') + } + return threadSchema.parse(envelope.data.node) +} + +export function parsePRConversationResponse(stdout: string): { + issueComments?: PRComment[] + reviewSummaries?: PRComment[] + reviewComments: PRComment[] +} { + return mapPRConversationSources(parsePRConversationSources(stdout)) +} + +export function mapPRConversationSources(sources: PRConversationSources): { + issueComments?: PRComment[] + reviewSummaries?: PRComment[] + reviewComments: PRComment[] +} { + const { comments, reviews, reviewThreads: threads } = sources + return { + issueComments: comments + ? comments.nodes.filter(hasDatabaseId).map(mapGraphQLComment) + : undefined, + reviewSummaries: reviews + ? reviews.nodes + .filter(hasDatabaseId) + .filter((c) => hasVisibleReviewBody(c.body)) + .map(mapGraphQLComment) + : undefined, + reviewComments: threads + ? threads.nodes.flatMap((thread) => thread ? thread.comments.nodes.filter(hasDatabaseId).map((c) => Object.assign(mapGraphQLComment(c), { @@ -193,14 +227,13 @@ const restCommentSchema = z.object({ html_url: z.string() }) -export function parseRestPRComments( +export function parseRestPRCommentPage( stdout: string, reviews: boolean, viewerLogin: string | null -): PRComment[] { - return z - .array(restCommentSchema) - .parse(JSON.parse(stdout)) +): { comments: PRComment[]; rawIds: number[]; hasMore: boolean } { + const rows = z.array(restCommentSchema).parse(JSON.parse(stdout)) + const comments = rows .filter((c) => !reviews || hasVisibleReviewBody(c.body)) .map((c) => ({ id: c.id, @@ -213,4 +246,13 @@ export function parseRestPRComments( isBot: c.user?.type === 'Bot', ...viewerAuthorship(c.user?.login, viewerLogin) })) + return { comments, rawIds: rows.map((row) => row.id), hasMore: rows.length >= 100 } +} + +export function parseRestPRComments( + stdout: string, + reviews: boolean, + viewerLogin: string | null +): PRComment[] { + return parseRestPRCommentPage(stdout, reviews, viewerLogin).comments } diff --git a/src/main/github/client/fetch/pr-review-threads-query.ts b/src/main/github/client/fetch/pr-review-threads-query.ts index 0e608c43974..32af905f93e 100644 --- a/src/main/github/client/fetch/pr-review-threads-query.ts +++ b/src/main/github/client/fetch/pr-review-threads-query.ts @@ -1,82 +1,39 @@ -// REST review comments omit thread IDs and resolution status; fetch them through GraphQL. -export const REVIEW_THREADS_QUERY = ` -query($owner: String!, $repo: String!, $pr: Int!) { - repository(owner: $owner, name: $repo) { - pullRequest(number: $pr) { - reviewThreads(first: 100) { - nodes { - id - isResolved - line - startLine - originalLine - originalStartLine - diffSide - rootHunk: comments(first: 1) { - nodes { - diffHunk - } - } - comments(first: 100) { - nodes { - id - databaseId - author { __typename login avatarUrl(size: 48) } - body - bodyHTML - createdAt - url - viewerDidAuthor - path - reactionGroups { - content - viewerHasReacted - reactors { - totalCount - } - } - } - } - } - } - comments(first: 100) { - nodes { - id - databaseId - author { __typename login avatarUrl(size: 48) } - body - bodyHTML - createdAt - url - viewerDidAuthor - reactionGroups { - content - viewerHasReacted - reactors { - totalCount - } - } - } - } - reviews(first: 100) { - nodes { - id - databaseId - author { __typename login avatarUrl(size: 48) } - body - bodyHTML - createdAt - submittedAt - url - reactionGroups { - content - viewerHasReacted - reactors { - totalCount - } - } - } - } +const PAGE_INFO = 'pageInfo { hasNextPage endCursor }' +const COMMENT_FIELDS = ` + id databaseId author { __typename login avatarUrl(size: 48) } + body bodyHTML createdAt url viewerDidAuthor + reactionGroups { content viewerHasReacted reactors { totalCount } } +` +const THREAD_FIELDS = ` + id isResolved line startLine originalLine originalStartLine diffSide + rootHunk: comments(first: 1) { nodes { diffHunk } } + comments(first: 100) { ${PAGE_INFO} nodes { ${COMMENT_FIELDS} path } } +` +export type PRConversationSource = 'comments' | 'reviews' | 'reviewThreads' + +export function reviewConversationQuery(source?: PRConversationSource): string { + const connection = (name: PRConversationSource): string => { + if (source && name !== source) { + return '' } + const fields = + name === 'reviewThreads' + ? THREAD_FIELDS + : `${COMMENT_FIELDS}${name === 'reviews' ? ' submittedAt' : ''}` + return `${name}(first: 100${source ? ', after: $cursor' : ''}) { ${PAGE_INFO} nodes { ${fields} } }` } + return `query($owner: String!, $repo: String!, $pr: Int!${source ? ', $cursor: String!' : ''}) { + repository(owner: $owner, name: $repo) { pullRequest(number: $pr) { + ${connection('reviewThreads')} ${connection('comments')} ${connection('reviews')} + } } + }` +} + +export const REVIEW_THREADS_QUERY = reviewConversationQuery() +export const REVIEW_THREAD_REPLIES_QUERY = ` +query($threadId: ID!, $cursor: String!) { + node(id: $threadId) { ... on PullRequestReviewThread { + id isResolved line startLine originalLine originalStartLine diffSide + comments(first: 100, after: $cursor) { ${PAGE_INFO} nodes { ${COMMENT_FIELDS} path } } + } } }` diff --git a/src/main/github/client/lookup/pr-branch-lookup.ts b/src/main/github/client/lookup/pr-branch-lookup.ts index 547a50977ae..c77460698a7 100644 --- a/src/main/github/client/lookup/pr-branch-lookup.ts +++ b/src/main/github/client/lookup/pr-branch-lookup.ts @@ -1,3 +1,5 @@ +import { assertRateLimitBudget } from './pr-lookup-rate-limit' +import { selectBranchReview } from '../../../source-control/branch-review-selection' import { ghExecFileAsync } from '../../gh-utils' import type { OwnerRepo, ghRepoExecOptions } from '../../gh-utils' import { @@ -24,12 +26,20 @@ import { revalidateGitHubRestJson } from '../../github-rest-revalidation' import { noteRepositoryRateLimitSpend } from '../../rate-limit' import { ownerRepoFromPullRequestUrl } from '../github-exec-scope' -// Why: GitHub lists a branch's PRs newest first, so with a page of one a closed PR opened after -// the live one wins. Fetch a page and prefer the open PR; fall back to the newest one. const BRANCH_PR_LOOKUP_PAGE_SIZE = 10 -function preferOpenPullRequest(list: T[]): T | undefined { - return list.find((pr) => pr.state.toLowerCase() === 'open') ?? list[0] +function parseBranchList(stdout: string): T[] { + const parsed: unknown = JSON.parse(stdout) + if ( + !Array.isArray(parsed) || + !parsed.every( + (row) => + row && typeof row.state === 'string' && Number.isInteger(row.number) && row.number > 0 + ) + ) { + throw new Error('Invalid branch review list') + } + return parsed } export async function getRestPRForBranch( @@ -39,13 +49,20 @@ export async function getRestPRForBranch( ghOptions: ReturnType ): Promise { const head = encodeURIComponent(`${headOwner}:${branchName}`) - const stdout = await revalidateGitHubRestJson( - prRepo, - `repos/${prRepo.owner}/${prRepo.repo}/pulls?head=${head}&state=all&per_page=${BRANCH_PR_LOOKUP_PAGE_SIZE}`, - ghOptions - ) - const list = JSON.parse(stdout) as RestPullRequest[] - const pr = preferOpenPullRequest(list) + const read = async (state: 'all' | 'open', limit: number): Promise => + parseBranchList( + await revalidateGitHubRestJson( + prRepo, + `repos/${prRepo.owner}/${prRepo.repo}/pulls?head=${head}&state=${state}&per_page=${limit}`, + ghOptions + ) + ) + const pr = await selectBranchReview({ + readRecent: () => read('all', BRANCH_PR_LOOKUP_PAGE_SIZE), + readActive: async () => (await read('open', 1))[0] ?? null, + isActive: (row) => row.state.toLowerCase() === 'open', + pageSize: BRANCH_PR_LOOKUP_PAGE_SIZE + }) return pr ? mapRestPullRequest(pr) : null } @@ -54,26 +71,34 @@ export async function getFallbackPRListForBranch( branchName: string, ghOptions: ReturnType ): Promise { - noteRepositoryRateLimitSpend(prRepo, 'graphql', 1, ghOptions) - const { stdout } = await ghExecFileAsync( - [ - 'pr', - 'list', - '--repo', - `${prRepo.owner}/${prRepo.repo}`, - '--head', - branchName, - '--state', - 'all', - '--limit', - String(BRANCH_PR_LOOKUP_PAGE_SIZE), - '--json', - PR_BRANCH_LIST_JSON_FIELDS - ], - { ...ghOptions, ...githubHostExecOptions(prRepo) } - ) - const list = JSON.parse(stdout) as PullRequestLookupData[] - const pr = preferOpenPullRequest(list) + const read = async (state: 'all' | 'open', limit: number): Promise => { + await assertRateLimitBudget('graphql', prRepo, ghOptions) + noteRepositoryRateLimitSpend(prRepo, 'graphql', 1, ghOptions) + const { stdout } = await ghExecFileAsync( + [ + 'pr', + 'list', + '--repo', + `${prRepo.owner}/${prRepo.repo}`, + '--head', + branchName, + '--state', + state, + '--limit', + String(limit), + '--json', + PR_BRANCH_LIST_JSON_FIELDS + ], + { ...ghOptions, ...githubHostExecOptions(prRepo) } + ) + return parseBranchList(stdout) + } + const pr = await selectBranchReview({ + readRecent: () => read('all', BRANCH_PR_LOOKUP_PAGE_SIZE), + readActive: async () => (await read('open', 1))[0] ?? null, + isActive: (row) => row.state.toLowerCase() === 'open', + pageSize: BRANCH_PR_LOOKUP_PAGE_SIZE + }) // Branch lists paginate PRs, not their nested check contexts. return pr ? { ...pr, statusCheckRollup: [], checksUnavailable: true } : null } diff --git a/src/main/github/client/lookup/pull-request-lookup-data.ts b/src/main/github/client/lookup/pull-request-lookup-data.ts index 1ac916c7ce9..0c39f4c22a7 100644 --- a/src/main/github/client/lookup/pull-request-lookup-data.ts +++ b/src/main/github/client/lookup/pull-request-lookup-data.ts @@ -1,3 +1,5 @@ +import { readCurrentReviewHead } from '../../../source-control/review-current-head' +import { shouldHideMergedImplicitReview } from '../../../source-control/branch-review-selection' import type { GitHubOwnerRepo, GitHubPRMergeMethodSettings, @@ -15,9 +17,7 @@ import { normalizeReviewDecision, isAutoMergeEnabled } from './../map/work-item-field-coercion' -import { requireReachableGitRoute } from '../../../providers/execution-host-provider-dispatch' import { ownerRepoFromPullRequestUrl, sameOwnerRepo } from '../github-exec-scope' -import { getConnectionExecutionHostId } from '../../../../shared/execution-host' import { githubRepositoryWebHost } from '../../github-repository-host' export type PullRequestLookupData = { number: number @@ -226,11 +226,14 @@ export function shouldHideMergedImplicitPR( linkedPRNumber: number | null | undefined, currentHeadOid: string | null ): boolean { - if (!data || !isMergedImplicitPR(data, linkedPRNumber)) { - return false - } - // Preserve historical merged reviews only when their head matches the current checkout. - return !currentHeadOid || data.headRefOid !== currentHeadOid + return data + ? shouldHideMergedImplicitReview( + mapPRState(data.state, data.isDraft), + linkedPRNumber, + data.headRefOid, + currentHeadOid + ) + : false } export async function linkedMergedPRDivergedHeadOid( @@ -267,15 +270,5 @@ export async function getCurrentHeadOid( connectionId?: string | null, localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {} ): Promise { - requireReachableGitRoute(getConnectionExecutionHostId(connectionId)) - try { - const result = await gitExecFileAsync(['rev-parse', 'HEAD'], { - cwd: repoPath, - ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}), - ...(localGitOptions.admissionTier ? { admissionTier: localGitOptions.admissionTier } : {}) - }) - return result.stdout.trim() || null - } catch { - return null - } + return readCurrentReviewHead(repoPath, connectionId, localGitOptions, gitExecFileAsync) } diff --git a/src/main/github/client/lookup/tracked-upstream-branch.ts b/src/main/github/client/lookup/tracked-upstream-branch.ts index 884ba4be3f6..82eaaeee235 100644 --- a/src/main/github/client/lookup/tracked-upstream-branch.ts +++ b/src/main/github/client/lookup/tracked-upstream-branch.ts @@ -1,3 +1,7 @@ +import { + readGitReviewBranchSources, + type GitReviewBranchSource +} from '../../../../shared/git/remotes/git-review-branch-source' import { gitExecFileAsync } from '../../gh-utils' import { readLocalGitConfigSignature } from '../../local-git-config-signature' import type { GitAdmissionTier } from '../../../git/command-runner/git-exec-options' @@ -11,7 +15,6 @@ import { pruneTrackedUpstreamSnapshotCache, parseTrackedUpstreamBranch, getCacheableTrackedUpstreamSnapshot, - canUseCachedTrackedUpstreamBranch, doesTrackedUpstreamCacheConfigSignatureMatch, getTrackedUpstreamBranchCacheKey, type TrackedUpstreamBranch, @@ -25,87 +28,148 @@ export async function getTrackedUpstreamBranch( connectionId?: string | null, localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {} ): Promise { + const snapshot = await getTrackedUpstreamSnapshot( + repoPath, + branchName, + connectionId, + localGitOptions + ) + return snapshot.upstreamsByBranchName.get(branchName) ?? null +} + +export async function getReviewBranchSource( + repoPath: string, + branchName: string, + connectionId?: string | null, + localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {}, + force = false +): Promise { + const snapshot = await getTrackedUpstreamSnapshot( + repoPath, + branchName, + connectionId, + localGitOptions, + true, + force + ) + const source = snapshot.reviewSources?.get(branchName) + if (snapshot.probeFailed || !source || source instanceof Error) { + throw new Error('Cannot establish the branch review source') + } + return source +} + +async function getTrackedUpstreamSnapshot( + repoPath: string, + branchName: string, + connectionId?: string | null, + localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {}, + includeReviewSources = false, + force = false +): Promise { const cacheKey = getTrackedUpstreamBranchCacheKey(repoPath, connectionId, localGitOptions) - const now = Date.now() + const serves = ( + value: Pick + ): boolean => + value.upstreamsByBranchName.has(branchName) && + (!includeReviewSources || value.reviewSources?.has(branchName) === true) const cached = trackedUpstreamSnapshotCache.get(cacheKey) - if (cached && cached.expiresAt > now) { - const configSignatureMatches = await doesTrackedUpstreamCacheConfigSignatureMatch( + if ( + cached && + !force && + cached.expiresAt > Date.now() && + serves(cached) && + (await doesTrackedUpstreamCacheConfigSignatureMatch( cached, repoPath, connectionId, localGitOptions - ) - if ( - configSignatureMatches && - cached.upstreamsByBranchName.has(branchName) && - canUseCachedTrackedUpstreamBranch(cached, branchName) - ) { - return cached.upstreamsByBranchName.get(branchName) ?? null - } - trackedUpstreamSnapshotCache.delete(cacheKey) + )) + ) { + return { ...cached, cacheable: true, probeFailed: false } } if (cached) { trackedUpstreamSnapshotCache.delete(cacheKey) } - const inFlight = trackedUpstreamSnapshotInFlight.get(cacheKey) - if (inFlight) { + if (inFlight && !force) { const result = await inFlight - if (result.upstreamsByBranchName.has(branchName)) { - return result.upstreamsByBranchName.get(branchName) ?? null + if (serves(result)) { + return result } - // A concurrent snapshot can predate branch creation; reprobe instead of fabricating absence. - const retryInFlight = trackedUpstreamSnapshotInFlight.get(cacheKey) - if (retryInFlight) { - const retryResult = await retryInFlight - return retryResult.upstreamsByBranchName.get(branchName) ?? null + const retry = trackedUpstreamSnapshotInFlight.get(cacheKey) + if (retry && retry !== inFlight) { + const fresh = await retry + if (serves(fresh)) { + return fresh + } } } - - // Share one repo/runtime upstream scan across hundreds of polled branches. - const probeGeneration = beginTrackedUpstreamSnapshotProbe(cacheKey) - const probe = probeTrackedUpstreamSnapshot(repoPath, connectionId, localGitOptions) + const generation = beginTrackedUpstreamSnapshotProbe(cacheKey) + const probe = probeTrackedUpstreamSnapshot( + repoPath, + connectionId, + localGitOptions, + includeReviewSources ? branchName : undefined + ) trackedUpstreamSnapshotInFlight.set(cacheKey, probe) try { const result = await probe - if (result.cacheable && trackedUpstreamSnapshotGenerations.get(cacheKey) === probeGeneration) { + if (result.cacheable && trackedUpstreamSnapshotGenerations.get(cacheKey) === generation) { trackedUpstreamSnapshotCache.set(cacheKey, { ...(result.gitConfigSignature ? { gitConfigSignature: result.gitConfigSignature } : {}), upstreamsByBranchName: getCacheableTrackedUpstreamSnapshot(result.upstreamsByBranchName), + ...(result.reviewSources ? { reviewSources: result.reviewSources } : {}), expiresAt: Date.now() + TRACKED_UPSTREAM_SNAPSHOT_CACHE_TTL_MS }) pruneTrackedUpstreamSnapshotCache(Date.now()) } - if (trackedUpstreamSnapshotGenerations.get(cacheKey) !== probeGeneration) { - const fresherCached = trackedUpstreamSnapshotCache.get(cacheKey) - if (fresherCached?.upstreamsByBranchName.has(branchName)) { - return fresherCached.upstreamsByBranchName.get(branchName) ?? null + if (trackedUpstreamSnapshotGenerations.get(cacheKey) !== generation) { + const fresh = trackedUpstreamSnapshotCache.get(cacheKey) + if (fresh && serves(fresh)) { + return { ...fresh, cacheable: true, probeFailed: false } } } - return result.upstreamsByBranchName.get(branchName) ?? null + return result } finally { if (trackedUpstreamSnapshotInFlight.get(cacheKey) === probe) { trackedUpstreamSnapshotInFlight.delete(cacheKey) } - finishTrackedUpstreamSnapshotProbe(cacheKey, probeGeneration) + finishTrackedUpstreamSnapshotProbe(cacheKey, generation) } } export async function probeTrackedUpstreamSnapshot( repoPath: string, connectionId?: string | null, - localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {} + localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {}, + reviewBranchName?: string ): Promise { const startingGitConfigSignature = await readLocalGitConfigSignature({ repoPath, connectionId: connectionId ?? null, ...localGitOptions }) - const { probeFailed, upstreamsByBranchName } = await probeTrackedUpstreamBranches( + let { probeFailed, upstreamsByBranchName } = await probeTrackedUpstreamBranches( repoPath, connectionId, localGitOptions ) + let reviewSources: Map | undefined + if (reviewBranchName && !probeFailed) { + try { + requireReachableGitRoute(getConnectionExecutionHostId(connectionId)) + if (!upstreamsByBranchName.has(reviewBranchName)) { + upstreamsByBranchName.set(reviewBranchName, null) + } + reviewSources = await readGitReviewBranchSources( + (args) => gitExecFileAsync(args, { cwd: repoPath, ...localGitOptions }), + upstreamsByBranchName.keys() + ) + } catch { + probeFailed = true + } + } const endingGitConfigSignature = await readLocalGitConfigSignature({ repoPath, connectionId: connectionId ?? null, @@ -121,7 +185,8 @@ export async function probeTrackedUpstreamSnapshot( cacheable: !configSignatureChanged && !probeFailed, probeFailed, ...(gitConfigSignature ? { gitConfigSignature } : {}), - upstreamsByBranchName + upstreamsByBranchName, + ...(reviewSources ? { reviewSources } : {}) } } diff --git a/src/main/github/client/lookup/tracked-upstream-cache.ts b/src/main/github/client/lookup/tracked-upstream-cache.ts index 9e2dc28d2ae..7a0f37d06d7 100644 --- a/src/main/github/client/lookup/tracked-upstream-cache.ts +++ b/src/main/github/client/lookup/tracked-upstream-cache.ts @@ -1,3 +1,4 @@ +import type { GitReviewBranchSource } from '../../../../shared/git/remotes/git-review-branch-source' import { splitRemoteBranchName } from '../../../../shared/git/remotes/git-remote-branch-name' import type { OwnerRepo } from '../../gh-utils' import { readLocalGitConfigSignature } from '../../local-git-config-signature' @@ -15,6 +16,7 @@ export type TrackedUpstreamSnapshotCacheEntry = { expiresAt: number gitConfigSignature?: string upstreamsByBranchName: Map + reviewSources?: Map } export type TrackedUpstreamSnapshotProbeResult = { @@ -22,6 +24,7 @@ export type TrackedUpstreamSnapshotProbeResult = { gitConfigSignature?: string probeFailed: boolean upstreamsByBranchName: Map + reviewSources?: Map } export const trackedUpstreamSnapshotCache = new Map() diff --git a/src/main/github/github-read-execution-scope.ts b/src/main/github/github-read-execution-scope.ts index d424feeb7b0..0731cf4ed48 100644 --- a/src/main/github/github-read-execution-scope.ts +++ b/src/main/github/github-read-execution-scope.ts @@ -1,19 +1 @@ -import { createHash } from 'node:crypto' -import type { GitHubRepoExecOptions } from './github-api-repository' - -export function githubReadExecutionScope( - options: GitHubRepoExecOptions, - environment: NodeJS.ProcessEnv = options.env ?? process.env -): string { - const { admissionTier: _admissionTier, ...executionOptions } = options - // gh wrappers and credential selection can depend on cwd and the inherited environment. - return createHash('sha256') - .update( - JSON.stringify([ - executionOptions, - process.cwd(), - Object.entries(environment).sort(([a], [b]) => a.localeCompare(b, 'en')) - ]) - ) - .digest('hex') -} +export { codeHostReadExecutionScope as githubReadExecutionScope } from '../source-control/code-host-read-execution-scope' diff --git a/src/main/github/merged-pr-commit-membership.ts b/src/main/github/merged-pr-commit-membership.ts index 97c1e819090..6432356e33d 100644 --- a/src/main/github/merged-pr-commit-membership.ts +++ b/src/main/github/merged-pr-commit-membership.ts @@ -5,35 +5,18 @@ import { githubHostExecOptions, type GitHubRepoExecOptions } from './github-api- import { githubRepoIdentityKey } from '../../shared/github/repository-identity-key' import type { OwnerRepo } from './github-repository-identity' -// Definitive merged-commit membership is immutable; errors expire sooner so later pushes can resolve unknowns. -const MEMBERSHIP_CACHE_MAX_ENTRIES = 200 -const MEMBERSHIP_DEFINITIVE_TTL_MS = 6 * 60 * 60 * 1000 -const MEMBERSHIP_ERROR_TTL_MS = 5 * 60 * 1000 +import { + MergedReviewMembershipMemo, + type MergedReviewCommitMembership +} from '../source-control/merged-review-membership-memo' + const COMMIT_PULLS_PAGE_SIZE = 100 -// Full pages through the cap cannot prove absence; keep pathological commit fan-out unknown. const COMMIT_PULLS_MAX_PAGES = 5 - -export type MergedPRCommitMembership = 'contained' | 'not-contained' | 'unknown' - -const membershipCache = new Map() - -function pruneMergedPRCommitMembershipCache(now = Date.now()): void { - for (const [cacheKey, cached] of membershipCache) { - if (cached.expiresAt <= now) { - membershipCache.delete(cacheKey) - } - } - while (membershipCache.size > MEMBERSHIP_CACHE_MAX_ENTRIES) { - const oldestKey = membershipCache.keys().next().value - if (oldestKey === undefined) { - break - } - membershipCache.delete(oldestKey) - } -} +export type MergedPRCommitMembership = MergedReviewCommitMembership +const membershipMemo = new MergedReviewMembershipMemo() export function resetMergedPRCommitMembershipCacheForTest(): void { - membershipCache.clear() + membershipMemo.clear() } /** Check PR-history membership rather than branch-name reuse; failures return unknown. */ @@ -51,76 +34,52 @@ export async function isCommitPartOfMergedPR(args: { const repo = args.ownerRepo.repo const ghOptions = { ...args.ghOptions, ...githubHostExecOptions(args.ownerRepo) } const cacheKey = `${githubReadExecutionScope(ghOptions)}\0${githubRepoIdentityKey(args.ownerRepo)}#${args.prNumber}@${oid}` - const now = Date.now() - pruneMergedPRCommitMembershipCache(now) - const cached = membershipCache.get(cacheKey) - if (cached && cached.expiresAt > now) { - return cached.value + const cached = membershipMemo.peek(cacheKey) + if (cached !== undefined) { + return cached } // An unrun probe cannot justify clearing a durable linked PR. if (repositoryRateLimitGuard(args.ownerRepo, 'core', ghOptions).blocked) { return 'unknown' } - try { - // Paginate until found or a short page proves absence; a full final page leaves membership unknown. - for (let page = 1; page <= COMMIT_PULLS_MAX_PAGES; page += 1) { - if (page > 1 && repositoryRateLimitGuard(args.ownerRepo, 'core', ghOptions).blocked) { - membershipCache.set(cacheKey, { - value: 'unknown', - expiresAt: now + MEMBERSHIP_ERROR_TTL_MS - }) - return 'unknown' - } - noteRepositoryRateLimitSpend(args.ownerRepo, 'core', 1, ghOptions) - const { stdout } = await ghExecFileAsync( - [ - 'api', - `repos/${owner}/${repo}/commits/${oid}/pulls?per_page=${COMMIT_PULLS_PAGE_SIZE}&page=${page}` - ], - ghOptions - ) - const parsed = JSON.parse(stdout) as unknown - // Non-array success is unverified, not evidence that a durable link should be cleared. - if (!Array.isArray(parsed)) { - membershipCache.set(cacheKey, { - value: 'unknown', - expiresAt: now + MEMBERSHIP_ERROR_TTL_MS - }) - return 'unknown' - } - const entries = parsed - const contained = entries.some( - (entry) => - typeof entry === 'object' && - entry !== null && - (entry as { number?: unknown }).number === args.prNumber - ) - if (contained) { - membershipCache.set(cacheKey, { - value: 'contained', - expiresAt: now + MEMBERSHIP_DEFINITIVE_TTL_MS - }) - return 'contained' - } - if (entries.length < COMMIT_PULLS_PAGE_SIZE) { - membershipCache.set(cacheKey, { - value: 'not-contained', - expiresAt: now + MEMBERSHIP_DEFINITIVE_TTL_MS - }) - return 'not-contained' + return membershipMemo.read(cacheKey, async () => { + try { + // Paginate until found or a short page proves absence; a full final page leaves membership unknown. + for (let page = 1; page <= COMMIT_PULLS_MAX_PAGES; page += 1) { + if (page > 1 && repositoryRateLimitGuard(args.ownerRepo, 'core', ghOptions).blocked) { + return 'unknown' + } + noteRepositoryRateLimitSpend(args.ownerRepo, 'core', 1, ghOptions) + const { stdout } = await ghExecFileAsync( + [ + 'api', + `repos/${owner}/${repo}/commits/${oid}/pulls?per_page=${COMMIT_PULLS_PAGE_SIZE}&page=${page}` + ], + ghOptions + ) + const parsed = JSON.parse(stdout) as unknown + // Non-array success is unverified, not evidence that a durable link should be cleared. + if (!Array.isArray(parsed)) { + return 'unknown' + } + const entries = parsed + const contained = entries.some( + (entry) => + typeof entry === 'object' && + entry !== null && + (entry as { number?: unknown }).number === args.prNumber + ) + if (contained) { + return 'contained' + } + if (entries.length < COMMIT_PULLS_PAGE_SIZE) { + return 'not-contained' + } } + return 'unknown' + } catch { + // A local commit can become queryable after push; preserve links until verification succeeds. + return 'unknown' } - membershipCache.set(cacheKey, { - value: 'unknown', - expiresAt: now + MEMBERSHIP_ERROR_TTL_MS - }) - return 'unknown' - } catch { - // A local commit can become queryable after push; preserve links until verification succeeds. - membershipCache.set(cacheKey, { - value: 'unknown', - expiresAt: now + MEMBERSHIP_ERROR_TTL_MS - }) - return 'unknown' - } + }) } diff --git a/src/main/gitlab/branch-review-discovery.test.ts b/src/main/gitlab/branch-review-discovery.test.ts new file mode 100644 index 00000000000..faf56c500ef --- /dev/null +++ b/src/main/gitlab/branch-review-discovery.test.ts @@ -0,0 +1,93 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import type * as GlabApiResponse from './glab-api-response' +const { read, pages } = vi.hoisted(() => ({ read: vi.fn(), pages: vi.fn() })) +vi.mock('./gl-utils', async () => ({ + ...(await vi.importActual('./glab-api-response')), + glabExecFileAsync: read, + glabApiWithHeaders: pages, + glabHostnameArgs: () => [], + glabRepoExecOptions: () => ({}) +})) +import { createGitLabBranchDiscovery } from './branch-review-discovery' +const args = { + repoPath: '/repo', + project: { host: 'gitlab.com', path: 'g/p' }, + sourceProjectId: 1, + localGitOptions: {} +} +const row = (iid: number, state = 'merged', source = 1) => ({ + iid, + state, + source_project_id: source, + target_project_id: 2, + source_branch: 'feature', + updated_at: `2026-11-01T00:00:${String(iid % 60).padStart(2, '0')}Z` +}) +beforeEach(() => { + read.mockReset() + pages.mockReset() +}) +it('prefers an older active MR and probes both active states behind a full recent page', async () => { + read + .mockResolvedValueOnce({ + stdout: JSON.stringify(Array.from({ length: 10 }, (_, i) => row(i + 1))) + }) + .mockResolvedValueOnce({ stdout: JSON.stringify([row(11, 'opened')]) }) + .mockResolvedValueOnce({ stdout: JSON.stringify([row(12, 'locked')]) }) + await expect(createGitLabBranchDiscovery(args)('feature')).resolves.toMatchObject({ iid: 12 }) + expect(read.mock.calls.map(([a]) => a.at(-1))).toEqual([ + expect.stringContaining('source_project_id=1&state=all&per_page=10'), + expect.stringContaining('source_project_id=1&state=opened&per_page=1'), + expect.stringContaining('source_project_id=1&state=locked&per_page=1') + ]) +}) +it.each(['foreign', 'locked'])( + 'completes the existing branch-filtered endpoint on legacy %s filtering', + async (mode) => { + read.mockResolvedValueOnce({ + stdout: JSON.stringify( + mode === 'foreign' + ? [row(1, 'opened', 8)] + : Array.from({ length: 10 }, (_, i) => row(i + 1)) + ) + }) + if (mode === 'locked') { + read + .mockResolvedValueOnce({ stdout: '[]' }) + .mockRejectedValueOnce({ stderr: 'HTTP 400: state does not have a valid value: locked' }) + } + pages.mockImplementation(async ([endpoint]: string[]) => ({ + body: JSON.stringify( + new URL(endpoint, 'https://gitlab.com').searchParams.get('page') === '1' + ? Array.from({ length: 100 }, (_, i) => row(i + 1, 'opened', 8)) + : [row(101, 'opened')] + ), + headers: { + 'x-next-page': + new URL(endpoint, 'https://gitlab.com').searchParams.get('page') === '1' ? '2' : '' + } + })) + await expect(createGitLabBranchDiscovery(args)('feature')).resolves.toMatchObject({ iid: 101 }) + expect(pages.mock.calls[0][0][0]).toContain('&state=all&per_page=100&page=1') + expect(pages.mock.calls[0][0][0]).not.toContain('source_project_id=') + } +) +it('does not turn an active-probe failure into historical absence', async () => { + read + .mockResolvedValueOnce({ + stdout: JSON.stringify(Array.from({ length: 10 }, (_, i) => row(i + 1))) + }) + .mockRejectedValueOnce(new Error('offline')) + await expect(createGitLabBranchDiscovery(args)('feature')).rejects.toThrow('offline') + expect(pages).not.toHaveBeenCalled() +}) +it('fails a legacy traversal rather than selecting from an incomplete foreign prefix', async () => { + read.mockResolvedValue({ stdout: JSON.stringify([row(1, 'opened', 8)]) }) + pages + .mockResolvedValueOnce({ + body: JSON.stringify(Array.from({ length: 100 }, (_, i) => row(i + 1, 'opened', 8))), + headers: { 'x-next-page': '2' } + }) + .mockRejectedValueOnce(new Error('offline')) + await expect(createGitLabBranchDiscovery(args)('feature')).rejects.toThrow('incomplete') +}) diff --git a/src/main/gitlab/branch-review-discovery.ts b/src/main/gitlab/branch-review-discovery.ts new file mode 100644 index 00000000000..25f7bd0e4eb --- /dev/null +++ b/src/main/gitlab/branch-review-discovery.ts @@ -0,0 +1,143 @@ +import { selectBranchReview } from '../source-control/branch-review-selection' +import { extractExecError } from '../git/exec-error' +import { fetchAllGitLabPages } from './gitlab-paginated-list' +import { isUnsupportedReviewListFilter } from './glab-error-classification' +import { + glabExecFileAsync, + glabHostnameArgs, + glabRepoExecOptions, + parseGlabJsonList, + type LocalGitExecOptions, + type ProjectRef +} from './gl-utils' +import { encodedProject } from './project-path-encoding' + +export type GitLabBranchReview = { + iid: number + state: string + source_project_id: number + target_project_id: number + source_branch: string + updated_at: string +} + +class GitLabReviewFilterUnavailableError extends Error {} + +function validateReviews(rows: unknown[], branch: string): GitLabBranchReview[] { + if ( + !rows.every((row): row is GitLabBranchReview => { + if (!row || typeof row !== 'object') { + return false + } + const data = row as Record + return ( + typeof data.iid === 'number' && + Number.isSafeInteger(data.iid) && + data.iid > 0 && + typeof data.source_project_id === 'number' && + Number.isSafeInteger(data.source_project_id) && + data.source_project_id > 0 && + typeof data.target_project_id === 'number' && + Number.isSafeInteger(data.target_project_id) && + data.target_project_id > 0 && + typeof data.state === 'string' && + ['opened', 'locked', 'closed', 'merged'].includes(data.state) && + data.source_branch === branch && + typeof data.updated_at === 'string' && + Number.isFinite(Date.parse(data.updated_at)) + ) + }) + ) { + throw new Error('Invalid GitLab branch review list') + } + return rows +} + +export function isActiveGitLabReview(review: GitLabBranchReview): boolean { + return review.state === 'opened' || review.state === 'locked' +} + +/** Compatibility observation lasts for this lookup, including its one qualified alternate name. */ +export function createGitLabBranchDiscovery(args: { + repoPath: string + project: ProjectRef + sourceProjectId: number + connectionId?: string | null + localGitOptions: LocalGitExecOptions +}): (branch: string) => Promise { + let completeTraversal = false + const endpoint = `projects/${encodedProject(args.project.path)}/merge_requests` + const ordered = (branch: string) => + `source_branch=${encodeURIComponent(branch)}&order_by=updated_at&sort=desc&with_merge_status_recheck=true` + const readComplete = async (branch: string): Promise => { + const raw = await fetchAllGitLabPages( + args.repoPath, + args.project, + `${endpoint}?${ordered(branch)}&state=all`, + args.connectionId, + args.localGitOptions + ) + const rows = validateReviews(raw, branch).filter( + (row) => row.source_project_id === args.sourceProjectId + ) + return rows.find(isActiveGitLabReview) ?? rows[0] ?? null + } + const read = async ( + branch: string, + state: 'all' | 'opened' | 'locked', + limit: number + ): Promise => { + let stdout: string + try { + ;({ stdout } = await glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(args.project, args.connectionId), + `${endpoint}?${ordered(branch)}&source_project_id=${args.sourceProjectId}&state=${state}&per_page=${limit}` + ], + glabRepoExecOptions(args.repoPath, args.connectionId, args.localGitOptions) + )) + } catch (error) { + const detail = extractExecError(error) + if (isUnsupportedReviewListFilter([detail.stderr, detail.stdout].join('\n'), state)) { + throw new GitLabReviewFilterUnavailableError() + } + throw error + } + const rows = validateReviews(parseGlabJsonList(stdout), branch) + if (rows.some((row) => row.source_project_id !== args.sourceProjectId)) { + throw new GitLabReviewFilterUnavailableError() + } + if (state !== 'all' && rows.some((row) => row.state !== state)) { + throw new Error('Invalid GitLab active review list') + } + return rows + } + return async (branch) => { + if (completeTraversal) { + return readComplete(branch) + } + try { + return await selectBranchReview({ + readRecent: () => read(branch, 'all', 10), + readActive: async () => { + const opened = (await read(branch, 'opened', 1))[0] + const locked = (await read(branch, 'locked', 1))[0] + return ( + [opened, locked] + .filter((row) => row !== undefined) + .sort((a, b) => Date.parse(b.updated_at) - Date.parse(a.updated_at))[0] ?? null + ) + }, + isActive: isActiveGitLabReview, + pageSize: 10 + }) + } catch (error) { + if (!(error instanceof GitLabReviewFilterUnavailableError)) { + throw error + } + completeTraversal = true + return readComplete(branch) + } + } +} diff --git a/src/main/gitlab/branch-review-source.ts b/src/main/gitlab/branch-review-source.ts new file mode 100644 index 00000000000..e5e28028fb0 --- /dev/null +++ b/src/main/gitlab/branch-review-source.ts @@ -0,0 +1,42 @@ +import type { GitReviewBranchSource } from '../../shared/git/remotes/git-review-branch-source' +import { parseGitLabProjectRef, normalizeGitLabHost } from './project-ref-parser' +import { readReviewProjectIdentity } from './review-project-identity' +import type { LocalGitExecOptions, ProjectRef } from './gl-utils' + +export async function resolveReviewSourceProject(args: { + repoPath: string + target: ProjectRef + urls: GitReviewBranchSource['urls'] + connectionId?: string | null + localGitOptions: LocalGitExecOptions + force?: boolean +}): Promise<{ project: ProjectRef; id: number }> { + let source: { project: ProjectRef; id: number } | undefined + const seen = new Set() + for (const url of args.urls) { + const project = parseGitLabProjectRef(url, [args.target.host]) + if (!project || normalizeGitLabHost(project.host) !== normalizeGitLabHost(args.target.host)) { + throw new Error('Review source is not on the target GitLab host') + } + const key = `${project.host}\0${project.path}` + if (seen.has(key)) { + continue + } + seen.add(key) + const identity = await readReviewProjectIdentity( + args.repoPath, + project, + args.connectionId, + args.localGitOptions, + args.force + ) + if (source && source.id !== identity.id) { + throw new Error('Review source has multiple projects') + } + source ??= { project, id: identity.id } + } + if (!source) { + throw new Error('Review source is unavailable') + } + return source +} diff --git a/src/main/gitlab/client-mr-branch-lookup.test.ts b/src/main/gitlab/client-mr-branch-lookup.test.ts index 7303ea89036..bc9abc8e515 100644 --- a/src/main/gitlab/client-mr-branch-lookup.test.ts +++ b/src/main/gitlab/client-mr-branch-lookup.test.ts @@ -11,7 +11,8 @@ const { resolveIssueSourceMock, acquireMock, releaseMock, - gitExecFileAsyncMock + gitExecFileAsyncMock, + reviewSourceMock } = vi.hoisted(() => ({ glabExecFileAsyncMock: vi.fn(), glabApiWithHeadersMock: vi.fn(), @@ -20,7 +21,8 @@ const { resolveIssueSourceMock: vi.fn(), acquireMock: vi.fn(), releaseMock: vi.fn(), - gitExecFileAsyncMock: vi.fn() + gitExecFileAsyncMock: vi.fn(), + reviewSourceMock: vi.fn() })) // Why: the #9171 default-branch guard resolves the repo default branch via @@ -29,6 +31,12 @@ vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) +vi.mock('../github/client/lookup/tracked-upstream-branch', () => ({ + getReviewBranchSource: reviewSourceMock +})) +vi.mock('./branch-review-source', () => ({ + resolveReviewSourceProject: async () => ({ id: 1, project: { host: 'gitlab.com', path: 'g/p' } }) +})) vi.mock('./gl-utils', async () => { const actual = await vi.importActual('./gl-utils') @@ -45,13 +53,20 @@ vi.mock('./gl-utils', async () => { }) import { getMergeRequestForBranch, getMergeRequestForBranchOrThrow } from './client' import { resetGitLabMrMocks } from './client-mr-test-harness' +import { resetMergedMRCommitMembershipForTest } from './merged-mr-commit-membership' type MergeRequestDetail = Parameters[0] function mockBranchLookup(mr: MergeRequestDetail): void { + const identity = { + source_project_id: 1, + target_project_id: 1, + source_branch: 'main', + updated_at: '2026-11-01T00:00:00Z' + } glabExecFileAsyncMock - .mockResolvedValueOnce({ stdout: JSON.stringify([mr]) }) - .mockResolvedValueOnce({ stdout: JSON.stringify(mr) }) + .mockResolvedValueOnce({ stdout: JSON.stringify([{ ...identity, ...mr }]) }) + .mockResolvedValueOnce({ stdout: JSON.stringify({ ...identity, ...mr }) }) } describe('gitlab client — MR operations', () => { @@ -61,6 +76,12 @@ describe('gitlab client — MR operations', () => { }) beforeEach(() => { + resetMergedMRCommitMembershipForTest() + reviewSourceMock.mockReset().mockImplementation(async (_repo: string, branch: string) => ({ + remoteName: 'origin', + urls: ['https://gitlab.com/g/p.git'], + branchName: branch + })) resetGitLabMrMocks({ glabExecFileAsyncMock, glabApiWithHeadersMock, @@ -80,6 +101,10 @@ describe('gitlab client — MR operations', () => { 'reads the failed head pipeline from detail instead of the branch list: %j', async (pipelineFields) => { const detail = { + source_project_id: 1, + target_project_id: 1, + source_branch: 'feature/pipeline', + updated_at: '2026-11-01T00:00:00Z', iid: 5049, title: 'Pipeline regression', state: 'opened', @@ -108,7 +133,17 @@ describe('gitlab client — MR operations', () => { for (const lookup of [getMergeRequestForBranch, getMergeRequestForBranchOrThrow]) { glabExecFileAsyncMock .mockResolvedValueOnce({ - stdout: JSON.stringify([{ iid: 6, title: 'Flaky', state: 'opened' }]) + stdout: JSON.stringify([ + { + iid: 6, + title: 'Flaky', + state: 'opened', + source_project_id: 1, + target_project_id: 1, + source_branch: 'flaky', + updated_at: '2026-11-01T00:00:00Z' + } + ]) }) .mockRejectedValueOnce(new Error('glab: 502')) const result = lookup('/repo', 'flaky') @@ -125,6 +160,100 @@ describe('gitlab client — MR operations', () => { expect(releaseMock).toHaveBeenCalledTimes(3) }) + it('uses a qualified tracked name only after complete local absence and excludes the default branch', async () => { + getProjectRefMock.mockResolvedValue({ host: 'gitlab.com', path: 'g/p' }) + reviewSourceMock.mockResolvedValue({ + remoteName: 'origin', + urls: ['https://gitlab.com/g/p.git'], + branchName: 'wip', + trackedBranchName: 'renamed', + trackedUrls: ['https://gitlab.com/g/p.git'] + }) + const mr = { + iid: 8, + title: 'Renamed', + state: 'opened', + source_project_id: 1, + target_project_id: 1, + source_branch: 'renamed', + updated_at: '2026-11-01T00:00:00Z' + } + glabExecFileAsyncMock + .mockResolvedValueOnce({ stdout: '[]' }) + .mockResolvedValueOnce({ stdout: JSON.stringify([mr]) }) + .mockResolvedValueOnce({ stdout: JSON.stringify(mr) }) + await expect(getMergeRequestForBranchOrThrow('/repo', 'wip')).resolves.toMatchObject({ + number: 8 + }) + expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(3) + reviewSourceMock.mockResolvedValue({ + remoteName: 'origin', + urls: ['https://gitlab.com/g/p.git'], + branchName: 'wip', + trackedBranchName: 'main', + trackedUrls: ['https://gitlab.com/g/p.git'] + }) + glabExecFileAsyncMock + .mockResolvedValueOnce({ stdout: '[]' }) + .mockResolvedValueOnce({ stdout: JSON.stringify([{ ...mr, source_branch: 'main' }]) }) + await expect(getMergeRequestForBranchOrThrow('/repo', 'wip')).resolves.toBeNull() + expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(5) + }) + + it.each([10, 100])( + 'walks immutable membership once across %s admitted provider refreshes', + async (count) => { + getProjectRefMock.mockResolvedValue({ host: 'gitlab.com', path: 'g/p' }) + const head = 'f'.repeat(40) + const mr = { + iid: 8, + title: 'Merged', + state: 'merged', + sha: 'a'.repeat(40), + source_project_id: 1, + target_project_id: 1, + source_branch: 'feature', + updated_at: '2026-11-01T00:00:00Z' + } + glabExecFileAsyncMock.mockImplementation(async (args: string[]) => ({ + stdout: + args.at(-1) === 'user' + ? '{"id":1}' + : JSON.stringify(args.at(-1)?.includes('source_branch=') ? [mr] : mr) + })) + glabApiWithHeadersMock.mockImplementation(async (args: string[]) => { + const page = Number( + new URL(args.at(-1) ?? '', 'https://gitlab.com').searchParams.get('page') + ) + return { + body: JSON.stringify( + Array.from({ length: 100 }, (_, i) => ({ + id: page === 5 && i === 99 ? head : (page * 100 + i).toString(16).padStart(40, '0') + })) + ), + headers: { 'x-next-page': page < 5 ? String(page + 1) : '' } + } + }) + for (let i = 0; i < count; i++) { + await expect( + getMergeRequestForBranchOrThrow('/repo', 'feature', null, null, { + currentHeadOid: head + }) + ).resolves.toMatchObject({ number: 8 }) + } + expect(glabApiWithHeadersMock).toHaveBeenCalledTimes(5) + expect( + glabExecFileAsyncMock.mock.calls.filter(([args]) => args.at(-1) === 'user') + ).toHaveLength(count) + expect( + glabExecFileAsyncMock.mock.calls.filter(([args]) => + args.at(-1)?.includes('source_branch=') + ) + ).toHaveLength(count) + expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(count * 3) + } + ) + it('hides a stale closed MR whose source branch is the repo default branch (#9171)', async () => { getProjectRefMock.mockResolvedValueOnce({ host: 'gitlab.com', path: 'g/p' }) mockBranchLookup({ diff --git a/src/main/gitlab/gitlab-paginated-list.ts b/src/main/gitlab/gitlab-paginated-list.ts index 0ac5b05f8c9..75b1ae3bdd1 100644 --- a/src/main/gitlab/gitlab-paginated-list.ts +++ b/src/main/gitlab/gitlab-paginated-list.ts @@ -35,7 +35,7 @@ export async function fetchAllGitLabPages( const { body, headers } = await glabApiWithHeaders( [ ...glabHostnameArgs(projectRef, connectionId), - `${endpoint}?per_page=${PAGE_SIZE}&page=${page}` + `${endpoint}${endpoint.includes('?') ? '&' : '?'}per_page=${PAGE_SIZE}&page=${page}` ], glabRepoExecOptions(repoPath, connectionId, localGitOptions) ) diff --git a/src/main/gitlab/glab-error-classification.ts b/src/main/gitlab/glab-error-classification.ts index b42d028a904..87a278026d3 100644 --- a/src/main/gitlab/glab-error-classification.ts +++ b/src/main/gitlab/glab-error-classification.ts @@ -81,3 +81,20 @@ export function classifyJobLogError(stderr: string): ClassifiedError { export function isMissingJobLogError(stderr: string): boolean { return classifyGlabError(stderr).type === 'not_found' && !/project\s+not\s+found/i.test(stderr) } + +/** Older servers reject these optimizations; ordinary permission/transport errors are not capabilities. */ +export function isUnsupportedReviewListFilter(message: string, state: string): boolean { + const status = /HTTP\s+(\d{3})/i.exec(message)?.[1] + if (status && status !== '400' && status !== '422') { + return false + } + return ( + /source_project_id[^\n]*(?:unsupported|unknown|unrecognized|not permitted|not allowed|invalid)/i.test( + message + ) || + (state === 'locked' && + /\bstate\b[^\n]*(?:does not have a valid value|invalid|unsupported|not (?:an? )?allowed)/i.test( + message + )) + ) +} diff --git a/src/main/gitlab/mappers.ts b/src/main/gitlab/mappers.ts index fcbd69bc731..852ca812e12 100644 --- a/src/main/gitlab/mappers.ts +++ b/src/main/gitlab/mappers.ts @@ -1,7 +1,4 @@ -import { - mapGitLabPipelineJobStatusToCheckStatus, - mapGitLabPipelineJobStatusToConclusion -} from '../../shared/source-control/checks/gitlab/gitlab-pipeline-checks' +import { gitLabPipelineJobOutcome } from '../../shared/source-control/checks/gitlab/gitlab-pipeline-checks' import type { CheckStatus } from '../../shared/github/pull-request-types' import type { GitLabIssueInfo, GitLabWorkItem, MRInfo, MRState } from '../../shared/gitlab-types' @@ -148,7 +145,12 @@ function deriveMergeStateStatus( } export function derivePipelineStatus( - rollup: { status?: string }[] | { status?: string } | string | null | undefined + rollup: + | { status?: string; allowFailure?: boolean }[] + | { status?: string } + | string + | null + | undefined ): CheckStatus { if (!rollup) { return 'neutral' @@ -160,15 +162,7 @@ export function derivePipelineStatus( return classifyPipelineString(rollup.status ?? '') } // Share rollup rules so pipeline cards cannot diverge from Checks rows. - const { state } = summarizeProviderChecks( - rollup.map((job) => { - const s = job.status?.toLowerCase() ?? '' - return { - status: mapGitLabPipelineJobStatusToCheckStatus(s), - conclusion: mapGitLabPipelineJobStatusToConclusion(s) - } - }) - ) + const { state } = summarizeProviderChecks(rollup.map(gitLabPipelineJobOutcome)) // The public status type uses neutral for no check results. return state === 'none' ? 'neutral' : state } diff --git a/src/main/gitlab/merge-request-lookup.ts b/src/main/gitlab/merge-request-lookup.ts index 206f54e2931..f1f5e04e04a 100644 --- a/src/main/gitlab/merge-request-lookup.ts +++ b/src/main/gitlab/merge-request-lookup.ts @@ -1,3 +1,16 @@ +import { getReviewBranchSource } from '../github/client/lookup/tracked-upstream-branch' +import { createGitLabBranchDiscovery } from './branch-review-discovery' +import { resolveReviewSourceProject } from './branch-review-source' +import { forgetReviewProjectIdentity } from './review-project-identity' +import { mergedMRContainsHead } from './merged-mr-commit-membership' +import { readCurrentReviewHead } from '../source-control/review-current-head' +import { shouldHideMergedImplicitReview } from '../source-control/branch-review-selection' +import { + getRemoteHeadBranchName, + getRepoDefaultBranchName +} from '../source-control/repo-default-branch' +import { extractExecError } from '../git/exec-error' +import { classifyGlabError } from './glab-error-classification' import type { MRInfo } from '../../shared/gitlab-types' import { derivePipelineStatus, mapMRInfo } from './mappers' import { @@ -18,6 +31,11 @@ import { } from '../source-control/hosted-review-git-options' import { shouldHideNonOpenReviewOnDefaultBranch } from '../source-control/repo-default-branch' +type BranchReviewOptions = HostedReviewExecutionOptions & { + currentHeadOid?: string | null + userRefresh?: boolean +} + type HostedReviewLocalGitOptions = ReturnType function hostedReviewLocalGitOptionArgs( @@ -79,7 +97,7 @@ export async function getMergeRequestForBranch( branch: string, linkedMRIid?: number | null, connectionId?: string | null, - options: HostedReviewExecutionOptions = {}, + options: BranchReviewOptions = {}, // Strict callers need failures distinguished from confirmed missing reviews. throwOnFailure = false ): Promise { @@ -96,7 +114,7 @@ export async function getMergeRequestForBranch( } await acquire() try { - const fetchByIid = async (iid: number): Promise => { + const fetchByIid = async (iid: number) => { const { stdout } = await glabExecFileAsync( [ 'api', @@ -105,40 +123,139 @@ export async function getMergeRequestForBranch( ], glabRepoExecOptions(repoPath, connectionId, localGitOptions) ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the single-MR endpoint returns the MR fields and its optional pipeline. - const raw = JSON.parse(stdout) as Parameters[0] - const pipelineStatus = derivePipelineStatus(raw.head_pipeline ?? raw.pipeline ?? null) - return mapMRInfo(raw, pipelineStatus) + const raw = JSON.parse(stdout) as Parameters[0] & { + target_project_id?: number + project_id?: number + source_project_id?: number + source_branch?: string + } + return { + raw, + info: mapMRInfo(raw, derivePipelineStatus(raw.head_pipeline ?? raw.pipeline ?? null)) + } } if (typeof linkedMRIid === 'number') { - return await fetchByIid(linkedMRIid) + return (await fetchByIid(linkedMRIid)).info } - if (branchName) { - const { stdout } = await glabExecFileAsync( - [ - 'api', - ...glabHostnameArgs(projectRef, connectionId), - // List endpoints need asynchronous merge-status recheck; GitLab may restrict this to Developers. - `projects/${encodedProject(projectRef.path)}/merge_requests?source_branch=${encodeURIComponent(branchName)}&order_by=updated_at&sort=desc&per_page=1&with_merge_status_recheck=true` - ], - glabRepoExecOptions(repoPath, connectionId, localGitOptions) - ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the branch-list endpoint returns MR summaries; only their identity is used. - const data = JSON.parse(stdout) as Parameters[0][] - if (Array.isArray(data) && data.length > 0) { - // List summaries omit head_pipeline; only detail can supply an authoritative check result. - const info = await fetchByIid(data[0].iid ?? data[0].number ?? 0) - const hideOnDefaultBranch = await shouldHideNonOpenReviewOnDefaultBranch({ - state: info.state, - reviewNumber: info.number, - branchName, + const source = await getReviewBranchSource( + repoPath, + branchName, + connectionId, + localGitOptions, + options.userRefresh + ) + for (let attempt = 0; attempt < 2; attempt += 1) { + const identityArgs = { + repoPath, + target: projectRef, + urls: source.urls, + connectionId, + localGitOptions, + force: options.userRefresh || attempt > 0 + } + const sourceProject = await resolveReviewSourceProject(identityArgs) + try { + const discover = createGitLabBranchDiscovery({ repoPath, + project: projectRef, + sourceProjectId: sourceProject.id, connectionId, localGitOptions }) - if (!hideOnDefaultBranch) { + let candidate = await discover(source.branchName) + let usedTrackedName = false + if (!candidate && source.trackedBranchName && source.trackedUrls) { + const trackedSource = await resolveReviewSourceProject({ + ...identityArgs, + urls: source.trackedUrls + }) + if (trackedSource.id === sourceProject.id) { + candidate = await discover(source.trackedBranchName) + usedTrackedName = true + } + } + if (!candidate) { + return null + } + if (usedTrackedName && candidate.source_project_id === candidate.target_project_id) { + const defaultBranch = + source.remoteName === 'origin' + ? await getRepoDefaultBranchName(repoPath, connectionId, localGitOptions) + : await getRemoteHeadBranchName( + repoPath, + source.remoteName, + connectionId, + localGitOptions + ) + if (candidate.source_branch === defaultBranch) { + return null + } + } + const { info, raw } = await fetchByIid(candidate.iid) + if ( + info.number !== candidate.iid || + raw.source_project_id !== candidate.source_project_id || + raw.target_project_id !== candidate.target_project_id || + raw.source_branch !== candidate.source_branch + ) { + throw new Error('GitLab merge request identity changed during lookup') + } + if (info.state === 'merged') { + const currentHead = + options.currentHeadOid?.trim() || + (await readCurrentReviewHead(repoPath, connectionId, localGitOptions)) + if (shouldHideMergedImplicitReview(info.state, linkedMRIid, info.headSha, currentHead)) { + if (!currentHead) { + return null + } + const targetProjectId = raw.target_project_id ?? raw.project_id + if ( + !Number.isSafeInteger(targetProjectId) || + !targetProjectId || + targetProjectId <= 0 + ) { + throw new Error('Invalid GitLab target project identity') + } + if ( + (await mergedMRContainsHead({ + repoPath, + project: projectRef, + targetProjectId, + iid: info.number, + headOid: currentHead, + connectionId, + localGitOptions, + userRefresh: options.userRefresh + })) !== 'contained' + ) { + return null + } + } + } + if ( + !(await shouldHideNonOpenReviewOnDefaultBranch({ + state: info.state, + reviewNumber: info.number, + branchName, + repoPath, + connectionId, + localGitOptions + })) + ) { return info } + return null + } catch (error) { + const detail = extractExecError(error) + if ( + attempt > 0 || + classifyGlabError( + [detail.stderr, detail.stdout, error instanceof Error ? error.message : ''].join('\n') + ).type !== 'not_found' + ) { + throw error + } + forgetReviewProjectIdentity(repoPath, sourceProject.project, connectionId, localGitOptions) } } return null @@ -158,7 +275,7 @@ export function getMergeRequestForBranchOrThrow( branch: string, linkedMRIid?: number | null, connectionId?: string | null, - options: HostedReviewExecutionOptions = {} + options: BranchReviewOptions = {} ): Promise { return getMergeRequestForBranch(repoPath, branch, linkedMRIid, connectionId, options, true) } diff --git a/src/main/gitlab/merged-mr-commit-membership.test.ts b/src/main/gitlab/merged-mr-commit-membership.test.ts new file mode 100644 index 00000000000..ac956e3e24c --- /dev/null +++ b/src/main/gitlab/merged-mr-commit-membership.test.ts @@ -0,0 +1,82 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import type * as GlabApiResponse from './glab-api-response' +const { pages, viewer } = vi.hoisted(() => ({ pages: vi.fn(), viewer: vi.fn() })) +vi.mock('./gl-utils', async () => ({ + ...(await vi.importActual('./glab-api-response')), + glabApiWithHeaders: pages, + glabHostnameArgs: () => [], + glabRepoExecOptions: () => ({ cwd: '/repo' }) +})) +vi.mock('./gitlab-auth-and-rate-limit', () => ({ readGlabViewer: viewer })) +import { + mergedMRContainsHead, + resetMergedMRCommitMembershipForTest +} from './merged-mr-commit-membership' +const args = { + repoPath: '/repo', + project: { host: 'gitlab.com', path: 'g/p' }, + targetProjectId: 1, + iid: 7, + headOid: 'f'.repeat(40), + localGitOptions: {} +} +beforeEach(() => { + resetMergedMRCommitMembershipForTest() + pages.mockReset() + viewer.mockReset().mockResolvedValue({ id: 1 }) +}) +it.each([10, 100])( + 'reuses a complete 500-commit result across %s admitted refreshes and coalesces a cold walk', + async (count) => { + pages.mockImplementation(async ([endpoint]: string[]) => { + const page = Number(new URL(endpoint, 'https://gitlab.com').searchParams.get('page')) + return { + body: JSON.stringify( + Array.from({ length: 100 }, (_, i) => ({ + id: + page === 5 && i === 99 + ? args.headOid + : (page * 100 + i).toString(16).padStart(40, '0') + })) + ), + headers: { 'x-next-page': page < 5 ? String(page + 1) : '' } + } + }) + await expect( + Promise.all([mergedMRContainsHead(args), mergedMRContainsHead(args)]) + ).resolves.toEqual(['contained', 'contained']) + for (let i = 0; i < count; i++) { + await expect(mergedMRContainsHead(args)).resolves.toBe('contained') + } + expect(pages).toHaveBeenCalledTimes(5) + viewer.mockResolvedValue({ id: 2 }) + await mergedMRContainsHead(args) + expect(pages).toHaveBeenCalledTimes(10) + } +) +it('preserves a failed page as unavailable, and a user refresh retries it', async () => { + pages + .mockResolvedValueOnce({ + body: JSON.stringify( + Array.from({ length: 100 }, (_, i) => ({ id: i.toString(16).padStart(40, '0') })) + ), + headers: { 'x-next-page': '2' } + }) + .mockRejectedValueOnce(new Error('offline')) + await expect(mergedMRContainsHead(args)).rejects.toThrow() + await expect(mergedMRContainsHead(args)).rejects.toThrow() + expect(pages).toHaveBeenCalledTimes(2) + pages.mockResolvedValue({ + body: JSON.stringify([{ id: args.headOid }]), + headers: { 'x-next-page': '' } + }) + await expect(mergedMRContainsHead({ ...args, userRefresh: true })).resolves.toBe('contained') + expect(pages).toHaveBeenCalledTimes(3) +}) +it('does a fresh authorized walk without a usable viewer identity', async () => { + viewer.mockRejectedValue(new Error('no viewer')) + pages.mockResolvedValue({ body: '[]', headers: { 'x-next-page': '' } }) + await expect(mergedMRContainsHead(args)).resolves.toBe('not-contained') + await expect(mergedMRContainsHead(args)).resolves.toBe('not-contained') + expect(pages).toHaveBeenCalledTimes(2) +}) diff --git a/src/main/gitlab/merged-mr-commit-membership.ts b/src/main/gitlab/merged-mr-commit-membership.ts new file mode 100644 index 00000000000..6418b9a8af7 --- /dev/null +++ b/src/main/gitlab/merged-mr-commit-membership.ts @@ -0,0 +1,93 @@ +import { + MergedReviewMembershipMemo, + type MergedReviewCommitMembership +} from '../source-control/merged-review-membership-memo' +import { codeHostReadExecutionScope } from '../source-control/code-host-read-execution-scope' +import { runCoalescedProbe, type CoalescedProbes } from '../git/remotes/coalesced-probe' +import { fetchAllGitLabPages } from './gitlab-paginated-list' +import { readGlabViewer } from './gitlab-auth-and-rate-limit' +import { + glabHostnameArgs, + glabRepoExecOptions, + type LocalGitExecOptions, + type ProjectRef +} from './gl-utils' +import { encodedProject } from './project-path-encoding' + +const membershipMemo = new MergedReviewMembershipMemo() +const viewers: CoalescedProbes = new Map() + +export function resetMergedMRCommitMembershipForTest(): void { + membershipMemo.clear() + viewers.clear() +} + +export async function mergedMRContainsHead(args: { + repoPath: string + project: ProjectRef + targetProjectId: number + iid: number + headOid: string + connectionId?: string | null + localGitOptions: LocalGitExecOptions + userRefresh?: boolean +}): Promise { + const options = glabRepoExecOptions(args.repoPath, args.connectionId, args.localGitOptions) + const scope = codeHostReadExecutionScope({ ...options, connectionId: args.connectionId ?? null }) + const viewerKey = `${args.project.host.toLowerCase()}\0${scope}` + const viewer = await runCoalescedProbe( + viewers, + viewerKey, + async () => { + try { + const data = await readGlabViewer( + glabHostnameArgs(args.project, args.connectionId), + options + ) + return typeof data.id === 'number' && Number.isSafeInteger(data.id) && data.id > 0 + ? data.id + : null + } catch { + return null + } + }, + Infinity, + { userRefresh: args.userRefresh } + ) + const load = async (): Promise => { + const commits = await fetchAllGitLabPages<{ id?: unknown }>( + args.repoPath, + args.project, + `projects/${encodedProject(args.project.path)}/merge_requests/${args.iid}/commits`, + args.connectionId, + args.localGitOptions + ) + if ( + commits.some( + (commit) => typeof commit.id !== 'string' || !/^[0-9a-f]{40,64}$/i.test(commit.id) + ) + ) { + throw new Error('Invalid GitLab merge request commits') + } + return commits.some( + (commit) => + typeof commit.id === 'string' && commit.id.toLowerCase() === args.headOid.toLowerCase() + ) + ? 'contained' + : 'not-contained' + } + // A missing account identity disables bookkeeping, never the authorized fresh read. + if (viewer === null) { + return load() + } + const key = [ + 'gitlab', + args.project.host.toLowerCase(), + scope, + viewer, + args.targetProjectId, + args.iid, + args.headOid.toLowerCase() + ].join('\0') + return membershipMemo.read(key, load, { refreshFailed: args.userRefresh }) +} diff --git a/src/main/gitlab/mr-discussion-notes.test.ts b/src/main/gitlab/mr-discussion-notes.test.ts new file mode 100644 index 00000000000..845fbaf581e --- /dev/null +++ b/src/main/gitlab/mr-discussion-notes.test.ts @@ -0,0 +1,120 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import type * as GlabApiResponse from './glab-api-response' +const { pages, viewer } = vi.hoisted(() => ({ pages: vi.fn(), viewer: vi.fn() })) +vi.mock('./gl-utils', async () => ({ + ...(await vi.importActual('./glab-api-response')), + glabApiWithHeaders: pages, + glabHostnameArgs: () => [], + glabRepoExecOptions: () => ({}) +})) +vi.mock('./gitlab-auth-and-rate-limit', () => ({ readGlabViewer: viewer })) +import { fetchDiscussionComments } from './mr-discussion-notes' +beforeEach(() => { + pages.mockReset() + viewer.mockReset().mockResolvedValue({ username: 'me' }) +}) +it.each(['mr', 'issue'] as const)( + 'reads newest %s discussions beyond 100 with thread metadata', + async (type) => { + pages.mockImplementation(async ([endpoint]: string[]) => { + const page = Number(new URL(endpoint, 'https://gitlab.com').searchParams.get('page')) + return { + body: JSON.stringify( + Array.from({ length: page === 1 ? 100 : 1 }, (_, i) => ({ + id: `D${page}-${i}`, + notes: [ + { + id: (page - 1) * 100 + i, + body: 'Review', + created_at: page === 1 ? '2026-01-01' : '2026-11-08', + author: { username: 'me' }, + resolvable: true, + resolved: true, + position: { new_path: 'a.ts', new_line: 4 } + } + ] + })) + ), + headers: { 'x-next-page': page === 1 ? '2' : '' } + } + }) + const comments = await fetchDiscussionComments( + '/repo', + { host: 'gitlab.com', path: 'g/p' }, + type, + 7 + ) + expect(comments).toHaveLength(101) + expect(comments.at(-1)).toMatchObject({ + id: 100, + threadId: 'D2-0', + isResolved: true, + path: 'a.ts', + line: 4, + viewerDidAuthor: true + }) + expect(pages).toHaveBeenCalledTimes(2) + expect(viewer).toHaveBeenCalledTimes(1) + } +) +it('never presents a successful prefix after a later discussion page fails', async () => { + pages + .mockResolvedValueOnce({ + body: JSON.stringify(Array.from({ length: 100 }, (_, i) => ({ id: String(i) }))), + headers: { 'x-next-page': '2' } + }) + .mockRejectedValueOnce(new Error('offline')) + await expect( + fetchDiscussionComments('/repo', { host: 'gitlab.com', path: 'g/p' }, 'mr', 7) + ).rejects.toThrow('incomplete') +}) + +it.each([100, 1000])('measures complete realistic discussions at %s rows', async (count) => { + const body = `## Review\n\nPlease preserve the existing owner across reconnects.\n\n\`\`\`typescript\nconst state = await readOwner()\nreturn state.current\n\`\`\`\n\n${'The next request should retain the confirmed state and report incomplete reads. '.repeat( + 20 + )}` + let rawBytes = 0 + pages.mockImplementation(async ([endpoint]: string[]) => { + const page = Number(new URL(endpoint, 'https://gitlab.com').searchParams.get('page')) + const rows = Array.from({ length: Math.min(100, count - (page - 1) * 100) }, (_, i) => ({ + id: `discussion-${page}-${i}`, + notes: [ + { + id: (page - 1) * 100 + i, + body, + created_at: '2026-11-08T00:00:00Z', + author: { username: 'me', avatar_url: 'https://gitlab.com/avatar.png' }, + resolvable: true, + resolved: false, + position: { new_path: 'src/file.ts', new_line: 17 } + } + ] + })) + const serialized = JSON.stringify(rows) + rawBytes += Buffer.byteLength(serialized) + return { + body: serialized, + headers: { 'x-next-page': page * 100 < count ? String(page + 1) : '' } + } + }) + const before = process.memoryUsage().heapUsed + const start = performance.now() + const result = await fetchDiscussionComments( + '/repo', + { host: 'gitlab.com', path: 'g/p' }, + 'mr', + 7 + ) + const normalized = performance.now() + const wireBytes = Buffer.byteLength(JSON.stringify(result)) + console.info('gitlab-review-parity-discussions', { + count, + rawBytes, + wireBytes, + readParseSortMs: normalized - start, + serializeMs: performance.now() - normalized, + heapDeltaBytes: process.memoryUsage().heapUsed - before + }) + expect(result).toHaveLength(count) + expect(pages).toHaveBeenCalledTimes(count / 100) +}) diff --git a/src/main/gitlab/mr-discussion-notes.ts b/src/main/gitlab/mr-discussion-notes.ts index fdef56b89e3..e186d4f50dc 100644 --- a/src/main/gitlab/mr-discussion-notes.ts +++ b/src/main/gitlab/mr-discussion-notes.ts @@ -1,3 +1,4 @@ +import { fetchAllGitLabPages } from './gitlab-paginated-list' import type { MRComment } from '../../shared/gitlab-types' import { viewerAuthorship } from '../source-control/comment-viewer-authorship' import { readGlabViewer } from './gitlab-auth-and-rate-limit' @@ -5,7 +6,6 @@ import { encodedProject } from './project-path-encoding' import { glabHostnameArgs, glabRepoExecOptions, - glabExecFileAsync, type LocalGitExecOptions, type ProjectRef } from './gl-utils' @@ -71,15 +71,13 @@ export async function fetchDiscussionComments( const resource = type === 'mr' ? 'merge_requests' : 'issues' const hostArgs = glabHostnameArgs(projectRef, connectionId) const options = glabRepoExecOptions(repoPath, connectionId, localGitOptions) - const [{ stdout }, viewerUsername] = await Promise.all([ - glabExecFileAsync( - [ - 'api', - ...hostArgs, - // Bound detail loads to a recent page rather than retaining every historic discussion. - `projects/${encodedProject(projectRef.path)}/${resource}/${iid}/discussions?per_page=100` - ], - options + const [discussions, viewerUsername] = await Promise.all([ + fetchAllGitLabPages( + repoPath, + projectRef, + `projects/${encodedProject(projectRef.path)}/${resource}/${iid}/discussions`, + connectionId, + localGitOptions ), // Notes carry no authorship flag, so ask the reading account who it is. markViewer @@ -89,5 +87,5 @@ export async function fetchDiscussionComments( ) : null ]) - return flattenDiscussions(JSON.parse(stdout) as GitLabRawDiscussion[], viewerUsername) + return flattenDiscussions(discussions, viewerUsername) } diff --git a/src/main/gitlab/pipeline-job-graph.test.ts b/src/main/gitlab/pipeline-job-graph.test.ts index 852163832b2..a9746d1daf2 100644 --- a/src/main/gitlab/pipeline-job-graph.test.ts +++ b/src/main/gitlab/pipeline-job-graph.test.ts @@ -6,6 +6,8 @@ const { glabApiWithHeadersMock } = vi.hoisted(() => ({ glabApiWithHeadersMock: v vi.mock('./gl-utils', async () => ({ ...(await vi.importActual('./glab-api-response')), glabApiWithHeaders: glabApiWithHeadersMock, + acquire: vi.fn(), + release: vi.fn(), // Serves single-request fetches from the same pipeline, so a reverted fix fails on row counts. glabExecFileAsync: async (args: string[]) => ({ stdout: (await glabApiWithHeadersMock(args.slice(1))).body @@ -16,6 +18,7 @@ vi.mock('./gl-utils', async () => ({ import { GitLabIncompletePaginationError } from './gitlab-paginated-list' import { fetchPipelineJobs } from './pipeline-job-graph' +import { retryJob } from './pipeline-job-mutations' /** Serves `/jobs` and `/bridges` 100 per page with GitLab's x-next-page header. */ function servePipeline( @@ -56,6 +59,32 @@ describe('fetchPipelineJobs', () => { glabApiWithHeadersMock.mockReset() }) + it('preserves optional failure policy through job, bridge and retry responses', async () => { + glabApiWithHeadersMock.mockImplementation(async (args: string[]) => { + const endpoint = args.at(-1) ?? '' + const raw = { id: 19, name: 'test', status: 'failed', allow_failure: true } + return { + body: JSON.stringify( + endpoint.endsWith('/retry') + ? raw + : endpoint.includes('/bridges?') + ? [{ ...raw, name: 'trigger' }] + : [raw] + ), + headers: { 'x-next-page': '' } + } + }) + const project = { host: 'gitlab.com', path: 'g/p' } + await expect(fetchPipelineJobs('/repo', project, 7)).resolves.toMatchObject([ + { id: 19, status: 'failed', allowFailure: true }, + { id: 0, name: 'trigger', status: 'failed', allowFailure: true } + ]) + await expect(retryJob('/repo', 19, undefined, null, project)).resolves.toMatchObject({ + ok: true, + job: { id: 19, allowFailure: true } + }) + }) + it.each([ // One request per started 100-item page on each endpoint. { jobs: 130, bridges: 101, requests: 4 }, diff --git a/src/main/gitlab/pipeline-job-graph.ts b/src/main/gitlab/pipeline-job-graph.ts index aa565f6d8d2..60172577289 100644 --- a/src/main/gitlab/pipeline-job-graph.ts +++ b/src/main/gitlab/pipeline-job-graph.ts @@ -16,6 +16,7 @@ type GitLabRawJob = { name?: string stage?: string status?: string + allow_failure?: boolean web_url?: string duration?: number | null started_at?: string | null @@ -27,6 +28,7 @@ type GitLabRawBridge = { name?: string stage?: string status?: string + allow_failure?: boolean web_url?: string duration?: number | null started_at?: string | null @@ -46,6 +48,7 @@ function mapPipelineJob(raw: GitLabRawJob, pipelineId: number): GitLabPipelineJo name: raw.name ?? '', stage: raw.stage ?? '', status: raw.status ?? '', + ...(typeof raw.allow_failure === 'boolean' ? { allowFailure: raw.allow_failure } : {}), webUrl: raw.web_url ?? '', duration: typeof raw.duration === 'number' ? raw.duration : null, ...gitLabRunTimes(raw) @@ -62,6 +65,7 @@ function mapBridgeAsJob(raw: GitLabRawBridge, pipelineId: number): GitLabPipelin stage: raw.stage ?? '', // Bridge status may remain successful while its downstream pipeline is running or failed. status: childStatus || raw.status || '', + ...(typeof raw.allow_failure === 'boolean' ? { allowFailure: raw.allow_failure } : {}), webUrl: raw.downstream_pipeline?.web_url ?? raw.web_url ?? '', duration: typeof raw.duration === 'number' ? raw.duration : null, // The trigger job's own times can end long before the child pipeline it now stands for. diff --git a/src/main/gitlab/pipeline-job-mutations.ts b/src/main/gitlab/pipeline-job-mutations.ts index 1116a36e043..9d4f41618d4 100644 --- a/src/main/gitlab/pipeline-job-mutations.ts +++ b/src/main/gitlab/pipeline-job-mutations.ts @@ -31,6 +31,7 @@ function mapRetriedPipelineJob( name?: string stage?: string status?: string + allow_failure?: boolean web_url?: string duration?: number | null started_at?: string | null @@ -44,6 +45,7 @@ function mapRetriedPipelineJob( name: data.name ?? '', stage: data.stage ?? '', status: data.status ?? '', + ...(typeof data.allow_failure === 'boolean' ? { allowFailure: data.allow_failure } : {}), webUrl: data.web_url ?? '', duration: typeof data.duration === 'number' ? data.duration : null, ...gitLabRunTimes(data) diff --git a/src/main/gitlab/review-project-identity.test.ts b/src/main/gitlab/review-project-identity.test.ts new file mode 100644 index 00000000000..31dfe59cdcb --- /dev/null +++ b/src/main/gitlab/review-project-identity.test.ts @@ -0,0 +1,71 @@ +import { beforeEach, expect, it, vi } from 'vitest' +const { read, signature } = vi.hoisted(() => ({ read: vi.fn(), signature: vi.fn() })) +vi.mock('./gl-utils', () => ({ + glabExecFileAsync: read, + glabHostnameArgs: () => [], + glabRepoExecOptions: (cwd: string) => ({ cwd }) +})) +vi.mock('../github/local-git-config-signature', () => ({ readLocalGitConfigSignature: signature })) +import { + readReviewProjectIdentity, + resetReviewProjectIdentitiesForTest +} from './review-project-identity' +const project = { host: 'gitlab.com', path: 'g/p' } +const result = (id: number) => ({ + stdout: JSON.stringify({ id, path_with_namespace: 'canonical/p' }) +}) +beforeEach(() => { + resetReviewProjectIdentitiesForTest() + read.mockReset() + signature.mockReset().mockResolvedValue('config-1') +}) +it('coalesces minimal identities, invalidates changed configuration, and does not retain failed reads', async () => { + read.mockResolvedValue(result(1)) + await expect( + Promise.all([ + readReviewProjectIdentity('/repo', project, null, {}), + readReviewProjectIdentity('/repo', project, null, {}) + ]) + ).resolves.toEqual([ + { id: 1, path: 'canonical/p' }, + { id: 1, path: 'canonical/p' } + ]) + expect(read).toHaveBeenCalledTimes(1) + signature.mockResolvedValue('config-2') + read.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce(result(2)) + await expect(readReviewProjectIdentity('/repo', project, null, {})).rejects.toThrow('offline') + await expect(readReviewProjectIdentity('/repo', project, null, {})).resolves.toMatchObject({ + id: 2 + }) + expect(read).toHaveBeenCalledTimes(3) +}) +it('does not let an older forced-out read overwrite its successor', async () => { + let finish: (value: { stdout: string }) => void = () => { + throw new Error('not started') + } + let started: () => void = () => { + throw new Error('not started') + } + const admitted = new Promise((resolve) => { + started = resolve + }) + read + .mockImplementationOnce(() => { + started() + return new Promise<{ stdout: string }>((resolve) => { + finish = resolve + }) + }) + .mockResolvedValueOnce(result(2)) + const old = readReviewProjectIdentity('/repo', project, null, {}) + await admitted + await expect(readReviewProjectIdentity('/repo', project, null, {}, true)).resolves.toMatchObject({ + id: 2 + }) + finish(result(1)) + await old + await expect(readReviewProjectIdentity('/repo', project, null, {})).resolves.toMatchObject({ + id: 2 + }) + expect(read).toHaveBeenCalledTimes(2) +}) diff --git a/src/main/gitlab/review-project-identity.ts b/src/main/gitlab/review-project-identity.ts new file mode 100644 index 00000000000..4e808bc6312 --- /dev/null +++ b/src/main/gitlab/review-project-identity.ts @@ -0,0 +1,113 @@ +import { runCoalescedProbe, type CoalescedProbes } from '../git/remotes/coalesced-probe' +import { codeHostReadExecutionScope } from '../source-control/code-host-read-execution-scope' +import { readLocalGitConfigSignature } from '../github/local-git-config-signature' +import { + glabExecFileAsync, + glabHostnameArgs, + glabRepoExecOptions, + type LocalGitExecOptions, + type ProjectRef +} from './gl-utils' +import { encodedProject } from './project-path-encoding' +import { normalizeGitLabHost } from './project-ref-parser' + +type ProjectIdentity = { id: number; path: string } +type CachedIdentity = { value: ProjectIdentity; expiresAt: number; configSignature?: string } +const identities = new Map() +const pending: CoalescedProbes = new Map() + +function identityKey( + repoPath: string, + project: ProjectRef, + connectionId: string | null | undefined, + options: LocalGitExecOptions +): string { + return [ + normalizeGitLabHost(project.host), + project.path, + connectionId ?? '', + codeHostReadExecutionScope(glabRepoExecOptions(repoPath, connectionId, options)) + ].join('\0') +} + +export function forgetReviewProjectIdentity( + repoPath: string, + project: ProjectRef, + connectionId: string | null | undefined, + options: LocalGitExecOptions +): void { + const key = identityKey(repoPath, project, connectionId, options) + identities.delete(key) + pending.delete(key) +} + +export function resetReviewProjectIdentitiesForTest(): void { + identities.clear() + pending.clear() +} + +export async function readReviewProjectIdentity( + repoPath: string, + project: ProjectRef, + connectionId: string | null | undefined, + options: LocalGitExecOptions, + force = false +): Promise { + const key = identityKey(repoPath, project, connectionId, options) + const signature = await readLocalGitConfigSignature({ repoPath, connectionId, ...options }) + const cached = identities.get(key) + if (!force && cached && cached.expiresAt > Date.now() && cached.configSignature === signature) { + return cached.value + } + return runCoalescedProbe( + pending, + key, + async (ownsKey) => { + const { stdout } = await glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(project, connectionId), + `projects/${encodedProject(project.path)}` + ], + glabRepoExecOptions(repoPath, connectionId, options) + ) + const data: unknown = JSON.parse(stdout) + if ( + !data || + typeof data !== 'object' || + !('id' in data) || + typeof data.id !== 'number' || + !Number.isSafeInteger(data.id) || + data.id <= 0 || + !('path_with_namespace' in data) || + typeof data.path_with_namespace !== 'string' || + !data.path_with_namespace + ) { + throw new Error('Invalid GitLab source project identity') + } + const value = { id: data.id, path: data.path_with_namespace } + if (ownsKey()) { + identities.set(key, { + value, + configSignature: signature, + expiresAt: Date.now() + 5 * 60_000 + }) + for (const [entryKey, entry] of identities) { + if (entry.expiresAt <= Date.now()) { + identities.delete(entryKey) + } + } + while (identities.size > 512) { + const oldest = identities.keys().next().value + if (oldest === undefined) { + break + } + identities.delete(oldest) + } + } + return value + }, + Infinity, + { userRefresh: force } + ) +} diff --git a/src/main/gitlab/work-item-details.test.ts b/src/main/gitlab/work-item-details.test.ts index b705874420a..71e86e58246 100644 --- a/src/main/gitlab/work-item-details.test.ts +++ b/src/main/gitlab/work-item-details.test.ts @@ -261,4 +261,30 @@ describe('getWorkItemDetails', () => { ]) } ) + it.each(['mr', 'issue'] as const)( + 'returns unavailable for a late %s discussion failure', + async (type) => { + glabExecFileAsyncMock.mockImplementation(async (args: string[]) => { + const endpoint = args.at(-1) ?? '' + if (endpoint.includes('/discussions')) { + if (endpoint.includes('page=2')) { + throw new Error('offline') + } + return { + stdout: JSON.stringify( + Array.from({ length: 100 }, (_, i) => ({ + id: String(i), + notes: [{ id: i, body: 'Existing note' }] + })) + ) + } + } + if (endpoint === 'user') { + return { stdout: '{"username":"me"}' } + } + return { stdout: JSON.stringify({ iid: 12, title: 'Item', state: 'opened' }) } + }) + await expect(getWorkItemDetails('/repo', 12, type)).resolves.toBeNull() + } + ) }) diff --git a/src/main/source-control/branch-review-selection.ts b/src/main/source-control/branch-review-selection.ts new file mode 100644 index 00000000000..f95583bc641 --- /dev/null +++ b/src/main/source-control/branch-review-selection.ts @@ -0,0 +1,29 @@ +export async function selectBranchReview(input: { + readRecent: () => Promise + readActive: () => Promise + isActive: (review: T) => boolean + pageSize: number +}): Promise { + const recent = await input.readRecent() + const active = recent.find(input.isActive) + if (active) { + return active + } + // A full mixed-state page cannot prove that no older active review exists. + return recent.length < input.pageSize + ? (recent[0] ?? null) + : ((await input.readActive()) ?? recent[0] ?? null) +} + +export function shouldHideMergedImplicitReview( + state: string, + linkedNumber: number | null | undefined, + reviewHead: string | null | undefined, + currentHead: string | null +): boolean { + return ( + typeof linkedNumber !== 'number' && + state.toLowerCase() === 'merged' && + (!currentHead || reviewHead !== currentHead) + ) +} diff --git a/src/main/source-control/code-host-read-execution-scope.ts b/src/main/source-control/code-host-read-execution-scope.ts new file mode 100644 index 00000000000..4226c342d52 --- /dev/null +++ b/src/main/source-control/code-host-read-execution-scope.ts @@ -0,0 +1,18 @@ +import { createHash } from 'node:crypto' + +export function codeHostReadExecutionScope( + options: T & { env?: NodeJS.ProcessEnv; admissionTier?: unknown }, + environment: NodeJS.ProcessEnv = options.env ?? process.env +): string { + const { admissionTier: _admissionTier, ...executionOptions } = options + // gh wrappers and credential selection can depend on cwd and the inherited environment. + return createHash('sha256') + .update( + JSON.stringify([ + executionOptions, + process.cwd(), + Object.entries(environment).sort(([a], [b]) => a.localeCompare(b, 'en')) + ]) + ) + .digest('hex') +} diff --git a/src/main/source-control/forge-provider.ts b/src/main/source-control/forge-provider.ts index 8ef7db33607..79f4b5ecc24 100644 --- a/src/main/source-control/forge-provider.ts +++ b/src/main/source-control/forge-provider.ts @@ -57,8 +57,8 @@ export type ForgeReviewForBranchInput = ForgeProviderRepositoryContext & { branch: string linkedReviewNumber?: number | null fallbackReviewNumber?: number | null - // GitHub-only merged-at-head visibility; other providers ignore this inspected HEAD. - githubCurrentHeadOid?: string | null + // The inspected checkout HEAD scopes implicit merged-review visibility. + currentHeadOid?: string | null userRefresh?: boolean } @@ -109,7 +109,7 @@ const gitLabForgeProvider = { input.branch, input.linkedReviewNumber ?? null, forgeConnectionId(input), - ...hostedReviewExecutionArgs(input) + { ...input, currentHeadOid: input.currentHeadOid } ) return mr ? mapGitLabReview(mr) : null }, @@ -178,7 +178,7 @@ const gitHubForgeProvider = { ...executionArgs[0], ...(input.userRefresh === true ? { userRefresh: true } : {}), ...(fallbackReviewNumber !== null ? { acceptMergedFallbackPR: true } : {}), - currentHeadOid: input.githubCurrentHeadOid ?? null + currentHeadOid: input.currentHeadOid ?? null } ) return unwrapGitHubPRForBranchOutcome(outcome) diff --git a/src/main/source-control/hosted-review.ts b/src/main/source-control/hosted-review.ts index 6925c940755..8dd813873b7 100644 --- a/src/main/source-control/hosted-review.ts +++ b/src/main/source-control/hosted-review.ts @@ -138,7 +138,7 @@ export async function readHostedReviewForBranch( ...(providerOptions.localGitExecOptions ? { localGitExecOptions: providerOptions.localGitExecOptions } : {}), - githubCurrentHeadOid: headOid, + currentHeadOid: headOid, ...(input.userRefresh === true ? { userRefresh: true } : {}), ...reviewLinkForProvider(input, provider.id) }) diff --git a/src/main/source-control/merged-review-membership-memo.ts b/src/main/source-control/merged-review-membership-memo.ts new file mode 100644 index 00000000000..9b4196299e1 --- /dev/null +++ b/src/main/source-control/merged-review-membership-memo.ts @@ -0,0 +1,92 @@ +import { runCoalescedProbe, type CoalescedProbes } from '../git/remotes/coalesced-probe' + +export type MergedReviewCommitMembership = 'contained' | 'not-contained' | 'unknown' + +type Receipt = { value: MergedReviewCommitMembership; expiresAt: number; failed?: boolean } + +export class MergedReviewMembershipUnavailableError extends Error { + constructor() { + super('Could not verify merged review commit membership') + } +} + +/** Each provider owns a partition; one provider cannot evict another's immutable verdicts. */ +export class MergedReviewMembershipMemo { + private readonly receipts = new Map() + private readonly pending: CoalescedProbes = new Map() + + clear(): void { + this.receipts.clear() + this.pending.clear() + } + + peek(key: string): MergedReviewCommitMembership | undefined { + this.prune() + const receipt = this.receipts.get(key) + if (receipt?.failed) { + throw new MergedReviewMembershipUnavailableError() + } + return receipt?.value + } + + async read( + key: string, + load: () => Promise, + options: { refreshFailed?: boolean; bypass?: boolean } = {} + ): Promise { + this.prune() + const cached = this.receipts.get(key) + if (cached && !options.bypass && !(options.refreshFailed && cached.failed)) { + if (cached.failed) { + throw new MergedReviewMembershipUnavailableError() + } + return cached.value + } + return runCoalescedProbe( + this.pending, + key, + async (ownsKey) => { + try { + const value = await load() + if (ownsKey()) { + this.receipts.set(key, { + value, + expiresAt: Date.now() + (value === 'unknown' ? 5 * 60_000 : 6 * 60 * 60_000) + }) + this.prune() + } + return value + } catch { + if (ownsKey()) { + this.receipts.set(key, { + value: 'unknown', + failed: true, + expiresAt: Date.now() + 5 * 60_000 + }) + this.prune() + } + throw new MergedReviewMembershipUnavailableError() + } + }, + // A slow live walk stays shared; elapsed time alone must not multiply it. + Infinity, + { userRefresh: options.bypass || options.refreshFailed } + ) + } + + private prune(): void { + const now = Date.now() + for (const [key, receipt] of this.receipts) { + if (receipt.expiresAt <= now) { + this.receipts.delete(key) + } + } + while (this.receipts.size > 200) { + const key = this.receipts.keys().next().value + if (key === undefined) { + break + } + this.receipts.delete(key) + } + } +} diff --git a/src/main/source-control/review-current-head.ts b/src/main/source-control/review-current-head.ts new file mode 100644 index 00000000000..a74e7b387ad --- /dev/null +++ b/src/main/source-control/review-current-head.ts @@ -0,0 +1,23 @@ +import { gitExecFileAsync } from '../git/runner' +import { requireReachableGitRoute } from '../providers/execution-host-provider-dispatch' +import { getConnectionExecutionHostId } from '../../shared/execution-host' +import type { HostedReviewLocalGitOptions } from './hosted-review-git-options' + +export async function readCurrentReviewHead( + repoPath: string, + connectionId?: string | null, + options: HostedReviewLocalGitOptions = {}, + runGit = gitExecFileAsync +): Promise { + requireReachableGitRoute(getConnectionExecutionHostId(connectionId)) + try { + const result = await runGit(['rev-parse', 'HEAD'], { + cwd: repoPath, + ...(options.wslDistro ? { wslDistro: options.wslDistro } : {}), + ...(options.admissionTier ? { admissionTier: options.admissionTier } : {}) + }) + return result.stdout.trim() || null + } catch { + return null + } +} diff --git a/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.tsx b/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.tsx index 1ede5c869af..d17904031fc 100644 --- a/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.tsx +++ b/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.tsx @@ -36,11 +36,15 @@ function formatCheckTimestamp( } type CheckStatusLike = { + gitlabAllowedFailure?: boolean status: PRCheckDetail['status'] | (string & {}) | null | undefined conclusion: PRCheckDetail['conclusion'] | (string & {}) | null | undefined } function getCheckStatusLabel(check: CheckStatusLike, t: Translate = translate): string { + if (check.gitlabAllowedFailure === true && check.conclusion === 'neutral') { + return t('checks.gitlabAllowedFailure', 'Allowed to fail') + } const conclusion = check.conclusion ?? 'pending' switch (conclusion) { case 'success': diff --git a/src/renderer/src/components/github-item-dialog/inspect-pull-request/checks-tab-check-row.tsx b/src/renderer/src/components/github-item-dialog/inspect-pull-request/checks-tab-check-row.tsx index a427e1106bf..24db4565558 100644 --- a/src/renderer/src/components/github-item-dialog/inspect-pull-request/checks-tab-check-row.tsx +++ b/src/renderer/src/components/github-item-dialog/inspect-pull-request/checks-tab-check-row.tsx @@ -3,11 +3,11 @@ import { ChevronDown, CircleDashed } from 'lucide-react' import { cn } from '@/lib/utils' import { CHECK_COLOR, - CHECK_ICON + CHECK_ICON, + checkPresentationKey } from '@/components/right-sidebar/checks-panel/presentation/check-presentation' import type { CheckDetailsLoadState } from '@/components/github-checks-tab-state' import type { PRCheckDetail } from '../../../../../shared/github/check-types' -import { getCheckConclusion } from '@/components/pr-check-counts' import { getCheckDetailsKey, getCheckStatusLabel } from '@/components/github/pr-check-presentation' import { ChecksTabCheckDetails } from './checks-tab-check-details' import { useTranslate } from '@/i18n/use-translate' @@ -57,7 +57,7 @@ export function ChecksTabCheckRow({ onRetry: (check: PRCheckDetail, key: string) => void }): React.JSX.Element { const t = useTranslate() - const conclusion = getCheckConclusion(check) + const conclusion = checkPresentationKey(check) const Icon = CHECK_ICON[conclusion] ?? CircleDashed const color = CHECK_COLOR[conclusion] ?? 'text-muted-foreground' const statusLabel = getCheckStatusLabel(check, t) diff --git a/src/renderer/src/components/github/pr-check-presentation.ts b/src/renderer/src/components/github/pr-check-presentation.ts index 35cb292a5f5..b04177a5b29 100644 --- a/src/renderer/src/components/github/pr-check-presentation.ts +++ b/src/renderer/src/components/github/pr-check-presentation.ts @@ -8,6 +8,9 @@ import type { } from '../../../../shared/github/check-types' export function getCheckStatusLabel(check: PRCheckDetail, t: Translate = translate): string { + if (check.gitlabAllowedFailure === true && check.conclusion === 'neutral') { + return t('checks.gitlabAllowedFailure', 'Allowed to fail') + } const conclusion = getCheckConclusion(check) if (conclusion === 'success') { return t('auto.components.github.prCheckPresentation.successful', 'Successful') diff --git a/src/renderer/src/components/gitlab-item-dialog-parts.tsx b/src/renderer/src/components/gitlab-item-dialog-parts.tsx index ac5ca964159..63082528347 100644 --- a/src/renderer/src/components/gitlab-item-dialog-parts.tsx +++ b/src/renderer/src/components/gitlab-item-dialog-parts.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { ExternalLink, LoaderCircle } from 'lucide-react' +import { AlertTriangle, ExternalLink, LoaderCircle } from 'lucide-react' import { toast } from 'sonner' import { Button } from '@/components/ui/button' import CommentMarkdown from '@/components/sidebar/CommentMarkdown' @@ -42,6 +42,7 @@ export function jobStatusTone(status: string): string { case 'waiting_for_resource': case 'scheduled': return 'bg-sky-500/15 text-sky-700 dark:text-sky-300' + case 'warning': case 'manual': return 'bg-amber-500/15 text-amber-700 dark:text-amber-300' case 'canceled': @@ -204,12 +205,14 @@ export function PipelineJobRow({ onRetry: (job: GitLabPipelineJob) => void }): React.JSX.Element { const t = useTranslate() - const canRetry = ['failed', 'canceled', 'cancelled'].includes(job.status) + const allowedFailure = job.status === 'failed' && job.allowFailure === true + const canRetry = job.id > 0 && ['failed', 'canceled', 'cancelled'].includes(job.status) return (
-
+