diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 81d427efb..55bf9035d 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -851,17 +851,21 @@ export async function getWorkItemByOwnerRepo( /** * Get PR info for a given branch using gh CLI. * Returns null if gh is not installed, or no PR exists for the branch. + * + * When `linkedPRNumber` is provided and the branch lookup yields nothing, + * falls back to looking up the PR by number. This handles "create from PR" + * worktrees, whose branch is a fresh local branch (not the PR's head ref) — + * the branch-keyed lookup misses, but the user still expects the linked PR + * to surface on the worktree card. */ -export async function getPRForBranch(repoPath: string, branch: string): Promise { +export async function getPRForBranch( + repoPath: string, + branch: string, + linkedPRNumber?: number | null +): Promise { // Strip refs/heads/ prefix if present const branchName = branch.replace(/^refs\/heads\//, '') - // During a rebase the worktree is in detached HEAD and branch is empty. - // An empty --head filter causes gh to return an arbitrary PR — bail early. - if (!branchName) { - return null - } - await acquire() try { const ownerRepo = await getOwnerRepo(repoPath) @@ -880,37 +884,64 @@ export async function getPRForBranch(repoPath: string, branch: string): Promise< headRefOid?: string } | null = null - if (ownerRepo) { - const { stdout } = await ghExecFileAsync( - [ - 'pr', - 'list', - '--repo', - `${ownerRepo.owner}/${ownerRepo.repo}`, - '--head', - branchName, - '--state', - 'all', - '--limit', - '1', - '--json', - 'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid' - ], - { cwd: repoPath } - ) - const list = JSON.parse(stdout) as NonNullable[] - data = list[0] ?? null - } else { - const { stdout } = await ghExecFileAsync( - [ - 'pr', - 'view', - branchName, - '--json', - 'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid' - ], - { cwd: repoPath } - ) + // During a rebase the worktree is in detached HEAD and branch is empty. + // An empty --head filter causes gh to return an arbitrary PR — skip the + // branch lookup and rely on the linkedPR fallback below if available. + if (branchName) { + if (ownerRepo) { + const { stdout } = await ghExecFileAsync( + [ + 'pr', + 'list', + '--repo', + `${ownerRepo.owner}/${ownerRepo.repo}`, + '--head', + branchName, + '--state', + 'all', + '--limit', + '1', + '--json', + 'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid' + ], + { cwd: repoPath } + ) + const list = JSON.parse(stdout) as NonNullable[] + data = list[0] ?? null + } else { + const { stdout } = await ghExecFileAsync( + [ + 'pr', + 'view', + branchName, + '--json', + 'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid' + ], + { cwd: repoPath } + ) + data = JSON.parse(stdout) + } + } + + if (!data && typeof linkedPRNumber === 'number') { + const args = ownerRepo + ? [ + 'pr', + 'view', + String(linkedPRNumber), + '--repo', + `${ownerRepo.owner}/${ownerRepo.repo}`, + '--json', + 'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid' + ] + : [ + 'pr', + 'view', + String(linkedPRNumber), + '--json', + 'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid' + ] + const { stdout } = await ghExecFileAsync(args, { cwd: repoPath }) data = JSON.parse(stdout) } diff --git a/src/main/ipc/github.test.ts b/src/main/ipc/github.test.ts index 8e0957530..8a74e3b74 100644 --- a/src/main/ipc/github.test.ts +++ b/src/main/ipc/github.test.ts @@ -93,7 +93,7 @@ describe('registerGitHubHandlers', () => { branch: 'feature/test' }) - expect(getPRForBranchMock).toHaveBeenCalledWith('/workspace/repo', 'feature/test') + expect(getPRForBranchMock).toHaveBeenCalledWith('/workspace/repo', 'feature/test', null) }) it('rejects unknown repository paths', async () => { diff --git a/src/main/ipc/github.ts b/src/main/ipc/github.ts index d0da43341..0926093bb 100644 --- a/src/main/ipc/github.ts +++ b/src/main/ipc/github.ts @@ -84,22 +84,25 @@ function assertRegisteredRepo(repoPath: string, store: Store): Repo { } export function registerGitHubHandlers(store: Store, stats: StatsCollector): void { - ipcMain.handle('gh:prForBranch', async (_event, args: { repoPath: string; branch: string }) => { - const repo = assertRegisteredRepo(args.repoPath, store) - const pr = await getPRForBranch(repo.path, args.branch) - // Emit pr_created when a PR is first detected for a branch. - // Why here: the renderer polls gh:prForBranch to check PR status per worktree. - // This captures PRs opened from any workflow (Orca UI, gh CLI, github.com). - if (pr && !stats.hasCountedPR(pr.url)) { - stats.record({ - type: 'pr_created', - at: Date.now(), - repoId: repo.id, - meta: { prNumber: pr.number, prUrl: pr.url } - }) + ipcMain.handle( + 'gh:prForBranch', + async (_event, args: { repoPath: string; branch: string; linkedPRNumber?: number | null }) => { + const repo = assertRegisteredRepo(args.repoPath, store) + const pr = await getPRForBranch(repo.path, args.branch, args.linkedPRNumber ?? null) + // Emit pr_created when a PR is first detected for a branch. + // Why here: the renderer polls gh:prForBranch to check PR status per worktree. + // This captures PRs opened from any workflow (Orca UI, gh CLI, github.com). + if (pr && !stats.hasCountedPR(pr.url)) { + stats.record({ + type: 'pr_created', + at: Date.now(), + repoId: repo.id, + meta: { prNumber: pr.number, prUrl: pr.url } + }) + } + return pr } - return pr - }) + ) ipcMain.handle('gh:issue', (_event, args: { repoPath: string; number: number }) => { const repo = assertRegisteredRepo(args.repoPath, store) diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index e5aaf567b..4fb6e1acb 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -499,7 +499,11 @@ export type PreloadApi = { gh: { viewer: () => Promise repoSlug: (args: { repoPath: string }) => Promise<{ owner: string; repo: string } | null> - prForBranch: (args: { repoPath: string; branch: string }) => Promise + prForBranch: (args: { + repoPath: string + branch: string + linkedPRNumber?: number | null + }) => Promise issue: (args: { repoPath: string; number: number }) => Promise workItem: (args: { repoPath: string @@ -603,9 +607,7 @@ export type PreloadApi = { updateProjectItemField: ( args: UpdateProjectItemFieldArgs ) => Promise - clearProjectItemField: ( - args: ClearProjectItemFieldArgs - ) => Promise + clearProjectItemField: (args: ClearProjectItemFieldArgs) => Promise updateIssueBySlug: (args: UpdateIssueBySlugArgs) => Promise updatePullRequestBySlug: ( args: UpdatePullRequestBySlugArgs @@ -624,9 +626,7 @@ export type PreloadApi = { args: ListAssignableUsersBySlugArgs ) => Promise listIssueTypesBySlug: (args: ListIssueTypesBySlugArgs) => Promise - updateIssueTypeBySlug: ( - args: UpdateIssueTypeBySlugArgs - ) => Promise + updateIssueTypeBySlug: (args: UpdateIssueTypeBySlugArgs) => Promise } linear: { connect: (args: { diff --git a/src/preload/index.ts b/src/preload/index.ts index 2a62a9e43..b722f0863 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -522,8 +522,11 @@ const api = { repoSlug: (args: { repoPath: string }): Promise => ipcRenderer.invoke('gh:repoSlug', args), - prForBranch: (args: { repoPath: string; branch: string }): Promise => - ipcRenderer.invoke('gh:prForBranch', args), + prForBranch: (args: { + repoPath: string + branch: string + linkedPRNumber?: number | null + }): Promise => ipcRenderer.invoke('gh:prForBranch', args), issue: (args: { repoPath: string; number: number }): Promise => ipcRenderer.invoke('gh:issue', args), @@ -678,8 +681,7 @@ const api = { ipcRenderer.invoke('gh:updateProjectItemField', args), clearProjectItemField: ( args: ClearProjectItemFieldArgs - ): Promise => - ipcRenderer.invoke('gh:clearProjectItemField', args), + ): Promise => ipcRenderer.invoke('gh:clearProjectItemField', args), updateIssueBySlug: (args: UpdateIssueBySlugArgs): Promise => ipcRenderer.invoke('gh:updateIssueBySlug', args), updatePullRequestBySlug: ( @@ -708,8 +710,7 @@ const api = { ipcRenderer.invoke('gh:listIssueTypesBySlug', args), updateIssueTypeBySlug: ( args: UpdateIssueTypeBySlugArgs - ): Promise => - ipcRenderer.invoke('gh:updateIssueTypeBySlug', args) + ): Promise => ipcRenderer.invoke('gh:updateIssueTypeBySlug', args) }, linear: { diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index 185072714..df4205926 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -79,12 +79,15 @@ export default function ChecksPanel(): React.JSX.Element { ? (gitConflictOperationByWorktree[activeWorktreeId] ?? 'unknown') : 'unknown' - // Fetch PR data when the active worktree/branch changes + // Fetch PR data when the active worktree/branch changes. + // Why: pass linkedPR so worktrees created from a PR (whose new local branch + // differs from the PR's head ref) resolve via the number-based fallback. + const linkedPR = activeWorktree?.linkedPR ?? null useEffect(() => { if (repo && !isFolder && branch) { - void fetchPRForBranch(repo.path, branch) + void fetchPRForBranch(repo.path, branch, { linkedPRNumber: linkedPR }) } - }, [repo, isFolder, branch, fetchPRForBranch]) + }, [repo, isFolder, branch, linkedPR, fetchPRForBranch]) useEffect(() => { if (!repo || isFolder || !branch || !pr || pr.mergeable !== 'CONFLICTING') { diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index d933045ed..788c4bdc5 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -297,6 +297,7 @@ function SourceControlInner(): React.JSX.Element { const prCacheKey = activeRepo && branchName ? `${activeRepo.path}::${branchName}` : null const prInfo: PRInfo | null = prCacheKey ? (prCache[prCacheKey]?.data ?? null) : null + const linkedPR = activeWorktree?.linkedPR ?? null useEffect(() => { if (!isBranchVisible || !activeRepo || isFolder || !branchName || branchName === 'HEAD') { return @@ -305,9 +306,10 @@ function SourceControlInner(): React.JSX.Element { // Why: the Source Control panel renders the branch's PR badge directly. // When a terminal checkout moves this worktree onto a new branch, we need // to fetch that branch's PR immediately instead of waiting for the user to - // reselect the worktree or open the separate Checks panel. - void fetchPRForBranch(activeRepo.path, branchName) - }, [activeRepo, branchName, fetchPRForBranch, isBranchVisible, isFolder]) + // reselect the worktree or open the separate Checks panel. Pass linkedPR + // so create-from-PR worktrees resolve via the number-based fallback. + void fetchPRForBranch(activeRepo.path, branchName, { linkedPRNumber: linkedPR }) + }, [activeRepo, branchName, fetchPRForBranch, isBranchVisible, isFolder, linkedPR]) const grouped = useMemo(() => { const groups = { diff --git a/src/renderer/src/components/sidebar/WorktreeCard.tsx b/src/renderer/src/components/sidebar/WorktreeCard.tsx index 8a3ae5a9e..1bd9f786e 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.tsx @@ -255,9 +255,22 @@ const WorktreeCard = React.memo(function WorktreeCard({ // spend rate limit budget on data the user cannot see. useEffect(() => { if (repo && !isFolder && !worktree.isBare && prCacheKey && (showPR || showCI)) { - fetchPRForBranch(repo.path, branch) + // Why: pass linkedPR so worktrees created from a PR (whose new local + // branch differs from the PR's head ref) still resolve their PR via + // a number-based fallback in the main process. + fetchPRForBranch(repo.path, branch, { linkedPRNumber: worktree.linkedPR ?? null }) } - }, [repo, isFolder, worktree.isBare, fetchPRForBranch, branch, prCacheKey, showPR, showCI]) + }, [ + repo, + isFolder, + worktree.isBare, + worktree.linkedPR, + fetchPRForBranch, + branch, + prCacheKey, + showPR, + showCI + ]) // Same rationale for issues: once that section is hidden, polling only burns // GitHub calls and keeps stale-but-invisible data warm for no user benefit. diff --git a/src/renderer/src/components/sidebar/WorktreeCardMeta.tsx b/src/renderer/src/components/sidebar/WorktreeCardMeta.tsx index 2bbe8e7dd..d2f8e4c71 100644 --- a/src/renderer/src/components/sidebar/WorktreeCardMeta.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCardMeta.tsx @@ -73,13 +73,16 @@ type PrSectionProps = { onClick: (e: React.MouseEvent) => void } -export function PrSection({ pr, onClick }: PrSectionProps): React.JSX.Element { +export function PrSection({ pr, onClick: _onClick }: PrSectionProps): React.JSX.Element { return ( -
e.stopPropagation()} > -
+
diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index 21a3a6c00..2da6a45d5 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -7,7 +7,11 @@ import { toast } from 'sonner' 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 { + parseGitHubIssueOrPRNumber, + parseGitHubIssueOrPRLink, + normalizeGitHubLinkQuery +} from '@/lib/github-links' import { activateAndRevealWorktree } from '@/lib/worktree-activation' import { buildAgentDraftLaunchPlan, buildAgentStartupPlan } from '@/lib/tui-agent-startup' import { TUI_AGENT_CONFIG } from '../../../shared/tui-agent-config' @@ -398,6 +402,20 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS () => (linkedIssue.trim() ? parseGitHubIssueOrPRNumber(linkedIssue) : null), [linkedIssue] ) + // Why: when the user pastes a PR URL straight into the workspace name field + // (without picking from the source picker), `linkedPR` stays null and the + // worktree card has no PR strip. Recover the PR number from the name on + // submit so create-from-PR worktrees always link back to their PR. + const effectiveLinkedPR = useMemo(() => { + if (linkedPR !== null) { + return linkedPR + } + const fromName = parseGitHubIssueOrPRLink(name) + if (fromName && fromName.type === 'pr') { + return fromName.number + } + return null + }, [linkedPR, name]) const setupConfig = useMemo( () => getSetupConfig(selectedRepo, yamlHooks), [selectedRepo, yamlHooks] @@ -1235,7 +1253,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS await applyWorktreeMeta(worktree.id, { ...(parsedLinkedIssueNumber !== null ? { linkedIssue: parsedLinkedIssueNumber } : {}), - ...(linkedPR !== null ? { linkedPR } : {}), + ...(effectiveLinkedPR !== null ? { linkedPR: effectiveLinkedPR } : {}), ...(note.trim() ? { comment: note.trim() } : {}) }) @@ -1288,7 +1306,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS createWorktree, applyWorktreeMeta, issueCommandTemplate, - linkedPR, + effectiveLinkedPR, linkedWorkItem?.url, normalizedSparseDirectories, note, @@ -1362,7 +1380,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS const trimmedNote = note.trim() await applyWorktreeMeta(worktree.id, { ...(parsedLinkedIssueNumber !== null ? { linkedIssue: parsedLinkedIssueNumber } : {}), - ...(linkedPR !== null ? { linkedPR } : {}), + ...(effectiveLinkedPR !== null ? { linkedPR: effectiveLinkedPR } : {}), ...(trimmedNote ? { comment: trimmedNote } : {}) }) @@ -1464,7 +1482,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS clearNewWorkspaceDraft, createWorktree, fallbackCreatureName, - linkedPR, + effectiveLinkedPR, linkedWorkItem, name, normalizedSparseDirectories, diff --git a/src/renderer/src/store/slices/github.ts b/src/renderer/src/store/slices/github.ts index db8cadc6d..e77901aba 100644 --- a/src/renderer/src/store/slices/github.ts +++ b/src/renderer/src/store/slices/github.ts @@ -71,7 +71,9 @@ export type ProjectRowContentPatch = { // different rows when the view's stored filter is non-empty, so it gets its // own cache key. function queryOverrideKeyPart(queryOverride: string | undefined): string { - if (queryOverride === undefined) {return ''} + if (queryOverride === undefined) { + return '' + } return `:q=${queryOverride}` } @@ -405,7 +407,7 @@ export type GitHubSlice = { fetchPRForBranch: ( repoPath: string, branch: string, - options?: FetchOptions + options?: FetchOptions & { linkedPRNumber?: number | null } ) => Promise fetchIssue: (repoPath: string, number: number) => Promise fetchPRChecks: ( @@ -566,11 +568,7 @@ export type GitHubSlice = { * alone only walks `workItemsCache` and would leave the Project view stale * until the next refresh. The actual write is dispatched separately via * the slug-addressed update IPCs. */ - patchProjectRowContent: ( - cacheKey: string, - rowId: string, - patch: ProjectRowContentPatch - ) => void + patchProjectRowContent: (cacheKey: string, rowId: string, patch: ProjectRowContentPatch) => void } export const createGitHubSlice: StateCreator = (set, get) => ({ @@ -784,12 +782,18 @@ export const createGitHubSlice: StateCreator = (s } // Optimistic content patch. const nextContent = { ...previousRow.content } - if (updates.title !== undefined) {nextContent.title = updates.title} - if (updates.body !== undefined) {nextContent.body = updates.body} + if (updates.title !== undefined) { + nextContent.title = updates.title + } + if (updates.body !== undefined) { + nextContent.body = updates.body + } if (updates.addLabels || updates.removeLabels) { const next = new Map(nextContent.labels.map((l) => [l.name, l])) for (const name of updates.addLabels ?? []) { - if (!next.has(name)) {next.set(name, { name, color: '808080' })} + if (!next.has(name)) { + next.set(name, { name, color: '808080' }) + } } for (const name of updates.removeLabels ?? []) { next.delete(name) @@ -799,7 +803,9 @@ export const createGitHubSlice: StateCreator = (s if (updates.addAssignees || updates.removeAssignees) { const next = new Map(nextContent.assignees.map((u) => [u.login, u])) for (const login of updates.addAssignees ?? []) { - if (!next.has(login)) {next.set(login, { login, name: null, avatarUrl: null })} + if (!next.has(login)) { + next.set(login, { login, name: null, avatarUrl: null }) + } } for (const login of updates.removeAssignees ?? []) { next.delete(login) @@ -827,7 +833,9 @@ export const createGitHubSlice: StateCreator = (s ...(updates.body !== undefined ? { body: updates.body } : {}) } }) - if (!prRes.ok) {envelope = prRes} + if (!prRes.ok) { + envelope = prRes + } } if ( envelope.ok && @@ -851,7 +859,9 @@ export const createGitHubSlice: StateCreator = (s ...(updates.removeAssignees ? { removeAssignees: updates.removeAssignees } : {}) } }) - if (!issueRes.ok) {envelope = issueRes} + if (!issueRes.ok) { + envelope = issueRes + } } if (!envelope.ok) { rollbackRowIfPresent(set, get, cacheKey, rowId, previousRow) @@ -913,8 +923,12 @@ export const createGitHubSlice: StateCreator = (s return } const nextContent = { ...previousRow.content } - if (patch.title !== undefined) {nextContent.title = patch.title} - if (patch.body !== undefined) {nextContent.body = patch.body} + if (patch.title !== undefined) { + nextContent.title = patch.title + } + if (patch.body !== undefined) { + nextContent.body = patch.body + } if (patch.state !== undefined) { // Why: ProjectV2 row.state mirrors GitHub's UPPERCASE state enum // ('OPEN' | 'CLOSED' | 'MERGED'). The dialog tracks lowercase @@ -1167,21 +1181,27 @@ export const createGitHubSlice: StateCreator = (s fetchPRForBranch: async (repoPath, branch, options): Promise => { const cacheKey = `${repoPath}::${branch}` const cached = get().prCache[cacheKey] - if (!options?.force && isFresh(cached)) { + // Why: if a prior caller without a linkedPR cached `null` for this branch, + // the worktree-card lookup (which has a linked PR fallback) would otherwise + // return null forever. Refetch when the cached miss could now resolve via + // the linkedPR path. + const linkedRefetch = cached?.data === null && (options?.linkedPRNumber ?? null) !== null + if (!options?.force && !linkedRefetch && isFresh(cached)) { return cached.data } const inflightRequest = inflightPRRequests.get(cacheKey) - if (inflightRequest && (!options?.force || inflightRequest.force)) { + if (inflightRequest && (!options?.force || inflightRequest.force) && !linkedRefetch) { return inflightRequest.promise } const generation = (prRequestGenerations.get(cacheKey) ?? 0) + 1 prRequestGenerations.set(cacheKey, generation) + const linkedPRNumber = options?.linkedPRNumber ?? null const request = (async () => { try { - const pr = await window.api.gh.prForBranch({ repoPath, branch }) + const pr = await window.api.gh.prForBranch({ repoPath, branch, linkedPRNumber }) if (prRequestGenerations.get(cacheKey) === generation) { set((s) => ({ prCache: { ...s.prCache, [cacheKey]: { data: pr, fetchedAt: Date.now() } }