Add project Windows runtime selection (#5519)

* Add project Windows runtime selection

* Fix project Windows runtime selection

Co-authored-by: Orca <help@stably.ai>

* fix: preserve WSL shell variables

---------

Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com>
Co-authored-by: Orca <help@stably.ai>
Co-authored-by: Neil <neil@stably.ai>
This commit is contained in:
slashdevcorpse
2026-06-17 16:08:14 -07:00
committed by GitHub
co-authored by Orca Jinwoo-H Neil
parent 25d2053b25
commit 0ec3882cb8
333 changed files with 21039 additions and 5507 deletions
+36
View File
@@ -117,6 +117,42 @@ describe('createGitHubPullRequest', () => {
expect(releaseMock).toHaveBeenCalledOnce()
})
it('runs local WSL project pull request creation through the selected distro', async () => {
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
ghExecFileAsyncMock.mockResolvedValueOnce({
stdout: JSON.stringify({
number: 43,
url: 'https://github.com/acme/widgets/pull/43'
})
})
await expect(
createGitHubPullRequest(
'/repo-root',
{
provider: 'github',
base: 'main',
head: 'feature/wsl-create-pr',
title: 'WSL Create PR'
},
null,
{ localGitExecOptions: { wslDistro: 'Ubuntu' } }
)
).resolves.toEqual({
ok: true,
number: 43,
url: 'https://github.com/acme/widgets/pull/43'
})
const [, options] = ghExecFileAsyncMock.mock.calls[0]
expect(options).toMatchObject({
cwd: '/repo-root',
wslDistro: 'Ubuntu',
timeout: 60_000,
idempotent: false
})
})
it('creates SSH-backed pull requests without using the remote path as a local cwd', async () => {
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
ghExecFileAsyncMock.mockResolvedValueOnce({
+28 -3
View File
@@ -14,10 +14,15 @@ vi.mock('./gh-utils', () => ({
getIssueOwnerRepo: vi.fn(),
getOwnerRepoForRemote: vi.fn(),
resolveIssueSource: vi.fn(),
ghRepoExecOptions: vi.fn((context) => (context.connectionId ? {} : { cwd: context.repoPath })),
githubRepoContext: vi.fn((repoPath, connectionId) => ({
ghRepoExecOptions: vi.fn((context) =>
context.connectionId
? {}
: { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) }
),
githubRepoContext: vi.fn((repoPath, connectionId, localGitOptions) => ({
repoPath,
connectionId: connectionId ?? null
connectionId: connectionId ?? null,
...localGitOptions
})),
classifyGhError: vi.fn(),
classifyListIssuesError: vi.fn(),
@@ -73,4 +78,24 @@ describe('setPRFileViewed', () => {
const args = ghExecFileAsyncMock.mock.calls[0][0]
expect(args.find((arg: string) => arg.startsWith('query='))).toContain('unmarkFileAsViewed')
})
it('routes local WSL file-viewed mutations through the selected distro', async () => {
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '{}' })
await expect(
setPRFileViewed({
repoPath: '/repo-root',
connectionId: null,
localGitOptions: { wslDistro: 'Ubuntu' },
pullRequestId: 'PR_kwDO123',
path: 'src/app.ts',
viewed: true
})
).resolves.toBe(true)
expect(ghExecFileAsyncMock.mock.calls[0][1]).toEqual({
cwd: '/repo-root',
wslDistro: 'Ubuntu'
})
})
})
+8 -3
View File
@@ -173,8 +173,13 @@ describe('GitHub issue source split', () => {
await listWorkItems('/home/jinwoo/orca', 10, undefined, undefined, 'auto', 'openclaw-2')
expect(resolveIssueSourceMock).toHaveBeenCalledWith('/home/jinwoo/orca', 'auto', 'openclaw-2')
expect(getOwnerRepoMock).toHaveBeenCalledWith('/home/jinwoo/orca', 'openclaw-2')
expect(resolveIssueSourceMock).toHaveBeenCalledWith(
'/home/jinwoo/orca',
'auto',
'openclaw-2',
{}
)
expect(getOwnerRepoMock).toHaveBeenCalledWith('/home/jinwoo/orca', 'openclaw-2', {})
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
1,
[
@@ -512,7 +517,7 @@ describe('GitHub issue source split', () => {
const result = await listWorkItems('/repo-root', 10, undefined, undefined, 'auto')
expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'auto', undefined)
expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'auto', undefined, {})
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
1,
[
+56 -3
View File
@@ -38,11 +38,19 @@ const {
vi.mock('./gh-utils', () => ({
execFileAsync: execFileAsyncMock,
ghExecFileAsync: ghExecFileAsyncMock,
githubRepoContext: (repoPath: string, connectionId?: string | null) => ({
githubRepoContext: (
repoPath: string,
connectionId?: string | null,
localGitOptions: { wslDistro?: string } = {}
) => ({
repoPath,
connectionId: connectionId ?? null
connectionId: connectionId ?? null,
...localGitOptions
}),
ghRepoExecOptions: (context: { repoPath: string; wslDistro?: string }) => ({
cwd: context.repoPath,
...(context.wslDistro ? { wslDistro: context.wslDistro } : {})
}),
ghRepoExecOptions: (context: { repoPath: string }) => ({ cwd: context.repoPath }),
getOwnerRepo: getOwnerRepoMock,
getIssueOwnerRepo: getIssueOwnerRepoMock,
extractExecError: extractExecErrorMock,
@@ -231,6 +239,51 @@ describe('getPRChecks', () => {
)
})
it('routes local WSL check retrieval and reruns through the selected distro', async () => {
const localGitOptions = { wslDistro: 'Ubuntu' }
getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' })
ghExecFileAsyncMock
.mockResolvedValueOnce({
stdout: JSON.stringify({
check_runs: [
{
name: 'build',
status: 'completed',
conclusion: 'success',
html_url: 'https://github.com/acme/widgets/actions/runs/66',
details_url: null
}
]
})
})
.mockResolvedValueOnce({
stdout: JSON.stringify([
{
name: 'lint',
state: 'FAIL',
link: 'https://github.com/acme/widgets/actions/runs/77/job/88'
}
])
})
.mockResolvedValueOnce({ stdout: '' })
await getPRChecks('/repo-root', 42, 'head-oid', undefined, undefined, null, localGitOptions)
await rerunPRChecks('/repo-root', 42, { failedOnly: true }, null, localGitOptions)
expect(getOwnerRepoMock).toHaveBeenCalledWith('/repo-root', null, localGitOptions)
expect(ghExecFileAsyncMock.mock.calls.every((call) => call[1]?.wslDistro === 'Ubuntu')).toBe(
true
)
expect(ghExecFileAsyncMock).toHaveBeenLastCalledWith(
['api', '-X', 'POST', 'repos/acme/widgets/actions/runs/77/rerun-failed-jobs'],
expect.objectContaining({
cwd: '/repo-root',
wslDistro: 'Ubuntu',
env: expect.objectContaining({ GH_PROMPT_DISABLED: '1' })
})
)
})
it('uses explicit PR repo for check-runs and gh pr checks fallback', async () => {
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'widgets' })
ghExecFileAsyncMock
@@ -0,0 +1,241 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
type RateLimitGuardResult =
| { blocked: false }
| { blocked: true; remaining: number; limit: number; resetAt: number }
const {
execFileAsyncMock,
ghExecFileAsyncMock,
getOwnerRepoMock,
getIssueOwnerRepoMock,
getOwnerRepoForRemoteMock,
resolvePRRepositoryCandidatesMock,
getRemoteUrlForRepoMock,
gitExecFileAsyncMock,
getRateLimitMock,
rateLimitGuardMock,
noteRateLimitSpendMock,
acquireMock,
releaseMock
} = vi.hoisted(() => ({
execFileAsyncMock: vi.fn(),
ghExecFileAsyncMock: vi.fn(),
getOwnerRepoMock: vi.fn(),
getIssueOwnerRepoMock: vi.fn(),
getOwnerRepoForRemoteMock: vi.fn(),
resolvePRRepositoryCandidatesMock: vi.fn(),
getRemoteUrlForRepoMock: vi.fn(),
gitExecFileAsyncMock: vi.fn(),
getRateLimitMock: vi.fn(),
rateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })),
noteRateLimitSpendMock: vi.fn(),
acquireMock: vi.fn(),
releaseMock: vi.fn()
}))
vi.mock('./gh-utils', () => ({
execFileAsync: execFileAsyncMock,
ghExecFileAsync: ghExecFileAsyncMock,
gitExecFileAsync: gitExecFileAsyncMock,
extractExecError: (err: unknown) => ({
stderr: err instanceof Error ? err.message : String(err),
stdout: ''
}),
acquire: acquireMock,
release: releaseMock,
getOwnerRepo: getOwnerRepoMock,
getIssueOwnerRepo: getIssueOwnerRepoMock,
getOwnerRepoForRemote: getOwnerRepoForRemoteMock,
resolvePRRepositoryCandidates: resolvePRRepositoryCandidatesMock,
resolveIssueSource: vi.fn(),
classifyGhError: (message: string) => ({ type: 'unknown', message }),
classifyListIssuesError: (message: string) => ({ type: 'unknown', message }),
ghRepoExecOptions: (context: {
repoPath: string
connectionId?: string | null
wslDistro?: string
}) =>
context.connectionId
? {}
: { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) },
githubRepoContext: (
repoPath: string,
connectionId?: string | null,
localGitOptions: { wslDistro?: string } = {}
) => ({
repoPath,
connectionId: connectionId ?? null,
...localGitOptions
}),
getRemoteUrlForRepo: getRemoteUrlForRepoMock,
_resetOwnerRepoCache: vi.fn()
}))
vi.mock('../git/runner', () => ({
gitExecFileAsync: gitExecFileAsyncMock
}))
vi.mock('../providers/ssh-git-dispatch', () => ({
getSshGitProvider: vi.fn()
}))
vi.mock('./conflict-summary', () => ({
getPRConflictSummary: vi.fn()
}))
vi.mock('./rate-limit', () => ({
getRateLimit: getRateLimitMock,
rateLimitGuard: rateLimitGuardMock,
noteRateLimitSpend: noteRateLimitSpendMock
}))
import {
addPRReviewComment,
addPRReviewCommentReply,
getPRComments,
mergePR,
removePRReviewers,
requestPRReviewers,
resolveReviewThread,
setPRAutoMerge,
updatePRDetails,
updatePRState,
updatePRTitle
} from './client'
describe('GitHub PR local runtime routing', () => {
beforeEach(() => {
execFileAsyncMock.mockReset()
ghExecFileAsyncMock.mockReset()
getOwnerRepoMock.mockReset()
getIssueOwnerRepoMock.mockReset()
getOwnerRepoForRemoteMock.mockReset()
resolvePRRepositoryCandidatesMock.mockReset()
getRemoteUrlForRepoMock.mockReset()
gitExecFileAsyncMock.mockReset()
getRateLimitMock.mockReset()
getRateLimitMock.mockResolvedValue({ resources: {} })
rateLimitGuardMock.mockReset()
rateLimitGuardMock.mockReturnValue({ blocked: false })
noteRateLimitSpendMock.mockReset()
acquireMock.mockReset()
releaseMock.mockReset()
acquireMock.mockResolvedValue(undefined)
})
it('routes PR details and mutations through the selected WSL distro', async () => {
const localGitOptions = { wslDistro: 'Ubuntu' }
const prRepo = { owner: 'acme', repo: 'orca' }
getOwnerRepoMock.mockResolvedValue(prRepo)
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
const endpoint = args.find((arg) => arg.startsWith('repos/acme/orca/')) ?? ''
const query = args.find((arg) => arg.startsWith('query=')) ?? ''
if (args[0] === 'pr' && args[1] === 'view') {
return {
stdout: JSON.stringify({
number: 7,
title: 'PR',
state: 'OPEN',
url: 'https://github.com/acme/orca/pull/7',
statusCheckRollup: [],
updatedAt: '2026-04-01T00:00:00Z',
isDraft: false,
mergeable: 'MERGEABLE',
reviewDecision: 'APPROVED',
mergeStateStatus: 'CLEAN',
autoMergeRequest: null,
baseRefName: 'main',
baseRefOid: 'base-oid',
headRefOid: 'head-oid'
})
}
}
if (query.includes('reviewThreads')) {
return {
stdout: JSON.stringify({
data: {
repository: {
pullRequest: {
reviewThreads: { nodes: [] },
comments: { nodes: [] }
}
}
}
})
}
}
if (endpoint.endsWith('/issues/7/comments?per_page=100')) {
return { stdout: '[]' }
}
if (endpoint.endsWith('/pulls/7/reviews?per_page=100')) {
return { stdout: '[]' }
}
if (endpoint.endsWith('/pulls/7/comments/11/replies')) {
return { stdout: JSON.stringify({ id: 12, user: null, body: 'Reply' }) }
}
if (endpoint.endsWith('/pulls/7/comments')) {
return { stdout: JSON.stringify({ id: 13, user: null, body: 'Inline' }) }
}
return { stdout: '', stderr: '' }
})
await getPRComments('/repo-root', 7, { prRepo }, null, localGitOptions)
await expect(
resolveReviewThread('/repo-root', 'thread-1', true, null, localGitOptions)
).resolves.toBe(true)
await expect(
addPRReviewCommentReply(
'/repo-root',
7,
11,
'Reply',
'thread-1',
'src/app.ts',
10,
null,
prRepo,
localGitOptions
)
).resolves.toMatchObject({ ok: true })
await expect(
addPRReviewComment({
repoPath: '/repo-root',
connectionId: null,
localGitOptions,
prNumber: 7,
body: 'Inline',
commitId: 'head-oid',
path: 'src/app.ts',
line: 10
})
).resolves.toMatchObject({ ok: true })
await expect(
updatePRTitle('/repo-root', 7, 'New title', null, prRepo, localGitOptions)
).resolves.toBe(true)
await expect(
updatePRDetails('/repo-root', 7, { body: 'New body' }, null, prRepo, localGitOptions)
).resolves.toEqual({ ok: true })
await expect(
updatePRState('/repo-root', 7, { state: 'closed' }, null, localGitOptions)
).resolves.toEqual({ ok: true })
await expect(
requestPRReviewers('/repo-root', 7, ['octo'], null, localGitOptions)
).resolves.toEqual({ ok: true })
await expect(
removePRReviewers('/repo-root', 7, ['octo'], null, localGitOptions)
).resolves.toEqual({ ok: true })
await expect(
setPRAutoMerge('/repo-root', 7, true, 'squash', null, prRepo, localGitOptions)
).resolves.toEqual({ ok: true })
await expect(
mergePR('/repo-root', 7, 'squash', null, prRepo, localGitOptions)
).resolves.toEqual({ ok: true })
expect(getOwnerRepoMock).toHaveBeenCalledWith('/repo-root', null, localGitOptions)
expect(ghExecFileAsyncMock.mock.calls.every((call) => call[1]?.wslDistro === 'Ubuntu')).toBe(
true
)
})
})
+54 -4
View File
@@ -32,12 +32,23 @@ const {
vi.mock('./gh-utils', () => ({
execFileAsync: execFileAsyncMock,
ghExecFileAsync: ghExecFileAsyncMock,
githubRepoContext: (repoPath: string, connectionId?: string | null) => ({
githubRepoContext: (
repoPath: string,
connectionId?: string | null,
localGitOptions: { wslDistro?: string } = {}
) => ({
repoPath,
connectionId: connectionId ?? null
connectionId: connectionId ?? null,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
}),
ghRepoExecOptions: (context: { repoPath: string; connectionId?: string | null }) =>
context.connectionId ? {} : { cwd: context.repoPath },
ghRepoExecOptions: (context: {
repoPath: string
connectionId?: string | null
wslDistro?: string
}) =>
context.connectionId
? {}
: { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) },
getOwnerRepo: getOwnerRepoMock,
getIssueOwnerRepo: getIssueOwnerRepoMock,
getOwnerRepoForRemote: getOwnerRepoForRemoteMock,
@@ -227,6 +238,45 @@ describe('listWorkItems', () => {
])
})
it('routes local WSL work-item listing through repo resolution and gh execution options', async () => {
const localGitOptions = { wslDistro: 'Ubuntu' }
resolveIssueSourceMock.mockResolvedValue({
source: { owner: 'acme', repo: 'widgets' },
fellBack: false
})
getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' })
getOwnerRepoForRemoteMock.mockResolvedValue(null)
ghExecFileAsyncMock.mockResolvedValue({ stdout: '[]' })
await listWorkItems(
'/repo-root',
5,
undefined,
undefined,
undefined,
null,
false,
localGitOptions
)
expect(resolveIssueSourceMock).toHaveBeenCalledWith(
'/repo-root',
undefined,
null,
localGitOptions
)
expect(getOwnerRepoMock).toHaveBeenCalledWith('/repo-root', null, localGitOptions)
expect(getOwnerRepoForRemoteMock).toHaveBeenCalledWith(
'/repo-root',
'upstream',
null,
localGitOptions
)
expect(ghExecFileAsyncMock.mock.calls.every((call) => call[1]?.wslDistro === 'Ubuntu')).toBe(
true
)
})
it('hydrates PR list rows with repository merge metadata', async () => {
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
+76 -3
View File
@@ -35,11 +35,17 @@ const {
rateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })),
noteRateLimitSpendMock: vi.fn(),
ghRepoExecOptionsMock: vi.fn((context) =>
context.connectionId ? {} : { cwd: context.repoPath }
context.connectionId
? {}
: {
cwd: context.repoPath,
...(context.wslDistro ? { wslDistro: context.wslDistro } : {})
}
),
githubRepoContextMock: vi.fn((repoPath, connectionId) => ({
githubRepoContextMock: vi.fn((repoPath, connectionId, localGitOptions) => ({
repoPath,
connectionId: connectionId ?? null
connectionId: connectionId ?? null,
...localGitOptions
})),
getSshGitProviderMock: vi.fn(),
acquireMock: vi.fn(),
@@ -1218,6 +1224,73 @@ describe('getPRForBranch', () => {
})
})
it('routes local WSL branch status and conflict summary git probes through the selected distro', async () => {
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
ghExecFileAsyncMock.mockResolvedValueOnce({
stdout: JSON.stringify([
{
number: 42,
title: 'Fix PR discovery',
state: 'open',
html_url: 'https://github.com/acme/widgets/pull/42',
updated_at: '2026-06-16T00:00:00Z',
draft: false,
mergeable_state: 'dirty',
base: { ref: 'main', sha: 'base-oid' },
head: { ref: 'feature/test', sha: 'head-oid' }
}
])
})
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: '' })
.mockResolvedValueOnce({ stdout: 'latest-base-oid\n' })
.mockResolvedValueOnce({ stdout: 'merge-base-oid\n' })
.mockResolvedValueOnce({ stdout: '2\n' })
.mockResolvedValueOnce({ stdout: 'result-tree-oid\u0000src/conflict.ts\u0000' })
const pr = await getPRForBranch('/repo-root', 'feature/test', null, null, null, {
localGitExecOptions: { wslDistro: 'Ubuntu' }
})
expect(pr?.conflictSummary?.files).toEqual(['src/conflict.ts'])
expect(resolvePRRepositoryCandidatesMock).toHaveBeenCalledWith('/repo-root', null, {
wslDistro: 'Ubuntu'
})
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
expect.any(Array),
expect.objectContaining({
cwd: '/repo-root',
wslDistro: 'Ubuntu'
})
)
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(
1,
['fetch', '--quiet', 'origin', 'main'],
{
cwd: '/repo-root',
timeout: 10_000,
wslDistro: 'Ubuntu'
}
)
expect(gitExecFileAsyncMock).toHaveBeenLastCalledWith(
[
'merge-tree',
'--write-tree',
'--name-only',
'-z',
'--no-messages',
'--merge-base',
'merge-base-oid',
'head-oid',
'latest-base-oid'
],
{
cwd: '/repo-root',
wslDistro: 'Ubuntu'
}
)
})
it('treats GitHub DIRTY merge state as conflicting when mergeable is still unknown', async () => {
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
ghExecFileAsyncMock
+240 -113
View File
@@ -57,9 +57,15 @@ import {
ghRepoExecOptions,
githubRepoContext,
getRemoteUrlForRepo,
type LocalGitExecOptions,
type OwnerRepo
} from './gh-utils'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
import {
hasHostedReviewLocalGitOptions,
getHostedReviewLocalGitOptions,
type HostedReviewExecutionOptions
} from '../source-control/hosted-review-git-options'
export { _resetOwnerRepoCache } from './gh-utils'
export {
getIssue,
@@ -87,6 +93,7 @@ import {
} from './rate-limit'
type GhExecOptions = ReturnType<typeof ghRepoExecOptions>
type HostedReviewLocalGitOptions = ReturnType<typeof getHostedReviewLocalGitOptions>
const ORCA_REPO = 'stablyai/orca'
const PR_CHECK_LOG_TAIL_LINES = 200
@@ -97,6 +104,12 @@ const PR_CHECK_LOG_TAIL_JOB_LIMIT = 5
const PR_CHECK_LOG_TAIL_CACHE_MAX_ENTRIES = 128
const prCheckLogTailCache = new Map<string, string | null>()
function hostedReviewLocalGitOptionArgs(
options: HostedReviewExecutionOptions = {}
): [] | [HostedReviewLocalGitOptions] {
return hasHostedReviewLocalGitOptions(options) ? [getHostedReviewLocalGitOptions(options)] : []
}
function setPrCheckLogTailCache(cacheKey: string, logTail: string | null): void {
prCheckLogTailCache.set(cacheKey, logTail)
while (prCheckLogTailCache.size > PR_CHECK_LOG_TAIL_CACHE_MAX_ENTRIES) {
@@ -273,11 +286,16 @@ export type PullRequestPushTarget = {
export async function getPullRequestPushTarget(
repoPath: string,
prNumber: number,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<PullRequestPushTarget | null> {
const context = githubRepoContext(repoPath, connectionId)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const { candidates } = await resolvePRRepositoryCandidates(repoPath, connectionId)
const { candidates } = await resolvePRRepositoryCandidates(
repoPath,
connectionId,
localGitOptions
)
if (candidates.length === 0) {
return null
}
@@ -308,7 +326,7 @@ export async function getPullRequestPushTarget(
if (!prStdout) {
return null
}
const origin = await getOwnerRepoForRemote(repoPath, 'origin', connectionId)
const origin = await getOwnerRepoForRemote(repoPath, 'origin', connectionId, localGitOptions)
const pr = JSON.parse(prStdout) as {
maintainer_can_modify?: boolean
head?: {
@@ -346,9 +364,7 @@ export async function getPullRequestPushTarget(
let originUrl: string | null = null
try {
const rawOriginUrl = connectionId
? await getRemoteUrlForRepo(context, 'origin')
: (await gitExecFileAsync(['remote', 'get-url', 'origin'], { cwd: repoPath })).stdout
const rawOriginUrl = await getRemoteUrlForRepo(context, 'origin')
originUrl = rawOriginUrl?.trim() || null
} catch {
originUrl = null
@@ -788,9 +804,10 @@ async function fetchIssueWorkItem(
repoPath: string,
ownerRepo: OwnerRepo | null,
number: number,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<MainWorkItem | null> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
if (ownerRepo) {
const { stdout } = await ghExecFileAsync(
['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${number}`],
@@ -814,9 +831,10 @@ async function fetchPullRequestWorkItem(
repoPath: string,
ownerRepo: OwnerRepo | null,
number: number,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<MainWorkItem> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
if (ownerRepo) {
try {
const { stdout } = await ghExecFileAsync(
@@ -960,11 +978,12 @@ type ResolvedPrWorkItemSource = {
async function resolvePrWorkItemSource(
repoPath: string,
preference: IssueSourcePreference | undefined,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<ResolvedPrWorkItemSource> {
const [originCandidate, upstreamCandidate] = await Promise.all([
getOwnerRepo(repoPath, connectionId),
getOwnerRepoForRemote(repoPath, 'upstream', connectionId)
getOwnerRepo(repoPath, connectionId, localGitOptions),
getOwnerRepoForRemote(repoPath, 'upstream', connectionId, localGitOptions)
])
const source =
preference === 'upstream' ? (upstreamCandidate ?? originCandidate) : originCandidate
@@ -977,9 +996,10 @@ async function listRecentWorkItems(
prOwnerRepo: OwnerRepo | null,
limit: number,
connectionId?: string | null,
noCache?: boolean
noCache?: boolean,
localGitOptions: LocalGitExecOptions = {}
): Promise<PartialWorkItemsResult> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const requiresExplicitRepo = Boolean(connectionId)
const restCacheArgs = noCache ? [] : ['--cache', '120s']
assertSshRepoHasResolvedGitHubSource({ connectionId, issueOwnerRepo, prOwnerRepo })
@@ -1142,9 +1162,10 @@ async function listQueriedWorkItems(
query: ParsedTaskQuery,
limit: number,
before?: string,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<PartialWorkItemsResult> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const requiresExplicitRepo = Boolean(connectionId)
assertSshRepoHasResolvedGitHubSource({ connectionId, issueOwnerRepo, prOwnerRepo })
const hasPrOnlyFilter =
@@ -1227,11 +1248,12 @@ export async function listWorkItems(
before?: string,
preference?: IssueSourcePreference,
connectionId?: string | null,
noCache?: boolean
noCache?: boolean,
localGitOptions: LocalGitExecOptions = {}
): Promise<ListWorkItemsResult<MainWorkItem>> {
const [issueResolved, prResolved] = await Promise.all([
resolveIssueSource(repoPath, preference, connectionId),
resolvePrWorkItemSource(repoPath, preference, connectionId)
resolveIssueSource(repoPath, preference, connectionId, localGitOptions),
resolvePrWorkItemSource(repoPath, preference, connectionId, localGitOptions)
])
const issueOwnerRepo = issueResolved.source
const prOwnerRepo = prResolved.source
@@ -1249,7 +1271,8 @@ export async function listWorkItems(
prOwnerRepo,
limit,
connectionId,
noCache
noCache,
localGitOptions
)
: await listQueriedWorkItems(
repoPath,
@@ -1258,7 +1281,8 @@ export async function listWorkItems(
parseTaskQuery(trimmedQuery),
limit,
before,
connectionId
connectionId,
localGitOptions
)
const errors = partial.issuesError ? { issues: partial.issuesError } : undefined
@@ -1332,10 +1356,11 @@ async function countWorkItemsForQuery(
repoPath: string,
ownerRepo: OwnerRepo,
query: ParsedTaskQuery,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<number> {
const searchQ = buildSearchQueryString(ownerRepo, query)
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const { stdout } = await ghExecFileAsync(
[
'api',
@@ -1381,11 +1406,12 @@ export async function countWorkItems(
repoPath: string,
query?: string,
preference?: IssueSourcePreference,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<number> {
const [issueResolved, prResolved] = await Promise.all([
resolveIssueSource(repoPath, preference, connectionId),
resolvePrWorkItemSource(repoPath, preference, connectionId)
resolveIssueSource(repoPath, preference, connectionId, localGitOptions),
resolvePrWorkItemSource(repoPath, preference, connectionId, localGitOptions)
])
const issueOwnerRepo = issueResolved.source
const prOwnerRepo = prResolved.source
@@ -1401,7 +1427,13 @@ export async function countWorkItems(
await acquire()
try {
if (sameOwnerRepo(issueOwnerRepo, prOwnerRepo)) {
return await countWorkItemsForQuery(repoPath, ownerRepo, effectiveQuery, connectionId)
return await countWorkItemsForQuery(
repoPath,
ownerRepo,
effectiveQuery,
connectionId,
localGitOptions
)
}
const counts: Promise<number>[] = []
@@ -1423,7 +1455,8 @@ export async function countWorkItems(
repoPath,
issueOwnerRepo,
{ ...effectiveQuery, scope: 'issue' },
connectionId
connectionId,
localGitOptions
)
)
}
@@ -1433,7 +1466,8 @@ export async function countWorkItems(
repoPath,
prOwnerRepo,
{ ...effectiveQuery, scope: 'pr' },
connectionId
connectionId,
localGitOptions
)
)
}
@@ -1460,9 +1494,10 @@ export async function countWorkItems(
export async function getRepoSlug(
repoPath: string,
connectionId?: string | null
connectionId?: string | null,
options: HostedReviewExecutionOptions = {}
): Promise<{ owner: string; repo: string } | null> {
return getOwnerRepo(repoPath, connectionId)
return getOwnerRepo(repoPath, connectionId, ...hostedReviewLocalGitOptionArgs(options))
}
/**
@@ -1475,13 +1510,21 @@ export async function getRepoSlug(
*/
export async function getRepoUpstream(
repoPath: string,
connectionId?: string | null
connectionId?: string | null,
options: HostedReviewExecutionOptions = {}
): Promise<OwnerRepo | null> {
const origin = await getOwnerRepo(repoPath, connectionId)
const localGitArgs = hostedReviewLocalGitOptionArgs(options)
const localGitOptions = localGitArgs[0] ?? {}
const origin = await getOwnerRepo(repoPath, connectionId, ...localGitArgs)
if (!origin) {
return null
}
const upstreamRemote = await getOwnerRepoForRemote(repoPath, 'upstream', connectionId)
const upstreamRemote = await getOwnerRepoForRemote(
repoPath,
'upstream',
connectionId,
...localGitArgs
)
if (upstreamRemote && !sameOwnerRepo(upstreamRemote, origin)) {
return upstreamRemote
}
@@ -1491,7 +1534,10 @@ export async function getRepoUpstream(
['repo', 'view', `${origin.owner}/${origin.repo}`, '--json', 'isFork,parent'],
// Why: best-effort fork lookup runs at add-time; cap latency so a stalled
// gh process can't hold up repo creation.
{ ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId)), timeout: 10_000 }
{
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
timeout: 10_000
}
)
const data = JSON.parse(stdout) as {
isFork?: boolean
@@ -1585,6 +1631,7 @@ async function findOpenPRByHeadBase(args: {
head: string
base: string
connectionId?: string | null
options?: HostedReviewExecutionOptions
}): Promise<{ number: number; url: string } | null> {
const context = githubRepoContext(args.repoPath, args.connectionId)
const { stdout } = await ghExecFileAsync(
@@ -1604,7 +1651,10 @@ async function findOpenPRByHeadBase(args: {
'--json',
'number,url'
],
ghRepoExecOptions(context)
{
...ghRepoExecOptions(context),
...(args.connectionId ? {} : getHostedReviewLocalGitOptions(args.options))
}
)
const list = JSON.parse(stdout) as { number?: number; url?: string }[]
if (list.length !== 1 || !list[0]?.number || !list[0]?.url) {
@@ -1651,7 +1701,8 @@ async function readPullRequestTemplate(
export async function createGitHubPullRequest(
repoPath: string,
input: CreateHostedReviewInput,
connectionId?: string | null
connectionId?: string | null,
options: HostedReviewExecutionOptions = {}
): Promise<CreateHostedReviewResult> {
if (input.provider !== 'github') {
return {
@@ -1661,7 +1712,11 @@ export async function createGitHubPullRequest(
}
}
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ownerRepo = await getOwnerRepo(
repoPath,
connectionId,
...hostedReviewLocalGitOptionArgs(options)
)
if (!ownerRepo) {
return {
ok: false,
@@ -1719,6 +1774,7 @@ export async function createGitHubPullRequest(
const context = githubRepoContext(repoPath, connectionId)
const { stdout } = await ghExecFileAsync(createArgs, {
...ghRepoExecOptions(context),
...(connectionId ? {} : getHostedReviewLocalGitOptions(options)),
timeout: 60_000,
idempotent: false
})
@@ -1727,9 +1783,14 @@ export async function createGitHubPullRequest(
return { ok: true, ...created }
}
const found = head
? await findOpenPRByHeadBase({ repoPath, ownerRepo, head, base, connectionId }).catch(
() => null
)
? await findOpenPRByHeadBase({
repoPath,
ownerRepo,
head,
base,
connectionId,
options
}).catch(() => null)
: null
if (found) {
return { ok: true, ...found }
@@ -1751,7 +1812,8 @@ export async function createGitHubPullRequest(
ownerRepo,
head,
base,
connectionId
connectionId,
options
}).catch(() => null)
if (existing) {
return {
@@ -1774,33 +1836,37 @@ export async function getWorkItem(
repoPath: string,
number: number,
type?: 'issue' | 'pr',
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<MainWorkItem | null> {
await acquire()
try {
if (type === 'issue') {
return await fetchIssueWorkItem(
repoPath,
await getIssueOwnerRepo(repoPath, connectionId),
await getIssueOwnerRepo(repoPath, connectionId, localGitOptions),
number,
connectionId
connectionId,
localGitOptions
)
}
if (type === 'pr') {
return await fetchPullRequestWorkItem(
repoPath,
await getOwnerRepo(repoPath, connectionId),
await getOwnerRepo(repoPath, connectionId, localGitOptions),
number,
connectionId
connectionId,
localGitOptions
)
}
try {
const issue = await fetchIssueWorkItem(
repoPath,
await getIssueOwnerRepo(repoPath, connectionId),
await getIssueOwnerRepo(repoPath, connectionId, localGitOptions),
number,
connectionId
connectionId,
localGitOptions
)
if (issue) {
return issue
@@ -1819,9 +1885,10 @@ export async function getWorkItem(
}
return await fetchPullRequestWorkItem(
repoPath,
await getOwnerRepo(repoPath, connectionId),
await getOwnerRepo(repoPath, connectionId, localGitOptions),
number,
connectionId
connectionId,
localGitOptions
)
} catch {
return null
@@ -1835,14 +1902,21 @@ export async function getWorkItemByOwnerRepo(
ownerRepo: OwnerRepo,
number: number,
type: 'issue' | 'pr',
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<MainWorkItem | null> {
await acquire()
try {
if (type === 'issue') {
return await fetchIssueWorkItem(repoPath, ownerRepo, number, connectionId)
return await fetchIssueWorkItem(repoPath, ownerRepo, number, connectionId, localGitOptions)
}
return await fetchPullRequestWorkItem(repoPath, ownerRepo, number, connectionId)
return await fetchPullRequestWorkItem(
repoPath,
ownerRepo,
number,
connectionId,
localGitOptions
)
} catch {
return null
} finally {
@@ -2154,14 +2228,18 @@ function parseTrackedUpstreamBranch(
async function getTrackedUpstreamBranch(
repoPath: string,
branchName: string,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: { wslDistro?: string } = {}
): Promise<TrackedUpstreamBranch | null> {
const args = ['rev-parse', '--abbrev-ref', '--symbolic-full-name', `${branchName}@{upstream}`]
try {
const provider = connectionId ? getSshGitProvider(connectionId) : null
const result = provider
? await provider.exec(args, repoPath)
: await gitExecFileAsync(args, { cwd: repoPath })
: await gitExecFileAsync(args, {
cwd: repoPath,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
})
return parseTrackedUpstreamBranch(result.stdout, branchName)
} catch {
return null
@@ -2353,14 +2431,16 @@ export async function getPRForBranch(
branch: string,
linkedPRNumber?: number | null,
connectionId?: string | null,
fallbackPRNumber?: number | null
fallbackPRNumber?: number | null,
options: HostedReviewExecutionOptions = {}
): Promise<PRInfo | null> {
const outcome = await getPRForBranchOutcome(
repoPath,
branch,
linkedPRNumber,
connectionId,
fallbackPRNumber
fallbackPRNumber,
options
)
return outcome.kind === 'found' ? outcome.pr : null
}
@@ -2370,7 +2450,8 @@ export async function getPRForBranchOutcome(
branch: string,
linkedPRNumber?: number | null,
connectionId?: string | null,
fallbackPRNumber?: number | null
fallbackPRNumber?: number | null,
options: HostedReviewExecutionOptions = {}
): Promise<PRRefreshOutcome> {
// Strip refs/heads/ prefix if present
const branchName = branch.replace(/^refs\/heads\//, '')
@@ -2379,12 +2460,18 @@ export async function getPRForBranchOutcome(
if (!branchName && typeof linkedPRNumber !== 'number' && typeof fallbackPRNumber !== 'number') {
return { kind: 'no-pr', fetchedAt: Date.now() }
}
const context = githubRepoContext(repoPath, connectionId)
const localGitArgs = hostedReviewLocalGitOptionArgs(options)
const localGitOptions = localGitArgs[0] ?? {}
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
await acquire()
try {
const { candidates, headRepo } = await resolvePRRepositoryCandidates(repoPath, connectionId)
const { candidates, headRepo } = await resolvePRRepositoryCandidates(
repoPath,
connectionId,
...localGitArgs
)
let data: PullRequestLookupData | null = null
let dataRepo: OwnerRepo | null = null
let dataHeadRepo: OwnerRepo | null = headRepo
@@ -2411,11 +2498,20 @@ export async function getPRForBranchOutcome(
if (!data) {
// Why: worktrees can have a short local branch tracking a differently
// named remote PR head; after the local miss, try that configured head.
const upstreamBranch = await getTrackedUpstreamBranch(repoPath, branchName, connectionId)
const upstreamBranch = await getTrackedUpstreamBranch(
repoPath,
branchName,
connectionId,
localGitOptions
)
if (upstreamBranch) {
const upstreamHeadRepo =
(await getOwnerRepoForRemote(repoPath, upstreamBranch.remoteName, connectionId)) ??
headRepo
(await getOwnerRepoForRemote(
repoPath,
upstreamBranch.remoteName,
connectionId,
...localGitArgs
)) ?? headRepo
const upstreamLookup = await lookupPRByBranchName({
candidates,
headRepo: upstreamHeadRepo,
@@ -2458,7 +2554,13 @@ export async function getPRForBranchOutcome(
data.baseRefName &&
data.baseRefOid &&
data.headRefOid
? await getPRConflictSummary(repoPath, data.baseRefName, data.baseRefOid, data.headRefOid)
? await getPRConflictSummary(
repoPath,
data.baseRefName,
data.baseRefOid,
data.headRefOid,
localGitOptions
)
: undefined
return {
@@ -2507,10 +2609,11 @@ export async function getPRChecks(
headSha?: string,
prRepo?: OwnerRepo | null,
options?: { noCache?: boolean },
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<PRCheckDetail[]> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId, localGitOptions))
const fallbackToPRChecks = async (): Promise<PRCheckDetail[]> => {
// Why: the REST check-runs path spends core only. Guard GraphQL only when
// we actually fall back to `gh pr checks`, so a low GraphQL bucket does not
@@ -2745,10 +2848,11 @@ export async function getPRCheckDetails(
url?: string | null
prRepo?: OwnerRepo | null
},
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<PRCheckRunDetails | null> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = args.prRepo ?? (await getOwnerRepo(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = args.prRepo ?? (await getOwnerRepo(repoPath, connectionId, localGitOptions))
if (!ownerRepo) {
return null
}
@@ -2837,10 +2941,11 @@ export async function rerunPRChecks(
repoPath: string,
prNumber: number,
options: { headSha?: string; failedOnly?: boolean } = {},
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubRerunPRChecksResult> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = await getOwnerRepo(repoPath, connectionId, localGitOptions)
if (!ownerRepo) {
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
}
@@ -2851,7 +2956,8 @@ export async function rerunPRChecks(
options.headSha,
ownerRepo,
{ noCache: true },
connectionId
connectionId,
localGitOptions
)
const candidates = options.failedOnly
? checks.filter((check) =>
@@ -2975,10 +3081,11 @@ export async function getPRComments(
repoPath: string,
prNumber: number,
options?: { noCache?: boolean; prRepo?: OwnerRepo | null },
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<PRComment[]> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = options?.prRepo ?? (await getOwnerRepo(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = options?.prRepo ?? (await getOwnerRepo(repoPath, connectionId, localGitOptions))
if (ownerRepo) {
await assertRateLimitBudget('core')
}
@@ -3215,11 +3322,14 @@ export async function getPRComments(
export async function setPRFileViewed(args: {
repoPath: string
connectionId?: string | null
localGitOptions?: LocalGitExecOptions
pullRequestId: string
path: string
viewed: boolean
}): Promise<boolean> {
const ghOptions = ghRepoExecOptions(githubRepoContext(args.repoPath, args.connectionId))
const ghOptions = ghRepoExecOptions(
githubRepoContext(args.repoPath, args.connectionId, args.localGitOptions)
)
const mutation = args.viewed ? 'markFileAsViewed' : 'unmarkFileAsViewed'
const query = `mutation($pullRequestId: ID!, $path: String!) {
${mutation}(input: { pullRequestId: $pullRequestId, path: $path }) {
@@ -3257,11 +3367,12 @@ export async function resolveReviewThread(
repoPath: string,
threadId: string,
resolve: boolean,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<boolean> {
const mutation = resolve ? 'resolveReviewThread' : 'unresolveReviewThread'
const query = `mutation($threadId: ID!) { ${mutation}(input: { threadId: $threadId }) { thread { isResolved } } }`
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const guard = rateLimitGuard('graphql')
if (guard.blocked) {
console.warn(
@@ -3325,10 +3436,11 @@ export async function addPRReviewCommentReply(
path?: string,
line?: number,
connectionId?: string | null,
prRepo?: OwnerRepo | null
prRepo?: OwnerRepo | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubCommentResult> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId, localGitOptions))
if (!ownerRepo) {
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
}
@@ -3362,10 +3474,15 @@ export async function addPRReviewCommentReply(
}
export async function addPRReviewComment(
args: GitHubPRReviewCommentInput & { connectionId?: string | null }
args: GitHubPRReviewCommentInput & {
connectionId?: string | null
localGitOptions?: LocalGitExecOptions
}
): Promise<GitHubCommentResult> {
const ghOptions = ghRepoExecOptions(githubRepoContext(args.repoPath, args.connectionId))
const ownerRepo = await getOwnerRepo(args.repoPath, args.connectionId)
const ghOptions = ghRepoExecOptions(
githubRepoContext(args.repoPath, args.connectionId, args.localGitOptions)
)
const ownerRepo = await getOwnerRepo(args.repoPath, args.connectionId, args.localGitOptions)
if (!ownerRepo) {
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
}
@@ -3423,10 +3540,11 @@ export async function mergePR(
prNumber: number,
method: 'merge' | 'squash' | 'rebase' = 'squash',
connectionId?: string | null,
prRepo?: OwnerRepo | null
prRepo?: OwnerRepo | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true } | { ok: false; error: string }> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId, localGitOptions))
await acquire()
try {
const mergeBlocker = await getPRMergeBlocker(
@@ -3434,7 +3552,8 @@ export async function mergePR(
prNumber,
ownerRepo,
ghOptions,
connectionId
connectionId,
localGitOptions
)
if (mergeBlocker) {
return { ok: false, error: mergeBlocker }
@@ -3467,10 +3586,11 @@ export async function setPRAutoMerge(
enabled: boolean,
method: GitHubPRMergeMethod = 'squash',
connectionId?: string | null,
prRepo?: OwnerRepo | null
prRepo?: OwnerRepo | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true } | { ok: false; error: string }> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId, localGitOptions))
await acquire()
try {
const args = ['pr', 'merge', String(prNumber), enabled ? '--auto' : '--disable-auto']
@@ -3499,7 +3619,8 @@ async function getPRMergeBlocker(
prNumber: number,
ownerRepo: OwnerRepo | null,
ghOptions: GhExecOptions,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<string | null> {
if (!ownerRepo) {
return null
@@ -3535,7 +3656,8 @@ async function getPRMergeBlocker(
repoPath,
pr.baseRefName,
pr.baseRefOid,
pr.headRefOid
pr.headRefOid,
localGitOptions
)
return formatMergeConflictBlocker(pr.baseRefName, summary)
} catch {
@@ -3563,11 +3685,12 @@ export async function updatePRState(
repoPath: string,
prNumber: number,
updates: GitHubPullRequestStateUpdate,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true } | { ok: false; error: string }> {
const context = githubRepoContext(repoPath, connectionId)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ownerRepo = await getOwnerRepo(repoPath, connectionId, localGitOptions)
if (!ownerRepo) {
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
}
@@ -3597,14 +3720,15 @@ export async function requestPRReviewers(
repoPath: string,
prNumber: number,
reviewers: string[],
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true } | { ok: false; error: string }> {
const logins = reviewers.map((reviewer) => reviewer.trim()).filter(Boolean)
if (logins.length === 0) {
return { ok: false, error: 'Enter at least one reviewer' }
}
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = await getOwnerRepo(repoPath, connectionId, localGitOptions)
await acquire()
try {
const args = ['pr', 'edit', String(prNumber), '--add-reviewer', logins.join(',')]
@@ -3629,14 +3753,15 @@ export async function removePRReviewers(
repoPath: string,
prNumber: number,
reviewers: string[],
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true } | { ok: false; error: string }> {
const logins = reviewers.map((reviewer) => reviewer.trim()).filter(Boolean)
if (logins.length === 0) {
return { ok: false, error: 'Enter at least one reviewer' }
}
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = await getOwnerRepo(repoPath, connectionId, localGitOptions)
await acquire()
try {
const args = ['pr', 'edit', String(prNumber), '--remove-reviewer', logins.join(',')]
@@ -3665,10 +3790,11 @@ export async function updatePRTitle(
prNumber: number,
title: string,
connectionId?: string | null,
prRepo?: OwnerRepo | null
prRepo?: OwnerRepo | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<boolean> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId, localGitOptions))
await acquire()
try {
const args = ['pr', 'edit', String(prNumber), '--title', title]
@@ -3692,10 +3818,11 @@ export async function updatePRDetails(
prNumber: number,
updates: { title?: string; body?: string },
connectionId?: string | null,
prRepo?: OwnerRepo | null
prRepo?: OwnerRepo | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true } | { ok: false; error: string }> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId))
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId, localGitOptions))
if (!ownerRepo) {
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
}
+42 -15
View File
@@ -1,11 +1,16 @@
import type { PRConflictSummary } from '../../shared/types'
import { gitExecFileAsync } from '../git/runner'
type LocalGitExecOptions = {
wslDistro?: string
}
export async function getPRConflictSummary(
repoPath: string,
baseRefName: string,
baseRefOid: string,
headRefOid: string
headRefOid: string,
localGitOptions: LocalGitExecOptions = {}
): Promise<PRConflictSummary | undefined> {
try {
// Why: the renderer only needs a read-only merge-conflict snapshot. We
@@ -16,11 +21,16 @@ export async function getPRConflictSummary(
// freshly-fetched remote-tracking ref so Orca matches GitHub's portal,
// which compares against the latest base branch tip rather than the PR's
// older pinned baseRefOid snapshot.
const latestBaseOid = await resolveLatestBaseOid(repoPath, baseRefName, baseRefOid)
const mergeBase = await resolveMergeBase(repoPath, headRefOid, latestBaseOid)
const latestBaseOid = await resolveLatestBaseOid(
repoPath,
baseRefName,
baseRefOid,
localGitOptions
)
const mergeBase = await resolveMergeBase(repoPath, headRefOid, latestBaseOid, localGitOptions)
const [commitsBehind, files] = await Promise.all([
countCommits(repoPath, `${headRefOid}..${latestBaseOid}`),
loadConflictingFiles(repoPath, mergeBase, headRefOid, latestBaseOid)
countCommits(repoPath, `${headRefOid}..${latestBaseOid}`, localGitOptions),
loadConflictingFiles(repoPath, mergeBase, headRefOid, latestBaseOid, localGitOptions)
])
return {
@@ -37,7 +47,8 @@ export async function getPRConflictSummary(
async function resolveLatestBaseOid(
repoPath: string,
baseRefName: string,
fallbackBaseOid: string
fallbackBaseOid: string,
localGitOptions: LocalGitExecOptions
): Promise<string> {
const remoteName = 'origin'
@@ -46,7 +57,8 @@ async function resolveLatestBaseOid(
// the conflict-summary derivation indefinitely.
await gitExecFileAsync(['fetch', '--quiet', remoteName, baseRefName], {
cwd: repoPath,
timeout: 10_000
timeout: 10_000,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
})
} catch {
// Why: fetching the base ref keeps the conflict list aligned with GitHub's
@@ -57,7 +69,8 @@ async function resolveLatestBaseOid(
for (const ref of [`refs/remotes/${remoteName}/${baseRefName}`, `${remoteName}/${baseRefName}`]) {
try {
const { stdout } = await gitExecFileAsync(['rev-parse', '--verify', ref], {
cwd: repoPath
cwd: repoPath,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
})
const oid = stdout.trim()
if (oid) {
@@ -74,17 +87,24 @@ async function resolveLatestBaseOid(
async function resolveMergeBase(
repoPath: string,
headOid: string,
baseOid: string
baseOid: string,
localGitOptions: LocalGitExecOptions
): Promise<string> {
const { stdout } = await gitExecFileAsync(['merge-base', headOid, baseOid], {
cwd: repoPath
cwd: repoPath,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
})
return stdout.trim()
}
async function countCommits(repoPath: string, range: string): Promise<number> {
async function countCommits(
repoPath: string,
range: string,
localGitOptions: LocalGitExecOptions
): Promise<number> {
const { stdout } = await gitExecFileAsync(['rev-list', '--count', range], {
cwd: repoPath
cwd: repoPath,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
})
return Number.parseInt(stdout.trim(), 10) || 0
}
@@ -93,7 +113,8 @@ async function loadConflictingFiles(
repoPath: string,
mergeBase: string,
headOid: string,
baseOid: string
baseOid: string,
localGitOptions: LocalGitExecOptions
): Promise<string[]> {
const modernArgs = [
'merge-tree',
@@ -117,7 +138,10 @@ async function loadConflictingFiles(
]
try {
const result = await gitExecFileAsync(modernArgs, { cwd: repoPath })
const result = await gitExecFileAsync(modernArgs, {
cwd: repoPath,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
})
return parseMergeTreeNameOnlyOutput(result.stdout)
} catch (error) {
// Why: `git merge-tree --write-tree` exits with status 1 when it finds
@@ -133,7 +157,10 @@ async function loadConflictingFiles(
}
try {
const result = await gitExecFileAsync(legacyArgs, { cwd: repoPath })
const result = await gitExecFileAsync(legacyArgs, {
cwd: repoPath,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
})
return parseMergeTreeNameOnlyOutput(result.stdout)
} catch (fallbackError) {
const fallbackStdout = getGitErrorOutput(fallbackError, 'stdout')
@@ -0,0 +1,55 @@
import type { ClassifiedError } from '../../shared/types'
// Why: gh CLI surfaces API errors as unstructured stderr. Map known
// patterns to typed errors so callers can show user-friendly messages.
export function classifyGhError(stderr: string): ClassifiedError {
const s = stderr.toLowerCase()
if (s.includes('http 403') || s.includes('resource not accessible')) {
return {
type: 'permission_denied',
message: "You don't have permission to edit this issue. Check your GitHub token scopes."
}
}
if (s.includes('http 404') || s.includes('could not resolve to a repository')) {
return { type: 'not_found', message: 'Issue not found — it may have been deleted.' }
}
if (s.includes('has disabled issues')) {
return { type: 'issues_disabled', message: 'Issues are disabled on this repository.' }
}
if (s.includes('http 422') || s.includes('validation failed')) {
return { type: 'validation_error', message: `Invalid update — ${stderr.trim()}` }
}
if (s.includes('rate limit')) {
return {
type: 'rate_limited',
message: 'GitHub rate limit hit. Try again in a few minutes.'
}
}
if (
s.includes('timeout') ||
s.includes('no such host') ||
s.includes('network') ||
s.includes('could not resolve host')
) {
return { type: 'network_error', message: 'Network error — check your connection.' }
}
return { type: 'unknown', message: `Failed to update issue: ${stderr.trim()}` }
}
// Why: classifyGhError's copy is phrased for edit/update operations, but
// listIssues is a read op and renderer banners interpolate the message.
export function classifyListIssuesError(stderr: string): ClassifiedError {
const c = classifyGhError(stderr)
const trimmed = stderr.trim()
const readMessages: Record<ClassifiedError['type'], string> = {
permission_denied:
"You don't have permission to read issues for this repository. Check your GitHub token scopes.",
not_found: 'Repository not found.',
issues_disabled: 'Issues are disabled on this repository.',
validation_error: `Invalid request — ${trimmed}`,
rate_limited: 'GitHub rate limit hit. Try again in a few minutes.',
network_error: 'Network error — check your connection.',
unknown: `Failed to load issues: ${trimmed}`
}
return { type: c.type, message: readMessages[c.type] }
}
+25
View File
@@ -191,6 +191,31 @@ describe('github owner/repo resolution', () => {
await expect(getOwnerRepo('/repo', 'ssh-1')).resolves.toEqual({ owner: 'remote', repo: 'orca' })
})
it('keeps local host and local WSL owner/repo cache entries separate for the same path', async () => {
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'git@github.com:host/orca.git\n' })
.mockResolvedValueOnce({ stdout: 'git@github.com:wsl/orca.git\n' })
await expect(getOwnerRepo('/repo')).resolves.toEqual({ owner: 'host', repo: 'orca' })
await expect(getOwnerRepo('/repo', null, { wslDistro: 'Ubuntu' })).resolves.toEqual({
owner: 'wsl',
repo: 'orca'
})
await expect(getOwnerRepo('/repo', null, { wslDistro: 'Ubuntu' })).resolves.toEqual({
owner: 'wsl',
repo: 'orca'
})
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['remote', 'get-url', 'origin'], {
cwd: '/repo'
})
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['remote', 'get-url', 'origin'], {
cwd: '/repo',
wslDistro: 'Ubuntu'
})
})
it('prunes expired distinct owner/repo cache entries on later lookups', async () => {
const nowSpy = vi.spyOn(Date, 'now')
try {
+28 -365
View File
@@ -1,393 +1,56 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { gitExecFileAsync, ghExecFileAsync, extractExecError } from '../git/runner'
import type { ClassifiedError, GitHubOwnerRepo, IssueSourcePreference } from '../../shared/types'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
// Why: legacy generic execFile wrapper — only used by callers that don't need
// WSL-aware routing (e.g. non-repo-scoped gh commands). Repo-scoped callers
// should use ghExecFileAsync or gitExecFileAsync from the runner instead.
// Why: legacy generic execFile wrapper - only used by callers that don't need
// WSL-aware routing. Repo-scoped callers should use the runner exports below.
export const execFileAsync = promisify(execFile)
export { ghExecFileAsync, gitExecFileAsync, extractExecError }
export { classifyGhError, classifyListIssuesError } from './gh-error-classification'
export {
_getOwnerRepoCacheSize,
_resetOwnerRepoCache,
getIssueOwnerRepo,
getOwnerRepo,
getOwnerRepoForRemote,
getRemoteUrlForRepo,
ghRepoExecOptions,
githubRepoContext,
parseGitHubOwnerRepo,
parseGitHubRemoteIdentity,
resolveIssueSource,
resolvePRRepositoryCandidates
} from './github-repository-identity'
export type {
GitHubRemoteIdentity,
GitHubRepoContext,
LocalGitExecOptions,
OwnerRepo,
PRRepositoryCandidates,
ResolvedIssueSource
} from './github-repository-identity'
// Concurrency limiter - max 4 parallel gh processes
const MAX_CONCURRENT = 4
let running = 0
const queue: (() => void)[] = []
export function acquire(): Promise<void> {
if (running < MAX_CONCURRENT) {
running++
running += 1
return Promise.resolve()
}
return new Promise((resolve) =>
queue.push(() => {
running++
running += 1
resolve()
})
)
}
export function release(): void {
running--
running -= 1
const next = queue.shift()
if (next) {
next()
}
}
// ── Error classification ─────────────────────────────────────────────
// Why: gh CLI surfaces API errors as unstructured stderr. This helper maps
// known patterns to typed errors so callers can show user-friendly messages.
export function classifyGhError(stderr: string): ClassifiedError {
const s = stderr.toLowerCase()
if (s.includes('http 403') || s.includes('resource not accessible')) {
return {
type: 'permission_denied',
message: "You don't have permission to edit this issue. Check your GitHub token scopes."
}
}
// Why: the full gh message is "Could not resolve to a Repository with the
// name ...". Matching the substring 'could not resolve' alone would also
// capture DNS failures like "could not resolve host: api.github.com" and
// misclassify them as not_found. Anchor on the 'repository' qualifier so
// DNS errors fall through to the network_error branch below.
if (s.includes('http 404') || s.includes('could not resolve to a repository')) {
return { type: 'not_found', message: 'Issue not found — it may have been deleted.' }
}
// Why: `gh issue list` prints "the '<owner>/<repo>' repository has disabled
// issues" when Issues are turned off in repo settings (common on forks). This
// hits during feature-2 when a user flips the selector to an origin fork —
// without a dedicated branch the raw "Command failed: gh issue list …" line
// leaks verbatim into the banner via the `unknown` fallback.
if (s.includes('has disabled issues')) {
return { type: 'issues_disabled', message: 'Issues are disabled on this repository.' }
}
if (s.includes('http 422') || s.includes('validation failed')) {
return { type: 'validation_error', message: `Invalid update — ${stderr.trim()}` }
}
if (s.includes('rate limit')) {
return {
type: 'rate_limited',
message: 'GitHub rate limit hit. Try again in a few minutes.'
}
}
if (
s.includes('timeout') ||
s.includes('no such host') ||
s.includes('network') ||
s.includes('could not resolve host')
) {
return { type: 'network_error', message: 'Network error — check your connection.' }
}
return { type: 'unknown', message: `Failed to update issue: ${stderr.trim()}` }
}
// Why: classifyGhError's copy is phrased for edit/update operations, but
// `listIssues` is a read op and the renderer interpolates err.message verbatim
// into a read-context banner. Rewrite the message for read contexts while
// keeping the typed classification so callers/telemetry are unaffected.
export function classifyListIssuesError(stderr: string): ClassifiedError {
const c = classifyGhError(stderr)
const trimmed = stderr.trim()
// Why: provide an explicit entry for every `ClassifiedError['type']` value
// (even when the copy matches the generic fallback) so the read-context
// rewrite is complete and any newly added error type surfaces as a
// TypeScript error rather than silently falling through to edit-phrased copy.
const readMessages: Record<ClassifiedError['type'], string> = {
permission_denied:
"You don't have permission to read issues for this repository. Check your GitHub token scopes.",
not_found: 'Repository not found.',
issues_disabled: 'Issues are disabled on this repository.',
validation_error: `Invalid request — ${trimmed}`,
rate_limited: 'GitHub rate limit hit. Try again in a few minutes.',
network_error: 'Network error — check your connection.',
unknown: `Failed to load issues: ${trimmed}`
}
return { type: c.type, message: readMessages[c.type] }
}
// ── Owner/repo resolution for gh api --cache ──────────────────────────
// Why: alias the shared shape so `src/shared/types.ts#GitHubOwnerRepo` remains
// the single source of truth while main-side call sites can keep using the
// short local name `OwnerRepo`.
export type OwnerRepo = GitHubOwnerRepo
export type GitHubRemoteIdentity = GitHubOwnerRepo & { host: string }
export type GitHubRepoContext = {
repoPath: string
connectionId?: string | null
}
export function githubRepoContext(
repoPath: string,
connectionId?: string | null
): GitHubRepoContext {
return { repoPath, connectionId: connectionId ?? null }
}
export function ghRepoExecOptions(context: GitHubRepoContext): {
cwd?: string
encoding?: BufferEncoding
} {
// Why: SSH repo paths are meaningful only on the remote host. All GitHub
// calls in this layer pass explicit --repo/API targets, so local gh should
// not receive a remote-only cwd.
return context.connectionId ? {} : { cwd: context.repoPath }
}
const OWNER_REPO_CACHE_TTL_MS = 30_000
const OWNER_REPO_CACHE_MAX_ENTRIES = 512
type OwnerRepoCacheEntry = {
value: OwnerRepo | null
expiresAt: number
}
const ownerRepoCache = new Map<string, OwnerRepoCacheEntry>()
const ownerRepoInFlight = new Map<string, Promise<OwnerRepo | null>>()
/** @internal — exposed for tests only */
export function _resetOwnerRepoCache(): void {
ownerRepoCache.clear()
ownerRepoInFlight.clear()
}
/** @internal — exposed for tests only */
export function _getOwnerRepoCacheSize(): number {
return ownerRepoCache.size
}
function pruneOwnerRepoCache(now: number): void {
for (const [key, entry] of ownerRepoCache) {
if (entry.expiresAt <= now) {
ownerRepoCache.delete(key)
}
}
while (ownerRepoCache.size > OWNER_REPO_CACHE_MAX_ENTRIES) {
const oldestKey = ownerRepoCache.keys().next().value
if (oldestKey === undefined) {
return
}
ownerRepoCache.delete(oldestKey)
}
}
export function parseGitHubOwnerRepo(remoteUrl: string): OwnerRepo | null {
const identity = parseGitHubRemoteIdentity(remoteUrl)
if (!identity || identity.host.toLowerCase() !== 'github.com') {
return null
}
return { owner: identity.owner, repo: identity.repo }
}
function normalizeGitHubRemoteHost(host: string): string {
const normalizedHost = host.toLowerCase()
// Why: GitHub documents ssh.github.com:443 as SSH-over-HTTPS for github.com repos.
return normalizedHost === 'ssh.github.com' ? 'github.com' : normalizedHost
}
function parseGitHubRemotePath(path: string): Pick<GitHubRemoteIdentity, 'owner' | 'repo'> | null {
const parts = path.replace(/^\/+/, '').replace(/\/+$/, '').split('/')
if (parts.length !== 2) {
return null
}
const [owner, repoWithSuffix] = parts
const repo = repoWithSuffix.replace(/\.git$/i, '')
if (!owner || !repo) {
return null
}
return { owner, repo }
}
export function parseGitHubRemoteIdentity(remoteUrl: string): GitHubRemoteIdentity | null {
const trimmed = remoteUrl.trim()
const sshMatch = trimmed.match(/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/i)
if (sshMatch) {
return { host: normalizeGitHubRemoteHost(sshMatch[1]), owner: sshMatch[2], repo: sshMatch[3] }
}
try {
const url = new URL(trimmed)
if (!['git:', 'git+ssh:', 'http:', 'https:', 'ssh:'].includes(url.protocol.toLowerCase())) {
return null
}
const path = parseGitHubRemotePath(url.pathname)
return path ? { host: normalizeGitHubRemoteHost(url.hostname), ...path } : null
} catch {
return null
}
}
export async function getRemoteUrlForRepo(
context: GitHubRepoContext,
remoteName: string
): Promise<string | null> {
if (context.connectionId) {
const provider = getSshGitProvider(context.connectionId)
if (!provider) {
return null
}
const { stdout } = await provider.exec(['remote', 'get-url', remoteName], context.repoPath)
return stdout
}
const { stdout } = await gitExecFileAsync(['remote', 'get-url', remoteName], {
cwd: context.repoPath
})
return stdout
}
export async function getOwnerRepoForRemote(
repoPath: string,
remoteName: string,
connectionId?: string | null
): Promise<OwnerRepo | null> {
const context = githubRepoContext(repoPath, connectionId)
const cacheKey = `${context.connectionId ?? 'local'}\0${context.repoPath}\0${remoteName}`
const now = Date.now()
pruneOwnerRepoCache(now)
const cached = ownerRepoCache.get(cacheKey)
if (cached && cached.expiresAt > now) {
return cached.value
}
const inFlight = ownerRepoInFlight.get(cacheKey)
if (inFlight) {
return inFlight
}
// Why: startup can resolve issue sources, PR candidates, and repo metadata
// for the same repo concurrently. Coalesce missing-remote probes so a stable
// absent upstream does not spawn identical `git remote get-url` processes.
const probe = resolveOwnerRepoForRemote(context, remoteName, cacheKey)
ownerRepoInFlight.set(cacheKey, probe)
try {
return await probe
} finally {
if (ownerRepoInFlight.get(cacheKey) === probe) {
ownerRepoInFlight.delete(cacheKey)
}
}
}
async function resolveOwnerRepoForRemote(
context: GitHubRepoContext,
remoteName: string,
cacheKey: string
): Promise<OwnerRepo | null> {
const now = Date.now()
try {
const remoteUrl = await getRemoteUrlForRepo(context, remoteName)
const result = remoteUrl ? parseGitHubOwnerRepo(remoteUrl) : null
if (result) {
ownerRepoCache.set(cacheKey, {
value: result,
expiresAt: now + OWNER_REPO_CACHE_TTL_MS
})
pruneOwnerRepoCache(now)
return result
}
} catch {
// ignore — non-GitHub remote or no remote
}
ownerRepoCache.set(cacheKey, { value: null, expiresAt: now + OWNER_REPO_CACHE_TTL_MS })
pruneOwnerRepoCache(now)
return null
}
export async function getOwnerRepo(
repoPath: string,
connectionId?: string | null
): Promise<OwnerRepo | null> {
return getOwnerRepoForRemote(repoPath, 'origin', connectionId)
}
export async function getIssueOwnerRepo(
repoPath: string,
connectionId?: string | null
): Promise<OwnerRepo | null> {
const upstream = await getOwnerRepoForRemote(repoPath, 'upstream', connectionId)
if (upstream) {
return upstream
}
return getOwnerRepoForRemote(repoPath, 'origin', connectionId)
}
export type PRRepositoryCandidates = {
candidates: OwnerRepo[]
headRepo: OwnerRepo | null
}
function ownerRepoKey(ownerRepo: OwnerRepo): string {
return `${ownerRepo.owner.toLowerCase()}/${ownerRepo.repo.toLowerCase()}`
}
export async function resolvePRRepositoryCandidates(
repoPath: string,
connectionId?: string | null
): Promise<PRRepositoryCandidates> {
const upstream = await getOwnerRepoForRemote(repoPath, 'upstream', connectionId)
const origin = await getOwnerRepoForRemote(repoPath, 'origin', connectionId)
const seen = new Set<string>()
const candidates: OwnerRepo[] = []
for (const candidate of [upstream, origin]) {
if (!candidate) {
continue
}
const key = ownerRepoKey(candidate)
if (seen.has(key)) {
continue
}
seen.add(key)
candidates.push(candidate)
}
return { candidates, headRepo: origin }
}
export type ResolvedIssueSource = {
source: OwnerRepo | null
/** True when the user preferred `upstream` but the upstream remote is no
* longer configured and the resolver fell back to origin. Consumers
* surface this as a one-time toast per session/repo. */
fellBack: boolean
}
/**
* Resolve the issue source for a repo honoring the user's per-repo preference.
*
* Do not delete `getIssueOwnerRepo`: it remains the right primitive for
* `'auto'` mode and for preference-agnostic callers like typed work-item
* detail lookups (where the issue-vs-PR disambiguation is orthogonal to
* user choice).
*/
export async function resolveIssueSource(
repoPath: string,
preference: IssueSourcePreference | undefined,
connectionId?: string | null
): Promise<ResolvedIssueSource> {
if (preference === 'upstream') {
const upstream = await getOwnerRepoForRemote(repoPath, 'upstream', connectionId)
if (upstream) {
return { source: upstream, fellBack: false }
}
// Why: explicit upstream is gone — fall back to origin but only flag the
// fallback when it actually produced an origin source. If origin is also
// missing (or non-GitHub), there's nothing to "fall back to" and the
// UI toast "using origin" would be misleading. Do NOT auto-reset the
// preference: the user may be mid-way through a workflow and expect
// their choice to re-engage if `upstream` is re-added.
const origin = await getOwnerRepoForRemote(repoPath, 'origin', connectionId)
return { source: origin, fellBack: origin !== null }
}
if (preference === 'origin') {
return {
source: await getOwnerRepoForRemote(repoPath, 'origin', connectionId),
fellBack: false
}
}
// 'auto' or undefined
return { source: await getIssueOwnerRepo(repoPath, connectionId), fellBack: false }
}
@@ -0,0 +1,294 @@
import { gitExecFileAsync } from '../git/runner'
import type { GitHubOwnerRepo, IssueSourcePreference } from '../../shared/types'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
export type OwnerRepo = GitHubOwnerRepo
export type GitHubRemoteIdentity = GitHubOwnerRepo & { host: string }
export type GitHubRepoContext = {
repoPath: string
connectionId?: string | null
wslDistro?: string
}
export type LocalGitExecOptions = {
wslDistro?: string
}
export function githubRepoContext(
repoPath: string,
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): GitHubRepoContext {
return {
repoPath,
connectionId: connectionId ?? null,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
}
}
export function ghRepoExecOptions(context: GitHubRepoContext): {
cwd?: string
encoding?: BufferEncoding
wslDistro?: string
} {
return context.connectionId
? {}
: {
cwd: context.repoPath,
...(context.wslDistro ? { wslDistro: context.wslDistro } : {})
}
}
const OWNER_REPO_CACHE_TTL_MS = 30_000
const OWNER_REPO_CACHE_MAX_ENTRIES = 512
type OwnerRepoCacheEntry = {
value: OwnerRepo | null
expiresAt: number
}
const ownerRepoCache = new Map<string, OwnerRepoCacheEntry>()
const ownerRepoInFlight = new Map<string, Promise<OwnerRepo | null>>()
/** @internal - exposed for tests only */
export function _resetOwnerRepoCache(): void {
ownerRepoCache.clear()
ownerRepoInFlight.clear()
}
/** @internal - exposed for tests only */
export function _getOwnerRepoCacheSize(): number {
return ownerRepoCache.size
}
function pruneOwnerRepoCache(now: number): void {
for (const [key, entry] of ownerRepoCache) {
if (entry.expiresAt <= now) {
ownerRepoCache.delete(key)
}
}
while (ownerRepoCache.size > OWNER_REPO_CACHE_MAX_ENTRIES) {
const oldestKey = ownerRepoCache.keys().next().value
if (oldestKey === undefined) {
return
}
ownerRepoCache.delete(oldestKey)
}
}
export function parseGitHubOwnerRepo(remoteUrl: string): OwnerRepo | null {
const identity = parseGitHubRemoteIdentity(remoteUrl)
if (!identity || identity.host.toLowerCase() !== 'github.com') {
return null
}
return { owner: identity.owner, repo: identity.repo }
}
function normalizeGitHubRemoteHost(host: string): string {
const normalizedHost = host.toLowerCase()
// Why: GitHub documents ssh.github.com:443 as SSH-over-HTTPS for github.com repos.
return normalizedHost === 'ssh.github.com' ? 'github.com' : normalizedHost
}
function parseGitHubRemotePath(path: string): Pick<GitHubRemoteIdentity, 'owner' | 'repo'> | null {
const parts = path.replace(/^\/+/, '').replace(/\/+$/, '').split('/')
if (parts.length !== 2) {
return null
}
const [owner, repoWithSuffix] = parts
const repo = repoWithSuffix.replace(/\.git$/i, '')
if (!owner || !repo) {
return null
}
return { owner, repo }
}
export function parseGitHubRemoteIdentity(remoteUrl: string): GitHubRemoteIdentity | null {
const trimmed = remoteUrl.trim()
const sshMatch = trimmed.match(/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/i)
if (sshMatch) {
return { host: normalizeGitHubRemoteHost(sshMatch[1]), owner: sshMatch[2], repo: sshMatch[3] }
}
try {
const url = new URL(trimmed)
if (!['git:', 'git+ssh:', 'http:', 'https:', 'ssh:'].includes(url.protocol.toLowerCase())) {
return null
}
const path = parseGitHubRemotePath(url.pathname)
return path ? { host: normalizeGitHubRemoteHost(url.hostname), ...path } : null
} catch {
return null
}
}
export async function getRemoteUrlForRepo(
context: GitHubRepoContext,
remoteName: string
): Promise<string | null> {
if (context.connectionId) {
const provider = getSshGitProvider(context.connectionId)
if (!provider) {
return null
}
const { stdout } = await provider.exec(['remote', 'get-url', remoteName], context.repoPath)
return stdout
}
const { stdout } = await gitExecFileAsync(['remote', 'get-url', remoteName], {
cwd: context.repoPath,
...(context.wslDistro ? { wslDistro: context.wslDistro } : {})
})
return stdout
}
export async function getOwnerRepoForRemote(
repoPath: string,
remoteName: string,
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<OwnerRepo | null> {
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const runtimeKey = context.connectionId ?? `local:${context.wslDistro ?? 'host'}`
const cacheKey = `${runtimeKey}\0${context.repoPath}\0${remoteName}`
const now = Date.now()
pruneOwnerRepoCache(now)
const cached = ownerRepoCache.get(cacheKey)
if (cached && cached.expiresAt > now) {
return cached.value
}
const inFlight = ownerRepoInFlight.get(cacheKey)
if (inFlight) {
return inFlight
}
// Why: startup can resolve issue sources, PR candidates, and repo metadata
// for the same repo concurrently. Coalesce missing-remote probes.
const probe = resolveOwnerRepoForRemote(context, remoteName, cacheKey)
ownerRepoInFlight.set(cacheKey, probe)
try {
return await probe
} finally {
if (ownerRepoInFlight.get(cacheKey) === probe) {
ownerRepoInFlight.delete(cacheKey)
}
}
}
async function resolveOwnerRepoForRemote(
context: GitHubRepoContext,
remoteName: string,
cacheKey: string
): Promise<OwnerRepo | null> {
const now = Date.now()
try {
const remoteUrl = await getRemoteUrlForRepo(context, remoteName)
const result = remoteUrl ? parseGitHubOwnerRepo(remoteUrl) : null
if (result) {
ownerRepoCache.set(cacheKey, {
value: result,
expiresAt: now + OWNER_REPO_CACHE_TTL_MS
})
pruneOwnerRepoCache(now)
return result
}
} catch {
// ignore - non-GitHub remote or no remote
}
ownerRepoCache.set(cacheKey, { value: null, expiresAt: now + OWNER_REPO_CACHE_TTL_MS })
pruneOwnerRepoCache(now)
return null
}
export async function getOwnerRepo(
repoPath: string,
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<OwnerRepo | null> {
return getOwnerRepoForRemote(repoPath, 'origin', connectionId, localGitOptions)
}
export async function getIssueOwnerRepo(
repoPath: string,
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<OwnerRepo | null> {
const upstream = await getOwnerRepoForRemote(repoPath, 'upstream', connectionId, localGitOptions)
if (upstream) {
return upstream
}
return getOwnerRepoForRemote(repoPath, 'origin', connectionId, localGitOptions)
}
export type PRRepositoryCandidates = {
candidates: OwnerRepo[]
headRepo: OwnerRepo | null
}
function ownerRepoKey(ownerRepo: OwnerRepo): string {
return `${ownerRepo.owner.toLowerCase()}/${ownerRepo.repo.toLowerCase()}`
}
export async function resolvePRRepositoryCandidates(
repoPath: string,
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<PRRepositoryCandidates> {
const upstream = await getOwnerRepoForRemote(repoPath, 'upstream', connectionId, localGitOptions)
const origin = await getOwnerRepoForRemote(repoPath, 'origin', connectionId, localGitOptions)
const seen = new Set<string>()
const candidates: OwnerRepo[] = []
for (const candidate of [upstream, origin]) {
if (!candidate) {
continue
}
const key = ownerRepoKey(candidate)
if (seen.has(key)) {
continue
}
seen.add(key)
candidates.push(candidate)
}
return { candidates, headRepo: origin }
}
export type ResolvedIssueSource = {
source: OwnerRepo | null
/** True when explicit upstream is gone and resolver fell back to origin. */
fellBack: boolean
}
export async function resolveIssueSource(
repoPath: string,
preference: IssueSourcePreference | undefined,
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<ResolvedIssueSource> {
if (preference === 'upstream') {
const upstream = await getOwnerRepoForRemote(
repoPath,
'upstream',
connectionId,
localGitOptions
)
if (upstream) {
return { source: upstream, fellBack: false }
}
const origin = await getOwnerRepoForRemote(repoPath, 'origin', connectionId, localGitOptions)
return { source: origin, fellBack: origin !== null }
}
if (preference === 'origin') {
return {
source: await getOwnerRepoForRemote(repoPath, 'origin', connectionId, localGitOptions),
fellBack: false
}
}
return {
source: await getIssueOwnerRepo(repoPath, connectionId, localGitOptions),
fellBack: false
}
}
+74 -1
View File
@@ -27,7 +27,15 @@ vi.mock('./gh-utils', async () => {
}
})
import { createIssue, getIssue, listIssues, updateIssue } from './issues'
import {
addIssueComment,
createIssue,
getIssue,
listAssignableUsers,
listIssues,
listLabels,
updateIssue
} from './issues'
describe('issue source operations', () => {
beforeEach(() => {
@@ -65,6 +73,71 @@ describe('issue source operations', () => {
)
})
it('routes local WSL issue operations through repo resolution and gh execution options', async () => {
const localGitOptions = { wslDistro: 'Ubuntu' }
getIssueOwnerRepoMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' })
resolveIssueSourceMock.mockResolvedValue({
source: { owner: 'stablyai', repo: 'orca' },
fellBack: false
})
ghExecFileAsyncMock
.mockResolvedValueOnce({
stdout: JSON.stringify({
number: 923,
title: 'Use upstream issues',
state: 'open',
html_url: 'https://github.com/stablyai/orca/issues/923',
labels: []
})
})
.mockResolvedValueOnce({ stdout: '[]' })
.mockResolvedValueOnce({
stdout: JSON.stringify({
number: 924,
html_url: 'https://github.com/stablyai/orca/issues/924'
})
})
.mockResolvedValueOnce({ stdout: '' })
.mockResolvedValueOnce({
stdout: JSON.stringify({
id: 1,
user: { login: 'octo', avatar_url: '', type: 'User' },
body: 'Comment',
created_at: '2026-06-16T00:00:00.000Z',
html_url: 'https://github.com/stablyai/orca/issues/923#issuecomment-1'
})
})
.mockResolvedValueOnce({ stdout: 'bug\nfrontend\n' })
.mockResolvedValueOnce({ stdout: '{"login":"octo","avatar_url":""}\n' })
await getIssue('/repo-root', 923, null, localGitOptions)
await listIssues('/repo-root', 5, undefined, null, localGitOptions)
await createIssue(
'/repo-root',
'New issue',
'Body',
undefined,
null,
undefined,
localGitOptions
)
await updateIssue('/repo-root', 923, { body: 'Updated' }, null, localGitOptions)
await addIssueComment('/repo-root', 923, 'Comment', null, null, localGitOptions)
await listLabels('/repo-root', undefined, null, localGitOptions)
await listAssignableUsers('/repo-root', undefined, null, localGitOptions)
expect(getIssueOwnerRepoMock).toHaveBeenCalledWith('/repo-root', null, localGitOptions)
expect(resolveIssueSourceMock).toHaveBeenCalledWith(
'/repo-root',
undefined,
null,
localGitOptions
)
expect(ghExecFileAsyncMock.mock.calls.every((call) => call[1]?.wslDistro === 'Ubuntu')).toBe(
true
)
})
it('lists issues from the issue owner/repo', async () => {
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' })
+50 -22
View File
@@ -13,7 +13,7 @@ import type {
PRComment
} from '../../shared/types'
import { mapIssueInfo } from './mappers'
import type { OwnerRepo } from './gh-utils'
import type { LocalGitExecOptions, OwnerRepo } from './gh-utils'
// prettier-ignore
import { ghExecFileAsync, acquire, release, getIssueOwnerRepo, resolveIssueSource, classifyGhError, classifyListIssuesError, ghRepoExecOptions, githubRepoContext } from './gh-utils'
@@ -45,11 +45,12 @@ export type IssueListResult = {
export async function getIssue(
repoPath: string,
issueNumber: number,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<IssueInfo | null> {
const context = githubRepoContext(repoPath, connectionId)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const ownerRepo = await getIssueOwnerRepo(repoPath, connectionId)
const ownerRepo = await getIssueOwnerRepo(repoPath, connectionId, localGitOptions)
await acquire()
try {
if (ownerRepo) {
@@ -94,11 +95,17 @@ export async function listIssues(
repoPath: string,
limit = 20,
preference?: IssueSourcePreference,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<IssueListResult> {
const context = githubRepoContext(repoPath, connectionId)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const { source: ownerRepo } = await resolveIssueSource(repoPath, preference, connectionId)
const { source: ownerRepo } = await resolveIssueSource(
repoPath,
preference,
connectionId,
localGitOptions
)
await acquire()
try {
if (ownerRepo) {
@@ -153,15 +160,21 @@ export async function createIssue(
body: string,
preference?: IssueSourcePreference,
connectionId?: string | null,
fields?: GitHubCreateIssueFields
fields?: GitHubCreateIssueFields,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true; number: number; url: string } | { ok: false; error: string }> {
const trimmedTitle = title.trim()
if (!trimmedTitle) {
return { ok: false, error: 'Title is required' }
}
const context = githubRepoContext(repoPath, connectionId)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const { source: ownerRepo } = await resolveIssueSource(repoPath, preference, connectionId)
const { source: ownerRepo } = await resolveIssueSource(
repoPath,
preference,
connectionId,
localGitOptions
)
if (!ownerRepo) {
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
}
@@ -219,11 +232,12 @@ export async function updateIssue(
repoPath: string,
issueNumber: number,
updates: GitHubIssueUpdate,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true } | { ok: false; error: string }> {
const context = githubRepoContext(repoPath, connectionId)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const ownerRepo = await getIssueOwnerRepo(repoPath, connectionId)
const ownerRepo = await getIssueOwnerRepo(repoPath, connectionId, localGitOptions)
if (!ownerRepo) {
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
}
@@ -341,11 +355,13 @@ export async function addIssueComment(
issueNumber: number,
body: string,
connectionId?: string | null,
ownerRepoOverride?: OwnerRepo | null
ownerRepoOverride?: OwnerRepo | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubCommentResult> {
const context = githubRepoContext(repoPath, connectionId)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const ownerRepo = ownerRepoOverride ?? (await getIssueOwnerRepo(repoPath, connectionId))
const ownerRepo =
ownerRepoOverride ?? (await getIssueOwnerRepo(repoPath, connectionId, localGitOptions))
if (!ownerRepo) {
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
}
@@ -393,11 +409,17 @@ export async function addIssueComment(
export async function listLabels(
repoPath: string,
preference?: IssueSourcePreference,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<string[]> {
const context = githubRepoContext(repoPath, connectionId)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const { source: ownerRepo } = await resolveIssueSource(repoPath, preference, connectionId)
const { source: ownerRepo } = await resolveIssueSource(
repoPath,
preference,
connectionId,
localGitOptions
)
if (!ownerRepo) {
return []
}
@@ -427,11 +449,17 @@ export async function listLabels(
export async function listAssignableUsers(
repoPath: string,
preference?: IssueSourcePreference,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubAssignableUser[]> {
const context = githubRepoContext(repoPath, connectionId)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const { source: ownerRepo } = await resolveIssueSource(repoPath, preference, connectionId)
const { source: ownerRepo } = await resolveIssueSource(
repoPath,
preference,
connectionId,
localGitOptions
)
if (!ownerRepo) {
return []
}
+11 -2
View File
@@ -1,17 +1,26 @@
import { gitExecFileAsync } from '../git/runner'
import type { SshGitProvider } from '../providers/ssh-git-provider'
type LocalGitExecOptions = {
cwd: string
wslDistro?: string
}
// Why: the relay's read-only git.exec channel rejects `fetch`, so SSH repos
// must use the dedicated git.fetchRemoteTrackingRef RPC.
export async function fetchPrHeadTrackingRef(
repo: { path: string; connectionId?: string | null },
sshGitProvider: SshGitProvider | null | undefined,
remote: string,
branch: string
branch: string,
options: { localGitExecOptions?: LocalGitExecOptions } = {}
): Promise<void> {
const ref = `refs/remotes/${remote}/${branch}`
if (!repo.connectionId) {
await gitExecFileAsync(['fetch', remote, `+refs/heads/${branch}:${ref}`], { cwd: repo.path })
await gitExecFileAsync(
['fetch', remote, `+refs/heads/${branch}:${ref}`],
options.localGitExecOptions ?? { cwd: repo.path }
)
return
}
if (!sshGitProvider) {
@@ -355,6 +355,53 @@ describe('pr-refresh-coordinator', () => {
)
})
it('does not coalesce host and WSL refreshes for the same local branch', async () => {
const { enqueuePRRefresh } = await import('./pr-refresh-coordinator')
getPRForBranchOutcomeMock
.mockResolvedValueOnce({
kind: 'found',
pr: makePR({ number: 12 }),
fetchedAt: Date.now()
})
.mockResolvedValueOnce({
kind: 'found',
pr: makePR({ number: 44 }),
fetchedAt: Date.now()
})
enqueuePRRefresh(makeCandidate({ cacheKey: 'host::repo-1::feature/test' }), 'active', 80, 1)
enqueuePRRefresh(
makeCandidate({
cacheKey: 'wsl::repo-1::feature/test',
localGitOptions: { wslDistro: 'Ubuntu' }
}),
'active',
80,
1
)
await vi.runOnlyPendingTimersAsync()
await vi.runOnlyPendingTimersAsync()
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2)
expect(getPRForBranchOutcomeMock).toHaveBeenNthCalledWith(
1,
'/repo',
'feature/test',
null,
null,
null
)
expect(getPRForBranchOutcomeMock).toHaveBeenNthCalledWith(
2,
'/repo',
'feature/test',
null,
null,
null,
{ localGitExecOptions: { wslDistro: 'Ubuntu' } }
)
})
it('preserves coalesced aliases across visible follow-up refreshes', async () => {
const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator')
getPRForBranchOutcomeMock
+18 -4
View File
@@ -10,6 +10,7 @@ import type {
GitHubPRRefreshSkippedReason,
PRRefreshOutcome
} from '../../shared/types'
import type { HostedReviewExecutionOptions } from '../source-control/hosted-review-git-options'
import { getPRForBranchOutcome } from './client'
import { getRateLimit, noteRateLimitSpend, rateLimitGuard } from './rate-limit'
@@ -29,6 +30,14 @@ type PRRefreshOutcomeObserver = (
outcome: PRRefreshOutcome
) => void
function hostedReviewOptionArgs(
localGitOptions?: GitHubPRRefreshCandidate['localGitOptions']
): [] | [HostedReviewExecutionOptions] {
return localGitOptions?.wslDistro
? [{ localGitExecOptions: { wslDistro: localGitOptions.wslDistro } }]
: []
}
const MIN_BACKGROUND_REFRESH_AGE_MS = 60_000
const MERGEABILITY_PENDING_REFRESH_MS = 10_000
const MANUAL_MERGEABILITY_PENDING_REFRESH_MS = 2_500
@@ -93,10 +102,13 @@ function broadcast(event: Omit<GitHubPRRefreshEvent, 'sequence'>, sequenceOverri
function refreshKey(candidate: GitHubPRRefreshCandidate): string {
const connectionScope = candidate.connectionId ?? 'local'
const runtimeScope = candidate.connectionId
? 'remote'
: `runtime:${candidate.localGitOptions?.wslDistro ? `wsl:${candidate.localGitOptions.wslDistro}` : 'host'}`
if (typeof candidate.linkedPRNumber === 'number') {
return `${connectionScope}::${candidate.repoPath}::pr::${candidate.linkedPRNumber}`
return `${connectionScope}::${runtimeScope}::${candidate.repoPath}::pr::${candidate.linkedPRNumber}`
}
return `${connectionScope}::${candidate.repoPath}::branch::${candidate.branch}`
return `${connectionScope}::${runtimeScope}::${candidate.repoPath}::branch::${candidate.branch}`
}
function isVisibleKey(key: string): boolean {
@@ -519,7 +531,8 @@ async function drainQueue(): Promise<void> {
next.candidate.branch,
next.candidate.linkedPRNumber ?? null,
next.candidate.connectionId ?? null,
next.candidate.linkedPRNumber == null ? (next.candidate.fallbackPRNumber ?? null) : null
next.candidate.linkedPRNumber == null ? (next.candidate.fallbackPRNumber ?? null) : null,
...hostedReviewOptionArgs(next.candidate.localGitOptions)
)
outcomeObserver?.(next.candidate, outcome)
broadcast({ aliases, reason: next.reason, outcome, requestStartedAt }, requestSequence)
@@ -645,7 +658,8 @@ export async function refreshPRNow(candidate: GitHubPRRefreshCandidate): Promise
candidate.branch,
candidate.linkedPRNumber ?? null,
candidate.connectionId ?? null,
candidate.linkedPRNumber == null ? (candidate.fallbackPRNumber ?? null) : null
candidate.linkedPRNumber == null ? (candidate.fallbackPRNumber ?? null) : null,
...hostedReviewOptionArgs(candidate.localGitOptions)
)
outcomeObserver?.(candidate, outcome)
broadcast({ aliases, reason: 'manual', outcome, requestStartedAt }, requestSequence)
+16 -2
View File
@@ -11,6 +11,7 @@ type ResolveGitHubPrStartPointArgs = {
baseRefName?: string
isCrossRepository?: boolean
connectionId?: string | null
localGitOptions?: { wslDistro?: string }
gitExec: GitExec
fetchRemoteTrackingRef: (remote: string, branch: string) => Promise<void>
resolveRemote: () => Promise<string>
@@ -18,6 +19,12 @@ type ResolveGitHubPrStartPointArgs = {
type ResolveGitHubPrStartPointResult = GitHubPrStartPoint | { error: string }
function localGitOptionArgs(
options: { wslDistro?: string } | undefined
): [] | [{ wslDistro?: string }] {
return options && Object.keys(options).length > 0 ? [options] : []
}
export async function resolveGitHubPrStartPoint(
args: ResolveGitHubPrStartPointArgs
): Promise<ResolveGitHubPrStartPointResult> {
@@ -35,7 +42,8 @@ export async function resolveGitHubPrStartPoint(
const resolved = await getPullRequestPushTarget(
args.repoPath,
args.prNumber,
args.connectionId ?? null
args.connectionId ?? null,
...localGitOptionArgs(args.localGitOptions)
)
pushTarget = resolved?.pushTarget
maintainerCanModify = resolved?.maintainerCanModify
@@ -47,7 +55,13 @@ export async function resolveGitHubPrStartPoint(
}
if (!headRefName) {
const item = await getWorkItem(args.repoPath, args.prNumber, 'pr', args.connectionId ?? null)
const item = await getWorkItem(
args.repoPath,
args.prNumber,
'pr',
args.connectionId ?? null,
...localGitOptionArgs(args.localGitOptions)
)
if (!item || item.type !== 'pr') {
return { error: `PR #${args.prNumber} not found.` }
}
+87 -3
View File
@@ -27,11 +27,14 @@ const {
rateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })),
noteRateLimitSpendMock: vi.fn(),
ghRepoExecOptionsMock: vi.fn((context) =>
context.connectionId ? {} : { cwd: context.repoPath }
context.connectionId
? {}
: { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) }
),
githubRepoContextMock: vi.fn((repoPath, connectionId) => ({
githubRepoContextMock: vi.fn((repoPath, connectionId, localGitOptions) => ({
repoPath,
connectionId: connectionId ?? null
connectionId: connectionId ?? null,
...localGitOptions
})),
acquireMock: vi.fn(),
releaseMock: vi.fn()
@@ -241,4 +244,85 @@ describe('getWorkItemDetails', () => {
expect(ghExecFileAsyncMock.mock.calls[0][1]).toEqual({})
expect(details?.body).toBe('Remote issue body')
})
it('routes local WSL PR detail fan-out through the selected distro', async () => {
const localGitOptions = { wslDistro: 'Ubuntu' }
getWorkItemMock.mockResolvedValueOnce({
id: 'pr:42',
type: 'pr',
number: 42,
title: 'Review drawer WSL',
state: 'open',
url: 'https://github.com/stablyai/orca/pull/42',
labels: [],
updatedAt: '2026-04-01T00:00:00Z',
author: 'octocat'
})
getOwnerRepoMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' })
getPRCommentsMock.mockResolvedValue([])
getPRChecksMock.mockResolvedValue([])
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
const target = args.at(-1)
if (target === 'repos/stablyai/orca/pulls/42') {
return {
stdout: JSON.stringify({
body: 'PR body',
head: { sha: 'head-sha' },
base: { sha: 'base-sha' }
})
}
}
if (target === 'repos/stablyai/orca/pulls/42/files?per_page=100') {
return { stdout: '[]' }
}
const query = args.find((arg) => arg.startsWith('query=')) ?? ''
if (query.includes('viewerViewedState')) {
return {
stdout: JSON.stringify({
data: {
repository: {
pullRequest: {
id: 'PR_kwDO123',
files: { pageInfo: { hasNextPage: false }, nodes: [] }
}
}
}
})
}
}
if (query.includes('participants(first: 100)')) {
return {
stdout: JSON.stringify({
data: { repository: { pullRequest: { participants: { nodes: [] } } } }
})
}
}
return { stdout: JSON.stringify({ data: {} }) }
})
const details = await getWorkItemDetails('/repo-root', 42, 'pr', null, localGitOptions)
expect(details?.body).toBe('PR body')
expect(getWorkItemMock).toHaveBeenCalledWith('/repo-root', 42, 'pr', null, localGitOptions)
expect(getOwnerRepoMock).toHaveBeenCalledWith('/repo-root', null, localGitOptions)
expect(getPRCommentsMock).toHaveBeenCalledWith(
'/repo-root',
42,
undefined,
null,
localGitOptions
)
expect(getPRChecksMock).toHaveBeenCalledWith(
'/repo-root',
42,
'head-sha',
null,
undefined,
null,
localGitOptions
)
expect(ghExecFileAsyncMock.mock.calls.every((call) => call[1]?.wslDistro === 'Ubuntu')).toBe(
true
)
})
})
+121 -45
View File
@@ -18,7 +18,8 @@ import {
getOwnerRepo,
getIssueOwnerRepo,
ghRepoExecOptions,
githubRepoContext
githubRepoContext,
type LocalGitExecOptions
} from './gh-utils'
import { getWorkItem, getPRChecks, getPRComments } from './client'
import { noteRateLimitSpend, rateLimitGuard } from './rate-limit'
@@ -34,6 +35,10 @@ const MAX_PR_FILES = 300
// the safety fallback.
const GITHUB_RAW_CONTENT_MAX_BUFFER_BYTES = 8 * 1024 * 1024
function localGitOptionArgs(options: LocalGitExecOptions = {}): [] | [LocalGitExecOptions] {
return Object.keys(options).length > 0 ? [options] : []
}
const PR_FILE_VIEWED_STATES_QUERY = `query($owner: String!, $repo: String!, $number: Int!, $after: String) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
@@ -124,15 +129,20 @@ type GraphQLIssueDetailsResponse = {
async function getIssueDetailsViaGraphQL(
repoPath: string,
issueNumber: number,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{
body: string
comments: PRComment[]
assignees: string[]
participants: GitHubAssignableUser[]
} | null> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getIssueOwnerRepo(repoPath, connectionId)
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = await getIssueOwnerRepo(
repoPath,
connectionId,
...localGitOptionArgs(localGitOptions)
)
if (!ownerRepo) {
return null
}
@@ -274,10 +284,15 @@ function isBinaryHint(file: RESTPRFile): boolean {
async function getPRHeadBaseSha(
repoPath: string,
prNumber: number,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ headSha: string; baseSha: string } | null> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = await getOwnerRepo(
repoPath,
connectionId,
...localGitOptionArgs(localGitOptions)
)
try {
if (ownerRepo) {
const { stdout } = await ghExecFileAsync(
@@ -313,10 +328,15 @@ async function getPRHeadBaseSha(
async function getPRFiles(
repoPath: string,
prNumber: number,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubPRFile[]> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = await getOwnerRepo(
repoPath,
connectionId,
...localGitOptionArgs(localGitOptions)
)
if (!ownerRepo) {
return []
}
@@ -353,10 +373,15 @@ type PRFileViewedStatesResult = {
async function getPRFileViewedStates(
repoPath: string,
prNumber: number,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<PRFileViewedStatesResult | null> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = await getOwnerRepo(
repoPath,
connectionId,
...localGitOptionArgs(localGitOptions)
)
if (!ownerRepo) {
return null
}
@@ -444,10 +469,15 @@ function mergePRFileViewedStates(
async function getIssueBodyAndComments(
repoPath: string,
issueNumber: number,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ body: string; comments: PRComment[]; assignees: string[] }> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getIssueOwnerRepo(repoPath, connectionId)
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = await getIssueOwnerRepo(
repoPath,
connectionId,
...localGitOptionArgs(localGitOptions)
)
try {
if (ownerRepo) {
const [issueResult, commentsResult] = await Promise.all([
@@ -530,10 +560,15 @@ async function getIssueBodyAndComments(
async function getPRBody(
repoPath: string,
prNumber: number,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<string> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
const ownerRepo = await getOwnerRepo(
repoPath,
connectionId,
...localGitOptionArgs(localGitOptions)
)
try {
if (ownerRepo) {
const { stdout } = await ghExecFileAsync(
@@ -557,15 +592,16 @@ async function getPRBody(
async function getWorkItemParticipants(
repoPath: string,
item: Pick<GitHubWorkItem, 'number' | 'type'>,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubAssignableUser[]> {
// Why: issues in a fork live on the upstream remote, so participants must be
// resolved via getIssueOwnerRepo to stay consistent with getIssueBodyAndComments.
// PRs remain tied to origin via getOwnerRepo.
const ownerRepo =
item.type === 'issue'
? await getIssueOwnerRepo(repoPath, connectionId)
: await getOwnerRepo(repoPath, connectionId)
? await getIssueOwnerRepo(repoPath, connectionId, ...localGitOptionArgs(localGitOptions))
: await getOwnerRepo(repoPath, connectionId, ...localGitOptionArgs(localGitOptions))
if (!ownerRepo) {
return []
}
@@ -589,7 +625,7 @@ async function getWorkItemParticipants(
'-F',
`isPr=${item.type === 'pr'}`
],
ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
)
const data = JSON.parse(stdout) as {
data?: {
@@ -622,7 +658,8 @@ async function getWorkItemParticipants(
async function getGitHubUsersByLogin(
repoPath: string,
logins: string[],
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubAssignableUser[]> {
const uniqueLogins = Array.from(
new Set(logins.filter((login) => login && login !== 'ghost').map((login) => login.trim()))
@@ -643,7 +680,7 @@ async function getGitHubUsersByLogin(
noteRateLimitSpend('graphql')
const { stdout } = await ghExecFileAsync(
['api', 'graphql', '-f', `query=query { ${fields} }`],
ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
)
const data = JSON.parse(stdout) as {
data?: Record<
@@ -680,14 +717,20 @@ async function getMentionParticipants(
item: Pick<GitHubWorkItem, 'author' | 'number' | 'type'>,
comments: PRComment[],
participants: GitHubAssignableUser[],
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubAssignableUser[]> {
const visibleLogins = [item.author ?? '', ...comments.map((comment) => comment.author)]
// Why: one aliased GraphQL query returns login/name/avatarUrl for every
// mentioned author in a single round-trip. The previous REST fan-out
// (/users/<login>) returned the same fields but cost one rate-limit point
// per user.
const graphQlUsers = await getGitHubUsersByLogin(repoPath, visibleLogins, connectionId)
const graphQlUsers = await getGitHubUsersByLogin(
repoPath,
visibleLogins,
connectionId,
localGitOptions
)
return mergeGitHubUsers([...participants, ...graphQlUsers])
}
@@ -695,10 +738,19 @@ async function getPRChecksForDetails(
repoPath: string,
prNumber: number,
headSha: string | undefined,
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<PRCheckDetail[]> {
try {
return await getPRChecks(repoPath, prNumber, headSha, null, undefined, connectionId)
return await getPRChecks(
repoPath,
prNumber,
headSha,
null,
undefined,
connectionId,
...localGitOptionArgs(localGitOptions)
)
} catch (err) {
// Why: checks are auxiliary PR metadata; a gh CLI edge case must not block
// the user from opening the PR review drawer and reading the files/comments.
@@ -711,7 +763,8 @@ export async function getWorkItemDetails(
repoPath: string,
number: number,
type?: 'issue' | 'pr',
connectionId?: string | null
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubWorkItemDetails | null> {
// Why: getWorkItem already handles acquire/release. We call it first (outside
// our semaphore) so the known-cheap lookup doesn't compete with the richer
@@ -720,7 +773,8 @@ export async function getWorkItemDetails(
repoPath,
number,
type,
connectionId
connectionId,
...localGitOptionArgs(localGitOptions)
)
if (!item) {
return null
@@ -736,7 +790,12 @@ export async function getWorkItemDetails(
// is preserved. The GraphQL `participants` connection includes every
// commenter, so we skip the extra `getMentionParticipants` aliased
// user-hydration trip when the collapsed path succeeds.
const collapsed = await getIssueDetailsViaGraphQL(repoPath, item.number, connectionId)
const collapsed = await getIssueDetailsViaGraphQL(
repoPath,
item.number,
connectionId,
localGitOptions
)
if (collapsed) {
return {
item,
@@ -749,15 +808,16 @@ export async function getWorkItemDetails(
// Why: fall back to body/comments and GraphQL participants in parallel;
// the mention-participant merge is a cheap local operation afterward.
const [{ body, comments, assignees }, participants] = await Promise.all([
getIssueBodyAndComments(repoPath, item.number, connectionId),
getWorkItemParticipants(repoPath, item, connectionId)
getIssueBodyAndComments(repoPath, item.number, connectionId, localGitOptions),
getWorkItemParticipants(repoPath, item, connectionId, localGitOptions)
])
const mentionParticipants = await getMentionParticipants(
repoPath,
item,
comments,
participants,
connectionId
connectionId,
localGitOptions
)
return {
item,
@@ -770,20 +830,26 @@ export async function getWorkItemDetails(
// PR: fetch body + comments + checks + files + head/base SHAs in parallel.
const [body, comments, shas, files, viewedStates, participants] = await Promise.all([
getPRBody(repoPath, item.number, connectionId),
getPRComments(repoPath, item.number, undefined, connectionId),
getPRHeadBaseSha(repoPath, item.number, connectionId),
getPRFiles(repoPath, item.number, connectionId),
getPRFileViewedStates(repoPath, item.number, connectionId),
getWorkItemParticipants(repoPath, item, connectionId)
getPRBody(repoPath, item.number, connectionId, localGitOptions),
getPRComments(
repoPath,
item.number,
undefined,
connectionId,
...localGitOptionArgs(localGitOptions)
),
getPRHeadBaseSha(repoPath, item.number, connectionId, localGitOptions),
getPRFiles(repoPath, item.number, connectionId, localGitOptions),
getPRFileViewedStates(repoPath, item.number, connectionId, localGitOptions),
getWorkItemParticipants(repoPath, item, connectionId, localGitOptions)
])
// Why: run the mention-author GraphQL lookup in parallel with the final
// checks fetch instead of serially — both depend only on data from the
// Promise.all above, so there's no ordering requirement between them.
const [mentionParticipants, checks] = await Promise.all([
getMentionParticipants(repoPath, item, comments, participants, connectionId),
getPRChecksForDetails(repoPath, item.number, shas?.headSha, connectionId)
getMentionParticipants(repoPath, item, comments, participants, connectionId, localGitOptions),
getPRChecksForDetails(repoPath, item.number, shas?.headSha, connectionId, localGitOptions)
])
return {
@@ -809,6 +875,7 @@ export async function getWorkItemDetails(
async function fetchContentAtRef(args: {
repoPath: string
connectionId?: string | null
localGitOptions?: LocalGitExecOptions
owner: string
repo: string
path: string
@@ -825,7 +892,9 @@ async function fetchContentAtRef(args: {
`repos/${args.owner}/${args.repo}/contents/${encodeURI(args.path)}?ref=${encodeURIComponent(args.ref)}`
],
{
...ghRepoExecOptions(githubRepoContext(args.repoPath, args.connectionId)),
...ghRepoExecOptions(
githubRepoContext(args.repoPath, args.connectionId, args.localGitOptions)
),
maxBuffer: GITHUB_RAW_CONTENT_MAX_BUFFER_BYTES
}
)
@@ -848,6 +917,7 @@ async function fetchContentAtRef(args: {
export async function getPRFileContents(args: {
repoPath: string
connectionId?: string | null
localGitOptions?: LocalGitExecOptions
prNumber: number
path: string
oldPath?: string
@@ -855,7 +925,11 @@ export async function getPRFileContents(args: {
headSha: string
baseSha: string
}): Promise<GitHubPRFileContents> {
const ownerRepo = await getOwnerRepo(args.repoPath, args.connectionId)
const ownerRepo = await getOwnerRepo(
args.repoPath,
args.connectionId,
...localGitOptionArgs(args.localGitOptions)
)
if (!ownerRepo) {
return {
original: '',
@@ -880,6 +954,7 @@ export async function getPRFileContents(args: {
? fetchContentAtRef({
repoPath: args.repoPath,
connectionId: args.connectionId,
localGitOptions: args.localGitOptions,
owner: ownerRepo.owner,
repo: ownerRepo.repo,
path: originalPath,
@@ -893,6 +968,7 @@ export async function getPRFileContents(args: {
? fetchContentAtRef({
repoPath: args.repoPath,
connectionId: args.connectionId,
localGitOptions: args.localGitOptions,
owner: ownerRepo.owner,
repo: ownerRepo.repo,
path: args.path,