From a090176de920404a4ea80ee7ef09e0cf3b1329a4 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sun, 31 May 2026 00:05:15 -0700 Subject: [PATCH] feat: close GitLab review parity gaps (#4001) --- src/main/gitlab/client-mr.test.ts | 299 ++++- src/main/gitlab/client.ts | 426 +++++++ src/main/gitlab/issues.test.ts | 9 +- src/main/gitlab/issues.ts | 14 +- .../gitlab/merge-request-creation.test.ts | 231 ++++ src/main/gitlab/merge-request-creation.ts | 303 +++++ src/main/gitlab/work-item-details.ts | 196 +++- src/main/ipc/gitlab.ts | 132 ++- src/main/runtime/orca-runtime.test.ts | 92 +- src/main/runtime/orca-runtime.ts | 110 ++ src/main/runtime/rpc/methods/gitlab.test.ts | 88 ++ src/main/runtime/rpc/methods/gitlab.ts | 102 ++ src/main/runtime/runtime-rpc.test.ts | 24 + src/main/runtime/runtime-rpc.ts | 1 + .../hosted-review-creation.test.ts | 80 +- .../source-control/hosted-review-creation.ts | 188 ++- src/preload/api-types.ts | 46 + src/preload/gitlab.ts | 37 + .../src/components/GitLabItemDialog.tsx | 1019 ++++++++++++++++- .../gitlab/gitlab-rate-limit-display.tsx | 168 +++ .../components/right-sidebar/ChecksPanel.tsx | 425 +++++-- .../right-sidebar/CreatePullRequestDialog.tsx | 77 +- ...{PRActions.tsx => HostedReviewActions.tsx} | 225 +++- .../right-sidebar/SourceControl.tsx | 158 ++- .../right-sidebar/checks-panel-content.tsx | 69 +- .../source-control-dropdown-items.test.ts | 46 +- .../source-control-dropdown-items.ts | 44 +- .../source-control-primary-action.test.ts | 21 + .../source-control-primary-action.ts | 14 +- .../src/components/settings/GitPane.tsx | 16 + .../src/components/settings/git-search.ts | 5 + src/renderer/src/web/web-preload-api.test.ts | 90 ++ src/renderer/src/web/web-preload-api.ts | 45 +- src/shared/gitlab-types.ts | 76 ++ src/shared/hosted-review-gitlab.test.ts | 72 ++ src/shared/hosted-review-gitlab.ts | 125 ++ src/shared/types.ts | 12 + 37 files changed, 4741 insertions(+), 344 deletions(-) create mode 100644 src/main/gitlab/merge-request-creation.test.ts create mode 100644 src/main/gitlab/merge-request-creation.ts create mode 100644 src/renderer/src/components/gitlab/gitlab-rate-limit-display.tsx rename src/renderer/src/components/right-sidebar/{PRActions.tsx => HostedReviewActions.tsx} (61%) create mode 100644 src/shared/hosted-review-gitlab.test.ts create mode 100644 src/shared/hosted-review-gitlab.ts diff --git a/src/main/gitlab/client-mr.test.ts b/src/main/gitlab/client-mr.test.ts index c8a7957c2..189ec6919 100644 --- a/src/main/gitlab/client-mr.test.ts +++ b/src/main/gitlab/client-mr.test.ts @@ -35,7 +35,20 @@ vi.mock('./gl-utils', async () => { } }) -import { getMergeRequest, getMergeRequestForBranch, listMergeRequests, updateMR } from './client' +import { + _resetGitLabRateLimitCache, + getMergeRequest, + getMergeRequestForBranch, + getJobTrace, + addMRInlineComment, + diagnoseAuth, + getRateLimit, + listMergeRequests, + resolveMRDiscussion, + retryJob, + updateMR, + updateMRReviewers +} from './client' describe('gitlab client — MR operations', () => { beforeEach(() => { @@ -47,6 +60,7 @@ describe('gitlab client — MR operations', () => { acquireMock.mockReset() releaseMock.mockReset() acquireMock.mockResolvedValue(undefined) + _resetGitLabRateLimitCache() getGlabKnownHostsMock.mockResolvedValue(['gitlab.com']) resolveIssueSourceMock.mockResolvedValue({ source: { host: 'gitlab.com', path: 'g/p' }, @@ -117,6 +131,63 @@ describe('gitlab client — MR operations', () => { }) }) + describe('diagnoseAuth', () => { + it('reports glab hosts from auth status', async () => { + glabExecFileAsyncMock.mockResolvedValueOnce({ + stdout: '✓ Logged in to gitlab.com as alice\n', + stderr: '' + }) + + await expect(diagnoseAuth()).resolves.toMatchObject({ + glabAvailable: true, + authenticated: true, + hosts: ['gitlab.com'], + activeHost: 'gitlab.com' + }) + }) + }) + + describe('getRateLimit', () => { + it('parses GitLab REST budget headers', async () => { + glabApiWithHeadersMock.mockResolvedValueOnce({ + body: '{}', + headers: { + 'ratelimit-limit': '2000', + 'ratelimit-remaining': '1997', + 'ratelimit-reset': '1780000000' + } + }) + + await expect( + getRateLimit({ host: 'gitlab.example.com', force: true }) + ).resolves.toMatchObject({ + ok: true, + snapshot: { + host: 'gitlab.example.com', + rest: { + limit: 2000, + remaining: 1997, + resetAt: 1780000000 + } + } + }) + expect(glabApiWithHeadersMock).toHaveBeenCalledWith([ + '--hostname', + 'gitlab.example.com', + 'user' + ]) + }) + + it('reports a null bucket when the host omits rate-limit headers', async () => { + glabApiWithHeadersMock.mockResolvedValueOnce({ body: '{}', headers: {} }) + + await expect(getRateLimit({ force: true })).resolves.toMatchObject({ + ok: true, + snapshot: { host: null, rest: null } + }) + }) + }) + describe('getMergeRequestForBranch', () => { it('finds the most recently updated MR for a branch across states', async () => { getProjectRefMock.mockResolvedValueOnce({ host: 'gitlab.com', path: 'g/p' }) @@ -411,4 +482,230 @@ describe('gitlab client — MR operations', () => { ) }) }) + + describe('resolveMRDiscussion', () => { + beforeEach(() => { + resolveIssueSourceMock.mockImplementation(async () => ({ + source: { host: 'git.internal', path: 'g/p' }, + fellBack: false + })) + }) + + it('updates the discussion resolved state through the selected SSH GitLab host', async () => { + glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: '{}' }) + + await expect( + resolveMRDiscussion('/repo', 12, 'discussion-1', true, 'upstream', 'conn-1') + ).resolves.toEqual({ ok: true }) + + expect(glabExecFileAsyncMock).toHaveBeenCalledWith( + [ + 'api', + '--hostname', + 'git.internal', + '-X', + 'PUT', + 'projects/g%2Fp/merge_requests/12/discussions/discussion-1', + '-f', + 'resolved=true' + ], + {} + ) + }) + + it('rejects an empty discussion id without calling glab', async () => { + await expect(resolveMRDiscussion('/repo', 12, ' ', true)).resolves.toEqual({ + ok: false, + error: 'Discussion id is required' + }) + + expect(glabExecFileAsyncMock).not.toHaveBeenCalled() + }) + }) + + describe('addMRInlineComment', () => { + beforeEach(() => { + resolveIssueSourceMock.mockImplementation(async () => ({ + source: { host: 'git.internal', path: 'g/p' }, + fellBack: false + })) + }) + + it('posts an inline discussion with GitLab position fields', async () => { + glabExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ + id: 'discussion-1', + notes: [ + { + id: 500, + author: { username: 'alice', avatar_url: 'https://example.com/a.png' }, + body: 'please fix', + created_at: '2026-05-05T10:00:00Z', + position: { new_path: 'src/app.ts', new_line: 12 } + } + ] + }) + }) + + await expect( + addMRInlineComment( + '/repo', + 12, + { + body: 'please fix', + path: 'src/app.ts', + line: 12, + baseSha: 'base', + startSha: 'start', + headSha: 'head' + }, + 'upstream', + 'conn-1' + ) + ).resolves.toMatchObject({ + ok: true, + comment: { + id: 500, + threadId: 'discussion-1', + path: 'src/app.ts', + line: 12 + } + }) + + expect(glabExecFileAsyncMock).toHaveBeenCalledWith( + [ + 'api', + '--hostname', + 'git.internal', + '-X', + 'POST', + 'projects/g%2Fp/merge_requests/12/discussions', + '-f', + 'body=please fix', + '-f', + 'position[position_type]=text', + '-f', + 'position[base_sha]=base', + '-f', + 'position[start_sha]=start', + '-f', + 'position[head_sha]=head', + '-f', + 'position[old_path]=src/app.ts', + '-f', + 'position[new_path]=src/app.ts', + '-f', + 'position[new_line]=12' + ], + {} + ) + }) + }) + + describe('job CI operations', () => { + beforeEach(() => { + resolveIssueSourceMock.mockImplementation(async () => ({ + source: { host: 'git.internal', path: 'g/p' }, + fellBack: false + })) + }) + + it('fetches a job trace through the selected SSH GitLab host', async () => { + glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: 'trace output' }) + + await expect(getJobTrace('/repo', 99, 'upstream', 'conn-1')).resolves.toEqual({ + ok: true, + trace: 'trace output' + }) + + expect(glabExecFileAsyncMock).toHaveBeenCalledWith( + ['api', '--hostname', 'git.internal', 'projects/g%2Fp/jobs/99/trace'], + {} + ) + }) + + it('retries a job through the selected SSH GitLab host', async () => { + glabExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ + id: 100, + pipeline: { id: 50 }, + name: 'test', + stage: 'test', + status: 'pending', + web_url: 'https://git.internal/g/p/-/jobs/100', + duration: null + }) + }) + + await expect(retryJob('/repo', 99, 'upstream', 'conn-1')).resolves.toEqual({ + ok: true, + job: { + id: 100, + pipelineId: 50, + name: 'test', + stage: 'test', + status: 'pending', + webUrl: 'https://git.internal/g/p/-/jobs/100', + duration: null + } + }) + + expect(glabExecFileAsyncMock).toHaveBeenCalledWith( + ['api', '--hostname', 'git.internal', '-X', 'POST', 'projects/g%2Fp/jobs/99/retry'], + {} + ) + }) + }) + + describe('updateMRReviewers', () => { + beforeEach(() => { + resolveIssueSourceMock.mockImplementation(async () => ({ + source: { host: 'git.internal', path: 'g/p' }, + fellBack: false + })) + }) + + it('sets reviewers through reviewer_ids on the selected SSH GitLab host', async () => { + glabExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ + reviewers: [ + { + id: 1, + username: 'alice', + name: 'Alice', + avatar_url: 'https://example.com/a.png', + state: 'active' + } + ] + }) + }) + + await expect(updateMRReviewers('/repo', 12, [1], 'upstream', 'conn-1')).resolves.toEqual({ + ok: true, + reviewers: [ + { + id: 1, + username: 'alice', + name: 'Alice', + avatarUrl: 'https://example.com/a.png', + state: 'active' + } + ] + }) + + expect(glabExecFileAsyncMock).toHaveBeenCalledWith( + [ + 'api', + '--hostname', + 'git.internal', + '-X', + 'PUT', + 'projects/g%2Fp/merge_requests/12', + '-f', + 'reviewer_ids[]=1' + ], + {} + ) + }) + }) }) diff --git a/src/main/gitlab/client.ts b/src/main/gitlab/client.ts index 06afc5fff..122efd7b8 100644 --- a/src/main/gitlab/client.ts +++ b/src/main/gitlab/client.ts @@ -3,10 +3,20 @@ co-locating GitLab MR/issue/work-item operations keeps the concurrency acquire/release pattern obvious across operations. */ import type { ClassifiedError, + GitLabAssignableUser, + GitLabAuthDiagnostic, + GitLabDiscussionResolveResult, + GitLabJobTraceResult, GitLabPagedResult, + GitLabPipelineJob, + GitLabRateLimitSnapshot, + GitLabMRInlineCommentInput, + GitLabMRReviewersUpdateResult, + GitLabRetryJobResult, GitLabTodo, GitLabViewer, GitLabWorkItem, + GetGitLabRateLimitResult, IssueSourcePreference, ListMergeRequestsResult, MRComment, @@ -25,6 +35,7 @@ import { glabRepoExecOptions, glabApiWithHeaders, glabExecFileAsync, + parseGlabAuthStatusHosts, release, resolveIssueSource, type ProjectRef @@ -37,6 +48,9 @@ function encodedProject(projectPath: string): string { return encodeURIComponent(projectPath) } +const GITLAB_RATE_LIMIT_CACHE_TTL_MS = 30_000 +const gitLabRateLimitCache = new Map() + /** * Get the authenticated GitLab viewer. Mirrors getAuthenticatedViewer * from the GitHub client — returns null when glab is unavailable, the @@ -61,6 +75,119 @@ export async function getAuthenticatedViewer(): Promise { } } +export async function diagnoseAuth(): Promise { + const envTokenInProcess = process.env.GITLAB_TOKEN + ? 'GITLAB_TOKEN' + : process.env.GLAB_TOKEN + ? 'GLAB_TOKEN' + : null + try { + const { stdout, stderr } = await glabExecFileAsync(['auth', 'status']) + const output = `${stdout}\n${stderr}` + const hosts = parseGlabAuthStatusHosts(output) + return { + glabAvailable: true, + authenticated: + /logged in|authenticated|token/i.test(output) && !/not logged in/i.test(output), + hosts, + activeHost: hosts[0] ?? null, + envTokenInProcess, + error: null + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + return { + glabAvailable: !/ENOENT|not found|spawn/i.test(message), + authenticated: false, + hosts: [], + activeHost: null, + envTokenInProcess, + error: message + } + } +} + +function parseRateLimitHeader( + headers: Record, + keys: readonly string[] +): number | null { + for (const key of keys) { + const parsed = Number.parseInt(headers[key], 10) + if (Number.isFinite(parsed)) { + return parsed + } + } + return null +} + +function parseRateLimitResetAt(headers: Record): number | null { + const numeric = parseRateLimitHeader(headers, ['ratelimit-reset', 'x-ratelimit-reset']) + if (numeric !== null) { + return numeric + } + const resetTime = headers['ratelimit-resettime'] ?? headers['x-ratelimit-resettime'] + if (!resetTime) { + return null + } + const millis = Date.parse(resetTime) + return Number.isFinite(millis) ? Math.floor(millis / 1000) : null +} + +function parseGitLabRateLimitSnapshot( + headers: Record, + host: string | null +): GitLabRateLimitSnapshot { + const limit = parseRateLimitHeader(headers, ['ratelimit-limit', 'x-ratelimit-limit']) + const remaining = parseRateLimitHeader(headers, ['ratelimit-remaining', 'x-ratelimit-remaining']) + const resetAt = parseRateLimitResetAt(headers) + return { + host, + fetchedAt: Date.now(), + rest: + limit === null && remaining === null && resetAt === null + ? null + : { + limit: limit ?? 0, + remaining: remaining ?? 0, + resetAt + } + } +} + +/** @internal — test-only */ +export function _resetGitLabRateLimitCache(): void { + gitLabRateLimitCache.clear() +} + +export async function getRateLimit(options?: { + force?: boolean + host?: string | null +}): Promise { + const host = options?.host?.trim() || null + const cacheKey = host ?? 'default' + const cached = gitLabRateLimitCache.get(cacheKey) + if (!options?.force && cached && Date.now() - cached.fetchedAt < GITLAB_RATE_LIMIT_CACHE_TTL_MS) { + return { ok: true, snapshot: cached } + } + + await acquire() + try { + // Why: GitLab.com and self-managed GitLab instances expose REST budget + // headers inconsistently. Query a cheap authenticated endpoint and report + // the headers when present; a null bucket means this host omitted them. + const args = host ? ['--hostname', host, 'user'] : ['user'] + const { headers } = await glabApiWithHeaders(args) + const snapshot = parseGitLabRateLimitSnapshot(headers, host) + gitLabRateLimitCache.set(cacheKey, snapshot) + return { ok: true, snapshot } + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + return { ok: false, error: message } + } finally { + release() + } +} + /** * Resolve a project's full GitLab project ref (host + path). Mirrors * github/getRepoSlug. Returns null for non-GitLab remotes. @@ -774,6 +901,305 @@ export async function addMRComment( ) } +export async function addMRInlineComment( + repoPath: string, + iid: number, + input: GitLabMRInlineCommentInput, + preference?: IssueSourcePreference, + connectionId?: string | null, + projectRef?: ProjectRef | null +): Promise<{ ok: true; comment: MRComment } | { ok: false; error: string }> { + return withProjectRef<{ ok: true; comment: MRComment } | { ok: false; error: string }>( + repoPath, + preference, + connectionId, + projectRef, + async (projectRef) => { + const body = input.body.trim() + if (!body) { + return { ok: false, error: 'Comment body is required' } + } + await acquire() + try { + const oldPath = input.oldPath ?? input.path + const { stdout } = await glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(projectRef, connectionId), + '-X', + 'POST', + `projects/${encodedProject(projectRef.path)}/merge_requests/${iid}/discussions`, + '-f', + `body=${body}`, + '-f', + 'position[position_type]=text', + '-f', + `position[base_sha]=${input.baseSha}`, + '-f', + `position[start_sha]=${input.startSha}`, + '-f', + `position[head_sha]=${input.headSha}`, + '-f', + `position[old_path]=${oldPath}`, + '-f', + `position[new_path]=${input.path}`, + '-f', + `position[new_line]=${input.line}` + ], + glabRepoExecOptions(repoPath, connectionId) + ) + const data = JSON.parse(stdout) as { + id?: string + notes?: { + id?: number + author?: { username?: string; avatar_url?: string; state?: string } | null + body?: string + created_at?: string + position?: { new_path?: string; new_line?: number } | null + }[] + } + const note = data.notes?.[0] + return { + ok: true, + comment: { + id: note?.id ?? Date.now(), + author: note?.author?.username ?? 'You', + authorAvatarUrl: note?.author?.avatar_url ?? '', + body: note?.body ?? body, + createdAt: note?.created_at ?? new Date().toISOString(), + url: '', + threadId: data.id, + isResolved: false, + isBot: note?.author?.state === 'bot', + path: note?.position?.new_path ?? input.path, + line: note?.position?.new_line ?? input.line + } + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + return { ok: false, error: classifyGlabError(msg).message } + } finally { + release() + } + }, + { ok: false, error: 'Could not resolve GitLab project for this repository' } + ) +} + +export async function resolveMRDiscussion( + repoPath: string, + iid: number, + discussionId: string, + resolved: boolean, + preference?: IssueSourcePreference, + connectionId?: string | null, + projectRef?: ProjectRef | null +): Promise { + return withProjectRef( + repoPath, + preference, + connectionId, + projectRef, + async (projectRef) => { + const trimmedDiscussionId = discussionId.trim() + if (!trimmedDiscussionId) { + return { ok: false, error: 'Discussion id is required' } + } + await acquire() + try { + // Why: GitLab resolves/reopens the whole discussion thread, not a single + // note; this mirrors GitHub's thread-level resolve mutation. + await glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(projectRef, connectionId), + '-X', + 'PUT', + `projects/${encodedProject(projectRef.path)}/merge_requests/${iid}/discussions/${encodeURIComponent(trimmedDiscussionId)}`, + '-f', + `resolved=${resolved ? 'true' : 'false'}` + ], + glabRepoExecOptions(repoPath, connectionId) + ) + return { ok: true } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + return { ok: false, error: classifyGlabError(msg).message } + } finally { + release() + } + }, + { ok: false, error: 'Could not resolve GitLab project for this repository' } + ) +} + +function mapRetriedPipelineJob( + data: { + id?: number + pipeline?: { id?: number | null } | null + name?: string + stage?: string + status?: string + web_url?: string + duration?: number | null + }, + fallbackJobId: number +): GitLabPipelineJob { + return { + id: data.id ?? fallbackJobId, + ...(typeof data.pipeline?.id === 'number' ? { pipelineId: data.pipeline.id } : {}), + name: data.name ?? '', + stage: data.stage ?? '', + status: data.status ?? '', + webUrl: data.web_url ?? '', + duration: typeof data.duration === 'number' ? data.duration : null + } +} + +function mapGitLabReviewer(raw: { + id?: number + username?: string | null + name?: string | null + avatar_url?: string | null + state?: string | null +}): GitLabAssignableUser | null { + if (!raw.username) { + return null + } + return { + ...(typeof raw.id === 'number' ? { id: raw.id } : {}), + username: raw.username, + name: raw.name ?? null, + avatarUrl: raw.avatar_url ?? '', + ...(raw.state !== undefined ? { state: raw.state } : {}) + } +} + +export async function updateMRReviewers( + repoPath: string, + iid: number, + reviewerIds: number[], + preference?: IssueSourcePreference, + connectionId?: string | null, + projectRef?: ProjectRef | null +): Promise { + return withProjectRef( + repoPath, + preference, + connectionId, + projectRef, + async (projectRef) => { + await acquire() + try { + const fields = + reviewerIds.length > 0 + ? reviewerIds.map((id) => ['-f', `reviewer_ids[]=${id}`]).flat() + : ['-f', 'reviewer_ids='] + const { stdout } = await glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(projectRef, connectionId), + '-X', + 'PUT', + `projects/${encodedProject(projectRef.path)}/merge_requests/${iid}`, + ...fields + ], + glabRepoExecOptions(repoPath, connectionId) + ) + const data = JSON.parse(stdout) as { reviewers?: Parameters[0][] } + return { + ok: true, + reviewers: (data.reviewers ?? []) + .map(mapGitLabReviewer) + .filter((u): u is GitLabAssignableUser => !!u) + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + return { ok: false, error: classifyGlabError(msg).message } + } finally { + release() + } + }, + { ok: false, error: 'Could not resolve GitLab project for this repository' } + ) +} + +export async function getJobTrace( + repoPath: string, + jobId: number, + preference?: IssueSourcePreference, + connectionId?: string | null, + projectRef?: ProjectRef | null +): Promise { + return withProjectRef( + repoPath, + preference, + connectionId, + projectRef, + async (projectRef) => { + await acquire() + try { + const { stdout } = await glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(projectRef, connectionId), + `projects/${encodedProject(projectRef.path)}/jobs/${jobId}/trace` + ], + glabRepoExecOptions(repoPath, connectionId) + ) + return { ok: true, trace: stdout } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + return { ok: false, error: classifyGlabError(msg).message } + } finally { + release() + } + }, + { ok: false, error: 'Could not resolve GitLab project for this repository' } + ) +} + +export async function retryJob( + repoPath: string, + jobId: number, + preference?: IssueSourcePreference, + connectionId?: string | null, + projectRef?: ProjectRef | null +): Promise { + return withProjectRef( + repoPath, + preference, + connectionId, + projectRef, + async (projectRef) => { + await acquire() + try { + const { stdout } = await glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(projectRef, connectionId), + '-X', + 'POST', + `projects/${encodedProject(projectRef.path)}/jobs/${jobId}/retry` + ], + glabRepoExecOptions(repoPath, connectionId) + ) + const trimmed = stdout.trim() + return { + ok: true, + ...(trimmed ? { job: mapRetriedPipelineJob(JSON.parse(trimmed), jobId) } : {}) + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + return { ok: false, error: classifyGlabError(msg).message } + } finally { + release() + } + }, + { ok: false, error: 'Could not resolve GitLab project for this repository' } + ) +} + export async function updateMR( repoPath: string, iid: number, diff --git a/src/main/gitlab/issues.test.ts b/src/main/gitlab/issues.test.ts index 14712d8f6..9fc2303ec 100644 --- a/src/main/gitlab/issues.test.ts +++ b/src/main/gitlab/issues.test.ts @@ -256,7 +256,8 @@ describe('gitlab issue operations', () => { glabExecFileAsyncMock .mockResolvedValueOnce({ stdout: 'bug\nfeature\n' }) .mockResolvedValueOnce({ - stdout: '{"username":"alice","name":"Alice","avatar_url":"https://example.com/a.png"}\n' + stdout: + '{"id":12,"username":"alice","name":"Alice","avatar_url":"https://example.com/a.png","state":"active"}\n' }) await expect(listLabels('/repo-root', 'upstream', 'conn-1')).resolves.toEqual([ @@ -265,9 +266,11 @@ describe('gitlab issue operations', () => { ]) await expect(listAssignableUsers('/repo-root', 'upstream', 'conn-1')).resolves.toEqual([ { + id: 12, username: 'alice', name: 'Alice', - avatarUrl: 'https://example.com/a.png' + avatarUrl: 'https://example.com/a.png', + state: 'active' } ]) @@ -287,7 +290,7 @@ describe('gitlab issue operations', () => { '--paginate', 'projects/stablyai%2Forca/members/all?per_page=100', '--jq', - '.[] | {username, name, avatar_url}' + '.[] | {id, username, name, avatar_url, state}' ]) }) diff --git a/src/main/gitlab/issues.ts b/src/main/gitlab/issues.ts index 8f9278bd7..b2ced1e35 100644 --- a/src/main/gitlab/issues.ts +++ b/src/main/gitlab/issues.ts @@ -474,11 +474,17 @@ export async function listAssignableUsers( '--paginate', `projects/${encodedProject(projectRef.path)}/members/all?per_page=100`, '--jq', - '.[] | {username, name, avatar_url}' + '.[] | {id, username, name, avatar_url, state}' ], glabRepoExecOptions(repoPath, connectionId) ) - type RESTMember = { username?: string; name?: string | null; avatar_url?: string | null } + type RESTMember = { + id?: number + username?: string + name?: string | null + avatar_url?: string | null + state?: string | null + } const users: GitLabAssignableUser[] = [] for (const line of stdout.split('\n')) { const trimmed = line.trim() @@ -489,9 +495,11 @@ export async function listAssignableUsers( const user = JSON.parse(trimmed) as RESTMember if (user.username) { users.push({ + ...(typeof user.id === 'number' ? { id: user.id } : {}), username: user.username, name: user.name ?? null, - avatarUrl: user.avatar_url ?? '' + avatarUrl: user.avatar_url ?? '', + ...(user.state !== undefined ? { state: user.state } : {}) }) } } catch { diff --git a/src/main/gitlab/merge-request-creation.test.ts b/src/main/gitlab/merge-request-creation.test.ts new file mode 100644 index 000000000..742413c08 --- /dev/null +++ b/src/main/gitlab/merge-request-creation.test.ts @@ -0,0 +1,231 @@ +/* eslint-disable max-lines -- Why: MR creation tests share glab and SSH filesystem mocks across CLI, template, and duplicate-detection paths. */ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + getProjectSlugMock, + glabExecFileAsyncMock, + glabHostnameArgsMock, + glabRepoExecOptionsMock, + acquireMock, + releaseMock, + getSshFilesystemProviderMock +} = vi.hoisted(() => ({ + getProjectSlugMock: vi.fn(), + glabExecFileAsyncMock: vi.fn(), + glabHostnameArgsMock: vi.fn((projectRef: { host: string }) => ['--hostname', projectRef.host]), + glabRepoExecOptionsMock: vi.fn((repoPath: string, connectionId?: string | null) => + connectionId ? {} : { cwd: repoPath } + ), + acquireMock: vi.fn(), + releaseMock: vi.fn(), + getSshFilesystemProviderMock: vi.fn() +})) + +vi.mock('./client', () => ({ + getProjectSlug: getProjectSlugMock +})) + +vi.mock('./gl-utils', () => ({ + acquire: acquireMock, + release: releaseMock, + glabExecFileAsync: glabExecFileAsyncMock, + glabHostnameArgs: glabHostnameArgsMock, + glabRepoExecOptions: glabRepoExecOptionsMock +})) + +vi.mock('../providers/ssh-filesystem-dispatch', () => ({ + getSshFilesystemProvider: getSshFilesystemProviderMock +})) + +import { createGitLabMergeRequest } from './merge-request-creation' + +describe('createGitLabMergeRequest', () => { + beforeEach(() => { + getProjectSlugMock.mockReset() + glabExecFileAsyncMock.mockReset() + glabHostnameArgsMock.mockClear() + glabRepoExecOptionsMock.mockClear() + acquireMock.mockReset() + releaseMock.mockReset() + getSshFilesystemProviderMock.mockReset() + acquireMock.mockResolvedValue(undefined) + getProjectSlugMock.mockResolvedValue({ host: 'gitlab.com', path: 'acme/widgets' }) + }) + + it('creates a GitLab merge request with normalized refs', async () => { + glabExecFileAsyncMock.mockResolvedValueOnce({ + stdout: 'https://gitlab.com/acme/widgets/-/merge_requests/42\n', + stderr: '' + }) + + await expect( + createGitLabMergeRequest('/repo-root', { + provider: 'gitlab', + base: 'origin/main', + head: 'refs/heads/feature/create-mr', + title: ' Create MR UI ', + body: 'Body text', + draft: true + }) + ).resolves.toEqual({ + ok: true, + number: 42, + url: 'https://gitlab.com/acme/widgets/-/merge_requests/42' + }) + + const [args, options] = glabExecFileAsyncMock.mock.calls[0] + expect(args).toEqual( + expect.arrayContaining([ + 'mr', + 'create', + '-R', + 'acme/widgets', + '--target-branch', + 'main', + '--source-branch', + 'feature/create-mr', + '--title', + 'Create MR UI', + '--description', + 'Body text', + '--draft' + ]) + ) + expect(args).toEqual(expect.arrayContaining(['--hostname', 'gitlab.com'])) + expect(options).toMatchObject({ + cwd: '/repo-root', + timeout: 60_000, + idempotent: false + }) + expect(acquireMock).toHaveBeenCalledOnce() + expect(releaseMock).toHaveBeenCalledOnce() + }) + + it('creates SSH-backed merge requests without using the remote path as a local cwd', async () => { + glabExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ + iid: 45, + web_url: 'https://gitlab.com/acme/widgets/-/merge_requests/45' + }), + stderr: '' + }) + + await expect( + createGitLabMergeRequest( + '/remote/repo-root', + { + provider: 'gitlab', + base: 'main', + head: 'feature/ssh-create-mr', + title: 'SSH Create MR' + }, + 'ssh-1' + ) + ).resolves.toEqual({ + ok: true, + number: 45, + url: 'https://gitlab.com/acme/widgets/-/merge_requests/45' + }) + + expect(getProjectSlugMock).toHaveBeenCalledWith('/remote/repo-root', 'ssh-1') + const [args, options] = glabExecFileAsyncMock.mock.calls[0] + expect(args).toEqual( + expect.arrayContaining([ + 'mr', + 'create', + '-R', + 'acme/widgets', + '--target-branch', + 'main', + '--source-branch', + 'feature/ssh-create-mr' + ]) + ) + expect(options).toMatchObject({ + timeout: 60_000, + idempotent: false + }) + expect(options).not.toHaveProperty('cwd') + }) + + it('reads merge request templates from the SSH filesystem provider', async () => { + const readRemoteFile = vi.fn(async (path: string) => { + if (path === '/remote/repo-root/.gitlab/merge_request_templates/Default.md') { + return { content: 'Remote MR template body', isBinary: false } + } + throw new Error('missing template') + }) + getSshFilesystemProviderMock.mockReturnValue({ readFile: readRemoteFile }) + glabExecFileAsyncMock.mockResolvedValueOnce({ + stdout: 'https://gitlab.com/acme/widgets/-/merge_requests/46\n', + stderr: '' + }) + + await expect( + createGitLabMergeRequest( + '/remote/repo-root', + { + provider: 'gitlab', + base: 'main', + head: 'feature/ssh-template', + title: 'SSH Template MR', + body: '', + useTemplate: true + }, + 'ssh-1' + ) + ).resolves.toEqual({ + ok: true, + number: 46, + url: 'https://gitlab.com/acme/widgets/-/merge_requests/46' + }) + + const [args] = glabExecFileAsyncMock.mock.calls[0] + expect(readRemoteFile).toHaveBeenCalledWith( + '/remote/repo-root/.gitlab/merge_request_templates/Default.md' + ) + expect(args[args.indexOf('--description') + 1]).toBe('Remote MR template body') + }) + + it('returns an existing merge request when GitLab reports a duplicate', async () => { + glabExecFileAsyncMock + .mockRejectedValueOnce(new Error('merge request already exists')) + .mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + iid: 77, + web_url: 'https://gitlab.com/acme/widgets/-/merge_requests/77' + } + ]), + stderr: '' + }) + + await expect( + createGitLabMergeRequest('/repo-root', { + provider: 'gitlab', + base: 'main', + head: 'feature/existing', + title: 'Existing MR' + }) + ).resolves.toEqual({ + ok: false, + code: 'already_exists', + error: 'A merge request already exists for this branch.', + existingReview: { + number: 77, + url: 'https://gitlab.com/acme/widgets/-/merge_requests/77' + } + }) + + expect(glabExecFileAsyncMock.mock.calls[1][0]).toEqual( + expect.arrayContaining([ + 'mr', + 'list', + '--source-branch', + 'feature/existing', + '--target-branch', + 'main' + ]) + ) + }) +}) diff --git a/src/main/gitlab/merge-request-creation.ts b/src/main/gitlab/merge-request-creation.ts new file mode 100644 index 000000000..9dee1b66e --- /dev/null +++ b/src/main/gitlab/merge-request-creation.ts @@ -0,0 +1,303 @@ +import { readFile } from 'fs/promises' +import { join } from 'path' +import type { CreateHostedReviewInput, CreateHostedReviewResult } from '../../shared/hosted-review' +import { + normalizeHostedReviewBaseRef, + normalizeHostedReviewHeadRef +} from '../../shared/hosted-review-refs' +import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' +import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths' +import { getProjectSlug } from './client' +import { + acquire, + glabExecFileAsync, + glabHostnameArgs, + glabRepoExecOptions, + release, + type ProjectRef +} from './gl-utils' + +function execErrorMessage(error: unknown): string { + if (error instanceof Error) { + const maybeExec = error as Error & { stderr?: unknown; stdout?: unknown } + return [maybeExec.stderr, maybeExec.stdout, error.message] + .filter((value): value is string => typeof value === 'string' && value.trim().length > 0) + .join('\n') + .trim() + } + return String(error) +} + +function classifyCreateMRError(error: unknown): CreateHostedReviewResult { + const message = execErrorMessage(error) + if (message) { + console.warn('createGitLabMergeRequest failed:', message) + } + const lower = message.toLowerCase() + if ( + lower.includes('not logged') || + lower.includes('not authenticated') || + lower.includes('authentication') || + lower.includes('glab auth login') || + lower.includes('http 401') + ) { + return { + ok: false, + code: 'auth_required', + error: + 'Create MR failed: GitLab is not authenticated. Next step: run glab auth login in this environment.' + } + } + if (lower.includes('already exists') || lower.includes('merge request already exists')) { + return { + ok: false, + code: 'already_exists', + error: 'A merge request already exists for this branch.' + } + } + if (lower.includes('timed out') || lower.includes('timeout')) { + return { + ok: false, + code: 'unknown_completion', + error: 'MR creation may have completed. Refreshing branch review state...' + } + } + if (lower.includes('validation failed') || lower.includes('http 422')) { + return { + ok: false, + code: 'validation', + error: + 'Create MR failed: GitLab rejected the merge request. Check the base branch and branch state, then try again.' + } + } + return { + ok: false, + code: 'unknown', + error: 'Create MR failed: GitLab could not create the merge request. Try again in a moment.' + } +} + +function parseMergeRequestPayload(stdout: string): { number: number; url: string } | null { + const trimmed = stdout.trim() + if (!trimmed) { + return null + } + try { + const parsed = JSON.parse(trimmed) as { + iid?: unknown + number?: unknown + web_url?: unknown + webUrl?: unknown + url?: unknown + } + const number = Number(parsed.iid ?? parsed.number) + const url = + typeof parsed.web_url === 'string' + ? parsed.web_url.trim() + : typeof parsed.webUrl === 'string' + ? parsed.webUrl.trim() + : typeof parsed.url === 'string' + ? parsed.url.trim() + : '' + if (Number.isInteger(number) && number > 0 && url) { + return { number, url } + } + } catch { + // Fall through to URL parsing for glab's normal text output. + } + const urlMatch = trimmed.match(/https?:\/\/[^\s]+\/-\/merge_requests\/(\d+)/) + if (!urlMatch) { + return null + } + return { number: Number(urlMatch[1]), url: urlMatch[0] } +} + +async function findOpenMRByHeadBase(args: { + repoPath: string + projectRef: ProjectRef + head: string + base: string + connectionId?: string | null +}): Promise<{ number: number; url: string } | null> { + const { stdout } = await glabExecFileAsync( + [ + 'mr', + 'list', + '-R', + args.projectRef.path, + '--source-branch', + args.head, + '--target-branch', + args.base, + '--per-page', + '2', + '--output', + 'json', + ...glabHostnameArgs(args.projectRef, args.connectionId) + ], + glabRepoExecOptions(args.repoPath, args.connectionId) + ) + const list = JSON.parse(stdout) as { + iid?: number + number?: number + web_url?: string + webUrl?: string + url?: string + }[] + if (list.length !== 1) { + return null + } + return parseMergeRequestPayload(JSON.stringify(list[0])) +} + +async function readMergeRequestTemplate( + repoPath: string, + connectionId?: string | null +): Promise { + const relativeCandidates = [ + '.gitlab/merge_request_templates/Default.md', + '.gitlab/merge_request_templates/default.md', + '.gitlab/merge_request_template.md', + '.gitlab/MERGE_REQUEST_TEMPLATE.md' + ] + const remoteProvider = connectionId ? getSshFilesystemProvider(connectionId) : undefined + if (connectionId && !remoteProvider) { + return '' + } + for (const relativeCandidate of relativeCandidates) { + try { + if (remoteProvider) { + const result = await remoteProvider.readFile( + joinWorktreeRelativePath(repoPath, relativeCandidate) + ) + if (result.isBinary) { + continue + } + return result.content + } + return await readFile(join(repoPath, relativeCandidate), 'utf8') + } catch { + // Try the next conventional GitLab merge-request template path. + } + } + return '' +} + +export async function createGitLabMergeRequest( + repoPath: string, + input: CreateHostedReviewInput, + connectionId?: string | null +): Promise { + if (input.provider !== 'gitlab') { + return { + ok: false, + code: 'unsupported_provider', + error: 'Creating reviews for this provider is not supported yet.' + } + } + + const projectRef = await getProjectSlug(repoPath, connectionId) + if (!projectRef) { + return { + ok: false, + code: 'unsupported_provider', + error: 'Creating merge requests requires a GitLab remote.' + } + } + + const base = normalizeHostedReviewBaseRef(input.base) + const head = input.head ? normalizeHostedReviewHeadRef(input.head) || undefined : undefined + const title = input.title.trim() + if (!base || !title) { + return { + ok: false, + code: 'validation', + error: 'Create MR failed: base branch and title are required.' + } + } + if (head && head.toLowerCase() === base.toLowerCase()) { + return { + ok: false, + code: 'validation', + error: 'Create MR failed: choose a different base branch before creating a merge request.' + } + } + + await acquire() + try { + const body = + input.useTemplate && !input.body?.trim() + ? await readMergeRequestTemplate(repoPath, connectionId) + : (input.body ?? '') + const createArgs = [ + 'mr', + 'create', + '-R', + projectRef.path, + '--target-branch', + base, + '--title', + title, + '--description', + body, + '--yes', + ...glabHostnameArgs(projectRef, connectionId) + ] + if (head) { + createArgs.push('--source-branch', head) + } + if (input.draft) { + createArgs.push('--draft') + } + try { + const { stdout } = await glabExecFileAsync(createArgs, { + ...glabRepoExecOptions(repoPath, connectionId), + timeout: 60_000, + idempotent: false + }) + const created = parseMergeRequestPayload(stdout) + if (created) { + return { ok: true, ...created } + } + const found = head + ? await findOpenMRByHeadBase({ repoPath, projectRef, head, base, connectionId }).catch( + () => null + ) + : null + if (found) { + return { ok: true, ...found } + } + return { + ok: false, + code: 'unknown_completion', + error: 'MR creation may have completed. Refreshing branch review state...' + } + } catch (error) { + const classified = classifyCreateMRError(error) + if ( + !classified.ok && + (classified.code === 'already_exists' || classified.code === 'unknown_completion') && + head + ) { + const existing = await findOpenMRByHeadBase({ + repoPath, + projectRef, + head, + base, + connectionId + }).catch(() => null) + if (existing) { + return { + ok: false, + code: 'already_exists', + error: 'A merge request already exists for this branch.', + existingReview: existing + } + } + } + return classified + } + } finally { + release() + } +} diff --git a/src/main/gitlab/work-item-details.ts b/src/main/gitlab/work-item-details.ts index ddec56a3d..8cb45f1df 100644 --- a/src/main/gitlab/work-item-details.ts +++ b/src/main/gitlab/work-item-details.ts @@ -1,8 +1,12 @@ +/* eslint-disable max-lines -- Why: aggregated detail-fetch for GitLabItemDialog spans issues, MRs, comments, pipelines, reviewers, approvals, and changed files; splitting would obscure the shared fetch context. */ // Why: aggregated detail-fetch for GitLabItemDialog. Parallel of // src/main/github/work-item-details.ts but scoped to v1 surface — -// description body, flattened discussion notes, MR pipeline jobs. -// Files / inline review-comment positioning / approvals are deferred. +// description body, flattened discussion notes, MR pipeline jobs/reviewers. +// Files / inline review-comment positioning are deferred. import type { + GitLabAssignableUser, + GitLabMRApprovalState, + GitLabMRFile, GitLabPipelineJob, GitLabWorkItem, GitLabWorkItemDetails, @@ -108,9 +112,31 @@ type GitLabRawJob = { duration?: number | null } -function mapPipelineJob(raw: GitLabRawJob): GitLabPipelineJob { +type GitLabRawUser = { + id?: number + username?: string | null + name?: string | null + avatar_url?: string | null + state?: string | null +} + +function mapGitLabUser(raw: GitLabRawUser | null | undefined): GitLabAssignableUser | null { + if (!raw?.username) { + return null + } + return { + ...(typeof raw.id === 'number' ? { id: raw.id } : {}), + username: raw.username, + name: raw.name ?? null, + avatarUrl: raw.avatar_url ?? '', + ...(raw.state !== undefined ? { state: raw.state } : {}) + } +} + +function mapPipelineJob(raw: GitLabRawJob, pipelineId: number): GitLabPipelineJob { return { id: raw.id ?? 0, + pipelineId, name: raw.name ?? '', stage: raw.stage ?? '', status: raw.status ?? '', @@ -135,7 +161,73 @@ async function fetchPipelineJobs( glabRepoExecOptions(repoPath, connectionId) ) const data = JSON.parse(stdout) as GitLabRawJob[] - return data.map(mapPipelineJob) + return data.map((job) => mapPipelineJob(job, pipelineId)) +} + +function countDiffLines(diff: string): { additions: number; deletions: number } { + let additions = 0 + let deletions = 0 + for (const line of diff.split('\n')) { + if (line.startsWith('+++') || line.startsWith('---')) { + continue + } + if (line.startsWith('+')) { + additions += 1 + } else if (line.startsWith('-')) { + deletions += 1 + } + } + return { additions, deletions } +} + +function mapMRFile(raw: { + new_path?: string + old_path?: string + diff?: string + new_file?: boolean + deleted_file?: boolean + renamed_file?: boolean + binary?: boolean + too_large?: boolean +}): GitLabMRFile { + const diff = raw.diff ?? '' + const counts = countDiffLines(diff) + const status = raw.new_file + ? 'added' + : raw.deleted_file + ? 'removed' + : raw.renamed_file + ? 'renamed' + : 'modified' + return { + path: raw.new_path ?? raw.old_path ?? '', + ...(raw.old_path && raw.old_path !== raw.new_path ? { oldPath: raw.old_path } : {}), + status, + additions: counts.additions, + deletions: counts.deletions, + isBinary: Boolean(raw.binary || raw.too_large || !diff), + ...(diff ? { diff } : {}) + } +} + +async function fetchMRFiles( + repoPath: string, + projectRef: ProjectRef, + iid: number, + connectionId?: string | null +): Promise { + const { stdout } = await glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(projectRef, connectionId), + `projects/${encodedProject(projectRef.path)}/merge_requests/${iid}/changes` + ], + glabRepoExecOptions(repoPath, connectionId) + ) + const data = JSON.parse(stdout) as { + changes?: Parameters[0][] + } + return (data.changes ?? []).map(mapMRFile).filter((file) => file.path) } // ── Top-level aggregator ─────────────────────────────────────────── @@ -150,6 +242,89 @@ type GitLabRawMR = Parameters[0] & { sha?: string diff_refs?: { base_sha?: string; head_sha?: string; start_sha?: string } | null head_pipeline?: { id?: number } | null + reviewers?: GitLabRawUser[] | null +} + +async function fetchMRReviewers( + repoPath: string, + projectRef: ProjectRef, + iid: number, + connectionId?: string | null +): Promise { + const { stdout } = await glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(projectRef, connectionId), + `projects/${encodedProject(projectRef.path)}/merge_requests/${iid}/reviewers` + ], + glabRepoExecOptions(repoPath, connectionId) + ) + const data = JSON.parse(stdout) as { user?: GitLabRawUser | null }[] + return data + .map((entry) => mapGitLabUser(entry.user)) + .filter((u): u is GitLabAssignableUser => !!u) +} + +async function fetchMRApprovalState( + repoPath: string, + projectRef: ProjectRef, + iid: number, + connectionId?: string | null +): Promise { + const [approvalsRes, stateRes] = await Promise.allSettled([ + glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(projectRef, connectionId), + `projects/${encodedProject(projectRef.path)}/merge_requests/${iid}/approvals` + ], + glabRepoExecOptions(repoPath, connectionId) + ), + glabExecFileAsync( + [ + 'api', + ...glabHostnameArgs(projectRef, connectionId), + `projects/${encodedProject(projectRef.path)}/merge_requests/${iid}/approval_state` + ], + glabRepoExecOptions(repoPath, connectionId) + ) + ]) + if (approvalsRes.status === 'rejected' && stateRes.status === 'rejected') { + return undefined + } + const approvals = + approvalsRes.status === 'fulfilled' + ? (JSON.parse(approvalsRes.value.stdout) as { + approvals_required?: number | null + approvals_left?: number | null + approved_by?: { user?: GitLabRawUser | null }[] + }) + : null + const state = + stateRes.status === 'fulfilled' + ? (JSON.parse(stateRes.value.stdout) as { + rules?: { + id?: number + name?: string + approvals_required?: number + approved?: boolean + }[] + }) + : null + return { + approvalsRequired: + typeof approvals?.approvals_required === 'number' ? approvals.approvals_required : null, + approvalsLeft: typeof approvals?.approvals_left === 'number' ? approvals.approvals_left : null, + approvedBy: (approvals?.approved_by ?? []) + .map((entry) => mapGitLabUser(entry.user)) + .filter((u): u is GitLabAssignableUser => !!u), + rules: (state?.rules ?? []).map((rule) => ({ + id: rule.id ?? 0, + name: rule.name ?? 'Approval rule', + approvalsRequired: rule.approvals_required ?? 0, + approved: Boolean(rule.approved) + })) + } } /** @@ -259,12 +434,23 @@ async function fetchMRDetails( typeof pipelineId === 'number' ? await fetchPipelineJobs(repoPath, projectRef, pipelineId, connectionId).catch(() => []) : undefined + const [reviewers, approvalState, files] = await Promise.all([ + fetchMRReviewers(repoPath, projectRef, iid, connectionId).catch(() => + (mrRaw.reviewers ?? []).map(mapGitLabUser).filter((u): u is GitLabAssignableUser => !!u) + ), + fetchMRApprovalState(repoPath, projectRef, iid, connectionId).catch(() => undefined), + fetchMRFiles(repoPath, projectRef, iid, connectionId).catch(() => []) + ]) return { item, body: mrRaw.description ?? '', comments: flattenDiscussions(discussions), headSha: mrRaw.sha, baseSha: mrRaw.diff_refs?.base_sha, - ...(pipelineJobs !== undefined ? { pipelineJobs } : {}) + startSha: mrRaw.diff_refs?.start_sha, + files, + ...(pipelineJobs !== undefined ? { pipelineJobs } : {}), + reviewers, + ...(approvalState ? { approvalState } : {}) } } diff --git a/src/main/ipc/gitlab.ts b/src/main/ipc/gitlab.ts index fba51798a..c753c1de6 100644 --- a/src/main/ipc/gitlab.ts +++ b/src/main/ipc/gitlab.ts @@ -3,7 +3,13 @@ GitLab IPC handlers co-located keeps the repo-path validation pattern reviewable as one surface. */ import { ipcMain } from 'electron' import { resolve } from 'path' -import type { GitLabIssueUpdate, GitLabWorkItem, Repo } from '../../shared/types' +import type { + GitLabIssueUpdate, + GitLabMRInlineCommentInput, + GitLabMRUpdate, + GitLabWorkItem, + Repo +} from '../../shared/types' import type { Store } from '../persistence' import { normalizeGitLabIssueAssignee, @@ -14,14 +20,18 @@ import { import { recordGitLabProjectRecent } from '../gitlab/gitlab-project-recents' import { addIssueComment, + addMRInlineComment, addMRComment, closeMR, createIssue, + diagnoseAuth, getAuthenticatedViewer, + getJobTrace, getIssue, getMergeRequest, getMergeRequestForBranch, getProjectSlug, + getRateLimit, getWorkItemByProjectRef, listAssignableUsers, listIssues, @@ -31,7 +41,11 @@ import { listWorkItems, mergeMR, reopenMR, - updateIssue + resolveMRDiscussion, + retryJob, + updateIssue, + updateMR, + updateMRReviewers } from '../gitlab/client' import { getWorkItemDetails } from '../gitlab/work-item-details' import type { ProjectRef } from '../gitlab/gl-utils' @@ -57,6 +71,14 @@ export function registerGitLabHandlers(store: Store): void { return getAuthenticatedViewer() }) + ipcMain.handle('gitlab:diagnoseAuth', async () => diagnoseAuth()) + + ipcMain.handle( + 'gitlab:rateLimit', + async (_event, args?: { force?: boolean; host?: string | null }) => + getRateLimit({ force: Boolean(args?.force), host: args?.host ?? null }) + ) + ipcMain.handle('gitlab:projectSlug', async (_event, args: { repoPath: string }) => { const repo = assertRegisteredRepo(args.repoPath, store) return getProjectSlug(repo.path, repoConnectionId(repo)) @@ -276,6 +298,43 @@ export function registerGitLabHandlers(store: Store): void { } ) + ipcMain.handle( + 'gitlab:updateMR', + async (_event, args: { repoPath: string; iid: number; updates: GitLabMRUpdate }) => { + const repo = assertRegisteredRepo(args.repoPath, store) + return updateMR( + repo.path, + args.iid, + args.updates, + repo.issueSourcePreference, + repoConnectionId(repo) + ) + } + ) + + ipcMain.handle( + 'gitlab:updateMRReviewers', + async ( + _event, + args: { + repoPath: string + iid: number + reviewerIds: number[] + projectRef?: ProjectRef | null + } + ) => { + const repo = assertRegisteredRepo(args.repoPath, store) + return updateMRReviewers( + repo.path, + args.iid, + args.reviewerIds, + repo.issueSourcePreference, + repoConnectionId(repo), + args.projectRef + ) + } + ) + ipcMain.handle( 'gitlab:addMRComment', async (_event, args: { repoPath: string; iid: number; body: string }) => { @@ -290,6 +349,75 @@ export function registerGitLabHandlers(store: Store): void { } ) + ipcMain.handle( + 'gitlab:addMRInlineComment', + async ( + _event, + args: { + repoPath: string + iid: number + input: GitLabMRInlineCommentInput + projectRef?: ProjectRef | null + } + ) => { + const repo = assertRegisteredRepo(args.repoPath, store) + return addMRInlineComment( + repo.path, + args.iid, + args.input, + repo.issueSourcePreference, + repoConnectionId(repo), + args.projectRef + ) + } + ) + + ipcMain.handle( + 'gitlab:resolveMRDiscussion', + async ( + _event, + args: { repoPath: string; iid: number; discussionId: string; resolved: boolean } + ) => { + const repo = assertRegisteredRepo(args.repoPath, store) + return resolveMRDiscussion( + repo.path, + args.iid, + args.discussionId, + args.resolved, + repo.issueSourcePreference, + repoConnectionId(repo) + ) + } + ) + + ipcMain.handle( + 'gitlab:jobTrace', + async (_event, args: { repoPath: string; jobId: number; projectRef?: ProjectRef | null }) => { + const repo = assertRegisteredRepo(args.repoPath, store) + return getJobTrace( + repo.path, + args.jobId, + repo.issueSourcePreference, + repoConnectionId(repo), + args.projectRef + ) + } + ) + + ipcMain.handle( + 'gitlab:retryJob', + async (_event, args: { repoPath: string; jobId: number; projectRef?: ProjectRef | null }) => { + const repo = assertRegisteredRepo(args.repoPath, store) + return retryJob( + repo.path, + args.jobId, + repo.issueSourcePreference, + repoConnectionId(repo), + args.projectRef + ) + } + ) + // Why: My Todos surface — cross-project, user-scoped. The repoPath is // only used for the registered-repo guard; `glab api todos` doesn't // care about cwd because the endpoint is user-scoped. diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 6cb08d792..bc2269729 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -93,6 +93,7 @@ const { listGitLabMergeRequestsMock, listGitLabWorkItemsMock, listGitLabIssuesMock, + listGitLabLabelsMock, listGitLabTodosMock, getGitLabProjectRefForRemoteMock, getGitLabWorkItemByProjectRefMock, @@ -100,11 +101,16 @@ const { updateGitLabIssueMock, addGitLabIssueCommentMock, addGitLabMRCommentMock, + addGitLabMRInlineCommentMock, + resolveGitLabMRDiscussionMock, + getGitLabJobTraceMock, + retryGitLabJobMock, mergeGitLabMRMock, closeGitLabMRMock, reopenGitLabMRMock, getGlabKnownHostsMock, getGitLabWorkItemDetailsMock, + updateGitLabMRReviewersMock, getIssueMock, deleteWorktreeHistoryDirMock } = vi.hoisted(() => { @@ -147,6 +153,7 @@ const { listGitLabMergeRequestsMock: vi.fn(), listGitLabWorkItemsMock: vi.fn(), listGitLabIssuesMock: vi.fn(), + listGitLabLabelsMock: vi.fn(), listGitLabTodosMock: vi.fn(), getGitLabProjectRefForRemoteMock: vi.fn(), getGitLabWorkItemByProjectRefMock: vi.fn(), @@ -154,11 +161,16 @@ const { updateGitLabIssueMock: vi.fn(), addGitLabIssueCommentMock: vi.fn(), addGitLabMRCommentMock: vi.fn(), + addGitLabMRInlineCommentMock: vi.fn(), + resolveGitLabMRDiscussionMock: vi.fn(), + getGitLabJobTraceMock: vi.fn(), + retryGitLabJobMock: vi.fn(), mergeGitLabMRMock: vi.fn(), closeGitLabMRMock: vi.fn(), reopenGitLabMRMock: vi.fn(), getGlabKnownHostsMock: vi.fn(), getGitLabWorkItemDetailsMock: vi.fn(), + updateGitLabMRReviewersMock: vi.fn(), getIssueMock: vi.fn(), deleteWorktreeHistoryDirMock: vi.fn() } @@ -258,6 +270,7 @@ vi.mock('../gitlab/client', async (importOriginal) => { listMergeRequests: listGitLabMergeRequestsMock, listWorkItems: listGitLabWorkItemsMock, listIssues: listGitLabIssuesMock, + listLabels: listGitLabLabelsMock, listTodos: listGitLabTodosMock, getProjectRefForRemote: getGitLabProjectRefForRemoteMock, getWorkItemByProjectRef: getGitLabWorkItemByProjectRefMock, @@ -265,9 +278,14 @@ vi.mock('../gitlab/client', async (importOriginal) => { updateIssue: updateGitLabIssueMock, addIssueComment: addGitLabIssueCommentMock, addMRComment: addGitLabMRCommentMock, + addMRInlineComment: addGitLabMRInlineCommentMock, + resolveMRDiscussion: resolveGitLabMRDiscussionMock, + getJobTrace: getGitLabJobTraceMock, + retryJob: retryGitLabJobMock, mergeMR: mergeGitLabMRMock, closeMR: closeGitLabMRMock, - reopenMR: reopenGitLabMRMock + reopenMR: reopenGitLabMRMock, + updateMRReviewers: updateGitLabMRReviewersMock } }) @@ -391,6 +409,8 @@ afterEach(() => { listGitLabWorkItemsMock.mockResolvedValue({ items: [] }) listGitLabIssuesMock.mockReset() listGitLabIssuesMock.mockResolvedValue({ items: [] }) + listGitLabLabelsMock.mockReset() + listGitLabLabelsMock.mockResolvedValue(['bug']) listGitLabTodosMock.mockReset() listGitLabTodosMock.mockResolvedValue([]) getGitLabProjectRefForRemoteMock.mockReset() @@ -411,6 +431,14 @@ afterEach(() => { addGitLabIssueCommentMock.mockResolvedValue({ ok: true }) addGitLabMRCommentMock.mockReset() addGitLabMRCommentMock.mockResolvedValue({ ok: true }) + addGitLabMRInlineCommentMock.mockReset() + addGitLabMRInlineCommentMock.mockResolvedValue({ ok: true }) + resolveGitLabMRDiscussionMock.mockReset() + resolveGitLabMRDiscussionMock.mockResolvedValue({ ok: true }) + getGitLabJobTraceMock.mockReset() + getGitLabJobTraceMock.mockResolvedValue({ ok: true, trace: 'log' }) + retryGitLabJobMock.mockReset() + retryGitLabJobMock.mockResolvedValue({ ok: true }) mergeGitLabMRMock.mockReset() mergeGitLabMRMock.mockResolvedValue({ ok: true }) closeGitLabMRMock.mockReset() @@ -419,6 +447,8 @@ afterEach(() => { reopenGitLabMRMock.mockResolvedValue({ ok: true }) getGitLabWorkItemDetailsMock.mockReset() getGitLabWorkItemDetailsMock.mockResolvedValue({ body: 'Details' }) + updateGitLabMRReviewersMock.mockReset() + updateGitLabMRReviewersMock.mockResolvedValue({ ok: true, reviewers: [] }) getIssueMock.mockReset() getIssueMock.mockResolvedValue(null) }) @@ -8690,6 +8720,7 @@ describe('OrcaRuntimeService', () => { ] }) listGitLabTodosMock.mockResolvedValue([]) + listGitLabLabelsMock.mockResolvedValue(['bug', 'frontend']) getGitLabWorkItemByProjectRefMock.mockResolvedValue({ id: 'gitlab-issue-7', type: 'issue', @@ -8703,10 +8734,15 @@ describe('OrcaRuntimeService', () => { updateGitLabIssueMock.mockResolvedValue({ ok: true }) addGitLabIssueCommentMock.mockResolvedValue({ ok: true }) addGitLabMRCommentMock.mockResolvedValue({ ok: true }) + addGitLabMRInlineCommentMock.mockResolvedValue({ ok: true }) + resolveGitLabMRDiscussionMock.mockResolvedValue({ ok: true }) + getGitLabJobTraceMock.mockResolvedValue({ ok: true, trace: 'log' }) + retryGitLabJobMock.mockResolvedValue({ ok: true }) mergeGitLabMRMock.mockResolvedValue({ ok: true }) closeGitLabMRMock.mockResolvedValue({ ok: true }) reopenGitLabMRMock.mockResolvedValue({ ok: true }) getGitLabWorkItemDetailsMock.mockResolvedValue({ body: 'Details' }) + updateGitLabMRReviewersMock.mockResolvedValue({ ok: true, reviewers: [] }) const remoteRepo = { id: TEST_REPO_ID, @@ -8728,14 +8764,28 @@ describe('OrcaRuntimeService', () => { await runtime.listGitLabRepoWorkItems(TEST_REPO_ID, 'closed', 2, 25, 'ambiguous selector') const issues = await runtime.listGitLabRepoIssues(TEST_REPO_ID, 'opened', '@me', 50) await runtime.listGitLabRepoTodos(TEST_REPO_ID) + await runtime.listGitLabRepoLabels(TEST_REPO_ID) await runtime.createGitLabRepoIssue(TEST_REPO_ID, 'New issue', 'Body') await runtime.updateGitLabRepoIssue(TEST_REPO_ID, 7, { state: 'closed' }) await runtime.addGitLabRepoIssueComment(TEST_REPO_ID, 7, 'Looks good') await runtime.addGitLabRepoMRComment(TEST_REPO_ID, 8, 'Ship it') + const inlineCommentInput = { + body: 'please fix', + path: 'src/app.ts', + line: 12, + baseSha: 'base', + startSha: 'start', + headSha: 'head' + } + await runtime.addGitLabRepoMRInlineComment(TEST_REPO_ID, 8, inlineCommentInput) + await runtime.resolveGitLabRepoMRDiscussion(TEST_REPO_ID, 8, 'discussion-1', true) + await runtime.getGitLabRepoJobTrace(TEST_REPO_ID, 99) + await runtime.retryGitLabRepoJob(TEST_REPO_ID, 99) await runtime.mergeGitLabRepoMR(TEST_REPO_ID, 8, 'squash') await runtime.updateGitLabRepoMRState(TEST_REPO_ID, 8, 'closed') await runtime.updateGitLabRepoMRState(TEST_REPO_ID, 8, 'opened') await runtime.getGitLabRepoWorkItemDetails(TEST_REPO_ID, 8, 'mr') + await runtime.updateGitLabRepoMRReviewers(TEST_REPO_ID, 8, [1, 2]) await runtime.getGitLabRepoWorkItemByPath( TEST_REPO_ID, { host: 'gitlab.example.com', path: 'group/project' }, @@ -8784,6 +8834,7 @@ describe('OrcaRuntimeService', () => { } ]) expect(listGitLabTodosMock).toHaveBeenCalledWith('/remote/repo', 'ssh-1') + expect(listGitLabLabelsMock).toHaveBeenCalledWith('/remote/repo', 'origin', 'ssh-1') expect(createGitLabIssueMock).toHaveBeenCalledWith( '/remote/repo', 'New issue', @@ -8815,6 +8866,37 @@ describe('OrcaRuntimeService', () => { 'ssh-1', undefined ) + expect(addGitLabMRInlineCommentMock).toHaveBeenCalledWith( + '/remote/repo', + 8, + inlineCommentInput, + 'origin', + 'ssh-1', + undefined + ) + expect(resolveGitLabMRDiscussionMock).toHaveBeenCalledWith( + '/remote/repo', + 8, + 'discussion-1', + true, + 'origin', + 'ssh-1', + undefined + ) + expect(getGitLabJobTraceMock).toHaveBeenCalledWith( + '/remote/repo', + 99, + 'origin', + 'ssh-1', + undefined + ) + expect(retryGitLabJobMock).toHaveBeenCalledWith( + '/remote/repo', + 99, + 'origin', + 'ssh-1', + undefined + ) expect(mergeGitLabMRMock).toHaveBeenCalledWith( '/remote/repo', 8, @@ -8833,6 +8915,14 @@ describe('OrcaRuntimeService', () => { 'ssh-1', undefined ) + expect(updateGitLabMRReviewersMock).toHaveBeenCalledWith( + '/remote/repo', + 8, + [1, 2], + 'origin', + 'ssh-1', + undefined + ) expect(getGitLabWorkItemByProjectRefMock).toHaveBeenCalledWith( '/remote/repo', { host: 'gitlab.example.com', path: 'group/project' }, diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index f95acd342..324b43f92 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -193,17 +193,25 @@ import { getRateLimit } from '../github/rate-limit' import { closeMR as closeGitLabMR, createIssue as createGitLabIssue, + diagnoseAuth as diagnoseGitLabAuthClient, + getJobTrace as getGitLabJobTrace, getProjectRefForRemote as getGitLabProjectRefForRemote, + getRateLimit as getGitLabRateLimit, getWorkItemByProjectRef as getGitLabWorkItemByProjectRef, addIssueComment as addGitLabIssueComment, + addMRInlineComment as addGitLabMRInlineComment, addMRComment as addGitLabMRComment, listTodos as listGitLabTodos, listIssues as listGitLabIssues, + listLabels as listGitLabLabels, listMergeRequests as listGitLabMergeRequests, listWorkItems as listGitLabWorkItems, mergeMR as mergeGitLabMR, reopenMR as reopenGitLabMR, + resolveMRDiscussion as resolveGitLabMRDiscussion, + retryJob as retryGitLabJob, updateMR as updateGitLabMR, + updateMRReviewers as updateGitLabMRReviewers, updateIssue as updateGitLabIssue } from '../gitlab/client' import { getGlabKnownHosts } from '../gitlab/gl-utils' @@ -221,6 +229,7 @@ import type { GitHubPRFile, GitHubPRReviewCommentInput, GitLabIssueUpdate, + GitLabMRInlineCommentInput, GitLabProjectRef, GitLabWorkItem, MRListState @@ -6156,6 +6165,24 @@ export class OrcaRuntimeService { return listGitLabTodos(repo.path, repo.connectionId ?? null) } + async diagnoseGitLabAuth(): Promise>> { + return diagnoseGitLabAuthClient() + } + + async getGitLabRateLimit(options?: { + force?: boolean + host?: string | null + }): Promise>> { + return getGitLabRateLimit(options) + } + + async listGitLabRepoLabels( + repoSelector: string + ): Promise>> { + const repo = await this.resolveRepoSelector(repoSelector) + return listGitLabLabels(repo.path, repo.issueSourcePreference, repo.connectionId ?? null) + } + async createGitLabRepoIssue( repoSelector: string, title: string, @@ -6222,6 +6249,72 @@ export class OrcaRuntimeService { ) } + async addGitLabRepoMRInlineComment( + repoSelector: string, + iid: number, + input: GitLabMRInlineCommentInput, + projectRef?: GitLabProjectRef | null + ): Promise>> { + const repo = await this.resolveRepoSelector(repoSelector) + return addGitLabMRInlineComment( + repo.path, + iid, + input, + repo.issueSourcePreference, + repo.connectionId ?? null, + projectRef + ) + } + + async resolveGitLabRepoMRDiscussion( + repoSelector: string, + iid: number, + discussionId: string, + resolved: boolean, + projectRef?: GitLabProjectRef | null + ): Promise>> { + const repo = await this.resolveRepoSelector(repoSelector) + return resolveGitLabMRDiscussion( + repo.path, + iid, + discussionId, + resolved, + repo.issueSourcePreference, + repo.connectionId ?? null, + projectRef + ) + } + + async getGitLabRepoJobTrace( + repoSelector: string, + jobId: number, + projectRef?: GitLabProjectRef | null + ): Promise>> { + const repo = await this.resolveRepoSelector(repoSelector) + return getGitLabJobTrace( + repo.path, + jobId, + repo.issueSourcePreference, + repo.connectionId ?? null, + projectRef + ) + } + + async retryGitLabRepoJob( + repoSelector: string, + jobId: number, + projectRef?: GitLabProjectRef | null + ): Promise>> { + const repo = await this.resolveRepoSelector(repoSelector) + return retryGitLabJob( + repo.path, + jobId, + repo.issueSourcePreference, + repo.connectionId ?? null, + projectRef + ) + } + async mergeGitLabRepoMR( repoSelector: string, iid: number, @@ -6280,6 +6373,23 @@ export class OrcaRuntimeService { ) } + async updateGitLabRepoMRReviewers( + repoSelector: string, + iid: number, + reviewerIds: number[], + projectRef?: GitLabProjectRef | null + ): Promise>> { + const repo = await this.resolveRepoSelector(repoSelector) + return updateGitLabMRReviewers( + repo.path, + iid, + reviewerIds, + repo.issueSourcePreference, + repo.connectionId ?? null, + projectRef + ) + } + async getGitLabRepoWorkItemDetails( repoSelector: string, iid: number, diff --git a/src/main/runtime/rpc/methods/gitlab.test.ts b/src/main/runtime/rpc/methods/gitlab.test.ts index 03b38b421..cb88fbff7 100644 --- a/src/main/runtime/rpc/methods/gitlab.test.ts +++ b/src/main/runtime/rpc/methods/gitlab.test.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-lines -- Why: one routing test exercises the full GitLab RPC surface so provider parity regressions show up in a single contract fixture. */ import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from '../dispatcher' import type { RpcRequest } from '../core' @@ -12,23 +13,35 @@ describe('gitlab RPC methods', () => { it('routes GitLab task queries and mutations to the runtime server', async () => { const runtime = { getRuntimeId: () => 'test-runtime', + diagnoseGitLabAuth: vi.fn().mockResolvedValue({ glabAvailable: true }), + getGitLabRateLimit: vi.fn().mockResolvedValue({ ok: true }), listGitLabRepoMRs: vi.fn().mockResolvedValue({ items: [] }), listGitLabRepoWorkItems: vi.fn().mockResolvedValue({ items: [] }), listGitLabRepoIssues: vi.fn().mockResolvedValue({ items: [] }), listGitLabRepoTodos: vi.fn().mockResolvedValue([{ id: 1 }]), + listGitLabRepoLabels: vi.fn().mockResolvedValue(['bug']), createGitLabRepoIssue: vi.fn().mockResolvedValue({ ok: true, number: 7 }), updateGitLabRepoIssue: vi.fn().mockResolvedValue({ ok: true }), addGitLabRepoIssueComment: vi.fn().mockResolvedValue({ ok: true }), addGitLabRepoMRComment: vi.fn().mockResolvedValue({ ok: true }), + addGitLabRepoMRInlineComment: vi.fn().mockResolvedValue({ ok: true }), + resolveGitLabRepoMRDiscussion: vi.fn().mockResolvedValue({ ok: true }), + getGitLabRepoJobTrace: vi.fn().mockResolvedValue({ ok: true, trace: 'log' }), + retryGitLabRepoJob: vi.fn().mockResolvedValue({ ok: true }), mergeGitLabRepoMR: vi.fn().mockResolvedValue({ ok: true }), updateGitLabRepoMRState: vi.fn().mockResolvedValue({ ok: true }), updateGitLabRepoMR: vi.fn().mockResolvedValue({ ok: true }), + updateGitLabRepoMRReviewers: vi.fn().mockResolvedValue({ ok: true, reviewers: [] }), getGitLabRepoWorkItemDetails: vi.fn().mockResolvedValue({ body: 'Details' }), getGitLabRepoWorkItemByPath: vi.fn().mockResolvedValue({ id: 'gitlab-issue-7' }) } as unknown as OrcaRuntimeService const dispatcher = new RpcDispatcher({ runtime, methods: GITLAB_METHODS }) const projectRef = { host: 'gitlab.example.com', path: 'group/project' } + await dispatcher.dispatch(makeRequest('gitlab.diagnoseAuth')) + await dispatcher.dispatch( + makeRequest('gitlab.rateLimit', { force: true, host: 'gitlab.example.com' }) + ) await dispatcher.dispatch( makeRequest('gitlab.listMRs', { repo: 'id:repo-1', @@ -63,6 +76,7 @@ describe('gitlab RPC methods', () => { }) ) await dispatcher.dispatch(makeRequest('gitlab.todos', { repo: 'id:repo-1' })) + await dispatcher.dispatch(makeRequest('gitlab.listLabels', { repo: 'id:repo-1' })) await dispatcher.dispatch( makeRequest('gitlab.updateIssue', { repo: 'id:repo-1', @@ -87,6 +101,45 @@ describe('gitlab RPC methods', () => { projectRef }) ) + const inlineInput = { + body: 'please fix', + path: 'src/app.ts', + line: 12, + baseSha: 'base', + startSha: 'start', + headSha: 'head' + } + await dispatcher.dispatch( + makeRequest('gitlab.addMRInlineComment', { + repo: 'id:repo-1', + iid: 8, + input: inlineInput, + projectRef + }) + ) + await dispatcher.dispatch( + makeRequest('gitlab.resolveMRDiscussion', { + repo: 'id:repo-1', + iid: 8, + discussionId: 'discussion-1', + resolved: true, + projectRef + }) + ) + await dispatcher.dispatch( + makeRequest('gitlab.jobTrace', { + repo: 'id:repo-1', + jobId: 99, + projectRef + }) + ) + await dispatcher.dispatch( + makeRequest('gitlab.retryJob', { + repo: 'id:repo-1', + jobId: 99, + projectRef + }) + ) await dispatcher.dispatch( makeRequest('gitlab.mergeMR', { repo: 'id:repo-1', @@ -111,6 +164,14 @@ describe('gitlab RPC methods', () => { projectRef }) ) + await dispatcher.dispatch( + makeRequest('gitlab.updateMRReviewers', { + repo: 'id:repo-1', + iid: 8, + reviewerIds: [1, 2], + projectRef + }) + ) await dispatcher.dispatch( makeRequest('gitlab.workItemDetails', { repo: 'id:repo-1', @@ -129,6 +190,11 @@ describe('gitlab RPC methods', () => { }) ) + expect(runtime.diagnoseGitLabAuth).toHaveBeenCalledWith() + expect(runtime.getGitLabRateLimit).toHaveBeenCalledWith({ + force: true, + host: 'gitlab.example.com' + }) expect(runtime.listGitLabRepoMRs).toHaveBeenCalledWith('id:repo-1', 'opened', 1, 25, 'bug') expect(runtime.listGitLabRepoWorkItems).toHaveBeenCalledWith( 'id:repo-1', @@ -140,6 +206,7 @@ describe('gitlab RPC methods', () => { expect(runtime.listGitLabRepoIssues).toHaveBeenCalledWith('id:repo-1', 'opened', '@me', 50) expect(runtime.createGitLabRepoIssue).toHaveBeenCalledWith('id:repo-1', 'Fix bug', 'Details') expect(runtime.listGitLabRepoTodos).toHaveBeenCalledWith('id:repo-1') + expect(runtime.listGitLabRepoLabels).toHaveBeenCalledWith('id:repo-1') expect(runtime.updateGitLabRepoIssue).toHaveBeenCalledWith( 'id:repo-1', 7, @@ -162,6 +229,21 @@ describe('gitlab RPC methods', () => { 'ship it', projectRef ) + expect(runtime.addGitLabRepoMRInlineComment).toHaveBeenCalledWith( + 'id:repo-1', + 8, + inlineInput, + projectRef + ) + expect(runtime.resolveGitLabRepoMRDiscussion).toHaveBeenCalledWith( + 'id:repo-1', + 8, + 'discussion-1', + true, + projectRef + ) + expect(runtime.getGitLabRepoJobTrace).toHaveBeenCalledWith('id:repo-1', 99, projectRef) + expect(runtime.retryGitLabRepoJob).toHaveBeenCalledWith('id:repo-1', 99, projectRef) expect(runtime.mergeGitLabRepoMR).toHaveBeenCalledWith('id:repo-1', 8, 'squash', projectRef) expect(runtime.updateGitLabRepoMRState).toHaveBeenCalledWith( 'id:repo-1', @@ -179,6 +261,12 @@ describe('gitlab RPC methods', () => { }, projectRef ) + expect(runtime.updateGitLabRepoMRReviewers).toHaveBeenCalledWith( + 'id:repo-1', + 8, + [1, 2], + projectRef + ) expect(runtime.getGitLabRepoWorkItemDetails).toHaveBeenCalledWith( 'id:repo-1', 8, diff --git a/src/main/runtime/rpc/methods/gitlab.ts b/src/main/runtime/rpc/methods/gitlab.ts index b7243fcd6..c10a7eee7 100644 --- a/src/main/runtime/rpc/methods/gitlab.ts +++ b/src/main/runtime/rpc/methods/gitlab.ts @@ -7,6 +7,15 @@ const RepoSelector = z.object({ repo: requiredString('Missing repo selector') }) +const EmptyParams = z.object({}).optional().default({}) +const GitLabRateLimit = z + .object({ + force: z.boolean().optional(), + host: OptionalString + }) + .optional() + .default({}) + const GitLabProjectRef = z .object({ host: requiredString('Missing GitLab host'), @@ -65,6 +74,12 @@ const UpdateMr = RepoSelector.extend({ projectRef: GitLabProjectRef }) +const UpdateMrReviewers = RepoSelector.extend({ + iid: z.number().int().positive(), + reviewerIds: z.array(z.number().int().nonnegative()), + projectRef: GitLabProjectRef +}) + const MergeMr = RepoSelector.extend({ iid: z.number().int().positive(), method: z.enum(['merge', 'squash', 'rebase']).optional(), @@ -83,6 +98,37 @@ const AddMRComment = RepoSelector.extend({ projectRef: GitLabProjectRef }) +const AddMRInlineComment = RepoSelector.extend({ + iid: z.number().int().positive(), + input: z.object({ + body: requiredString('Comment body is required'), + path: requiredString('File path is required'), + oldPath: z.string().optional(), + line: z.number().int().positive(), + baseSha: requiredString('Base SHA is required'), + startSha: requiredString('Start SHA is required'), + headSha: requiredString('Head SHA is required') + }), + projectRef: GitLabProjectRef +}) + +const ResolveMRDiscussion = RepoSelector.extend({ + iid: z.number().int().positive(), + discussionId: requiredString('Discussion id is required'), + resolved: z.boolean(), + projectRef: GitLabProjectRef +}) + +const JobTrace = RepoSelector.extend({ + jobId: z.number().int().positive(), + projectRef: GitLabProjectRef +}) + +const RetryJob = RepoSelector.extend({ + jobId: z.number().int().positive(), + projectRef: GitLabProjectRef +}) + const WorkItemDetails = RepoSelector.extend({ iid: z.number().int().positive(), type: z.enum(['issue', 'mr']), @@ -139,6 +185,21 @@ export const GITLAB_METHODS: RpcMethod[] = [ params: RepoSelector, handler: async (params, { runtime }) => runtime.listGitLabRepoTodos(params.repo) }), + defineMethod({ + name: 'gitlab.diagnoseAuth', + params: EmptyParams, + handler: async (_params, { runtime }) => runtime.diagnoseGitLabAuth() + }), + defineMethod({ + name: 'gitlab.rateLimit', + params: GitLabRateLimit, + handler: async (params, { runtime }) => runtime.getGitLabRateLimit(params) + }), + defineMethod({ + name: 'gitlab.listLabels', + params: RepoSelector, + handler: async (params, { runtime }) => runtime.listGitLabRepoLabels(params.repo) + }), defineMethod({ name: 'gitlab.createIssue', params: CreateIssue, @@ -163,6 +224,36 @@ export const GITLAB_METHODS: RpcMethod[] = [ handler: async (params, { runtime }) => runtime.addGitLabRepoMRComment(params.repo, params.iid, params.body, params.projectRef) }), + defineMethod({ + name: 'gitlab.addMRInlineComment', + params: AddMRInlineComment, + handler: async (params, { runtime }) => + runtime.addGitLabRepoMRInlineComment(params.repo, params.iid, params.input, params.projectRef) + }), + defineMethod({ + name: 'gitlab.resolveMRDiscussion', + params: ResolveMRDiscussion, + handler: async (params, { runtime }) => + runtime.resolveGitLabRepoMRDiscussion( + params.repo, + params.iid, + params.discussionId, + params.resolved, + params.projectRef + ) + }), + defineMethod({ + name: 'gitlab.jobTrace', + params: JobTrace, + handler: async (params, { runtime }) => + runtime.getGitLabRepoJobTrace(params.repo, params.jobId, params.projectRef) + }), + defineMethod({ + name: 'gitlab.retryJob', + params: RetryJob, + handler: async (params, { runtime }) => + runtime.retryGitLabRepoJob(params.repo, params.jobId, params.projectRef) + }), defineMethod({ name: 'gitlab.mergeMR', params: MergeMr, @@ -181,6 +272,17 @@ export const GITLAB_METHODS: RpcMethod[] = [ handler: async (params, { runtime }) => runtime.updateGitLabRepoMR(params.repo, params.iid, params.updates, params.projectRef) }), + defineMethod({ + name: 'gitlab.updateMRReviewers', + params: UpdateMrReviewers, + handler: async (params, { runtime }) => + runtime.updateGitLabRepoMRReviewers( + params.repo, + params.iid, + params.reviewerIds, + params.projectRef + ) + }), defineMethod({ name: 'gitlab.workItemDetails', params: WorkItemDetails, diff --git a/src/main/runtime/runtime-rpc.test.ts b/src/main/runtime/runtime-rpc.test.ts index 1472ca073..270ef54bd 100644 --- a/src/main/runtime/runtime-rpc.test.ts +++ b/src/main/runtime/runtime-rpc.test.ts @@ -818,6 +818,7 @@ describe('OrcaRuntimeRpcServer', () => { const mergeRepoPR = vi.fn().mockResolvedValue({ ok: true }) const addGitLabRepoIssueComment = vi.fn().mockResolvedValue({ ok: true }) const addGitLabRepoMRComment = vi.fn().mockResolvedValue({ ok: true }) + const resolveGitLabRepoMRDiscussion = vi.fn().mockResolvedValue({ ok: true }) const mergeGitLabRepoMR = vi.fn().mockResolvedValue({ ok: true }) const addGitHubIssueCommentBySlug = vi.fn().mockResolvedValue({ ok: true, @@ -877,6 +878,7 @@ describe('OrcaRuntimeRpcServer', () => { mergeRepoPR, addGitLabRepoIssueComment, addGitLabRepoMRComment, + resolveGitLabRepoMRDiscussion, mergeGitLabRepoMR, addGitHubIssueCommentBySlug, updateGitHubIssueCommentBySlug, @@ -1290,6 +1292,21 @@ describe('OrcaRuntimeRpcServer', () => { (response) => replies.push(JSON.parse(response) as Record), () => {} ) + await server['handleWebSocketMessage']( + JSON.stringify({ + id: 'req_gitlab_resolve_mr_discussion', + method: 'gitlab.resolveMRDiscussion', + deviceToken: mobile.token, + params: { + repo: 'id:repo-1', + iid: 456, + discussionId: 'discussion-1', + resolved: true + } + }), + (response) => replies.push(JSON.parse(response) as Record), + () => {} + ) await server['handleWebSocketMessage']( JSON.stringify({ id: 'req_gitlab_merge_mr', @@ -1789,6 +1806,13 @@ describe('OrcaRuntimeRpcServer', () => { expect(mergeRepoPR).toHaveBeenCalledWith('id:repo-1', 456, 'squash', null) expect(addGitLabRepoIssueComment).toHaveBeenCalledWith('id:repo-1', 123, 'done', undefined) expect(addGitLabRepoMRComment).toHaveBeenCalledWith('id:repo-1', 456, 'ship it', undefined) + expect(resolveGitLabRepoMRDiscussion).toHaveBeenCalledWith( + 'id:repo-1', + 456, + 'discussion-1', + true, + undefined + ) expect(mergeGitLabRepoMR).toHaveBeenCalledWith('id:repo-1', 456, 'merge', undefined) expect(updateGitHubProjectItemField).toHaveBeenCalledWith({ projectId: 'project-1', diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index a89b933a9..29d49ac41 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -208,6 +208,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'gitlab.addMRComment', 'gitlab.listWorkItems', 'gitlab.mergeMR', + 'gitlab.resolveMRDiscussion', 'gitlab.todos', 'gitlab.updateIssue', 'gitlab.updateMR', diff --git a/src/main/source-control/hosted-review-creation.test.ts b/src/main/source-control/hosted-review-creation.test.ts index b5a8475c3..1efd0f00b 100644 --- a/src/main/source-control/hosted-review-creation.test.ts +++ b/src/main/source-control/hosted-review-creation.test.ts @@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const { createGitHubPullRequestMock, + createGitLabMergeRequestMock, getRepoSlugMock, getProjectSlugMock, getBitbucketRepoSlugMock, @@ -10,11 +11,13 @@ const { getGiteaRepoSlugMock, getHostedReviewForBranchMock, ghExecFileAsyncMock, + glabExecFileAsyncMock, gitExecFileAsyncMock, getUpstreamStatusMock, getSshGitProviderMock } = vi.hoisted(() => ({ createGitHubPullRequestMock: vi.fn(), + createGitLabMergeRequestMock: vi.fn(), getRepoSlugMock: vi.fn(), getProjectSlugMock: vi.fn(), getBitbucketRepoSlugMock: vi.fn(), @@ -22,6 +25,7 @@ const { getGiteaRepoSlugMock: vi.fn(), getHostedReviewForBranchMock: vi.fn(), ghExecFileAsyncMock: vi.fn(), + glabExecFileAsyncMock: vi.fn(), gitExecFileAsyncMock: vi.fn(), getUpstreamStatusMock: vi.fn(), getSshGitProviderMock: vi.fn() @@ -36,6 +40,10 @@ vi.mock('../gitlab/client', () => ({ getProjectSlug: getProjectSlugMock })) +vi.mock('../gitlab/merge-request-creation', () => ({ + createGitLabMergeRequest: createGitLabMergeRequestMock +})) + vi.mock('../bitbucket/client', () => ({ getBitbucketRepoSlug: getBitbucketRepoSlugMock })) @@ -55,6 +63,14 @@ vi.mock('../github/gh-utils', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) +vi.mock('../gitlab/gl-utils', () => ({ + acquire: vi.fn(), + release: vi.fn(), + glabExecFileAsync: glabExecFileAsyncMock, + glabRepoExecOptions: (repoPath: string, connectionId?: string | null) => + connectionId ? {} : { cwd: repoPath } +})) + vi.mock('../git/upstream', () => ({ getUpstreamStatus: getUpstreamStatusMock })) @@ -72,6 +88,7 @@ import { createHostedReview, getHostedReviewCreationEligibility } from './hosted function resetMocks(): void { for (const mock of [ createGitHubPullRequestMock, + createGitLabMergeRequestMock, getRepoSlugMock, getProjectSlugMock, getBitbucketRepoSlugMock, @@ -79,6 +96,7 @@ function resetMocks(): void { getGiteaRepoSlugMock, getHostedReviewForBranchMock, ghExecFileAsyncMock, + glabExecFileAsyncMock, gitExecFileAsyncMock, getUpstreamStatusMock, getSshGitProviderMock @@ -95,6 +113,14 @@ function mockGitHubProvider(): void { getGiteaRepoSlugMock.mockResolvedValue(null) } +function mockGitLabProvider(): void { + getProjectSlugMock.mockResolvedValue({ host: 'gitlab.com', path: 'acme/orca' }) + getRepoSlugMock.mockResolvedValue(null) + getBitbucketRepoSlugMock.mockResolvedValue(null) + getAzureDevOpsRepoSlugMock.mockResolvedValue(null) + getGiteaRepoSlugMock.mockResolvedValue(null) +} + describe('createHostedReview', () => { beforeEach(() => { resetMocks() @@ -102,6 +128,7 @@ describe('createHostedReview', () => { mockGitHubProvider() getHostedReviewForBranchMock.mockResolvedValue(null) ghExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + glabExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) getUpstreamStatusMock.mockResolvedValue({ hasUpstream: true, upstreamName: 'origin/feature', @@ -128,6 +155,11 @@ describe('createHostedReview', () => { number: 12, url: 'https://github.com/acme/orca/pull/12' }) + createGitLabMergeRequestMock.mockResolvedValue({ + ok: true, + number: 44, + url: 'https://gitlab.com/acme/orca/-/merge_requests/44' + }) }) it('revalidates ahead commits before creating a GitHub pull request', async () => { @@ -192,6 +224,39 @@ describe('createHostedReview', () => { expect(createGitHubPullRequestMock).toHaveBeenCalledOnce() }) + it('creates a GitLab merge request after fresh main-process validation passes', async () => { + mockGitLabProvider() + + await expect( + createHostedReview('/repo', { + provider: 'gitlab', + base: 'main', + head: 'feature', + title: 'Feature' + }) + ).resolves.toEqual({ + ok: true, + number: 44, + url: 'https://gitlab.com/acme/orca/-/merge_requests/44' + }) + + expect(glabExecFileAsyncMock).toHaveBeenCalledWith( + ['auth', 'status', '--hostname', 'gitlab.com'], + { cwd: '/repo' } + ) + expect(createGitLabMergeRequestMock).toHaveBeenCalledWith( + '/repo', + { + provider: 'gitlab', + base: 'main', + head: 'feature', + title: 'Feature' + }, + undefined + ) + expect(createGitHubPullRequestMock).not.toHaveBeenCalled() + }) + it('uses the SSH git provider for remote hosted-review preflight', async () => { const remoteGit = { getStatus: vi.fn(async () => ({ entries: [], conflictOperation: 'unknown' })), @@ -411,9 +476,8 @@ describe('getHostedReviewCreationEligibility', () => { }) }) - it('blocks unsupported providers before GitHub authentication checks', async () => { - getProjectSlugMock.mockResolvedValue({ host: 'gitlab.com', path: 'acme/orca' }) - getRepoSlugMock.mockResolvedValue(null) + it('enables creation for clean, in-sync, authenticated GitLab feature branches', async () => { + mockGitLabProvider() await expect( getHostedReviewCreationEligibility({ @@ -427,9 +491,15 @@ describe('getHostedReviewCreationEligibility', () => { }) ).resolves.toMatchObject({ provider: 'gitlab', - canCreate: false, - blockedReason: 'unsupported_provider' + canCreate: true, + blockedReason: null, + nextAction: null, + head: 'feature/gitlab' }) expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + expect(glabExecFileAsyncMock).toHaveBeenCalledWith( + ['auth', 'status', '--hostname', 'gitlab.com'], + { cwd: '/repo' } + ) }) }) diff --git a/src/main/source-control/hosted-review-creation.ts b/src/main/source-control/hosted-review-creation.ts index 1cecc2210..b22db643e 100644 --- a/src/main/source-control/hosted-review-creation.ts +++ b/src/main/source-control/hosted-review-creation.ts @@ -23,6 +23,13 @@ import { gitOptionalLocksDisabledEnv } from '../git/runner' import { resolveDefaultBaseRefViaExec } from '../git/repo' import { getUpstreamStatus } from '../git/upstream' import { getProjectSlug } from '../gitlab/client' +import { createGitLabMergeRequest } from '../gitlab/merge-request-creation' +import { + acquire as acquireGlab, + glabExecFileAsync, + glabRepoExecOptions, + release as releaseGlab +} from '../gitlab/gl-utils' import { getSshGitProvider } from '../providers/ssh-git-dispatch' import { getHostedReviewForBranch } from './hosted-review' @@ -74,6 +81,28 @@ async function isGitHubAuthenticated( } } +async function isGitLabAuthenticated( + repoPath: string, + connectionId?: string | null +): Promise { + const projectRef = await getProjectSlug(repoPath, connectionId) + if (!projectRef) { + return false + } + await acquireGlab() + try { + await glabExecFileAsync( + ['auth', 'status', '--hostname', projectRef.host], + glabRepoExecOptions(repoPath, connectionId) + ) + return true + } catch { + return false + } finally { + releaseGlab() + } +} + async function runGitForHostedReview( repoPath: string, args: string[], @@ -154,56 +183,83 @@ async function getHostedReviewUpstreamStatus( } } -const blockedCreateResultByReason = { - auth_required: { - ok: false, - code: 'auth_required', - error: - 'Create PR failed: GitHub is not authenticated. Next step: run gh auth login in this environment.' - }, - unsupported_provider: { - ok: false, - code: 'unsupported_provider', - error: 'Creating pull requests requires a GitHub remote.' - }, - dirty: { - ok: false, - code: 'validation', - error: 'Create PR failed: commit or discard local changes before creating a pull request.' - }, - detached_head: { - ok: false, - code: 'validation', - error: 'Create PR failed: switch to a branch before creating a pull request.' - }, - default_branch: { - ok: false, - code: 'validation', - error: 'Create PR failed: choose a feature branch before creating a pull request.' - }, - no_upstream: { - ok: false, - code: 'validation', - error: 'Create PR failed: publish this branch before creating a pull request.' - }, - needs_push: { - ok: false, - code: 'validation', - error: 'Create PR failed: push this branch before creating a pull request.' - }, - needs_sync: { - ok: false, - code: 'validation', - error: 'Create PR failed: sync this branch before creating a pull request.' - }, - fork_head_unsupported: { - ok: false, - code: 'validation', - error: 'Create PR failed: refresh source control status and try again.' - } -} satisfies Partial< - Record, CreateHostedReviewResult> -> +function reviewCopy(provider: HostedReviewProvider): { + shortLabel: 'PR' | 'MR' + reviewLabel: 'pull request' | 'merge request' + providerName: 'GitHub' | 'GitLab' + authCommand: 'gh auth login' | 'glab auth login' +} { + return provider === 'gitlab' + ? { + shortLabel: 'MR', + reviewLabel: 'merge request', + providerName: 'GitLab', + authCommand: 'glab auth login' + } + : { + shortLabel: 'PR', + reviewLabel: 'pull request', + providerName: 'GitHub', + authCommand: 'gh auth login' + } +} + +function blockedCreateResultForReason( + reason: NonNullable, + provider: HostedReviewProvider +): CreateHostedReviewResult | null { + const copy = reviewCopy(provider) + const blockedCreateResultByReason = { + auth_required: { + ok: false, + code: 'auth_required', + error: `Create ${copy.shortLabel} failed: ${copy.providerName} is not authenticated. Next step: run ${copy.authCommand} in this environment.` + }, + unsupported_provider: { + ok: false, + code: 'unsupported_provider', + error: `Creating ${copy.reviewLabel}s requires a ${copy.providerName} remote.` + }, + dirty: { + ok: false, + code: 'validation', + error: `Create ${copy.shortLabel} failed: commit or discard local changes before creating a ${copy.reviewLabel}.` + }, + detached_head: { + ok: false, + code: 'validation', + error: `Create ${copy.shortLabel} failed: switch to a branch before creating a ${copy.reviewLabel}.` + }, + default_branch: { + ok: false, + code: 'validation', + error: `Create ${copy.shortLabel} failed: choose a feature branch before creating a ${copy.reviewLabel}.` + }, + no_upstream: { + ok: false, + code: 'validation', + error: `Create ${copy.shortLabel} failed: publish this branch before creating a ${copy.reviewLabel}.` + }, + needs_push: { + ok: false, + code: 'validation', + error: `Create ${copy.shortLabel} failed: push this branch before creating a ${copy.reviewLabel}.` + }, + needs_sync: { + ok: false, + code: 'validation', + error: `Create ${copy.shortLabel} failed: sync this branch before creating a ${copy.reviewLabel}.` + }, + fork_head_unsupported: { + ok: false, + code: 'validation', + error: `Create ${copy.shortLabel} failed: refresh source control status and try again.` + } + } satisfies Partial< + Record, CreateHostedReviewResult> + > + return blockedCreateResultByReason[reason] ?? null +} function blockedEligibilityToCreateResult( eligibility: HostedReviewCreationEligibility @@ -212,20 +268,22 @@ function blockedEligibilityToCreateResult( return null } if (eligibility.review?.url) { + const copy = reviewCopy(eligibility.provider) return { ok: false, code: 'already_exists', - error: 'A pull request already exists for this branch.', + error: `A ${copy.reviewLabel} already exists for this branch.`, existingReview: eligibility.review } } if (eligibility.blockedReason) { - return blockedCreateResultByReason[eligibility.blockedReason] ?? null + return blockedCreateResultForReason(eligibility.blockedReason, eligibility.provider) } + const copy = reviewCopy(eligibility.provider) return { ok: false, code: 'validation', - error: 'Create PR failed: refresh source control status and try again.' + error: `Create ${copy.shortLabel} failed: refresh source control status and try again.` } } @@ -236,11 +294,12 @@ async function validateCurrentBranchCanCreateReview( ): Promise { const requestedHead = input.head ? stripRefPrefix(input.head).trim() : '' const currentBranch = await getCurrentBranch(repoPath, connectionId) + const copy = reviewCopy(input.provider) if (requestedHead && requestedHead !== currentBranch) { return { ok: false, code: 'validation', - error: 'Create PR failed: switch back to the selected branch before creating a pull request.' + error: `Create ${copy.shortLabel} failed: switch back to the selected branch before creating a ${copy.reviewLabel}.` } } @@ -267,8 +326,7 @@ async function validateCurrentBranchCanCreateReview( return { ok: false, code: 'validation', - error: - 'Create PR failed: could not verify branch status. Refresh source control and try again.' + error: `Create ${copy.shortLabel} failed: could not verify branch status. Refresh source control and try again.` } } } @@ -311,7 +369,7 @@ export async function getHostedReviewCreationEligibility( nextAction: 'open_existing_review' } } - if (provider !== 'github') { + if (provider !== 'github' && provider !== 'gitlab') { return { ...baseResult, canCreate: false, @@ -334,7 +392,11 @@ export async function getHostedReviewCreationEligibility( if ((args.behind ?? 0) > 0) { return { ...baseResult, canCreate: false, blockedReason: 'needs_sync', nextAction: 'sync' } } - if (!(await isGitHubAuthenticated(args.repoPath, args.connectionId))) { + const authenticated = + provider === 'gitlab' + ? await isGitLabAuthenticated(args.repoPath, args.connectionId) + : await isGitHubAuthenticated(args.repoPath, args.connectionId) + if (!authenticated) { return { ...baseResult, canCreate: false, @@ -353,7 +415,7 @@ export async function createHostedReview( input: CreateHostedReviewInput, connectionId?: string | null ): Promise { - if (input.provider !== 'github') { + if (input.provider !== 'github' && input.provider !== 'gitlab') { return { ok: false, code: 'unsupported_provider', @@ -361,16 +423,20 @@ export async function createHostedReview( } } const provider = await detectHostedReviewProvider(repoPath, connectionId) - if (provider !== 'github') { + if (provider !== input.provider) { + const copy = reviewCopy(input.provider) return { ok: false, code: 'unsupported_provider', - error: 'Creating pull requests requires a GitHub remote.' + error: `Creating ${copy.reviewLabel}s requires a ${copy.providerName} remote.` } } const blocked = await validateCurrentBranchCanCreateReview(repoPath, connectionId, input) if (blocked) { return blocked } + if (input.provider === 'gitlab') { + return createGitLabMergeRequest(repoPath, input, connectionId) + } return createGitHubPullRequest(repoPath, input, connectionId) } diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 1ea464695..e683f74a4 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -47,14 +47,22 @@ import type { GitHubWorkItemDetails, GitHubViewer, GitLabAssignableUser, + GitLabAuthDiagnostic, GitLabCommentResult, + GitLabDiscussionResolveResult, GitLabIssueInfo, GitLabIssueUpdate, + GitLabJobTraceResult, + GitLabMRInlineCommentInput, + GitLabMRReviewersUpdateResult, + GitLabMRUpdate, GitLabProjectRef, + GitLabRetryJobResult, GitLabTodo, GitLabViewer, GitLabWorkItem, GitLabWorkItemDetails, + GetGitLabRateLimitResult, ListMergeRequestsResult, MRInfo, MRListState, @@ -1167,6 +1175,11 @@ export type PreloadApi = { // host, paginated envelope from `glab api -i`). gl: { viewer: () => Promise + diagnoseAuth: () => Promise + rateLimit: (args?: { + force?: boolean + host?: string | null + }) => Promise projectSlug: (args: { repoPath: string }) => Promise mrForBranch: (args: { repoPath: string @@ -1233,11 +1246,44 @@ export type PreloadApi = { iid: number method?: 'merge' | 'squash' | 'rebase' }) => Promise<{ ok: true } | { ok: false; error: string }> + updateMR: (args: { + repoPath: string + iid: number + updates: GitLabMRUpdate + }) => Promise<{ ok: true } | { ok: false; error: string }> + updateMRReviewers: (args: { + repoPath: string + iid: number + reviewerIds: number[] + projectRef?: GitLabProjectRef | null + }) => Promise addMRComment: (args: { repoPath: string iid: number body: string }) => Promise + addMRInlineComment: (args: { + repoPath: string + iid: number + input: GitLabMRInlineCommentInput + projectRef?: GitLabProjectRef | null + }) => Promise + resolveMRDiscussion: (args: { + repoPath: string + iid: number + discussionId: string + resolved: boolean + }) => Promise + jobTrace: (args: { + repoPath: string + jobId: number + projectRef?: GitLabProjectRef | null + }) => Promise + retryJob: (args: { + repoPath: string + jobId: number + projectRef?: GitLabProjectRef | null + }) => Promise workItemByPath: (args: { repoPath: string host: string diff --git a/src/preload/gitlab.ts b/src/preload/gitlab.ts index 6c4011ca1..809545816 100644 --- a/src/preload/gitlab.ts +++ b/src/preload/gitlab.ts @@ -6,6 +6,9 @@ import { ipcRenderer } from 'electron' export const glApi = { viewer: (): Promise => ipcRenderer.invoke('gitlab:viewer'), + diagnoseAuth: (): Promise => ipcRenderer.invoke('gitlab:diagnoseAuth'), + rateLimit: (args?: { force?: boolean; host?: string | null }): Promise => + ipcRenderer.invoke('gitlab:rateLimit', args), projectSlug: (args: { repoPath: string }): Promise => ipcRenderer.invoke('gitlab:projectSlug', args), @@ -95,9 +98,43 @@ export const glApi = { }): Promise<{ ok: true } | { ok: false; error: string }> => ipcRenderer.invoke('gitlab:mergeMR', args), + updateMR: (args: { + repoPath: string + iid: number + updates: unknown + }): Promise<{ ok: true } | { ok: false; error: string }> => + ipcRenderer.invoke('gitlab:updateMR', args), + + updateMRReviewers: (args: { + repoPath: string + iid: number + reviewerIds: number[] + projectRef?: unknown + }): Promise => ipcRenderer.invoke('gitlab:updateMRReviewers', args), + addMRComment: (args: { repoPath: string; iid: number; body: string }): Promise => ipcRenderer.invoke('gitlab:addMRComment', args), + addMRInlineComment: (args: { + repoPath: string + iid: number + input: unknown + projectRef?: unknown + }): Promise => ipcRenderer.invoke('gitlab:addMRInlineComment', args), + + resolveMRDiscussion: (args: { + repoPath: string + iid: number + discussionId: string + resolved: boolean + }): Promise => ipcRenderer.invoke('gitlab:resolveMRDiscussion', args), + + jobTrace: (args: { repoPath: string; jobId: number; projectRef?: unknown }): Promise => + ipcRenderer.invoke('gitlab:jobTrace', args), + + retryJob: (args: { repoPath: string; jobId: number; projectRef?: unknown }): Promise => + ipcRenderer.invoke('gitlab:retryJob', args), + workItemByPath: (args: { repoPath: string host: string diff --git a/src/renderer/src/components/GitLabItemDialog.tsx b/src/renderer/src/components/GitLabItemDialog.tsx index f0c9f7a05..ae36d2176 100644 --- a/src/renderer/src/components/GitLabItemDialog.tsx +++ b/src/renderer/src/components/GitLabItemDialog.tsx @@ -10,7 +10,17 @@ inline review-comment positioning / approvals are deferred to v1.5 since they mirror substantial GitHub-side surface area. */ import React, { useCallback, useEffect, useState } from 'react' -import { CircleDot, ExternalLink, GitMerge, LoaderCircle, RefreshCw, Send } from 'lucide-react' +import { + Check, + CircleDot, + ExternalLink, + GitMerge, + LoaderCircle, + Pencil, + RefreshCw, + Send, + X +} from 'lucide-react' import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { Sheet, SheetContent, SheetDescription, SheetTitle } from '@/components/ui/sheet' @@ -21,7 +31,9 @@ import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' import { useMountedRef } from '@/hooks/useMountedRef' import { cn } from '@/lib/utils' import type { + GitLabAssignableUser, GitLabPipelineJob, + GitLabMRUpdate, GitLabWorkItem, GitLabWorkItemDetails, MRComment @@ -34,6 +46,12 @@ type Props = { onCreateWorkspace?: (item: GitLabWorkItem) => void } +type JobTraceState = { + loading: boolean + trace?: string + error?: string +} + // Why: GitLab MR / issue states map onto a coarser palette than GitHub. const STATE_TONE: Record = { opened: 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-300', @@ -81,7 +99,62 @@ function StateBadge({ state }: { state: GitLabWorkItem['state'] }): React.JSX.El ) } -function CommentCard({ comment }: { comment: MRComment }): React.JSX.Element { +function normalizeGitLabLabels(labels: readonly string[]): string[] { + const seen = new Set() + const normalized: string[] = [] + for (const label of labels) { + const trimmed = label.trim() + const key = trimmed.toLowerCase() + if (!trimmed || seen.has(key)) { + continue + } + seen.add(key) + normalized.push(trimmed) + } + return normalized +} + +function parseGitLabLabelDraft(value: string): string[] { + return normalizeGitLabLabels(value.split(',')) +} + +function formatGitLabLabelDraft(labels: readonly string[]): string { + return normalizeGitLabLabels(labels).join(', ') +} + +function toggleGitLabLabelDraft(value: string, label: string): string { + const labels = parseGitLabLabelDraft(value) + const key = label.trim().toLowerCase() + const next = labels.some((item) => item.toLowerCase() === key) + ? labels.filter((item) => item.toLowerCase() !== key) + : [...labels, label] + return formatGitLabLabelDraft(next) +} + +function gitLabUserKey(user: GitLabAssignableUser): string { + return typeof user.id === 'number' ? `id:${user.id}` : `username:${user.username.toLowerCase()}` +} + +function dedupeGitLabUsers(users: readonly GitLabAssignableUser[]): GitLabAssignableUser[] { + const byKey = new Map() + for (const user of users) { + byKey.set(gitLabUserKey(user), user) + } + return Array.from(byKey.values()).sort((a, b) => a.username.localeCompare(b.username)) +} + +function CommentCard({ + comment, + canResolve, + resolving, + onResolve +}: { + comment: MRComment + canResolve?: boolean + resolving?: boolean + onResolve?: (threadId: string, resolved: boolean) => void +}): React.JSX.Element { + const hasThread = Boolean(comment.threadId) return (
@@ -103,7 +176,22 @@ function CommentCard({ comment }: { comment: MRComment }): React.JSX.Element { ) : null}
- {comment.createdAt ? new Date(comment.createdAt).toLocaleDateString() : ''} +
+ {canResolve && hasThread && onResolve ? ( + + ) : null} + {comment.createdAt ? new Date(comment.createdAt).toLocaleDateString() : ''} +
{comment.path ? (
@@ -116,33 +204,100 @@ function CommentCard({ comment }: { comment: MRComment }): React.JSX.Element { ) } -function PipelineJobRow({ job }: { job: GitLabPipelineJob }): React.JSX.Element { +function PipelineJobRow({ + job, + expanded, + traceState, + retrying, + onToggleTrace, + onRetry +}: { + job: GitLabPipelineJob + expanded: boolean + traceState?: JobTraceState + retrying: boolean + onToggleTrace: (job: GitLabPipelineJob) => void + onRetry: (job: GitLabPipelineJob) => void +}): React.JSX.Element { + const canRetry = ['failed', 'canceled', 'cancelled'].includes(job.status) return ( - +
+
+ + {job.stage} + + {job.status} + + + {/* Why: durations come back as seconds; show "Nm Ns" for >60s + and "Ns" otherwise. null = job hasn't finished. */} + {typeof job.duration === 'number' + ? job.duration >= 60 + ? `${Math.floor(job.duration / 60)}m ${Math.floor(job.duration % 60)}s` + : `${Math.floor(job.duration)}s` + : '—'} + +
+ {canRetry ? ( + + ) : null} + {job.webUrl ? ( + + ) : null} +
+
+ {expanded ? ( +
+
+ Job log + +
+ {traceState?.loading ? ( +
+ + Loading log +
+ ) : traceState?.error ? ( +
{traceState.error}
+ ) : ( +
+              {traceState?.trace?.trim() ? traceState.trace : 'No log output.'}
+            
+ )} +
+ ) : null} +
) } @@ -158,6 +313,25 @@ export default function GitLabItemDialog({ const [refreshNonce, setRefreshNonce] = useState(0) const [commentDraft, setCommentDraft] = useState('') const [commentSubmitting, setCommentSubmitting] = useState(false) + const [resolvingThreadId, setResolvingThreadId] = useState(null) + const [editingDetails, setEditingDetails] = useState(false) + const [titleDraft, setTitleDraft] = useState('') + const [bodyDraft, setBodyDraft] = useState('') + const [labelDraft, setLabelDraft] = useState('') + const [labelOptions, setLabelOptions] = useState(null) + const [labelOptionsLoading, setLabelOptionsLoading] = useState(false) + const [detailsSaving, setDetailsSaving] = useState(false) + const [reviewerOptions, setReviewerOptions] = useState(null) + const [reviewerOptionsLoading, setReviewerOptionsLoading] = useState(false) + const [reviewerUpdating, setReviewerUpdating] = useState(false) + const [reviewerDraftId, setReviewerDraftId] = useState('') + const [inlineCommentFilePath, setInlineCommentFilePath] = useState('') + const [inlineCommentLine, setInlineCommentLine] = useState('') + const [inlineCommentBody, setInlineCommentBody] = useState('') + const [inlineCommentSubmitting, setInlineCommentSubmitting] = useState(false) + const [expandedJobId, setExpandedJobId] = useState(null) + const [jobTraceById, setJobTraceById] = useState>({}) + const [retryingJobId, setRetryingJobId] = useState(null) const [actionInFlight, setActionInFlight] = useState<'close' | 'reopen' | 'merge' | null>(null) const mountedRef = useMountedRef() @@ -166,6 +340,7 @@ export default function GitLabItemDialog({ setDetails(null) setLoading(false) setError(null) + setEditingDetails(false) return } let stale = false @@ -202,12 +377,354 @@ export default function GitLabItemDialog({ // user doesn't accidentally post one MR's draft against another. useEffect(() => { setCommentDraft('') + setEditingDetails(false) + setTitleDraft('') + setBodyDraft('') + setLabelDraft('') + setLabelOptions(null) + setLabelOptionsLoading(false) + setReviewerOptions(null) + setReviewerOptionsLoading(false) + setReviewerUpdating(false) + setReviewerDraftId('') + setInlineCommentFilePath('') + setInlineCommentLine('') + setInlineCommentBody('') + setInlineCommentSubmitting(false) + setExpandedJobId(null) + setJobTraceById({}) + setRetryingJobId(null) }, [item?.id]) const handleRefresh = useCallback(() => { setRefreshNonce((n) => n + 1) }, []) + const loadGitLabLabelOptions = useCallback(async (): Promise => { + if (!repoPath || labelOptions !== null || labelOptionsLoading) { + return + } + setLabelOptionsLoading(true) + try { + const labels = await window.api.gl.listLabels({ repoPath }) + if (mountedRef.current) { + setLabelOptions(normalizeGitLabLabels(labels)) + } + } catch { + if (mountedRef.current) { + setLabelOptions([]) + } + } finally { + if (mountedRef.current) { + setLabelOptionsLoading(false) + } + } + }, [labelOptions, labelOptionsLoading, mountedRef, repoPath]) + + const loadGitLabReviewerOptions = useCallback(async (): Promise => { + if (!repoPath || reviewerOptions !== null || reviewerOptionsLoading) { + return + } + setReviewerOptionsLoading(true) + try { + const users = await window.api.gl.listAssignableUsers({ repoPath }) + if (mountedRef.current) { + setReviewerOptions(dedupeGitLabUsers(users)) + } + } catch { + if (mountedRef.current) { + setReviewerOptions([]) + } + } finally { + if (mountedRef.current) { + setReviewerOptionsLoading(false) + } + } + }, [mountedRef, repoPath, reviewerOptions, reviewerOptionsLoading]) + + const handleStartDetailsEdit = useCallback((): void => { + if (!item || !details || item.type !== 'mr') { + return + } + setTitleDraft(details.item.title || item.title) + setBodyDraft(details.body) + setLabelDraft(formatGitLabLabelDraft(details.item.labels ?? item.labels)) + setEditingDetails(true) + void loadGitLabLabelOptions() + }, [details, item, loadGitLabLabelOptions]) + + const handleCancelDetailsEdit = useCallback((): void => { + setEditingDetails(false) + setTitleDraft('') + setBodyDraft('') + setLabelDraft('') + }, []) + + const handleSaveDetails = useCallback(async (): Promise => { + if (!item || !details || !repoPath || item.type !== 'mr') { + return + } + const currentTitle = details.item.title || item.title + const currentBody = details.body + const currentLabels = normalizeGitLabLabels(details.item.labels ?? item.labels) + const nextTitle = titleDraft.trim() + const nextBody = bodyDraft + const nextLabels = parseGitLabLabelDraft(labelDraft) + if (!nextTitle) { + toast.error('MR title is required.') + return + } + + const currentLabelKeys = new Set(currentLabels.map((label) => label.toLowerCase())) + const nextLabelKeys = new Set(nextLabels.map((label) => label.toLowerCase())) + const addLabels = nextLabels.filter((label) => !currentLabelKeys.has(label.toLowerCase())) + const removeLabels = currentLabels.filter((label) => !nextLabelKeys.has(label.toLowerCase())) + const updates: GitLabMRUpdate = {} + if (nextTitle !== currentTitle) { + updates.title = nextTitle + } + if (nextBody !== currentBody) { + updates.body = nextBody + } + if (addLabels.length > 0) { + updates.addLabels = addLabels + } + if (removeLabels.length > 0) { + updates.removeLabels = removeLabels + } + if (Object.keys(updates).length === 0) { + handleCancelDetailsEdit() + return + } + + setDetailsSaving(true) + try { + const res = await window.api.gl.updateMR({ repoPath, iid: item.number, updates }) + if (res.ok) { + if (mountedRef.current) { + setDetails((current) => + current + ? { + ...current, + body: nextBody, + item: { ...current.item, title: nextTitle, labels: nextLabels } + } + : current + ) + setLabelOptions((current) => + current ? normalizeGitLabLabels([...current, ...nextLabels]) : current + ) + setEditingDetails(false) + setTitleDraft('') + setBodyDraft('') + setLabelDraft('') + } + } else if (mountedRef.current) { + toast.error(res.error) + } + } finally { + if (mountedRef.current) { + setDetailsSaving(false) + } + } + }, [ + bodyDraft, + details, + handleCancelDetailsEdit, + item, + labelDraft, + mountedRef, + repoPath, + titleDraft + ]) + + const handleToggleJobTrace = useCallback( + async (job: GitLabPipelineJob): Promise => { + if (expandedJobId === job.id) { + setExpandedJobId(null) + return + } + setExpandedJobId(job.id) + if (!repoPath || !item || jobTraceById[job.id]?.trace || jobTraceById[job.id]?.error) { + return + } + setJobTraceById((current) => ({ + ...current, + [job.id]: { loading: true } + })) + try { + const result = await window.api.gl.jobTrace({ + repoPath, + jobId: job.id, + projectRef: details?.item.projectRef ?? item.projectRef ?? null + }) + if (!mountedRef.current) { + return + } + setJobTraceById((current) => ({ + ...current, + [job.id]: result.ok + ? { loading: false, trace: result.trace } + : { loading: false, error: result.error } + })) + } catch (error) { + if (mountedRef.current) { + setJobTraceById((current) => ({ + ...current, + [job.id]: { + loading: false, + error: error instanceof Error ? error.message : String(error) + } + })) + } + } + }, + [details?.item.projectRef, expandedJobId, item, jobTraceById, mountedRef, repoPath] + ) + + const handleRetryJob = useCallback( + async (job: GitLabPipelineJob): Promise => { + if (!repoPath || !item) { + return + } + setRetryingJobId(job.id) + try { + const result = await window.api.gl.retryJob({ + repoPath, + jobId: job.id, + projectRef: details?.item.projectRef ?? item.projectRef ?? null + }) + if (!mountedRef.current) { + return + } + if (result.ok) { + toast.success(`Retried ${job.name}`) + if (result.job) { + setDetails((current) => + current + ? { + ...current, + pipelineJobs: (current.pipelineJobs ?? []).map((existing) => + existing.id === job.id ? result.job! : existing + ) + } + : current + ) + } + handleRefresh() + } else { + toast.error(result.error) + } + } finally { + if (mountedRef.current) { + setRetryingJobId(null) + } + } + }, + [details?.item.projectRef, handleRefresh, item, mountedRef, repoPath] + ) + + const handleSetReviewers = useCallback( + async (nextReviewers: GitLabAssignableUser[]): Promise => { + if (!repoPath || !item || !details || item.type !== 'mr') { + return + } + const reviewerIds = nextReviewers + .map((reviewer) => reviewer.id) + .filter((id): id is number => typeof id === 'number') + if (reviewerIds.length !== nextReviewers.length) { + toast.error('Reviewer id is unavailable for this GitLab user.') + return + } + setReviewerUpdating(true) + try { + const result = await window.api.gl.updateMRReviewers({ + repoPath, + iid: item.number, + reviewerIds, + projectRef: details.item.projectRef ?? item.projectRef ?? null + }) + if (!mountedRef.current) { + return + } + if (result.ok) { + setDetails((current) => + current ? { ...current, reviewers: dedupeGitLabUsers(result.reviewers) } : current + ) + setReviewerDraftId('') + setReviewerOptions((current) => + current ? dedupeGitLabUsers([...current, ...result.reviewers]) : current + ) + } else { + toast.error(result.error) + } + } finally { + if (mountedRef.current) { + setReviewerUpdating(false) + } + } + }, + [details, item, mountedRef, repoPath] + ) + + const handleSubmitInlineComment = useCallback(async (): Promise => { + if (!repoPath || !item || !details || item.type !== 'mr') { + return + } + const file = (details.files ?? []).find((row) => row.path === inlineCommentFilePath) + const line = Number.parseInt(inlineCommentLine, 10) + const body = inlineCommentBody.trim() + if (!file || !Number.isFinite(line) || line <= 0 || !body) { + toast.error('File, line, and comment are required.') + return + } + if (!details.baseSha || !details.startSha || !details.headSha) { + toast.error('MR diff refs are unavailable for inline comments.') + return + } + setInlineCommentSubmitting(true) + try { + const result = await window.api.gl.addMRInlineComment({ + repoPath, + iid: item.number, + projectRef: details.item.projectRef ?? item.projectRef ?? null, + input: { + body, + path: file.path, + ...(file.oldPath ? { oldPath: file.oldPath } : {}), + line, + baseSha: details.baseSha, + startSha: details.startSha, + headSha: details.headSha + } + }) + if (!mountedRef.current) { + return + } + if (result.ok) { + setDetails((current) => + current ? { ...current, comments: [...current.comments, result.comment] } : current + ) + setInlineCommentBody('') + toast.success('Inline comment added') + } else { + toast.error(result.error) + } + } finally { + if (mountedRef.current) { + setInlineCommentSubmitting(false) + } + } + }, [ + details, + inlineCommentBody, + inlineCommentFilePath, + inlineCommentLine, + item, + mountedRef, + repoPath + ]) + const handleClose = useCallback(async (): Promise => { if (!item || !repoPath || item.type !== 'mr') { return @@ -310,6 +827,44 @@ export default function GitLabItemDialog({ } }, [commentDraft, item, repoPath, mountedRef, handleRefresh]) + const handleResolveDiscussion = useCallback( + async (threadId: string, resolved: boolean): Promise => { + if (!item || !repoPath || item.type !== 'mr') { + return + } + setResolvingThreadId(threadId) + try { + const res = await window.api.gl.resolveMRDiscussion({ + repoPath, + iid: item.number, + discussionId: threadId, + resolved + }) + if (res.ok) { + if (mountedRef.current) { + setDetails((current) => + current + ? { + ...current, + comments: current.comments.map((comment) => + comment.threadId === threadId ? { ...comment, isResolved: resolved } : comment + ) + } + : current + ) + } + } else if (mountedRef.current) { + toast.error(res.error) + } + } finally { + if (mountedRef.current) { + setResolvingThreadId(null) + } + } + }, + [item, repoPath, mountedRef] + ) + // Why: GitMerge for MRs visually disambiguates from GitBranch (and // matches gitlab.com's MR iconography); CircleDot stays on issues. const Icon = item?.type === 'mr' ? GitMerge : CircleDot @@ -318,12 +873,26 @@ export default function GitLabItemDialog({ const canClose = isMR && item?.state === 'opened' const canReopen = isMR && item?.state === 'closed' const canMerge = isMR && item?.state === 'opened' + const visibleTitle = details?.item.title || item?.title || '' + const visibleLabels = normalizeGitLabLabels(details?.item.labels ?? item?.labels ?? []) + const labelSuggestionOptions = normalizeGitLabLabels([ + ...(labelOptions ?? []), + ...visibleLabels, + ...parseGitLabLabelDraft(labelDraft) + ]) + const currentReviewers = dedupeGitLabUsers(details?.reviewers ?? []) + const currentReviewerKeys = new Set(currentReviewers.map(gitLabUserKey)) + const reviewerOptionRows = dedupeGitLabUsers([ + ...(reviewerOptions ?? []), + ...currentReviewers + ]).filter((user) => !currentReviewerKeys.has(gitLabUserKey(user))) + const approvalState = details?.approvalState return ( !open && onClose()}> - {item ? item.title : 'Work item'} + {item ? visibleTitle : 'Work item'} GitLab work item detail @@ -342,8 +911,20 @@ export default function GitLabItemDialog({ {item.author ? by {item.author} : null}

- {item.title} + {visibleTitle}

+ {visibleLabels.length > 0 ? ( +
+ {visibleLabels.map((label) => ( + + {label} + + ))} +
+ ) : null} + +
+ {currentReviewers.length > 0 ? ( + currentReviewers.map((reviewer) => ( + + {reviewer.username} + + + )) + ) : ( + No reviewers. + )} +
+ {reviewerOptions ? ( +
+ + +
+ ) : null} + {approvalState?.rules.length ? ( +
+ {approvalState.rules.map((rule) => ( +
+ {rule.name} + + {rule.approved ? 'Approved' : `${rule.approvalsRequired} required`} + +
+ ))} +
+ ) : null} + + ) : null} {loading && !details ? (
+ ) : editingDetails ? ( +
+
+ + setTitleDraft(event.target.value)} + disabled={detailsSaving} + className="h-9 w-full rounded-md border border-input bg-transparent px-2.5 text-sm shadow-xs focus:border-ring focus:outline-none focus:ring-[3px] focus:ring-ring/50" + /> +
+
+ +