Add Source Control Create PR flow (#5436)

* Add Source Control Create PR intent flow

Implements the Source Control Create PR flow described in docs/source-control-create-pr-flow.md.

* Keep Commit visible beside Create PR

* Fix Create PR partial staging action band

* Integrate hosted review creation into Create PR intent flow

- Automatically create the pull or merge request on GitHub/GitLab after
  successfully staging, committing, and pushing in the intent flow.
- Introduce a unified `updateCommitDrafts` helper to keep React state and
  its ref synchronized, preventing draft-overwrite race conditions.
- Split primary action tests into focused files to satisfy the ESLint
  `max-lines` rule.
- Replace hardcoded "Local Mac" strings with dynamic host labels.

* Support Azure DevOps and Gitea PR creation and limit large diffs

Implement automated pull request creation for Azure DevOps and Gitea
repositories. This includes REST API integration, credential checks via
environment variables, template support, and error classification.

Additionally, introduce limits on large diff payloads in git status
extraction to prevent renderer-freezing performance bottlenecks when
loading extremely large files.

* Skip source control refetches when PR creation intent is in flight

Avoid recomputing branch eligibility while isCreatePrIntentInFlight is true.
This prevents tearing down the PR composer or rotating dropdown hints
prematurely if ahead/behind or dirty states are temporarily perturbed
temporarily perturbed mid-flow.

* Expose manual prerequisite actions next to Create PR button

Previously, the Create PR intent only supported "Stage All" as a
sibling action. This expands prerequisite resolution to handle other
intermediate steps such as committing, publishing, and pushing
(including force pushing).

This ensures the edit-commit-push-review loop remains streamlined
directly within the CommitArea by displaying the specific required
next action beside the primary Create PR button.

* Move PR creation actions from CommitArea to sidebar header

- Decouples PR creation and PR intent actions from the local commit area
  primary button, ensuring local/remote git actions remain primary.
- Renders a dedicated PR creation button in the source control header
  beside the hosted review status.
- Simplifies CommitArea by removing prerequisite split-button rendering
  and review composer logic.

* Delete source control create PR flow design document

Remove the design document for the source control create PR flow as the feature has been successfully implemented.

* Display PR creation errors in inline notice

Unify PR/review creation error reporting by replacing the duplicate
createPrErrors state with the shared createPrIntentNotice. Validation
and API errors are now shown directly within the visible inline alert
notice to improve layout consistency and visibility.

Also refactor the execution host platform label lookup to use simple
if statements instead of a switch block.

* Improve Create PR intent flow safety and provider awareness

- Integrate the hosted review composer directly into the Source Control
  panel when a direct review creation action is available.
- Abort the in-flight PR creation intent flow early if the current git
  branch changes to prevent staging or committing on the wrong target.
- Keep in-flight action labels provider-aware (e.g., "Create MR" on GitLab)
  by passing hosted review inputs to the action resolver.
- Omit large diff text payloads from git status responses when line counts
  exceed safe rendering limits to avoid UI performance degradation.
- Ensure field generation does not retarget the base branch of a PR/MR without
  explicit user confirmation.

* Preserve PR and MR templates in AI pull request generation

- Preload templates (including GitLab merge requests) into the AI
  context before generation to prevent bypassing provider-side fallbacks.
- Instruct the AI generator to fill out and preserve existing template
  headings, required sections, and checklists instead of deleting them.
- Pass provider and template settings from the renderer to the backend
  RPC and runtime handlers.

* Mock DropdownMenuShortcut in tab-title-tooltip test

Add a mock for the DropdownMenuShortcut component in the dropdown menu
mock to prevent test failures.
This commit is contained in:
Jinjing
2026-06-16 15:36:27 -07:00
committed by GitHub
parent ca05dbf652
commit a300e2c7b4
64 changed files with 4161 additions and 528 deletions
@@ -0,0 +1,155 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createAzureDevOpsPullRequest,
isAzureDevOpsReviewCreationAuthenticated
} from './pull-request-creation'
import { _resetAzureDevOpsRepoRefCache } from './repository-ref'
const { gitExecFileAsyncMock, getSshGitProviderMock } = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn(),
getSshGitProviderMock: vi.fn()
}))
vi.mock('../git/runner', () => ({
gitExecFileAsync: gitExecFileAsyncMock
}))
vi.mock('../providers/ssh-git-dispatch', () => ({
getSshGitProvider: getSshGitProviderMock
}))
vi.mock('../source-control/pull-request-template', () => ({
readHostedPullRequestTemplate: vi.fn(async () => 'Template body')
}))
const OLD_ENV = process.env
const OLD_FETCH = globalThis.fetch
describe('Azure DevOps pull request creation', () => {
beforeEach(() => {
process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'pat-token' }
gitExecFileAsyncMock.mockReset()
getSshGitProviderMock.mockReset()
gitExecFileAsyncMock.mockResolvedValue({
stdout: 'https://dev.azure.com/acme/Project/_git/repo\n',
stderr: ''
})
_resetAzureDevOpsRepoRefCache()
})
afterEach(() => {
process.env = OLD_ENV
globalThis.fetch = OLD_FETCH
_resetAzureDevOpsRepoRefCache()
})
it('treats token-only auth as sufficient for repo-scoped creation', () => {
delete process.env.ORCA_AZURE_DEVOPS_API_BASE_URL
expect(isAzureDevOpsReviewCreationAuthenticated()).toBe(true)
})
it('posts a pull request create body to the repository REST endpoint', async () => {
const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
const url = new URL(String(input))
expect(url.pathname).toBe('/acme/Project/_apis/git/repositories/repo/pullRequests')
expect(url.searchParams.get('api-version')).toBe('7.1')
expect(init).toBeDefined()
const requestInit = init!
expect(requestInit.method).toBe('POST')
expect((requestInit.headers as Record<string, string>).Authorization).toMatch(/^Basic /)
expect(JSON.parse(String(requestInit.body))).toEqual({
sourceRefName: 'refs/heads/feature/azure',
targetRefName: 'refs/heads/main',
title: 'Add Azure create',
description: 'Body',
isDraft: true
})
return Response.json({
pullRequestId: 37,
title: 'Add Azure create',
status: 'active',
isDraft: true,
creationDate: '2026-06-01T00:00:00Z',
_links: {
web: {
href: 'https://dev.azure.com/acme/Project/_git/repo/pullrequest/37'
}
}
})
})
globalThis.fetch = fetchMock as never
await expect(
createAzureDevOpsPullRequest('/repo', {
provider: 'azure-devops',
base: 'origin/main',
head: 'refs/heads/feature/azure',
title: 'Add Azure create',
body: 'Body',
draft: true
})
).resolves.toEqual({
ok: true,
number: 37,
url: 'https://dev.azure.com/acme/Project/_git/repo/pullrequest/37'
})
expect(fetchMock).toHaveBeenCalledOnce()
})
it('resolves Azure DevOps remotes through the SSH git provider', async () => {
const remoteGit = {
exec: vi.fn(async () => ({
stdout: 'git@ssh.dev.azure.com:v3/acme/Project/repo.git\n',
stderr: ''
}))
}
getSshGitProviderMock.mockReturnValue(remoteGit)
globalThis.fetch = vi.fn(async () =>
Response.json({
pullRequestId: 38,
title: 'Remote Azure create',
status: 'active',
creationDate: '2026-06-01T00:00:00Z'
})
) as never
await expect(
createAzureDevOpsPullRequest(
'/remote/repo',
{
provider: 'azure-devops',
base: 'main',
head: 'feature/azure',
title: 'Remote Azure create'
},
'ssh-1'
)
).resolves.toMatchObject({
ok: true,
number: 38
})
expect(remoteGit.exec).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], '/remote/repo')
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
})
it('classifies auth failures without retrying shell commands', async () => {
globalThis.fetch = vi.fn(async () =>
Response.json({ message: 'Unauthorized' }, { status: 401 })
) as never
await expect(
createAzureDevOpsPullRequest('/repo', {
provider: 'azure-devops',
base: 'main',
head: 'feature/azure',
title: 'Add Azure create'
})
).resolves.toMatchObject({
ok: false,
code: 'auth_required'
})
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], {
cwd: '/repo'
})
})
})
@@ -0,0 +1,238 @@
import { Buffer } from 'buffer'
import type { CreateHostedReviewInput, CreateHostedReviewResult } from '../../shared/hosted-review'
import {
normalizeHostedReviewBaseRef,
normalizeHostedReviewHeadRef
} from '../../shared/hosted-review-refs'
import {
HostedReviewApiRequestError,
requestHostedReviewJson
} from '../source-control/hosted-review-api-request'
import { readHostedPullRequestTemplate } from '../source-control/pull-request-template'
import { getAzureDevOpsPullRequestForBranch } from './client'
import { mapAzureDevOpsPullRequest, type RawAzureDevOpsPullRequest } from './pull-request-mappers'
import { getAzureDevOpsRepoRef, type AzureDevOpsRepoRef } from './repository-ref'
const CREATE_REQUEST_TIMEOUT_MS = 60_000
type AzureDevOpsCreateAuthConfig = {
apiBaseUrl: string | null
pat: string | null
accessToken: string | null
username: string | null
}
function envValue(name: string): string | null {
const value = process.env[name]?.trim() ?? ''
return value.length > 0 ? value : null
}
function normalizeApiBaseUrl(value: string): string {
return value
.trim()
.replace(/\/+$/, '')
.replace(/\/_apis$/i, '')
}
function getAuthConfig(): AzureDevOpsCreateAuthConfig {
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')
}
}
export function isAzureDevOpsReviewCreationAuthenticated(): boolean {
const config = getAuthConfig()
return Boolean(config.pat || config.accessToken)
}
function authHeaders(config: AzureDevOpsCreateAuthConfig): Record<string, string> {
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 apiUrl(repo: AzureDevOpsRepoRef, path: string): URL {
const config = getAuthConfig()
const baseUrl = config.apiBaseUrl ? normalizeApiBaseUrl(config.apiBaseUrl) : repo.apiBaseUrl
const url = new URL(`${baseUrl.replace(/\/+$/, '')}${path}`)
url.searchParams.set('api-version', '7.1')
return url
}
function encodePathSegment(value: string): string {
return encodeURIComponent(value)
}
function azureBranchRef(branch: string): string {
return `refs/heads/${branch.replace(/^refs\/heads\//, '')}`
}
function apiErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
function classifyCreateError(error: unknown): CreateHostedReviewResult {
const message = apiErrorMessage(error)
if (message) {
console.warn('createAzureDevOpsPullRequest failed:', message)
}
const lower = message.toLowerCase()
const status = error instanceof HostedReviewApiRequestError ? error.status : null
if (
status === 401 ||
status === 403 ||
lower.includes('unauthorized') ||
lower.includes('forbidden') ||
lower.includes('authentication')
) {
return {
ok: false,
code: 'auth_required',
error:
'Create PR failed: Azure DevOps is not authenticated. Next step: set ORCA_AZURE_DEVOPS_TOKEN in this environment.'
}
}
if (status === 409 || lower.includes('already exists') || lower.includes('active pull request')) {
return {
ok: false,
code: 'already_exists',
error: 'A pull request already exists for this branch.'
}
}
if (error instanceof HostedReviewApiRequestError && error.timedOut) {
return {
ok: false,
code: 'unknown_completion',
error: 'PR creation may have completed. Refreshing branch review state...'
}
}
if (status === 400 || status === 422 || lower.includes('validation')) {
return {
ok: false,
code: 'validation',
error:
'Create PR failed: Azure DevOps rejected the pull request. Check the base branch and branch state, then try again.'
}
}
return {
ok: false,
code: 'unknown',
error:
'Create PR failed: Azure DevOps could not create the pull request. Try again in a moment.'
}
}
async function findExistingPullRequest(
repoPath: string,
head: string,
connectionId?: string | null
): Promise<{ number: number; url: string } | null> {
const existing = await getAzureDevOpsPullRequestForBranch(repoPath, head, null, connectionId)
return existing ? { number: existing.number, url: existing.url } : null
}
export async function createAzureDevOpsPullRequest(
repoPath: string,
input: CreateHostedReviewInput,
connectionId?: string | null
): Promise<CreateHostedReviewResult> {
if (input.provider !== 'azure-devops') {
return {
ok: false,
code: 'unsupported_provider',
error: 'Creating reviews for this provider is not supported yet.'
}
}
const repo = await getAzureDevOpsRepoRef(repoPath, connectionId)
if (!repo) {
return {
ok: false,
code: 'unsupported_provider',
error: 'Creating pull requests requires an Azure DevOps remote.'
}
}
const base = normalizeHostedReviewBaseRef(input.base)
const head = input.head ? normalizeHostedReviewHeadRef(input.head) : ''
const title = input.title.trim()
if (!base || !head || !title) {
return {
ok: false,
code: 'validation',
error: 'Create PR failed: base branch, head branch, and title are required.'
}
}
if (head.toLowerCase() === base.toLowerCase()) {
return {
ok: false,
code: 'validation',
error: 'Create PR failed: choose a different base branch before creating a pull request.'
}
}
const body =
input.useTemplate && !input.body?.trim()
? await readHostedPullRequestTemplate(repoPath, connectionId)
: (input.body ?? '')
const requestBody = {
sourceRefName: azureBranchRef(head),
targetRefName: azureBranchRef(base),
title,
description: body,
...(input.draft ? { isDraft: true } : {})
}
try {
const raw = await requestHostedReviewJson<RawAzureDevOpsPullRequest>(
apiUrl(repo, `/_apis/git/repositories/${encodePathSegment(repo.repository)}/pullRequests`),
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...authHeaders(getAuthConfig())
},
body: JSON.stringify(requestBody)
},
CREATE_REQUEST_TIMEOUT_MS
)
const created = mapAzureDevOpsPullRequest(raw, 'neutral', repo.webBaseUrl)
if (created) {
return { ok: true, number: created.number, url: created.url }
}
const found = await findExistingPullRequest(repoPath, head, connectionId).catch(() => null)
return found
? { ok: true, ...found }
: {
ok: false,
code: 'unknown_completion',
error: 'PR creation may have completed. Refreshing branch review state...'
}
} catch (error) {
const classified = classifyCreateError(error)
if (
!classified.ok &&
(classified.code === 'already_exists' || classified.code === 'unknown_completion')
) {
const existing = await findExistingPullRequest(repoPath, head, connectionId).catch(() => null)
if (existing) {
return {
ok: false,
code: 'already_exists',
error: 'A pull request already exists for this branch.',
existingReview: existing
}
}
}
return classified
}
}
+31 -1
View File
@@ -1,7 +1,10 @@
/* eslint-disable max-lines -- Why: git status/discard/chunking behavior is verified together here to keep the command contract readable in one place. */
import { beforeEach, describe, expect, it, vi } from 'vitest'
import path from 'path'
import { MAX_RENDERED_DIFF_COMBINED_CHARACTERS } from '../../shared/large-diff-render-limit'
import {
MAX_RENDERED_DIFF_COMBINED_CHARACTERS,
MAX_RENDERED_DIFF_LINES_PER_SIDE
} from '../../shared/large-diff-render-limit'
const {
gitExecFileAsyncMock,
@@ -384,6 +387,33 @@ describe('getDiff', () => {
)
})
it('omits over-limit text bodies when line-count exceeds the cap', async () => {
const oversizedByLines = 'x\n'.repeat(MAX_RENDERED_DIFF_LINES_PER_SIDE)
gitExecFileAsyncBufferMock.mockResolvedValueOnce({ stdout: Buffer.from('index-content\n') })
statMock.mockResolvedValueOnce({
isFile: () => true,
size: oversizedByLines.length
})
readFileMock.mockResolvedValue(Buffer.from(oversizedByLines))
const result = await getDiff('/repo', 'dist/large-lines.log', false)
expect(result.kind).toBe('text')
if (result.kind !== 'text') {
throw new Error('expected text diff result')
}
expect(result.originalContent).toBe('')
expect(result.modifiedContent).toBe('')
expect(result.largeDiffRenderLimit?.limited).toBe(true)
if (result.largeDiffRenderLimit?.limited !== true) {
throw new Error('expected large diff render limit')
}
expect(result.largeDiffRenderLimit.reason).toBe('line-count')
expect(result.largeDiffRenderLimit.lineCounts?.modified).toBeGreaterThan(
MAX_RENDERED_DIFF_LINES_PER_SIDE
)
})
it('marks git blobs that overflow maxBuffer as binary instead of pretending they are missing', async () => {
gitExecFileAsyncBufferMock.mockRejectedValueOnce(
Object.assign(new Error('stdout maxBuffer length exceeded'), { code: 'ENOBUFS' })
+2
View File
@@ -1072,6 +1072,8 @@ function buildDiffResult(
} as GitDiffResult
}
// Why: if the diff exceeds safe render limits, avoid sending large text
// payloads and return metadata so the renderer can show fallback UI.
const largeDiffRenderLimit = getLargeDiffRenderLimit({ originalContent, modifiedContent })
if (largeDiffRenderLimit.limited) {
return {
@@ -0,0 +1,155 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createGiteaPullRequest, isGiteaReviewCreationAuthenticated } from './pull-request-creation'
import { _resetGiteaRepoRefCache } from './repository-ref'
const { gitExecFileAsyncMock, getSshGitProviderMock } = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn(),
getSshGitProviderMock: vi.fn()
}))
vi.mock('../git/runner', () => ({
gitExecFileAsync: gitExecFileAsyncMock
}))
vi.mock('../providers/ssh-git-dispatch', () => ({
getSshGitProvider: getSshGitProviderMock
}))
vi.mock('../source-control/pull-request-template', () => ({
readHostedPullRequestTemplate: vi.fn(async () => 'Template body')
}))
const OLD_ENV = process.env
const OLD_FETCH = globalThis.fetch
describe('Gitea pull request creation', () => {
beforeEach(() => {
process.env = { ...OLD_ENV, ORCA_GITEA_TOKEN: 'gitea-token' }
gitExecFileAsyncMock.mockReset()
getSshGitProviderMock.mockReset()
gitExecFileAsyncMock.mockResolvedValue({
stdout: 'https://git.example.com/code/team/repo.git\n',
stderr: ''
})
_resetGiteaRepoRefCache()
})
afterEach(() => {
process.env = OLD_ENV
globalThis.fetch = OLD_FETCH
_resetGiteaRepoRefCache()
})
it('requires a token for repo-scoped creation', () => {
expect(isGiteaReviewCreationAuthenticated()).toBe(true)
delete process.env.ORCA_GITEA_TOKEN
expect(isGiteaReviewCreationAuthenticated()).toBe(false)
})
it('posts a pull request create body to the repository REST endpoint', async () => {
const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
const url = new URL(String(input))
expect(url.origin).toBe('https://git.example.com')
expect(url.pathname).toBe('/code/api/v1/repos/team/repo/pulls')
expect(init).toBeDefined()
const requestInit = init!
expect(requestInit.method).toBe('POST')
expect((requestInit.headers as Record<string, string>).Authorization).toBe(
'token gitea-token'
)
expect(JSON.parse(String(requestInit.body))).toEqual({
base: 'main',
head: 'feature/gitea',
title: 'Add Gitea create',
body: 'Body',
draft: true
})
return Response.json({
number: 13,
title: 'Add Gitea create',
state: 'open',
draft: true,
html_url: 'https://git.example.com/code/team/repo/pulls/13',
updated_at: '2026-06-01T00:00:00Z',
mergeable: true,
head: {
ref: 'feature/gitea',
sha: 'abc123'
}
})
})
globalThis.fetch = fetchMock as never
await expect(
createGiteaPullRequest('/repo', {
provider: 'gitea',
base: 'origin/main',
head: 'refs/heads/feature/gitea',
title: 'Add Gitea create',
body: 'Body',
draft: true
})
).resolves.toEqual({
ok: true,
number: 13,
url: 'https://git.example.com/code/team/repo/pulls/13'
})
expect(fetchMock).toHaveBeenCalledOnce()
})
it('resolves Gitea remotes through the SSH git provider', async () => {
const remoteGit = {
exec: vi.fn(async () => ({
stdout: 'git@git.example.com:code/team/repo.git\n',
stderr: ''
}))
}
getSshGitProviderMock.mockReturnValue(remoteGit)
globalThis.fetch = vi.fn(async () =>
Response.json({
number: 14,
title: 'Remote Gitea create',
state: 'open',
html_url: 'https://git.example.com/code/team/repo/pulls/14',
updated_at: '2026-06-01T00:00:00Z',
mergeable: true
})
) as never
await expect(
createGiteaPullRequest(
'/remote/repo',
{
provider: 'gitea',
base: 'main',
head: 'feature/gitea',
title: 'Remote Gitea create'
},
'ssh-1'
)
).resolves.toMatchObject({
ok: true,
number: 14
})
expect(remoteGit.exec).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], '/remote/repo')
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
})
it('classifies validation failures from the REST API', async () => {
globalThis.fetch = vi.fn(async () =>
Response.json({ message: 'Validation failed' }, { status: 422 })
) as never
await expect(
createGiteaPullRequest('/repo', {
provider: 'gitea',
base: 'main',
head: 'feature/gitea',
title: 'Add Gitea create'
})
).resolves.toMatchObject({
ok: false,
code: 'validation'
})
})
})
+208
View File
@@ -0,0 +1,208 @@
import type { CreateHostedReviewInput, CreateHostedReviewResult } from '../../shared/hosted-review'
import {
normalizeHostedReviewBaseRef,
normalizeHostedReviewHeadRef
} from '../../shared/hosted-review-refs'
import {
HostedReviewApiRequestError,
requestHostedReviewJson
} from '../source-control/hosted-review-api-request'
import { readHostedPullRequestTemplate } from '../source-control/pull-request-template'
import { getGiteaPullRequestForBranch } from './client'
import { mapGiteaPullRequest, type RawGiteaPullRequest } from './pull-request-mappers'
import { getGiteaRepoRef, type GiteaRepoRef } from './repository-ref'
const CREATE_REQUEST_TIMEOUT_MS = 60_000
function envValue(name: string): string | null {
const value = process.env[name]?.trim() ?? ''
return value.length > 0 ? value : null
}
function normalizeApiBaseUrl(value: string): string {
const trimmed = value.trim().replace(/\/+$/, '')
return /\/api\/v1$/i.test(trimmed) ? trimmed : `${trimmed}/api/v1`
}
function configuredApiBaseUrl(repo: GiteaRepoRef): string {
const configured = envValue('ORCA_GITEA_API_BASE_URL')
return configured ? normalizeApiBaseUrl(configured) : repo.apiBaseUrl
}
export function isGiteaReviewCreationAuthenticated(): boolean {
return envValue('ORCA_GITEA_TOKEN') !== null
}
function authHeaders(): Record<string, string> {
const token = envValue('ORCA_GITEA_TOKEN')
return token ? { Authorization: `token ${token}` } : {}
}
function apiUrl(repo: GiteaRepoRef, path: string): URL {
return new URL(`${configuredApiBaseUrl(repo).replace(/\/+$/, '')}${path}`)
}
function encodedRepoPath(repo: GiteaRepoRef): string {
return `${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.repo)}`
}
function apiErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
function classifyCreateError(error: unknown): CreateHostedReviewResult {
const message = apiErrorMessage(error)
if (message) {
console.warn('createGiteaPullRequest failed:', message)
}
const lower = message.toLowerCase()
const status = error instanceof HostedReviewApiRequestError ? error.status : null
if (
status === 401 ||
status === 403 ||
lower.includes('unauthorized') ||
lower.includes('forbidden') ||
lower.includes('authentication')
) {
return {
ok: false,
code: 'auth_required',
error:
'Create PR failed: Gitea is not authenticated. Next step: set ORCA_GITEA_TOKEN in this environment.'
}
}
if (status === 409 || lower.includes('already exists') || lower.includes('already open')) {
return {
ok: false,
code: 'already_exists',
error: 'A pull request already exists for this branch.'
}
}
if (error instanceof HostedReviewApiRequestError && error.timedOut) {
return {
ok: false,
code: 'unknown_completion',
error: 'PR creation may have completed. Refreshing branch review state...'
}
}
if (status === 400 || status === 422 || lower.includes('validation')) {
return {
ok: false,
code: 'validation',
error:
'Create PR failed: Gitea rejected the pull request. Check the base branch and branch state, then try again.'
}
}
return {
ok: false,
code: 'unknown',
error: 'Create PR failed: Gitea could not create the pull request. Try again in a moment.'
}
}
async function findExistingPullRequest(
repoPath: string,
head: string,
connectionId?: string | null
): Promise<{ number: number; url: string } | null> {
const existing = await getGiteaPullRequestForBranch(repoPath, head, null, connectionId)
return existing ? { number: existing.number, url: existing.url } : null
}
export async function createGiteaPullRequest(
repoPath: string,
input: CreateHostedReviewInput,
connectionId?: string | null
): Promise<CreateHostedReviewResult> {
if (input.provider !== 'gitea') {
return {
ok: false,
code: 'unsupported_provider',
error: 'Creating reviews for this provider is not supported yet.'
}
}
const repo = await getGiteaRepoRef(repoPath, connectionId)
if (!repo) {
return {
ok: false,
code: 'unsupported_provider',
error: 'Creating pull requests requires a Gitea remote.'
}
}
const base = normalizeHostedReviewBaseRef(input.base)
const head = input.head ? normalizeHostedReviewHeadRef(input.head) : ''
const title = input.title.trim()
if (!base || !head || !title) {
return {
ok: false,
code: 'validation',
error: 'Create PR failed: base branch, head branch, and title are required.'
}
}
if (head.toLowerCase() === base.toLowerCase()) {
return {
ok: false,
code: 'validation',
error: 'Create PR failed: choose a different base branch before creating a pull request.'
}
}
const body =
input.useTemplate && !input.body?.trim()
? await readHostedPullRequestTemplate(repoPath, connectionId)
: (input.body ?? '')
const requestBody = {
base,
head,
title,
body,
...(input.draft ? { draft: true } : {})
}
try {
const raw = await requestHostedReviewJson<RawGiteaPullRequest>(
apiUrl(repo, `/repos/${encodedRepoPath(repo)}/pulls`),
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...authHeaders()
},
body: JSON.stringify(requestBody)
},
CREATE_REQUEST_TIMEOUT_MS
)
const created = mapGiteaPullRequest(raw, 'neutral')
if (created) {
return { ok: true, number: created.number, url: created.url }
}
const found = await findExistingPullRequest(repoPath, head, connectionId).catch(() => null)
return found
? { ok: true, ...found }
: {
ok: false,
code: 'unknown_completion',
error: 'PR creation may have completed. Refreshing branch review state...'
}
} catch (error) {
const classified = classifyCreateError(error)
if (
!classified.ok &&
(classified.code === 'already_exists' || classified.code === 'unknown_completion')
) {
const existing = await findExistingPullRequest(repoPath, head, connectionId).catch(() => null)
if (existing) {
return {
ok: false,
code: 'already_exists',
error: 'A pull request already exists for this branch.',
existingReview: existing
}
}
}
return classified
}
}
+20 -2
View File
@@ -78,6 +78,7 @@ import {
} from '../git/huge-folder-ignore'
import { assertGitPushTargetShape } from '../../shared/git-push-target-validation'
import { getCommitMessageModelDiscoveryHostKey } from '../../shared/commit-message-host-key'
import type { HostedReviewProvider } from '../../shared/hosted-review'
import type { ResolvedSourceControlAiGenerationParams } from '../../shared/source-control-ai'
import { validateGitPushTarget } from '../git/push-target-validation'
import { getRemoteCommitUrl, getRemoteFileUrl } from '../git/repo'
@@ -101,6 +102,7 @@ import {
getSshGitProvider,
SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE
} from '../providers/ssh-git-dispatch'
import { resolveHostedReviewBodyForGeneration } from '../source-control/pull-request-template'
import {
prepareLocalCommitMessageAgentEnv,
type CommitMessageAgentEnvironmentResolvers
@@ -1130,6 +1132,8 @@ export function registerFilesystemHandlers(
title: string
body: string
draft: boolean
provider?: HostedReviewProvider
useTemplate?: boolean
connectionId?: string
sourceControlAiResolvedParams?: ResolvedSourceControlAiGenerationParams
sourceControlAi?: GlobalSettings['sourceControlAi']
@@ -1166,12 +1170,19 @@ export function registerFilesystemHandlers(
}
let context: Awaited<ReturnType<typeof getPullRequestDraftContext>>
try {
const currentBody = await resolveHostedReviewBodyForGeneration({
body: args.body,
repoPath: args.worktreePath,
connectionId: args.connectionId,
provider: args.provider,
useTemplate: args.useTemplate
})
context = await getPullRequestDraftContext(
(argv) => provider.exec(argv, args.worktreePath),
{
base: args.base,
currentTitle: args.title,
currentBody: args.body,
currentBody,
currentDraft: args.draft
}
)
@@ -1197,12 +1208,19 @@ export function registerFilesystemHandlers(
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
let context: Awaited<ReturnType<typeof getPullRequestDraftContext>>
try {
const currentBody = await resolveHostedReviewBodyForGeneration({
body: args.body,
repoPath: worktreePath,
connectionId: args.connectionId,
provider: args.provider,
useTemplate: args.useTemplate
})
context = await getPullRequestDraftContext(
(argv, options) => gitExecFileAsync(argv, { cwd: worktreePath, ...options }),
{
base: args.base,
currentTitle: args.title,
currentBody: args.body,
currentBody,
currentDraft: args.draft
}
)
+70
View File
@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({
generateCommitMessageFromContext: vi.fn(),
generatePullRequestFieldsFromContext: vi.fn(),
resolveCommitMessageSettings: vi.fn(),
resolveHostedReviewBodyForGeneration: vi.fn(),
getSshGitProvider: vi.fn()
}))
@@ -53,6 +54,10 @@ vi.mock('../providers/ssh-git-dispatch', () => ({
getSshGitProvider: mocks.getSshGitProvider
}))
vi.mock('../source-control/pull-request-template', () => ({
resolveHostedReviewBodyForGeneration: mocks.resolveHostedReviewBodyForGeneration
}))
const tempDirs: string[] = []
function makeWorktree(path: string): ResolvedRuntimeGitWorktree {
@@ -86,6 +91,8 @@ describe('RuntimeGitCommands', () => {
mocks.generateCommitMessageFromContext.mockReset()
mocks.generatePullRequestFieldsFromContext.mockReset()
mocks.resolveCommitMessageSettings.mockReset()
mocks.resolveHostedReviewBodyForGeneration.mockReset()
mocks.resolveHostedReviewBodyForGeneration.mockImplementation(async ({ body }) => body)
mocks.getSshGitProvider.mockReset()
mocks.checkoutBranch.mockReset()
mocks.listLocalBranches.mockReset()
@@ -409,6 +416,69 @@ describe('RuntimeGitCommands', () => {
)
})
it('loads the hosted review template before generating pull-request fields', async () => {
const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-'))
tempDirs.push(worktreePath)
const templateBody = '## Summary\n\n## Testing\n\n- [ ] Required checks'
const context = {
base: 'main',
branch: 'feature/template-aware-pr',
branchChangedByPreparation: false,
commitSummary: 'abc123 feat: test',
changeSummary: 'M README.md',
patch: '+hello',
currentTitle: '',
currentBody: templateBody,
currentDraft: false
}
const sourceControlAiResolvedParams = {
agentId: 'codex' as const,
model: 'gpt-5.5'
}
mocks.resolveHostedReviewBodyForGeneration.mockResolvedValue(templateBody)
mocks.getPullRequestDraftContext.mockResolvedValue(context)
mocks.generatePullRequestFieldsFromContext.mockResolvedValue({
success: true,
fields: {
base: 'main',
title: 'Use existing template',
body: templateBody,
draft: false
}
})
const commands = new RuntimeGitCommands({
resolveRuntimeGitTarget: async () => ({ worktree: makeWorktree(worktreePath) }),
getRuntimeSettings: () => ({}) as GlobalSettings
})
await commands.generateRuntimePullRequestFields(
'id:wt-1',
{
base: 'main',
title: '',
body: '',
draft: false,
provider: 'gitlab',
useTemplate: true
},
{ sourceControlAiResolvedParams }
)
expect(mocks.resolveHostedReviewBodyForGeneration).toHaveBeenCalledWith({
body: '',
repoPath: worktreePath,
connectionId: undefined,
provider: 'gitlab',
useTemplate: true
})
expect(mocks.getPullRequestDraftContext).toHaveBeenCalledWith(
expect.any(Function),
expect.objectContaining({
currentBody: templateBody
})
)
})
it('resolves remote commit-message settings against the SSH host cache', async () => {
const worktreePath = '/remote/repo'
const context = {
+19 -3
View File
@@ -71,6 +71,8 @@ import { prepareLocalCommitMessageAgentEnv } from '../text-generation/commit-mes
import { getPullRequestDraftContext } from '../text-generation/pull-request-context'
import { normalizeRuntimeRelativePath } from './runtime-relative-paths'
import { gitExecFileAsync } from '../git/runner'
import { resolveHostedReviewBodyForGeneration } from '../source-control/pull-request-template'
import type { HostedReviewProvider } from '../../shared/hosted-review'
export type ResolvedRuntimeGitWorktree = Worktree & { git: GitWorktreeInfo }
type RuntimeCommitMessageSettingsOverride = Partial<
@@ -580,7 +582,14 @@ export class RuntimeGitCommands {
async generateRuntimePullRequestFields(
worktreeSelector: string,
input: { base: string; title: string; body: string; draft: boolean },
input: {
base: string
title: string
body: string
draft: boolean
provider?: HostedReviewProvider
useTemplate?: boolean
},
settingsOverride?: RuntimeCommitMessageSettingsOverride
): Promise<GeneratePullRequestFieldsResult> {
const target = await this.host.resolveRuntimeGitTarget(worktreeSelector)
@@ -612,11 +621,18 @@ export class RuntimeGitCommands {
}
let context: Awaited<ReturnType<typeof getPullRequestDraftContext>>
try {
const currentBody = await resolveHostedReviewBodyForGeneration({
body: input.body,
repoPath: target.worktree.path,
connectionId: target.connectionId,
provider: input.provider,
useTemplate: input.useTemplate
})
context = target.connectionId
? await getPullRequestDraftContext((argv) => provider!.exec(argv, target.worktree.path), {
base: input.base,
currentTitle: input.title,
currentBody: input.body,
currentBody,
currentDraft: input.draft
})
: await getPullRequestDraftContext(
@@ -624,7 +640,7 @@ export class RuntimeGitCommands {
{
base: input.base,
currentTitle: input.title,
currentBody: input.body,
currentBody,
currentDraft: input.draft
}
)
+5 -1
View File
@@ -172,7 +172,11 @@ export const GitGeneratePullRequestFields = GitGenerateCommitMessage.extend({
base: z.string().min(1, 'Missing base branch'),
title: z.string(),
body: z.string(),
draft: z.boolean()
draft: z.boolean(),
provider: z
.enum(['github', 'gitlab', 'bitbucket', 'azure-devops', 'gitea', 'unsupported'])
.optional(),
useTemplate: z.boolean().optional()
})
export const GitBulkPaths = WorktreeSelector.extend({
+10 -1
View File
@@ -512,13 +512,22 @@ describe('git RPC methods', () => {
title: '',
body: '',
draft: false,
provider: 'github',
useTemplate: true,
sourceControlAiResolvedParams
})
)
expect(runtime.generateRuntimePullRequestFields).toHaveBeenCalledWith(
'id:wt-1',
{ base: 'main', title: '', body: '', draft: false },
{
base: 'main',
title: '',
body: '',
draft: false,
provider: 'github',
useTemplate: true
},
{ sourceControlAiResolvedParams }
)
})
+3 -1
View File
@@ -278,7 +278,9 @@ export const GIT_METHODS: RpcMethod[] = [
base: params.base,
title: params.title,
body: params.body,
draft: params.draft
draft: params.draft,
provider: params.provider,
useTemplate: params.useTemplate
}
const override = buildCommitMessageGenerationOverride(params)
if (override === undefined) {
+88 -2
View File
@@ -3,6 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
createGitHubPullRequestMock,
createGitLabMergeRequestMock,
createAzureDevOpsPullRequestMock,
createGiteaPullRequestMock,
getAzureDevOpsRepoSlugMock,
getBitbucketRepoSlugMock,
getGiteaRepoSlugMock,
@@ -13,6 +15,8 @@ const {
} = vi.hoisted(() => ({
createGitHubPullRequestMock: vi.fn(),
createGitLabMergeRequestMock: vi.fn(),
createAzureDevOpsPullRequestMock: vi.fn(),
createGiteaPullRequestMock: vi.fn(),
getAzureDevOpsRepoSlugMock: vi.fn(),
getBitbucketRepoSlugMock: vi.fn(),
getGiteaRepoSlugMock: vi.fn(),
@@ -50,12 +54,20 @@ vi.mock('../azure-devops/client', () => ({
getAzureDevOpsPullRequest: vi.fn()
}))
vi.mock('../azure-devops/pull-request-creation', () => ({
createAzureDevOpsPullRequest: createAzureDevOpsPullRequestMock
}))
vi.mock('../gitea/client', () => ({
getGiteaRepoSlug: getGiteaRepoSlugMock,
getGiteaPullRequestForBranch: vi.fn(),
getGiteaPullRequest: vi.fn()
}))
vi.mock('../gitea/pull-request-creation', () => ({
createGiteaPullRequest: createGiteaPullRequestMock
}))
import {
FORGE_PROVIDERS,
detectHostedReviewProvider,
@@ -67,6 +79,8 @@ describe('forge provider interface', () => {
beforeEach(() => {
createGitHubPullRequestMock.mockReset()
createGitLabMergeRequestMock.mockReset()
createAzureDevOpsPullRequestMock.mockReset()
createGiteaPullRequestMock.mockReset()
getAzureDevOpsRepoSlugMock.mockReset()
getBitbucketRepoSlugMock.mockReset()
getGiteaRepoSlugMock.mockReset()
@@ -94,8 +108,8 @@ describe('forge provider interface', () => {
['gitlab', true],
['github', true],
['bitbucket', false],
['azure-devops', false],
['gitea', false]
['azure-devops', true],
['gitea', true]
])
createGitHubPullRequestMock.mockResolvedValue({
ok: true,
@@ -160,6 +174,78 @@ describe('forge provider interface', () => {
)
})
it('routes Azure DevOps review creation through the shared provider contract', async () => {
createAzureDevOpsPullRequestMock.mockResolvedValue({
ok: true,
number: 88,
url: 'https://dev.azure.com/acme/Project/_git/orca/pullrequest/88'
})
const provider = getForgeProviderById('azure-devops')
await expect(
provider.createReview?.(
'/repo',
{
provider: 'azure-devops',
base: 'main',
head: 'feature/provider-interface',
title: 'Add provider interface'
},
'ssh-1'
)
).resolves.toEqual({
ok: true,
number: 88,
url: 'https://dev.azure.com/acme/Project/_git/orca/pullrequest/88'
})
expect(createAzureDevOpsPullRequestMock).toHaveBeenCalledWith(
'/repo',
{
provider: 'azure-devops',
base: 'main',
head: 'feature/provider-interface',
title: 'Add provider interface'
},
'ssh-1'
)
})
it('routes Gitea review creation through the shared provider contract', async () => {
createGiteaPullRequestMock.mockResolvedValue({
ok: true,
number: 19,
url: 'https://git.example.com/team/orca/pulls/19'
})
const provider = getForgeProviderById('gitea')
await expect(
provider.createReview?.(
'/repo',
{
provider: 'gitea',
base: 'main',
head: 'feature/provider-interface',
title: 'Add provider interface'
},
'ssh-1'
)
).resolves.toEqual({
ok: true,
number: 19,
url: 'https://git.example.com/team/orca/pulls/19'
})
expect(createGiteaPullRequestMock).toHaveBeenCalledWith(
'/repo',
{
provider: 'gitea',
base: 'main',
head: 'feature/provider-interface',
title: 'Add provider interface'
},
'ssh-1'
)
})
it('adapts GitHub branch lookup through the shared provider contract', async () => {
getPRForBranchMock.mockResolvedValue({
number: 7,
+8 -4
View File
@@ -11,6 +11,7 @@ import {
getAzureDevOpsPullRequestForBranch,
getAzureDevOpsRepoSlug
} from '../azure-devops/client'
import { createAzureDevOpsPullRequest } from '../azure-devops/pull-request-creation'
import type { AzureDevOpsPullRequestInfo } from '../azure-devops/pull-request-mappers'
import {
getBitbucketPullRequest,
@@ -23,6 +24,7 @@ import {
getGiteaPullRequestForBranch,
getGiteaRepoSlug
} from '../gitea/client'
import { createGiteaPullRequest } from '../gitea/pull-request-creation'
import type { GiteaPullRequestInfo } from '../gitea/pull-request-mappers'
import { createGitHubPullRequest, getPRForBranch, getRepoSlug } from '../github/client'
import { getMergeRequest, getMergeRequestForBranch, getProjectSlug } from '../gitlab/client'
@@ -198,7 +200,7 @@ const bitbucketForgeProvider = {
const azureDevOpsForgeProvider = {
id: 'azure-devops',
supportsReviewCreation: false,
supportsReviewCreation: true,
resolveRepository: ({ repoPath, connectionId }) => getAzureDevOpsRepoSlug(repoPath, connectionId),
async getReviewForBranch(input) {
const pr = await getAzureDevOpsPullRequestForBranch(
@@ -212,12 +214,13 @@ const azureDevOpsForgeProvider = {
async getReviewByNumber(input) {
const pr = await getAzureDevOpsPullRequest(input.repoPath, input.number, input.connectionId)
return pr ? mapAzureDevOpsReview(pr) : null
}
},
createReview: createAzureDevOpsPullRequest
} satisfies ForgeProvider
const giteaForgeProvider = {
id: 'gitea',
supportsReviewCreation: false,
supportsReviewCreation: true,
resolveRepository: ({ repoPath, connectionId }) => getGiteaRepoSlug(repoPath, connectionId),
async getReviewForBranch(input) {
const pr = await getGiteaPullRequestForBranch(
@@ -231,7 +234,8 @@ const giteaForgeProvider = {
async getReviewByNumber(input) {
const pr = await getGiteaPullRequest(input.repoPath, input.number, input.connectionId)
return pr ? mapGiteaReview(pr) : null
}
},
createReview: createGiteaPullRequest
} satisfies ForgeProvider
// Why: provider order preserves existing branch-status behavior when remotes
@@ -0,0 +1,48 @@
export class HostedReviewApiRequestError extends Error {
readonly status: number | null
readonly timedOut: boolean
constructor(message: string, options: { status?: number | null; timedOut?: boolean } = {}) {
super(message)
this.name = 'HostedReviewApiRequestError'
this.status = options.status ?? null
this.timedOut = options.timedOut ?? false
}
}
async function readResponseText(response: Response): Promise<string> {
try {
return await response.text()
} catch {
return ''
}
}
export async function requestHostedReviewJson<T>(
url: URL,
init: Omit<RequestInit, 'signal'>,
timeoutMs: number
): Promise<T> {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), timeoutMs)
try {
const response = await fetch(url, { ...init, signal: controller.signal })
if (!response.ok) {
const body = await readResponseText(response)
throw new HostedReviewApiRequestError(body || response.statusText, {
status: response.status
})
}
return (await response.json()) as T
} catch (error) {
if (error instanceof HostedReviewApiRequestError) {
throw error
}
if (error instanceof Error && error.name === 'AbortError') {
throw new HostedReviewApiRequestError('Request timed out', { timedOut: true })
}
throw error
} finally {
clearTimeout(timeout)
}
}
@@ -4,6 +4,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
createGitHubPullRequestMock,
createGitLabMergeRequestMock,
createAzureDevOpsPullRequestMock,
createGiteaPullRequestMock,
isAzureDevOpsReviewCreationAuthenticatedMock,
isGiteaReviewCreationAuthenticatedMock,
getRepoSlugMock,
getProjectSlugMock,
getBitbucketRepoSlugMock,
@@ -18,6 +22,10 @@ const {
} = vi.hoisted(() => ({
createGitHubPullRequestMock: vi.fn(),
createGitLabMergeRequestMock: vi.fn(),
createAzureDevOpsPullRequestMock: vi.fn(),
createGiteaPullRequestMock: vi.fn(),
isAzureDevOpsReviewCreationAuthenticatedMock: vi.fn(),
isGiteaReviewCreationAuthenticatedMock: vi.fn(),
getRepoSlugMock: vi.fn(),
getProjectSlugMock: vi.fn(),
getBitbucketRepoSlugMock: vi.fn(),
@@ -59,12 +67,22 @@ vi.mock('../azure-devops/client', () => ({
getAzureDevOpsPullRequest: vi.fn()
}))
vi.mock('../azure-devops/pull-request-creation', () => ({
createAzureDevOpsPullRequest: createAzureDevOpsPullRequestMock,
isAzureDevOpsReviewCreationAuthenticated: isAzureDevOpsReviewCreationAuthenticatedMock
}))
vi.mock('../gitea/client', () => ({
getGiteaRepoSlug: getGiteaRepoSlugMock,
getGiteaPullRequestForBranch: vi.fn(),
getGiteaPullRequest: vi.fn()
}))
vi.mock('../gitea/pull-request-creation', () => ({
createGiteaPullRequest: createGiteaPullRequestMock,
isGiteaReviewCreationAuthenticated: isGiteaReviewCreationAuthenticatedMock
}))
vi.mock('../github/gh-utils', () => ({
acquire: vi.fn(),
release: vi.fn(),
@@ -98,6 +116,10 @@ function resetMocks(): void {
for (const mock of [
createGitHubPullRequestMock,
createGitLabMergeRequestMock,
createAzureDevOpsPullRequestMock,
createGiteaPullRequestMock,
isAzureDevOpsReviewCreationAuthenticatedMock,
isGiteaReviewCreationAuthenticatedMock,
getRepoSlugMock,
getProjectSlugMock,
getBitbucketRepoSlugMock,
@@ -130,6 +152,34 @@ function mockGitLabProvider(): void {
getGiteaRepoSlugMock.mockResolvedValue(null)
}
function mockAzureDevOpsProvider(): void {
getProjectSlugMock.mockResolvedValue(null)
getRepoSlugMock.mockResolvedValue(null)
getBitbucketRepoSlugMock.mockResolvedValue(null)
getAzureDevOpsRepoSlugMock.mockResolvedValue({
host: 'dev.azure.com',
project: 'Project',
repository: 'orca',
apiBaseUrl: 'https://dev.azure.com/acme/Project',
webBaseUrl: 'https://dev.azure.com/acme/Project/_git/orca'
})
getGiteaRepoSlugMock.mockResolvedValue(null)
}
function mockGiteaProvider(): void {
getProjectSlugMock.mockResolvedValue(null)
getRepoSlugMock.mockResolvedValue(null)
getBitbucketRepoSlugMock.mockResolvedValue(null)
getAzureDevOpsRepoSlugMock.mockResolvedValue(null)
getGiteaRepoSlugMock.mockResolvedValue({
host: 'git.example.com',
owner: 'acme',
repo: 'orca',
apiBaseUrl: 'https://git.example.com/api/v1',
webBaseUrl: 'https://git.example.com'
})
}
describe('createHostedReview', () => {
beforeEach(() => {
resetMocks()
@@ -169,6 +219,18 @@ describe('createHostedReview', () => {
number: 44,
url: 'https://gitlab.com/acme/orca/-/merge_requests/44'
})
createAzureDevOpsPullRequestMock.mockResolvedValue({
ok: true,
number: 88,
url: 'https://dev.azure.com/acme/Project/_git/orca/pullrequest/88'
})
createGiteaPullRequestMock.mockResolvedValue({
ok: true,
number: 19,
url: 'https://git.example.com/acme/orca/pulls/19'
})
isAzureDevOpsReviewCreationAuthenticatedMock.mockReturnValue(true)
isGiteaReviewCreationAuthenticatedMock.mockReturnValue(true)
})
it('revalidates ahead commits before creating a GitHub pull request', async () => {
@@ -266,6 +328,66 @@ describe('createHostedReview', () => {
expect(createGitHubPullRequestMock).not.toHaveBeenCalled()
})
it('creates an Azure DevOps pull request after fresh main-process validation passes', async () => {
mockAzureDevOpsProvider()
await expect(
createHostedReview('/repo', {
provider: 'azure-devops',
base: 'main',
head: 'feature',
title: 'Feature'
})
).resolves.toEqual({
ok: true,
number: 88,
url: 'https://dev.azure.com/acme/Project/_git/orca/pullrequest/88'
})
expect(createAzureDevOpsPullRequestMock).toHaveBeenCalledWith(
'/repo',
{
provider: 'azure-devops',
base: 'main',
head: 'feature',
title: 'Feature'
},
undefined
)
expect(createGitHubPullRequestMock).not.toHaveBeenCalled()
expect(createGitLabMergeRequestMock).not.toHaveBeenCalled()
})
it('creates a Gitea pull request after fresh main-process validation passes', async () => {
mockGiteaProvider()
await expect(
createHostedReview('/repo', {
provider: 'gitea',
base: 'main',
head: 'feature',
title: 'Feature'
})
).resolves.toEqual({
ok: true,
number: 19,
url: 'https://git.example.com/acme/orca/pulls/19'
})
expect(createGiteaPullRequestMock).toHaveBeenCalledWith(
'/repo',
{
provider: 'gitea',
base: 'main',
head: 'feature',
title: 'Feature'
},
undefined
)
expect(createGitHubPullRequestMock).not.toHaveBeenCalled()
expect(createGitLabMergeRequestMock).not.toHaveBeenCalled()
})
it('uses the SSH git provider for remote hosted-review preflight', async () => {
const remoteGit = {
getStatus: vi.fn(async () => ({ entries: [], conflictOperation: 'unknown' })),
@@ -375,6 +497,8 @@ describe('getHostedReviewCreationEligibility', () => {
getHostedReviewForBranchMock.mockResolvedValue(null)
ghExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'Feature title\n', stderr: '' })
isAzureDevOpsReviewCreationAuthenticatedMock.mockReturnValue(true)
isGiteaReviewCreationAuthenticatedMock.mockReturnValue(true)
})
it('treats short remote base refs as the default branch name', async () => {
@@ -511,4 +635,54 @@ describe('getHostedReviewCreationEligibility', () => {
{ cwd: '/repo' }
)
})
it('enables creation for clean, in-sync, token-configured Azure DevOps feature branches', async () => {
mockAzureDevOpsProvider()
await expect(
getHostedReviewCreationEligibility({
repoPath: '/repo',
branch: 'feature/azure',
base: 'main',
hasUncommittedChanges: false,
hasUpstream: true,
ahead: 0,
behind: 0
})
).resolves.toMatchObject({
provider: 'azure-devops',
canCreate: true,
blockedReason: null,
nextAction: null,
head: 'feature/azure'
})
expect(isAzureDevOpsReviewCreationAuthenticatedMock).toHaveBeenCalledOnce()
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
expect(glabExecFileAsyncMock).not.toHaveBeenCalled()
})
it('enables creation for clean, in-sync, token-configured Gitea feature branches', async () => {
mockGiteaProvider()
await expect(
getHostedReviewCreationEligibility({
repoPath: '/repo',
branch: 'feature/gitea',
base: 'main',
hasUncommittedChanges: false,
hasUpstream: true,
ahead: 0,
behind: 0
})
).resolves.toMatchObject({
provider: 'gitea',
canCreate: true,
blockedReason: null,
nextAction: null,
head: 'feature/gitea'
})
expect(isGiteaReviewCreationAuthenticatedMock).toHaveBeenCalledOnce()
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
expect(glabExecFileAsyncMock).not.toHaveBeenCalled()
})
})
@@ -12,6 +12,12 @@ import {
normalizeHostedReviewBaseRef,
normalizeHostedReviewHeadRef
} from '../../shared/hosted-review-refs'
import {
supportsHostedReviewCreation,
type HostedReviewCreationProvider
} from '../../shared/hosted-review-creation-providers'
import { isAzureDevOpsReviewCreationAuthenticated } from '../azure-devops/pull-request-creation'
import { isGiteaReviewCreationAuthenticated } from '../gitea/pull-request-creation'
import { acquire, ghExecFileAsync, gitExecFileAsync, release } from '../github/gh-utils'
import { isNoUpstreamError, normalizeGitErrorMessage } from '../../shared/git-remote-error'
import type { GitUpstreamStatus } from '../../shared/types'
@@ -160,22 +166,56 @@ async function getHostedReviewUpstreamStatus(
function reviewCopy(provider: HostedReviewProvider): {
shortLabel: 'PR' | 'MR'
reviewLabel: 'pull request' | 'merge request'
providerName: 'GitHub' | 'GitLab'
authCommand: 'gh auth login' | 'glab auth login'
providerName: string
authInstruction: string
} {
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'
}
if (provider === 'gitlab') {
return {
shortLabel: 'MR',
reviewLabel: 'merge request',
providerName: 'GitLab',
authInstruction: 'Run glab auth login'
}
}
if (provider === 'azure-devops') {
return {
shortLabel: 'PR',
reviewLabel: 'pull request',
providerName: 'Azure DevOps',
authInstruction: 'Set ORCA_AZURE_DEVOPS_TOKEN'
}
}
if (provider === 'gitea') {
return {
shortLabel: 'PR',
reviewLabel: 'pull request',
providerName: 'Gitea',
authInstruction: 'Set ORCA_GITEA_TOKEN'
}
}
return {
shortLabel: 'PR',
reviewLabel: 'pull request',
providerName: 'GitHub',
authInstruction: 'Run gh auth login'
}
}
async function isProviderAuthenticated(
provider: HostedReviewCreationProvider,
repoPath: string,
connectionId?: string | null
): Promise<boolean> {
if (provider === 'gitlab') {
return isGitLabAuthenticated(repoPath, connectionId)
}
if (provider === 'azure-devops') {
return isAzureDevOpsReviewCreationAuthenticated()
}
if (provider === 'gitea') {
return isGiteaReviewCreationAuthenticated()
}
return isGitHubAuthenticated(repoPath, connectionId)
}
function blockedCreateResultForReason(
@@ -187,7 +227,7 @@ function blockedCreateResultForReason(
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.`
error: `Create ${copy.shortLabel} failed: ${copy.providerName} is not authenticated. Next step: ${copy.authInstruction} in this environment.`
},
unsupported_provider: {
ok: false,
@@ -346,7 +386,7 @@ export async function getHostedReviewCreationEligibility(
nextAction: 'open_existing_review'
}
}
if (provider !== 'github' && provider !== 'gitlab') {
if (!supportsHostedReviewCreation(provider)) {
return {
...baseResult,
canCreate: false,
@@ -369,10 +409,7 @@ export async function getHostedReviewCreationEligibility(
if ((args.behind ?? 0) > 0) {
return { ...baseResult, canCreate: false, blockedReason: 'needs_sync', nextAction: 'sync' }
}
const authenticated =
provider === 'gitlab'
? await isGitLabAuthenticated(args.repoPath, args.connectionId)
: await isGitHubAuthenticated(args.repoPath, args.connectionId)
const authenticated = await isProviderAuthenticated(provider, args.repoPath, args.connectionId)
if (!authenticated) {
return {
...baseResult,
@@ -392,7 +429,7 @@ export async function createHostedReview(
input: CreateHostedReviewInput,
connectionId?: string | null
): Promise<CreateHostedReviewResult> {
if (input.provider !== 'github' && input.provider !== 'gitlab') {
if (!supportsHostedReviewCreation(input.provider)) {
return {
ok: false,
code: 'unsupported_provider',
@@ -0,0 +1,82 @@
import { readFile } from 'fs/promises'
import { join } from 'path'
import type { HostedReviewProvider } from '../../shared/hosted-review'
import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch'
import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths'
const PULL_REQUEST_TEMPLATE_CANDIDATES = [
'.github/pull_request_template.md',
'.github/PULL_REQUEST_TEMPLATE.md',
'.azuredevops/pull_request_template.md',
'.azuredevops/PULL_REQUEST_TEMPLATE.md',
'.gitea/pull_request_template.md',
'.gitea/PULL_REQUEST_TEMPLATE.md',
'pull_request_template.md',
'PULL_REQUEST_TEMPLATE.md',
'docs/pull_request_template.md',
'docs/PULL_REQUEST_TEMPLATE.md'
]
const MERGE_REQUEST_TEMPLATE_CANDIDATES = [
'.gitlab/merge_request_templates/Default.md',
'.gitlab/merge_request_templates/default.md',
'.gitlab/merge_request_template.md',
'.gitlab/MERGE_REQUEST_TEMPLATE.md'
]
function getTemplateCandidates(provider?: HostedReviewProvider | null): string[] {
if (provider === 'gitlab') {
return [...MERGE_REQUEST_TEMPLATE_CANDIDATES, ...PULL_REQUEST_TEMPLATE_CANDIDATES]
}
return PULL_REQUEST_TEMPLATE_CANDIDATES
}
export async function readHostedPullRequestTemplate(
repoPath: string,
connectionId?: string | null
): Promise<string> {
return readHostedReviewTemplate(repoPath, connectionId)
}
export async function readHostedReviewTemplate(
repoPath: string,
connectionId?: string | null,
provider?: HostedReviewProvider | null
): Promise<string> {
const remoteProvider = connectionId ? getSshFilesystemProvider(connectionId) : undefined
if (connectionId && !remoteProvider) {
return ''
}
for (const relativeCandidate of getTemplateCandidates(provider)) {
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 hosted-review template path.
}
}
return ''
}
export async function resolveHostedReviewBodyForGeneration(args: {
body: string
repoPath: string
connectionId?: string | null
provider?: HostedReviewProvider | null
useTemplate?: boolean
}): Promise<string> {
if (!args.useTemplate || args.body.trim()) {
return args.body
}
// Why: generated non-empty bodies bypass provider-side template fallback, so
// preload the template into the AI context when the user asked to use it.
return readHostedReviewTemplate(args.repoPath, args.connectionId, args.provider)
}