mirror of
https://github.com/stablyai/orca.git
synced 2026-11-17 03:15:01 +00:00
test: remove 287 low-value suites from combined audit (#42659)
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
@@ -1,155 +0,0 @@
|
||||
import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity'
|
||||
import type * as GitExecFileModule from '../../../git/command-runner/git-exec-file'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
ghExecFileAsyncMock,
|
||||
getOwnerRepoMock,
|
||||
getOwnerRepoForRemoteMock,
|
||||
getEnterpriseGitHubRepoSlugMock,
|
||||
extractExecErrorMock,
|
||||
acquireMock,
|
||||
releaseMock
|
||||
} = vi.hoisted(() => ({
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getOwnerRepoMock: vi.fn(),
|
||||
getOwnerRepoForRemoteMock: vi.fn(),
|
||||
getEnterpriseGitHubRepoSlugMock: vi.fn(),
|
||||
extractExecErrorMock: vi.fn((error: unknown) => {
|
||||
const value = error as { stderr?: string; stdout?: string; message?: string }
|
||||
return {
|
||||
stderr: value?.stderr ?? value?.message ?? '',
|
||||
stdout: value?.stdout ?? ''
|
||||
}
|
||||
}),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../execution/github-legacy-command', () => ({
|
||||
execFileAsync: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({
|
||||
ghExecFileAsync: ghExecFileAsyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../../repositories/github-owner-repo-selection', () => ({
|
||||
getOwnerRepo: getOwnerRepoMock
|
||||
}))
|
||||
|
||||
vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubRepositoryIdentityModule>()),
|
||||
getOwnerRepoForRemote: getOwnerRepoForRemoteMock,
|
||||
githubRepoContext: vi.fn((repoPath: string, connectionId?: string | null, options = {}) => ({
|
||||
...options,
|
||||
repoPath,
|
||||
connectionId: connectionId ?? null
|
||||
})),
|
||||
ghRepoExecOptions: vi.fn(
|
||||
(context: { repoPath: string; connectionId?: string | null; wslDistro?: string }) =>
|
||||
context.connectionId
|
||||
? {}
|
||||
: { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) }
|
||||
),
|
||||
_resetOwnerRepoCache: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GitExecFileModule>()),
|
||||
gitExecFileAsync: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../execution/github-operation-slots', () => ({
|
||||
acquire: acquireMock,
|
||||
release: releaseMock
|
||||
}))
|
||||
|
||||
vi.mock('../../repositories/github-enterprise-repository', () => ({
|
||||
getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock,
|
||||
isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true)
|
||||
}))
|
||||
|
||||
import { createGitHubPullRequest } from './create-github-pull-request'
|
||||
|
||||
import { _resetOriginGitHubApiRepositoryCache } from '../../repositories/github-api-repository-remote-probe'
|
||||
|
||||
beforeEach(() => {
|
||||
_resetOriginGitHubApiRepositoryCache()
|
||||
})
|
||||
|
||||
describe('createGitHubPullRequest', () => {
|
||||
beforeEach(() => {
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getOwnerRepoMock.mockReset()
|
||||
getOwnerRepoForRemoteMock.mockReset()
|
||||
// Bridge explicit-origin creation to the fixtures that define getOwnerRepoMock.
|
||||
getOwnerRepoForRemoteMock.mockImplementation(
|
||||
async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) =>
|
||||
remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null
|
||||
)
|
||||
getEnterpriseGitHubRepoSlugMock.mockReset()
|
||||
getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null)
|
||||
extractExecErrorMock.mockClear()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
acquireMock.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('returns the existing PR when gh reports an already-open pull request', async () => {
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
ghExecFileAsyncMock
|
||||
.mockRejectedValueOnce({ stderr: 'a pull request already exists for feature/existing' })
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 44,
|
||||
url: 'https://github.com/acme/widgets/pull/44'
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
await expect(
|
||||
createGitHubPullRequest(
|
||||
'/repo-root',
|
||||
{
|
||||
provider: 'github',
|
||||
base: 'main',
|
||||
head: 'refs/remotes/origin/feature/existing',
|
||||
title: 'Existing'
|
||||
},
|
||||
'local'
|
||||
)
|
||||
).resolves.toEqual({
|
||||
ok: false,
|
||||
code: 'already_exists',
|
||||
error: 'A pull request already exists for this branch.',
|
||||
reason: 'existing_review',
|
||||
existingReview: {
|
||||
number: 44,
|
||||
url: 'https://github.com/acme/widgets/pull/44'
|
||||
}
|
||||
})
|
||||
|
||||
expect(ghExecFileAsyncMock.mock.calls[1]).toEqual([
|
||||
[
|
||||
'pr',
|
||||
'list',
|
||||
'--repo',
|
||||
'acme/widgets',
|
||||
'--head',
|
||||
'feature/existing',
|
||||
'--base',
|
||||
'main',
|
||||
'--state',
|
||||
'open',
|
||||
'--limit',
|
||||
'2',
|
||||
'--json',
|
||||
'number,url'
|
||||
],
|
||||
// Pin dotcom against process-level GH_HOST.
|
||||
{ cwd: '/repo-root', host: 'github.com' }
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -1,206 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { exec, guard, spend } = vi.hoisted(() => ({ exec: vi.fn(), guard: vi.fn(), spend: vi.fn() }))
|
||||
vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({
|
||||
ghExecFileAsync: exec
|
||||
}))
|
||||
vi.mock('../../api/rate-limit', () => ({
|
||||
repositoryRateLimitGuard: guard,
|
||||
noteRepositoryRateLimitSpend: spend
|
||||
}))
|
||||
|
||||
import { detectRepositoryMergeMetadata } from './repository-merge-metadata'
|
||||
import { _resetMergeQueueCacheForTests } from './repository-merge-metadata-cache'
|
||||
|
||||
const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' }
|
||||
const options = { cwd: '/repo' }
|
||||
|
||||
function response(autoMergeAllowed: boolean): { stdout: string } {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
data: { repository: { autoMergeAllowed, mergeQueue: null, ref: { rules: { nodes: [] } } } }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
vi.stubEnv('GH_CONFIG_DIR', undefined)
|
||||
vi.stubEnv('XDG_CONFIG_HOME', undefined)
|
||||
_resetMergeQueueCacheForTests()
|
||||
guard.mockReturnValue({ blocked: false })
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('repository merge metadata reuse', () => {
|
||||
it.each([true, false])(
|
||||
'retains a successful concurrent read when a newer read fails (failure first: %s)',
|
||||
async (failureFirst) => {
|
||||
const older = Promise.withResolvers<{ stdout: string }>()
|
||||
const newer = Promise.withResolvers<{ stdout: string }>()
|
||||
exec.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise)
|
||||
const first = detectRepositoryMergeMetadata(repository, 'main', options, 'local:host')
|
||||
const second = detectRepositoryMergeMetadata(
|
||||
repository,
|
||||
'main',
|
||||
{ cwd: '/another-worktree' },
|
||||
'local:host'
|
||||
)
|
||||
if (failureFirst) {
|
||||
newer.reject(new Error('ECONNRESET'))
|
||||
await second
|
||||
older.resolve(response(true))
|
||||
await first
|
||||
} else {
|
||||
older.resolve(response(true))
|
||||
await first
|
||||
newer.reject(new Error('ECONNRESET'))
|
||||
await second
|
||||
}
|
||||
await expect(
|
||||
detectRepositoryMergeMetadata(repository, 'main', options, 'local:host')
|
||||
).resolves.toMatchObject({ autoMergeAllowed: true })
|
||||
expect(exec).toHaveBeenCalledTimes(2)
|
||||
}
|
||||
)
|
||||
|
||||
it('does not couple independent abort signals or cache an aborted result', async () => {
|
||||
const canceled = Promise.withResolvers<{ stdout: string }>()
|
||||
const surviving = Promise.withResolvers<{ stdout: string }>()
|
||||
const firstController = new AbortController()
|
||||
const secondController = new AbortController()
|
||||
exec.mockReturnValueOnce(canceled.promise).mockReturnValueOnce(surviving.promise)
|
||||
const first = detectRepositoryMergeMetadata(
|
||||
repository,
|
||||
'main',
|
||||
{ ...options, signal: firstController.signal },
|
||||
'local:host'
|
||||
)
|
||||
const second = detectRepositoryMergeMetadata(
|
||||
repository,
|
||||
'main',
|
||||
{ ...options, signal: secondController.signal },
|
||||
'local:host'
|
||||
)
|
||||
expect(exec).toHaveBeenCalledTimes(2)
|
||||
firstController.abort()
|
||||
canceled.reject(firstController.signal.reason)
|
||||
await expect(first).resolves.toMatchObject({ autoMergeAllowed: null })
|
||||
surviving.resolve(response(false))
|
||||
await expect(second).resolves.toMatchObject({ autoMergeAllowed: false })
|
||||
await expect(
|
||||
detectRepositoryMergeMetadata(repository, 'main', options, 'local:host')
|
||||
).resolves.toMatchObject({ autoMergeAllowed: false })
|
||||
expect(exec).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('retries immediately with a new signal after the only probe aborts', async () => {
|
||||
const canceled = Promise.withResolvers<{ stdout: string }>()
|
||||
const controller = new AbortController()
|
||||
exec.mockReturnValueOnce(canceled.promise).mockResolvedValueOnce(response(true))
|
||||
const first = detectRepositoryMergeMetadata(
|
||||
repository,
|
||||
'main',
|
||||
{ ...options, signal: controller.signal },
|
||||
'local:host'
|
||||
)
|
||||
controller.abort()
|
||||
canceled.reject(controller.signal.reason)
|
||||
await first
|
||||
|
||||
await expect(
|
||||
detectRepositoryMergeMetadata(
|
||||
repository,
|
||||
'main',
|
||||
{ ...options, signal: new AbortController().signal },
|
||||
'local:host'
|
||||
)
|
||||
).resolves.toMatchObject({ autoMergeAllowed: true })
|
||||
expect(exec).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('retains a surviving cache writer when a newer independent probe aborts', async () => {
|
||||
const older = Promise.withResolvers<{ stdout: string }>()
|
||||
const canceled = Promise.withResolvers<{ stdout: string }>()
|
||||
const controller = new AbortController()
|
||||
exec.mockReturnValueOnce(older.promise).mockReturnValueOnce(canceled.promise)
|
||||
const first = detectRepositoryMergeMetadata(repository, 'main', options, 'local:host')
|
||||
const second = detectRepositoryMergeMetadata(
|
||||
repository,
|
||||
'main',
|
||||
{ ...options, signal: controller.signal },
|
||||
'local:host'
|
||||
)
|
||||
controller.abort()
|
||||
canceled.reject(controller.signal.reason)
|
||||
await second
|
||||
older.resolve(response(false))
|
||||
await first
|
||||
|
||||
await expect(
|
||||
detectRepositoryMergeMetadata(repository, 'main', options, 'local:host')
|
||||
).resolves.toMatchObject({ autoMergeAllowed: false })
|
||||
expect(exec).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('does not spend quota for an already aborted probe', async () => {
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
exec.mockResolvedValue(response(true))
|
||||
|
||||
await expect(
|
||||
detectRepositoryMergeMetadata(
|
||||
repository,
|
||||
'main',
|
||||
{ ...options, signal: controller.signal },
|
||||
'local:host'
|
||||
)
|
||||
).resolves.toMatchObject({ autoMergeAllowed: null })
|
||||
expect(exec).not.toHaveBeenCalled()
|
||||
expect(spend).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps newer worktree settings when an older directory probe completes later', async () => {
|
||||
const older = Promise.withResolvers<{ stdout: string }>()
|
||||
const newer = Promise.withResolvers<{ stdout: string }>()
|
||||
exec.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise)
|
||||
const first = detectRepositoryMergeMetadata(repository, 'main', options, 'local:host')
|
||||
const second = detectRepositoryMergeMetadata(
|
||||
repository,
|
||||
'main',
|
||||
{ cwd: '/another-worktree' },
|
||||
'local:host'
|
||||
)
|
||||
|
||||
newer.resolve(response(false))
|
||||
await expect(second).resolves.toMatchObject({ autoMergeAllowed: false })
|
||||
older.resolve(response(true))
|
||||
await expect(first).resolves.toMatchObject({ autoMergeAllowed: true })
|
||||
await expect(
|
||||
detectRepositoryMergeMetadata(repository, 'main', options, 'local:host')
|
||||
).resolves.toMatchObject({ autoMergeAllowed: false })
|
||||
expect(exec).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('allows a stale successor without letting the older completion replace its cache', async () => {
|
||||
vi.useFakeTimers()
|
||||
const older = Promise.withResolvers<{ stdout: string }>()
|
||||
const newer = Promise.withResolvers<{ stdout: string }>()
|
||||
exec.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise)
|
||||
const first = detectRepositoryMergeMetadata(repository, 'main', options, 'local:host')
|
||||
vi.advanceTimersByTime(60_000)
|
||||
const second = detectRepositoryMergeMetadata(repository, 'main', options, 'local:host')
|
||||
|
||||
newer.resolve(response(false))
|
||||
await expect(second).resolves.toMatchObject({ autoMergeAllowed: false })
|
||||
older.resolve(response(true))
|
||||
await expect(first).resolves.toMatchObject({ autoMergeAllowed: true })
|
||||
await expect(
|
||||
detectRepositoryMergeMetadata(repository, 'main', options, 'local:host')
|
||||
).resolves.toMatchObject({ autoMergeAllowed: false })
|
||||
expect(exec).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -1,167 +0,0 @@
|
||||
import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { ghExecFileAsyncMock, getOwnerRepoMock, rateLimitGuardMock } = vi.hoisted(() => ({
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getOwnerRepoMock: vi.fn(),
|
||||
rateLimitGuardMock: vi.fn(() => ({ blocked: false }))
|
||||
}))
|
||||
|
||||
vi.mock('../../execution/github-legacy-command', () => ({
|
||||
execFileAsync: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({
|
||||
ghExecFileAsync: ghExecFileAsyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubRepositoryIdentityModule>()),
|
||||
githubRepoContext: (repoPath: string, connectionId?: string | null) => ({
|
||||
repoPath,
|
||||
connectionId: connectionId ?? null
|
||||
}),
|
||||
ghRepoExecOptions: (context: { repoPath: string }) => ({ cwd: context.repoPath }),
|
||||
getOwnerRepoForRemote: (
|
||||
repoPath: string,
|
||||
remoteName: string,
|
||||
connectionId?: string | null,
|
||||
localGitOptions?: unknown
|
||||
) =>
|
||||
remoteName === 'origin'
|
||||
? getOwnerRepoMock(repoPath, connectionId, localGitOptions)
|
||||
: Promise.resolve(null),
|
||||
_resetOwnerRepoCache: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../repositories/github-owner-repo-selection', () => ({
|
||||
getOwnerRepo: getOwnerRepoMock,
|
||||
resolveIssueSource: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../git/command-runner/process-capture/exec-error', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
extractExecError: vi.fn((err: unknown) => ({ stderr: String(err), stdout: '' }))
|
||||
}))
|
||||
|
||||
vi.mock('../../execution/github-operation-slots', () => ({
|
||||
acquire: vi.fn(),
|
||||
release: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../api/gh-error-classification', () => ({
|
||||
classifyGhError: (stderr: string) => ({ type: 'unknown', message: stderr }),
|
||||
classifyListIssuesError: (stderr: string) => ({ type: 'unknown', message: stderr })
|
||||
}))
|
||||
|
||||
vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
gitExecFileAsync: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../api/rate-limit', () => ({
|
||||
rateLimitGuard: rateLimitGuardMock,
|
||||
noteRateLimitSpend: vi.fn(),
|
||||
getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })),
|
||||
repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })),
|
||||
noteRepositoryRateLimitSpend: vi.fn(),
|
||||
spendsSharedGitHubComQuota: vi.fn(() => true)
|
||||
}))
|
||||
|
||||
import { getWorkItem } from './get-work-item'
|
||||
import { _resetMergeQueueCacheForTests } from '../detect/repository-merge-metadata-cache'
|
||||
import { _resetOwnerRepoCache } from '../../repositories/github-repository-identity'
|
||||
import { _resetOriginGitHubApiRepositoryCache } from '../../repositories/github-api-repository-remote-probe'
|
||||
|
||||
// Metadata and complete checks are independent provider responses.
|
||||
function mockPullRequestDetail(payload: Record<string, unknown>): void {
|
||||
const head = 'a'.repeat(40)
|
||||
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
||||
if (args[0] === 'pr' && args[1] === 'view') {
|
||||
return { stdout: JSON.stringify({ ...payload, headRefOid: head }) }
|
||||
}
|
||||
if (args.includes('graphql') && args.some((arg) => arg.includes('statusCheckRollup'))) {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
pullRequest: {
|
||||
number: payload.number,
|
||||
headRefOid: head,
|
||||
commits: {
|
||||
nodes: [
|
||||
{
|
||||
commit: {
|
||||
oid: head,
|
||||
statusCheckRollup: {
|
||||
contexts: {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these test payloads contain object rollup rows only.
|
||||
nodes: (payload.statusCheckRollup as Record<string, unknown>[]).map(
|
||||
(raw) => ({
|
||||
...raw,
|
||||
__typename:
|
||||
raw.__typename ?? (raw.state ? 'StatusContext' : 'CheckRun'),
|
||||
...(!raw.state ? { checkSuite: { databaseId: 7 } } : {})
|
||||
})
|
||||
),
|
||||
pageInfo: { hasNextPage: false, endCursor: null }
|
||||
}
|
||||
},
|
||||
checkSuites: {
|
||||
nodes: [],
|
||||
pageInfo: { hasNextPage: false, endCursor: null }
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
throw new Error('unexpected gh call')
|
||||
})
|
||||
}
|
||||
|
||||
describe('work item checksSummary', () => {
|
||||
beforeEach(() => {
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getOwnerRepoMock.mockReset()
|
||||
rateLimitGuardMock.mockReset()
|
||||
rateLimitGuardMock.mockReturnValue({ blocked: false })
|
||||
_resetOwnerRepoCache()
|
||||
_resetOriginGitHubApiRepositoryCache()
|
||||
_resetMergeQueueCacheForTests()
|
||||
getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' })
|
||||
})
|
||||
|
||||
it('counts a skipped run as passing and reads a StatusContext state as its conclusion', async () => {
|
||||
mockPullRequestDetail({
|
||||
number: 42,
|
||||
title: 'Add feature',
|
||||
state: 'OPEN',
|
||||
url: 'https://github.com/acme/widgets/pull/42',
|
||||
updatedAt: '2026-04-01T00:00:00Z',
|
||||
statusCheckRollup: [
|
||||
{ __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'SKIPPED' },
|
||||
// StatusContext supplies state instead of CheckRun's status/conclusion.
|
||||
{ __typename: 'StatusContext', state: 'SUCCESS' },
|
||||
{ __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'NEUTRAL' }
|
||||
]
|
||||
})
|
||||
|
||||
const item = await getWorkItem('/repo-root', 42, 'pr', null, {}, 'origin')
|
||||
|
||||
expect(item?.checksSummary).toEqual({
|
||||
state: 'success',
|
||||
total: 3,
|
||||
passed: 2,
|
||||
failed: 0,
|
||||
cancelled: 0,
|
||||
pending: 0,
|
||||
neutral: 1
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,203 +0,0 @@
|
||||
import type * as GithubLegacyCommandModule from '../../execution/github-legacy-command'
|
||||
import type * as GhExecFileModule from '../../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import type * as GithubOwnerRepoSelectionModule from '../../repositories/github-owner-repo-selection'
|
||||
import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity'
|
||||
import type * as GithubOperationSlotsModule from '../../execution/github-operation-slots'
|
||||
import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository'
|
||||
import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
ghExecFileAsyncMock,
|
||||
getOwnerRepoMock,
|
||||
getIssueOwnerRepoMock,
|
||||
getOwnerRepoForRemoteMock,
|
||||
resolvePRRepositoryCandidatesMock,
|
||||
resolveIssueSourceMock,
|
||||
rateLimitGuardMock,
|
||||
noteRateLimitSpendMock,
|
||||
acquireMock,
|
||||
releaseMock
|
||||
} = vi.hoisted(() => ({
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getOwnerRepoMock: vi.fn(),
|
||||
getIssueOwnerRepoMock: vi.fn(),
|
||||
getOwnerRepoForRemoteMock: vi.fn(),
|
||||
resolvePRRepositoryCandidatesMock: vi.fn(),
|
||||
resolveIssueSourceMock: vi.fn(),
|
||||
rateLimitGuardMock: vi.fn(() => ({ blocked: false })),
|
||||
noteRateLimitSpendMock: vi.fn(),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../execution/github-legacy-command', async () => {
|
||||
const actual = await vi.importActual<typeof GithubLegacyCommandModule>(
|
||||
'../../execution/github-legacy-command'
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
execFileAsync: vi.fn()
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async () => {
|
||||
const actual = await vi.importActual<typeof GhExecFileModule>(
|
||||
'../../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
ghExecFileAsync: ghExecFileAsyncMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../repositories/github-owner-repo-selection', async () => {
|
||||
const actual = await vi.importActual<typeof GithubOwnerRepoSelectionModule>(
|
||||
'../../repositories/github-owner-repo-selection'
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
getOwnerRepo: getOwnerRepoMock,
|
||||
resolveIssueSource: resolveIssueSourceMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../repositories/github-repository-identity', async () => {
|
||||
const actual = await vi.importActual<typeof GithubRepositoryIdentityModule>(
|
||||
'../../repositories/github-repository-identity'
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
getOwnerRepoForRemote: getOwnerRepoForRemoteMock,
|
||||
_resetOwnerRepoCache: vi.fn()
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../execution/github-operation-slots', async () => {
|
||||
const actual = await vi.importActual<typeof GithubOperationSlotsModule>(
|
||||
'../../execution/github-operation-slots'
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
acquire: acquireMock,
|
||||
release: releaseMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../api/rate-limit', () => ({
|
||||
rateLimitGuard: rateLimitGuardMock,
|
||||
noteRateLimitSpend: noteRateLimitSpendMock,
|
||||
getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })),
|
||||
repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })),
|
||||
noteRepositoryRateLimitSpend: vi.fn(),
|
||||
spendsSharedGitHubComQuota: () => true
|
||||
}))
|
||||
|
||||
vi.mock('../../repositories/github-api-repository', async (importOriginal) => {
|
||||
return {
|
||||
...(await importOriginal<typeof GithubApiRepositoryModule>()),
|
||||
resolveIssueGitHubApiRepositorySource: (
|
||||
repoPath: string,
|
||||
preference: unknown,
|
||||
connectionId?: string | null,
|
||||
localGitOptions?: unknown
|
||||
) => resolveIssueSourceMock(repoPath, preference, connectionId, localGitOptions),
|
||||
getIssueGitHubApiRepository: (repoPath: string, connectionId?: string | null) =>
|
||||
getIssueOwnerRepoMock(repoPath, connectionId),
|
||||
resolveGitHubApiRepositoryCandidates: (
|
||||
repoPath: string,
|
||||
connectionId?: string | null,
|
||||
localGitOptions?: unknown
|
||||
) => resolvePRRepositoryCandidatesMock(repoPath, connectionId, localGitOptions)
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) => {
|
||||
return {
|
||||
...(await importOriginal<typeof GithubApiRepositoryRemoteProbeModule>()),
|
||||
getOriginGitHubApiRepository: (
|
||||
repoPath: string,
|
||||
connectionId?: string | null,
|
||||
localGitOptions?: unknown
|
||||
) => getOwnerRepoMock(repoPath, connectionId, localGitOptions),
|
||||
getGitHubApiRepositoryForRemote: (
|
||||
repoPath: string,
|
||||
remoteName: string,
|
||||
connectionId?: string | null,
|
||||
localGitOptions?: unknown
|
||||
) =>
|
||||
remoteName === 'origin'
|
||||
? getOwnerRepoMock(repoPath, connectionId, localGitOptions)
|
||||
: getOwnerRepoForRemoteMock(repoPath, remoteName, connectionId, localGitOptions)
|
||||
}
|
||||
})
|
||||
|
||||
import { getWorkItem } from './get-work-item'
|
||||
import { _resetOwnerRepoCache } from '../../repositories/github-repository-identity'
|
||||
|
||||
describe('GitHub issue open-by-number origin preference', () => {
|
||||
beforeEach(() => {
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getOwnerRepoMock.mockReset()
|
||||
getIssueOwnerRepoMock.mockReset()
|
||||
getOwnerRepoForRemoteMock.mockReset()
|
||||
resolvePRRepositoryCandidatesMock.mockReset()
|
||||
resolveIssueSourceMock.mockReset()
|
||||
rateLimitGuardMock.mockReset()
|
||||
rateLimitGuardMock.mockReturnValue({ blocked: false })
|
||||
noteRateLimitSpendMock.mockReset()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
acquireMock.mockResolvedValue(undefined)
|
||||
getOwnerRepoForRemoteMock.mockImplementation(
|
||||
async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) =>
|
||||
remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null
|
||||
)
|
||||
resolvePRRepositoryCandidatesMock.mockImplementation(async (repoPath, connectionId) => {
|
||||
const origin = await getOwnerRepoMock(repoPath, connectionId)
|
||||
const repository = origin ? { host: 'github.com', ...origin } : null
|
||||
return { candidates: repository ? [repository] : [], headRepo: repository }
|
||||
})
|
||||
_resetOwnerRepoCache()
|
||||
})
|
||||
|
||||
it('does not run a bare issue lookup when explicit origin identity is unresolved', async () => {
|
||||
resolveIssueSourceMock.mockResolvedValueOnce({ source: null, fellBack: false })
|
||||
|
||||
await expect(getWorkItem('/repo-root', 7, 'issue', null, {}, 'origin')).resolves.toBeNull()
|
||||
|
||||
expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'origin', null, {})
|
||||
expect(getIssueOwnerRepoMock).not.toHaveBeenCalled()
|
||||
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('skips the issue probe on untyped open when origin identity is unresolved', async () => {
|
||||
const origin = { owner: 'fork', repo: 'orca', host: 'github.com' }
|
||||
resolveIssueSourceMock.mockResolvedValueOnce({ source: null, fellBack: false })
|
||||
getOwnerRepoMock.mockResolvedValue(origin)
|
||||
resolvePRRepositoryCandidatesMock.mockResolvedValue({ candidates: [origin], headRepo: origin })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 7,
|
||||
title: 'Origin PR',
|
||||
state: 'open',
|
||||
labels: [],
|
||||
isDraft: false,
|
||||
url: 'https://github.com/fork/orca/pull/7',
|
||||
baseRefName: 'main',
|
||||
headRefName: 'origin/fix',
|
||||
updatedAt: '2026-04-02T00:00:00Z',
|
||||
author: { login: 'octocat' }
|
||||
})
|
||||
})
|
||||
|
||||
const item = await getWorkItem('/repo-root', 7, undefined, null, {}, 'origin')
|
||||
|
||||
expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'origin', null, {})
|
||||
expect(getIssueOwnerRepoMock).not.toHaveBeenCalled()
|
||||
expect(ghExecFileAsyncMock.mock.calls[0]?.[0]).toEqual(
|
||||
expect.arrayContaining(['pr', 'view', '--repo', 'fork/orca'])
|
||||
)
|
||||
expect(item).toMatchObject({ number: 7, type: 'pr' })
|
||||
})
|
||||
})
|
||||
@@ -1,215 +0,0 @@
|
||||
import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity'
|
||||
import type * as GhExecFileModule from '../../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository'
|
||||
import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe'
|
||||
import type * as GitExecFileModule from '../../../git/command-runner/git-exec-file'
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type * as GitHubEnterpriseRepositoryModule from '../../repositories/github-enterprise-repository'
|
||||
|
||||
const { clientMocks, moduleMocks } = await vi.hoisted(async () => {
|
||||
const moduleMocks = await import('../client-test-mocks')
|
||||
return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks }
|
||||
})
|
||||
|
||||
vi.mock('../../execution/github-legacy-command', () =>
|
||||
moduleMocks.githubLegacyCommandModuleMock(clientMocks)
|
||||
)
|
||||
|
||||
vi.mock('../../repositories/github-owner-repo-selection', () =>
|
||||
moduleMocks.githubOwnerSelectionModuleMock(clientMocks)
|
||||
)
|
||||
|
||||
vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubRepositoryIdentityModule>()),
|
||||
...moduleMocks.githubRepositoryIdentityModuleMock(clientMocks)
|
||||
}))
|
||||
|
||||
vi.mock('../../api/gh-error-classification', () =>
|
||||
moduleMocks.githubErrorClassificationModuleMock()
|
||||
)
|
||||
|
||||
vi.mock('../../execution/github-operation-slots', () =>
|
||||
moduleMocks.githubOperationSlotsModuleMock(clientMocks)
|
||||
)
|
||||
|
||||
vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GitExecFileModule>()),
|
||||
gitExecFileAsync: clientMocks.gitExecFileAsyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GhExecFileModule>()),
|
||||
...moduleMocks.githubHostedCliModuleMock(clientMocks)
|
||||
}))
|
||||
vi.mock('../../repositories/local-git-config-signature', () =>
|
||||
moduleMocks.localGitConfigSignatureModuleMock(clientMocks)
|
||||
)
|
||||
vi.mock('../../repositories/github-enterprise-repository', async (importOriginal) =>
|
||||
moduleMocks.githubEnterpriseRepositoryModuleMock(
|
||||
await importOriginal<typeof GitHubEnterpriseRepositoryModule>()
|
||||
)
|
||||
)
|
||||
vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks))
|
||||
vi.mock('../../repositories/github-api-repository', async (importOriginal) =>
|
||||
moduleMocks.githubApiRepositoryModuleMock(
|
||||
clientMocks,
|
||||
await importOriginal<typeof GithubApiRepositoryModule>()
|
||||
)
|
||||
)
|
||||
|
||||
vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) =>
|
||||
moduleMocks.githubApiRepositoryRemoteProbeModuleMock(
|
||||
clientMocks,
|
||||
await importOriginal<typeof GithubApiRepositoryRemoteProbeModule>()
|
||||
)
|
||||
)
|
||||
|
||||
import { getPRForBranch } from './get-pr-for-branch'
|
||||
import { resetPRForBranchMocks } from '../client-test-harness'
|
||||
import type { RestPullRequest } from './pull-request-lookup-data'
|
||||
import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity'
|
||||
|
||||
const {
|
||||
ghExecFileAsyncMock,
|
||||
getOwnerRepoMock,
|
||||
resolvePRRepositoryCandidatesMock,
|
||||
gitExecFileAsyncMock
|
||||
} = clientMocks
|
||||
|
||||
const ACME = { owner: 'acme', repo: 'widgets' }
|
||||
|
||||
function primeGit(
|
||||
trackedUpstream: string,
|
||||
remoteHeads: Record<string, string> = { origin: 'develop' }
|
||||
): void {
|
||||
gitExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
||||
if (args[0] === 'for-each-ref' && args.includes('--format=%(refname)%00%(upstream)')) {
|
||||
return { stdout: `refs/heads/feature/my-change\0${trackedUpstream}\n`, stderr: '' }
|
||||
}
|
||||
if (args[0] === 'for-each-ref' && args.includes('--format=%(refname)%00%(symref)')) {
|
||||
const stdout = Object.entries(remoteHeads)
|
||||
.filter(([remote]) => args.includes(`refs/remotes/${remote}/HEA[D]`))
|
||||
.map(
|
||||
([remote, branch]) => `refs/remotes/${remote}/HEAD\0refs/remotes/${remote}/${branch}\n`
|
||||
)
|
||||
.join('')
|
||||
return { stdout, stderr: '' }
|
||||
}
|
||||
if (args[0] === 'rev-parse' && args[1] === 'HEAD') {
|
||||
return { stdout: 'feature-head-oid\n', stderr: '' }
|
||||
}
|
||||
throw new Error(`unexpected git call: ${args.join(' ')}`)
|
||||
})
|
||||
}
|
||||
|
||||
function restPR(
|
||||
headRefName = 'develop',
|
||||
headRepo: OwnerRepo = ACME,
|
||||
prRepo: OwnerRepo = ACME
|
||||
): RestPullRequest {
|
||||
return {
|
||||
number: 7,
|
||||
title: 'Release develop',
|
||||
state: 'closed',
|
||||
merged_at: null,
|
||||
html_url: `https://${prRepo.host ?? 'github.com'}/${prRepo.owner}/${prRepo.repo}/pull/7`,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
draft: false,
|
||||
mergeable: null,
|
||||
base: { ref: 'release', sha: 'release-oid' },
|
||||
head: {
|
||||
ref: headRefName,
|
||||
sha: 'old-develop-oid',
|
||||
repo: { name: headRepo.repo, owner: { login: headRepo.owner } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function primeGh(
|
||||
listsByHead: Record<string, RestPullRequest[]>,
|
||||
exactPR: RestPullRequest | RestPullRequest[] = Object.values(listsByHead).flat()[0] ?? restPR()
|
||||
): void {
|
||||
const repositorySlug = (pr: RestPullRequest): string =>
|
||||
new URL(pr.html_url ?? '').pathname.split('/').slice(1, 3).join('/')
|
||||
const repositoryHost = (pr: RestPullRequest): string => new URL(pr.html_url ?? '').host
|
||||
const exactPRs = Array.isArray(exactPR) ? exactPR : [exactPR]
|
||||
const prsByRepositoryAndNumber = new Map(
|
||||
[...Object.values(listsByHead).flat(), ...exactPRs].map((pr) => [
|
||||
`${repositoryHost(pr)}/${repositorySlug(pr)}#${pr.number}`,
|
||||
pr
|
||||
])
|
||||
)
|
||||
ghExecFileAsyncMock.mockImplementation(
|
||||
async (args: string[], options: { host?: string } = {}) => {
|
||||
const host = options.host ?? 'github.com'
|
||||
const match = args[1]?.match(/^repos\/([^/]+\/[^/]+)\/pulls\?head=([^&]+)/)
|
||||
if (args[0] === 'api' && match) {
|
||||
const list = (listsByHead[decodeURIComponent(match[2])] ?? []).filter(
|
||||
(pr) => repositoryHost(pr) === host && repositorySlug(pr) === match[1]
|
||||
)
|
||||
return { stdout: JSON.stringify(list) }
|
||||
}
|
||||
const exactRestMatch = args[1]?.match(/^repos\/([^/]+\/[^/]+)\/pulls\/(\d+)$/)
|
||||
if (args[0] === 'api' && exactRestMatch) {
|
||||
const pr = prsByRepositoryAndNumber.get(`${host}/${exactRestMatch[1]}#${exactRestMatch[2]}`)
|
||||
if (pr) {
|
||||
return { stdout: JSON.stringify(pr) }
|
||||
}
|
||||
throw new Error('HTTP 404 Not Found')
|
||||
}
|
||||
const repoIndex = args.indexOf('--repo')
|
||||
const exact = prsByRepositoryAndNumber.get(`${host}/${args[repoIndex + 1]}#${args[2]}`)
|
||||
if (args[0] === 'pr' && args[1] === 'view') {
|
||||
if (!exact) {
|
||||
throw new Error('HTTP 404 Not Found')
|
||||
}
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
number: exact.number,
|
||||
title: exact.title,
|
||||
state: exact.merged_at ? 'MERGED' : exact.state.toUpperCase(),
|
||||
url: exact.html_url,
|
||||
statusCheckRollup: [],
|
||||
updatedAt: exact.updated_at,
|
||||
isDraft: exact.draft,
|
||||
mergeable: 'UNKNOWN',
|
||||
baseRefName: exact.base?.ref,
|
||||
headRefName: exact.head?.ref,
|
||||
baseRefOid: exact.base?.sha,
|
||||
headRefOid: exact.head?.sha,
|
||||
headRepositoryOwner: exact.head?.repo?.owner,
|
||||
headRepository: exact.head?.repo ? { name: exact.head.repo.name } : null
|
||||
})
|
||||
}
|
||||
}
|
||||
throw new Error(`gh unavailable: ${args.join(' ')}`)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
describe('issue #26948: a branch tracking the default branch', () => {
|
||||
beforeEach(() => {
|
||||
resetPRForBranchMocks(clientMocks)
|
||||
getOwnerRepoMock.mockResolvedValue(ACME)
|
||||
})
|
||||
|
||||
it('does not query another GitHub server for a known public GitHub head', async () => {
|
||||
const enterprise = { ...ACME, host: 'ghe.example' }
|
||||
resolvePRRepositoryCandidatesMock.mockResolvedValue({
|
||||
candidates: [enterprise, ACME],
|
||||
headRepo: ACME
|
||||
})
|
||||
primeGit('')
|
||||
primeGh({
|
||||
'acme:feature/my-change': [
|
||||
{ ...restPR('feature/my-change', enterprise, enterprise), state: 'open' }
|
||||
]
|
||||
})
|
||||
expect(await getPRForBranch('/repo-root', 'feature/my-change')).toBeNull()
|
||||
expect(
|
||||
ghExecFileAsyncMock.mock.calls.some(([, options]) => options?.host === 'ghe.example')
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,108 +0,0 @@
|
||||
import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity'
|
||||
import type * as GhExecFileModule from '../../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository'
|
||||
import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe'
|
||||
import type * as GitExecFileModule from '../../../git/command-runner/git-exec-file'
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type * as GitHubEnterpriseRepositoryModule from '../../repositories/github-enterprise-repository'
|
||||
|
||||
const { clientMocks, moduleMocks } = await vi.hoisted(async () => {
|
||||
const moduleMocks = await import('../client-test-mocks')
|
||||
return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks }
|
||||
})
|
||||
|
||||
vi.mock('../../execution/github-legacy-command', () =>
|
||||
moduleMocks.githubLegacyCommandModuleMock(clientMocks)
|
||||
)
|
||||
|
||||
vi.mock('../../repositories/github-owner-repo-selection', () =>
|
||||
moduleMocks.githubOwnerSelectionModuleMock(clientMocks)
|
||||
)
|
||||
|
||||
vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubRepositoryIdentityModule>()),
|
||||
...moduleMocks.githubRepositoryIdentityModuleMock(clientMocks)
|
||||
}))
|
||||
|
||||
vi.mock('../../api/gh-error-classification', () =>
|
||||
moduleMocks.githubErrorClassificationModuleMock()
|
||||
)
|
||||
|
||||
vi.mock('../../execution/github-operation-slots', () =>
|
||||
moduleMocks.githubOperationSlotsModuleMock(clientMocks)
|
||||
)
|
||||
|
||||
vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GitExecFileModule>()),
|
||||
gitExecFileAsync: clientMocks.gitExecFileAsyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GhExecFileModule>()),
|
||||
...moduleMocks.githubHostedCliModuleMock(clientMocks)
|
||||
}))
|
||||
vi.mock('../../repositories/local-git-config-signature', () =>
|
||||
moduleMocks.localGitConfigSignatureModuleMock(clientMocks)
|
||||
)
|
||||
vi.mock('../../repositories/github-enterprise-repository', async (importOriginal) =>
|
||||
moduleMocks.githubEnterpriseRepositoryModuleMock(
|
||||
await importOriginal<typeof GitHubEnterpriseRepositoryModule>()
|
||||
)
|
||||
)
|
||||
vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks))
|
||||
vi.mock('../../repositories/github-api-repository', async (importOriginal) =>
|
||||
moduleMocks.githubApiRepositoryModuleMock(
|
||||
clientMocks,
|
||||
await importOriginal<typeof GithubApiRepositoryModule>()
|
||||
)
|
||||
)
|
||||
|
||||
vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) =>
|
||||
moduleMocks.githubApiRepositoryRemoteProbeModuleMock(
|
||||
clientMocks,
|
||||
await importOriginal<typeof GithubApiRepositoryRemoteProbeModule>()
|
||||
)
|
||||
)
|
||||
|
||||
import { getRestPRForBranch } from './pr-branch-lookup'
|
||||
|
||||
import { resetPRForBranchMocks } from '../client-test-harness'
|
||||
|
||||
const { ghExecFileAsyncMock } = clientMocks
|
||||
|
||||
describe('PR lookup conditional REST reads', () => {
|
||||
beforeEach(() => resetPRForBranchMocks(clientMocks))
|
||||
|
||||
it('revalidates both mixed and active discovery responses before falling back to history', async () => {
|
||||
const repo = { owner: 'acme', repo: 'widgets', host: 'github.com' }
|
||||
const old = Array.from({ length: 10 }, (_, i) => ({
|
||||
number: i + 1,
|
||||
state: 'closed',
|
||||
title: 'Old',
|
||||
head: { ref: 'feature' }
|
||||
}))
|
||||
const open = { number: 11, state: 'open', title: 'Active', head: { ref: 'feature' } }
|
||||
const http = (data: unknown, etag: string) => ({
|
||||
stdout: `HTTP/2.0 200 OK\nEtag: "${etag}"\r\n\r\n${JSON.stringify(data)}`
|
||||
})
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce(http(old, 'recent'))
|
||||
.mockResolvedValueOnce(http([open], 'active'))
|
||||
.mockRejectedValueOnce(
|
||||
Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' })
|
||||
)
|
||||
.mockRejectedValueOnce(
|
||||
Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' })
|
||||
)
|
||||
await expect(
|
||||
getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' })
|
||||
).resolves.toMatchObject({ number: 11 })
|
||||
await expect(
|
||||
getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' })
|
||||
).resolves.toMatchObject({ number: 11 })
|
||||
expect(ghExecFileAsyncMock.mock.calls[2][0]).toContain('If-None-Match: "recent"')
|
||||
expect(ghExecFileAsyncMock.mock.calls[3][0]).toContain('If-None-Match: "active"')
|
||||
})
|
||||
})
|
||||
@@ -1,77 +0,0 @@
|
||||
import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types'
|
||||
import type {
|
||||
GitHubRepoContext,
|
||||
LocalGitExecOptions
|
||||
} from '../../repositories/github-repository-identity'
|
||||
|
||||
import { __resetHostedReviewBranchCacheForTests } from '../../../source-control/hosted-review-branch-cache'
|
||||
|
||||
const mocks = vi.hoisted(() => ({ resolve: vi.fn(), acquire: vi.fn(), release: vi.fn() }))
|
||||
vi.mock('../../execution/github-operation-slots', () => ({
|
||||
acquire: mocks.acquire,
|
||||
release: mocks.release
|
||||
}))
|
||||
|
||||
vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubRepositoryIdentityModule>()),
|
||||
githubRepoContext: (
|
||||
repoPath: string,
|
||||
connectionId: string | null,
|
||||
options: LocalGitExecOptions
|
||||
) => ({
|
||||
repoPath,
|
||||
connectionId,
|
||||
...options
|
||||
}),
|
||||
ghRepoExecOptions: (context: GitHubRepoContext) => context
|
||||
}))
|
||||
vi.mock('./branch-lookup-resolution', () => ({
|
||||
resolvePRForBranchOutcome: mocks.resolve
|
||||
}))
|
||||
vi.mock('./pr-for-branch-outcome', async () => ({
|
||||
getPRForBranchOutcome: (await import('./pr-for-branch-outcome')).getPRForBranchOutcome
|
||||
}))
|
||||
|
||||
vi.mock('../fetch/repo-slug-upstream', async () => ({
|
||||
getRepoSlug: vi.fn(async () => ({ owner: 'acme', repo: 'orca' }))
|
||||
}))
|
||||
|
||||
vi.mock('./pr-lookup-rate-limit', async () => ({
|
||||
getGitHubPRLookupRateLimitBlock: vi.fn(async () => null)
|
||||
}))
|
||||
|
||||
vi.mock('../create/create-github-pull-request', async () => ({
|
||||
createGitHubPullRequest: vi.fn()
|
||||
}))
|
||||
vi.mock('../../../gitlab/merge-requests/merge-request-lookup', () => ({
|
||||
getProjectSlug: vi.fn(async () => null)
|
||||
}))
|
||||
import { getPRForBranchOutcome } from './pr-for-branch-outcome'
|
||||
|
||||
const outcome: PRRefreshOutcome = { kind: 'no-pr', fetchedAt: 1 }
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.resolve.mockReset()
|
||||
__resetHostedReviewBranchCacheForTests()
|
||||
mocks.acquire.mockResolvedValue(undefined)
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('PR lookup coalescing', () => {
|
||||
it('cleans up errors so later reads can recover', async () => {
|
||||
mocks.resolve.mockRejectedValueOnce(new Error('network down')).mockResolvedValue(outcome)
|
||||
const results = await Promise.all([
|
||||
getPRForBranchOutcome('/repo', 'topic'),
|
||||
getPRForBranchOutcome('/repo', 'topic')
|
||||
])
|
||||
expect(results.every((result) => result.kind === 'upstream-error')).toBe(true)
|
||||
expect(mocks.resolve).toHaveBeenCalledTimes(1)
|
||||
await expect(getPRForBranchOutcome('/repo', 'topic')).resolves.toEqual(outcome)
|
||||
expect(mocks.resolve).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -1,209 +0,0 @@
|
||||
import type * as GithubRepositoryIdentityModule from '../repositories/github-repository-identity'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
const mocks = vi.hoisted(() => ({ exec: vi.fn(), guard: vi.fn() }))
|
||||
vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({
|
||||
ghExecFileAsync: mocks.exec
|
||||
}))
|
||||
|
||||
vi.mock('../repositories/github-repository-identity', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubRepositoryIdentityModule>()),
|
||||
ghRepoExecOptions: () => ({}),
|
||||
githubRepoContext: () => ({})
|
||||
}))
|
||||
vi.mock('../api/rate-limit', () => ({
|
||||
repositoryRateLimitGuard: mocks.guard,
|
||||
noteRepositoryRateLimitSpend: vi.fn()
|
||||
}))
|
||||
import { getIssueBodyAndComments, getIssueDetailsViaGraphQL } from './issue-work-item-details'
|
||||
const repository = { owner: 'acme', repo: 'widgets' }
|
||||
|
||||
describe('explicit task refresh conversation reads', () => {
|
||||
beforeEach(() => {
|
||||
mocks.exec.mockReset()
|
||||
mocks.guard.mockReset()
|
||||
mocks.guard.mockReturnValue({ blocked: false })
|
||||
})
|
||||
it('bypasses body, comments and timeline caches and reads every comments page', async () => {
|
||||
mocks.exec.mockImplementation(async (args: string[]) => ({
|
||||
stdout: args.some((arg) => arg.includes('/comments?'))
|
||||
? JSON.stringify([
|
||||
[{ id: 1, user: null, body: 'first', created_at: '', html_url: '' }],
|
||||
[{ id: 2, user: null, body: 'second', created_at: '', html_url: '' }]
|
||||
])
|
||||
: args.some((arg) => arg.includes('/timeline?'))
|
||||
? ''
|
||||
: JSON.stringify({ body: 'current', assignees: [] })
|
||||
}))
|
||||
const result = await getIssueBodyAndComments('/repo', 42, repository, null, {}, true)
|
||||
expect(result.body).toBe('current')
|
||||
expect(result.comments.map((comment) => comment.body)).toEqual(['first', 'second'])
|
||||
for (const [args] of mocks.exec.mock.calls.filter(([args]) =>
|
||||
args.some((arg: string) => arg.startsWith('repos/'))
|
||||
)) {
|
||||
expect(args).not.toContain('--cache')
|
||||
}
|
||||
expect(
|
||||
mocks.exec.mock.calls.find(([args]) =>
|
||||
args.some((arg: string) => arg.includes('/comments?'))
|
||||
)?.[0]
|
||||
).toEqual(expect.arrayContaining(['--paginate', '--slurp']))
|
||||
})
|
||||
it('marks only the comments the reading gh account wrote', async () => {
|
||||
const comment = (id: number, login: string) => ({
|
||||
id,
|
||||
user: { login, avatar_url: '' },
|
||||
body: 'LGTM',
|
||||
created_at: '',
|
||||
html_url: ''
|
||||
})
|
||||
mocks.exec.mockImplementation(async (args: string[]) => ({
|
||||
stdout: args.includes('user')
|
||||
? 'Me\n'
|
||||
: args.some((arg) => arg.includes('/comments?'))
|
||||
? JSON.stringify([[comment(1, 'alice')], [comment(2, 'me')]])
|
||||
: args.some((arg) => arg.includes('/timeline?'))
|
||||
? ''
|
||||
: JSON.stringify({ body: 'current' })
|
||||
}))
|
||||
const result = await getIssueBodyAndComments('/repo', 42, repository, null, {}, true)
|
||||
expect(result.comments.map((c) => [c.author, c.viewerDidAuthor])).toEqual([
|
||||
['alice', undefined],
|
||||
['me', true]
|
||||
])
|
||||
})
|
||||
|
||||
it('retains ordinary fallback behavior but does not report an explicit rate-limited read as success', async () => {
|
||||
mocks.guard.mockReturnValue({ blocked: true })
|
||||
expect(await getIssueBodyAndComments('/repo', 42, repository)).toEqual({
|
||||
body: '',
|
||||
comments: [],
|
||||
assignees: [],
|
||||
timelineItems: []
|
||||
})
|
||||
await expect(getIssueBodyAndComments('/repo', 42, repository, null, {}, true)).rejects.toThrow()
|
||||
expect(mocks.exec).not.toHaveBeenCalled()
|
||||
})
|
||||
it('falls back from incomplete GraphQL conversations and malformed timelines', async () => {
|
||||
mocks.exec.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
issue: { body: 'new', comments: { nodes: [], pageInfo: { hasNextPage: true } } }
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
expect(
|
||||
await getIssueDetailsViaGraphQL('/repo', 42, repository, null, {}, false, true)
|
||||
).toBeNull()
|
||||
mocks.exec.mockImplementation(async (args: string[]) => ({
|
||||
stdout: args.some((arg) => arg.includes('/timeline?'))
|
||||
? 'not-json'
|
||||
: args.some((arg) => arg.includes('/comments?'))
|
||||
? '[]'
|
||||
: '{"body":"new"}'
|
||||
}))
|
||||
await expect(getIssueBodyAndComments('/repo', 42, repository, null, {}, true)).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
it('pairs issue and comment image sources through collapsed and REST detail reads', async () => {
|
||||
mocks.exec.mockReset()
|
||||
mocks.guard.mockReturnValue({ blocked: false })
|
||||
const body =
|
||||
''
|
||||
const html =
|
||||
'<img src="https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST">'
|
||||
mocks.exec.mockImplementation(async (args: string[]) => ({
|
||||
stdout: JSON.stringify(
|
||||
args.includes('graphql')
|
||||
? {
|
||||
data: {
|
||||
repository: {
|
||||
issue: {
|
||||
body,
|
||||
bodyHTML: html,
|
||||
comments: { nodes: [{ databaseId: 1, body, bodyHTML: html }] }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
: args.some((arg) => arg.includes('/timeline?'))
|
||||
? []
|
||||
: args.some((arg) => arg.includes('/comments?'))
|
||||
? [{ id: 1, user: null, body, body_html: html }]
|
||||
: { body, body_html: html }
|
||||
)
|
||||
}))
|
||||
const collapsed = await getIssueDetailsViaGraphQL('/repo', 42, repository)
|
||||
const rest = await getIssueBodyAndComments('/repo', 42, repository)
|
||||
for (const details of [collapsed!, rest]) {
|
||||
expect(details.body).toBe(body)
|
||||
expect(details.bodyImageUrls).toEqual({
|
||||
'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488':
|
||||
'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST'
|
||||
})
|
||||
expect(details.comments[0].bodyImageUrls).toEqual(details.bodyImageUrls)
|
||||
}
|
||||
for (const [args] of mocks.exec.mock.calls.filter(([args]) =>
|
||||
args.some((arg: string) => /\/issues\/42(?:$|\/comments)/.test(arg))
|
||||
)) {
|
||||
expect(args).toContain('Accept: application/vnd.github.full+json')
|
||||
expect(args).not.toContain('--cache')
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['optional HTML', 'required body', 'pathless', 'rejection without errors'] as const)(
|
||||
'admits rejected issue stdout only for available optional HTML failures (%s)',
|
||||
async (input) => {
|
||||
mocks.exec.mockReset()
|
||||
mocks.guard.mockReturnValue({ blocked: false })
|
||||
const body =
|
||||
''
|
||||
const html =
|
||||
'<img src="https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST">'
|
||||
mocks.exec.mockRejectedValueOnce(
|
||||
Object.assign(new Error('GraphQL failed'), {
|
||||
stdout: JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
issue: {
|
||||
body,
|
||||
bodyHTML: html,
|
||||
comments: {
|
||||
pageInfo: { hasNextPage: false },
|
||||
nodes: [{ databaseId: 1, body, bodyHTML: html }]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
errors:
|
||||
input === 'rejection without errors'
|
||||
? undefined
|
||||
: [
|
||||
{
|
||||
path:
|
||||
input === 'pathless'
|
||||
? undefined
|
||||
: ['repository', 'issue', input === 'required body' ? 'body' : 'bodyHTML']
|
||||
}
|
||||
]
|
||||
})
|
||||
})
|
||||
)
|
||||
mocks.exec.mockResolvedValueOnce({ stdout: '[]' })
|
||||
const result = await getIssueDetailsViaGraphQL('/repo', 42, repository, null, {}, false, true)
|
||||
if (input !== 'optional HTML') {
|
||||
expect(result).toBeNull()
|
||||
expect(mocks.exec).toHaveBeenCalledTimes(1)
|
||||
return
|
||||
}
|
||||
expect(result?.body).toBe(body)
|
||||
expect(result?.bodyImageUrls).toBeUndefined()
|
||||
expect(result?.comments[0].bodyImageUrls).toEqual({
|
||||
'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488':
|
||||
'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST'
|
||||
})
|
||||
expect(mocks.exec).toHaveBeenCalledTimes(2)
|
||||
}
|
||||
)
|
||||
@@ -1,40 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { setPRAutoRefreshCadence } from '../../../shared/review-refresh-policy'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
read: vi.fn(async () => []),
|
||||
pending: vi.fn(() => [{ headSha: 'old-head', movedAt: 1, expiresAt: null }])
|
||||
}))
|
||||
vi.mock('../pull-requests/refresh/pr-refresh-coordinator', () => ({ schedulePRWatchRead: vi.fn() }))
|
||||
vi.mock('./pr-head-check-read', () => ({ readPRHeadCheckRollup: mocks.read }))
|
||||
|
||||
import { PREarlierHeadJobs } from './pr-earlier-head-jobs'
|
||||
import { prWatchPlanDueAt } from '../pull-requests/refresh/pr-refresh-watch-jobs'
|
||||
|
||||
afterEach(() => setPRAutoRefreshCadence('default'))
|
||||
|
||||
it.each([
|
||||
['default', 120_000],
|
||||
['reduced', 10 * 60_000],
|
||||
['minimal', 20 * 60_000],
|
||||
// A chat is waiting for the result, so off slows to minimal instead of stopping.
|
||||
['off', 20 * 60_000]
|
||||
] as const)(
|
||||
'an earlier head’s next read follows the %s watch cadence',
|
||||
async (cadence, interval) => {
|
||||
setPRAutoRefreshCadence(cadence)
|
||||
const jobs = new PREarlierHeadJobs({
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this read-only probe only requests pending heads.
|
||||
database: { read: async () => mocks.pending() } as never,
|
||||
apply: async () => false,
|
||||
logger: { warn: vi.fn() },
|
||||
now: () => 1_000
|
||||
})
|
||||
const readAt = await jobs.read(
|
||||
{ prKey: 'github.com/acme/repo#7', headSha: 'old-head' },
|
||||
{ repoId: 'r', repoPath: '/repo', branch: 'topic', repoKind: 'git', cacheKey: 'k' }
|
||||
)
|
||||
expect(readAt).toBe(1_000)
|
||||
expect(prWatchPlanDueAt({ kind: 'head', at: readAt! })).toBe(1_000 + interval)
|
||||
}
|
||||
)
|
||||
@@ -1,58 +0,0 @@
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness'
|
||||
import { getPRForBranchOutcome } from '../../client/lookup/pr-for-branch-outcome'
|
||||
import { runHostedPRRead } from './pr-refresh-coordinator'
|
||||
import { refreshIntervalForCandidate } from './pr-refresh-candidate-policy'
|
||||
|
||||
vi.mock('../../client/lookup/branch-lookup-resolution', () => ({
|
||||
resolvePRForBranchOutcome: async () => ({
|
||||
kind: 'found',
|
||||
fetchedAt: Date.now(),
|
||||
pr: makePR({
|
||||
headSha: 'head',
|
||||
checksStatus: 'success',
|
||||
checksReadComplete: true,
|
||||
checksFinal: true,
|
||||
autoMergeEnabled: false,
|
||||
mergeQueueRequired: false
|
||||
})
|
||||
})
|
||||
}))
|
||||
vi.mock('../../execution/github-operation-slots', () => ({
|
||||
acquire: async () => {},
|
||||
release: () => {}
|
||||
}))
|
||||
|
||||
it('stretches a confirmed quiet PR’s interval by the cadence, as it does every other interval', async () => {
|
||||
const candidate = makeCandidate({
|
||||
branch: 'branch',
|
||||
currentHeadOid: 'head',
|
||||
cachedHeadOid: 'head',
|
||||
cachedFetchedAt: 2_000,
|
||||
cachedPRState: 'open',
|
||||
cachedChecksStatus: 'success',
|
||||
cachedHasPR: true
|
||||
})
|
||||
const read = () =>
|
||||
runHostedPRRead(candidate, () =>
|
||||
getPRForBranchOutcome('/repo', 'branch', null, null, null, { currentHeadOid: 'head' })
|
||||
)
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(1_000)
|
||||
await read()
|
||||
vi.setSystemTime(2_000)
|
||||
await read()
|
||||
const unconfirmed = { ...candidate, fallbackPRNumber: 9 }
|
||||
expect(
|
||||
(['default', 'reduced', 'minimal', 'off'] as const).map((cadence) => [
|
||||
refreshIntervalForCandidate(candidate, cadence),
|
||||
refreshIntervalForCandidate(unconfirmed, cadence)
|
||||
])
|
||||
).toEqual([
|
||||
[300_000, 120_000],
|
||||
[1_500_000, 600_000],
|
||||
[3_000_000, 1_200_000],
|
||||
[Infinity, Infinity]
|
||||
])
|
||||
vi.useRealTimers()
|
||||
})
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { PRInfo } from '../../../../shared/github/pull-requests/pull-request-types'
|
||||
|
||||
const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => {
|
||||
const moduleMocks = await import('./pr-refresh-coordinator-test-mocks')
|
||||
return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks }
|
||||
})
|
||||
|
||||
vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks))
|
||||
vi.mock('../../client/lookup/pr-for-branch-outcome', () => {
|
||||
return moduleMocks.clientModuleMock(coordinatorMocks)
|
||||
})
|
||||
vi.mock('../../repositories/github-api-repository-remote-probe', () => {
|
||||
return {
|
||||
getOriginGitHubApiRepository: coordinatorMocks.getOriginGitHubApiRepositoryMock
|
||||
}
|
||||
})
|
||||
vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks))
|
||||
|
||||
import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness'
|
||||
|
||||
const { sendMock, getPRForBranchOutcomeMock } = coordinatorMocks
|
||||
|
||||
function deferred<T>(): {
|
||||
promise: Promise<T>
|
||||
resolve: (value: T) => void
|
||||
reject: (error: unknown) => void
|
||||
} {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (error: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
describe('pr-refresh-coordinator', () => {
|
||||
beforeEach(() => {
|
||||
moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks)
|
||||
})
|
||||
|
||||
// Transforming the coordinator's module graph is the slow first step on a loaded machine: do it
|
||||
// once under the hook limit, so each test still imports its own fresh instance, quickly.
|
||||
beforeAll(async () => {
|
||||
await import('./pr-refresh-coordinator')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
// A body that failed must not leave its timers to run on the next test's clock.
|
||||
vi.clearAllTimers()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('preserves an active refresh queued while a visible refresh is in flight', async () => {
|
||||
const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } =
|
||||
await import('./pr-refresh-coordinator')
|
||||
const visibleOutcome = deferred<{
|
||||
kind: 'found'
|
||||
pr: PRInfo
|
||||
fetchedAt: number
|
||||
}>()
|
||||
getPRForBranchOutcomeMock.mockReturnValueOnce(visibleOutcome.promise).mockResolvedValueOnce({
|
||||
kind: 'found',
|
||||
pr: makePR({ checksStatus: 'success', state: 'merged' }),
|
||||
fetchedAt: Date.now()
|
||||
})
|
||||
|
||||
const candidate = makeCandidate()
|
||||
reportVisiblePRRefreshCandidates([candidate], 1, 1)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
enqueuePRRefresh({ ...candidate, cachedFetchedAt: Date.now() }, 'active', 80, 1)
|
||||
visibleOutcome.resolve({
|
||||
kind: 'found',
|
||||
pr: makePR({ checksStatus: 'pending', mergeable: 'MERGEABLE' }),
|
||||
fetchedAt: Date.now()
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
const inFlightEvents = sendMock.mock.calls
|
||||
.map(([, event]) => event)
|
||||
.filter((event) => event.status === 'in-flight')
|
||||
|
||||
expect(inFlightEvents.map((event) => event.reason)).toEqual(['visible', 'active'])
|
||||
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -1,56 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types'
|
||||
|
||||
import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness'
|
||||
|
||||
const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => {
|
||||
const moduleMocks = await import('./pr-refresh-coordinator-test-mocks')
|
||||
return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks }
|
||||
})
|
||||
vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks))
|
||||
vi.mock('../../client/lookup/pr-for-branch-outcome', () => {
|
||||
return moduleMocks.clientModuleMock(coordinatorMocks)
|
||||
})
|
||||
vi.mock('../../repositories/github-api-repository-remote-probe', () => {
|
||||
return {
|
||||
getOriginGitHubApiRepository: coordinatorMocks.getOriginGitHubApiRepositoryMock
|
||||
}
|
||||
})
|
||||
vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks))
|
||||
|
||||
const { getPRForBranchOutcomeMock } = coordinatorMocks
|
||||
|
||||
function found(state: 'open' | 'closed' | 'merged'): PRRefreshOutcome {
|
||||
return { kind: 'found', pr: makePR({ state, checksStatus: 'success' }), fetchedAt: Date.now() }
|
||||
}
|
||||
|
||||
describe('main refresh completion ordering', () => {
|
||||
beforeEach(() => moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks))
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('preserves a newer failure gate when an older successful lookup completes', async () => {
|
||||
let finishOlder: (outcome: PRRefreshOutcome) => void = () => {}
|
||||
getPRForBranchOutcomeMock
|
||||
.mockImplementationOnce(
|
||||
() => new Promise<PRRefreshOutcome>((resolve) => (finishOlder = resolve))
|
||||
)
|
||||
.mockImplementation(async () => ({
|
||||
kind: 'upstream-error',
|
||||
errorType: 'rate_limited',
|
||||
message: 'wait',
|
||||
fetchedAt: Date.now(),
|
||||
retryDisabledUntil: Date.now() + 300_000
|
||||
}))
|
||||
const { reportVisiblePRRefreshCandidates, refreshPRNow } =
|
||||
await import('./pr-refresh-coordinator')
|
||||
const candidate = makeCandidate({ isSelected: true })
|
||||
reportVisiblePRRefreshCandidates([candidate], 1, 1)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await refreshPRNow(candidate)
|
||||
finishOlder(found('open'))
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2)
|
||||
await expect(refreshPRNow(candidate)).resolves.toMatchObject({ errorType: 'rate_limited' })
|
||||
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -1,76 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { GitHubPRRefreshCandidate } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types'
|
||||
|
||||
const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => {
|
||||
const moduleMocks = await import('./pr-refresh-coordinator-test-mocks')
|
||||
return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks }
|
||||
})
|
||||
|
||||
vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks))
|
||||
vi.mock('../../client/lookup/pr-for-branch-outcome', () => {
|
||||
return moduleMocks.clientModuleMock(coordinatorMocks)
|
||||
})
|
||||
vi.mock('../../repositories/github-api-repository-remote-probe', () => {
|
||||
return {
|
||||
getOriginGitHubApiRepository: coordinatorMocks.getOriginGitHubApiRepositoryMock
|
||||
}
|
||||
})
|
||||
vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks))
|
||||
|
||||
import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness'
|
||||
|
||||
const { getPRForBranchOutcomeMock } = coordinatorMocks
|
||||
const LINKED_PR_KEY = 'local::runtime:host::/repo::pr::42'
|
||||
|
||||
describe('pr-refresh queue growth bounds', () => {
|
||||
beforeEach(() => {
|
||||
moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks)
|
||||
getPRForBranchOutcomeMock.mockImplementation(async () => ({
|
||||
kind: 'found' as const,
|
||||
pr: makePR({ checksStatus: 'pending' as const }),
|
||||
fetchedAt: Date.now()
|
||||
}))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('keeps the newer alias when a branch switch lands mid-request', async () => {
|
||||
const { reportVisiblePRRefreshCandidates, _getPRRefreshAliasCountForTests } =
|
||||
await import('./pr-refresh-coordinator')
|
||||
|
||||
const churnCandidate = (index: number): GitHubPRRefreshCandidate =>
|
||||
makeCandidate({
|
||||
cacheKey: `/repo::churn/${index}`,
|
||||
branch: `churn/${index}`,
|
||||
worktreeId: 'wt-churn',
|
||||
linkedPRNumber: 42,
|
||||
cachedFetchedAt: null
|
||||
})
|
||||
|
||||
let switched = false
|
||||
getPRForBranchOutcomeMock.mockImplementation(async () => {
|
||||
if (!switched) {
|
||||
switched = true
|
||||
// Re-enqueue after dequeue so the older in-flight snapshot merges into a newer queued entry.
|
||||
reportVisiblePRRefreshCandidates([churnCandidate(2)], 2, 1)
|
||||
}
|
||||
return {
|
||||
kind: 'found' as const,
|
||||
pr: makePR({ checksStatus: 'pending' as const }),
|
||||
fetchedAt: Date.now()
|
||||
}
|
||||
})
|
||||
|
||||
reportVisiblePRRefreshCandidates([churnCandidate(1)], 1, 1)
|
||||
await vi.advanceTimersByTimeAsync(120_000)
|
||||
|
||||
expect(_getPRRefreshAliasCountForTests(LINKED_PR_KEY)).toBe(1)
|
||||
const broadcasts = coordinatorMocks.sendMock.mock.calls.filter(
|
||||
(call) => call[0] === 'gh:prRefreshEvent'
|
||||
) as [string, { aliases: { cacheKey: string }[] }][]
|
||||
const lastBroadcast = broadcasts.at(-1)
|
||||
expect(lastBroadcast?.[1].aliases.map((alias) => alias.cacheKey)).toEqual(['/repo::churn/2'])
|
||||
})
|
||||
})
|
||||
@@ -1,128 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types'
|
||||
import type { PullRequestLookupData } from '../../client/lookup/pull-request-lookup-data'
|
||||
import { makeCandidate } from './pr-refresh-coordinator-test-harness'
|
||||
|
||||
const fixture = vi.hoisted(() => ({
|
||||
lookup: vi.fn(),
|
||||
conflict: vi.fn(),
|
||||
stack: { number: 2, position: 1, size: 2, baseRefName: 'main', baseSha: 'base-sha' }
|
||||
}))
|
||||
vi.mock('../../repositories/github-api-repository', () => ({
|
||||
resolveGitHubApiRepositoryCandidates: async () => ({
|
||||
candidates: [{ owner: 'acme', repo: 'widgets' }],
|
||||
headRepo: { owner: 'acme', repo: 'widgets' }
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('../../repositories/github-api-repository-remote-probe', () => ({
|
||||
getOriginGitHubApiRepository: async () => ({ owner: 'acme', repo: 'widgets' })
|
||||
}))
|
||||
vi.mock('../../api/rate-limit', () => ({
|
||||
repositoryRateLimitGuard: () => ({ blocked: false }),
|
||||
spendsSharedGitHubComQuota: () => false
|
||||
}))
|
||||
vi.mock('../../client/lookup/pr-number-lookup', () => ({ lookupPRByNumber: fixture.lookup }))
|
||||
vi.mock('../../client/lookup/pr-stack-summary-cache', () => ({
|
||||
getCachedGitHubPRStackSummary: async () => fixture.stack
|
||||
}))
|
||||
vi.mock('../stacks/github-pr-stack', () => ({
|
||||
hydrateGitHubPRStack: async () => fixture.stack
|
||||
}))
|
||||
vi.mock('../../client/detect/repository-merge-metadata', () => ({
|
||||
detectRepositoryMergeMetadata: async () => ({ mergeQueueRequired: true })
|
||||
}))
|
||||
vi.mock('../conflicts/conflict-summary', () => ({
|
||||
getPRConflictSummary: fixture.conflict
|
||||
}))
|
||||
|
||||
const data: PullRequestLookupData = {
|
||||
number: 12,
|
||||
title: 'Conflicting change',
|
||||
state: 'OPEN',
|
||||
url: 'https://github.com/acme/widgets/pull/12',
|
||||
updatedAt: '2026-11-11T00:00:00Z',
|
||||
mergeable: 'CONFLICTING',
|
||||
baseRefName: 'main',
|
||||
baseRefOid: 'base-sha',
|
||||
headRefName: 'topic',
|
||||
headRefOid: 'head-sha',
|
||||
checksUnavailable: false,
|
||||
statusCheckRollup: [{ __typename: 'CheckRun', name: 'build', status: 'IN_PROGRESS' }]
|
||||
}
|
||||
const summary = { baseRef: 'main', baseCommit: 'base-sh', commitsBehind: 1, files: ['a.ts'] }
|
||||
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('watches preserve provider checks while full and phone reads retain derived details', async () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(1_000)
|
||||
fixture.lookup.mockImplementation(async () => ({
|
||||
data: { ...data },
|
||||
dataRepo: { owner: 'acme', repo: 'widgets' }
|
||||
}))
|
||||
fixture.conflict.mockResolvedValue(summary)
|
||||
const { addPRRefreshOutcomeObserver, schedulePRWatchRead } =
|
||||
await import('./pr-refresh-coordinator')
|
||||
const { getPRForBranchOutcome, readRecentPhonePROutcome } =
|
||||
await import('../../client/lookup/pr-for-branch-outcome')
|
||||
const candidate = makeCandidate({ branch: 'topic', linkedPRNumber: 12 })
|
||||
const watched = Promise.withResolvers<PRRefreshOutcome>()
|
||||
const unsubscribe = addPRRefreshOutcomeObserver((_, outcome) => watched.resolve(outcome))
|
||||
schedulePRWatchRead({ prKey: 'github.com/acme/widgets#12' }, candidate, Date.now())
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
const watch = await watched.promise
|
||||
unsubscribe()
|
||||
expect(watch).toMatchObject({
|
||||
kind: 'found',
|
||||
pr: { number: 12, headSha: 'head-sha', state: 'open', checksStatus: 'pending' }
|
||||
})
|
||||
if (watch.kind !== 'found') {
|
||||
throw new Error('watch did not find the PR')
|
||||
}
|
||||
expect(watch.pr.conflictSummary).toBeUndefined()
|
||||
expect(watch.pr.stack).toBeUndefined()
|
||||
expect(watch.pr.mergeQueueRequired).toBeUndefined()
|
||||
|
||||
// An uncapped partial read must also stay separate from a concurrent full read.
|
||||
const provider = Promise.withResolvers<void>()
|
||||
const entered = Promise.withResolvers<void>()
|
||||
const conflict = Promise.withResolvers<typeof summary>()
|
||||
fixture.lookup.mockImplementation(async () => {
|
||||
entered.resolve()
|
||||
await provider.promise
|
||||
return { data: { ...data }, dataRepo: { owner: 'acme', repo: 'widgets' } }
|
||||
})
|
||||
fixture.conflict.mockReturnValue(conflict.promise)
|
||||
const partial = getPRForBranchOutcome('/repo', 'topic', 12, null, null, {
|
||||
includeDerivedData: false
|
||||
})
|
||||
await entered.promise
|
||||
const full = getPRForBranchOutcome('/repo', 'topic', 12, null, null)
|
||||
provider.resolve()
|
||||
try {
|
||||
expect(await partial).toMatchObject({ kind: 'found', pr: { conflictSummary: undefined } })
|
||||
expect(
|
||||
await readRecentPhonePROutcome('/repo', 'topic', 12, null, null, {
|
||||
currentHeadOid: 'head-sha'
|
||||
})
|
||||
).toBeNull()
|
||||
} finally {
|
||||
conflict.resolve(summary)
|
||||
}
|
||||
const complete = await full
|
||||
expect(complete).toMatchObject({
|
||||
kind: 'found',
|
||||
pr: {
|
||||
number: 12,
|
||||
headSha: 'head-sha',
|
||||
checksStatus: 'pending',
|
||||
conflictSummary: { files: ['a.ts'], commitsBehind: 1 },
|
||||
stack: { number: 2, baseRefName: 'main' },
|
||||
mergeQueueRequired: true
|
||||
}
|
||||
})
|
||||
expect(
|
||||
await readRecentPhonePROutcome('/repo', 'topic', 12, null, null, { currentHeadOid: 'head-sha' })
|
||||
).toEqual(complete)
|
||||
})
|
||||
@@ -1,53 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { ghExecFileAsyncMock, rateLimitGuardMock, noteRateLimitSpendMock } = vi.hoisted(() => ({
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
rateLimitGuardMock: vi.fn(() => ({ blocked: false })),
|
||||
noteRateLimitSpendMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
ghExecFileAsync: ghExecFileAsyncMock
|
||||
}))
|
||||
vi.mock('../../api/rate-limit', () => ({
|
||||
repositoryRateLimitGuard: rateLimitGuardMock,
|
||||
noteRepositoryRateLimitSpend: noteRateLimitSpendMock
|
||||
}))
|
||||
import { _resetGitHubPRStackCacheForTests } from './github-pr-stack'
|
||||
import { mergeGitHubPRStack } from './github-pr-stack-async-merge'
|
||||
|
||||
const repository = { owner: 'stablyai', repo: 'orca', host: 'github.com' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useRealTimers()
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
rateLimitGuardMock.mockReset()
|
||||
rateLimitGuardMock.mockReturnValue({ blocked: false })
|
||||
noteRateLimitSpendMock.mockReset()
|
||||
_resetGitHubPRStackCacheForTests()
|
||||
})
|
||||
|
||||
describe('mergeGitHubPRStack', () => {
|
||||
it('reports an in-progress merge after polling is exhausted', async () => {
|
||||
vi.useFakeTimers()
|
||||
ghExecFileAsyncMock.mockResolvedValue({
|
||||
stdout: JSON.stringify({ status: 'pending', details: { uuid: 'merge-uuid' } })
|
||||
})
|
||||
|
||||
const result = mergeGitHubPRStack({
|
||||
repository,
|
||||
prNumber: 202,
|
||||
method: 'squash',
|
||||
mergeAction: 'direct_merge',
|
||||
ghOptions: { cwd: '/repo' }
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(180_000)
|
||||
|
||||
await expect(result).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: 'GitHub is still merging this stack. Refresh to check its status.'
|
||||
})
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(181)
|
||||
})
|
||||
})
|
||||
@@ -1,68 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as GitExecFileModule from '../../git/command-runner/git-exec-file'
|
||||
|
||||
const { gitExecFileAsyncMock } = vi.hoisted(() => ({
|
||||
gitExecFileAsyncMock: vi.fn<(args: string[]) => Promise<{ stdout: string; stderr: string }>>()
|
||||
}))
|
||||
|
||||
vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GitExecFileModule>()),
|
||||
gitExecFileAsync: gitExecFileAsyncMock
|
||||
}))
|
||||
|
||||
import { _resetOwnerRepoCache } from './github-repository-identity'
|
||||
import { _resetRemoteNameListingCache } from '../../git/remotes/remote-name-listing'
|
||||
import {
|
||||
_resetOriginGitHubApiRepositoryCache,
|
||||
getGitHubApiRepositoryForRemote
|
||||
} from './github-api-repository-remote-probe'
|
||||
|
||||
// Why: no real .git config means no config signature, so caches use their short unsigned TTLs.
|
||||
const REPO_PATH = '/does-not-exist/orca-remote-probe-fixture'
|
||||
|
||||
function mockRemotes(remotes: Record<string, string>): void {
|
||||
gitExecFileAsyncMock.mockImplementation((args) => {
|
||||
if (args[0] === 'remote' && args.length === 1) {
|
||||
return Promise.resolve({ stdout: Object.keys(remotes).join('\n'), stderr: '' })
|
||||
}
|
||||
if (args[0] === 'remote' && args[1] === 'get-url') {
|
||||
const url = remotes[args[2]]
|
||||
if (url) {
|
||||
return Promise.resolve({ stdout: `${url}\n`, stderr: '' })
|
||||
}
|
||||
return Promise.reject(
|
||||
Object.assign(new Error(`git remote get-url ${args[2]}`), {
|
||||
stderr: `error: No such remote '${args[2]}'`
|
||||
})
|
||||
)
|
||||
}
|
||||
return Promise.reject(new Error(`unexpected git exec: ${JSON.stringify(args)}`))
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
_resetOriginGitHubApiRepositoryCache()
|
||||
_resetOwnerRepoCache()
|
||||
_resetRemoteNameListingCache()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('getGitHubApiRepositoryForRemote', () => {
|
||||
it('still resolves a configured upstream remote', async () => {
|
||||
mockRemotes({
|
||||
origin: 'https://github.com/acme/orca.git',
|
||||
upstream: 'https://github.com/stablyai/orca.git'
|
||||
})
|
||||
|
||||
await expect(getGitHubApiRepositoryForRemote(REPO_PATH, 'upstream')).resolves.toEqual({
|
||||
owner: 'stablyai',
|
||||
repo: 'orca',
|
||||
host: 'github.com'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,55 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as GitRunner from '../../git/command-runner/git-exec-file'
|
||||
|
||||
const { gitExecFileAsyncMock, readLocalGitConfigSignatureMock } = vi.hoisted(() => ({
|
||||
gitExecFileAsyncMock: vi.fn(),
|
||||
readLocalGitConfigSignatureMock: vi.fn<() => Promise<string | undefined>>(async () => 'sig-1')
|
||||
}))
|
||||
|
||||
vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GitRunner>()),
|
||||
gitExecFileAsync: gitExecFileAsyncMock
|
||||
}))
|
||||
|
||||
vi.mock('./local-git-config-signature', () => ({
|
||||
readLocalGitConfigSignature: readLocalGitConfigSignatureMock
|
||||
}))
|
||||
|
||||
import { getOwnerRepoForRemote, _resetOwnerRepoCache } from './github-repository-identity'
|
||||
|
||||
const REPO = '/tmp/signed-cache-repo'
|
||||
const THIRTY_SECONDS = 30_000
|
||||
|
||||
let remoteUrl = 'https://github.com/stablyai/orca.git'
|
||||
|
||||
const remoteGetUrlCalls = (): number =>
|
||||
gitExecFileAsyncMock.mock.calls.filter(([args]) => (args as string[])[1] === 'get-url').length
|
||||
|
||||
beforeEach(() => {
|
||||
_resetOwnerRepoCache()
|
||||
vi.useRealTimers()
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
remoteUrl = 'https://github.com/stablyai/orca.git'
|
||||
readLocalGitConfigSignatureMock.mockReset()
|
||||
readLocalGitConfigSignatureMock.mockImplementation(async () => 'sig-1')
|
||||
gitExecFileAsyncMock.mockImplementation(async () => ({ stdout: remoteUrl }))
|
||||
})
|
||||
|
||||
describe('owner/repo identity cache', () => {
|
||||
it('re-probes as soon as the git config signature changes', async () => {
|
||||
vi.useFakeTimers()
|
||||
await getOwnerRepoForRemote(REPO, 'origin')
|
||||
expect(remoteGetUrlCalls()).toBe(1)
|
||||
|
||||
remoteUrl = 'https://github.com/other-org/orca.git'
|
||||
readLocalGitConfigSignatureMock.mockImplementation(async () => 'sig-2')
|
||||
vi.setSystemTime(Date.now() + THIRTY_SECONDS)
|
||||
|
||||
await expect(getOwnerRepoForRemote(REPO, 'origin')).resolves.toEqual({
|
||||
owner: 'other-org',
|
||||
repo: 'orca'
|
||||
})
|
||||
expect(remoteGetUrlCalls()).toBe(2)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
@@ -1,218 +0,0 @@
|
||||
import type * as GithubRepositoryIdentityModule from '../repositories/github-repository-identity'
|
||||
import type * as WorkItemDetailsTestLookup from './work-item-details-test-lookup'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
type RateLimitGuardResult =
|
||||
| { blocked: false }
|
||||
| { blocked: true; remaining: number; limit: number; resetAt: number }
|
||||
|
||||
const {
|
||||
ghExecFileAsyncMock,
|
||||
getEnterpriseGitHubRepoSlugMock,
|
||||
getOwnerRepoMock,
|
||||
getWorkItemMock,
|
||||
getPRChecksMock,
|
||||
getPRCommentsMock,
|
||||
noteRepositoryRateLimitSpendMock,
|
||||
repositoryRateLimitGuardMock
|
||||
} = vi.hoisted(() => ({
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getEnterpriseGitHubRepoSlugMock: vi.fn(),
|
||||
getOwnerRepoMock: vi.fn(),
|
||||
getWorkItemMock: vi.fn(),
|
||||
getPRChecksMock: 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 }
|
||||
) => RateLimitGuardResult
|
||||
>(() => ({ blocked: false }))
|
||||
}))
|
||||
|
||||
vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({
|
||||
ghExecFileAsync: ghExecFileAsyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../repositories/github-repository-identity', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubRepositoryIdentityModule>()),
|
||||
getOwnerRepoForRemote: getOwnerRepoMock,
|
||||
ghRepoExecOptions: vi.fn((context) => ({ cwd: context.repoPath })),
|
||||
githubRepoContext: vi.fn((repoPath, connectionId, localGitOptions) => ({
|
||||
repoPath,
|
||||
connectionId: connectionId ?? null,
|
||||
...localGitOptions
|
||||
}))
|
||||
}))
|
||||
|
||||
vi.mock('../repositories/github-owner-repo-selection', () => ({
|
||||
getOwnerRepo: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../execution/github-operation-slots', () => ({
|
||||
acquire: vi.fn(),
|
||||
release: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../client/fetch/get-work-item', async () => ({
|
||||
getWorkItem: getWorkItemMock,
|
||||
getWorkItemWithRepository: (
|
||||
await vi.importActual<typeof WorkItemDetailsTestLookup>('./work-item-details-test-lookup')
|
||||
).makeWorkItemDetailsLookupMock(getWorkItemMock),
|
||||
getWorkItemByOwnerRepo: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../client/check/get-pr-checks', async () => ({
|
||||
getPRChecks: getPRChecksMock
|
||||
}))
|
||||
|
||||
vi.mock('../client/fetch/get-pr-comments', async () => ({
|
||||
getPRComments: getPRCommentsMock
|
||||
}))
|
||||
|
||||
vi.mock('../repositories/github-enterprise-repository', () => ({
|
||||
getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock,
|
||||
isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true)
|
||||
}))
|
||||
|
||||
vi.mock('../api/rate-limit', () => ({
|
||||
rateLimitGuard: vi.fn(() => ({ blocked: false })),
|
||||
noteRateLimitSpend: vi.fn(),
|
||||
repositoryRateLimitGuard: repositoryRateLimitGuardMock,
|
||||
noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock
|
||||
}))
|
||||
import { getWorkItemDetails } from './work-item-details'
|
||||
|
||||
import { _resetOriginGitHubApiRepositoryCache } from '../repositories/github-api-repository-remote-probe'
|
||||
|
||||
beforeEach(() => {
|
||||
_resetOriginGitHubApiRepositoryCache()
|
||||
})
|
||||
|
||||
function pullRequestItem(number: number, title: string): Record<string, unknown> {
|
||||
return {
|
||||
id: `pr:${number}`,
|
||||
type: 'pr',
|
||||
number,
|
||||
title,
|
||||
state: 'open',
|
||||
url: `https://github.com/acme/widgets/pull/${number}`,
|
||||
labels: [],
|
||||
updatedAt: '2026-07-16T00:00:00Z',
|
||||
author: 'pr-author'
|
||||
}
|
||||
}
|
||||
|
||||
function auxiliaryPRResponse(args: string[]): { stdout: string } {
|
||||
const query = args.find((arg) => arg.startsWith('query=')) ?? ''
|
||||
if (query.includes('viewerViewedState')) {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
viewedPullRequest: {
|
||||
id: 'PR_file_list',
|
||||
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: {} }) }
|
||||
}
|
||||
|
||||
describe('getWorkItemDetails PR file listing', () => {
|
||||
beforeEach(() => {
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getOwnerRepoMock.mockReset()
|
||||
getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' })
|
||||
getEnterpriseGitHubRepoSlugMock.mockReset()
|
||||
getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null)
|
||||
getWorkItemMock.mockReset()
|
||||
getPRChecksMock.mockReset()
|
||||
getPRChecksMock.mockResolvedValue([])
|
||||
getPRCommentsMock.mockReset()
|
||||
getPRCommentsMock.mockResolvedValue([])
|
||||
noteRepositoryRateLimitSpendMock.mockReset()
|
||||
repositoryRateLimitGuardMock.mockReset()
|
||||
repositoryRateLimitGuardMock.mockReturnValue({ blocked: false })
|
||||
})
|
||||
|
||||
it('loads files beyond the first 100-result REST page', async () => {
|
||||
getWorkItemMock.mockResolvedValueOnce(pullRequestItem(108, 'Large PR'))
|
||||
const restFile = (index: number) => ({
|
||||
filename: `src/file-${index}.ts`,
|
||||
status: 'modified',
|
||||
additions: 1,
|
||||
deletions: 0,
|
||||
changes: 1,
|
||||
patch: '@@ -1 +1 @@'
|
||||
})
|
||||
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
||||
const endpoint = args.find((arg) => arg.startsWith('repos/')) ?? ''
|
||||
if (endpoint === 'repos/acme/widgets/pulls/108') {
|
||||
return { stdout: JSON.stringify({ head: { sha: 'head' }, base: { sha: 'base' } }) }
|
||||
}
|
||||
if (endpoint === 'repos/acme/widgets/pulls/108/files?per_page=100') {
|
||||
return {
|
||||
stdout: JSON.stringify(Array.from({ length: 100 }, (_, index) => restFile(index)))
|
||||
}
|
||||
}
|
||||
if (endpoint === 'repos/acme/widgets/pulls/108/files?per_page=100&page=2') {
|
||||
return { stdout: JSON.stringify([restFile(100)]) }
|
||||
}
|
||||
return auxiliaryPRResponse(args)
|
||||
})
|
||||
|
||||
const details = await getWorkItemDetails('/repo-root', 108, 'pr')
|
||||
|
||||
expect(details?.files).toHaveLength(101)
|
||||
expect(details?.files?.at(-1)?.path).toBe('src/file-100.ts')
|
||||
const fileEndpoints = ghExecFileAsyncMock.mock.calls
|
||||
.map(([args]) => (args as string[]).find((arg) => arg.includes('/files?')))
|
||||
.filter(Boolean)
|
||||
expect(fileEndpoints).toEqual([
|
||||
'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)
|
||||
})
|
||||
|
||||
it('does not run bare PR detail commands when local host resolution fails', async () => {
|
||||
getWorkItemMock.mockResolvedValueOnce({
|
||||
...pullRequestItem(9, 'Unresolved PR'),
|
||||
prRepo: { owner: 'team', repo: 'orca' }
|
||||
})
|
||||
getOwnerRepoMock.mockResolvedValue(null)
|
||||
|
||||
const details = await getWorkItemDetails('/repo-root', 9, 'pr')
|
||||
|
||||
expect(details).toMatchObject({ body: '', comments: [], checks: [], filesUnavailable: true })
|
||||
expect(getPRCommentsMock).not.toHaveBeenCalled()
|
||||
expect(getPRChecksMock).not.toHaveBeenCalled()
|
||||
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,212 +0,0 @@
|
||||
import type * as GithubRepositoryIdentityModule from '../repositories/github-repository-identity'
|
||||
import type * as WorkItemDetailsTestLookup from './work-item-details-test-lookup'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
type RateLimitGuardResult =
|
||||
| { blocked: false }
|
||||
| { blocked: true; remaining: number; limit: number; resetAt: number }
|
||||
|
||||
const {
|
||||
ghExecFileAsyncMock,
|
||||
getOwnerRepoMock,
|
||||
getOwnerRepoForRemoteMock,
|
||||
getEnterpriseGitHubRepoSlugMock,
|
||||
getEnterpriseGitHubRepoSlugForRemoteMock,
|
||||
getWorkItemMock,
|
||||
getWorkItemByOwnerRepoMock,
|
||||
getPRChecksMock,
|
||||
getPRCommentsMock,
|
||||
repositoryRateLimitGuardMock,
|
||||
noteRepositoryRateLimitSpendMock,
|
||||
ghRepoExecOptionsMock,
|
||||
githubRepoContextMock,
|
||||
acquireMock,
|
||||
releaseMock
|
||||
} = vi.hoisted(() => ({
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getOwnerRepoMock: vi.fn(),
|
||||
getOwnerRepoForRemoteMock: vi.fn(),
|
||||
getEnterpriseGitHubRepoSlugMock: vi.fn(),
|
||||
getEnterpriseGitHubRepoSlugForRemoteMock: vi.fn(),
|
||||
getWorkItemMock: vi.fn(),
|
||||
getWorkItemByOwnerRepoMock: vi.fn(),
|
||||
getPRChecksMock: vi.fn(),
|
||||
getPRCommentsMock: vi.fn(),
|
||||
repositoryRateLimitGuardMock: vi.fn<
|
||||
(
|
||||
repository: { host?: string } | null | undefined,
|
||||
bucket: 'core' | 'graphql' | 'search',
|
||||
options?: { cwd?: string; wslDistro?: string }
|
||||
) => RateLimitGuardResult
|
||||
>(() => ({ blocked: false })),
|
||||
noteRepositoryRateLimitSpendMock: vi.fn(),
|
||||
ghRepoExecOptionsMock: vi.fn((context) =>
|
||||
context.connectionId
|
||||
? {}
|
||||
: { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) }
|
||||
),
|
||||
githubRepoContextMock: vi.fn((repoPath, connectionId, localGitOptions) => ({
|
||||
repoPath,
|
||||
connectionId: connectionId ?? null,
|
||||
...localGitOptions
|
||||
})),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({
|
||||
ghExecFileAsync: ghExecFileAsyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../repositories/github-owner-repo-selection', () => ({
|
||||
getOwnerRepo: getOwnerRepoMock
|
||||
}))
|
||||
|
||||
vi.mock('../repositories/github-repository-identity', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubRepositoryIdentityModule>()),
|
||||
getOwnerRepoForRemote: getOwnerRepoForRemoteMock,
|
||||
ghRepoExecOptions: ghRepoExecOptionsMock,
|
||||
githubRepoContext: githubRepoContextMock
|
||||
}))
|
||||
|
||||
vi.mock('../execution/github-operation-slots', () => ({
|
||||
acquire: acquireMock,
|
||||
release: releaseMock
|
||||
}))
|
||||
|
||||
vi.mock('../client/fetch/get-work-item', async () => ({
|
||||
getWorkItem: getWorkItemMock,
|
||||
getWorkItemWithRepository: (
|
||||
await vi.importActual<typeof WorkItemDetailsTestLookup>('./work-item-details-test-lookup')
|
||||
).makeWorkItemDetailsLookupMock(getWorkItemMock),
|
||||
getWorkItemByOwnerRepo: getWorkItemByOwnerRepoMock
|
||||
}))
|
||||
|
||||
vi.mock('../client/check/get-pr-checks', async () => ({
|
||||
getPRChecks: getPRChecksMock
|
||||
}))
|
||||
|
||||
vi.mock('../client/fetch/get-pr-comments', async () => ({
|
||||
getPRComments: getPRCommentsMock
|
||||
}))
|
||||
|
||||
vi.mock('../repositories/github-enterprise-repository', () => ({
|
||||
getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock,
|
||||
getEnterpriseGitHubRepoSlugForRemote: getEnterpriseGitHubRepoSlugForRemoteMock,
|
||||
isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true)
|
||||
}))
|
||||
|
||||
vi.mock('../api/rate-limit', () => ({
|
||||
repositoryRateLimitGuard: repositoryRateLimitGuardMock,
|
||||
noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock
|
||||
}))
|
||||
|
||||
import { getWorkItemDetails } from './work-item-details'
|
||||
|
||||
import { _resetOriginGitHubApiRepositoryCache } from '../repositories/github-api-repository-remote-probe'
|
||||
|
||||
beforeEach(() => {
|
||||
_resetOriginGitHubApiRepositoryCache()
|
||||
})
|
||||
|
||||
describe('getWorkItemDetails', () => {
|
||||
beforeEach(() => {
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getOwnerRepoMock.mockReset()
|
||||
getOwnerRepoForRemoteMock.mockReset()
|
||||
getEnterpriseGitHubRepoSlugMock.mockReset()
|
||||
getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null)
|
||||
getEnterpriseGitHubRepoSlugForRemoteMock.mockReset()
|
||||
getEnterpriseGitHubRepoSlugForRemoteMock.mockResolvedValue(null)
|
||||
getWorkItemMock.mockReset()
|
||||
getWorkItemByOwnerRepoMock.mockReset()
|
||||
getPRChecksMock.mockReset()
|
||||
getPRCommentsMock.mockReset()
|
||||
repositoryRateLimitGuardMock.mockReset()
|
||||
repositoryRateLimitGuardMock.mockReturnValue({ blocked: false })
|
||||
noteRepositoryRateLimitSpendMock.mockReset()
|
||||
ghRepoExecOptionsMock.mockClear()
|
||||
githubRepoContextMock.mockClear()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
acquireMock.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('caps issue timeline pagination by supported activity items', async () => {
|
||||
getWorkItemMock.mockResolvedValueOnce({
|
||||
id: 'issue:923',
|
||||
type: 'issue',
|
||||
number: 923,
|
||||
title: 'Use upstream issues',
|
||||
state: 'open',
|
||||
url: 'https://github.com/acme/widgets/issues/923',
|
||||
labels: [],
|
||||
updatedAt: '2026-04-01T00:00:00Z',
|
||||
author: 'issue-author'
|
||||
})
|
||||
getOwnerRepoForRemoteMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' })
|
||||
const makeTimelineEvent = (page: number, index: number, event: string): string =>
|
||||
JSON.stringify({
|
||||
id: `${page}:${index}`,
|
||||
event,
|
||||
actor: { login: 'issue-author', avatar_url: 'https://x/y' },
|
||||
assignee: { login: `assignee-${page}-${index}` },
|
||||
created_at: '2026-04-01T00:00:00Z'
|
||||
})
|
||||
const makeTimelinePage = (page: number, supportedCount: number): string =>
|
||||
Array.from({ length: 100 }, (_, index) =>
|
||||
makeTimelineEvent(page, index, index < supportedCount ? 'assigned' : 'subscribed')
|
||||
).join('\n')
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
issue: {
|
||||
body: 'Issue body',
|
||||
assignees: { nodes: [] },
|
||||
participants: { nodes: [] },
|
||||
comments: { nodes: [] }
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.mockResolvedValueOnce({ stdout: makeTimelinePage(1, 0) })
|
||||
.mockResolvedValueOnce({ stdout: makeTimelinePage(2, 0) })
|
||||
.mockResolvedValueOnce({ stdout: makeTimelinePage(3, 10) })
|
||||
.mockResolvedValueOnce({ stdout: makeTimelinePage(4, 100) })
|
||||
.mockResolvedValueOnce({ stdout: makeTimelinePage(5, 100) })
|
||||
.mockResolvedValueOnce({ stdout: makeTimelinePage(6, 100) })
|
||||
|
||||
const details = await getWorkItemDetails('/repo-root', 923, 'issue')
|
||||
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(7)
|
||||
expect(ghExecFileAsyncMock.mock.calls[1][0]).toContain(
|
||||
'repos/acme/widgets/issues/923/timeline?per_page=100&page=1'
|
||||
)
|
||||
expect(ghExecFileAsyncMock.mock.calls[2][0]).toContain(
|
||||
'repos/acme/widgets/issues/923/timeline?per_page=100&page=2'
|
||||
)
|
||||
expect(ghExecFileAsyncMock.mock.calls[3][0]).toContain(
|
||||
'repos/acme/widgets/issues/923/timeline?per_page=100&page=3'
|
||||
)
|
||||
expect(ghExecFileAsyncMock.mock.calls[6][0]).toContain(
|
||||
'repos/acme/widgets/issues/923/timeline?per_page=100&page=6'
|
||||
)
|
||||
expect(
|
||||
ghExecFileAsyncMock.mock.calls.some((call) =>
|
||||
call[0].includes('repos/acme/widgets/issues/923/timeline?per_page=100&page=7')
|
||||
)
|
||||
).toBe(false)
|
||||
const timelineItems = details?.timelineItems
|
||||
if (!timelineItems) {
|
||||
throw new Error('Expected timeline items to be present')
|
||||
}
|
||||
expect(timelineItems).toHaveLength(300)
|
||||
expect(timelineItems.at(0)).toMatchObject({ assignee: 'assignee-3-0' })
|
||||
expect(timelineItems.at(-1)).toMatchObject({ assignee: 'assignee-6-89' })
|
||||
})
|
||||
|
||||
// Number-based detail lookups must retain the list's source, avoiding same-number fork/upstream collisions.
|
||||
})
|
||||
Reference in New Issue
Block a user