diff --git a/src/main/github/client-issue-source.test.ts b/src/main/github/client-issue-source.test.ts new file mode 100644 index 000000000..449449e1d --- /dev/null +++ b/src/main/github/client-issue-source.test.ts @@ -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('./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) + }) +}) diff --git a/src/main/github/client-pr-checks.test.ts b/src/main/github/client-pr-checks.test.ts index 2585ea521..49064da51 100644 --- a/src/main/github/client-pr-checks.test.ts +++ b/src/main/github/client-pr-checks.test.ts @@ -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() diff --git a/src/main/github/client-work-items.test.ts b/src/main/github/client-work-items.test.ts index 490ce175e..72ddfb494 100644 --- a/src/main/github/client-work-items.test.ts +++ b/src/main/github/client-work-items.test.ts @@ -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({ diff --git a/src/main/github/client.test.ts b/src/main/github/client.test.ts index a778c0576..5ba69ebd3 100644 --- a/src/main/github/client.test.ts +++ b/src/main/github/client.test.ts @@ -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() diff --git a/src/main/github/client.ts b/src/main/github/client.ts index da38e3329..bbd8a1f91 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -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 { + if (ownerRepo) { + const { stdout } = await ghExecFileAsync( + ['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${number}`], + { cwd: repoPath } + ) + const item = JSON.parse(stdout) as Record + 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) +} + +async function fetchPullRequestWorkItem( + repoPath: string, + ownerRepo: OwnerRepo | null, + number: number +): Promise { + if (ownerRepo) { + const { stdout } = await ghExecFileAsync( + ['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${number}`], + { cwd: repoPath } + ) + return mapPullRequestWorkItem(JSON.parse(stdout) as Record, 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) +} + 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 { - 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[]) @@ -324,7 +405,7 @@ async function listRecentWorkItems( .map(mapIssueWorkItem) const prs = (JSON.parse(prsResult.stdout) as Record[]).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[]).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[]).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 { - 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 { + 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 { - 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[] = [] + // 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 { +export async function getWorkItem( + repoPath: string, + number: number, + type?: 'issue' | 'pr' +): Promise { 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 - 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 - 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 - 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 - 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 { diff --git a/src/main/github/gh-utils.test.ts b/src/main/github/gh-utils.test.ts new file mode 100644 index 000000000..afb73e833 --- /dev/null +++ b/src/main/github/gh-utils.test.ts @@ -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' }) + }) +}) diff --git a/src/main/github/gh-utils.ts b/src/main/github/gh-utils.ts index bea354587..095ead81a 100644 --- a/src/main/github/gh-utils.ts +++ b/src/main/github/gh-utils.ts @@ -65,32 +65,55 @@ export function classifyGhError(stderr: string): ClassifiedError { } // ── Owner/repo resolution for gh api --cache ────────────────────────── -const ownerRepoCache = new Map() +export type OwnerRepo = { owner: string; repo: string } + +const ownerRepoCache = new Map() /** @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 { + 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 { + return getOwnerRepoForRemote(repoPath, 'origin') +} + +export async function getIssueOwnerRepo(repoPath: string): Promise { + const upstream = await getOwnerRepoForRemote(repoPath, 'upstream') + if (upstream) { + return upstream + } + return getOwnerRepoForRemote(repoPath, 'origin') +} diff --git a/src/main/github/issues.test.ts b/src/main/github/issues.test.ts new file mode 100644 index 000000000..ab3640495 --- /dev/null +++ b/src/main/github/issues.test.ts @@ -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' } + ) + }) +}) diff --git a/src/main/github/issues.ts b/src/main/github/issues.ts index 73b0902d8..739498b7b 100644 --- a/src/main/github/issues.ts +++ b/src/main/github/issues.ts @@ -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 { - 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 { - 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 { - 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 { - const ownerRepo = await getOwnerRepo(repoPath) + const ownerRepo = await getIssueOwnerRepo(repoPath) if (!ownerRepo) { return [] } @@ -283,7 +283,7 @@ export async function listLabels(repoPath: string): Promise { } export async function listAssignableUsers(repoPath: string): Promise { - const ownerRepo = await getOwnerRepo(repoPath) + const ownerRepo = await getIssueOwnerRepo(repoPath) if (!ownerRepo) { return [] } diff --git a/src/main/github/work-item-details.test.ts b/src/main/github/work-item-details.test.ts new file mode 100644 index 000000000..054eeb2df --- /dev/null +++ b/src/main/github/work-item-details.test.ts @@ -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') + }) +}) diff --git a/src/main/github/work-item-details.ts b/src/main/github/work-item-details.ts index 3c25c910f..c0dbc1b46 100644 --- a/src/main/github/work-item-details.ts +++ b/src/main/github/work-item-details.ts @@ -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 ): Promise { - 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 { // 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 | null = await getWorkItem(repoPath, number) + const item: Omit | null = await getWorkItem(repoPath, number, type) if (!item) { return null } diff --git a/src/main/ipc/github-work-item-args.test.ts b/src/main/ipc/github-work-item-args.test.ts new file mode 100644 index 000000000..8bb38c817 --- /dev/null +++ b/src/main/ipc/github-work-item-args.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from 'vitest' +import { dispatchWorkItem } from './github-work-item-args' + +describe('dispatchWorkItem', () => { + it('rejects non-integer numbers', () => { + const fn = vi.fn() + expect(dispatchWorkItem({ repoPath: '/r', number: 1.5 }, '/r', fn)).toBeNull() + expect(fn).not.toHaveBeenCalled() + }) + + it('rejects numbers < 1', () => { + const fn = vi.fn() + expect(dispatchWorkItem({ repoPath: '/r', number: 0 }, '/r', fn)).toBeNull() + expect(dispatchWorkItem({ repoPath: '/r', number: -5 }, '/r', fn)).toBeNull() + expect(fn).not.toHaveBeenCalled() + }) + + it('rejects non-number values coming across IPC', () => { + const fn = vi.fn() + // Renderer can send anything; simulate a string that slips past TS. + const bogus = { repoPath: '/r', number: 'abc' as unknown as number } + expect(dispatchWorkItem(bogus, '/r', fn)).toBeNull() + expect(fn).not.toHaveBeenCalled() + }) + + it('coerces unknown type values to undefined', async () => { + const fn = vi.fn().mockResolvedValue(null) + const bogus = { + repoPath: '/r', + number: 42, + type: 'bogus' as unknown as 'issue' | 'pr' + } + await dispatchWorkItem(bogus, '/r', fn) + expect(fn).toHaveBeenCalledWith('/r', 42, undefined) + }) + + it('passes valid issue type through', async () => { + const fn = vi.fn().mockResolvedValue(null) + await dispatchWorkItem({ repoPath: '/r', number: 42, type: 'issue' }, '/r', fn) + expect(fn).toHaveBeenCalledWith('/r', 42, 'issue') + }) + + it('passes valid pr type through', async () => { + const fn = vi.fn().mockResolvedValue(null) + await dispatchWorkItem({ repoPath: '/r', number: 42, type: 'pr' }, '/r', fn) + expect(fn).toHaveBeenCalledWith('/r', 42, 'pr') + }) +}) diff --git a/src/main/ipc/github-work-item-args.ts b/src/main/ipc/github-work-item-args.ts new file mode 100644 index 000000000..43b16deb6 --- /dev/null +++ b/src/main/ipc/github-work-item-args.ts @@ -0,0 +1,22 @@ +export type WorkItemArgs = { + repoPath: string + number: number + type?: 'issue' | 'pr' +} + +// Why: renderer input crosses the IPC boundary and is untrusted. Reject +// non-integer or < 1 numbers, and coerce unrecognised `type` values to +// undefined so getWorkItem falls through to its issue-then-PR probe rather +// than silently dispatching to the wrong branch. +export function dispatchWorkItem( + args: WorkItemArgs, + repoPath: string, + fn: (path: string, n: number, t?: 'issue' | 'pr') => Promise +): Promise | null { + const { number, type } = args + if (typeof number !== 'number' || !Number.isInteger(number) || number < 1) { + return null + } + const safeType = type === 'issue' || type === 'pr' ? type : undefined + return fn(repoPath, number, safeType) +} diff --git a/src/main/ipc/github.ts b/src/main/ipc/github.ts index 6046aa721..cf379f4f8 100644 --- a/src/main/ipc/github.ts +++ b/src/main/ipc/github.ts @@ -29,6 +29,7 @@ import { } from '../github/client' import { getWorkItemDetails, getPRFileContents } from '../github/work-item-details' import type { GitHubPRFile } from '../../shared/types' +import { dispatchWorkItem, type WorkItemArgs } from './github-work-item-args' // Why: returns the full Repo object instead of just the path string so that // callers have access to repo.id for stat tracking and other context. @@ -90,15 +91,12 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi return countWorkItems(repo.path, args.query) }) - ipcMain.handle('gh:workItem', (_event, args: { repoPath: string; number: number }) => { - const repo = assertRegisteredRepo(args.repoPath, store) - return getWorkItem(repo.path, args.number) - }) - - ipcMain.handle('gh:workItemDetails', (_event, args: { repoPath: string; number: number }) => { - const repo = assertRegisteredRepo(args.repoPath, store) - return getWorkItemDetails(repo.path, args.number) - }) + ipcMain.handle('gh:workItem', (_event, args: WorkItemArgs) => + dispatchWorkItem(args, assertRegisteredRepo(args.repoPath, store).path, getWorkItem) + ) + ipcMain.handle('gh:workItemDetails', (_event, args: WorkItemArgs) => + dispatchWorkItem(args, assertRegisteredRepo(args.repoPath, store).path, getWorkItemDetails) + ) ipcMain.handle( 'gh:prFileContents', diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index af17e708f..fc2fba573 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -172,7 +172,10 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store // Skip the gh lookup when both hints are present (picker already has them). if (!headRefName) { - const item = await getWorkItem(repo.path, args.prNumber) + // Why: the caller already knows this is a PR number, so scope the + // lookup to `type: 'pr'` and skip the speculative issue-first probe + // that would hit the upstream issue tracker for fork checkouts. + const item = await getWorkItem(repo.path, args.prNumber, 'pr') if (!item || item.type !== 'pr') { return { error: `PR #${args.prNumber} not found.` } } diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 96c9a7386..fb0e79a77 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -411,10 +411,12 @@ export type PreloadApi = { workItem: (args: { repoPath: string number: number + type?: 'issue' | 'pr' }) => Promise | null> workItemDetails: (args: { repoPath: string number: number + type?: 'issue' | 'pr' }) => Promise prFileContents: (args: { repoPath: string diff --git a/src/preload/index.ts b/src/preload/index.ts index 57c27663d..b249f4fe9 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -391,11 +391,17 @@ const api = { issue: (args: { repoPath: string; number: number }): Promise => ipcRenderer.invoke('gh:issue', args), - workItem: (args: { repoPath: string; number: number }): Promise => - ipcRenderer.invoke('gh:workItem', args), + workItem: (args: { + repoPath: string + number: number + type?: 'issue' | 'pr' + }): Promise => ipcRenderer.invoke('gh:workItem', args), - workItemDetails: (args: { repoPath: string; number: number }): Promise => - ipcRenderer.invoke('gh:workItemDetails', args), + workItemDetails: (args: { + repoPath: string + number: number + type?: 'issue' | 'pr' + }): Promise => ipcRenderer.invoke('gh:workItemDetails', args), prFileContents: (args: { repoPath: string diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index d2134e00a..3b292882d 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -1983,7 +1983,7 @@ export default function GitHubItemDialog({ setTab('conversation') window.api.gh - .workItemDetails({ repoPath, number: workItem.number }) + .workItemDetails({ repoPath, number: workItem.number, type: workItem.type }) .then((result) => { if (requestId !== requestIdRef.current) { return diff --git a/src/renderer/src/components/TaskPage.tsx b/src/renderer/src/components/TaskPage.tsx index 64374c06f..441413ec9 100644 --- a/src/renderer/src/components/TaskPage.tsx +++ b/src/renderer/src/components/TaskPage.tsx @@ -1252,7 +1252,7 @@ export default function TaskPage(): React.JSX.Element { setDialogWorkItem(stub) const stubRepoId = newIssueTargetRepo.id void window.api.gh - .workItem({ repoPath: newIssueTargetRepo.path, number: result.number }) + .workItem({ repoPath: newIssueTargetRepo.path, number: result.number, type: 'issue' }) .then((full) => { if (full) { // Why: `full` is `Omit` (IPC shape). diff --git a/src/renderer/src/components/dashboard/AgentDashboard.tsx b/src/renderer/src/components/dashboard/AgentDashboard.tsx index b9622cb05..2f35a29db 100644 --- a/src/renderer/src/components/dashboard/AgentDashboard.tsx +++ b/src/renderer/src/components/dashboard/AgentDashboard.tsx @@ -167,163 +167,164 @@ const AgentDashboard = React.memo(function AgentDashboard() { ) : ( <> -
-
- - setSearchQuery(e.target.value)} - placeholder="Search..." - className="h-7 pl-7 pr-7 text-[11px] border-none bg-muted/50 shadow-none focus-visible:ring-1 focus-visible:ring-ring/30" - /> - {searchActive && ( - - )} -
-
- -
-
- -
- {hasResults ? ( -
- {filteredGroups.map((group, groupIdx) => { - const isCollapsed = collapsedRepos.has(group.repo.id) - // Why: per-repo stats replace the global stats strip that used - // to sit above the whole dashboard. Counts live at the scope - // of the grouping so the user sees per-repo agent load instead - // of a rollup that hides which repo is busy. Counts come from - // useDashboardFilter's memo so this doesn't re-walk every agent - // in every worktree on each `now` tick or search change. - const { running: groupRunning, blocked: groupBlocked, done: groupDone } = group - const Icon = isCollapsed ? ChevronRight : ChevronDown - return ( -
+
+ + setSearchQuery(e.target.value)} + placeholder="Search..." + className="h-7 pl-7 pr-7 text-[11px] border-none bg-muted/50 shadow-none focus-visible:ring-1 focus-visible:ring-ring/30" + /> + {searchActive && ( + + )} +
+
+ +
+
+ +
+ {hasResults ? ( +
+ {filteredGroups.map((group, groupIdx) => { + const isCollapsed = collapsedRepos.has(group.repo.id) + // Why: per-repo stats replace the global stats strip that used + // to sit above the whole dashboard. Counts live at the scope + // of the grouping so the user sees per-repo agent load instead + // of a rollup that hides which repo is busy. Counts come from + // useDashboardFilter's memo so this doesn't re-walk every agent + // in every worktree on each `now` tick or search change. + const { running: groupRunning, blocked: groupBlocked, done: groupDone } = group + const Icon = isCollapsed ? ChevronRight : ChevronDown + return ( +
+ {/* Why: the repo header is a lightweight row, not a card — no background fill, no border box. It stays an expand/collapse control so users can hide repos they aren't watching, but it doesn't wrap the children in chrome that duplicates the worktree row's own borders. */} - - {!isCollapsed && - group.worktrees.map((card, i) => ( - - ))} -
- ) - })} -
- ) : ( -
-
- {showNoResults - ? 'No matches.' - : filter === 'active' - ? 'No active agents.' - : filter === 'blocked' - ? 'No agents are blocked.' - : filter === 'done' - ? 'No completed agents to show.' - : 'No agent activity yet.'} -
- {showNoResults ? ( - + + {!isCollapsed && + group.worktrees.map((card, i) => ( + + ))} +
+ ) + })} +
) : ( - filter !== 'all' && ( - - ) +
+
+ {showNoResults + ? 'No matches.' + : filter === 'active' + ? 'No active agents.' + : filter === 'blocked' + ? 'No agents are blocked.' + : filter === 'done' + ? 'No completed agents to show.' + : 'No agent activity yet.'} +
+ {showNoResults ? ( + + ) : ( + filter !== 'all' && ( + + ) + )} +
)}
- )} -
)} diff --git a/src/renderer/src/components/new-workspace/CreateFromTab.tsx b/src/renderer/src/components/new-workspace/CreateFromTab.tsx index 796ef7c82..e2f25f6ae 100644 --- a/src/renderer/src/components/new-workspace/CreateFromTab.tsx +++ b/src/renderer/src/components/new-workspace/CreateFromTab.tsx @@ -20,7 +20,6 @@ import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs' import { useAppStore } from '@/store' import { cn } from '@/lib/utils' import { normalizeGitHubLinkQuery } from '@/lib/github-links' -import type { RepoSlug } from '@/lib/github-links' import { launchWorkItemDirect, launchFromBranch } from '@/lib/launch-work-item-direct' import { isGitRepoKind } from '../../../../shared/repo-kind' import type { GitHubWorkItem, LinearIssue } from '../../../../shared/types' @@ -201,37 +200,9 @@ export default function CreateFromTab({ ) const isRemoteRepo = Boolean(selectedRepo?.connectionId) - // Why: resolve the repo slug once so normalizeGitHubLinkQuery can detect - // pasted URLs that target a different repo than the selected one — same - // treatment StartFromPicker applies, so the "paste a URL" flow feels - // identical between the two surfaces. - const [repoSlug, setRepoSlug] = useState(null) - useEffect(() => { - if (!selectedRepo?.path) { - setRepoSlug(null) - return - } - let stale = false - void window.api.gh - .repoSlug({ repoPath: selectedRepo.path }) - .then((slug) => { - if (!stale) { - setRepoSlug(slug) - } - }) - .catch(() => { - if (!stale) { - setRepoSlug(null) - } - }) - return () => { - stale = true - } - }, [selectedRepo?.path]) - const normalizedGhQuery = useMemo( - () => normalizeGitHubLinkQuery(debouncedQuery, repoSlug), - [debouncedQuery, repoSlug] + () => normalizeGitHubLinkQuery(debouncedQuery), + [debouncedQuery] ) // --------------------------------------------------------------------- @@ -250,10 +221,7 @@ export default function CreateFromTab({ return // handled by direct-lookup effect below } const trimmed = debouncedQuery.trim() - const q = - trimmed && !normalizedGhQuery.repoMismatch - ? `is:pr is:open ${normalizedGhQuery.query}` - : 'is:pr is:open' + const q = trimmed ? `is:pr is:open ${normalizedGhQuery.query}` : 'is:pr is:open' let stale = false setPrLoading(true) @@ -288,7 +256,6 @@ export default function CreateFromTab({ isRemoteRepo, debouncedQuery, normalizedGhQuery.query, - normalizedGhQuery.repoMismatch, normalizedGhQuery.directNumber ]) @@ -307,10 +274,7 @@ export default function CreateFromTab({ return } const trimmed = debouncedQuery.trim() - const q = - trimmed && !normalizedGhQuery.repoMismatch - ? `is:issue is:open ${normalizedGhQuery.query}` - : 'is:issue is:open' + const q = trimmed ? `is:issue is:open ${normalizedGhQuery.query}` : 'is:issue is:open' let stale = false setIssueLoading(true) @@ -345,7 +309,6 @@ export default function CreateFromTab({ isRemoteRepo, debouncedQuery, normalizedGhQuery.query, - normalizedGhQuery.repoMismatch, normalizedGhQuery.directNumber ]) @@ -735,12 +698,6 @@ export default function CreateFromTab({ if (isRemoteRepo) { return { kind: 'empty', message: "PR start points aren't supported for remote repos yet." } } - if (normalizedGhQuery.repoMismatch && normalizedGhQuery.directNumber === null) { - return { - kind: 'empty', - message: `URL targets ${normalizedGhQuery.repoMismatch}, not the selected repo.` - } - } if (prError) { return { kind: 'empty', @@ -775,12 +732,6 @@ export default function CreateFromTab({ message: "Issue start points aren't supported for remote repos yet." } } - if (normalizedGhQuery.repoMismatch && normalizedGhQuery.directNumber === null) { - return { - kind: 'empty', - message: `URL targets ${normalizedGhQuery.repoMismatch}, not the selected repo.` - } - } if (issueError) { return { kind: 'empty', @@ -869,7 +820,6 @@ export default function CreateFromTab({ linearLoading, linearStatus.connected, normalizedGhQuery.directNumber, - normalizedGhQuery.repoMismatch, prError, prLoading, query, diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index bc8258c67..35c6054a9 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -8,7 +8,6 @@ import { useShallow } from 'zustand/react/shallow' import { useAppStore } from '@/store' import { AGENT_CATALOG } from '@/lib/agent-catalog' import { parseGitHubIssueOrPRNumber, normalizeGitHubLinkQuery } from '@/lib/github-links' -import type { RepoSlug } from '@/lib/github-links' import { activateAndRevealWorktree } from '@/lib/worktree-activation' import { buildAgentStartupPlan } from '@/lib/tui-agent-startup' import { isGitRepoKind } from '../../../shared/repo-kind' @@ -84,7 +83,7 @@ export type ComposerCardProps = { filteredLinkItems: GitHubWorkItem[] linkItemsLoading: boolean linkDirectLoading: boolean - normalizedLinkQuery: { query: string; repoMismatch: string | null } + normalizedLinkQuery: { query: string } onSelectLinkedItem: (item: GitHubWorkItem) => void tuiAgent: TuiAgent onTuiAgentChange: (value: TuiAgent) => void @@ -306,7 +305,6 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS const [linkItemsLoading, setLinkItemsLoading] = useState(false) const [linkDirectItem, setLinkDirectItem] = useState(null) const [linkDirectLoading, setLinkDirectLoading] = useState(false) - const [linkRepoSlug, setLinkRepoSlug] = useState(null) const lastAutoNameRef = useRef( persistDraft ? (newWorkspaceDraft?.name ?? initialName) : initialName @@ -415,8 +413,8 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS shouldApplyLinkedOnlyTemplate ]) const normalizedLinkQuery = useMemo( - () => normalizeGitHubLinkQuery(linkDebouncedQuery, linkRepoSlug), - [linkDebouncedQuery, linkRepoSlug] + () => normalizeGitHubLinkQuery(linkDebouncedQuery), + [linkDebouncedQuery] ) const filteredLinkItems = useMemo(() => { @@ -567,32 +565,6 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS prefetchWorkItems(selectedRepo.id, selectedRepo.path, PER_REPO_FETCH_LIMIT, 'is:pr is:open') }, [prefetchWorkItems, selectedRepo?.connectionId, selectedRepo?.id, selectedRepo?.path]) - // Per-repo: resolve repo slug for GH URL mismatch detection. - useEffect(() => { - if (!selectedRepo) { - setLinkRepoSlug(null) - return - } - - let cancelled = false - void window.api.gh - .repoSlug({ repoPath: selectedRepo.path }) - .then((slug) => { - if (!cancelled) { - setLinkRepoSlug(slug) - } - }) - .catch(() => { - if (!cancelled) { - setLinkRepoSlug(null) - } - }) - - return () => { - cancelled = true - } - }, [selectedRepo]) - // Reset setup decision when config / policy changes. useEffect(() => { if (shouldWaitForSetupCheck) { diff --git a/src/renderer/src/lib/github-links.test.ts b/src/renderer/src/lib/github-links.test.ts index 95dd4b2ce..320468d6f 100644 --- a/src/renderer/src/lib/github-links.test.ts +++ b/src/renderer/src/lib/github-links.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { parseGitHubIssueOrPRNumber } from './github-links' +import { normalizeGitHubLinkQuery, parseGitHubIssueOrPRNumber } from './github-links' describe('parseGitHubIssueOrPRNumber', () => { it('parses plain issue numbers and GitHub pull request URLs', () => { @@ -12,3 +12,12 @@ describe('parseGitHubIssueOrPRNumber', () => { expect(parseGitHubIssueOrPRNumber('https://example.com/stablyai/orca/pull/123')).toBeNull() }) }) + +describe('normalizeGitHubLinkQuery', () => { + it('accepts full GitHub URLs whose slug differs from the selected repo slug', () => { + expect(normalizeGitHubLinkQuery('https://github.com/stablyai/orca/issues/923')).toEqual({ + query: 'https://github.com/stablyai/orca/issues/923', + directNumber: 923 + }) + }) +}) diff --git a/src/renderer/src/lib/github-links.ts b/src/renderer/src/lib/github-links.ts index b7e71c937..e6db2b488 100644 --- a/src/renderer/src/lib/github-links.ts +++ b/src/renderer/src/lib/github-links.ts @@ -8,7 +8,6 @@ export type RepoSlug = { export type GitHubLinkQuery = { query: string - repoMismatch: string | null directNumber: number | null } @@ -83,40 +82,29 @@ export function parseGitHubIssueOrPRLink(input: string): { /** * Normalizes link-picker input so both raw issue/PR numbers and full GitHub - * URLs resolve to a usable query + direct-number lookup. Returns a repo - * mismatch when a URL targets a different repo than the selected one. + * URLs resolve to a usable query + direct-number lookup. */ -export function normalizeGitHubLinkQuery(raw: string, repoSlug: RepoSlug | null): GitHubLinkQuery { +export function normalizeGitHubLinkQuery(raw: string): GitHubLinkQuery { const trimmed = raw.trim() if (!trimmed) { - return { query: '', repoMismatch: null, directNumber: null } + return { query: '', directNumber: null } } const direct = parseGitHubIssueOrPRNumber(trimmed) if (direct !== null && !trimmed.startsWith('http')) { - return { query: trimmed, repoMismatch: null, directNumber: direct } + return { query: trimmed, directNumber: direct } } const link = parseGitHubIssueOrPRLink(trimmed) if (!link) { - return { query: trimmed, repoMismatch: null, directNumber: null } - } - - if ( - repoSlug && - (link.slug.owner.toLowerCase() !== repoSlug.owner.toLowerCase() || - link.slug.repo.toLowerCase() !== repoSlug.repo.toLowerCase()) - ) { - return { - query: '', - repoMismatch: `${repoSlug.owner}/${repoSlug.repo}`, - directNumber: null - } + return { query: trimmed, directNumber: null } } + // Why: any github.com issue/pull URL is accepted by number regardless of + // slug, since fork checkouts can legitimately target upstream issues whose + // slug differs from the origin remote. return { query: trimmed, - repoMismatch: null, directNumber: link.number } }