fix(github): link create-from-PR worktrees back to their PR (#1444)

When a worktree is created from a PR via the source picker, the new
local branch differs from the PR's head ref, so the branch-keyed PR
lookup misses and the worktree card shows no PR strip. Pass the
worktree's linkedPR number through the IPC call and fall back to a
number-based lookup in the main process. Also recover linkedPR from
a PR URL pasted into the workspace name when the user skips the
source picker. PR strip now wraps the whole row as the PR link.

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinjing
2026-05-05 11:43:13 -07:00
committed by GitHub
co-authored by Orca
parent 705be9e312
commit 6a7cd2c9ae
11 changed files with 198 additions and 110 deletions
+69 -38
View File
@@ -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<PRInfo | null> {
export async function getPRForBranch(
repoPath: string,
branch: string,
linkedPRNumber?: number | null
): Promise<PRInfo | null> {
// 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<typeof data>[]
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<typeof data>[]
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)
}
+1 -1
View File
@@ -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 () => {
+18 -15
View File
@@ -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)
+7 -7
View File
@@ -499,7 +499,11 @@ export type PreloadApi = {
gh: {
viewer: () => Promise<GitHubViewer | null>
repoSlug: (args: { repoPath: string }) => Promise<{ owner: string; repo: string } | null>
prForBranch: (args: { repoPath: string; branch: string }) => Promise<PRInfo | null>
prForBranch: (args: {
repoPath: string
branch: string
linkedPRNumber?: number | null
}) => Promise<PRInfo | null>
issue: (args: { repoPath: string; number: number }) => Promise<IssueInfo | null>
workItem: (args: {
repoPath: string
@@ -603,9 +607,7 @@ export type PreloadApi = {
updateProjectItemField: (
args: UpdateProjectItemFieldArgs
) => Promise<GitHubProjectMutationResult>
clearProjectItemField: (
args: ClearProjectItemFieldArgs
) => Promise<GitHubProjectMutationResult>
clearProjectItemField: (args: ClearProjectItemFieldArgs) => Promise<GitHubProjectMutationResult>
updateIssueBySlug: (args: UpdateIssueBySlugArgs) => Promise<GitHubProjectMutationResult>
updatePullRequestBySlug: (
args: UpdatePullRequestBySlugArgs
@@ -624,9 +626,7 @@ export type PreloadApi = {
args: ListAssignableUsersBySlugArgs
) => Promise<ListAssignableUsersBySlugResult>
listIssueTypesBySlug: (args: ListIssueTypesBySlugArgs) => Promise<ListIssueTypesBySlugResult>
updateIssueTypeBySlug: (
args: UpdateIssueTypeBySlugArgs
) => Promise<GitHubProjectMutationResult>
updateIssueTypeBySlug: (args: UpdateIssueTypeBySlugArgs) => Promise<GitHubProjectMutationResult>
}
linear: {
connect: (args: {
+7 -6
View File
@@ -522,8 +522,11 @@ const api = {
repoSlug: (args: { repoPath: string }): Promise<unknown> =>
ipcRenderer.invoke('gh:repoSlug', args),
prForBranch: (args: { repoPath: string; branch: string }): Promise<unknown> =>
ipcRenderer.invoke('gh:prForBranch', args),
prForBranch: (args: {
repoPath: string
branch: string
linkedPRNumber?: number | null
}): Promise<unknown> => ipcRenderer.invoke('gh:prForBranch', args),
issue: (args: { repoPath: string; number: number }): Promise<unknown> =>
ipcRenderer.invoke('gh:issue', args),
@@ -678,8 +681,7 @@ const api = {
ipcRenderer.invoke('gh:updateProjectItemField', args),
clearProjectItemField: (
args: ClearProjectItemFieldArgs
): Promise<GitHubProjectMutationResult> =>
ipcRenderer.invoke('gh:clearProjectItemField', args),
): Promise<GitHubProjectMutationResult> => ipcRenderer.invoke('gh:clearProjectItemField', args),
updateIssueBySlug: (args: UpdateIssueBySlugArgs): Promise<GitHubProjectMutationResult> =>
ipcRenderer.invoke('gh:updateIssueBySlug', args),
updatePullRequestBySlug: (
@@ -708,8 +710,7 @@ const api = {
ipcRenderer.invoke('gh:listIssueTypesBySlug', args),
updateIssueTypeBySlug: (
args: UpdateIssueTypeBySlugArgs
): Promise<GitHubProjectMutationResult> =>
ipcRenderer.invoke('gh:updateIssueTypeBySlug', args)
): Promise<GitHubProjectMutationResult> => ipcRenderer.invoke('gh:updateIssueTypeBySlug', args)
},
linear: {
@@ -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') {
@@ -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 = {
@@ -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.
@@ -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 (
<HoverCard openDelay={300}>
<HoverCardTrigger asChild>
<div
<a
href={pr.url}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1.5 min-w-0 cursor-pointer group/meta -mx-1.5 px-1.5 py-0.5 rounded transition-colors hover:bg-background/40"
onClick={onClick}
onClick={(e) => e.stopPropagation()}
>
<PullRequestIcon
className={cn(
@@ -93,20 +96,14 @@ export function PrSection({ pr, onClick }: PrSectionProps): React.JSX.Element {
)}
/>
<div className="flex-1 min-w-0 flex items-center gap-1.5 text-[11.5px] leading-none">
<a
href={pr.url}
target="_blank"
rel="noreferrer"
className="text-foreground opacity-80 shrink-0 hover:text-foreground hover:underline"
onClick={(e) => e.stopPropagation()}
>
<span className="text-foreground opacity-80 shrink-0 group-hover/meta:underline">
PR #{pr.number}
</a>
</span>
<span className="text-muted-foreground truncate group-hover/meta:text-foreground transition-colors">
{pr.title}
</span>
</div>
</div>
</a>
</HoverCardTrigger>
<HoverCardContent side="right" align="start" className="w-72 p-3 text-xs space-y-1.5">
<div className="font-semibold text-[13px]">
+23 -5
View File
@@ -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<number | null>(() => {
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,
+38 -18
View File
@@ -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<PRInfo | null>
fetchIssue: (repoPath: string, number: number) => Promise<IssueInfo | null>
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<AppState, [], [], GitHubSlice> = (set, get) => ({
@@ -784,12 +782,18 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (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<AppState, [], [], GitHubSlice> = (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<AppState, [], [], GitHubSlice> = (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<AppState, [], [], GitHubSlice> = (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<AppState, [], [], GitHubSlice> = (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<AppState, [], [], GitHubSlice> = (s
fetchPRForBranch: async (repoPath, branch, options): Promise<PRInfo | null> => {
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() } }