From e8f2dcb57d49381e2eb7a917df1094ba233a9695 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sat, 28 Mar 2026 00:30:47 -0700 Subject: [PATCH] fix: use gh pr list --head for reliable PR discovery (#162) gh pr view only matches the current checkout, which fails for worktrees on different branches. Switch to gh pr list --repo --head to query by branch name directly, with a fallback to gh pr view for non-GitHub remotes. Also fix the ChecksPanel refresh button to use the proper handleRefresh flow and force-refresh the PR cache. --- src/main/github/client.test.ts | 286 ++++++------------ src/main/github/client.ts | 77 ++++- .../components/right-sidebar/ChecksPanel.tsx | 15 +- src/renderer/src/store/slices/github.ts | 2 +- 4 files changed, 161 insertions(+), 219 deletions(-) diff --git a/src/main/github/client.test.ts b/src/main/github/client.test.ts index ae188eb18..bc8e839d1 100644 --- a/src/main/github/client.test.ts +++ b/src/main/github/client.test.ts @@ -1,213 +1,109 @@ -import { describe, expect, it } from 'vitest' -import { deriveCheckStatus, mapPRState, mapCheckStatus, mapCheckConclusion } from './mappers' +import { beforeEach, describe, expect, it, vi } from 'vitest' -describe('mapPRState', () => { - it('returns draft when an open PR is marked as draft', () => { - expect(mapPRState('OPEN', true)).toBe('draft') - }) +const { execFileAsyncMock } = vi.hoisted(() => ({ + execFileAsyncMock: vi.fn() +})) - it('preserves merged and closed states', () => { - expect(mapPRState('MERGED', true)).toBe('merged') - expect(mapPRState('CLOSED', true)).toBe('closed') - expect(mapPRState('OPEN')).toBe('open') - }) - - it('handles lowercase inputs', () => { - expect(mapPRState('merged')).toBe('merged') - expect(mapPRState('closed')).toBe('closed') - expect(mapPRState('open')).toBe('open') - }) - - it('returns open for undefined state', () => { - expect(mapPRState(undefined as unknown as string)).toBe('open') - }) - - it('returns open for null state', () => { - expect(mapPRState(null as unknown as string)).toBe('open') - }) - - it('returns open for unknown state', () => { - expect(mapPRState('UNKNOWN')).toBe('open') - }) +vi.mock('util', async () => { + const actual = await vi.importActual('util') + return { + ...actual, + promisify: vi.fn(() => execFileAsyncMock) + } }) -describe('deriveCheckStatus', () => { - it('returns neutral when no checks are present', () => { - expect(deriveCheckStatus(null)).toBe('neutral') - expect(deriveCheckStatus([])).toBe('neutral') +import { getPRForBranch, _resetOwnerRepoCache } from './client' + +describe('getPRForBranch', () => { + beforeEach(() => { + execFileAsyncMock.mockReset() + _resetOwnerRepoCache() }) - it('returns neutral for undefined input', () => { - expect(deriveCheckStatus(undefined)).toBe('neutral') - }) + it('queries GitHub by head branch when the remote is on github.com', async () => { + execFileAsyncMock + .mockResolvedValueOnce({ stdout: 'git@github.com:acme/widgets.git\n' }) + .mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + number: 42, + title: 'Fix PR discovery', + state: 'OPEN', + url: 'https://github.com/acme/widgets/pull/42', + statusCheckRollup: [], + updatedAt: '2026-03-28T00:00:00Z', + isDraft: false + } + ]) + }) - it('returns failure when a failed check is present', () => { - expect(deriveCheckStatus([{ status: 'QUEUED' }, { conclusion: 'FAILURE' }])).toBe('failure') - }) + const pr = await getPRForBranch('/repo-root', 'refs/heads/feature/test') - it('returns pending when checks are still running', () => { - expect(deriveCheckStatus([{ status: 'IN_PROGRESS' }])).toBe('pending') - }) - - it('returns success when all checks complete without failures', () => { - expect(deriveCheckStatus([{ conclusion: 'SUCCESS' }, { conclusion: 'SKIPPED' }])).toBe( - 'success' + expect(execFileAsyncMock).toHaveBeenNthCalledWith(1, 'git', ['remote', 'get-url', 'origin'], { + cwd: '/repo-root', + encoding: 'utf-8' + }) + expect(execFileAsyncMock).toHaveBeenNthCalledWith( + 2, + 'gh', + [ + 'pr', + 'list', + '--repo', + 'acme/widgets', + '--head', + 'feature/test', + '--state', + 'all', + '--limit', + '1', + '--json', + 'number,title,state,url,statusCheckRollup,updatedAt,isDraft' + ], + { cwd: '/repo-root', encoding: 'utf-8' } ) + expect(pr?.number).toBe(42) + expect(pr?.state).toBe('open') }) - it('returns failure when mixed success and failure', () => { - expect(deriveCheckStatus([{ conclusion: 'SUCCESS' }, { conclusion: 'FAILURE' }])).toBe( - 'failure' + it('falls back to gh pr view when the remote cannot be resolved to GitHub', async () => { + execFileAsyncMock.mockRejectedValueOnce(new Error('no origin')).mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 7, + title: 'Fallback lookup', + state: 'OPEN', + url: 'https://example.com/pr/7', + statusCheckRollup: [], + updatedAt: '2026-03-28T00:00:00Z', + isDraft: true + }) + }) + + const pr = await getPRForBranch('/non-github-repo', 'feature/test') + + expect(execFileAsyncMock).toHaveBeenNthCalledWith( + 2, + 'gh', + [ + 'pr', + 'view', + 'feature/test', + '--json', + 'number,title,state,url,statusCheckRollup,updatedAt,isDraft' + ], + { cwd: '/non-github-repo', encoding: 'utf-8' } ) + expect(pr?.number).toBe(7) + expect(pr?.state).toBe('draft') }) - it('returns pending when mixed success and pending', () => { - expect(deriveCheckStatus([{ conclusion: 'SUCCESS' }, { status: 'QUEUED' }])).toBe('pending') - }) + it('returns null when pr list returns an empty array', async () => { + execFileAsyncMock + .mockResolvedValueOnce({ stdout: 'git@github.com:acme/widgets.git\n' }) + .mockResolvedValueOnce({ stdout: '[]' }) - it('returns success when all checks succeed', () => { - expect( - deriveCheckStatus([ - { conclusion: 'SUCCESS' }, - { conclusion: 'SUCCESS' }, - { conclusion: 'SUCCESS' } - ]) - ).toBe('success') - }) + const pr = await getPRForBranch('/repo-root', 'no-pr-branch') - it('returns failure when a single failure is among many successes', () => { - expect( - deriveCheckStatus([ - { conclusion: 'SUCCESS' }, - { conclusion: 'SUCCESS' }, - { conclusion: 'FAILURE' }, - { conclusion: 'SUCCESS' } - ]) - ).toBe('failure') - }) - - it('returns failure for TIMED_OUT conclusion', () => { - expect(deriveCheckStatus([{ conclusion: 'SUCCESS' }, { conclusion: 'TIMED_OUT' }])).toBe( - 'failure' - ) - }) - - it('returns failure for CANCELLED conclusion', () => { - expect(deriveCheckStatus([{ conclusion: 'CANCELLED' }])).toBe('failure') - }) - - it('handles checks with state field instead of conclusion (FAILURE)', () => { - expect(deriveCheckStatus([{ state: 'FAILURE' }])).toBe('failure') - }) - - it('handles checks with state field instead of conclusion (ERROR)', () => { - expect(deriveCheckStatus([{ state: 'ERROR' }])).toBe('failure') - }) - - it('handles checks with state field PENDING', () => { - expect(deriveCheckStatus([{ state: 'PENDING' }])).toBe('pending') - }) - - it('returns pending for QUEUED status', () => { - expect(deriveCheckStatus([{ status: 'QUEUED' }])).toBe('pending') - }) - - it('returns pending for PENDING status', () => { - expect(deriveCheckStatus([{ status: 'PENDING' }])).toBe('pending') - }) - - it('failure takes priority over pending', () => { - expect( - deriveCheckStatus([ - { status: 'IN_PROGRESS' }, - { conclusion: 'FAILURE' }, - { conclusion: 'SUCCESS' } - ]) - ).toBe('failure') - }) -}) - -describe('mapCheckStatus', () => { - it('maps PENDING to queued', () => { - expect(mapCheckStatus('PENDING')).toBe('queued') - }) - - it('maps QUEUED to queued', () => { - expect(mapCheckStatus('QUEUED')).toBe('queued') - }) - - it('maps IN_PROGRESS to in_progress', () => { - expect(mapCheckStatus('IN_PROGRESS')).toBe('in_progress') - }) - - it('maps SUCCESS to completed', () => { - expect(mapCheckStatus('SUCCESS')).toBe('completed') - }) - - it('maps any other value to completed', () => { - expect(mapCheckStatus('FAILURE')).toBe('completed') - expect(mapCheckStatus('UNKNOWN')).toBe('completed') - }) - - it('handles lowercase inputs', () => { - expect(mapCheckStatus('pending')).toBe('queued') - expect(mapCheckStatus('in_progress')).toBe('in_progress') - }) -}) - -describe('mapCheckConclusion', () => { - it('maps SUCCESS to success', () => { - expect(mapCheckConclusion('SUCCESS')).toBe('success') - }) - - it('maps PASS to success', () => { - expect(mapCheckConclusion('PASS')).toBe('success') - }) - - it('maps FAILURE to failure', () => { - expect(mapCheckConclusion('FAILURE')).toBe('failure') - }) - - it('maps FAIL to failure', () => { - expect(mapCheckConclusion('FAIL')).toBe('failure') - }) - - it('maps CANCELLED to cancelled', () => { - expect(mapCheckConclusion('CANCELLED')).toBe('cancelled') - }) - - it('maps TIMED_OUT to timed_out', () => { - expect(mapCheckConclusion('TIMED_OUT')).toBe('timed_out') - }) - - it('maps SKIPPED to skipped', () => { - expect(mapCheckConclusion('SKIPPED')).toBe('skipped') - }) - - it('maps PENDING to pending', () => { - expect(mapCheckConclusion('PENDING')).toBe('pending') - }) - - it('maps QUEUED to pending', () => { - expect(mapCheckConclusion('QUEUED')).toBe('pending') - }) - - it('maps IN_PROGRESS to pending', () => { - expect(mapCheckConclusion('IN_PROGRESS')).toBe('pending') - }) - - it('maps NEUTRAL to neutral', () => { - expect(mapCheckConclusion('NEUTRAL')).toBe('neutral') - }) - - it('returns null for unknown values', () => { - expect(mapCheckConclusion('UNKNOWN')).toBeNull() - expect(mapCheckConclusion('FOO')).toBeNull() - }) - - it('handles lowercase inputs', () => { - expect(mapCheckConclusion('success')).toBe('success') - expect(mapCheckConclusion('failure')).toBe('failure') - expect(mapCheckConclusion('pending')).toBe('pending') + expect(pr).toBeNull() }) }) diff --git a/src/main/github/client.ts b/src/main/github/client.ts index e455f7796..2e0c7271e 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -42,6 +42,11 @@ function release(): void { // ── Owner/repo resolution for gh api --cache ────────────────────────── const ownerRepoCache = new Map() +/** @internal — exposed for tests only */ +export function _resetOwnerRepoCache(): void { + ownerRepoCache.clear() +} + async function getOwnerRepo(repoPath: string): Promise<{ owner: string; repo: string } | null> { if (ownerRepoCache.has(repoPath)) { return ownerRepoCache.get(repoPath)! @@ -71,23 +76,65 @@ async function getOwnerRepo(repoPath: string): Promise<{ owner: string; repo: st export async function getPRForBranch(repoPath: string, branch: string): Promise { await acquire() try { + const ownerRepo = await getOwnerRepo(repoPath) // Strip refs/heads/ prefix if present const branchName = branch.replace(/^refs\/heads\//, '') - const { stdout } = await execFileAsync( - 'gh', - [ - 'pr', - 'view', - branchName, - '--json', - 'number,title,state,url,statusCheckRollup,updatedAt,isDraft' - ], - { - cwd: repoPath, - encoding: 'utf-8' - } - ) - const data = JSON.parse(stdout) + let data: { + number: number + title: string + state: string + url: string + statusCheckRollup: unknown[] + updatedAt: string + isDraft?: boolean + } | null = null + + if (ownerRepo) { + const { stdout } = await execFileAsync( + 'gh', + [ + 'pr', + 'list', + '--repo', + `${ownerRepo.owner}/${ownerRepo.repo}`, + '--head', + branchName, + '--state', + 'all', + '--limit', + '1', + '--json', + 'number,title,state,url,statusCheckRollup,updatedAt,isDraft' + ], + { + cwd: repoPath, + encoding: 'utf-8' + } + ) + const list = JSON.parse(stdout) as NonNullable[] + data = list[0] ?? null + } else { + const { stdout } = await execFileAsync( + 'gh', + [ + 'pr', + 'view', + branchName, + '--json', + 'number,title,state,url,statusCheckRollup,updatedAt,isDraft' + ], + { + cwd: repoPath, + encoding: 'utf-8' + } + ) + data = JSON.parse(stdout) + } + + if (!data) { + return null + } + return { number: data.number, title: data.title, diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index 355f68f84..7e31522ae 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -22,7 +22,6 @@ export default function ChecksPanel(): React.JSX.Element { const repos = useAppStore((s) => s.repos) const prCache = useAppStore((s) => s.prCache) const fetchPRForBranch = useAppStore((s) => s.fetchPRForBranch) - const refreshGitHubForWorktree = useAppStore((s) => s.refreshGitHubForWorktree) const fetchPRChecks = useAppStore((s) => s.fetchPRChecks) @@ -82,9 +81,7 @@ export default function ChecksPanel(): React.JSX.Element { // Exponential backoff: if checks haven't changed, double the interval (cap 120s). // If they changed, reset to 30s. - const signature = JSON.stringify( - result.map((c) => `${c.name}:${c.status}:${c.conclusion}`) - ) + const signature = JSON.stringify(result.map((c) => `${c.name}:${c.status}:${c.conclusion}`)) pollIntervalRef.current = signature === prevChecksRef.current ? Math.min(pollIntervalRef.current * 2, 120_000) @@ -235,11 +232,13 @@ export default function ChecksPanel(): React.JSX.Element { title="Refresh" disabled={emptyRefreshing} onClick={() => { - if (activeWorktreeId) { - setEmptyRefreshing(true) - refreshGitHubForWorktree(activeWorktreeId) - setTimeout(() => setEmptyRefreshing(false), 2000) + if (!activeWorktreeId) { + return } + setEmptyRefreshing(true) + void handleRefresh().finally(() => { + setEmptyRefreshing(false) + }) }} > diff --git a/src/renderer/src/store/slices/github.ts b/src/renderer/src/store/slices/github.ts index 07a037769..d36e53e76 100644 --- a/src/renderer/src/store/slices/github.ts +++ b/src/renderer/src/store/slices/github.ts @@ -259,7 +259,7 @@ export const createGitHubSlice: StateCreator = (s // Re-fetch if (!worktree.isBare) { - void get().fetchPRForBranch(repo.path, branch) + void get().fetchPRForBranch(repo.path, branch, { force: true }) } if (worktree.linkedIssue) { void get().fetchIssue(repo.path, worktree.linkedIssue)