diff --git a/src/main/azure-devops/client.test.ts b/src/main/azure-devops/client.test.ts new file mode 100644 index 000000000..1b3e5fb11 --- /dev/null +++ b/src/main/azure-devops/client.test.ts @@ -0,0 +1,179 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + getAzureDevOpsAuthStatus, + getAzureDevOpsPullRequestForBranch, + normalizeAzureDevOpsApiBaseUrl +} from './client' +import { _resetAzureDevOpsRepoRefCache } from './repository-ref' + +const gitExecFileAsyncMock = vi.hoisted(() => vi.fn()) + +vi.mock('../git/runner', () => ({ + gitExecFileAsync: gitExecFileAsyncMock +})) + +const OLD_ENV = process.env +const OLD_FETCH = globalThis.fetch + +describe('Azure DevOps client', () => { + beforeEach(() => { + process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'pat-token' } + gitExecFileAsyncMock.mockReset() + _resetAzureDevOpsRepoRefCache() + }) + + afterEach(() => { + process.env = OLD_ENV + globalThis.fetch = OLD_FETCH + _resetAzureDevOpsRepoRefCache() + }) + + it('normalizes configured API base URLs', () => { + expect(normalizeAzureDevOpsApiBaseUrl('https://dev.azure.com/acme/Project/_apis/')).toBe( + 'https://dev.azure.com/acme/Project' + ) + }) + + it('marks token-only auth as configured but unverified because repository remotes supply the API base URL', async () => { + delete process.env.ORCA_AZURE_DEVOPS_API_BASE_URL + await expect(getAzureDevOpsAuthStatus()).resolves.toEqual({ + configured: true, + authenticated: false, + account: null, + baseUrl: null, + tokenConfigured: true + }) + }) + + it('resolves a PR for a branch through repository, PR, and status REST calls', async () => { + gitExecFileAsyncMock.mockResolvedValue({ + stdout: 'https://dev.azure.com/acme/Project/_git/repo\n' + }) + const requests: { pathname: string; search: string; authorization: string | null }[] = [] + globalThis.fetch = vi.fn(async (input: string | URL | Request) => { + const url = new URL(String(input)) + requests.push({ + pathname: url.pathname, + search: url.search, + authorization: null + }) + const response = (body: unknown): Response => + new Response(JSON.stringify(body), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) + + if (url.pathname === '/acme/Project/_apis/git/repositories/repo') { + return response({ + id: 'repo-guid', + webUrl: 'https://dev.azure.com/acme/Project/_git/repo' + }) + } + if (url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests') { + expect(url.searchParams.get('searchCriteria.sourceRefName')).toBe( + 'refs/heads/feature/azure' + ) + expect(url.searchParams.get('searchCriteria.status')).toBe('all') + return response({ + value: [ + { + pullRequestId: 17, + title: 'Old Azure PR', + status: 'completed', + creationDate: '2026-05-10T00:00:00Z', + lastMergeSourceCommit: { commitId: 'oldsha' } + }, + { + pullRequestId: 18, + title: 'Azure branch', + status: 'active', + creationDate: '2026-05-11T00:00:00Z', + mergeStatus: 'succeeded', + lastMergeSourceCommit: { commitId: 'abc123' } + } + ] + }) + } + if ( + url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests/18/statuses' + ) { + return response({ value: [{ state: 'succeeded' }] }) + } + return new Response(JSON.stringify({ message: 'not found' }), { status: 404 }) + }) as never + + await expect( + getAzureDevOpsPullRequestForBranch('/repo', 'refs/heads/feature/azure') + ).resolves.toEqual({ + number: 18, + title: 'Azure branch', + state: 'open', + url: 'https://dev.azure.com/acme/Project/_git/repo/pullrequest/18', + status: 'success', + updatedAt: '2026-05-11T00:00:00Z', + mergeable: 'MERGEABLE', + headSha: 'abc123' + }) + expect(requests.map((request) => request.pathname)).toEqual([ + '/acme/Project/_apis/git/repositories/repo', + '/acme/Project/_apis/git/repositories/repo-guid/pullRequests', + '/acme/Project/_apis/git/repositories/repo-guid/pullRequests/18/statuses' + ]) + }) + + it('uses the most recent branch PR instead of preferring stale active PRs', async () => { + gitExecFileAsyncMock.mockResolvedValue({ + stdout: 'https://dev.azure.com/acme/Project/_git/repo\n' + }) + globalThis.fetch = vi.fn(async (input: string | URL | Request) => { + const url = new URL(String(input)) + const response = (body: unknown): Response => + new Response(JSON.stringify(body), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) + + if (url.pathname === '/acme/Project/_apis/git/repositories/repo') { + return response({ id: 'repo-guid' }) + } + if (url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests') { + return response({ + value: [ + { + pullRequestId: 20, + title: 'Stale active PR', + status: 'active', + creationDate: '2026-05-10T00:00:00Z', + mergeStatus: 'succeeded', + lastMergeSourceCommit: { commitId: 'oldsha' } + }, + { + pullRequestId: 21, + title: 'Latest completed PR', + status: 'completed', + creationDate: '2026-05-15T00:00:00Z', + closedDate: '2026-05-16T00:00:00Z', + mergeStatus: 'succeeded', + lastMergeSourceCommit: { commitId: 'newsha' } + } + ] + }) + } + if ( + url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests/21/statuses' + ) { + return response({ value: [{ state: 'succeeded' }] }) + } + return new Response(JSON.stringify({ message: 'not found' }), { status: 404 }) + }) as never + + await expect( + getAzureDevOpsPullRequestForBranch('/repo', 'refs/heads/feature/azure') + ).resolves.toMatchObject({ + number: 21, + title: 'Latest completed PR', + state: 'merged', + headSha: 'newsha' + }) + }) +}) diff --git a/src/main/azure-devops/client.ts b/src/main/azure-devops/client.ts new file mode 100644 index 000000000..ca692563e --- /dev/null +++ b/src/main/azure-devops/client.ts @@ -0,0 +1,327 @@ +import { Buffer } from 'buffer' +import { + deriveAzureDevOpsStatus, + mapAzureDevOpsPullRequest, + type AzureDevOpsPullRequestInfo, + type RawAzureDevOpsPullRequest, + type RawAzureDevOpsStatus +} from './pull-request-mappers' +import { getAzureDevOpsRepoRef, type AzureDevOpsRepoRef } from './repository-ref' + +const REQUEST_TIMEOUT_MS = 5000 + +type AzureDevOpsAuthConfig = { + apiBaseUrl: string | null + pat: string | null + accessToken: string | null + username: string | null +} + +export type AzureDevOpsAuthStatus = { + configured: boolean + authenticated: boolean + account: string | null + baseUrl: string | null + tokenConfigured: boolean +} + +type RequestOptions = { + searchParams?: Record + timeoutMs?: number +} + +type RawAzureDevOpsRepository = { + id?: string | null + name?: string | null + webUrl?: string | null + _links?: { + web?: { + href?: string | null + } | null + } | null +} + +function envValue(name: string): string | null { + const value = process.env[name]?.trim() ?? '' + return value.length > 0 ? value : null +} + +export function normalizeAzureDevOpsApiBaseUrl(value: string): string { + return value + .trim() + .replace(/\/+$/, '') + .replace(/\/_apis$/i, '') +} + +function getAuthConfig(): AzureDevOpsAuthConfig { + return { + apiBaseUrl: envValue('ORCA_AZURE_DEVOPS_API_BASE_URL'), + pat: envValue('ORCA_AZURE_DEVOPS_TOKEN') ?? envValue('ORCA_AZURE_DEVOPS_PAT'), + accessToken: envValue('ORCA_AZURE_DEVOPS_ACCESS_TOKEN'), + username: envValue('ORCA_AZURE_DEVOPS_USERNAME') + } +} + +function tokenConfigured(config: AzureDevOpsAuthConfig): boolean { + return Boolean(config.pat || config.accessToken) +} + +function authHeaders(config: AzureDevOpsAuthConfig): Record { + if (config.accessToken) { + return { Authorization: `Bearer ${config.accessToken}` } + } + if (config.pat) { + const encoded = Buffer.from(`${config.username ?? ''}:${config.pat}`).toString('base64') + return { Authorization: `Basic ${encoded}` } + } + return {} +} + +function configuredApiBaseUrl(repo: AzureDevOpsRepoRef): string { + const configured = getAuthConfig().apiBaseUrl + return configured ? normalizeAzureDevOpsApiBaseUrl(configured) : repo.apiBaseUrl +} + +function apiUrl(baseUrl: string, path: string, searchParams?: RequestOptions['searchParams']): URL { + const url = new URL(`${baseUrl.replace(/\/+$/, '')}${path}`) + const params = { ...searchParams, 'api-version': searchParams?.['api-version'] ?? '7.1' } + for (const [key, value] of Object.entries(params)) { + url.searchParams.set(key, String(value)) + } + return url +} + +async function requestJsonAtBase( + baseUrl: string, + path: string, + options: RequestOptions = {} +): Promise { + const config = getAuthConfig() + const controller = new AbortController() + const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? REQUEST_TIMEOUT_MS) + try { + const response = await fetch(apiUrl(baseUrl, path, options.searchParams), { + headers: { + Accept: 'application/json', + ...authHeaders(config) + }, + signal: controller.signal + }) + if (!response.ok) { + return null + } + return (await response.json()) as T + } catch { + return null + } finally { + clearTimeout(timeout) + } +} + +function requestJson( + repo: AzureDevOpsRepoRef, + path: string, + options: RequestOptions = {} +): Promise { + return requestJsonAtBase(configuredApiBaseUrl(repo), path, options) +} + +function encodePathSegment(value: string): string { + return encodeURIComponent(value) +} + +async function getRepository( + repo: AzureDevOpsRepoRef +): Promise<{ idOrName: string; webBaseUrl: string } | null> { + const raw = await requestJson( + repo, + `/_apis/git/repositories/${encodePathSegment(repo.repository)}` + ) + if (!raw) { + return { idOrName: repo.repository, webBaseUrl: repo.webBaseUrl } + } + return { + idOrName: raw.id?.trim() || repo.repository, + webBaseUrl: raw.webUrl ?? raw._links?.web?.href ?? repo.webBaseUrl + } +} + +function readStatusList( + raw: RawAzureDevOpsStatus[] | { value?: RawAzureDevOpsStatus[] } | null +): RawAzureDevOpsStatus[] { + if (Array.isArray(raw)) { + return raw + } + return raw?.value ?? [] +} + +async function getPullRequestStatuses( + repo: AzureDevOpsRepoRef, + repoIdOrName: string, + pr: RawAzureDevOpsPullRequest +): Promise { + const raw = await requestJson( + repo, + `/_apis/git/repositories/${encodePathSegment(repoIdOrName)}/pullRequests/${encodePathSegment( + String(pr.pullRequestId) + )}/statuses` + ) + const prStatuses = readStatusList(raw) + if (prStatuses.length > 0) { + return prStatuses + } + const commitId = pr.lastMergeSourceCommit?.commitId?.trim() + if (!commitId) { + return pr.statuses ?? [] + } + const commitStatuses = await requestJson< + RawAzureDevOpsStatus[] | { value?: RawAzureDevOpsStatus[] } + >( + repo, + `/_apis/git/repositories/${encodePathSegment(repoIdOrName)}/commits/${encodePathSegment( + commitId + )}/statuses` + ) + return readStatusList(commitStatuses) +} + +async function normalizePullRequest( + repo: AzureDevOpsRepoRef, + repoIdOrName: string, + webBaseUrl: string, + raw: RawAzureDevOpsPullRequest +): Promise { + const statuses = await getPullRequestStatuses(repo, repoIdOrName, raw) + return mapAzureDevOpsPullRequest(raw, deriveAzureDevOpsStatus(statuses), webBaseUrl) +} + +function sortPullRequestsForBranch( + left: RawAzureDevOpsPullRequest, + right: RawAzureDevOpsPullRequest +): number { + const leftTime = Date.parse(left.closedDate ?? left.creationDate ?? '') || 0 + const rightTime = Date.parse(right.closedDate ?? right.creationDate ?? '') || 0 + if (leftTime !== rightTime) { + return rightTime - leftTime + } + const leftActive = left.status?.trim().toLowerCase() === 'active' + const rightActive = right.status?.trim().toLowerCase() === 'active' + if (leftActive !== rightActive) { + return leftActive ? -1 : 1 + } + return 0 +} + +export async function getAzureDevOpsAuthStatus(): Promise { + const config = getAuthConfig() + const baseUrl = config.apiBaseUrl ? normalizeAzureDevOpsApiBaseUrl(config.apiBaseUrl) : null + const hasToken = tokenConfigured(config) + if (!baseUrl && !hasToken) { + return { + configured: false, + authenticated: false, + account: null, + baseUrl: null, + tokenConfigured: false + } + } + if (!baseUrl) { + return { + configured: true, + authenticated: false, + account: null, + baseUrl: null, + tokenConfigured: hasToken + } + } + + const connection = await requestJsonAtBase<{ + authenticatedUser?: { + providerDisplayName?: string | null + customDisplayName?: string | null + uniqueName?: string | null + } | null + }>(baseUrl, '/_apis/connectionData', { timeoutMs: 4000 }) + const user = connection?.authenticatedUser + return { + configured: hasToken || connection !== null, + authenticated: connection !== null && (hasToken || user !== null), + account: user?.providerDisplayName ?? user?.customDisplayName ?? user?.uniqueName ?? null, + baseUrl, + tokenConfigured: hasToken + } +} + +export async function getAzureDevOpsPullRequest( + repoPath: string, + prNumber: number +): Promise { + const repo = await getAzureDevOpsRepoRef(repoPath) + if (!repo) { + return null + } + const repository = await getRepository(repo) + if (!repository) { + return null + } + const raw = await requestJson( + repo, + `/_apis/git/repositories/${encodePathSegment(repository.idOrName)}/pullRequests/${encodePathSegment( + String(prNumber) + )}` + ) + return raw ? normalizePullRequest(repo, repository.idOrName, repository.webBaseUrl, raw) : null +} + +export async function getAzureDevOpsPullRequestForBranch( + repoPath: string, + branch: string, + linkedPRNumber?: number | null +): Promise { + const branchName = branch.replace(/^refs\/heads\//, '') + if (!branchName && linkedPRNumber == null) { + return null + } + + const repo = await getAzureDevOpsRepoRef(repoPath) + if (!repo) { + return null + } + const repository = await getRepository(repo) + if (!repository) { + return null + } + + if (branchName) { + const list = await requestJson<{ value?: RawAzureDevOpsPullRequest[] }>( + repo, + `/_apis/git/repositories/${encodePathSegment(repository.idOrName)}/pullRequests`, + { + searchParams: { + 'searchCriteria.sourceRefName': `refs/heads/${branchName}`, + 'searchCriteria.status': 'all', + $top: 10 + } + } + ) + const raw = (list?.value ?? []).sort(sortPullRequestsForBranch)[0] + if (raw) { + return normalizePullRequest(repo, repository.idOrName, repository.webBaseUrl, raw) + } + } + + if (typeof linkedPRNumber !== 'number') { + return null + } + const raw = await requestJson( + repo, + `/_apis/git/repositories/${encodePathSegment(repository.idOrName)}/pullRequests/${encodePathSegment( + String(linkedPRNumber) + )}` + ) + return raw ? normalizePullRequest(repo, repository.idOrName, repository.webBaseUrl, raw) : null +} + +export async function getAzureDevOpsRepoSlug(repoPath: string): Promise { + return getAzureDevOpsRepoRef(repoPath) +} diff --git a/src/main/azure-devops/pull-request-mappers.test.ts b/src/main/azure-devops/pull-request-mappers.test.ts new file mode 100644 index 000000000..5d2f69bb1 --- /dev/null +++ b/src/main/azure-devops/pull-request-mappers.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { + deriveAzureDevOpsStatus, + mapAzureDevOpsPullRequest, + mapAzureDevOpsPullRequestState +} from './pull-request-mappers' + +describe('Azure DevOps pull request mappers', () => { + it('maps Azure DevOps PR states into the hosted review state set', () => { + expect(mapAzureDevOpsPullRequestState({ status: 'active' })).toBe('open') + expect(mapAzureDevOpsPullRequestState({ status: 'active', isDraft: true })).toBe('draft') + expect(mapAzureDevOpsPullRequestState({ status: 'completed' })).toBe('merged') + expect(mapAzureDevOpsPullRequestState({ status: 'abandoned' })).toBe('closed') + }) + + it('derives check status from Azure DevOps PR and commit status states', () => { + expect(deriveAzureDevOpsStatus([{ state: 'succeeded' }])).toBe('success') + expect(deriveAzureDevOpsStatus([{ state: 'succeeded' }, { state: 'pending' }])).toBe('pending') + expect(deriveAzureDevOpsStatus([{ state: 'succeeded' }, { state: 'failed' }])).toBe('failure') + expect(deriveAzureDevOpsStatus([])).toBe('neutral') + }) + + it('maps a raw PR into hosted review info', () => { + expect( + mapAzureDevOpsPullRequest( + { + pullRequestId: 42, + title: 'Add Azure support', + status: 'active', + creationDate: '2026-05-15T12:00:00Z', + mergeStatus: 'succeeded', + lastMergeSourceCommit: { commitId: 'abc123' } + }, + 'success', + 'https://dev.azure.com/acme/Project/_git/repo' + ) + ).toEqual({ + number: 42, + title: 'Add Azure support', + state: 'open', + url: 'https://dev.azure.com/acme/Project/_git/repo/pullrequest/42', + status: 'success', + updatedAt: '2026-05-15T12:00:00Z', + mergeable: 'MERGEABLE', + headSha: 'abc123' + }) + }) +}) diff --git a/src/main/azure-devops/pull-request-mappers.ts b/src/main/azure-devops/pull-request-mappers.ts new file mode 100644 index 000000000..d804029e5 --- /dev/null +++ b/src/main/azure-devops/pull-request-mappers.ts @@ -0,0 +1,125 @@ +import type { CheckStatus, PRMergeableState } from '../../shared/types' + +export type RawAzureDevOpsStatus = { + state?: string | null +} + +export type RawAzureDevOpsPullRequest = { + pullRequestId?: number + codeReviewId?: number + title?: string | null + status?: string | null + isDraft?: boolean | null + creationDate?: string | null + closedDate?: string | null + mergeStatus?: string | null + sourceRefName?: string | null + lastMergeSourceCommit?: { + commitId?: string | null + } | null + statuses?: RawAzureDevOpsStatus[] | null + _links?: { + web?: { + href?: string | null + } | null + } | null +} + +export type AzureDevOpsPullRequestInfo = { + number: number + title: string + state: 'open' | 'closed' | 'merged' | 'draft' + url: string + status: CheckStatus + updatedAt: string + mergeable: PRMergeableState + headSha?: string +} + +export function mapAzureDevOpsPullRequestState( + raw: Pick +): AzureDevOpsPullRequestInfo['state'] { + const status = raw.status?.trim().toLowerCase() + if (status === 'completed') { + return 'merged' + } + if (status === 'abandoned') { + return 'closed' + } + if (raw.isDraft) { + return 'draft' + } + return 'open' +} + +export function mapAzureDevOpsMergeable(mergeStatus: string | null | undefined): PRMergeableState { + switch (mergeStatus?.trim().toLowerCase()) { + case 'succeeded': + return 'MERGEABLE' + case 'conflicts': + return 'CONFLICTING' + default: + return 'UNKNOWN' + } +} + +function classifyAzureDevOpsStatus(state: string | null | undefined): CheckStatus { + switch (state?.trim().toLowerCase()) { + case 'succeeded': + case 'success': + return 'success' + case 'failed': + case 'error': + case 'rejected': + case 'canceled': + case 'cancelled': + return 'failure' + case 'pending': + case 'inprogress': + case 'in_progress': + case 'queued': + case 'running': + return 'pending' + default: + return 'neutral' + } +} + +export function deriveAzureDevOpsStatus(statuses: readonly RawAzureDevOpsStatus[]): CheckStatus { + if (statuses.length === 0) { + return 'neutral' + } + const classified = statuses.map((status) => classifyAzureDevOpsStatus(status.state)) + if (classified.includes('failure')) { + return 'failure' + } + if (classified.includes('pending')) { + return 'pending' + } + if (classified.every((status) => status === 'success')) { + return 'success' + } + return 'neutral' +} + +export function mapAzureDevOpsPullRequest( + raw: RawAzureDevOpsPullRequest, + status: CheckStatus, + webBaseUrl: string +): AzureDevOpsPullRequestInfo | null { + if (typeof raw.pullRequestId !== 'number' || !raw.title) { + return null + } + const headSha = raw.lastMergeSourceCommit?.commitId?.trim() + return { + number: raw.pullRequestId, + title: raw.title, + state: mapAzureDevOpsPullRequestState(raw), + url: + raw._links?.web?.href ?? `${webBaseUrl.replace(/\/+$/, '')}/pullrequest/${raw.pullRequestId}`, + status, + updatedAt: raw.closedDate ?? raw.creationDate ?? '', + mergeable: mapAzureDevOpsMergeable(raw.mergeStatus), + ...(headSha ? { headSha } : {}) + } +} diff --git a/src/main/azure-devops/repository-ref.test.ts b/src/main/azure-devops/repository-ref.test.ts new file mode 100644 index 000000000..4d07f58c8 --- /dev/null +++ b/src/main/azure-devops/repository-ref.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest' +import { parseAzureDevOpsRepoRef } from './repository-ref' + +describe('parseAzureDevOpsRepoRef', () => { + it('parses dev.azure.com HTTPS remotes', () => { + expect( + parseAzureDevOpsRepoRef('https://dev.azure.com/acme/Project%20One/_git/repo-name') + ).toEqual({ + host: 'dev.azure.com', + organization: 'acme', + project: 'Project One', + repository: 'repo-name', + apiBaseUrl: 'https://dev.azure.com/acme/Project%20One', + webBaseUrl: 'https://dev.azure.com/acme/Project%20One/_git/repo-name' + }) + }) + + it('parses legacy visualstudio.com HTTPS remotes', () => { + expect(parseAzureDevOpsRepoRef('https://acme.visualstudio.com/Project/_git/repo.git')).toEqual({ + host: 'acme.visualstudio.com', + organization: 'acme', + project: 'Project', + repository: 'repo', + apiBaseUrl: 'https://acme.visualstudio.com/Project', + webBaseUrl: 'https://acme.visualstudio.com/Project/_git/repo' + }) + }) + + it('parses Azure DevOps Services SSH remotes', () => { + expect(parseAzureDevOpsRepoRef('git@ssh.dev.azure.com:v3/acme/Project/repo')).toEqual({ + host: 'dev.azure.com', + organization: 'acme', + project: 'Project', + repository: 'repo', + apiBaseUrl: 'https://dev.azure.com/acme/Project', + webBaseUrl: 'https://dev.azure.com/acme/Project/_git/repo' + }) + }) + + it('parses Azure DevOps Server HTTPS remotes from the _git path convention', () => { + expect( + parseAzureDevOpsRepoRef('https://ado.example.com/tfs/DefaultCollection/Project/_git/repo.git') + ).toEqual({ + host: 'ado.example.com', + organization: null, + project: 'Project', + repository: 'repo', + apiBaseUrl: 'https://ado.example.com/tfs/DefaultCollection/Project', + webBaseUrl: 'https://ado.example.com/tfs/DefaultCollection/Project/_git/repo' + }) + }) + + it('ignores non-Azure remotes', () => { + expect(parseAzureDevOpsRepoRef('git@github.com:stablyai/orca.git')).toBeNull() + }) +}) diff --git a/src/main/azure-devops/repository-ref.ts b/src/main/azure-devops/repository-ref.ts new file mode 100644 index 000000000..1da1d60fd --- /dev/null +++ b/src/main/azure-devops/repository-ref.ts @@ -0,0 +1,208 @@ +import { gitExecFileAsync } from '../git/runner' + +export type AzureDevOpsRepoRef = { + host: string + project: string + repository: string + apiBaseUrl: string + webBaseUrl: string + organization?: string | null +} + +const repoRefCache = new Map() + +/** @internal - exposed for tests only */ +export function _resetAzureDevOpsRepoRefCache(): void { + repoRefCache.clear() +} + +function decodeSegment(value: string): string { + try { + return decodeURIComponent(value) + } catch { + return value + } +} + +function encodeSegment(value: string): string { + return encodeURIComponent(value) +} + +function splitPath(path: string): string[] { + return path + .replace(/\.git$/i, '') + .split('/') + .map((part) => part.trim()) + .filter(Boolean) + .map(decodeSegment) +} + +function joinUrl(origin: string, segments: readonly string[]): string { + const path = segments.map(encodeSegment).join('/') + return path ? `${origin.replace(/\/+$/, '')}/${path}` : origin.replace(/\/+$/, '') +} + +function parseGitHttpPath( + pathname: string +): { prefix: string[]; project: string; repository: string } | null { + const parts = splitPath(pathname) + const gitIndex = parts.findIndex((part) => part.toLowerCase() === '_git') + if (gitIndex < 1 || gitIndex + 1 >= parts.length) { + return null + } + const project = parts[gitIndex - 1] + const repository = parts[gitIndex + 1] + if (!project || !repository) { + return null + } + return { + prefix: parts.slice(0, gitIndex - 1), + project, + repository + } +} + +function makeCloudRef( + host: string, + organization: string, + project: string, + repository: string +): AzureDevOpsRepoRef { + return { + host: host.toLowerCase(), + organization, + project, + repository, + apiBaseUrl: joinUrl('https://dev.azure.com', [organization, project]), + webBaseUrl: joinUrl('https://dev.azure.com', [organization, project, '_git', repository]) + } +} + +function makeServerRef( + host: string, + origin: string, + prefix: readonly string[], + project: string, + repository: string +): AzureDevOpsRepoRef { + return { + host: host.toLowerCase(), + organization: null, + project, + repository, + apiBaseUrl: joinUrl(origin, [...prefix, project]), + webBaseUrl: joinUrl(origin, [...prefix, project, '_git', repository]) + } +} + +function parseDevAzureUrl(url: URL): AzureDevOpsRepoRef | null { + const parsed = parseGitHttpPath(url.pathname) + const organization = parsed?.prefix[0] + if (!parsed || !organization) { + return null + } + return makeCloudRef(url.hostname, organization, parsed.project, parsed.repository) +} + +function parseVisualStudioUrl(url: URL): AzureDevOpsRepoRef | null { + const parsed = parseGitHttpPath(url.pathname) + const suffix = '.visualstudio.com' + const host = url.hostname.toLowerCase() + if (!parsed || !host.endsWith(suffix)) { + return null + } + const organization = host.slice(0, -suffix.length) + if (!organization) { + return null + } + return { + host, + organization, + project: parsed.project, + repository: parsed.repository, + apiBaseUrl: joinUrl(url.origin, [...parsed.prefix, parsed.project]), + webBaseUrl: joinUrl(url.origin, [...parsed.prefix, parsed.project, '_git', parsed.repository]) + } +} + +function parseCloudSshPath(host: string, rawPath: string): AzureDevOpsRepoRef | null { + if (host.toLowerCase() !== 'ssh.dev.azure.com') { + return null + } + const parts = splitPath(rawPath) + if (parts.length < 4 || parts[0].toLowerCase() !== 'v3') { + return null + } + const [, organization, project, repository] = parts + if (!organization || !project || !repository) { + return null + } + return makeCloudRef('dev.azure.com', organization, project, repository) +} + +function parseScpLike(remoteUrl: string): AzureDevOpsRepoRef | null { + const match = remoteUrl.match(/^(?:[^@/:]+@)?([^:\s/]+):([^\s]+?)(?:\.git)?$/) + if (!match) { + return null + } + return parseCloudSshPath(match[1], match[2]) +} + +export function parseAzureDevOpsRepoRef(remoteUrl: string): AzureDevOpsRepoRef | null { + const trimmed = remoteUrl.trim() + if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) { + return parseScpLike(trimmed) + } + + try { + const url = new URL(trimmed) + const host = url.hostname.toLowerCase() + if (host === 'ssh.dev.azure.com') { + return parseCloudSshPath(host, url.pathname) + } + if (!['http:', 'https:', 'ssh:', 'git+ssh:'].includes(url.protocol.toLowerCase())) { + return null + } + if (host === 'dev.azure.com') { + return parseDevAzureUrl(url) + } + if (host.endsWith('.visualstudio.com')) { + return parseVisualStudioUrl(url) + } + + const parsed = parseGitHttpPath(url.pathname) + if (!parsed || !['http:', 'https:'].includes(url.protocol.toLowerCase())) { + return null + } + // Why: Azure DevOps Server remotes are self-hosted and only reliably + // identifiable by the `_git` path convention. + return makeServerRef(host, url.origin, parsed.prefix, parsed.project, parsed.repository) + } catch { + return null + } +} + +export async function getAzureDevOpsRepoRefForRemote( + repoPath: string, + remoteName: string +): Promise { + const cacheKey = `${repoPath}\0${remoteName}` + if (repoRefCache.has(cacheKey)) { + return repoRefCache.get(cacheKey)! + } + try { + const { stdout } = await gitExecFileAsync(['remote', 'get-url', remoteName], { + cwd: repoPath + }) + const result = parseAzureDevOpsRepoRef(stdout) + repoRefCache.set(cacheKey, result) + return result + } catch { + repoRefCache.set(cacheKey, null) + return null + } +} + +export async function getAzureDevOpsRepoRef(repoPath: string): Promise { + return getAzureDevOpsRepoRefForRemote(repoPath, 'origin') +} diff --git a/src/main/gitea/repository-ref.test.ts b/src/main/gitea/repository-ref.test.ts index 61083b2f3..0095fb9c9 100644 --- a/src/main/gitea/repository-ref.test.ts +++ b/src/main/gitea/repository-ref.test.ts @@ -70,6 +70,8 @@ describe('Gitea repository ref parsing', () => { expect(parseGiteaRepoRef('git@github.com:team/project.git')).toBeNull() expect(parseGiteaRepoRef('https://gitlab.com/team/project.git')).toBeNull() expect(parseGiteaRepoRef('https://bitbucket.org/team/project.git')).toBeNull() + expect(parseGiteaRepoRef('https://dev.azure.com/team/project/_git/repo')).toBeNull() + expect(parseGiteaRepoRef('https://team.visualstudio.com/project/_git/repo')).toBeNull() }) it('reads and caches the origin remote', async () => { diff --git a/src/main/gitea/repository-ref.ts b/src/main/gitea/repository-ref.ts index 1bae58455..6687525a4 100644 --- a/src/main/gitea/repository-ref.ts +++ b/src/main/gitea/repository-ref.ts @@ -8,7 +8,13 @@ export type GiteaRepoRef = { webBaseUrl: string } -const KNOWN_NON_GITEA_HOSTS = new Set(['github.com', 'gitlab.com', 'bitbucket.org']) +const KNOWN_NON_GITEA_HOSTS = new Set([ + 'github.com', + 'gitlab.com', + 'bitbucket.org', + 'dev.azure.com', + 'ssh.dev.azure.com' +]) const repoRefCache = new Map() /** @internal - exposed for tests only */ @@ -53,7 +59,11 @@ function apiBaseUrlFromWebBase(webBaseUrl: string): string { function makeRepoRef(host: string, path: string, webOrigin: string): GiteaRepoRef | null { const normalizedHost = host.toLowerCase() - if (!normalizedHost || KNOWN_NON_GITEA_HOSTS.has(normalizedHost)) { + if ( + !normalizedHost || + KNOWN_NON_GITEA_HOSTS.has(normalizedHost) || + normalizedHost.endsWith('.visualstudio.com') + ) { return null } diff --git a/src/main/ipc/hosted-review.ts b/src/main/ipc/hosted-review.ts index f19276e59..909eec869 100644 --- a/src/main/ipc/hosted-review.ts +++ b/src/main/ipc/hosted-review.ts @@ -40,6 +40,7 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector linkedGitHubPR: args.linkedGitHubPR ?? null, linkedGitLabMR: args.linkedGitLabMR ?? null, linkedBitbucketPR: args.linkedBitbucketPR ?? null, + linkedAzureDevOpsPR: args.linkedAzureDevOpsPR ?? null, linkedGiteaPR: args.linkedGiteaPR ?? null }) if (review?.provider === 'github' && !stats.hasCountedPR(review.url)) { diff --git a/src/main/ipc/preflight.test.ts b/src/main/ipc/preflight.test.ts index fefc0d0ad..bae8d145b 100644 --- a/src/main/ipc/preflight.test.ts +++ b/src/main/ipc/preflight.test.ts @@ -9,6 +9,7 @@ const { hydrateShellPathMock, mergePathSegmentsMock, getBitbucketAuthStatusMock, + getAzureDevOpsAuthStatusMock, getGiteaAuthStatusMock } = vi.hoisted(() => ({ handleMock: vi.fn(), @@ -17,6 +18,7 @@ const { hydrateShellPathMock: vi.fn(), mergePathSegmentsMock: vi.fn(), getBitbucketAuthStatusMock: vi.fn(), + getAzureDevOpsAuthStatusMock: vi.fn(), getGiteaAuthStatusMock: vi.fn() })) @@ -45,6 +47,10 @@ vi.mock('../bitbucket/client', () => ({ getBitbucketAuthStatus: getBitbucketAuthStatusMock })) +vi.mock('../azure-devops/client', () => ({ + getAzureDevOpsAuthStatus: getAzureDevOpsAuthStatusMock +})) + vi.mock('../gitea/client', () => ({ getGiteaAuthStatus: getGiteaAuthStatusMock })) @@ -61,6 +67,13 @@ type HandlerMap = Record { const handlers: HandlerMap = {} const defaultBitbucketStatus = { configured: false, authenticated: false, account: null } + const defaultAzureDevOpsStatus = { + configured: false, + authenticated: false, + account: null, + baseUrl: null, + tokenConfigured: false + } const defaultGiteaStatus = { configured: false, authenticated: false, @@ -75,8 +88,10 @@ describe('preflight', () => { hydrateShellPathMock.mockReset() mergePathSegmentsMock.mockReset() getBitbucketAuthStatusMock.mockReset() + getAzureDevOpsAuthStatusMock.mockReset() getGiteaAuthStatusMock.mockReset() getBitbucketAuthStatusMock.mockResolvedValue(defaultBitbucketStatus) + getAzureDevOpsAuthStatusMock.mockResolvedValue(defaultAzureDevOpsStatus) getGiteaAuthStatusMock.mockResolvedValue(defaultGiteaStatus) _resetPreflightCache() @@ -107,6 +122,7 @@ describe('preflight', () => { gh: { installed: true, authenticated: true }, glab: { installed: true, authenticated: true }, bitbucket: defaultBitbucketStatus, + azureDevOps: defaultAzureDevOpsStatus, gitea: defaultGiteaStatus }) expect(execFileAsyncMock).toHaveBeenNthCalledWith(4, 'gh', ['auth', 'status'], { @@ -209,6 +225,7 @@ describe('preflight', () => { gh: { installed: true, authenticated: true }, glab: { installed: true, authenticated: true }, bitbucket: defaultBitbucketStatus, + azureDevOps: defaultAzureDevOpsStatus, gitea: defaultGiteaStatus }) }) @@ -236,6 +253,7 @@ describe('preflight', () => { gh: { installed: true, authenticated: false }, glab: { installed: true, authenticated: true }, bitbucket: defaultBitbucketStatus, + azureDevOps: defaultAzureDevOpsStatus, gitea: defaultGiteaStatus }) expect(refreshedStatus).toEqual({ @@ -243,6 +261,7 @@ describe('preflight', () => { gh: { installed: true, authenticated: true }, glab: { installed: true, authenticated: true }, bitbucket: defaultBitbucketStatus, + azureDevOps: defaultAzureDevOpsStatus, gitea: defaultGiteaStatus }) }) diff --git a/src/main/ipc/preflight.ts b/src/main/ipc/preflight.ts index db3248091..8703e3b2e 100644 --- a/src/main/ipc/preflight.ts +++ b/src/main/ipc/preflight.ts @@ -5,6 +5,7 @@ import path from 'path' import { TUI_AGENT_CONFIG } from '../../shared/tui-agent-config' import type { PathSource, ShellHydrationFailureReason } from '../../shared/types' import { hydrateShellPath, mergePathSegments } from '../startup/hydrate-shell-path' +import { getAzureDevOpsAuthStatus } from '../azure-devops/client' import { getBitbucketAuthStatus } from '../bitbucket/client' import { getGiteaAuthStatus } from '../gitea/client' import { getActiveMultiplexer } from './ssh' @@ -20,6 +21,13 @@ export type PreflightStatus = { // gate on `glab?.authenticated`. glab?: { installed: boolean; authenticated: boolean } bitbucket?: { configured: boolean; authenticated: boolean; account: string | null } + azureDevOps?: { + configured: boolean + authenticated: boolean + account: string | null + baseUrl: string | null + tokenConfigured: boolean + } gitea?: { configured: boolean authenticated: boolean @@ -169,10 +177,11 @@ export async function runPreflightCheck(force = false): Promise isCommandAvailable('glab') ]) - const [ghAuthenticated, glabAuthenticated, bitbucket, gitea] = await Promise.all([ + const [ghAuthenticated, glabAuthenticated, bitbucket, azureDevOps, gitea] = await Promise.all([ ghInstalled ? isGhAuthenticated() : Promise.resolve(false), glabInstalled ? isGlabAuthenticated() : Promise.resolve(false), getBitbucketAuthStatus(), + getAzureDevOpsAuthStatus(), getGiteaAuthStatus() ]) @@ -181,6 +190,7 @@ export async function runPreflightCheck(force = false): Promise gh: { installed: ghInstalled, authenticated: ghAuthenticated }, glab: { installed: glabInstalled, authenticated: glabAuthenticated }, bitbucket, + azureDevOps, gitea } diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index bd47a1574..5b1cf7272 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -4544,6 +4544,7 @@ export class OrcaRuntimeService { linkedGitHubPR?: number | null linkedGitLabMR?: number | null linkedBitbucketPR?: number | null + linkedAzureDevOpsPR?: number | null linkedGiteaPR?: number | null }): Promise { const repo = await this.resolveRepoSelector(args.repoSelector) @@ -4554,6 +4555,7 @@ export class OrcaRuntimeService { linkedGitHubPR: args.linkedGitHubPR ?? null, linkedGitLabMR: args.linkedGitLabMR ?? null, linkedBitbucketPR: args.linkedBitbucketPR ?? null, + linkedAzureDevOpsPR: args.linkedAzureDevOpsPR ?? null, linkedGiteaPR: args.linkedGiteaPR ?? null }) if (review?.provider === 'github' && this.stats && !this.stats.hasCountedPR(review.url)) { @@ -4583,6 +4585,7 @@ export class OrcaRuntimeService { linkedGitHubPR: args.linkedGitHubPR ?? null, linkedGitLabMR: args.linkedGitLabMR ?? null, linkedBitbucketPR: args.linkedBitbucketPR ?? null, + linkedAzureDevOpsPR: args.linkedAzureDevOpsPR ?? null, linkedGiteaPR: args.linkedGiteaPR ?? null }) } diff --git a/src/main/runtime/rpc/methods/hosted-review.test.ts b/src/main/runtime/rpc/methods/hosted-review.test.ts index 0474ccaa2..28730ce1e 100644 --- a/src/main/runtime/rpc/methods/hosted-review.test.ts +++ b/src/main/runtime/rpc/methods/hosted-review.test.ts @@ -39,6 +39,7 @@ describe('hosted review RPC methods', () => { linkedGitHubPR: 12, linkedGitLabMR: null, linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, linkedGiteaPR: null }) expect(response).toMatchObject({ @@ -87,6 +88,7 @@ describe('hosted review RPC methods', () => { linkedGitHubPR: null, linkedGitLabMR: null, linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, linkedGiteaPR: null }) expect(response).toMatchObject({ diff --git a/src/main/runtime/rpc/methods/hosted-review.ts b/src/main/runtime/rpc/methods/hosted-review.ts index 3416e9939..e4d239a38 100644 --- a/src/main/runtime/rpc/methods/hosted-review.ts +++ b/src/main/runtime/rpc/methods/hosted-review.ts @@ -8,6 +8,7 @@ const HostedReviewForBranch = z.object({ linkedGitHubPR: z.number().int().positive().nullable().optional(), linkedGitLabMR: z.number().int().positive().nullable().optional(), linkedBitbucketPR: z.number().int().positive().nullable().optional(), + linkedAzureDevOpsPR: z.number().int().positive().nullable().optional(), linkedGiteaPR: z.number().int().positive().nullable().optional() }) @@ -22,12 +23,13 @@ const HostedReviewCreationEligibility = z.object({ linkedGitHubPR: z.number().int().positive().nullable().optional(), linkedGitLabMR: z.number().int().positive().nullable().optional(), linkedBitbucketPR: z.number().int().positive().nullable().optional(), + linkedAzureDevOpsPR: z.number().int().positive().nullable().optional(), linkedGiteaPR: z.number().int().positive().nullable().optional() }) const HostedReviewCreate = z.object({ repo: requiredString('Missing repo selector'), - provider: z.enum(['github', 'gitlab', 'bitbucket', 'gitea', 'unsupported']), + provider: z.enum(['github', 'gitlab', 'bitbucket', 'azure-devops', 'gitea', 'unsupported']), base: requiredString('Missing base branch'), head: z.string().optional(), title: requiredString('Missing title'), @@ -46,6 +48,7 @@ export const HOSTED_REVIEW_METHODS: RpcMethod[] = [ linkedGitHubPR: params.linkedGitHubPR ?? null, linkedGitLabMR: params.linkedGitLabMR ?? null, linkedBitbucketPR: params.linkedBitbucketPR ?? null, + linkedAzureDevOpsPR: params.linkedAzureDevOpsPR ?? null, linkedGiteaPR: params.linkedGiteaPR ?? null }) }), @@ -64,6 +67,7 @@ export const HOSTED_REVIEW_METHODS: RpcMethod[] = [ linkedGitHubPR: params.linkedGitHubPR ?? null, linkedGitLabMR: params.linkedGitLabMR ?? null, linkedBitbucketPR: params.linkedBitbucketPR ?? null, + linkedAzureDevOpsPR: params.linkedAzureDevOpsPR ?? null, linkedGiteaPR: params.linkedGiteaPR ?? null }) }), diff --git a/src/main/source-control/hosted-review-azure-devops.integration.test.ts b/src/main/source-control/hosted-review-azure-devops.integration.test.ts new file mode 100644 index 000000000..80f2a06cb --- /dev/null +++ b/src/main/source-control/hosted-review-azure-devops.integration.test.ts @@ -0,0 +1,128 @@ +import { execFile } from 'child_process' +import { mkdtemp, rm } from 'fs/promises' +import { createServer, type IncomingMessage, type ServerResponse } from 'http' +import { tmpdir } from 'os' +import { join } from 'path' +import { promisify } from 'util' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { _resetAzureDevOpsRepoRefCache } from '../azure-devops/repository-ref' +import { getHostedReviewForBranch } from './hosted-review' + +const execFileAsync = promisify(execFile) +const OLD_ENV = process.env + +type SeenRequest = { + pathname: string + search: string + authorization: string | undefined +} + +function sendJson(res: ServerResponse, body: unknown): void { + res.writeHead(200, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify(body)) +} + +describe('Azure DevOps hosted review integration', () => { + beforeEach(() => { + process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'local-pat' } + delete process.env.ORCA_AZURE_DEVOPS_API_BASE_URL + _resetAzureDevOpsRepoRefCache() + }) + + afterEach(() => { + process.env = OLD_ENV + _resetAzureDevOpsRepoRefCache() + }) + + it('resolves an Azure Repos PR through real git remote parsing and HTTP API calls', async () => { + const seen: SeenRequest[] = [] + const server = createServer((req: IncomingMessage, res: ServerResponse) => { + const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`) + seen.push({ + pathname: url.pathname, + search: url.search, + authorization: req.headers.authorization + }) + + if (url.pathname === '/acme/Project/_apis/git/repositories/repo') { + sendJson(res, { + id: 'repo-guid', + webUrl: 'https://dev.azure.com/acme/Project/_git/repo' + }) + return + } + + if (url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests') { + expect(url.searchParams.get('searchCriteria.sourceRefName')).toBe( + 'refs/heads/feature/azure' + ) + sendJson(res, { + value: [ + { + pullRequestId: 31, + title: 'Azure branch', + status: 'active', + creationDate: '2026-05-16T00:00:00Z', + mergeStatus: 'succeeded', + lastMergeSourceCommit: { commitId: 'abc123' } + } + ] + }) + return + } + + if ( + url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests/31/statuses' + ) { + sendJson(res, { value: [{ state: 'succeeded' }] }) + return + } + + res.writeHead(404, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify({ message: 'not found' })) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + + const repoPath = await mkdtemp(join(tmpdir(), 'orca-azure-review-')) + try { + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('expected TCP server address') + } + process.env.ORCA_AZURE_DEVOPS_API_BASE_URL = `http://127.0.0.1:${address.port}/acme/Project` + + await execFileAsync('git', ['init'], { cwd: repoPath }) + await execFileAsync( + 'git', + ['remote', 'add', 'origin', 'https://dev.azure.com/acme/Project/_git/repo'], + { cwd: repoPath } + ) + + await expect( + getHostedReviewForBranch({ repoPath, branch: 'refs/heads/feature/azure' }) + ).resolves.toEqual({ + provider: 'azure-devops', + number: 31, + title: 'Azure branch', + state: 'open', + url: 'https://dev.azure.com/acme/Project/_git/repo/pullrequest/31', + status: 'success', + updatedAt: '2026-05-16T00:00:00Z', + mergeable: 'MERGEABLE', + headSha: 'abc123' + }) + + expect(seen.map((request) => request.pathname)).toEqual([ + '/acme/Project/_apis/git/repositories/repo', + '/acme/Project/_apis/git/repositories/repo-guid/pullRequests', + '/acme/Project/_apis/git/repositories/repo-guid/pullRequests/31/statuses' + ]) + expect(seen.every((request) => request.authorization === 'Basic OmxvY2FsLXBhdA==')).toBe(true) + } finally { + await rm(repoPath, { recursive: true, force: true }) + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }) + } + }) +}) diff --git a/src/main/source-control/hosted-review-creation.test.ts b/src/main/source-control/hosted-review-creation.test.ts index ddaede683..2cdf3e46f 100644 --- a/src/main/source-control/hosted-review-creation.test.ts +++ b/src/main/source-control/hosted-review-creation.test.ts @@ -5,6 +5,7 @@ const { getRepoSlugMock, getProjectSlugMock, getBitbucketRepoSlugMock, + getAzureDevOpsRepoSlugMock, getGiteaRepoSlugMock, getHostedReviewForBranchMock, ghExecFileAsyncMock, @@ -15,6 +16,7 @@ const { getRepoSlugMock: vi.fn(), getProjectSlugMock: vi.fn(), getBitbucketRepoSlugMock: vi.fn(), + getAzureDevOpsRepoSlugMock: vi.fn(), getGiteaRepoSlugMock: vi.fn(), getHostedReviewForBranchMock: vi.fn(), ghExecFileAsyncMock: vi.fn(), @@ -35,6 +37,10 @@ vi.mock('../bitbucket/client', () => ({ getBitbucketRepoSlug: getBitbucketRepoSlugMock })) +vi.mock('../azure-devops/client', () => ({ + getAzureDevOpsRepoSlug: getAzureDevOpsRepoSlugMock +})) + vi.mock('../gitea/client', () => ({ getGiteaRepoSlug: getGiteaRepoSlugMock })) @@ -56,22 +62,36 @@ vi.mock('./hosted-review', () => ({ import { createHostedReview, getHostedReviewCreationEligibility } from './hosted-review-creation' +function resetMocks(): void { + for (const mock of [ + createGitHubPullRequestMock, + getRepoSlugMock, + getProjectSlugMock, + getBitbucketRepoSlugMock, + getAzureDevOpsRepoSlugMock, + getGiteaRepoSlugMock, + getHostedReviewForBranchMock, + ghExecFileAsyncMock, + gitExecFileAsyncMock, + getUpstreamStatusMock + ]) { + mock.mockReset() + } +} + +function mockGitHubProvider(): void { + getProjectSlugMock.mockResolvedValue(null) + getRepoSlugMock.mockResolvedValue({ owner: 'acme', repo: 'orca' }) + getBitbucketRepoSlugMock.mockResolvedValue(null) + getAzureDevOpsRepoSlugMock.mockResolvedValue(null) + getGiteaRepoSlugMock.mockResolvedValue(null) +} + describe('createHostedReview', () => { beforeEach(() => { - createGitHubPullRequestMock.mockReset() - getRepoSlugMock.mockReset() - getProjectSlugMock.mockReset() - getBitbucketRepoSlugMock.mockReset() - getGiteaRepoSlugMock.mockReset() - getHostedReviewForBranchMock.mockReset() - ghExecFileAsyncMock.mockReset() - gitExecFileAsyncMock.mockReset() - getUpstreamStatusMock.mockReset() + resetMocks() - getProjectSlugMock.mockResolvedValue(null) - getRepoSlugMock.mockResolvedValue({ owner: 'acme', repo: 'orca' }) - getBitbucketRepoSlugMock.mockResolvedValue(null) - getGiteaRepoSlugMock.mockResolvedValue(null) + mockGitHubProvider() getHostedReviewForBranchMock.mockResolvedValue(null) ghExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) getUpstreamStatusMock.mockResolvedValue({ @@ -198,20 +218,9 @@ describe('createHostedReview', () => { describe('getHostedReviewCreationEligibility', () => { beforeEach(() => { - createGitHubPullRequestMock.mockReset() - getRepoSlugMock.mockReset() - getProjectSlugMock.mockReset() - getBitbucketRepoSlugMock.mockReset() - getGiteaRepoSlugMock.mockReset() - getHostedReviewForBranchMock.mockReset() - ghExecFileAsyncMock.mockReset() - gitExecFileAsyncMock.mockReset() - getUpstreamStatusMock.mockReset() + resetMocks() - getProjectSlugMock.mockResolvedValue(null) - getRepoSlugMock.mockResolvedValue({ owner: 'acme', repo: 'orca' }) - getBitbucketRepoSlugMock.mockResolvedValue(null) - getGiteaRepoSlugMock.mockResolvedValue(null) + mockGitHubProvider() getHostedReviewForBranchMock.mockResolvedValue(null) ghExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) gitExecFileAsyncMock.mockResolvedValue({ stdout: 'Feature title\n', stderr: '' }) @@ -313,8 +322,7 @@ describe('getHostedReviewCreationEligibility', () => { ).resolves.toMatchObject({ provider: 'gitlab', canCreate: false, - blockedReason: 'unsupported_provider', - nextAction: null + blockedReason: 'unsupported_provider' }) expect(ghExecFileAsyncMock).not.toHaveBeenCalled() }) diff --git a/src/main/source-control/hosted-review-creation.ts b/src/main/source-control/hosted-review-creation.ts index 7b8b59bbc..34b370657 100644 --- a/src/main/source-control/hosted-review-creation.ts +++ b/src/main/source-control/hosted-review-creation.ts @@ -12,6 +12,7 @@ import { normalizeHostedReviewBaseRef, normalizeHostedReviewHeadRef } from '../../shared/hosted-review-refs' +import { getAzureDevOpsRepoSlug } from '../azure-devops/client' import { getBitbucketRepoSlug } from '../bitbucket/client' import { getGiteaRepoSlug } from '../gitea/client' import { createGitHubPullRequest, getRepoSlug } from '../github/client' @@ -44,6 +45,9 @@ async function detectHostedReviewProvider(repoPath: string): Promise ({ @@ -16,6 +18,8 @@ const { getPRForBranchMock: vi.fn(), getBitbucketRepoSlugMock: vi.fn(), getBitbucketPullRequestForBranchMock: vi.fn(), + getAzureDevOpsRepoSlugMock: vi.fn(), + getAzureDevOpsPullRequestForBranchMock: vi.fn(), getGiteaRepoSlugMock: vi.fn(), getGiteaPullRequestForBranchMock: vi.fn() })) @@ -37,6 +41,12 @@ vi.mock('../bitbucket/client', () => ({ getBitbucketPullRequest: vi.fn() })) +vi.mock('../azure-devops/client', () => ({ + getAzureDevOpsRepoSlug: getAzureDevOpsRepoSlugMock, + getAzureDevOpsPullRequestForBranch: getAzureDevOpsPullRequestForBranchMock, + getAzureDevOpsPullRequest: vi.fn() +})) + vi.mock('../gitea/client', () => ({ getGiteaRepoSlug: getGiteaRepoSlugMock, getGiteaPullRequestForBranch: getGiteaPullRequestForBranchMock, @@ -53,6 +63,8 @@ describe('getHostedReviewForBranch', () => { getPRForBranchMock.mockReset() getBitbucketRepoSlugMock.mockReset() getBitbucketPullRequestForBranchMock.mockReset() + getAzureDevOpsRepoSlugMock.mockReset() + getAzureDevOpsPullRequestForBranchMock.mockReset() getGiteaRepoSlugMock.mockReset() getGiteaPullRequestForBranchMock.mockReset() }) @@ -154,6 +166,7 @@ describe('getHostedReviewForBranch', () => { getProjectSlugMock.mockResolvedValue(null) getRepoSlugMock.mockResolvedValue(null) getBitbucketRepoSlugMock.mockResolvedValue(null) + getAzureDevOpsRepoSlugMock.mockResolvedValue(null) getGiteaRepoSlugMock.mockResolvedValue({ host: 'git.example.com', owner: 'team', @@ -189,4 +202,50 @@ describe('getHostedReviewForBranch', () => { }) expect(getGiteaPullRequestForBranchMock).toHaveBeenCalledWith('/repo', 'feature/gitea', 14) }) + + it('falls through to Azure DevOps before Gitea when origin is an Azure Repos remote', async () => { + getProjectSlugMock.mockResolvedValue(null) + getRepoSlugMock.mockResolvedValue(null) + getBitbucketRepoSlugMock.mockResolvedValue(null) + getAzureDevOpsRepoSlugMock.mockResolvedValue({ + host: 'dev.azure.com', + organization: 'team', + project: 'Project', + repository: 'orca' + }) + getAzureDevOpsPullRequestForBranchMock.mockResolvedValue({ + number: 21, + title: 'Azure branch', + state: 'open', + url: 'https://dev.azure.com/team/Project/_git/orca/pullrequest/21', + status: 'success', + updatedAt: '2026-05-16T00:00:00.000Z', + mergeable: 'MERGEABLE', + headSha: 'abc123' + }) + + await expect( + getHostedReviewForBranch({ + repoPath: '/repo', + branch: 'feature/azure', + linkedAzureDevOpsPR: 21 + }) + ).resolves.toEqual({ + provider: 'azure-devops', + number: 21, + title: 'Azure branch', + state: 'open', + url: 'https://dev.azure.com/team/Project/_git/orca/pullrequest/21', + status: 'success', + updatedAt: '2026-05-16T00:00:00.000Z', + mergeable: 'MERGEABLE', + headSha: 'abc123' + }) + expect(getAzureDevOpsPullRequestForBranchMock).toHaveBeenCalledWith( + '/repo', + 'feature/azure', + 21 + ) + expect(getGiteaRepoSlugMock).not.toHaveBeenCalled() + }) }) diff --git a/src/main/source-control/hosted-review.ts b/src/main/source-control/hosted-review.ts index 401f6b973..c76da7c48 100644 --- a/src/main/source-control/hosted-review.ts +++ b/src/main/source-control/hosted-review.ts @@ -1,5 +1,11 @@ import type { HostedReviewInfo } from '../../shared/hosted-review' import type { MRInfo, PRInfo } from '../../shared/types' +import { + getAzureDevOpsPullRequest, + getAzureDevOpsPullRequestForBranch, + getAzureDevOpsRepoSlug +} from '../azure-devops/client' +import type { AzureDevOpsPullRequestInfo } from '../azure-devops/pull-request-mappers' import { getBitbucketPullRequest, getBitbucketPullRequestForBranch, @@ -66,6 +72,20 @@ function mapBitbucketReview(pr: BitbucketPullRequestInfo): HostedReviewInfo { } } +function mapAzureDevOpsReview(pr: AzureDevOpsPullRequestInfo): HostedReviewInfo { + return { + provider: 'azure-devops', + number: pr.number, + title: pr.title, + state: pr.state, + url: pr.url, + status: pr.status, + updatedAt: pr.updatedAt, + mergeable: pr.mergeable, + ...(pr.headSha ? { headSha: pr.headSha } : {}) + } +} + function mapGiteaReview(pr: GiteaPullRequestInfo): HostedReviewInfo { return { provider: 'gitea', @@ -87,6 +107,7 @@ export async function getHostedReviewForBranch(input: { linkedGitHubPR?: number | null linkedGitLabMR?: number | null linkedBitbucketPR?: number | null + linkedAzureDevOpsPR?: number | null linkedGiteaPR?: number | null }): Promise { const branchName = input.branch.replace(/^refs\/heads\//, '') @@ -95,6 +116,7 @@ export async function getHostedReviewForBranch(input: { input.linkedGitHubPR == null && input.linkedGitLabMR == null && input.linkedBitbucketPR == null && + input.linkedAzureDevOpsPR == null && input.linkedGiteaPR == null ) { return null @@ -132,6 +154,16 @@ export async function getHostedReviewForBranch(input: { return pr ? mapBitbucketReview(pr) : null } + const azureDevOpsRepo = await getAzureDevOpsRepoSlug(input.repoPath) + if (azureDevOpsRepo) { + const pr = await getAzureDevOpsPullRequestForBranch( + input.repoPath, + branchName, + input.linkedAzureDevOpsPR ?? null + ) + return pr ? mapAzureDevOpsReview(pr) : null + } + const giteaRepo = await getGiteaRepoSlug(input.repoPath) if (giteaRepo) { const pr = await getGiteaPullRequestForBranch( @@ -147,7 +179,7 @@ export async function getHostedReviewForBranch(input: { export async function getHostedReviewByNumber(input: { repoPath: string - provider: 'github' | 'gitlab' | 'bitbucket' | 'gitea' + provider: 'github' | 'gitlab' | 'bitbucket' | 'azure-devops' | 'gitea' number: number }): Promise { if (input.provider === 'gitlab') { @@ -158,6 +190,10 @@ export async function getHostedReviewByNumber(input: { const pr = await getBitbucketPullRequest(input.repoPath, input.number) return pr ? mapBitbucketReview(pr) : null } + if (input.provider === 'azure-devops') { + const pr = await getAzureDevOpsPullRequest(input.repoPath, input.number) + return pr ? mapAzureDevOpsReview(pr) : null + } if (input.provider === 'gitea') { const pr = await getGiteaPullRequest(input.repoPath, input.number) return pr ? mapGiteaReview(pr) : null diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index c37e77db1..f56824db9 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -342,6 +342,13 @@ export type PreflightStatus = { * include it. Consumers gate on `glab?.installed` / `authenticated`. */ glab?: { installed: boolean; authenticated: boolean } bitbucket?: { configured: boolean; authenticated: boolean; account: string | null } + azureDevOps?: { + configured: boolean + authenticated: boolean + account: string | null + baseUrl: string | null + tokenConfigured: boolean + } gitea?: { configured: boolean authenticated: boolean diff --git a/src/preload/index.ts b/src/preload/index.ts index 6d2ba647d..c7dbe95f6 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1146,6 +1146,13 @@ const api = { gh: { installed: boolean; authenticated: boolean } glab?: { installed: boolean; authenticated: boolean } bitbucket?: { configured: boolean; authenticated: boolean; account: string | null } + azureDevOps?: { + configured: boolean + authenticated: boolean + account: string | null + baseUrl: string | null + tokenConfigured: boolean + } gitea?: { configured: boolean authenticated: boolean diff --git a/src/renderer/src/components/settings/IntegrationsPane.tsx b/src/renderer/src/components/settings/IntegrationsPane.tsx index 9847c2116..4e84d5651 100644 --- a/src/renderer/src/components/settings/IntegrationsPane.tsx +++ b/src/renderer/src/components/settings/IntegrationsPane.tsx @@ -53,6 +53,11 @@ export const INTEGRATIONS_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [ description: 'Bitbucket Cloud authentication via API token environment variables.', keywords: ['bitbucket', 'integration', 'pull request', 'api token'] }, + { + title: 'Azure DevOps Integration', + description: 'Azure DevOps Repos authentication via token environment variables.', + keywords: ['azure devops', 'azure repos', 'ado', 'integration', 'pull request', 'api token'] + }, { title: 'Gitea Integration', description: 'Gitea authentication via API token environment variables.', @@ -70,8 +75,17 @@ type GhStatus = 'checking' | 'connected' | 'not-installed' | 'not-authenticated' // modes (probe in-flight / installed-but-unauth / missing entirely). type GlabStatus = GhStatus type BitbucketStatus = 'checking' | 'connected' | 'not-configured' | 'not-authenticated' +type AzureDevOpsStatus = 'checking' | 'configured' | 'not-configured' | 'not-authenticated' type GiteaStatus = 'checking' | 'configured' | 'not-configured' | 'not-authenticated' +type TokenApiPreflightStatus = { + configured: boolean + authenticated: boolean + account: string | null + baseUrl: string | null + tokenConfigured: boolean +} + type GiteaPreflightStatus = { configured: boolean authenticated: boolean @@ -80,6 +94,21 @@ type GiteaPreflightStatus = { tokenConfigured: boolean } +function tokenApiStatusFromPreflight( + status: TokenApiPreflightStatus | undefined +): AzureDevOpsStatus { + if (!status?.configured) { + return 'not-configured' + } + if (status.tokenConfigured && !status.baseUrl) { + return 'configured' + } + if (status.tokenConfigured && !status.authenticated) { + return 'not-authenticated' + } + return 'configured' +} + function giteaStatusFromPreflight(status: GiteaPreflightStatus | undefined): GiteaStatus { if (!status?.configured) { return 'not-configured' @@ -103,6 +132,9 @@ export function IntegrationsPane(): React.JSX.Element { const [glabStatus, setGlabStatus] = useState('checking') const [bitbucketStatus, setBitbucketStatus] = useState('checking') const [bitbucketAccount, setBitbucketAccount] = useState(null) + const [azureDevOpsStatus, setAzureDevOpsStatus] = useState('checking') + const [azureDevOpsAccount, setAzureDevOpsAccount] = useState(null) + const [azureDevOpsBaseUrl, setAzureDevOpsBaseUrl] = useState(null) const [giteaStatus, setGiteaStatus] = useState('checking') const [giteaAccount, setGiteaAccount] = useState(null) const [giteaBaseUrl, setGiteaBaseUrl] = useState(null) @@ -147,6 +179,10 @@ export function IntegrationsPane(): React.JSX.Element { } else { setBitbucketStatus('connected') } + const azureDevOps = status.azureDevOps + setAzureDevOpsAccount(azureDevOps?.account ?? null) + setAzureDevOpsBaseUrl(azureDevOps?.baseUrl ?? null) + setAzureDevOpsStatus(tokenApiStatusFromPreflight(azureDevOps)) const gitea = status.gitea setGiteaAccount(gitea?.account ?? null) setGiteaBaseUrl(gitea?.baseUrl ?? null) @@ -253,6 +289,16 @@ export function IntegrationsPane(): React.JSX.Element { }) } + const handleRefreshAzureDevOps = (): void => { + setAzureDevOpsStatus('checking') + void window.api.preflight.check({ force: true }).then((status) => { + const azureDevOps = status.azureDevOps + setAzureDevOpsAccount(azureDevOps?.account ?? null) + setAzureDevOpsBaseUrl(azureDevOps?.baseUrl ?? null) + setAzureDevOpsStatus(tokenApiStatusFromPreflight(azureDevOps)) + }) + } + const handleRefreshGitea = (): void => { setGiteaStatus('checking') void window.api.preflight.check({ force: true }).then((status) => { @@ -502,6 +548,93 @@ export function IntegrationsPane(): React.JSX.Element { )} + {/* Azure DevOps */} +
+
+ +
+

Azure DevOps

+

+ {azureDevOpsStatus === 'configured' + ? azureDevOpsAccount + ? `${azureDevOpsAccount} · Pull requests and build statuses` + : azureDevOpsBaseUrl + ? `${azureDevOpsBaseUrl} · Pull requests and build statuses` + : 'Pull requests and build statuses for detected Azure Repos' + : 'Pull requests and build statuses via Azure DevOps REST API tokens.'} +

+
+ {azureDevOpsStatus === 'checking' ? ( + + ) : azureDevOpsStatus === 'configured' ? ( + + {azureDevOpsAccount ? 'Connected' : 'Configured'} + + ) : ( + + {azureDevOpsStatus === 'not-configured' ? 'Not configured' : 'Auth failed'} + + )} +
+ + {azureDevOpsStatus !== 'checking' && azureDevOpsStatus !== 'configured' && ( +
+ {azureDevOpsStatus === 'not-configured' ? ( + <> +

+ Set ORCA_AZURE_DEVOPS_TOKEN, or set{' '} + ORCA_AZURE_DEVOPS_ACCESS_TOKEN. Set{' '} + ORCA_AZURE_DEVOPS_API_BASE_URL only + when Orca cannot derive the API base URL from the git remote. +

+
+ + +
+ + ) : ( + <> +

+ Azure DevOps credentials are configured but could not authenticate. Check the + token, API base URL, and repository permissions, then restart Orca if environment + variables changed. +

+
+ + +
+ + )} +
+ )} +
+ {/* Gitea */}
diff --git a/src/renderer/src/components/sidebar/WorktreeCardMeta.tsx b/src/renderer/src/components/sidebar/WorktreeCardMeta.tsx index 876154c50..a8279c21b 100644 --- a/src/renderer/src/components/sidebar/WorktreeCardMeta.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCardMeta.tsx @@ -109,6 +109,9 @@ function getProviderName(review: WorktreeCardPrDisplay): string { if (review.provider === 'bitbucket') { return 'Bitbucket' } + if (review.provider === 'azure-devops') { + return 'Azure DevOps' + } if (review.provider === 'gitea') { return 'Gitea' } diff --git a/src/renderer/src/store/slices/hosted-review.test.ts b/src/renderer/src/store/slices/hosted-review.test.ts index 1d601022b..1cfeedd47 100644 --- a/src/renderer/src/store/slices/hosted-review.test.ts +++ b/src/renderer/src/store/slices/hosted-review.test.ts @@ -80,6 +80,7 @@ describe('hosted review slice', () => { linkedGitHubPR: null, linkedGitLabMR: 5, linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, linkedGiteaPR: null }) }) @@ -107,6 +108,7 @@ describe('hosted review slice', () => { linkedGitHubPR: 12, linkedGitLabMR: null, linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, linkedGiteaPR: null }, { timeoutMs: 30_000 } @@ -128,6 +130,7 @@ describe('hosted review slice', () => { linkedGitHubPR: null, linkedGitLabMR: 33, linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, linkedGiteaPR: null }) }) diff --git a/src/renderer/src/store/slices/hosted-review.ts b/src/renderer/src/store/slices/hosted-review.ts index f2f21b0d5..085b8ebc2 100644 --- a/src/renderer/src/store/slices/hosted-review.ts +++ b/src/renderer/src/store/slices/hosted-review.ts @@ -16,6 +16,7 @@ type LinkedReviewHints = { linkedGitHubPR?: number | null linkedGitLabMR?: number | null linkedBitbucketPR?: number | null + linkedAzureDevOpsPR?: number | null linkedGiteaPR?: number | null } @@ -43,6 +44,7 @@ function linkedReviewHintKey(options?: LinkedReviewHints): string { ['github', options?.linkedGitHubPR ?? null], ['gitlab', options?.linkedGitLabMR ?? null], ['bitbucket', options?.linkedBitbucketPR ?? null], + ['azure-devops', options?.linkedAzureDevOpsPR ?? null], ['gitea', options?.linkedGiteaPR ?? null] ] as const return hints @@ -89,6 +91,7 @@ export type HostedReviewSlice = { linkedGitHubPR?: number | null linkedGitLabMR?: number | null linkedBitbucketPR?: number | null + linkedAzureDevOpsPR?: number | null linkedGiteaPR?: number | null } ) => Promise @@ -101,6 +104,7 @@ type RefreshHostedReviewCardArgs = { linkedGitHubPR?: number | null linkedGitLabMR?: number | null linkedBitbucketPR?: number | null + linkedAzureDevOpsPR?: number | null linkedGiteaPR?: number | null } @@ -114,6 +118,7 @@ export function refreshHostedReviewCard( linkedGitHubPR: args.linkedGitHubPR ?? null, linkedGitLabMR: args.linkedGitLabMR ?? null, linkedBitbucketPR: args.linkedBitbucketPR ?? null, + linkedAzureDevOpsPR: args.linkedAzureDevOpsPR ?? null, linkedGiteaPR: args.linkedGiteaPR ?? null }) } @@ -195,6 +200,7 @@ export const createHostedReviewSlice: StateCreator['preflight']> { git: { installed: false }, gh: { installed: false, authenticated: false }, glab: { installed: false, authenticated: false }, - bitbucket: { configured: false, authenticated: false, account: null } + bitbucket: { configured: false, authenticated: false, account: null }, + azureDevOps: { + configured: false, + authenticated: false, + account: null, + baseUrl: null, + tokenConfigured: false + }, + gitea: { + configured: false, + authenticated: false, + account: null, + baseUrl: null, + tokenConfigured: false + } } const fallbackRefreshAgents: RefreshAgentsResult = { agents: [], diff --git a/src/shared/hosted-review.ts b/src/shared/hosted-review.ts index 4ebd122c4..7c86785b4 100644 --- a/src/shared/hosted-review.ts +++ b/src/shared/hosted-review.ts @@ -1,6 +1,12 @@ import type { CheckStatus, PRConflictSummary, PRMergeableState } from './types' -export type HostedReviewProvider = 'github' | 'gitlab' | 'bitbucket' | 'gitea' | 'unsupported' +export type HostedReviewProvider = + | 'github' + | 'gitlab' + | 'bitbucket' + | 'azure-devops' + | 'gitea' + | 'unsupported' export type HostedReviewState = 'open' | 'closed' | 'merged' | 'draft' @@ -24,6 +30,7 @@ export type HostedReviewForBranchArgs = { linkedGitHubPR?: number | null linkedGitLabMR?: number | null linkedBitbucketPR?: number | null + linkedAzureDevOpsPR?: number | null linkedGiteaPR?: number | null } @@ -111,6 +118,7 @@ export type HostedReviewCreationEligibilityArgs = { linkedGitHubPR?: number | null linkedGitLabMR?: number | null linkedBitbucketPR?: number | null + linkedAzureDevOpsPR?: number | null linkedGiteaPR?: number | null }