Support GitHub Enterprise diffs and mutations with host-scoped caches

- Carry host identity through PR mutations and reads so fork PRs on
  different GHES instances don't collide in cache or state tracking.
- Validate host authentication before routing requests to unconfigured
  Enterprise servers; ambient credentials must never reach untrusted hosts.
- Scope rate-limit guards and spend tracking per host so GHES quota stays
  independent from github.com quota.
- Respect explicit --hostname arguments in gh CLI calls ahead of GH_HOST or
  ambient defaults, so breaker state follows the actual request target.
- Detect implicit WSL runtimes from UNC paths for consistent host auth and
  execution-options scoping across mobile and desktop clients.
This commit is contained in:
Jinjing
2026-07-19 18:06:09 -07:00
parent 917c55f830
commit 5cef6ee8fa
83 changed files with 2855 additions and 650 deletions
+2 -1
View File
@@ -57,7 +57,8 @@ vi.mock('../git/runner', () => ({
}))
vi.mock('./github-enterprise-repository', () => ({
getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock
getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock,
isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true)
}))
import { createGitHubPullRequest } from './client'
+2 -1
View File
@@ -40,7 +40,8 @@ vi.mock('./gh-utils', () => ({
}))
vi.mock('./github-enterprise-repository', () => ({
getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock
getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock,
isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true)
}))
import { setPRFileViewed } from './client'
+27 -10
View File
@@ -79,7 +79,9 @@ vi.mock('../git/runner', () => ({
}))
vi.mock('./github-enterprise-repository', () => ({
getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock
getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock,
getEnterpriseGitHubRepoSlugForRemote: getEnterpriseGitHubRepoSlugMock,
isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true)
}))
vi.mock('../providers/ssh-git-dispatch', () => ({
@@ -228,7 +230,7 @@ describe('GitHub PR local runtime routing', () => {
await getPRComments('/repo-root', 7, { prRepo }, null, localGitOptions)
await expect(
resolveReviewThread('/repo-root', 'thread-1', true, null, localGitOptions)
resolveReviewThread('/repo-root', 'thread-1', true, null, prRepo, localGitOptions)
).resolves.toBe(true)
await expect(
addPRReviewCommentReply(
@@ -249,6 +251,7 @@ describe('GitHub PR local runtime routing', () => {
repoPath: '/repo-root',
connectionId: null,
localGitOptions,
prRepo,
prNumber: 7,
body: 'Inline',
commitId: 'head-oid',
@@ -263,13 +266,13 @@ describe('GitHub PR local runtime routing', () => {
updatePRDetails('/repo-root', 7, { body: 'New body' }, null, prRepo, localGitOptions)
).resolves.toEqual({ ok: true })
await expect(
updatePRState('/repo-root', 7, { state: 'closed' }, null, localGitOptions)
updatePRState('/repo-root', 7, { state: 'closed' }, null, prRepo, localGitOptions)
).resolves.toEqual({ ok: true })
await expect(
requestPRReviewers('/repo-root', 7, ['octo'], null, localGitOptions)
requestPRReviewers('/repo-root', 7, ['octo'], null, prRepo, localGitOptions)
).resolves.toEqual({ ok: true })
await expect(
removePRReviewers('/repo-root', 7, ['octo'], null, localGitOptions)
removePRReviewers('/repo-root', 7, ['octo'], null, prRepo, localGitOptions)
).resolves.toEqual({ ok: true })
await expect(
setPRAutoMerge('/repo-root', 7, true, 'squash', null, prRepo, localGitOptions)
@@ -449,9 +452,16 @@ describe('GitHub PR local runtime routing', () => {
getPRCheckDetails('/remote/repo', { checkRunId: 88, prRepo: enterpriseRepo }, 'ssh-1')
).resolves.toMatchObject({ name: 'lint', conclusion: 'failure' })
await expect(
rerunPRChecks('/remote/repo', 7, { headSha: 'head-sha', failedOnly: true }, 'ssh-1')
rerunPRChecks(
'/remote/repo',
7,
{ headSha: 'head-sha', failedOnly: true, prRepo: enterpriseRepo },
'ssh-1'
)
).resolves.toEqual({ ok: true, count: 1 })
await expect(resolveReviewThread('/remote/repo', 'thread-1', true, 'ssh-1')).resolves.toBe(true)
await expect(
resolveReviewThread('/remote/repo', 'thread-1', true, 'ssh-1', enterpriseRepo)
).resolves.toBe(true)
await expect(
addPRReviewCommentReply(
'/remote/repo',
@@ -469,6 +479,7 @@ describe('GitHub PR local runtime routing', () => {
addPRReviewComment({
repoPath: '/remote/repo',
connectionId: 'ssh-1',
prRepo: enterpriseRepo,
prNumber: 7,
body: 'Enterprise inline comment',
commitId: 'head-sha',
@@ -482,13 +493,19 @@ describe('GitHub PR local runtime routing', () => {
await expect(
updatePRDetails('/remote/repo', 7, { body: 'New body' }, 'ssh-1', enterpriseRepo)
).resolves.toEqual({ ok: true })
await expect(updatePRState('/remote/repo', 7, { state: 'closed' }, 'ssh-1')).resolves.toEqual({
await expect(
updatePRState('/remote/repo', 7, { state: 'closed' }, 'ssh-1', enterpriseRepo)
).resolves.toEqual({
ok: true
})
await expect(requestPRReviewers('/remote/repo', 7, ['octo'], 'ssh-1')).resolves.toEqual({
await expect(
requestPRReviewers('/remote/repo', 7, ['octo'], 'ssh-1', enterpriseRepo)
).resolves.toEqual({
ok: true
})
await expect(removePRReviewers('/remote/repo', 7, ['octo'], 'ssh-1')).resolves.toEqual({
await expect(
removePRReviewers('/remote/repo', 7, ['octo'], 'ssh-1', enterpriseRepo)
).resolves.toEqual({
ok: true
})
await expect(
@@ -11,6 +11,9 @@ const {
gitExecFileAsyncMock,
rateLimitGuardMock,
noteRateLimitSpendMock,
repositoryRateLimitGuardMock,
noteRepositoryRateLimitSpendMock,
spendsSharedGitHubComQuotaMock,
acquireMock,
releaseMock
} = vi.hoisted(() => ({
@@ -23,6 +26,11 @@ const {
gitExecFileAsyncMock: vi.fn(),
rateLimitGuardMock: vi.fn((_bucket?: unknown) => ({ blocked: false })),
noteRateLimitSpendMock: vi.fn(),
repositoryRateLimitGuardMock: vi.fn((_repo: unknown, bucket: string) =>
rateLimitGuardMock(bucket)
),
noteRepositoryRateLimitSpendMock: vi.fn(),
spendsSharedGitHubComQuotaMock: vi.fn(() => true),
acquireMock: vi.fn(),
releaseMock: vi.fn()
}))
@@ -67,11 +75,9 @@ vi.mock('./rate-limit', () => ({
noteRateLimitSpend: noteRateLimitSpendMock,
getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })),
// Mirror production: shared-scope calls delegate to the global guard/spend.
repositoryRateLimitGuard: vi.fn((_repo: unknown, bucket: string) => rateLimitGuardMock(bucket)),
noteRepositoryRateLimitSpend: vi.fn((_repo: unknown, bucket: string, cost?: number) =>
noteRateLimitSpendMock(bucket, cost)
),
spendsSharedGitHubComQuota: () => true
repositoryRateLimitGuard: repositoryRateLimitGuardMock,
noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock,
spendsSharedGitHubComQuota: spendsSharedGitHubComQuotaMock
}))
vi.mock('./github-api-repository', async (importOriginal) => {
@@ -135,6 +141,10 @@ describe('listWorkItems query paging', () => {
rateLimitGuardMock.mockReset()
rateLimitGuardMock.mockReturnValue({ blocked: false })
noteRateLimitSpendMock.mockReset()
repositoryRateLimitGuardMock.mockClear()
noteRepositoryRateLimitSpendMock.mockReset()
spendsSharedGitHubComQuotaMock.mockReset()
spendsSharedGitHubComQuotaMock.mockReturnValue(true)
acquireMock.mockReset()
releaseMock.mockReset()
acquireMock.mockResolvedValue(undefined)
@@ -165,6 +175,31 @@ describe('listWorkItems query paging', () => {
expect(releaseMock).not.toHaveBeenCalled()
})
it('uses an implicit WSL UNC cwd for search quota accounting', async () => {
const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' }
const repoPath = String.raw`\\wsl.localhost\Ubuntu\home\me\widgets`
getIssueOwnerRepoMock.mockResolvedValueOnce(repository)
getOwnerRepoMock.mockResolvedValueOnce(repository)
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '3' })
spendsSharedGitHubComQuotaMock.mockReturnValue(false)
await expect(countWorkItems(repoPath, 'is:issue is:open')).resolves.toBe(3)
const executionOptions = { cwd: repoPath, host: 'github.com' }
expect(spendsSharedGitHubComQuotaMock).toHaveBeenCalledWith(repository, executionOptions)
expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith(
repository,
'search',
executionOptions
)
expect(noteRepositoryRateLimitSpendMock).toHaveBeenCalledWith(
repository,
'search',
1,
executionOptions
)
})
it('passes review-requested as a --search qualifier (gh CLI has no dedicated flag)', async () => {
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
+59
View File
@@ -3690,6 +3690,39 @@ describe('getPRForBranch', () => {
)
})
it('does not confuse same-slug PR repositories across GitHub hosts', async () => {
const enterprise = { owner: 'team', repo: 'orca', host: 'github.acme-corp.com' }
const dotCom = { owner: 'team', repo: 'orca', host: 'github.com' }
resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({
candidates: [enterprise, dotCom],
headRepo: dotCom
})
getOwnerRepoForRemoteMock.mockResolvedValueOnce(dotCom)
getRemoteUrlForRepoMock.mockResolvedValueOnce('git@github.com:team/orca.git')
ghExecFileAsyncMock.mockResolvedValueOnce({
stdout: JSON.stringify({
head: {
ref: 'feature',
repo: {
full_name: 'team/orca',
name: 'orca',
clone_url: 'https://github.acme-corp.com/team/orca.git',
ssh_url: 'git@github.acme-corp.com:team/orca.git',
owner: { login: 'team' }
}
}
})
})
await expect(getPullRequestPushTarget('/repo-root', 7)).resolves.toEqual({
pushTarget: {
remoteName: 'pr-team-orca',
branchName: 'feature',
remoteUrl: 'git@github.acme-corp.com:team/orca.git'
}
})
})
it('probes additional PR repo candidates when the first lookup is not found', async () => {
resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({
candidates: [
@@ -4271,6 +4304,13 @@ describe('GitHub GraphQL rate-limit guard', () => {
})
it('isolates merge metadata for the same slug on different GitHub hosts', async () => {
resolvePRRepositoryCandidatesMock.mockResolvedValue({
candidates: [
{ owner: 'acme', repo: 'widgets', host: 'github.com' },
{ owner: 'acme', repo: 'widgets', host: 'github.acme-corp.com' }
],
headRepo: { owner: 'acme', repo: 'widgets', host: 'github.com' }
})
const prView = {
number: 7,
title: 'PR',
@@ -4320,6 +4360,25 @@ describe('GitHub GraphQL rate-limit guard', () => {
expect(graphqlCalls[1]?.[1]).toEqual(expect.objectContaining({ host: 'github.acme-corp.com' }))
})
it('rejects explicit work-item lookups outside configured repository candidates', async () => {
resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({
candidates: [{ owner: 'acme', repo: 'widgets', host: 'github.com' }],
headRepo: { owner: 'acme', repo: 'widgets', host: 'github.com' }
})
await expect(
getWorkItemByOwnerRepo(
'/repo-root',
{ owner: 'victim', repo: 'secrets', host: 'evil.example.test' },
7,
'pr'
)
).resolves.toBeNull()
expect(acquireMock).not.toHaveBeenCalled()
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
})
it('returns conflicting file details instead of running gh merge when PR is dirty', async () => {
ghExecFileAsyncMock.mockResolvedValueOnce({
stdout: JSON.stringify({
+52 -17
View File
@@ -189,7 +189,7 @@ function pruneRepositoryMergeMetadataCache(now = Date.now()): void {
async function assertRateLimitBudget(
bucket: RateLimitBucketKind,
repository?: GitHubApiRepository | null,
executionOptions?: Pick<GhExecOptions, 'wslDistro'>
executionOptions?: Pick<GhExecOptions, 'cwd' | 'wslDistro'>
): Promise<void> {
if (spendsSharedGitHubComQuota(repository, executionOptions)) {
await getRateLimit()
@@ -313,6 +313,7 @@ export async function getPullRequestPushTarget(
await acquire()
try {
let prStdout = ''
let matchedRepository: GitHubApiRepository | null = null
for (const candidate of candidates) {
try {
const { stdout } = await ghExecFileAsync(
@@ -320,6 +321,7 @@ export async function getPullRequestPushTarget(
{ ...ghOptions, ...githubHostExecOptions(candidate) }
)
prStdout = stdout
matchedRepository = candidate
break
} catch (error) {
// Why: in fork workflows `origin` is often the contributor fork while
@@ -331,7 +333,7 @@ export async function getPullRequestPushTarget(
throw error
}
}
if (!prStdout) {
if (!prStdout || !matchedRepository) {
return null
}
const origin = await getGitHubApiRepositoryForRemote(
@@ -366,8 +368,8 @@ export async function getPullRequestPushTarget(
}
if (
origin &&
origin.owner.toLowerCase() === owner.toLowerCase() &&
origin.repo.toLowerCase() === repo.toLowerCase()
githubRepoIdentityKey(origin) ===
githubRepoIdentityKey({ owner, repo, host: matchedRepository.host })
) {
return {
pushTarget: { remoteName: 'origin', branchName },
@@ -1577,7 +1579,7 @@ async function countWorkItemsForQuery(
)
// Why: over-counts gh cache hits, which is the safe direction — the search
// bucket is only 30/min and the next probe corrects the estimate.
noteRepositoryRateLimitSpend(ownerRepo, 'search', 1, localGitOptions)
noteRepositoryRateLimitSpend(ownerRepo, 'search', 1, ghOptions)
return Number.parseInt(stdout.trim(), 10) || 0
}
@@ -1629,16 +1631,20 @@ export async function countWorkItems(
const parsedQuery = trimmedQuery ? parseTaskQuery(trimmedQuery) : null
const effectiveQuery = parsedQuery ?? defaultOpenWorkItemQuery()
const ghOptions = {
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
...githubHostExecOptions(ownerRepo)
}
// Why: counts are decorative (pagination totals). The search bucket is only
// 30/min, so a multi-repo Tasks page must stop counting when the budget is
// gone instead of converting the remaining repos into 403 spawns. getRateLimit
// is 30s-cached and single-flight, so priming here is one spawn per window.
// Only shared github.com traffic consults the snapshot; other scopes bypass.
if (spendsSharedGitHubComQuota(ownerRepo, localGitOptions)) {
if (spendsSharedGitHubComQuota(ownerRepo, ghOptions)) {
await getRateLimit()
}
if (repositoryRateLimitGuard(ownerRepo, 'search', localGitOptions).blocked) {
if (repositoryRateLimitGuard(ownerRepo, 'search', ghOptions).blocked) {
return 0
}
@@ -2142,14 +2148,34 @@ export async function getWorkItemByOwnerRepo(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<MainWorkItem | null> {
const { candidates } = await resolveGitHubApiRepositoryCandidates(
repoPath,
connectionId,
localGitOptions
)
const requestedKey = githubRepoIdentityKey(ownerRepo)
const matchedRepository = candidates.find(
(candidate) => githubRepoIdentityKey(candidate) === requestedKey
)
// Why: this lookup is reachable from pasted links. Restricting it to a
// configured remote prevents gh from sending credentials to an arbitrary host.
if (!matchedRepository) {
return null
}
await acquire()
try {
if (type === 'issue') {
return await fetchIssueWorkItem(repoPath, ownerRepo, number, connectionId, localGitOptions)
return await fetchIssueWorkItem(
repoPath,
matchedRepository,
number,
connectionId,
localGitOptions
)
}
return await fetchPullRequestWorkItem(
repoPath,
ownerRepo,
matchedRepository,
number,
connectionId,
localGitOptions
@@ -4058,13 +4084,17 @@ function parseActionsRunId(url: string | null | undefined): number | undefined {
export async function rerunPRChecks(
repoPath: string,
prNumber: number,
options: { headSha?: string; failedOnly?: boolean } = {},
options: {
headSha?: string
failedOnly?: boolean
prRepo?: GitHubApiRepository | null
} = {},
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubRerunPRChecksResult> {
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
repoPath,
undefined,
options.prRepo,
connectionId,
localGitOptions
)
@@ -4452,13 +4482,14 @@ export async function setPRFileViewed(args: {
repoPath: string
connectionId?: string | null
localGitOptions?: LocalGitExecOptions
prRepo?: GitHubApiRepository | null
pullRequestId: string
path: string
viewed: boolean
}): Promise<boolean> {
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
args.repoPath,
undefined,
args.prRepo,
args.connectionId,
args.localGitOptions
)
@@ -4503,13 +4534,14 @@ export async function resolveReviewThread(
threadId: string,
resolve: boolean,
connectionId?: string | null,
prRepo?: GitHubApiRepository | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<boolean> {
const mutation = resolve ? 'resolveReviewThread' : 'unresolveReviewThread'
const query = `mutation($threadId: ID!) { ${mutation}(input: { threadId: $threadId }) { thread { isResolved } } }`
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
repoPath,
undefined,
prRepo,
connectionId,
localGitOptions
)
@@ -4628,7 +4660,7 @@ export async function addPRReviewComment(
): Promise<GitHubCommentResult> {
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
args.repoPath,
undefined,
args.prRepo,
args.connectionId,
args.localGitOptions
)
@@ -4956,11 +4988,12 @@ export async function updatePRState(
prNumber: number,
updates: GitHubPullRequestStateUpdate,
connectionId?: string | null,
prRepo?: GitHubApiRepository | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true } | { ok: false; error: string }> {
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
repoPath,
undefined,
prRepo,
connectionId,
localGitOptions
)
@@ -4994,6 +5027,7 @@ export async function requestPRReviewers(
prNumber: number,
reviewers: string[],
connectionId?: string | null,
prRepo?: GitHubApiRepository | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true } | { ok: false; error: string }> {
const logins = reviewers.map((reviewer) => reviewer.trim()).filter(Boolean)
@@ -5002,7 +5036,7 @@ export async function requestPRReviewers(
}
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
repoPath,
undefined,
prRepo,
connectionId,
localGitOptions
)
@@ -5034,6 +5068,7 @@ export async function removePRReviewers(
prNumber: number,
reviewers: string[],
connectionId?: string | null,
prRepo?: GitHubApiRepository | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<{ ok: true } | { ok: false; error: string }> {
const logins = reviewers.map((reviewer) => reviewer.trim()).filter(Boolean)
@@ -5042,7 +5077,7 @@ export async function removePRReviewers(
}
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
repoPath,
undefined,
prRepo,
connectionId,
localGitOptions
)
+60 -2
View File
@@ -1,6 +1,24 @@
import { describe, expect, it } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as GitHubEnterpriseRepository from './github-enterprise-repository'
import { githubHostExecOptions, resolveGitHubRepoExecution } from './github-api-repository'
const { isGitHubHostAuthenticatedMock } = vi.hoisted(() => ({
isGitHubHostAuthenticatedMock: vi.fn()
}))
vi.mock('./github-enterprise-repository', async (importOriginal) => ({
...(await importOriginal<typeof GitHubEnterpriseRepository>()),
isGitHubHostAuthenticated: isGitHubHostAuthenticatedMock
}))
import {
githubHostExecOptions,
resolveGitHubApiRepository,
resolveGitHubRepoExecution
} from './github-api-repository'
beforeEach(() => {
isGitHubHostAuthenticatedMock.mockReset().mockResolvedValue(false)
})
describe('githubHostExecOptions', () => {
it('pins every known repository host', () => {
@@ -21,6 +39,7 @@ describe('githubHostExecOptions', () => {
describe('resolveGitHubRepoExecution', () => {
it('combines local repository and GitHub host execution options', async () => {
const ownerRepo = { owner: 'acme', repo: 'widgets', host: 'github.acme-corp.com' }
isGitHubHostAuthenticatedMock.mockResolvedValue(true)
await expect(
resolveGitHubRepoExecution('/repo', ownerRepo, null, { wslDistro: 'Ubuntu' })
@@ -32,6 +51,45 @@ describe('resolveGitHubRepoExecution', () => {
host: 'github.acme-corp.com'
}
})
expect(isGitHubHostAuthenticatedMock).toHaveBeenCalledWith(
'github.acme-corp.com',
'/repo',
null,
{ wslDistro: 'Ubuntu' }
)
})
it('rejects an explicit Enterprise host absent from the local gh auth inventory', async () => {
await expect(
resolveGitHubApiRepository(
'/remote/repo',
{
owner: 'acme',
repo: 'widgets',
host: 'evil.example.test'
},
'ssh-1'
)
).resolves.toBeNull()
expect(isGitHubHostAuthenticatedMock).toHaveBeenCalledWith(
'evil.example.test',
'/remote/repo',
'ssh-1',
{}
)
})
it('normalizes github.com without spending an auth inventory probe', async () => {
await expect(
resolveGitHubApiRepository('/repo', {
owner: 'acme',
repo: 'widgets',
host: ' GitHub.COM '
})
).resolves.toEqual({ owner: 'acme', repo: 'widgets', host: 'github.com' })
expect(isGitHubHostAuthenticatedMock).not.toHaveBeenCalled()
})
it('uses a caller-specific repository resolver without changing its identity', async () => {
+18 -2
View File
@@ -11,7 +11,8 @@ import {
} from './gh-utils'
import {
getEnterpriseGitHubRepoSlug,
getEnterpriseGitHubRepoSlugForRemote
getEnterpriseGitHubRepoSlugForRemote,
isGitHubHostAuthenticated
} from './github-enterprise-repository'
export type GitHubApiRepository = GitHubOwnerRepo
@@ -241,7 +242,22 @@ export async function resolveGitHubApiRepository(
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubApiRepository | null> {
if (repository?.host) {
return repository
const host = repository.host.trim().toLowerCase()
if (!host) {
return null
}
if (isDefaultGitHubHost(host)) {
return { ...repository, host }
}
// Why: client-supplied hosts must match gh's local auth inventory before
// they can receive ambient Enterprise credentials from a host-pinned call.
const authenticated = await isGitHubHostAuthenticated(
host,
repoPath,
connectionId,
localGitOptions
)
return authenticated ? { ...repository, host } : null
}
const originRepository = await getOriginGitHubApiRepository(
repoPath,
@@ -15,7 +15,8 @@ vi.mock('../git/runner', () => ({
import {
_resetGitHubHostAuthCache,
getEnterpriseGitHubRepoSlug,
isGitHubHostAuthenticated
isGitHubHostAuthenticated,
isGitHubHostAuthenticatedForGlobalCli
} from './github-enterprise-repository'
function mockOriginRemote(url: string): void {
@@ -61,12 +62,9 @@ describe('getEnterpriseGitHubRepoSlug', () => {
repo: 'orca',
host: 'github.acme-corp.com'
})
// The auth probe targets the remote's host, not a hardcoded github.com, and
// scopes any breaker trip to that host via the exec options.
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
['auth', 'status', '--hostname', 'github.acme-corp.com'],
{ cwd: '/repo', host: 'github.acme-corp.com' }
)
// Why: inventory configured gh hosts without targeting the untrusted remote;
// passing it as --hostname could expose an ambient enterprise token.
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], { cwd: '/repo' })
})
it('resolves a GHES SCP-style SSH remote', async () => {
@@ -88,10 +86,10 @@ describe('getEnterpriseGitHubRepoSlug', () => {
localGitExecOptions: { wslDistro: 'Ubuntu' }
})
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
['auth', 'status', '--hostname', 'github.acme-corp.com'],
{ cwd: '/repo', wslDistro: 'Ubuntu', host: 'github.acme-corp.com' }
)
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], {
cwd: '/repo',
wslDistro: 'Ubuntu'
})
})
it('leaves github.com to getOwnerRepo without probing gh auth', async () => {
@@ -136,10 +134,7 @@ describe('isGitHubHostAuthenticated', () => {
await expect(
isGitHubHostAuthenticated('github.acme-corp.com', '/remote/repo', 'ssh-1')
).resolves.toBe(true)
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
['auth', 'status', '--hostname', 'github.acme-corp.com'],
{ host: 'github.acme-corp.com' }
)
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], {})
})
it('caches per runtime+host so detection polling does not re-spawn gh', async () => {
@@ -155,7 +150,12 @@ describe('isGitHubHostAuthenticated', () => {
ghExecFileAsyncMock.mockImplementation(
() =>
new Promise((resolve) => {
finishProbe = () => resolve({ stdout: '', stderr: '' })
finishProbe = () =>
resolve({
stdout:
'github.acme-corp.com\n ✓ Logged in to github.acme-corp.com account kelora (keyring)',
stderr: ''
})
})
)
@@ -175,6 +175,66 @@ describe('isGitHubHostAuthenticated', () => {
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2)
})
it('derives cache scope from an implicit WSL UNC repository path', async () => {
const originalPlatform = process.platform
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
ghExecFileAsyncMock.mockImplementation(async (_args: string[], options: { cwd?: string }) => ({
stdout: options.cwd?.includes('Ubuntu')
? 'github.com\n ✓ Logged in to github.com account other (keyring)'
: 'github.acme-corp.com\n ✓ Logged in to github.acme-corp.com account kelora (keyring)',
stderr: ''
}))
try {
await expect(isGitHubHostAuthenticated('github.acme-corp.com', '/native/repo')).resolves.toBe(
true
)
await expect(
isGitHubHostAuthenticated(
'github.acme-corp.com',
String.raw`\\wsl.localhost\Ubuntu\home\me\repo`
)
).resolves.toBe(false)
await expect(
isGitHubHostAuthenticated(
'github.acme-corp.com',
String.raw`\\wsl.localhost\Debian\home\me\repo`
)
).resolves.toBe(true)
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(3)
} finally {
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
}
})
it('shares the native gh auth probe across SSH connections', async () => {
mockHostAuthenticated()
await isGitHubHostAuthenticated('github.acme-corp.com', '/remote/a', 'ssh-1')
await isGitHubHostAuthenticated('github.acme-corp.com', '/remote/b', 'ssh-2')
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
})
it('does not target an unconfigured remote host with ambient credentials', async () => {
mockHostAuthenticated('github.acme-corp.com')
await expect(isGitHubHostAuthenticated('evil.example.test', '/repo')).resolves.toBe(false)
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], { cwd: '/repo' })
expect(ghExecFileAsyncMock.mock.calls.flat()).not.toContain('evil.example.test')
})
it('validates a global project host by inventory without targeting it', async () => {
mockHostAuthenticated('github.acme-corp.com')
await expect(isGitHubHostAuthenticatedForGlobalCli('evil.example.test')).resolves.toBe(false)
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], {})
expect(ghExecFileAsyncMock.mock.calls.flat()).not.toContain('evil.example.test')
})
it('treats a listed host as authenticated even when gh exits non-zero', async () => {
ghExecFileAsyncMock.mockRejectedValue(
Object.assign(new Error('exit 1'), {
+22 -18
View File
@@ -12,6 +12,7 @@ import {
parseGitHubRemoteIdentity,
type LocalGitExecOptions
} from './github-repository-identity'
import { parseWslPath } from '../wsl'
export type GitHubEnterpriseRepoSlug = GitHubOwnerRepo & { host: string }
@@ -30,12 +31,11 @@ type HostAuthCacheEntry = {
const hostAuthCache = new Map<string, HostAuthCacheEntry>()
const hostAuthInFlight = new Map<string, Promise<boolean>>()
// Why: gh's authenticated hosts live in per-runtime config — a WSL distro and an
// SSH host each carry their own `hosts.yml` — so cache state must be keyed by the
// runtime that executes gh, not shared under one "local" bucket. Mirrors the
// runtime scoping used by owner/repo resolution.
function runtimeCacheKey(connectionId?: string | null, wslDistro?: string): string {
return connectionId ?? `local:${wslDistro ?? 'host'}`
// Why: connection-backed Git operations execute remotely, but gh intentionally
// executes on the native host. Only WSL selects a distinct gh config/runtime.
function runtimeCacheKey(repoPath: string, wslDistro?: string): string {
const resolvedDistro = wslDistro ?? parseWslPath(repoPath)?.distro
return `local:${resolvedDistro?.toLowerCase() ?? 'host'}`
}
/** @internal - exposed for tests only */
@@ -78,11 +78,10 @@ function ghCommandOutput(error: unknown): string {
/**
* Whether `gh` is authenticated to `host` from the repository's own runtime.
*
* The probe runs `gh auth status --hostname <host>` with the repo's execution
* options (cwd / WSL distro, or SSH-local like the create path), so a GHES login
* stored only in that runtime's gh config — or a `GH_ENTERPRISE_TOKEN` inferred
* from it — is honored instead of the host/default-distro gh. Cached briefly per
* runtime+host so provider-detection polling does not re-spawn gh each time.
* The probe inventories gh's configured hosts and matches `host` locally. It
* deliberately does not pass an untrusted remote host to gh because ambient
* enterprise tokens could otherwise be sent to that host during validation.
* Cached briefly per runtime+host so provider-detection polling stays cheap.
*/
export async function isGitHubHostAuthenticated(
host: string,
@@ -91,7 +90,7 @@ export async function isGitHubHostAuthenticated(
localGitOptions: LocalGitExecOptions = {}
): Promise<boolean> {
const normalizedHost = host.toLowerCase()
const cacheKey = `${runtimeCacheKey(connectionId, localGitOptions.wslDistro)}\0${normalizedHost}`
const cacheKey = `${runtimeCacheKey(repoPath, localGitOptions.wslDistro)}\0${normalizedHost}`
const now = Date.now()
pruneHostAuthCache(now)
const cached = hostAuthCache.get(cacheKey)
@@ -106,15 +105,14 @@ export async function isGitHubHostAuthenticated(
// once; coalesce them so one host never spawns duplicate auth subprocesses.
const probe = (async () => {
const execOptions = {
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
// Why: scope any rate-limit breaker trip from this probe to the probed
// host, not to gh's default account.
host: normalizedHost
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
}
let authenticated: boolean
try {
await ghExecFileAsync(['auth', 'status', '--hostname', normalizedHost], execOptions)
authenticated = true
const { stdout, stderr } = await ghExecFileAsync(['auth', 'status'], execOptions)
authenticated = parseAuthStatus(`${stdout}\n${stderr}`).some(
(account) => account.host.toLowerCase() === normalizedHost
)
} catch (error) {
const output = ghCommandOutput(error)
if (!output) {
@@ -142,6 +140,12 @@ export async function isGitHubHostAuthenticated(
}
}
/** Safely validate a project-selected host without giving the untrusted host
* to gh. Global project calls have no repository cwd, so they use native gh. */
export function isGitHubHostAuthenticatedForGlobalCli(host: string): Promise<boolean> {
return isGitHubHostAuthenticated(host, '', 'project-host-validation')
}
/**
* Resolve owner/repo for a GitHub Enterprise Server remote — a custom host the
* user is gh-authenticated to. Returns null for github.com (already handled by
+26 -4
View File
@@ -2,6 +2,7 @@
request timestamps, and follow-up scheduling against shared module state. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { GitHubPRRefreshCandidate, PRInfo } from '../../shared/types'
import { isWslUncPath } from '../../shared/wsl-paths'
const {
sendMock,
@@ -117,8 +118,10 @@ describe('pr-refresh-coordinator', () => {
repositoryRateLimitGuardMock.mockReturnValue({ blocked: false })
spendsSharedGitHubComQuotaMock.mockReset()
spendsSharedGitHubComQuotaMock.mockImplementation(
(repository: { host?: string } | null, options?: { wslDistro?: string }) =>
(!repository?.host || repository.host.toLowerCase() === 'github.com') && !options?.wslDistro
(repository: { host?: string } | null, options?: { cwd?: string; wslDistro?: string }) =>
(!repository?.host || repository.host.toLowerCase() === 'github.com') &&
!options?.wslDistro &&
!(options?.cwd && isWslUncPath(options.cwd))
)
getAllWebContentsMock.mockReturnValue([
{
@@ -596,12 +599,20 @@ describe('pr-refresh-coordinator', () => {
{
scope: 'GitHub Enterprise',
repository: { owner: 'acme', repo: 'widgets', host: 'github.acme-corp.com' },
repoPath: '/repo',
localGitOptions: undefined
},
{
scope: 'WSL',
repository: { owner: 'acme', repo: 'widgets', host: 'github.com' },
repoPath: '/repo',
localGitOptions: { wslDistro: 'Ubuntu' }
},
{
scope: 'implicit WSL UNC',
repository: { owner: 'acme', repo: 'widgets', host: 'github.com' },
repoPath: String.raw`\\wsl.localhost\Ubuntu\home\me\widgets`,
localGitOptions: undefined
}
])('bypasses the shared budget for $scope background refreshes', async (testCase) => {
const { enqueuePRRefresh } = await import('./pr-refresh-coordinator')
@@ -610,9 +621,20 @@ describe('pr-refresh-coordinator', () => {
kind: 'no-pr',
fetchedAt: Date.now()
})
const executionOptions = testCase.localGitOptions ?? {}
const executionOptions = {
cwd: testCase.repoPath,
...testCase.localGitOptions
}
enqueuePRRefresh(makeCandidate({ localGitOptions: testCase.localGitOptions }), 'active', 80, 1)
enqueuePRRefresh(
makeCandidate({
repoPath: testCase.repoPath,
localGitOptions: testCase.localGitOptions
}),
'active',
80,
1
)
await vi.advanceTimersByTimeAsync(0)
+7 -1
View File
@@ -772,7 +772,13 @@ async function drainQueue(): Promise<void> {
)
if (isBackground(next.reason)) {
const executionOptions = next.candidate.localGitOptions ?? {}
const executionOptions = ghRepoExecOptions(
githubRepoContext(
next.candidate.repoPath,
next.candidate.connectionId,
next.candidate.localGitOptions
)
)
const repository = await getOriginGitHubApiRepository(
next.candidate.repoPath,
next.candidate.connectionId,
@@ -0,0 +1,93 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
acquireMock,
releaseMock,
ghExecFileAsyncMock,
hostAuthenticatedMock,
noteRepositoryRateLimitSpendMock
} = vi.hoisted(() => ({
acquireMock: vi.fn(),
releaseMock: vi.fn(),
ghExecFileAsyncMock: vi.fn(),
hostAuthenticatedMock: vi.fn(),
noteRepositoryRateLimitSpendMock: vi.fn()
}))
vi.mock('./gh-utils', () => ({
acquire: acquireMock,
release: releaseMock
}))
vi.mock('../git/runner', () => ({
extractExecError: vi.fn(() => ({ stdout: '', stderr: '' })),
ghExecFileAsync: ghExecFileAsyncMock
}))
vi.mock('./rate-limit', () => ({
rateLimitGuard: vi.fn(() => ({ blocked: false })),
noteRateLimitSpend: vi.fn(),
repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })),
noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock
}))
vi.mock('./github-enterprise-repository', () => ({
isGitHubHostAuthenticatedForGlobalCli: hostAuthenticatedMock
}))
import { runGraphql, runRest } from './project-view/internals'
describe('project view host authentication boundary', () => {
beforeEach(() => {
acquireMock.mockReset().mockResolvedValue(undefined)
releaseMock.mockReset()
ghExecFileAsyncMock.mockReset()
hostAuthenticatedMock.mockReset()
noteRepositoryRateLimitSpendMock.mockReset()
})
it('does not send GraphQL or REST requests to an unconfigured host', async () => {
hostAuthenticatedMock.mockResolvedValue(false)
const [graphql, rest] = await Promise.all([
runGraphql('query { viewer { login } }', {}, { host: 'evil.example.test' }),
runRest(['user'], undefined, 'core', { host: 'evil.example.test' })
])
expect(graphql).toMatchObject({ ok: false, error: { type: 'auth_required' } })
expect(rest).toMatchObject({ ok: false, error: { type: 'auth_required' } })
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
expect(acquireMock).not.toHaveBeenCalled()
expect(noteRepositoryRateLimitSpendMock).not.toHaveBeenCalled()
})
it('routes a configured Enterprise request to its selected host', async () => {
hostAuthenticatedMock.mockResolvedValue(true)
ghExecFileAsyncMock.mockResolvedValue({
stdout: '{"data":{"viewer":{"login":"me"}}}',
stderr: ''
})
await expect(
runGraphql('query { viewer { login } }', {}, { host: 'github.corp.example' })
).resolves.toMatchObject({ ok: true })
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(expect.any(Array), {
encoding: 'utf-8',
host: 'github.corp.example'
})
})
it('keeps github.com fast and never probes it as Enterprise', async () => {
ghExecFileAsyncMock.mockResolvedValue({
stdout: '{"data":{"viewer":{"login":"me"}}}',
stderr: ''
})
await expect(
runGraphql('query { viewer { login } }', {}, { host: 'github.com' })
).resolves.toMatchObject({ ok: true })
expect(hostAuthenticatedMock).not.toHaveBeenCalled()
})
})
+7
View File
@@ -176,6 +176,13 @@ describe('parseProjectPaste', () => {
).toEqual({ kind: 'org', owner: 'acme', number: 7 })
})
it('rejects credentials and paths that only begin like a Project URL', () => {
expect(parseProjectPaste('https://user:token@github.com/orgs/acme/projects/1')).toBeNull()
expect(parseProjectPaste('https://github.com/orgs/acme/projects/1evil')).toBeNull()
expect(parseProjectPaste('https://github.com/orgs/acme/projects/1/views/2evil')).toBeNull()
expect(parseProjectPaste('https://github.com/orgs/acme/projects/1/files')).toBeNull()
})
it('returns null for empty input', () => {
expect(parseProjectPaste('')).toBeNull()
expect(parseProjectPaste(' ')).toBeNull()
+34 -19
View File
@@ -15,6 +15,7 @@ import {
isValidOwnerSlug,
assertSlug,
assertPositiveInt,
projectHostAuthenticationError,
projectGhExecOptions,
type GraphqlVars
} from './project-view/internals'
@@ -887,6 +888,10 @@ async function fetchItemsPageWithRaw(args: {
stderr: string
}
> {
const authError = await projectHostAuthenticationError(args.host)
if (authError) {
return { ok: false, error: authError, rawErrors: [], stderr: '' }
}
const root = ownerQueryRoot(args.ownerType)
const afterArg = args.after ? `, after: $after` : ''
const afterVar = args.after ? `$after:String!, ` : ''
@@ -1619,32 +1624,42 @@ export function parseProjectPaste(input: string, host?: string): ParsedPaste | n
if (isGitHubProjectRefInputTooLarge(trimmed)) {
return null
}
// URL forms. Why: GHES project URLs live on the enterprise host — accept it
// alongside github.com when the caller supplies one.
const escapedHost = host ? host.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : null
const urlRe = new RegExp(
`^https?://(?:github\\.com${escapedHost ? `|${escapedHost}` : ''})/(orgs|users)/([^/]+)/projects/(\\d+)(?:/views/(\\d+))?`,
'i'
)
const m = trimmed.match(urlRe)
if (m) {
const [, kindSeg, owner, nStr, vStr] = m
const number = Number.parseInt(nStr, 10)
if (!Number.isInteger(number) || number < 1) {
// Why: URL parsing enforces an exact Project path and rejects credentials;
// a prefix regex could silently turn `/projects/1evil` into Project 1.
try {
const url = new URL(trimmed)
const allowedHosts = new Set(['github.com', ...(host ? [host.trim().toLowerCase()] : [])])
const parts = url.pathname.split('/').filter(Boolean)
const hasView = parts.length === 6 && parts[4] === 'views'
if (
(url.protocol !== 'https:' && url.protocol !== 'http:') ||
url.username ||
url.password ||
!allowedHosts.has(url.host.toLowerCase()) ||
(parts[0] !== 'orgs' && parts[0] !== 'users') ||
!isValidOwnerSlug(parts[1]) ||
parts[2] !== 'projects' ||
(parts.length !== 4 && !hasView)
) {
return null
}
if (!isValidOwnerSlug(owner)) {
const number = Number(parts[3])
const viewNumber = hasView ? Number(parts[5]) : undefined
if (
!Number.isSafeInteger(number) ||
number < 1 ||
(hasView && (!Number.isSafeInteger(viewNumber) || (viewNumber ?? 0) < 1))
) {
return null
}
const viewNumber = vStr ? Number.parseInt(vStr, 10) : undefined
return {
kind: kindSeg === 'orgs' ? 'org' : 'user',
owner,
kind: parts[0] === 'orgs' ? 'org' : 'user',
owner: parts[1],
number,
...(viewNumber !== undefined && Number.isInteger(viewNumber) && viewNumber >= 1
? { viewNumber }
: {})
...(viewNumber !== undefined ? { viewNumber } : {})
}
} catch {
// Shorthand parsing below remains available for non-URL input.
}
// owner/number shorthand — owner alphabet matches OWNER_SLUG_RE.
const shortRe = /^([A-Za-z0-9][A-Za-z0-9-]*)\/(\d+)$/
+28
View File
@@ -13,6 +13,8 @@ import {
} from '../rate-limit'
import type { GitHubProjectViewError } from '../../../shared/github-project-types'
import { githubProjectHost } from '../../../shared/github-project-identity'
import { isDefaultGitHubHost } from '../../../shared/github-repository-identity-key'
import { isGitHubHostAuthenticatedForGlobalCli } from '../github-enterprise-repository'
import {
classifyProjectError,
driftError,
@@ -42,6 +44,24 @@ export function projectGhExecOptions(host: string | undefined): ProjectGhExecOpt
return { host: githubProjectHost(host) }
}
export async function projectHostAuthenticationError(
host: string | undefined
): Promise<GitHubProjectViewError | null> {
const selectedHost = githubProjectHost(host)
if (
isDefaultGitHubHost(selectedHost) ||
(await isGitHubHostAuthenticatedForGlobalCli(selectedHost))
) {
return null
}
// Why: never target an unconfigured pasted host with gh; ambient
// GH_ENTERPRISE_TOKEN credentials could otherwise be sent to that server.
return {
type: 'auth_required',
message: `GitHub CLI is not authenticated to ${selectedHost}. Run gh auth login --hostname ${selectedHost}.`
}
}
// ─── Slug validation ──────────────────────────────────────────────────
// Why: GitHub usernames/org logins disallow `_`, `.`, leading `-`. Repo names
@@ -132,6 +152,10 @@ export async function runGraphql<T>(
| { ok: true; data: T }
| { ok: false; error: GitHubProjectViewError; raw: { stderr: string; stdout: string } }
> {
const authError = await projectHostAuthenticationError(exec?.host)
if (authError) {
return { ok: false, error: authError, raw: { stderr: '', stdout: '' } }
}
// Why: GHES traffic runs against its own quota — only github.com requests
// consult/debit the shared snapshot.
const guard = repositoryRateLimitGuard({ host: exec?.host }, 'graphql')
@@ -203,6 +227,10 @@ export async function runRest<T>(
bucket: RateLimitBucketKind = 'core',
options?: { expectEmpty?: boolean; host?: string }
): Promise<{ ok: true; data: T } | { ok: false; error: GitHubProjectViewError }> {
const authError = await projectHostAuthenticationError(options?.host)
if (authError) {
return { ok: false, error: authError }
}
// Why: GHES traffic runs against its own quota — only github.com requests
// consult/debit the shared snapshot.
const guard = repositoryRateLimitGuard({ host: options?.host }, bucket)
+77 -11
View File
@@ -1,14 +1,24 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { acquireMock, ghExecFileAsyncMock, releaseMock, runGraphqlMock, runRestMock } = vi.hoisted(
() => ({
acquireMock: vi.fn(),
ghExecFileAsyncMock: vi.fn(),
releaseMock: vi.fn(),
runGraphqlMock: vi.fn(),
runRestMock: vi.fn()
})
)
const {
acquireMock,
ghExecFileAsyncMock,
noteRepositoryRateLimitSpendMock,
projectHostAuthenticationErrorMock,
repositoryRateLimitGuardMock,
releaseMock,
runGraphqlMock,
runRestMock
} = vi.hoisted(() => ({
acquireMock: vi.fn(),
ghExecFileAsyncMock: vi.fn(),
noteRepositoryRateLimitSpendMock: vi.fn(),
projectHostAuthenticationErrorMock: vi.fn(),
repositoryRateLimitGuardMock: vi.fn(),
releaseMock: vi.fn(),
runGraphqlMock: vi.fn(),
runRestMock: vi.fn()
}))
vi.mock('./internals', () => ({
acquire: acquireMock,
@@ -20,8 +30,9 @@ vi.mock('./internals', () => ({
ghExecFileAsync: ghExecFileAsyncMock,
rateLimitGuard: () => ({ blocked: false }),
noteRateLimitSpend: vi.fn(),
repositoryRateLimitGuard: () => ({ blocked: false }),
noteRepositoryRateLimitSpend: vi.fn(),
repositoryRateLimitGuard: repositoryRateLimitGuardMock,
noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock,
projectHostAuthenticationError: projectHostAuthenticationErrorMock,
projectGhExecOptions: (host?: string) => (host ? { host } : {}),
classifyProjectError: (stderr: string) => ({ type: 'unknown', message: stderr }),
rateLimitedError: () => ({ type: 'rate_limited', message: 'rate limited' }),
@@ -41,6 +52,9 @@ describe('updateIssueBySlug', () => {
beforeEach(() => {
acquireMock.mockReset().mockResolvedValue(undefined)
ghExecFileAsyncMock.mockReset().mockResolvedValue({ stdout: '', stderr: '' })
noteRepositoryRateLimitSpendMock.mockReset()
projectHostAuthenticationErrorMock.mockReset().mockResolvedValue(null)
repositoryRateLimitGuardMock.mockReset().mockReturnValue({ blocked: false })
releaseMock.mockReset()
runRestMock.mockReset().mockResolvedValue({ ok: true, data: {} })
})
@@ -76,6 +90,58 @@ describe('updateIssueBySlug', () => {
expect(runRestMock).not.toHaveBeenCalled()
})
it('rejects an unconfigured Enterprise host before spawning gh', async () => {
projectHostAuthenticationErrorMock.mockResolvedValue({
type: 'auth_required',
message: 'GitHub host is not authenticated'
})
await expect(
updateIssueBySlug({
owner: 'acme',
repo: 'widgets',
host: 'evil.example.test',
number: 12,
updates: { state: 'closed' }
})
).resolves.toMatchObject({ ok: false, error: { type: 'auth_required' } })
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
expect(runRestMock).not.toHaveBeenCalled()
})
it('guards and accounts state mutations in the selected host quota scope', async () => {
const args = {
owner: 'acme',
repo: 'widgets',
host: 'github.corp.example',
number: 12,
updates: { state: 'closed' as const }
}
await expect(updateIssueBySlug(args)).resolves.toEqual({ ok: true })
expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith(args, 'core')
expect(noteRepositoryRateLimitSpendMock).toHaveBeenCalledWith(args, 'core')
})
it('does not spawn a state mutation while that host quota is blocked', async () => {
repositoryRateLimitGuardMock.mockReturnValue({ blocked: true })
await expect(
updateIssueBySlug({
owner: 'acme',
repo: 'widgets',
host: 'github.corp.example',
number: 12,
updates: { state: 'closed' }
})
).resolves.toMatchObject({ ok: false, error: { type: 'rate_limited' } })
expect(noteRepositoryRateLimitSpendMock).not.toHaveBeenCalled()
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
})
it('closes slug-addressed duplicate issues with --duplicate-of', async () => {
await expect(
updateIssueBySlug({
+18
View File
@@ -12,6 +12,7 @@ import {
runRest,
validateSlugArgs,
assertPositiveInt,
projectHostAuthenticationError,
projectGhExecOptions,
type GraphqlVars
} from './internals'
@@ -216,6 +217,10 @@ export async function updateIssueBySlug(
return { ok: false, error: duplicate.error }
}
}
const authError = await projectHostAuthenticationError(args.host)
if (authError) {
return { ok: false, error: authError }
}
// Title/body go through PATCH /repos/{owner}/{repo}/issues/{n}.
// State uses gh issue close/reopen so duplicate closes can record a target.
@@ -223,6 +228,10 @@ export async function updateIssueBySlug(
const base = `repos/${args.owner}/${args.repo}/issues/${args.number}`
if (state !== undefined) {
const guard = repositoryRateLimitGuard(args, 'core')
if (guard.blocked) {
return { ok: false, error: rateLimitedError(guard) }
}
const stateArgs =
state === 'closed'
? ['issue', 'close', String(args.number), '--repo', `${args.owner}/${args.repo}`]
@@ -237,6 +246,7 @@ export async function updateIssueBySlug(
}
}
await acquire()
noteRepositoryRateLimitSpend(args, 'core')
try {
await ghExecFileAsync(stateArgs, { encoding: 'utf-8', ...githubHostExecOptions(args) })
} catch (err) {
@@ -522,6 +532,10 @@ export async function listLabelsBySlug(
if (!v.ok) {
return v
}
const authError = await projectHostAuthenticationError(args.host)
if (authError) {
return { ok: false, error: authError }
}
const guard = repositoryRateLimitGuard(args, 'core')
if (guard.blocked) {
return { ok: false, error: rateLimitedError(guard) }
@@ -557,6 +571,10 @@ export async function listAssignableUsersBySlug(
if (!v.ok) {
return v
}
const authError = await projectHostAuthenticationError(args.host)
if (authError) {
return { ok: false, error: authError }
}
// Seed logins merge after the fetch so callers can include currently-visible
// assignees even if the repo participant search is sparse.
const result: GitHubAssignableUser[] = []
@@ -0,0 +1,147 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
acquireMock,
releaseMock,
ghExecFileAsyncMock,
getWorkItemMock,
getPRCommentsMock,
getPRChecksMock
} = vi.hoisted(() => ({
acquireMock: vi.fn<() => Promise<void>>(),
releaseMock: vi.fn(),
ghExecFileAsyncMock: vi.fn(),
getWorkItemMock: vi.fn(),
getPRCommentsMock: vi.fn(),
getPRChecksMock: vi.fn()
}))
vi.mock('./gh-utils', () => ({
acquire: acquireMock,
release: releaseMock,
ghExecFileAsync: ghExecFileAsyncMock,
ghRepoExecOptions: (context: { repoPath: string }) => ({ cwd: context.repoPath }),
githubRepoContext: (repoPath: string, connectionId?: string | null) => ({
repoPath,
connectionId: connectionId ?? null
})
}))
vi.mock('./client', () => ({
getWorkItem: getWorkItemMock,
getPRComments: getPRCommentsMock,
getPRChecks: getPRChecksMock
}))
vi.mock('./github-api-repository', () => ({
getIssueGitHubApiRepository: vi.fn(),
getOriginGitHubApiRepository: vi.fn(),
githubHostExecOptions: (repository?: { host?: string } | null) =>
repository?.host ? { host: repository.host } : {},
resolveGitHubRepoExecution: vi.fn()
}))
vi.mock('./rate-limit', () => ({
repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })),
noteRepositoryRateLimitSpend: vi.fn()
}))
import { getWorkItemDetails } from './work-item-details'
describe('getWorkItemDetails concurrency', () => {
beforeEach(() => {
let running = 0
const queue: (() => void)[] = []
acquireMock.mockReset()
acquireMock.mockImplementation(() => {
if (running < 4) {
running += 1
return Promise.resolve()
}
return new Promise((resolve) =>
queue.push(() => {
running += 1
resolve()
})
)
})
releaseMock.mockReset()
releaseMock.mockImplementation(() => {
running -= 1
queue.shift()?.()
})
getWorkItemMock.mockReset()
getWorkItemMock.mockImplementation(async (_repoPath: string, number: number) => ({
id: `pr:${number}`,
type: 'pr',
number,
title: `PR ${number}`,
state: 'open',
url: `https://github.com/acme/widgets/pull/${number}`,
labels: [],
updatedAt: '2026-07-16T00:00:00Z',
author: null,
prRepo: { owner: 'acme', repo: 'widgets', host: 'github.com' }
}))
const withNestedPermit = async <T>(value: T): Promise<T> => {
await acquireMock()
try {
return value
} finally {
releaseMock()
}
}
getPRCommentsMock.mockReset()
getPRCommentsMock.mockImplementation(() => withNestedPermit([]))
getPRChecksMock.mockReset()
getPRChecksMock.mockImplementation(() => withNestedPermit([]))
ghExecFileAsyncMock.mockReset()
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
const query = args.find((arg) => arg.startsWith('query=')) ?? ''
if (query.includes('viewerViewedState')) {
return {
stdout: JSON.stringify({
data: {
repository: {
pullRequest: {
id: 'PR_id',
files: { pageInfo: { hasNextPage: false }, nodes: [] }
}
}
}
})
}
}
if (query.includes('participants')) {
return {
stdout: JSON.stringify({
data: { repository: { pullRequest: { participants: { nodes: [] } } } }
})
}
}
const endpoint = args.find((arg) => arg.startsWith('repos/')) ?? ''
if (endpoint.includes('/files?')) {
return { stdout: '[]' }
}
if (/\/pulls\/\d+$/.test(endpoint)) {
return {
stdout: JSON.stringify({ body: 'body', head: { sha: 'head' }, base: { sha: 'base' } })
}
}
return { stdout: JSON.stringify({ data: {} }) }
})
})
it('does not deadlock four concurrent PR loads on nested client permits', async () => {
const details = await Promise.all(
[1, 2, 3, 4].map((number) => getWorkItemDetails('/repo', number, 'pr'))
)
expect(details.map((detail) => detail?.item.number)).toEqual([1, 2, 3, 4])
expect(acquireMock.mock.calls.length).toBeGreaterThan(4)
expect(releaseMock).toHaveBeenCalledTimes(acquireMock.mock.calls.length)
})
})
@@ -26,8 +26,22 @@ const {
getPRCommentsMock: vi.fn(),
rateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })),
noteRateLimitSpendMock: vi.fn(),
repositoryRateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })),
noteRepositoryRateLimitSpendMock: vi.fn(),
repositoryRateLimitGuardMock: vi.fn<
(
repository: { host?: string } | null | undefined,
bucket: string,
options?: { cwd?: string; host?: string }
) => RateLimitGuardResult
>(() => ({ blocked: false })),
noteRepositoryRateLimitSpendMock:
vi.fn<
(
repository: { host?: string } | null | undefined,
bucket: string,
cost?: number,
options?: { cwd?: string; host?: string }
) => void
>(),
acquireMock: vi.fn(),
releaseMock: vi.fn()
}))
@@ -184,6 +198,21 @@ describe('getWorkItemDetails PR file viewed state', () => {
undefined,
undefined
)
expect(repositoryRateLimitGuardMock.mock.calls.length).toBeGreaterThan(0)
expect(
repositoryRateLimitGuardMock.mock.calls.every(([, bucket, options]) =>
bucket === 'graphql'
? options?.cwd === '/repo-root' && options?.host === 'github.com'
: true
)
).toBe(true)
expect(
noteRepositoryRateLimitSpendMock.mock.calls.every(([, bucket, , options]) =>
bucket === 'graphql'
? options?.cwd === '/repo-root' && options?.host === 'github.com'
: true
)
).toBe(true)
})
it('keeps PR details loadable when checks lookup fails', async () => {
@@ -5,13 +5,31 @@ const {
getOwnerRepoMock,
getWorkItemMock,
getPRChecksMock,
getPRCommentsMock
getPRCommentsMock,
noteRepositoryRateLimitSpendMock,
repositoryRateLimitGuardMock
} = vi.hoisted(() => ({
ghExecFileAsyncMock: vi.fn(),
getOwnerRepoMock: vi.fn(),
getWorkItemMock: vi.fn(),
getPRChecksMock: vi.fn(),
getPRCommentsMock: vi.fn()
getPRCommentsMock: vi.fn(),
noteRepositoryRateLimitSpendMock:
vi.fn<
(
repository: { host?: string } | null | undefined,
bucket: string,
cost?: number,
options?: { cwd?: string; host?: string }
) => void
>(),
repositoryRateLimitGuardMock: vi.fn<
(
repository: { host?: string } | null | undefined,
bucket: string,
options?: { cwd?: string; host?: string }
) => { blocked: false }
>(() => ({ blocked: false }))
}))
vi.mock('./gh-utils', () => ({
@@ -36,14 +54,15 @@ vi.mock('./client', () => ({
}))
vi.mock('./github-enterprise-repository', () => ({
getEnterpriseGitHubRepoSlug: vi.fn().mockResolvedValue(null)
getEnterpriseGitHubRepoSlug: vi.fn().mockResolvedValue(null),
isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true)
}))
vi.mock('./rate-limit', () => ({
rateLimitGuard: vi.fn(() => ({ blocked: false })),
noteRateLimitSpend: vi.fn(),
repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })),
noteRepositoryRateLimitSpend: vi.fn()
repositoryRateLimitGuard: repositoryRateLimitGuardMock,
noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock
}))
import { getWorkItemDetails } from './work-item-details'
@@ -106,6 +125,8 @@ describe('getWorkItemDetails PR file listing', () => {
getPRChecksMock.mockResolvedValue([])
getPRCommentsMock.mockReset()
getPRCommentsMock.mockResolvedValue([])
noteRepositoryRateLimitSpendMock.mockReset()
repositoryRateLimitGuardMock.mockClear()
})
it('loads files beyond the first 100-result REST page', async () => {
@@ -145,6 +166,12 @@ describe('getWorkItemDetails PR file listing', () => {
'repos/acme/widgets/pulls/108/files?per_page=100',
'repos/acme/widgets/pulls/108/files?per_page=100&page=2'
])
expect(
noteRepositoryRateLimitSpendMock.mock.calls.filter(([, bucket]) => bucket === 'core')
).toHaveLength(3)
expect(
repositoryRateLimitGuardMock.mock.calls.filter(([, bucket]) => bucket === 'core')
).toHaveLength(3)
})
// Why: a rate-limited/auth-failed file fetch must not render as an empty PR;
+19 -17
View File
@@ -65,7 +65,8 @@ vi.mock('./client', () => ({
vi.mock('./github-enterprise-repository', () => ({
getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock,
getEnterpriseGitHubRepoSlugForRemote: getEnterpriseGitHubRepoSlugForRemoteMock
getEnterpriseGitHubRepoSlugForRemote: getEnterpriseGitHubRepoSlugForRemoteMock,
isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true)
}))
vi.mock('./rate-limit', () => ({
@@ -243,19 +244,19 @@ describe('getWorkItemDetails', () => {
expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith(
{ owner: 'acme', repo: 'widgets', host: 'github.com' },
'graphql',
{}
{ cwd: '/repo-root', host: 'github.com' }
)
expect(noteRepositoryRateLimitSpendMock).toHaveBeenCalledWith(
{ owner: 'acme', repo: 'widgets', host: 'github.com' },
'graphql',
1,
{}
{ cwd: '/repo-root', host: 'github.com' }
)
})
it('scopes collapsed issue GraphQL accounting to the selected WSL runtime', async () => {
it('scopes collapsed issue GraphQL accounting to an implicit WSL UNC runtime', async () => {
const repository = { owner: 'acme', repo: 'widgets' }
const localGitOptions = { wslDistro: 'Ubuntu' }
const repoPath = String.raw`\\wsl.localhost\Ubuntu\home\me\widgets`
getWorkItemMock.mockResolvedValueOnce({
id: 'issue:923',
type: 'issue',
@@ -285,24 +286,22 @@ describe('getWorkItemDetails', () => {
})
.mockResolvedValueOnce({ stdout: '' })
const details = await getWorkItemDetails('/repo-root', 923, 'issue', null, localGitOptions)
const details = await getWorkItemDetails(repoPath, 923, 'issue')
expect(details?.body).toBe('WSL issue body')
// Why: issue identities resolve hosted, pinned to github.com for dotcom.
expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith(
{ ...repository, host: 'github.com' },
'graphql',
localGitOptions
{ cwd: repoPath, host: 'github.com' }
)
expect(noteRepositoryRateLimitSpendMock).toHaveBeenCalledWith(
{ ...repository, host: 'github.com' },
'graphql',
1,
localGitOptions
)
expect(ghExecFileAsyncMock.mock.calls.every((call) => call[1]?.wslDistro === 'Ubuntu')).toBe(
true
{ cwd: repoPath, host: 'github.com' }
)
expect(ghExecFileAsyncMock.mock.calls.every((call) => call[1]?.cwd === repoPath)).toBe(true)
})
it('enriches a non-participating assignee avatar from the GraphQL assignees connection', async () => {
@@ -321,7 +320,7 @@ describe('getWorkItemDetails', () => {
author: 'issue-author',
assignees: [{ login: 'ghe-assignee', name: 'GHE Assignee', avatarUrl: '' }]
})
getIssueOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' })
getOwnerRepoForRemoteMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' })
ghExecFileAsyncMock
.mockResolvedValueOnce({
stdout: JSON.stringify({
@@ -612,7 +611,9 @@ describe('getWorkItemDetails', () => {
expect(getWorkItemMock).toHaveBeenCalledWith('/remote/repo', 7, 'issue', 'ssh-1')
expect(getWorkItemByOwnerRepoMock).not.toHaveBeenCalled()
expect(getEnterpriseGitHubRepoSlugMock).toHaveBeenCalledTimes(1)
expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith(enterpriseRepository, 'graphql', {})
expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith(enterpriseRepository, 'graphql', {
host: 'github.acme-corp.com'
})
expect(noteRepositoryRateLimitSpendMock).toHaveBeenCalled()
expect(
ghExecFileAsyncMock.mock.calls.every(
@@ -846,13 +847,13 @@ describe('getWorkItemDetails', () => {
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
})
it('uses the GitHub Enterprise host when fetching PR file contents', async () => {
getOwnerRepoMock.mockResolvedValue(null)
getEnterpriseGitHubRepoSlugMock.mockResolvedValue({
it('uses the selected upstream GitHub Enterprise repo for both PR file sides', async () => {
getOwnerRepoMock.mockResolvedValue({ owner: 'fork', repo: 'orca' })
const prRepo = {
owner: 'team',
repo: 'orca',
host: 'github.acme-corp.com'
})
}
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
const endpoint = args.find((arg) => arg.startsWith('repos/')) ?? ''
if (endpoint === 'repos/team/orca/contents/src/path%23with%3Fchars.ts?ref=base-sha') {
@@ -866,6 +867,7 @@ describe('getWorkItemDetails', () => {
const contents = await getPRFileContents({
repoPath: '/repo-root',
prRepo,
prNumber: 7,
path: 'src/path#with?chars.ts',
status: 'modified',
+99 -68
View File
@@ -26,6 +26,7 @@ import {
getIssueGitHubApiRepository,
getOriginGitHubApiRepository,
githubHostExecOptions,
resolveGitHubRepoExecution,
type GitHubApiRepository
} from './github-api-repository'
import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-limit'
@@ -359,11 +360,11 @@ async function getIssueDetailsViaGraphQL(
if (!ownerRepo) {
return null
}
if (repositoryRateLimitGuard(ownerRepo, 'graphql', localGitOptions).blocked) {
if (repositoryRateLimitGuard(ownerRepo, 'graphql', ghOptions).blocked) {
return null
}
try {
noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, localGitOptions)
noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions)
const { stdout } = await ghExecFileAsync(
[
'api',
@@ -515,7 +516,11 @@ async function getPRMetadata(
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
...githubHostExecOptions(ownerRepo)
}
if (repositoryRateLimitGuard(ownerRepo, 'core', ghOptions).blocked) {
return { body: '' }
}
try {
noteRepositoryRateLimitSpend(ownerRepo, 'core', 1, ghOptions)
if (ownerRepo) {
const { stdout } = await ghExecFileAsync(
['api', '--cache', '60s', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${prNumber}`],
@@ -571,7 +576,11 @@ async function getPRFiles(
try {
const data: RESTPRFile[] = []
for (let page = 1; data.length < MAX_PR_FILES; page += 1) {
if (repositoryRateLimitGuard(ownerRepo, 'core', ghOptions).blocked) {
return null
}
const pageSuffix = page === 1 ? '' : `&page=${page}`
noteRepositoryRateLimitSpend(ownerRepo, 'core', 1, ghOptions)
const { stdout } = await ghExecFileAsync(
[
'api',
@@ -620,7 +629,7 @@ async function getPRFileViewedStates(
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
...githubHostExecOptions(ownerRepo)
}
if (repositoryRateLimitGuard(ownerRepo, 'graphql', localGitOptions).blocked) {
if (repositoryRateLimitGuard(ownerRepo, 'graphql', ghOptions).blocked) {
return null
}
const viewedStates = new Map<string, GitHubPRFileViewedState>()
@@ -644,7 +653,7 @@ async function getPRFileViewedStates(
if (after) {
args.push('-f', `after=${after}`)
}
noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, localGitOptions)
noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions)
const { stdout } = await ghExecFileAsync(args, ghOptions)
const parsed = JSON.parse(stdout) as {
data?: {
@@ -815,11 +824,15 @@ async function getWorkItemParticipants(
if (!ownerRepo) {
return []
}
if (repositoryRateLimitGuard(ownerRepo, 'graphql', localGitOptions).blocked) {
const ghOptions = {
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
...githubHostExecOptions(ownerRepo)
}
if (repositoryRateLimitGuard(ownerRepo, 'graphql', ghOptions).blocked) {
return []
}
try {
noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, localGitOptions)
noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions)
const { stdout } = await ghExecFileAsync(
[
'api',
@@ -835,10 +848,7 @@ async function getWorkItemParticipants(
'-F',
`isPr=${item.type === 'pr'}`
],
{
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
...githubHostExecOptions(ownerRepo)
}
ghOptions
)
const data = JSON.parse(stdout) as {
data?: {
@@ -881,7 +891,11 @@ async function getGitHubUsersByLogin(
if (uniqueLogins.length === 0) {
return []
}
const guard = repositoryRateLimitGuard(repository, 'graphql', localGitOptions)
const ghOptions = {
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
...githubHostExecOptions(repository)
}
const guard = repositoryRateLimitGuard(repository, 'graphql', ghOptions)
if (guard.blocked) {
// Why: surface the skip. Callers degrade silently to login-based avatar URLs
// (blank on GHE), so without this log "why are avatars missing" is untraceable.
@@ -897,13 +911,10 @@ async function getGitHubUsersByLogin(
)
.join('\n')
try {
noteRepositoryRateLimitSpend(repository, 'graphql', 1, localGitOptions)
noteRepositoryRateLimitSpend(repository, 'graphql', 1, ghOptions)
const { stdout } = await ghExecFileAsync(
['api', 'graphql', '-f', `query=query { ${fields} }`],
{
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
...githubHostExecOptions(repository)
}
ghOptions
)
const data = JSON.parse(stdout) as {
data?: Record<
@@ -1066,6 +1077,15 @@ async function getPRChecksForDetails(
}
}
async function withWorkItemDetailsPermit<T>(operation: () => Promise<T>): Promise<T> {
await acquire()
try {
return await operation()
} finally {
release()
}
}
export async function getWorkItemDetails(
repoPath: string,
number: number,
@@ -1090,9 +1110,8 @@ export async function getWorkItemDetails(
: (item.prRepo ??
(await getOriginGitHubApiRepository(repoPath, connectionId, localGitOptions)))
await acquire()
try {
if (item.type === 'issue') {
if (item.type === 'issue') {
return withWorkItemDetailsPermit(async () => {
// Why: try the collapsed single-GraphQL path first — body, assignees,
// participants, and comments all return in one round-trip. On any
// failure (permissions, partial errors, non-GitHub remote), strictly
@@ -1152,33 +1171,45 @@ export async function getWorkItemDetails(
participants: mentionParticipants,
timelineItems
}
}
})
}
// PR: fetch metadata + comments + files + viewed states + participants in parallel.
const [metadata, comments, files, viewedStates, participants] = await Promise.all([
getPRMetadata(repoPath, item.number, resolvedRepository, connectionId, localGitOptions),
getPRComments(
repoPath,
item.number,
{ prRepo: resolvedRepository },
connectionId,
...localGitOptionArgs(localGitOptions)
// Why: getPRComments and getPRChecks own their semaphore permits. Keeping an
// outer permit while awaiting either can deadlock four concurrent detail loads.
const [[metadata, files, viewedStates, participants], comments] = await Promise.all([
Promise.all([
withWorkItemDetailsPermit(() =>
getPRMetadata(repoPath, item.number, resolvedRepository, connectionId, localGitOptions)
),
getPRFiles(repoPath, item.number, resolvedRepository, connectionId, localGitOptions),
getPRFileViewedStates(
repoPath,
item.number,
resolvedRepository,
connectionId,
localGitOptions
withWorkItemDetailsPermit(() =>
getPRFiles(repoPath, item.number, resolvedRepository, connectionId, localGitOptions)
),
getWorkItemParticipants(repoPath, item, resolvedRepository, connectionId, localGitOptions)
])
withWorkItemDetailsPermit(() =>
getPRFileViewedStates(
repoPath,
item.number,
resolvedRepository,
connectionId,
localGitOptions
)
),
withWorkItemDetailsPermit(() =>
getWorkItemParticipants(repoPath, item, resolvedRepository, connectionId, localGitOptions)
)
]),
getPRComments(
repoPath,
item.number,
{ prRepo: resolvedRepository },
connectionId,
...localGitOptionArgs(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([
// Why: mention hydration directly spawns gh, while checks owns a permit.
// Bound the direct spawn separately so neither operation nests a permit.
const [mentionParticipants, checks] = await Promise.all([
withWorkItemDetailsPermit(() =>
getMentionParticipants(
repoPath,
item,
@@ -1187,33 +1218,31 @@ export async function getWorkItemDetails(
resolvedRepository,
connectionId,
localGitOptions
),
getPRChecksForDetails(
repoPath,
item.number,
metadata.headSha,
resolvedRepository,
connectionId,
localGitOptions
)
])
),
getPRChecksForDetails(
repoPath,
item.number,
metadata.headSha,
resolvedRepository,
connectionId,
localGitOptions
)
])
return {
item: enrichItemDisplayAvatars(item, mentionParticipants),
body: metadata.body,
comments,
headSha: metadata.headSha,
baseSha: metadata.baseSha,
pullRequestId: viewedStates?.pullRequestId,
checks,
// Why: distinguish a failed file fetch (null) from an empty PR so the
// Files tab surfaces a retry instead of "No files changed."
files: files === null ? undefined : mergePRFileViewedStates(files, viewedStates),
filesUnavailable: files === null,
participants: mentionParticipants
}
} finally {
release()
return {
item: enrichItemDisplayAvatars(item, mentionParticipants),
body: metadata.body,
comments,
headSha: metadata.headSha,
baseSha: metadata.baseSha,
pullRequestId: viewedStates?.pullRequestId,
checks,
// Why: distinguish a failed file fetch (null) from an empty PR so the
// Files tab surfaces a retry instead of "No files changed."
files: files === null ? undefined : mergePRFileViewedStates(files, viewedStates),
filesUnavailable: files === null,
participants: mentionParticipants
}
}
@@ -1267,6 +1296,7 @@ export async function getPRFileContents(args: {
repoPath: string
connectionId?: string | null
localGitOptions?: LocalGitExecOptions
prRepo?: GitHubApiRepository | null
prNumber: number
path: string
oldPath?: string
@@ -1274,8 +1304,9 @@ export async function getPRFileContents(args: {
headSha: string
baseSha: string
}): Promise<GitHubPRFileContents> {
const ownerRepo = await getOriginGitHubApiRepository(
const { ownerRepo } = await resolveGitHubRepoExecution(
args.repoPath,
args.prRepo,
args.connectionId,
args.localGitOptions
)