From 2a86bb5bb43db3865cf2a640c97aad06cd3534d8 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:54:19 -0800 Subject: [PATCH] Fix fork PR attachment for remotes with separate push URLs Index linked workspaces by branch and PR to reduce refresh work. --- .../github/client/lookup/pr-branch-lookup.ts | 3 +- .../pr-published-branch-adoption.test.ts | 25 +++++++++++- .../pr-published-branch-adoption.ts | 10 ++++- .../pr-watch-workspace-sources.ts | 15 ++++++++ ...hub-pr-branch-linked-pr-divergence.test.ts | 26 +++++-------- .../workspace-review-repository.ts | 38 +++++++++++++++---- 6 files changed, 89 insertions(+), 28 deletions(-) diff --git a/src/main/github/client/lookup/pr-branch-lookup.ts b/src/main/github/client/lookup/pr-branch-lookup.ts index 5ad11334330..5ec21dea241 100644 --- a/src/main/github/client/lookup/pr-branch-lookup.ts +++ b/src/main/github/client/lookup/pr-branch-lookup.ts @@ -22,8 +22,7 @@ import { hydratePullRequestLookupData } from './pull-request-lookup-hydration' import type { PRProviderReadOptions } from './shared-pr-provider-reads' import { revalidateGitHubRestJson } from '../../github-rest-revalidation' import { noteRepositoryRateLimitSpend } from '../../rate-limit' -import { ownerRepoFromPullRequestUrl } from '../github-exec-scope' -import { sameOwnerRepo } from '../github-exec-scope' +import { ownerRepoFromPullRequestUrl, sameOwnerRepo } from '../github-exec-scope' import { getRepositoryForkParent } from '../fetch/repo-slug-upstream' // Why: GitHub lists a branch's PRs newest first, so with a page of one a closed PR opened after diff --git a/src/main/runtime/agent-session/pr-published-branch-adoption.test.ts b/src/main/runtime/agent-session/pr-published-branch-adoption.test.ts index 1012b5555bb..45ee1b1a516 100644 --- a/src/main/runtime/agent-session/pr-published-branch-adoption.test.ts +++ b/src/main/runtime/agent-session/pr-published-branch-adoption.test.ts @@ -23,6 +23,7 @@ async function adopt( branch?: string publishedFrom?: string checkoutAfterRemote?: { head: string; branch: string } + remotes?: string } = {} ) { const worktree: PublishedBranchWorkspace = { @@ -46,7 +47,10 @@ async function adopt( : { remoteUrl: `github.com:${options.owner ?? 'stablyai'}/orca.git` }) }, execGit: async (args) => ({ - stdout: args[0] === 'rev-parse' ? `${checkout.head}\n${checkout.branch}\n` : REMOTES + stdout: + args[0] === 'rev-parse' + ? `${checkout.head}\n${checkout.branch}\n` + : (options.remotes ?? REMOTES) }), resolveRemote: async (remoteName) => { checkout = options.checkoutAfterRemote ?? checkout @@ -54,6 +58,10 @@ async function adopt( ? { owner: 'me', repo: 'orca' } : { owner: 'stablyai', repo: 'orca' } }, + resolvePushUrl: async (pushUrl) => { + const owner = /github\.com:([^/]+)\//u.exec(pushUrl)?.[1] + return owner ? { owner, repo: 'orca' } : null + }, update: async (updates) => Object.assign(worktree, updates) }) return worktree @@ -82,6 +90,21 @@ describe('adoptPublishedPRBranch', () => { }) }) + it('adopts an opened fork PR through a remote that fetches upstream and pushes to the fork', async () => { + const worktree = await adopt({ + owner: 'me', + opened: true, + remotes: [ + 'origin\tgit@github.com:stablyai/orca.git (fetch)', + 'origin\tgit@github.com:me/orca.git (push)' + ].join('\n') + }) + expect(worktree).toMatchObject({ + pushTarget: { remoteName: 'origin', branchName: 'review' }, + linkedPR: 42 + }) + }) + it('leaves a checkout that has moved past the published commit alone', async () => { const worktree = await adopt({ head: '21a0e11287faaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }) expect(worktree).toMatchObject({ pushTarget: undefined, linkedPR: null, linkedItems: [] }) diff --git a/src/main/runtime/agent-session/pr-published-branch-adoption.ts b/src/main/runtime/agent-session/pr-published-branch-adoption.ts index 048b66cee2e..237a28d8f51 100644 --- a/src/main/runtime/agent-session/pr-published-branch-adoption.ts +++ b/src/main/runtime/agent-session/pr-published-branch-adoption.ts @@ -5,6 +5,7 @@ import { iterateProcessOutputLines } from '../../../shared/process-output-field- import { githubRepoIdentityKey } from '../../../shared/github/repository-identity-key' import type { GitHubOwnerRepo } from '../../../shared/github/pull-request-types' import { + parseGitRemoteFetchUrls, parseGitRemoteVerboseLine, findGitRemoteNameByPushedUrl } from '../../../shared/git/remotes/git-remote-url-index' @@ -30,6 +31,8 @@ export async function adoptPublishedPRBranch(args: { execGit: GitExec /** The GitHub repository a configured remote names, github.com or an authenticated Enterprise host. */ resolveRemote: (remoteName: string) => Promise + /** The repository a separate `pushurl` names; only compared, never contacted. */ + resolvePushUrl: (pushUrl: string) => Promise update: ( updates: { pushTarget: GitPushTarget @@ -59,12 +62,17 @@ export async function adoptPublishedPRBranch(args: { if (!published.headRepo) { return null } + const fetchUrls = parseGitRemoteFetchUrls(stdout) for (const line of iterateProcessOutputLines(stdout)) { const entry = parseGitRemoteVerboseLine(line) if (entry?.direction !== 'push' || (pushTarget && entry.name !== pushTarget.remoteName)) { continue } - const repository = await args.resolveRemote(entry.name) + // A remote that fetches upstream but pushes to a fork names the fork only in its pushurl. + const repository = + fetchUrls.get(entry.name) === entry.url + ? await args.resolveRemote(entry.name) + : await args.resolvePushUrl(entry.url) if ( repository && githubRepoIdentityKey(repository) === githubRepoIdentityKey(published.headRepo) diff --git a/src/main/runtime/agent-session/pr-watch-workspace-sources.ts b/src/main/runtime/agent-session/pr-watch-workspace-sources.ts index a0b5222fa37..48838dfea51 100644 --- a/src/main/runtime/agent-session/pr-watch-workspace-sources.ts +++ b/src/main/runtime/agent-session/pr-watch-workspace-sources.ts @@ -1,4 +1,6 @@ import { getGitHubApiRepositoryForRemote } from '../../github/github-api-repository' +import { classifyGitHubOwnerRepoFromRemoteUrl } from '../../github/github-ssh-host-alias-resolution' +import { parseGitHubRemoteIdentity } from '../../github/github-remote-identity-parsing' import type { ExecutionHostId } from '../../../shared/execution-host' import type { Repo } from '../../../shared/repo-types' import { HOSTED_REVIEW_LINK_KEYS } from '../../../shared/worktree/hosted-review-links' @@ -95,6 +97,19 @@ export function prWatchWorkspaceSources( null, getLocalProjectGhExecOptions(runtime.store(), repo) ), + resolvePushUrl: async (pushUrl) => { + const resolution = await classifyGitHubOwnerRepoFromRemoteUrl(pushUrl, { + repoPath: worktree.path, + ...getLocalProjectWorktreeGitOptions(runtime.store(), repo) + }) + // Thrown, so the intent stays and the PR's next read retries the alias. + if (resolution.kind === 'indeterminate') { + throw new Error('Push URL SSH host alias could not be resolved.') + } + return resolution.kind === 'github' + ? resolution.ownerRepo + : parseGitHubRemoteIdentity(pushUrl) + }, update: (updates, validateCheckout) => withCheckoutLock(worktree.path, () => runtime.updateManagedWorktreeMeta(selector, updates, { diff --git a/src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts b/src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts index 9100e19d065..ab155607fa2 100644 --- a/src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts +++ b/src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts @@ -7,6 +7,7 @@ import { resetRemoteRuntimeMocks } from '../github-slice-test-harness' import type { AppState } from '../../types' +import type { WorkspaceAttachment } from '../../../../../shared/worktree/types' import { getHostedReviewCacheKey } from '../../slices/hosted-review/hosted-review-cache-identity' describe('createGitHubSlice.fetchPRForBranch', () => { @@ -25,7 +26,7 @@ describe('createGitHubSlice.fetchPRForBranch', () => { vi.useRealTimers() }) - it.each([ + it.each<{ change: string; linkedPR: number | null; linkedItems: WorkspaceAttachment[] }>([ { change: 'unlinked', linkedPR: null, linkedItems: [] }, { change: 'linked to the same PR number in another repository', @@ -83,26 +84,17 @@ describe('createGitHubSlice.fetchPRForBranch', () => { worktreeId, linkedPRNumber: 12 }) - store.setState({ + store.setState((state) => ({ worktreesByRepo: { - [repoId]: [ - { - id: worktreeId, - repoId, - path: '/repo/worktrees/unlinked-direct-pr', - branch, - displayName: 'unlinked-direct-pr', - isMainWorktree: false, - isBare: false, - isArchived: false, - linkedPR, - linkedItems - } - ] + [repoId]: (state.worktreesByRepo[repoId] ?? []).map((worktree) => ({ + ...worktree, + linkedPR, + linkedItems + })) }, hostedReviewCache: {}, prCache: {} - } as unknown as Partial) + })) resolveRefresh({ kind: 'found', pr: makePR({ number: 12, title: 'Stale exact linked PR' }), diff --git a/src/renderer/src/store/slices/hosted-review/workspace-review-repository.ts b/src/renderer/src/store/slices/hosted-review/workspace-review-repository.ts index a58138af10f..a7a0e80bb30 100644 --- a/src/renderer/src/store/slices/hosted-review/workspace-review-repository.ts +++ b/src/renderer/src/store/slices/hosted-review/workspace-review-repository.ts @@ -28,6 +28,32 @@ export function selectReviewRepositoryForWorkspace( ) } +// Store arrays are replaced on change, so one index per array serves a whole refresh sweep. +const linkedWorkspaceIndexes = new WeakMap>() + +function linkedBranchKey(branch: string, prNumber: number): string { + return `${prNumber}\0${branch.replace(/^refs\/heads\//u, '')}` +} + +function workspacesLinkingPROnBranch( + worktrees: readonly Worktree[], + branch: string, + prNumber: number +): Worktree[] { + let index = linkedWorkspaceIndexes.get(worktrees) + if (!index) { + index = new Map() + for (const workspace of worktrees) { + if (workspace.linkedPR != null) { + const key = linkedBranchKey(workspace.branch, workspace.linkedPR) + index.set(key, [...(index.get(key) ?? []), workspace]) + } + } + linkedWorkspaceIndexes.set(worktrees, index) + } + return index.get(linkedBranchKey(branch, prNumber)) ?? [] +} + /** The repository of a linked GitHub PR, from the one workspace on this branch that links it. */ export function linkedGitHubPRRepositoryForBranch( state: AppState, @@ -35,12 +61,10 @@ export function linkedGitHubPRRepositoryForBranch( branch: string, prNumber: number ): GitHubOwnerRepo | undefined { - const branchName = branch.replace(/^refs\/heads\//u, '') - const worktrees = (selectWorktreesByRepo(state)?.[repo.id] ?? []).filter( - (workspace) => - workspace.branch.replace(/^refs\/heads\//u, '') === branchName && - workspace.linkedPR === prNumber && - reviewRepositoryMatchesWorkspace(repo, workspace) - ) + const worktrees = workspacesLinkingPROnBranch( + selectWorktreesByRepo(state)?.[repo.id] ?? [], + branch, + prNumber + ).filter((workspace) => reviewRepositoryMatchesWorkspace(repo, workspace)) return worktrees.length === 1 ? linkedPRRepository(worktrees[0]) : undefined }