Prefer upstream remotes for GitHub issue tasks (#1076)
Co-authored-by: Orca <help@stably.ai> Co-authored-by: brennanb2025 <brennankbenson@gmail.com>
This commit is contained in:
co-authored by
Orca
brennanb2025
parent
44c90b9c9a
commit
ed6c8755fe
@@ -0,0 +1,238 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as GhUtils from './gh-utils'
|
||||
|
||||
const {
|
||||
execFileAsyncMock,
|
||||
ghExecFileAsyncMock,
|
||||
getOwnerRepoMock,
|
||||
getIssueOwnerRepoMock,
|
||||
acquireMock,
|
||||
releaseMock
|
||||
} = vi.hoisted(() => ({
|
||||
execFileAsyncMock: vi.fn(),
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getOwnerRepoMock: vi.fn(),
|
||||
getIssueOwnerRepoMock: vi.fn(),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./gh-utils', async () => {
|
||||
const actual = await vi.importActual<typeof GhUtils>('./gh-utils')
|
||||
return {
|
||||
...actual,
|
||||
execFileAsync: execFileAsyncMock,
|
||||
ghExecFileAsync: ghExecFileAsyncMock,
|
||||
getOwnerRepo: getOwnerRepoMock,
|
||||
getIssueOwnerRepo: getIssueOwnerRepoMock,
|
||||
acquire: acquireMock,
|
||||
release: releaseMock,
|
||||
_resetOwnerRepoCache: vi.fn()
|
||||
}
|
||||
})
|
||||
|
||||
import { countWorkItems, getWorkItem, listWorkItems, _resetOwnerRepoCache } from './client'
|
||||
|
||||
describe('GitHub issue source split', () => {
|
||||
beforeEach(() => {
|
||||
execFileAsyncMock.mockReset()
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getOwnerRepoMock.mockReset()
|
||||
getIssueOwnerRepoMock.mockReset()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
acquireMock.mockResolvedValue(undefined)
|
||||
_resetOwnerRepoCache()
|
||||
})
|
||||
|
||||
it('uses upstream for issues and origin for PRs in mixed recent results', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 923,
|
||||
title: 'Use upstream issues',
|
||||
state: 'open',
|
||||
html_url: 'https://github.com/stablyai/orca/issues/923',
|
||||
labels: [],
|
||||
updated_at: '2026-04-01T00:00:00Z',
|
||||
user: { login: 'octocat' }
|
||||
}
|
||||
])
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 42,
|
||||
title: 'Fork PR',
|
||||
state: 'open',
|
||||
html_url: 'https://github.com/fork/orca/pull/42',
|
||||
labels: [],
|
||||
updated_at: '2026-03-31T00:00:00Z',
|
||||
user: { login: 'octocat' },
|
||||
draft: false,
|
||||
head: { ref: 'feature' },
|
||||
base: { ref: 'main' }
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
await listWorkItems('/repo-root', 10)
|
||||
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
'repos/stablyai/orca/issues?per_page=10&state=open&sort=updated&direction=desc'
|
||||
],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
'repos/fork/orca/pulls?per_page=10&state=open&sort=updated&direction=desc'
|
||||
],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
})
|
||||
|
||||
it('uses upstream for issue-only queries and origin for PR-only queries', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' })
|
||||
|
||||
await listWorkItems('/repo-root', 10, 'is:issue')
|
||||
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
expect.arrayContaining(['--repo', 'stablyai/orca']),
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
|
||||
ghExecFileAsyncMock.mockClear()
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' })
|
||||
|
||||
await listWorkItems('/repo-root', 10, 'is:pr')
|
||||
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
expect.arrayContaining(['--repo', 'fork/orca']),
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
})
|
||||
|
||||
it('counts default work items across upstream issues and origin PRs', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: '7\n' })
|
||||
.mockResolvedValueOnce({ stdout: '5\n' })
|
||||
|
||||
const count = await countWorkItems('/repo-root')
|
||||
|
||||
expect(count).toBe(12)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
`search/issues?q=${encodeURIComponent('repo:stablyai/orca is:issue is:open')}&per_page=1`,
|
||||
'--jq',
|
||||
'.total_count'
|
||||
],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
`search/issues?q=${encodeURIComponent('repo:fork/orca is:pull-request is:open')}&per_page=1`,
|
||||
'--jq',
|
||||
'.total_count'
|
||||
],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
})
|
||||
|
||||
it('typed PR lookup does not fetch an upstream issue with the same number', async () => {
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: 'Origin PR',
|
||||
state: 'open',
|
||||
html_url: 'https://github.com/fork/orca/pull/42',
|
||||
labels: [],
|
||||
updated_at: '2026-04-02T00:00:00Z',
|
||||
user: { login: 'octocat' },
|
||||
draft: false,
|
||||
head: { ref: 'feature' },
|
||||
base: { ref: 'main' }
|
||||
})
|
||||
})
|
||||
|
||||
const item = await getWorkItem('/repo-root', 42, 'pr')
|
||||
|
||||
expect(getIssueOwnerRepoMock).not.toHaveBeenCalled()
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['api', 'repos/fork/orca/pulls/42'], {
|
||||
cwd: '/repo-root'
|
||||
})
|
||||
expect(item?.type).toBe('pr')
|
||||
})
|
||||
|
||||
it('raw number lookup tries upstream issue before origin PR', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
// Why: simulate a real gh 404 (the only error type that should fall through).
|
||||
// Non-404 errors re-throw so transient upstream failures don't misroute to an
|
||||
// unrelated origin PR with the same number.
|
||||
ghExecFileAsyncMock.mockRejectedValueOnce(new Error('HTTP 404: Not Found'))
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: 'Origin PR',
|
||||
state: 'open',
|
||||
html_url: 'https://github.com/fork/orca/pull/42',
|
||||
labels: [],
|
||||
updated_at: '2026-04-02T00:00:00Z',
|
||||
user: { login: 'octocat' },
|
||||
draft: false
|
||||
})
|
||||
})
|
||||
|
||||
const item = await getWorkItem('/repo-root', 42)
|
||||
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
['api', 'repos/stablyai/orca/issues/42'],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['api', 'repos/fork/orca/pulls/42'], {
|
||||
cwd: '/repo-root'
|
||||
})
|
||||
expect(item?.type).toBe('pr')
|
||||
})
|
||||
|
||||
it('raw number lookup does not fall through on transient upstream errors', async () => {
|
||||
// Why: with issue source split, a non-404 upstream failure must not silently
|
||||
// route to origin's PR #N — that would return an unrelated item.
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
ghExecFileAsyncMock.mockRejectedValueOnce(new Error('HTTP 500: server error'))
|
||||
|
||||
const item = await getWorkItem('/repo-root', 42)
|
||||
|
||||
expect(item).toBeNull()
|
||||
expect(getOwnerRepoMock).not.toHaveBeenCalled()
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,7 @@ const {
|
||||
execFileAsyncMock,
|
||||
ghExecFileAsyncMock,
|
||||
getOwnerRepoMock,
|
||||
getIssueOwnerRepoMock,
|
||||
gitExecFileAsyncMock,
|
||||
acquireMock,
|
||||
releaseMock
|
||||
@@ -11,6 +12,7 @@ const {
|
||||
execFileAsyncMock: vi.fn(),
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getOwnerRepoMock: vi.fn(),
|
||||
getIssueOwnerRepoMock: vi.fn(),
|
||||
gitExecFileAsyncMock: vi.fn(),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
@@ -20,6 +22,7 @@ vi.mock('./gh-utils', () => ({
|
||||
execFileAsync: execFileAsyncMock,
|
||||
ghExecFileAsync: ghExecFileAsyncMock,
|
||||
getOwnerRepo: getOwnerRepoMock,
|
||||
getIssueOwnerRepo: getIssueOwnerRepoMock,
|
||||
acquire: acquireMock,
|
||||
release: releaseMock,
|
||||
_resetOwnerRepoCache: vi.fn()
|
||||
@@ -36,6 +39,7 @@ describe('getPRChecks', () => {
|
||||
execFileAsyncMock.mockReset()
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getOwnerRepoMock.mockReset()
|
||||
getIssueOwnerRepoMock.mockReset()
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
|
||||
@@ -4,6 +4,7 @@ const {
|
||||
execFileAsyncMock,
|
||||
ghExecFileAsyncMock,
|
||||
getOwnerRepoMock,
|
||||
getIssueOwnerRepoMock,
|
||||
gitExecFileAsyncMock,
|
||||
acquireMock,
|
||||
releaseMock
|
||||
@@ -11,6 +12,7 @@ const {
|
||||
execFileAsyncMock: vi.fn(),
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getOwnerRepoMock: vi.fn(),
|
||||
getIssueOwnerRepoMock: vi.fn(),
|
||||
gitExecFileAsyncMock: vi.fn(),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
@@ -20,6 +22,7 @@ vi.mock('./gh-utils', () => ({
|
||||
execFileAsync: execFileAsyncMock,
|
||||
ghExecFileAsync: ghExecFileAsyncMock,
|
||||
getOwnerRepo: getOwnerRepoMock,
|
||||
getIssueOwnerRepo: getIssueOwnerRepoMock,
|
||||
acquire: acquireMock,
|
||||
release: releaseMock,
|
||||
_resetOwnerRepoCache: vi.fn()
|
||||
@@ -36,6 +39,7 @@ describe('listWorkItems', () => {
|
||||
execFileAsyncMock.mockReset()
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getOwnerRepoMock.mockReset()
|
||||
getIssueOwnerRepoMock.mockReset()
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
@@ -44,6 +48,7 @@ describe('listWorkItems', () => {
|
||||
})
|
||||
|
||||
it('runs both issue and PR GitHub searches for a mixed query and merges the results by recency', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({
|
||||
@@ -137,6 +142,7 @@ describe('listWorkItems', () => {
|
||||
})
|
||||
|
||||
it('routes draft queries to PR search only', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
@@ -190,6 +196,7 @@ describe('listWorkItems', () => {
|
||||
})
|
||||
|
||||
it('passes review-requested as a --search qualifier (gh CLI has no dedicated flag)', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' })
|
||||
|
||||
@@ -207,6 +214,7 @@ describe('listWorkItems', () => {
|
||||
})
|
||||
|
||||
it('returns open issues and PRs for the all-open preset query', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({
|
||||
|
||||
@@ -4,6 +4,7 @@ const {
|
||||
execFileAsyncMock,
|
||||
ghExecFileAsyncMock,
|
||||
getOwnerRepoMock,
|
||||
getIssueOwnerRepoMock,
|
||||
gitExecFileAsyncMock,
|
||||
acquireMock,
|
||||
releaseMock
|
||||
@@ -11,6 +12,7 @@ const {
|
||||
execFileAsyncMock: vi.fn(),
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getOwnerRepoMock: vi.fn(),
|
||||
getIssueOwnerRepoMock: vi.fn(),
|
||||
gitExecFileAsyncMock: vi.fn(),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
@@ -20,6 +22,7 @@ vi.mock('./gh-utils', () => ({
|
||||
execFileAsync: execFileAsyncMock,
|
||||
ghExecFileAsync: ghExecFileAsyncMock,
|
||||
getOwnerRepo: getOwnerRepoMock,
|
||||
getIssueOwnerRepo: getIssueOwnerRepoMock,
|
||||
acquire: acquireMock,
|
||||
release: releaseMock,
|
||||
_resetOwnerRepoCache: vi.fn()
|
||||
@@ -36,6 +39,7 @@ describe('getPRForBranch', () => {
|
||||
execFileAsyncMock.mockReset()
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getOwnerRepoMock.mockReset()
|
||||
getIssueOwnerRepoMock.mockReset()
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
|
||||
+246
-198
@@ -19,7 +19,9 @@ import {
|
||||
acquire,
|
||||
release,
|
||||
getOwnerRepo,
|
||||
classifyGhError
|
||||
getIssueOwnerRepo,
|
||||
classifyGhError,
|
||||
type OwnerRepo
|
||||
} from './gh-utils'
|
||||
export { _resetOwnerRepoCache } from './gh-utils'
|
||||
export {
|
||||
@@ -221,9 +223,59 @@ function mapPullRequestWorkItem(
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchIssueWorkItem(
|
||||
repoPath: string,
|
||||
ownerRepo: OwnerRepo | null,
|
||||
number: number
|
||||
): Promise<MainWorkItem | null> {
|
||||
if (ownerRepo) {
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${number}`],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
const item = JSON.parse(stdout) as Record<string, unknown>
|
||||
if ('pull_request' in item) {
|
||||
return null
|
||||
}
|
||||
return mapIssueWorkItem(item)
|
||||
}
|
||||
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
['issue', 'view', String(number), '--json', 'number,title,state,url,labels,updatedAt,author'],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
return mapIssueWorkItem(JSON.parse(stdout) as Record<string, unknown>)
|
||||
}
|
||||
|
||||
async function fetchPullRequestWorkItem(
|
||||
repoPath: string,
|
||||
ownerRepo: OwnerRepo | null,
|
||||
number: number
|
||||
): Promise<MainWorkItem> {
|
||||
if (ownerRepo) {
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${number}`],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
return mapPullRequestWorkItem(JSON.parse(stdout) as Record<string, unknown>, ownerRepo.owner)
|
||||
}
|
||||
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'pr',
|
||||
'view',
|
||||
String(number),
|
||||
'--json',
|
||||
'number,title,state,url,labels,updatedAt,author,isDraft,headRefName,baseRefName,headRepositoryOwner'
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
return mapPullRequestWorkItem(JSON.parse(stdout) as Record<string, unknown>)
|
||||
}
|
||||
|
||||
function buildWorkItemListArgs(args: {
|
||||
kind: 'issue' | 'pr'
|
||||
ownerRepo: { owner: string; repo: string } | null
|
||||
ownerRepo: OwnerRepo | null
|
||||
limit: number
|
||||
query: ParsedTaskQuery
|
||||
before?: string
|
||||
@@ -291,29 +343,58 @@ function buildWorkItemListArgs(args: {
|
||||
|
||||
async function listRecentWorkItems(
|
||||
repoPath: string,
|
||||
ownerRepo: { owner: string; repo: string } | null,
|
||||
issueOwnerRepo: OwnerRepo | null,
|
||||
prOwnerRepo: OwnerRepo | null,
|
||||
limit: number
|
||||
): Promise<MainWorkItem[]> {
|
||||
if (ownerRepo) {
|
||||
if (issueOwnerRepo || prOwnerRepo) {
|
||||
const [issuesResult, prsResult] = await Promise.all([
|
||||
ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues?per_page=${limit}&state=open&sort=updated&direction=desc`
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
),
|
||||
ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
`repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls?per_page=${limit}&state=open&sort=updated&direction=desc`
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
issueOwnerRepo
|
||||
? ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
`repos/${issueOwnerRepo.owner}/${issueOwnerRepo.repo}/issues?per_page=${limit}&state=open&sort=updated&direction=desc`
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
: ghExecFileAsync(
|
||||
[
|
||||
'issue',
|
||||
'list',
|
||||
'--limit',
|
||||
String(limit),
|
||||
'--state',
|
||||
'open',
|
||||
'--json',
|
||||
'number,title,state,url,labels,updatedAt,author'
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
),
|
||||
prOwnerRepo
|
||||
? ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
`repos/${prOwnerRepo.owner}/${prOwnerRepo.repo}/pulls?per_page=${limit}&state=open&sort=updated&direction=desc`
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
: ghExecFileAsync(
|
||||
[
|
||||
'pr',
|
||||
'list',
|
||||
'--limit',
|
||||
String(limit),
|
||||
'--state',
|
||||
'open',
|
||||
'--json',
|
||||
'number,title,state,url,labels,updatedAt,author,isDraft,headRefName,baseRefName,headRepositoryOwner'
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
])
|
||||
|
||||
const issues = (JSON.parse(issuesResult.stdout) as Record<string, unknown>[])
|
||||
@@ -324,7 +405,7 @@ async function listRecentWorkItems(
|
||||
.map(mapIssueWorkItem)
|
||||
|
||||
const prs = (JSON.parse(prsResult.stdout) as Record<string, unknown>[]).map((item) =>
|
||||
mapPullRequestWorkItem(item, ownerRepo.owner)
|
||||
mapPullRequestWorkItem(item, prOwnerRepo?.owner ?? null)
|
||||
)
|
||||
|
||||
return sortWorkItemsByUpdatedAt([...issues, ...prs]).slice(0, limit)
|
||||
@@ -371,7 +452,8 @@ async function listRecentWorkItems(
|
||||
|
||||
async function listQueriedWorkItems(
|
||||
repoPath: string,
|
||||
ownerRepo: { owner: string; repo: string } | null,
|
||||
issueOwnerRepo: OwnerRepo | null,
|
||||
prOwnerRepo: OwnerRepo | null,
|
||||
query: ParsedTaskQuery,
|
||||
limit: number,
|
||||
before?: string
|
||||
@@ -383,7 +465,13 @@ async function listQueriedWorkItems(
|
||||
if (issueScope) {
|
||||
fetchers.push(
|
||||
(async () => {
|
||||
const args = buildWorkItemListArgs({ kind: 'issue', ownerRepo, limit, query, before })
|
||||
const args = buildWorkItemListArgs({
|
||||
kind: 'issue',
|
||||
ownerRepo: issueOwnerRepo,
|
||||
limit,
|
||||
query,
|
||||
before
|
||||
})
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(args, { cwd: repoPath })
|
||||
return (JSON.parse(stdout) as Record<string, unknown>[]).map(mapIssueWorkItem)
|
||||
@@ -397,11 +485,17 @@ async function listQueriedWorkItems(
|
||||
if (prScope) {
|
||||
fetchers.push(
|
||||
(async () => {
|
||||
const args = buildWorkItemListArgs({ kind: 'pr', ownerRepo, limit, query, before })
|
||||
const args = buildWorkItemListArgs({
|
||||
kind: 'pr',
|
||||
ownerRepo: prOwnerRepo,
|
||||
limit,
|
||||
query,
|
||||
before
|
||||
})
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(args, { cwd: repoPath })
|
||||
return (JSON.parse(stdout) as Record<string, unknown>[]).map((item) =>
|
||||
mapPullRequestWorkItem(item, ownerRepo?.owner ?? null)
|
||||
mapPullRequestWorkItem(item, prOwnerRepo?.owner ?? null)
|
||||
)
|
||||
} catch {
|
||||
return []
|
||||
@@ -420,7 +514,10 @@ export async function listWorkItems(
|
||||
query?: string,
|
||||
before?: string
|
||||
): Promise<MainWorkItem[]> {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
const [issueOwnerRepo, prOwnerRepo] = await Promise.all([
|
||||
getIssueOwnerRepo(repoPath),
|
||||
getOwnerRepo(repoPath)
|
||||
])
|
||||
const trimmedQuery = query?.trim() ?? ''
|
||||
await acquire()
|
||||
try {
|
||||
@@ -429,11 +526,18 @@ export async function listWorkItems(
|
||||
// catch-all here would make an auth/network failure indistinguishable from
|
||||
// an empty result and silently under-report per-repo failures.
|
||||
if (!trimmedQuery) {
|
||||
return await listRecentWorkItems(repoPath, ownerRepo, limit)
|
||||
return await listRecentWorkItems(repoPath, issueOwnerRepo, prOwnerRepo, limit)
|
||||
}
|
||||
|
||||
const parsedQuery = parseTaskQuery(trimmedQuery)
|
||||
return await listQueriedWorkItems(repoPath, ownerRepo, parsedQuery, limit, before)
|
||||
return await listQueriedWorkItems(
|
||||
repoPath,
|
||||
issueOwnerRepo,
|
||||
prOwnerRepo,
|
||||
parsedQuery,
|
||||
limit,
|
||||
before
|
||||
)
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
@@ -480,36 +584,107 @@ function buildSearchQueryString(
|
||||
return parts.join(' ')
|
||||
}
|
||||
|
||||
async function countWorkItemsForQuery(
|
||||
repoPath: string,
|
||||
ownerRepo: OwnerRepo,
|
||||
query: ParsedTaskQuery
|
||||
): Promise<number> {
|
||||
const searchQ = buildSearchQueryString(ownerRepo, query)
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
`search/issues?q=${encodeURIComponent(searchQ)}&per_page=1`,
|
||||
'--jq',
|
||||
'.total_count'
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
return parseInt(stdout.trim(), 10) || 0
|
||||
}
|
||||
|
||||
function sameOwnerRepo(left: OwnerRepo | null, right: OwnerRepo | null): boolean {
|
||||
// Why: GitHub treats owner and repo names as case-insensitive, so remotes
|
||||
// with different casing (StablyAI/Orca vs stablyai/orca) point at the same
|
||||
// repo and should not split into two search queries.
|
||||
return (
|
||||
left?.owner.toLowerCase() === right?.owner.toLowerCase() &&
|
||||
left?.repo.toLowerCase() === right?.repo.toLowerCase()
|
||||
)
|
||||
}
|
||||
|
||||
function defaultOpenWorkItemQuery(): ParsedTaskQuery {
|
||||
return {
|
||||
scope: 'all',
|
||||
state: 'open',
|
||||
draft: false,
|
||||
assignee: null,
|
||||
author: null,
|
||||
reviewRequested: null,
|
||||
reviewedBy: null,
|
||||
labels: [],
|
||||
freeText: ''
|
||||
}
|
||||
}
|
||||
|
||||
// Why: uses GitHub's search API to get total_count without fetching items.
|
||||
// This powers the pagination bar so the user sees total pages upfront.
|
||||
// Cached for 120s to avoid burning the search rate limit (30 req/min).
|
||||
export async function countWorkItems(repoPath: string, query?: string): Promise<number> {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
const [issueOwnerRepo, prOwnerRepo] = await Promise.all([
|
||||
getIssueOwnerRepo(repoPath),
|
||||
getOwnerRepo(repoPath)
|
||||
])
|
||||
const ownerRepo = prOwnerRepo ?? issueOwnerRepo
|
||||
if (!ownerRepo) {
|
||||
return 0
|
||||
}
|
||||
|
||||
const trimmedQuery = query?.trim() ?? ''
|
||||
const parsedQuery = trimmedQuery ? parseTaskQuery(trimmedQuery) : null
|
||||
|
||||
const searchQ = parsedQuery
|
||||
? buildSearchQueryString(ownerRepo, parsedQuery)
|
||||
: `repo:${ownerRepo.owner}/${ownerRepo.repo} is:open`
|
||||
const effectiveQuery = parsedQuery ?? defaultOpenWorkItemQuery()
|
||||
|
||||
await acquire()
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
`search/issues?q=${encodeURIComponent(searchQ)}&per_page=1`,
|
||||
'--jq',
|
||||
'.total_count'
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
return parseInt(stdout.trim(), 10) || 0
|
||||
if (sameOwnerRepo(issueOwnerRepo, prOwnerRepo)) {
|
||||
return await countWorkItemsForQuery(repoPath, ownerRepo, effectiveQuery)
|
||||
}
|
||||
|
||||
const counts: Promise<number>[] = []
|
||||
// Why: `draft`, `reviewRequested`, and `reviewedBy` are PR-only predicates.
|
||||
// When present, the issue half would always return 0 and wastes a search
|
||||
// API call — skip the issue half entirely in that case.
|
||||
const hasPrOnlyFilter =
|
||||
effectiveQuery.draft ||
|
||||
effectiveQuery.reviewRequested !== null ||
|
||||
effectiveQuery.reviewedBy !== null
|
||||
if (
|
||||
effectiveQuery.scope !== 'pr' &&
|
||||
effectiveQuery.state !== 'merged' &&
|
||||
!hasPrOnlyFilter &&
|
||||
issueOwnerRepo
|
||||
) {
|
||||
counts.push(
|
||||
countWorkItemsForQuery(repoPath, issueOwnerRepo, { ...effectiveQuery, scope: 'issue' })
|
||||
)
|
||||
}
|
||||
if (effectiveQuery.scope !== 'issue' && prOwnerRepo) {
|
||||
counts.push(countWorkItemsForQuery(repoPath, prOwnerRepo, { ...effectiveQuery, scope: 'pr' }))
|
||||
}
|
||||
// Why: allSettled so a single failing search (e.g. transient network, rate
|
||||
// limit on one side) doesn't silently zero out the total; sum only the
|
||||
// fulfilled halves instead.
|
||||
const results = await Promise.allSettled(counts)
|
||||
let total = 0
|
||||
for (const r of results) {
|
||||
if (r.status === 'fulfilled') {
|
||||
total += r.value
|
||||
} else {
|
||||
console.warn('countWorkItems partial failure:', r.reason)
|
||||
}
|
||||
}
|
||||
return total
|
||||
} catch (err) {
|
||||
console.warn('countWorkItems failed:', err)
|
||||
return 0
|
||||
@@ -524,165 +699,38 @@ export async function getRepoSlug(
|
||||
return getOwnerRepo(repoPath)
|
||||
}
|
||||
|
||||
export async function getWorkItem(repoPath: string, number: number): Promise<MainWorkItem | null> {
|
||||
export async function getWorkItem(
|
||||
repoPath: string,
|
||||
number: number,
|
||||
type?: 'issue' | 'pr'
|
||||
): Promise<MainWorkItem | null> {
|
||||
await acquire()
|
||||
try {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
if (ownerRepo) {
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${number}`],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
const item = JSON.parse(stdout) as Record<string, unknown>
|
||||
if ('pull_request' in item) {
|
||||
const prResult = await ghExecFileAsync(
|
||||
['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${number}`],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
const pr = JSON.parse(prResult.stdout) as Record<string, unknown>
|
||||
const prHeadOwner = extractHeadOwnerLogin(pr)
|
||||
return {
|
||||
id: `pr:${String(pr.number)}`,
|
||||
type: 'pr',
|
||||
number: Number(pr.number),
|
||||
title: String(pr.title ?? ''),
|
||||
state:
|
||||
pr.state === 'closed'
|
||||
? pr.merged_at
|
||||
? 'merged'
|
||||
: 'closed'
|
||||
: pr.draft
|
||||
? 'draft'
|
||||
: 'open',
|
||||
url: String(pr.html_url ?? pr.url ?? ''),
|
||||
labels: Array.isArray(pr.labels)
|
||||
? pr.labels
|
||||
.map((label) =>
|
||||
typeof label === 'object' && label !== null && 'name' in label
|
||||
? String((label as { name?: unknown }).name ?? '')
|
||||
: ''
|
||||
)
|
||||
.filter(Boolean)
|
||||
: [],
|
||||
updatedAt: String(pr.updated_at ?? ''),
|
||||
author:
|
||||
typeof pr.user === 'object' && pr.user !== null && 'login' in pr.user
|
||||
? String((pr.user as { login?: unknown }).login ?? '')
|
||||
: null,
|
||||
branchName:
|
||||
typeof pr.head === 'object' && pr.head !== null && 'ref' in pr.head
|
||||
? String((pr.head as { ref?: unknown }).ref ?? '')
|
||||
: undefined,
|
||||
baseRefName:
|
||||
typeof pr.base === 'object' && pr.base !== null && 'ref' in pr.base
|
||||
? String((pr.base as { ref?: unknown }).ref ?? '')
|
||||
: undefined,
|
||||
// Why: only emit isCrossRepository when we actually know the head
|
||||
// owner. Falsely claiming "not a fork" would let the picker try a
|
||||
// normal-PR fetch against a fork head and fail.
|
||||
...(prHeadOwner !== null ? { isCrossRepository: prHeadOwner !== ownerRepo.owner } : {})
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: `issue:${String(item.number)}`,
|
||||
type: 'issue',
|
||||
number: Number(item.number),
|
||||
title: String(item.title ?? ''),
|
||||
state: String(item.state ?? 'open') === 'closed' ? 'closed' : 'open',
|
||||
url: String(item.html_url ?? item.url ?? ''),
|
||||
labels: Array.isArray(item.labels)
|
||||
? item.labels
|
||||
.map((label) =>
|
||||
typeof label === 'object' && label !== null && 'name' in label
|
||||
? String((label as { name?: unknown }).name ?? '')
|
||||
: ''
|
||||
)
|
||||
.filter(Boolean)
|
||||
: [],
|
||||
updatedAt: String(item.updated_at ?? ''),
|
||||
author:
|
||||
typeof item.user === 'object' && item.user !== null && 'login' in item.user
|
||||
? String((item.user as { login?: unknown }).login ?? '')
|
||||
: null
|
||||
}
|
||||
if (type === 'issue') {
|
||||
return await fetchIssueWorkItem(repoPath, await getIssueOwnerRepo(repoPath), number)
|
||||
}
|
||||
if (type === 'pr') {
|
||||
return await fetchPullRequestWorkItem(repoPath, await getOwnerRepo(repoPath), number)
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'issue',
|
||||
'view',
|
||||
String(number),
|
||||
'--json',
|
||||
'number,title,state,url,labels,updatedAt,author'
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
const item = JSON.parse(stdout) as Record<string, unknown>
|
||||
return {
|
||||
id: `issue:${String(item.number)}`,
|
||||
type: 'issue',
|
||||
number: Number(item.number),
|
||||
title: String(item.title ?? ''),
|
||||
state: String(item.state ?? 'open') === 'closed' ? 'closed' : 'open',
|
||||
url: String(item.url ?? ''),
|
||||
labels: Array.isArray(item.labels)
|
||||
? item.labels
|
||||
.map((label) =>
|
||||
typeof label === 'object' && label !== null && 'name' in label
|
||||
? String((label as { name?: unknown }).name ?? '')
|
||||
: ''
|
||||
)
|
||||
.filter(Boolean)
|
||||
: [],
|
||||
updatedAt: String(item.updatedAt ?? ''),
|
||||
author:
|
||||
typeof item.author === 'object' && item.author !== null && 'login' in item.author
|
||||
? String((item.author as { login?: unknown }).login ?? '')
|
||||
: null
|
||||
const issue = await fetchIssueWorkItem(repoPath, await getIssueOwnerRepo(repoPath), number)
|
||||
if (issue) {
|
||||
return issue
|
||||
}
|
||||
} catch {
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'pr',
|
||||
'view',
|
||||
String(number),
|
||||
'--json',
|
||||
'number,title,state,url,labels,updatedAt,author,isDraft,headRefName,baseRefName,headRepositoryOwner'
|
||||
],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
const item = JSON.parse(stdout) as Record<string, unknown>
|
||||
return {
|
||||
id: `pr:${String(item.number)}`,
|
||||
type: 'pr',
|
||||
number: Number(item.number),
|
||||
title: String(item.title ?? ''),
|
||||
state: item.isDraft ? 'draft' : String(item.state ?? 'open') === 'open' ? 'open' : 'closed',
|
||||
url: String(item.url ?? ''),
|
||||
labels: Array.isArray(item.labels)
|
||||
? item.labels
|
||||
.map((label) =>
|
||||
typeof label === 'object' && label !== null && 'name' in label
|
||||
? String((label as { name?: unknown }).name ?? '')
|
||||
: ''
|
||||
)
|
||||
.filter(Boolean)
|
||||
: [],
|
||||
updatedAt: String(item.updatedAt ?? ''),
|
||||
author:
|
||||
typeof item.author === 'object' && item.author !== null && 'login' in item.author
|
||||
? String((item.author as { login?: unknown }).login ?? '')
|
||||
: null,
|
||||
branchName: String(item.headRefName ?? ''),
|
||||
baseRefName: String(item.baseRefName ?? '')
|
||||
// Why: ownerRepo is null on this path so we can't compare head vs base
|
||||
// owners. Leave isCrossRepository undefined rather than guessing —
|
||||
// falsely claiming "not a fork" would let the picker try a normal-PR
|
||||
// fetch against a fork head and fail.
|
||||
} catch (err) {
|
||||
// Why: the issue lookup now targets `upstream` while the PR lookup targets `origin`,
|
||||
// so a transient upstream failure (5xx, rate limit, network flake) on issue #N would
|
||||
// silently fall through to origin's PR #N — potentially a completely unrelated item.
|
||||
// Only fall through when the issue genuinely doesn't exist (404); re-throw everything
|
||||
// else so the outer catch returns null and the caller sees a real failure instead of
|
||||
// a wrong item. classifyGhError centralizes the 404/"not found" pattern-matching.
|
||||
const stderr = err instanceof Error ? err.message : String(err)
|
||||
if (classifyGhError(stderr).type !== 'not_found') {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
return await fetchPullRequestWorkItem(repoPath, await getOwnerRepo(repoPath), number)
|
||||
} catch {
|
||||
return null
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { gitExecFileAsyncMock } = vi.hoisted(() => ({
|
||||
gitExecFileAsyncMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../git/runner', () => ({
|
||||
gitExecFileAsync: gitExecFileAsyncMock,
|
||||
ghExecFileAsync: vi.fn()
|
||||
}))
|
||||
|
||||
import {
|
||||
_resetOwnerRepoCache,
|
||||
getIssueOwnerRepo,
|
||||
getOwnerRepo,
|
||||
parseGitHubOwnerRepo
|
||||
} from './gh-utils'
|
||||
|
||||
describe('github owner/repo resolution', () => {
|
||||
beforeEach(() => {
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
_resetOwnerRepoCache()
|
||||
})
|
||||
|
||||
it('parses GitHub HTTPS and SSH remotes', () => {
|
||||
expect(parseGitHubOwnerRepo('https://github.com/acme/widgets.git')).toEqual({
|
||||
owner: 'acme',
|
||||
repo: 'widgets'
|
||||
})
|
||||
expect(parseGitHubOwnerRepo('git@github.com:stablyai/orca.git')).toEqual({
|
||||
owner: 'stablyai',
|
||||
repo: 'orca'
|
||||
})
|
||||
expect(parseGitHubOwnerRepo('git@github.com:TheBoredTeam/boring.notch.git')).toEqual({
|
||||
owner: 'TheBoredTeam',
|
||||
repo: 'boring.notch'
|
||||
})
|
||||
expect(parseGitHubOwnerRepo('git@example.com:stablyai/orca.git')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps getOwnerRepo origin-based', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: 'git@github.com:fork/orca.git\n'
|
||||
})
|
||||
|
||||
await expect(getOwnerRepo('/repo')).resolves.toEqual({ owner: 'fork', repo: 'orca' })
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], {
|
||||
cwd: '/repo'
|
||||
})
|
||||
})
|
||||
|
||||
it('prefers upstream for issue owner/repo resolution', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: 'git@github.com:stablyai/orca.git\n'
|
||||
})
|
||||
|
||||
await expect(getIssueOwnerRepo('/repo')).resolves.toEqual({ owner: 'stablyai', repo: 'orca' })
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'upstream'], {
|
||||
cwd: '/repo'
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to origin when upstream is missing or non-GitHub', async () => {
|
||||
gitExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: 'git@example.com:stablyai/orca.git\n' })
|
||||
.mockResolvedValueOnce({ stdout: 'git@github.com:fork/orca.git\n' })
|
||||
|
||||
await expect(getIssueOwnerRepo('/repo')).resolves.toEqual({ owner: 'fork', repo: 'orca' })
|
||||
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['remote', 'get-url', 'upstream'], {
|
||||
cwd: '/repo'
|
||||
})
|
||||
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['remote', 'get-url', 'origin'], {
|
||||
cwd: '/repo'
|
||||
})
|
||||
})
|
||||
|
||||
it('does not mix origin and upstream cache entries for the same repo path', async () => {
|
||||
gitExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: 'git@github.com:fork/orca.git\n' })
|
||||
.mockResolvedValueOnce({ stdout: 'git@github.com:stablyai/orca.git\n' })
|
||||
|
||||
await expect(getOwnerRepo('/repo')).resolves.toEqual({ owner: 'fork', repo: 'orca' })
|
||||
await expect(getIssueOwnerRepo('/repo')).resolves.toEqual({ owner: 'stablyai', repo: 'orca' })
|
||||
})
|
||||
})
|
||||
+35
-12
@@ -65,32 +65,55 @@ export function classifyGhError(stderr: string): ClassifiedError {
|
||||
}
|
||||
|
||||
// ── Owner/repo resolution for gh api --cache ──────────────────────────
|
||||
const ownerRepoCache = new Map<string, { owner: string; repo: string } | null>()
|
||||
export type OwnerRepo = { owner: string; repo: string }
|
||||
|
||||
const ownerRepoCache = new Map<string, OwnerRepo | null>()
|
||||
|
||||
/** @internal — exposed for tests only */
|
||||
export function _resetOwnerRepoCache(): void {
|
||||
ownerRepoCache.clear()
|
||||
}
|
||||
|
||||
export async function getOwnerRepo(
|
||||
repoPath: string
|
||||
): Promise<{ owner: string; repo: string } | null> {
|
||||
if (ownerRepoCache.has(repoPath)) {
|
||||
return ownerRepoCache.get(repoPath)!
|
||||
export function parseGitHubOwnerRepo(remoteUrl: string): OwnerRepo | null {
|
||||
const match = remoteUrl.trim().match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/)
|
||||
if (!match) {
|
||||
return null
|
||||
}
|
||||
return { owner: match[1], repo: match[2] }
|
||||
}
|
||||
|
||||
async function getOwnerRepoForRemote(
|
||||
repoPath: string,
|
||||
remoteName: string
|
||||
): Promise<OwnerRepo | null> {
|
||||
const cacheKey = `${repoPath}\0${remoteName}`
|
||||
if (ownerRepoCache.has(cacheKey)) {
|
||||
return ownerRepoCache.get(cacheKey)!
|
||||
}
|
||||
try {
|
||||
const { stdout } = await gitExecFileAsync(['remote', 'get-url', 'origin'], {
|
||||
const { stdout } = await gitExecFileAsync(['remote', 'get-url', remoteName], {
|
||||
cwd: repoPath
|
||||
})
|
||||
const match = stdout.trim().match(/github\.com[:/]([^/]+)\/([^/.]+?)(?:\.git)?$/)
|
||||
if (match) {
|
||||
const result = { owner: match[1], repo: match[2] }
|
||||
ownerRepoCache.set(repoPath, result)
|
||||
const result = parseGitHubOwnerRepo(stdout)
|
||||
if (result) {
|
||||
ownerRepoCache.set(cacheKey, result)
|
||||
return result
|
||||
}
|
||||
} catch {
|
||||
// ignore — non-GitHub remote or no remote
|
||||
}
|
||||
ownerRepoCache.set(repoPath, null)
|
||||
ownerRepoCache.set(cacheKey, null)
|
||||
return null
|
||||
}
|
||||
|
||||
export async function getOwnerRepo(repoPath: string): Promise<OwnerRepo | null> {
|
||||
return getOwnerRepoForRemote(repoPath, 'origin')
|
||||
}
|
||||
|
||||
export async function getIssueOwnerRepo(repoPath: string): Promise<OwnerRepo | null> {
|
||||
const upstream = await getOwnerRepoForRemote(repoPath, 'upstream')
|
||||
if (upstream) {
|
||||
return upstream
|
||||
}
|
||||
return getOwnerRepoForRemote(repoPath, 'origin')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { ghExecFileAsyncMock, getIssueOwnerRepoMock, acquireMock, releaseMock } = vi.hoisted(() => ({
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getIssueOwnerRepoMock: vi.fn(),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./gh-utils', () => ({
|
||||
ghExecFileAsync: ghExecFileAsyncMock,
|
||||
getIssueOwnerRepo: getIssueOwnerRepoMock,
|
||||
acquire: acquireMock,
|
||||
release: releaseMock
|
||||
}))
|
||||
|
||||
import { createIssue, getIssue, listIssues } from './issues'
|
||||
|
||||
describe('issue source operations', () => {
|
||||
beforeEach(() => {
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getIssueOwnerRepoMock.mockReset()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
acquireMock.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('gets a single issue from the issue owner/repo', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 923,
|
||||
title: 'Use upstream issues',
|
||||
state: 'open',
|
||||
html_url: 'https://github.com/stablyai/orca/issues/923',
|
||||
labels: []
|
||||
})
|
||||
})
|
||||
|
||||
await expect(getIssue('/repo-root', 923)).resolves.toMatchObject({ number: 923 })
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
['api', '--cache', '300s', 'repos/stablyai/orca/issues/923'],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
})
|
||||
|
||||
it('lists issues from the issue owner/repo', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' })
|
||||
|
||||
await listIssues('/repo-root', 5)
|
||||
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
[
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
'repos/stablyai/orca/issues?per_page=5&state=open&sort=updated&direction=desc'
|
||||
],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
})
|
||||
|
||||
it('creates issues in the issue owner/repo', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 924,
|
||||
html_url: 'https://github.com/stablyai/orca/issues/924'
|
||||
})
|
||||
})
|
||||
|
||||
await expect(createIssue('/repo-root', 'New issue', 'Body')).resolves.toEqual({
|
||||
ok: true,
|
||||
number: 924,
|
||||
url: 'https://github.com/stablyai/orca/issues/924'
|
||||
})
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
[
|
||||
'api',
|
||||
'-X',
|
||||
'POST',
|
||||
'repos/stablyai/orca/issues',
|
||||
'--raw-field',
|
||||
'title=New issue',
|
||||
'--raw-field',
|
||||
'body=Body'
|
||||
],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -6,14 +6,14 @@ import type {
|
||||
PRComment
|
||||
} from '../../shared/types'
|
||||
import { mapIssueInfo } from './mappers'
|
||||
import { ghExecFileAsync, acquire, release, getOwnerRepo, classifyGhError } from './gh-utils'
|
||||
import { ghExecFileAsync, acquire, release, getIssueOwnerRepo, classifyGhError } from './gh-utils'
|
||||
|
||||
/**
|
||||
* Get a single issue by number.
|
||||
* Uses gh api --cache so 304 Not Modified responses don't count against the rate limit.
|
||||
*/
|
||||
export async function getIssue(repoPath: string, issueNumber: number): Promise<IssueInfo | null> {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
const ownerRepo = await getIssueOwnerRepo(repoPath)
|
||||
await acquire()
|
||||
try {
|
||||
if (ownerRepo) {
|
||||
@@ -48,7 +48,7 @@ export async function getIssue(repoPath: string, issueNumber: number): Promise<I
|
||||
* Uses gh api --cache so 304 Not Modified responses don't count against the rate limit.
|
||||
*/
|
||||
export async function listIssues(repoPath: string, limit = 20): Promise<IssueInfo[]> {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
const ownerRepo = await getIssueOwnerRepo(repoPath)
|
||||
await acquire()
|
||||
try {
|
||||
if (ownerRepo) {
|
||||
@@ -92,7 +92,7 @@ export async function createIssue(
|
||||
if (!trimmedTitle) {
|
||||
return { ok: false, error: 'Title is required' }
|
||||
}
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
const ownerRepo = await getIssueOwnerRepo(repoPath)
|
||||
if (!ownerRepo) {
|
||||
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
|
||||
}
|
||||
@@ -137,7 +137,7 @@ export async function updateIssue(
|
||||
issueNumber: number,
|
||||
updates: GitHubIssueUpdate
|
||||
): Promise<{ ok: true } | { ok: false; error: string }> {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
const ownerRepo = await getIssueOwnerRepo(repoPath)
|
||||
if (!ownerRepo) {
|
||||
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
|
||||
}
|
||||
@@ -212,7 +212,7 @@ export async function addIssueComment(
|
||||
issueNumber: number,
|
||||
body: string
|
||||
): Promise<GitHubCommentResult> {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
const ownerRepo = await getIssueOwnerRepo(repoPath)
|
||||
if (!ownerRepo) {
|
||||
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
|
||||
}
|
||||
@@ -255,7 +255,7 @@ export async function addIssueComment(
|
||||
}
|
||||
|
||||
export async function listLabels(repoPath: string): Promise<string[]> {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
const ownerRepo = await getIssueOwnerRepo(repoPath)
|
||||
if (!ownerRepo) {
|
||||
return []
|
||||
}
|
||||
@@ -283,7 +283,7 @@ export async function listLabels(repoPath: string): Promise<string[]> {
|
||||
}
|
||||
|
||||
export async function listAssignableUsers(repoPath: string): Promise<GitHubAssignableUser[]> {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
const ownerRepo = await getIssueOwnerRepo(repoPath)
|
||||
if (!ownerRepo) {
|
||||
return []
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
ghExecFileAsyncMock,
|
||||
getOwnerRepoMock,
|
||||
getIssueOwnerRepoMock,
|
||||
getWorkItemMock,
|
||||
getPRChecksMock,
|
||||
getPRCommentsMock,
|
||||
acquireMock,
|
||||
releaseMock
|
||||
} = vi.hoisted(() => ({
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getOwnerRepoMock: vi.fn(),
|
||||
getIssueOwnerRepoMock: vi.fn(),
|
||||
getWorkItemMock: vi.fn(),
|
||||
getPRChecksMock: vi.fn(),
|
||||
getPRCommentsMock: vi.fn(),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./gh-utils', () => ({
|
||||
ghExecFileAsync: ghExecFileAsyncMock,
|
||||
getOwnerRepo: getOwnerRepoMock,
|
||||
getIssueOwnerRepo: getIssueOwnerRepoMock,
|
||||
acquire: acquireMock,
|
||||
release: releaseMock
|
||||
}))
|
||||
|
||||
vi.mock('./client', () => ({
|
||||
getWorkItem: getWorkItemMock,
|
||||
getPRChecks: getPRChecksMock,
|
||||
getPRComments: getPRCommentsMock
|
||||
}))
|
||||
|
||||
import { getWorkItemDetails } from './work-item-details'
|
||||
|
||||
describe('getWorkItemDetails', () => {
|
||||
beforeEach(() => {
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getOwnerRepoMock.mockReset()
|
||||
getIssueOwnerRepoMock.mockReset()
|
||||
getWorkItemMock.mockReset()
|
||||
getPRChecksMock.mockReset()
|
||||
getPRCommentsMock.mockReset()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
acquireMock.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('passes row type into the lookup and fetches issue comments from the issue source', async () => {
|
||||
getWorkItemMock.mockResolvedValueOnce({
|
||||
id: 'issue:923',
|
||||
type: 'issue',
|
||||
number: 923,
|
||||
title: 'Use upstream issues',
|
||||
state: 'open',
|
||||
url: 'https://github.com/stablyai/orca/issues/923',
|
||||
labels: [],
|
||||
updatedAt: '2026-04-01T00:00:00Z',
|
||||
author: 'octocat'
|
||||
})
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify({ body: 'Issue body' }) })
|
||||
.mockResolvedValueOnce({ stdout: '[]' })
|
||||
|
||||
const details = await getWorkItemDetails('/repo-root', 923, 'issue')
|
||||
|
||||
expect(getWorkItemMock).toHaveBeenCalledWith('/repo-root', 923, 'issue')
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
['api', '--cache', '60s', 'repos/stablyai/orca/issues/923'],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
['api', '--cache', '60s', 'repos/stablyai/orca/issues/923/comments?per_page=100'],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
expect(details?.body).toBe('Issue body')
|
||||
})
|
||||
})
|
||||
@@ -9,7 +9,7 @@ import type {
|
||||
GitHubWorkItemDetails,
|
||||
PRComment
|
||||
} from '../../shared/types'
|
||||
import { ghExecFileAsync, acquire, release, getOwnerRepo } from './gh-utils'
|
||||
import { ghExecFileAsync, acquire, release, getOwnerRepo, getIssueOwnerRepo } from './gh-utils'
|
||||
import { getWorkItem, getPRChecks, getPRComments } from './client'
|
||||
|
||||
// Why: a PR "changed file" listing returned by the REST endpoint is paginated
|
||||
@@ -171,7 +171,7 @@ async function getIssueBodyAndComments(
|
||||
repoPath: string,
|
||||
issueNumber: number
|
||||
): Promise<{ body: string; comments: PRComment[]; assignees: string[] }> {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
const ownerRepo = await getIssueOwnerRepo(repoPath)
|
||||
try {
|
||||
if (ownerRepo) {
|
||||
const [issueResult, commentsResult] = await Promise.all([
|
||||
@@ -276,7 +276,11 @@ async function getWorkItemParticipants(
|
||||
repoPath: string,
|
||||
item: Pick<GitHubWorkItem, 'number' | 'type'>
|
||||
): Promise<GitHubAssignableUser[]> {
|
||||
const ownerRepo = await getOwnerRepo(repoPath)
|
||||
// Why: issues in a fork live on the upstream remote, so participants must be
|
||||
// resolved via getIssueOwnerRepo to stay consistent with getIssueBodyAndComments.
|
||||
// PRs remain tied to origin via getOwnerRepo.
|
||||
const ownerRepo =
|
||||
item.type === 'issue' ? await getIssueOwnerRepo(repoPath) : await getOwnerRepo(repoPath)
|
||||
if (!ownerRepo) {
|
||||
return []
|
||||
}
|
||||
@@ -386,12 +390,13 @@ async function getMentionParticipants(
|
||||
|
||||
export async function getWorkItemDetails(
|
||||
repoPath: string,
|
||||
number: number
|
||||
number: number,
|
||||
type?: 'issue' | 'pr'
|
||||
): Promise<GitHubWorkItemDetails | null> {
|
||||
// Why: getWorkItem already handles acquire/release. We call it first (outside
|
||||
// our semaphore) so the known-cheap lookup doesn't compete with the richer
|
||||
// detail fetches that follow.
|
||||
const item: Omit<GitHubWorkItem, 'repoId'> | null = await getWorkItem(repoPath, number)
|
||||
const item: Omit<GitHubWorkItem, 'repoId'> | null = await getWorkItem(repoPath, number, type)
|
||||
if (!item) {
|
||||
return null
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user