mirror of
https://github.com/stablyai/orca.git
synced 2026-11-15 18:37:24 +00:00
refactor(github): organize concrete feature owners (#41601)
This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
import { resolveIssueGitHubApiRepositorySource } from '../repositories/github-api-repository'
|
||||
import type { getWorkItem, WorkItemRepositoryLookup } from '../client/fetch/get-work-item'
|
||||
|
||||
// Why: detail tests replace item lookup; retain its selected-source metadata.
|
||||
export function makeWorkItemDetailsLookupMock(lookup: typeof getWorkItem) {
|
||||
return async (...args: Parameters<typeof getWorkItem>): Promise<WorkItemRepositoryLookup> => {
|
||||
const [repoPath, number, type, connectionId, localGitOptions, preference] = args
|
||||
const item = await lookup(repoPath, number, type, connectionId, localGitOptions, preference)
|
||||
return {
|
||||
item,
|
||||
repository:
|
||||
item?.type === 'issue'
|
||||
? (await resolveIssueGitHubApiRepositorySource(args[0], args[5], args[3], args[4])).source
|
||||
: null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
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.
|
||||
})
|
||||
@@ -0,0 +1,284 @@
|
||||
import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding'
|
||||
import {
|
||||
withGitHubRepoExecution,
|
||||
type LocalGitExecOptions
|
||||
} from '../repositories/github-repository-identity'
|
||||
import type { PRCheckDetail } from '../../../shared/github/checks/check-types'
|
||||
|
||||
import type { GitHubWorkItemDetails } from '../../../shared/github/work-items/work-item-types'
|
||||
import type { IssueSourcePreference } from '../../../shared/repo-types'
|
||||
import { getPRChecks } from '../client/check/get-pr-checks'
|
||||
import { getPRComments } from '../client/fetch/get-pr-comments'
|
||||
import { getWorkItemWithRepository, getWorkItemByOwnerRepo } from '../client/fetch/get-work-item'
|
||||
import { acquire, release } from '../execution/github-operation-slots'
|
||||
|
||||
import { resolveGitHubRepoExecution } from '../repositories/github-api-repository'
|
||||
import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity'
|
||||
import { isValidGitHubApiRepository } from '../repositories/github-api-repository-validation'
|
||||
import {
|
||||
getIssueBodyAndComments,
|
||||
getIssueDetailsViaGraphQL
|
||||
} from '../issues/issue-work-item-details'
|
||||
import {
|
||||
getPRFiles,
|
||||
getPRMetadata,
|
||||
mergePRFileViewedStates
|
||||
} from '../pull-requests/files/pull-request-file-data'
|
||||
import { getPRDetailContext } from '../pull-requests/files/pull-request-detail-context'
|
||||
|
||||
import {
|
||||
enrichItemDisplayAvatars,
|
||||
getMentionParticipants,
|
||||
getWorkItemParticipants
|
||||
} from './work-item-participants'
|
||||
|
||||
function localGitOptionArgs(options: LocalGitExecOptions = {}): [] | [LocalGitExecOptions] {
|
||||
return Object.keys(options).length > 0 ? [options] : []
|
||||
}
|
||||
|
||||
async function withWorkItemDetailsPermit<T>(operation: () => Promise<T>): Promise<T> {
|
||||
await acquire()
|
||||
try {
|
||||
return await operation()
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
}
|
||||
|
||||
async function getPRChecksForDetails(
|
||||
repoPath: string,
|
||||
prNumber: number,
|
||||
headSha: string | undefined,
|
||||
repository: GitHubApiRepository | null,
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): Promise<PRCheckDetail[]> {
|
||||
if (!repository) {
|
||||
return []
|
||||
}
|
||||
try {
|
||||
return await getPRChecks(
|
||||
repoPath,
|
||||
prNumber,
|
||||
headSha,
|
||||
repository,
|
||||
undefined,
|
||||
connectionId,
|
||||
...localGitOptionArgs(localGitOptions)
|
||||
)
|
||||
} catch (error) {
|
||||
console.warn('getWorkItemDetails PR checks failed:', error)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export async function getWorkItemDetails(
|
||||
repoPath: string,
|
||||
number: number,
|
||||
type?: 'issue' | 'pr',
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {},
|
||||
preference?: IssueSourcePreference,
|
||||
repositoryOverride?: unknown,
|
||||
// Only an explicit Refresh asks for uncached reads whose required parts fail instead of collapsing to empty.
|
||||
canonical = false,
|
||||
expectedGhAccount?: GhAccountBinding | null
|
||||
): Promise<GitHubWorkItemDetails | null> {
|
||||
return withGitHubRepoExecution(
|
||||
repoPath,
|
||||
connectionId,
|
||||
localGitOptions,
|
||||
async () => {
|
||||
let repositoryTarget: GitHubApiRepository | null = null
|
||||
if (type && repositoryOverride != null) {
|
||||
if (!isValidGitHubApiRepository(repositoryOverride)) {
|
||||
return null
|
||||
}
|
||||
repositoryTarget = (
|
||||
await resolveGitHubRepoExecution(
|
||||
repoPath,
|
||||
repositoryOverride,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
).ownerRepo
|
||||
if (!repositoryTarget) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
const {
|
||||
item,
|
||||
repository: selectedRepository,
|
||||
issueDetails
|
||||
} = repositoryTarget
|
||||
? {
|
||||
item: await getWorkItemByOwnerRepo(
|
||||
repoPath,
|
||||
repositoryTarget,
|
||||
number,
|
||||
type === 'pr' ? 'pr' : 'issue',
|
||||
connectionId,
|
||||
localGitOptions
|
||||
),
|
||||
repository: repositoryTarget,
|
||||
issueDetails: undefined
|
||||
}
|
||||
: await getWorkItemWithRepository(
|
||||
repoPath,
|
||||
number,
|
||||
type,
|
||||
connectionId,
|
||||
localGitOptions,
|
||||
preference,
|
||||
type === 'issue' && !canonical
|
||||
)
|
||||
if (!item) {
|
||||
return null
|
||||
}
|
||||
|
||||
// The clone selects execution; an addressed item selects every detail read.
|
||||
const resolvedRepository =
|
||||
repositoryTarget ??
|
||||
(item.type === 'issue'
|
||||
? selectedRepository
|
||||
: (await resolveGitHubRepoExecution(repoPath, item.prRepo, connectionId, localGitOptions))
|
||||
.ownerRepo)
|
||||
|
||||
if (item.type === 'issue') {
|
||||
return withWorkItemDetailsPermit(async () => {
|
||||
const collapsed =
|
||||
issueDetails === undefined
|
||||
? await getIssueDetailsViaGraphQL(
|
||||
repoPath,
|
||||
item.number,
|
||||
resolvedRepository,
|
||||
connectionId,
|
||||
localGitOptions,
|
||||
false,
|
||||
canonical
|
||||
)
|
||||
: issueDetails
|
||||
if (collapsed) {
|
||||
return {
|
||||
item: enrichItemDisplayAvatars(item, [
|
||||
...collapsed.participants,
|
||||
...collapsed.assigneeUsers
|
||||
]),
|
||||
body: collapsed.body,
|
||||
bodyImageUrls: collapsed.bodyImageUrls,
|
||||
comments: collapsed.comments,
|
||||
assignees: item.assignees?.map((user) => user.login) ?? collapsed.assignees,
|
||||
participants: collapsed.participants,
|
||||
timelineItems: collapsed.timelineItems
|
||||
}
|
||||
}
|
||||
const [{ body, bodyImageUrls, comments, assignees, timelineItems }, participants] =
|
||||
await Promise.all([
|
||||
getIssueBodyAndComments(
|
||||
repoPath,
|
||||
item.number,
|
||||
resolvedRepository,
|
||||
connectionId,
|
||||
localGitOptions,
|
||||
canonical
|
||||
),
|
||||
getWorkItemParticipants(
|
||||
repoPath,
|
||||
item,
|
||||
resolvedRepository,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
])
|
||||
const mentionParticipants = await getMentionParticipants(
|
||||
repoPath,
|
||||
item,
|
||||
comments,
|
||||
participants,
|
||||
resolvedRepository,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
return {
|
||||
item: enrichItemDisplayAvatars(item, mentionParticipants),
|
||||
body,
|
||||
bodyImageUrls,
|
||||
comments,
|
||||
assignees: item.assignees?.map((user) => user.login) ?? assignees,
|
||||
participants: mentionParticipants,
|
||||
timelineItems
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Nested client reads own their semaphore permits, so they stay outside these permits.
|
||||
const [{ viewedStates, participants }, metadata, files, comments] = await Promise.all([
|
||||
withWorkItemDetailsPermit(() =>
|
||||
getPRDetailContext(
|
||||
repoPath,
|
||||
item.number,
|
||||
resolvedRepository,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
),
|
||||
withWorkItemDetailsPermit(() =>
|
||||
getPRMetadata(repoPath, item.number, resolvedRepository, connectionId, localGitOptions)
|
||||
),
|
||||
withWorkItemDetailsPermit(() =>
|
||||
getPRFiles(repoPath, item.number, resolvedRepository, connectionId, localGitOptions)
|
||||
),
|
||||
resolvedRepository
|
||||
? getPRComments(
|
||||
repoPath,
|
||||
item.number,
|
||||
// An explicit refresh must not join or reuse a read that started before it.
|
||||
{ prRepo: resolvedRepository, noCache: canonical },
|
||||
connectionId,
|
||||
...localGitOptionArgs(localGitOptions)
|
||||
)
|
||||
: Promise.resolve([])
|
||||
])
|
||||
|
||||
const [mentionParticipants, checks] = await Promise.all([
|
||||
withWorkItemDetailsPermit(() =>
|
||||
getMentionParticipants(
|
||||
repoPath,
|
||||
item,
|
||||
comments,
|
||||
participants,
|
||||
resolvedRepository,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
),
|
||||
getPRChecksForDetails(
|
||||
repoPath,
|
||||
item.number,
|
||||
metadata.headSha,
|
||||
resolvedRepository,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
])
|
||||
|
||||
return {
|
||||
item: enrichItemDisplayAvatars(
|
||||
resolvedRepository ? { ...item, prRepo: resolvedRepository } : item,
|
||||
mentionParticipants
|
||||
),
|
||||
body: metadata.body,
|
||||
bodyImageUrls: metadata.bodyImageUrls,
|
||||
comments,
|
||||
headSha: metadata.headSha,
|
||||
baseSha: metadata.baseSha,
|
||||
pullRequestId: viewedStates?.pullRequestId,
|
||||
checks,
|
||||
files: files === null ? undefined : mergePRFileViewedStates(files, viewedStates),
|
||||
filesUnavailable: files === null,
|
||||
participants: mentionParticipants
|
||||
}
|
||||
},
|
||||
expectedGhAccount
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import type { PRComment } from '../../../shared/github/comments/comment-types'
|
||||
import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types'
|
||||
import type { GitHubWorkItem } from '../../../shared/github/work-items/work-item-types'
|
||||
import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import {
|
||||
ghRepoExecOptions,
|
||||
githubRepoContext,
|
||||
type LocalGitExecOptions
|
||||
} from '../repositories/github-repository-identity'
|
||||
|
||||
import { githubHostExecOptions } from '../repositories/github-repository-host'
|
||||
import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity'
|
||||
import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../api/rate-limit'
|
||||
|
||||
const WORK_ITEM_PARTICIPANTS_QUERY = `query($owner: String!, $repo: String!, $number: Int!, $isPr: Boolean!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
pullRequest(number: $number) @include(if: $isPr) {
|
||||
participants(first: 100) {
|
||||
nodes { login avatarUrl(size: 48) ... on User { name } }
|
||||
}
|
||||
}
|
||||
issue(number: $number) @skip(if: $isPr) {
|
||||
participants(first: 100) {
|
||||
nodes { login avatarUrl(size: 48) ... on User { name } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
function mergeGitHubUsers(users: GitHubAssignableUser[]): GitHubAssignableUser[] {
|
||||
const byLogin = new Map<string, GitHubAssignableUser>()
|
||||
for (const user of users) {
|
||||
if (!user.login) {
|
||||
continue
|
||||
}
|
||||
const key = user.login.toLowerCase()
|
||||
const existing = byLogin.get(key)
|
||||
if (existing) {
|
||||
byLogin.set(key, {
|
||||
login: existing.login,
|
||||
name: existing.name ?? user.name ?? null,
|
||||
avatarUrl: existing.avatarUrl || user.avatarUrl || ''
|
||||
})
|
||||
continue
|
||||
}
|
||||
byLogin.set(key, {
|
||||
login: user.login,
|
||||
name: user.name ?? null,
|
||||
avatarUrl: user.avatarUrl ?? ''
|
||||
})
|
||||
}
|
||||
return Array.from(byLogin.values())
|
||||
}
|
||||
|
||||
export async function getWorkItemParticipants(
|
||||
repoPath: string,
|
||||
item: Pick<GitHubWorkItem, 'number' | 'type'>,
|
||||
repository: GitHubApiRepository | null,
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): Promise<GitHubAssignableUser[]> {
|
||||
if (!repository) {
|
||||
return []
|
||||
}
|
||||
const ghOptions = {
|
||||
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
|
||||
...githubHostExecOptions(repository)
|
||||
}
|
||||
if (repositoryRateLimitGuard(repository, 'graphql', ghOptions).blocked) {
|
||||
return []
|
||||
}
|
||||
try {
|
||||
noteRepositoryRateLimitSpend(repository, 'graphql', 1, ghOptions)
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'graphql',
|
||||
'-f',
|
||||
`query=${WORK_ITEM_PARTICIPANTS_QUERY}`,
|
||||
'-f',
|
||||
`owner=${repository.owner}`,
|
||||
'-f',
|
||||
`repo=${repository.repo}`,
|
||||
'-F',
|
||||
`number=${item.number}`,
|
||||
'-F',
|
||||
`isPr=${item.type === 'pr'}`
|
||||
],
|
||||
ghOptions
|
||||
)
|
||||
const data = JSON.parse(stdout) as {
|
||||
data?: {
|
||||
repository?: {
|
||||
pullRequest?: { participants?: { nodes?: GitHubAssignableUser[] } } | null
|
||||
issue?: { participants?: { nodes?: GitHubAssignableUser[] } } | null
|
||||
}
|
||||
}
|
||||
}
|
||||
const nodes =
|
||||
data.data?.repository?.pullRequest?.participants?.nodes ??
|
||||
data.data?.repository?.issue?.participants?.nodes ??
|
||||
[]
|
||||
return nodes
|
||||
.map((user) => ({
|
||||
login: user.login,
|
||||
name: user.name ?? null,
|
||||
avatarUrl: user.avatarUrl ?? ''
|
||||
}))
|
||||
.filter((user) => user.login)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
async function getGitHubUsersByLogin(
|
||||
repoPath: string,
|
||||
logins: string[],
|
||||
repository: GitHubApiRepository | null,
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): Promise<GitHubAssignableUser[]> {
|
||||
if (!repository) {
|
||||
return []
|
||||
}
|
||||
const uniqueLogins = Array.from(
|
||||
new Set(logins.filter((login) => login && login !== 'ghost').map((login) => login.trim()))
|
||||
).slice(0, 40)
|
||||
if (uniqueLogins.length === 0) {
|
||||
return []
|
||||
}
|
||||
const ghOptions = {
|
||||
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
|
||||
...githubHostExecOptions(repository)
|
||||
}
|
||||
if (repositoryRateLimitGuard(repository, 'graphql', ghOptions).blocked) {
|
||||
console.warn(
|
||||
`getGitHubUsersByLogin skipped: GraphQL rate-limit budget exhausted (${uniqueLogins.length} logins unresolved)`
|
||||
)
|
||||
return []
|
||||
}
|
||||
const fields = uniqueLogins
|
||||
.map(
|
||||
(login, index) =>
|
||||
`u${index}: user(login: ${JSON.stringify(login)}) { login name avatarUrl(size: 48) }`
|
||||
)
|
||||
.join('\n')
|
||||
try {
|
||||
noteRepositoryRateLimitSpend(repository, 'graphql', 1, ghOptions)
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
['api', 'graphql', '-f', `query=query { ${fields} }`],
|
||||
ghOptions
|
||||
)
|
||||
const data = JSON.parse(stdout) as {
|
||||
data?: Record<
|
||||
string,
|
||||
{ login?: string; name?: string | null; avatarUrl?: string | null } | null
|
||||
>
|
||||
}
|
||||
return Object.values(data.data ?? {})
|
||||
.filter((user): user is { login: string; name?: string | null; avatarUrl?: string | null } =>
|
||||
Boolean(user?.login)
|
||||
)
|
||||
.map((user) => ({
|
||||
login: user.login,
|
||||
name: user.name ?? null,
|
||||
avatarUrl: user.avatarUrl ?? ''
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMentionParticipants(
|
||||
repoPath: string,
|
||||
item: Pick<
|
||||
GitHubWorkItem,
|
||||
'author' | 'number' | 'type' | 'reviewRequests' | 'latestReviews' | 'assignees'
|
||||
>,
|
||||
comments: PRComment[],
|
||||
participants: GitHubAssignableUser[],
|
||||
repository: GitHubApiRepository | null,
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): Promise<GitHubAssignableUser[]> {
|
||||
const resolvedLogins = new Set(
|
||||
participants.filter((user) => user.avatarUrl).map((user) => user.login.toLowerCase())
|
||||
)
|
||||
const visibleLogins = [
|
||||
item.author ?? '',
|
||||
...(item.reviewRequests ?? []).map((user) => user.login),
|
||||
...(item.latestReviews ?? []).map((review) => review.login),
|
||||
...(item.assignees ?? []).map((user) => user.login),
|
||||
...comments.map((comment) => comment.author)
|
||||
]
|
||||
const graphQlUsers = await getGitHubUsersByLogin(
|
||||
repoPath,
|
||||
visibleLogins.filter((login) => !resolvedLogins.has(login.trim().toLowerCase())),
|
||||
repository,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
return mergeGitHubUsers([...participants, ...graphQlUsers])
|
||||
}
|
||||
|
||||
export function enrichItemDisplayAvatars(
|
||||
item: Omit<GitHubWorkItem, 'repoId'>,
|
||||
knownUsers: GitHubAssignableUser[]
|
||||
): Omit<GitHubWorkItem, 'repoId'> {
|
||||
const avatarByLogin = new Map<string, string>()
|
||||
for (const user of knownUsers) {
|
||||
if (user.login && user.avatarUrl) {
|
||||
avatarByLogin.set(user.login.toLowerCase(), user.avatarUrl)
|
||||
}
|
||||
}
|
||||
if (avatarByLogin.size === 0) {
|
||||
return item
|
||||
}
|
||||
const avatarFor = (login: string): string | undefined => avatarByLogin.get(login.toLowerCase())
|
||||
const resolvedAvatar = (login: string, existing?: string | null): string | undefined =>
|
||||
avatarFor(login) || existing || undefined
|
||||
const authorAvatarUrl = (item.author ? avatarFor(item.author) : undefined) || item.authorAvatarUrl
|
||||
return {
|
||||
...item,
|
||||
...(authorAvatarUrl ? { authorAvatarUrl } : {}),
|
||||
...(item.reviewRequests
|
||||
? {
|
||||
reviewRequests: item.reviewRequests.map((user) => ({
|
||||
...user,
|
||||
avatarUrl: resolvedAvatar(user.login, user.avatarUrl) ?? ''
|
||||
}))
|
||||
}
|
||||
: {}),
|
||||
...(item.latestReviews
|
||||
? {
|
||||
latestReviews: item.latestReviews.map((review) => ({
|
||||
...review,
|
||||
avatarUrl: resolvedAvatar(review.login, review.avatarUrl) ?? null
|
||||
}))
|
||||
}
|
||||
: {}),
|
||||
...(item.assignees
|
||||
? {
|
||||
assignees: item.assignees.map((user) => ({
|
||||
...user,
|
||||
avatarUrl: resolvedAvatar(user.login, user.avatarUrl) ?? ''
|
||||
}))
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type * as GithubApiRepositoryModule from '../repositories/github-api-repository'
|
||||
import type * as GithubApiRepositoryRemoteProbeModule from '../repositories/github-api-repository-remote-probe'
|
||||
import { afterEach, beforeEach, vi, type Mock } from 'vitest'
|
||||
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { basename } from 'node:path'
|
||||
|
||||
import type * as GitExecFileModule from '../../git/command-runner/git-exec-file'
|
||||
import { WorkItemSearchApi } from '../__fixtures__/work-item-search-api'
|
||||
|
||||
const {
|
||||
capture,
|
||||
sourceContext
|
||||
}: {
|
||||
capture: Mock<WorkItemSearchApi['capture']>
|
||||
sourceContext: { host: string; available: boolean }
|
||||
} = vi.hoisted(() => ({
|
||||
capture: vi.fn<WorkItemSearchApi['capture']>(),
|
||||
sourceContext: { host: 'github.com', available: true }
|
||||
}))
|
||||
const gitExecFileAsync = vi.hoisted(() => vi.fn())
|
||||
vi.mock('../../git/command-runner/process-capture/exec-file-capture', () => ({
|
||||
execFileCaptureToTermination: capture
|
||||
}))
|
||||
vi.mock('../../git/command-runner/host-routing/wsl-command-resolution', () => ({
|
||||
resolveCommand: (binary: string, args: string[], cwd?: string, distro?: string) => ({
|
||||
binary,
|
||||
args,
|
||||
cwd,
|
||||
wsl: distro ? { distro } : null,
|
||||
wslMode: null
|
||||
}),
|
||||
resolveDefaultWslCli: () => null
|
||||
}))
|
||||
|
||||
vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GitExecFileModule>()),
|
||||
gitExecFileAsync
|
||||
}))
|
||||
vi.mock('../repositories/github-api-repository', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof GithubApiRepositoryModule>()
|
||||
const source = (repoPath: string) =>
|
||||
sourceContext.available
|
||||
? { owner: 'fixture', repo: basename(repoPath), host: sourceContext.host }
|
||||
: null
|
||||
return {
|
||||
...actual,
|
||||
resolveIssueGitHubApiRepositorySource: async (repoPath: string) => ({
|
||||
source: source(repoPath),
|
||||
fellBack: false
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../repositories/github-api-repository-remote-probe', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof GithubApiRepositoryRemoteProbeModule>()
|
||||
const source = (repoPath: string) =>
|
||||
sourceContext.available
|
||||
? { owner: 'fixture', repo: basename(repoPath), host: sourceContext.host }
|
||||
: null
|
||||
return {
|
||||
...actual,
|
||||
getOriginGitHubApiRepository: async (repoPath: string) => source(repoPath),
|
||||
getGitHubApiRepositoryForRemote: async () => null
|
||||
}
|
||||
})
|
||||
|
||||
import { _resetRateLimitCache } from '../api/rate-limit'
|
||||
import {
|
||||
clearGhRateLimitBlock,
|
||||
ghRateLimitScopeKey
|
||||
} from '../../git/command-runner/hosted-cli/gh-rate-limit-breaker'
|
||||
export let api: WorkItemSearchApi
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] })
|
||||
vi.setSystemTime(0)
|
||||
vi.stubEnv('GH_HOST', 'github.com')
|
||||
vi.stubEnv('ORCA_WORK_ITEM_SEARCH_FIXTURE', randomUUID())
|
||||
_resetRateLimitCache()
|
||||
for (const runtime of ['native', 'wsl:ubuntu', 'wsl:debian']) {
|
||||
for (const host of ['github.com', 'github.example.com']) {
|
||||
for (const bucket of ['core', 'graphql', 'search'] as const) {
|
||||
clearGhRateLimitBlock(bucket, ghRateLimitScopeKey(runtime, host))
|
||||
}
|
||||
}
|
||||
}
|
||||
sourceContext.host = 'github.com'
|
||||
sourceContext.available = true
|
||||
api = new WorkItemSearchApi()
|
||||
capture.mockReset().mockImplementation(api.capture.bind(api))
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
export { capture, sourceContext }
|
||||
Reference in New Issue
Block a user