From f2095d46fb8fae1d97634da6a3ceff5cbe929767 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 31 May 2026 16:48:04 -0700 Subject: [PATCH] fix: address review findings (#4329) --- .../src/store/slices/worktree-helpers.ts | 12 +- .../src/store/slices/worktrees.test.ts | 246 ++++++++++++++++-- src/renderer/src/store/slices/worktrees.ts | 147 ++++------- 3 files changed, 276 insertions(+), 129 deletions(-) diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index e2e22d903..3aebfece1 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -26,6 +26,12 @@ export type WorktreeDeleteState = { canForceDelete: boolean } +export type WorktreeMetaUpdateGuard = (worktree: Worktree | DetectedWorktree | undefined) => boolean + +export type WorktreeMetaUpdateOptions = { + shouldApply?: WorktreeMetaUpdateGuard +} + export type WorktreeSlice = { worktreesByRepo: Record detectedWorktreesByRepo: Record @@ -112,7 +118,11 @@ export type WorktreeSlice = { expectedHead: string ) => Promise<({ ok: true } & ForceDeleteWorktreeBranchResult) | { ok: false; error: string }> clearWorktreeDeleteState: (worktreeId: string) => void - updateWorktreeMeta: (worktreeId: string, updates: Partial) => Promise + updateWorktreeMeta: ( + worktreeId: string, + updates: Partial, + options?: WorktreeMetaUpdateOptions + ) => Promise updateWorktreesMeta: ( updatesByWorktreeId: ReadonlyMap> ) => Promise diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index c4e908c06..475685637 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -1959,10 +1959,162 @@ describe('worktree remote runtime mutations', () => { }) }) - it('optimistically links a terminal-observed GitHub PR for the same repo', () => { + it('waits for branch confirmation before linking a terminal PR URL for a known push target', async () => { const store = createTestStore() - const fetchPRForBranch = vi.fn().mockResolvedValue(null) - const fetchHostedReviewForBranch = vi.fn().mockResolvedValue(null) + const fetchPRForBranch = vi.fn().mockResolvedValue({ number: 42 }) + const wt = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/worktrees/orca', + branch: 'refs/heads/feature/pr-link', + pushTarget: { + remoteName: 'origin', + branchName: 'feature/pr-link', + remoteUrl: 'https://github.com/acme/orca.git' + } + }) + store.setState({ + repos: [ + { id: 'repo1', path: '/repos/orca', displayName: 'orca', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { repo1: [wt] }, + fetchPRForBranch + } as unknown as Partial) + + store.getState().observeTerminalGitHubPullRequestLink(wt.id, { + url: 'https://github.com/acme/orca/pull/42', + slug: { owner: 'acme', repo: 'orca' }, + number: 42 + }) + + expect(store.getState().worktreesByRepo.repo1[0]?.linkedPR).toBeNull() + expect(mockApi.worktrees.resolvePrBase).not.toHaveBeenCalled() + expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalled() + expect(fetchPRForBranch).toHaveBeenCalledWith('/repos/orca', 'feature/pr-link', { + force: true, + repoId: 'repo1', + linkedPRNumber: null, + fallbackPRNumber: null, + fallbackPRSource: 'explicit' + }) + for (let i = 0; i < 6; i++) { + await Promise.resolve() + } + + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: wt.id, + updates: { linkedPR: 42 } + }) + }) + + it('waits for branch confirmation before linking a same-repo terminal PR URL', async () => { + const store = createTestStore() + const fetchPRForBranch = vi.fn().mockResolvedValue({ number: 42 }) + const wt = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/worktrees/orca', + branch: 'refs/heads/feature/pr-link', + pushTarget: { + remoteName: 'origin', + branchName: 'feature/pr-link' + } + }) + store.setState({ + repos: [ + { id: 'repo1', path: '/repos/orca', displayName: 'orca', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { repo1: [wt] }, + fetchPRForBranch + } as unknown as Partial) + + store.getState().observeTerminalGitHubPullRequestLink(wt.id, { + url: 'https://github.com/acme/orca/pull/42', + slug: { owner: 'acme', repo: 'orca' }, + number: 42 + }) + + expect(store.getState().worktreesByRepo.repo1[0]?.linkedPR).toBeNull() + expect(fetchPRForBranch).toHaveBeenCalledWith('/repos/orca', 'feature/pr-link', { + force: true, + repoId: 'repo1', + linkedPRNumber: null, + fallbackPRNumber: null, + fallbackPRSource: 'explicit' + }) + for (let i = 0; i < 6; i++) { + await Promise.resolve() + } + + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: wt.id, + updates: { linkedPR: 42 } + }) + }) + + it('does not persist a terminal PR URL when the linked PR changes before branch confirmation resolves', async () => { + const store = createTestStore() + let resolveLookup: (value: { number: number } | null) => void = () => {} + const fetchPRForBranch = vi.fn( + () => + new Promise<{ number: number } | null>((resolve) => { + resolveLookup = resolve + }) + ) + const wt = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/worktrees/orca', + branch: 'refs/heads/feature/pr-link', + pushTarget: { + remoteName: 'origin', + branchName: 'feature/pr-link' + } + }) + store.setState({ + repos: [ + { id: 'repo1', path: '/repos/orca', displayName: 'orca', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { repo1: [wt] }, + fetchPRForBranch + } as unknown as Partial) + + store.getState().observeTerminalGitHubPullRequestLink(wt.id, { + url: 'https://github.com/acme/orca/pull/42', + slug: { owner: 'acme', repo: 'orca' }, + number: 42 + }) + expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalled() + + store.setState({ + worktreesByRepo: { repo1: [{ ...wt, linkedPR: 7 }] } + } as Partial) + + resolveLookup({ number: 42 }) + for (let i = 0; i < 6; i++) { + await Promise.resolve() + } + + expect(store.getState().worktreesByRepo.repo1[0]?.linkedPR).toBe(7) + expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalled() + }) + + it('does not persist a terminal PR URL when the linked PR changes while push target lookup resolves', async () => { + const store = createTestStore() + const fetchPRForBranch = vi.fn().mockResolvedValue({ number: 42 }) + let resolvePushTarget: (value: { + baseBranch: string + pushTarget: { remoteName: string; branchName: string } + }) => void = () => {} + mockApi.worktrees.resolvePrBase.mockImplementationOnce( + () => + new Promise<{ + baseBranch: string + pushTarget: { remoteName: string; branchName: string } + }>((resolve) => { + resolvePushTarget = resolve + }) + ) const wt = makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', @@ -1974,8 +2126,7 @@ describe('worktree remote runtime mutations', () => { { id: 'repo1', path: '/repos/orca', displayName: 'orca', badgeColor: '#000', addedAt: 0 } ], worktreesByRepo: { repo1: [wt] }, - fetchPRForBranch, - fetchHostedReviewForBranch + fetchPRForBranch } as unknown as Partial) store.getState().observeTerminalGitHubPullRequestLink(wt.id, { @@ -1984,32 +2135,71 @@ describe('worktree remote runtime mutations', () => { number: 42 }) - expect(store.getState().worktreesByRepo.repo1[0]?.linkedPR).toBe(42) - expect(mockApi.worktrees.resolvePrBase).not.toHaveBeenCalled() - expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ - worktreeId: wt.id, - updates: { linkedPR: 42 } - }) - expect(fetchPRForBranch).toHaveBeenCalledWith('/repos/orca', 'feature/pr-link', { - force: true, + for (let i = 0; i < 6; i++) { + await Promise.resolve() + } + + expect(mockApi.worktrees.resolvePrBase).toHaveBeenCalledWith({ repoId: 'repo1', - linkedPRNumber: 42, - fallbackPRNumber: null, - fallbackPRSource: null + prNumber: 42 }) - expect(fetchHostedReviewForBranch).toHaveBeenCalledWith( - '/repos/orca', - 'feature/pr-link', - expect.objectContaining({ - force: true, - repoId: 'repo1', - linkedGitHubPR: 42, - linkedGitLabMR: null - }) - ) + + store.setState({ + worktreesByRepo: { repo1: [{ ...wt, linkedPR: 7 }] } + } as Partial) + + resolvePushTarget({ + baseBranch: 'main', + pushTarget: { remoteName: 'origin', branchName: 'feature/pr-link' } + }) + for (let i = 0; i < 6; i++) { + await Promise.resolve() + } + + expect(store.getState().worktreesByRepo.repo1[0]?.linkedPR).toBe(7) + expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalled() }) - it('waits for exact lookup before linking a terminal PR URL for a differently named repo', async () => { + it('does not link an arbitrary same-repo terminal PR URL for a known push target when lookup misses', async () => { + const store = createTestStore() + const fetchPRForBranch = vi.fn().mockResolvedValue(null) + const wt = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/worktrees/orca', + branch: 'refs/heads/feature/pr-link', + pushTarget: { + remoteName: 'origin', + branchName: 'feature/pr-link', + remoteUrl: 'https://github.com/acme/orca.git' + } + }) + store.setState({ + repos: [ + { id: 'repo1', path: '/repos/orca', displayName: 'orca', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { repo1: [wt] }, + fetchPRForBranch + } as unknown as Partial) + + store.getState().observeTerminalGitHubPullRequestLink(wt.id, { + url: 'https://github.com/acme/orca/pull/1', + slug: { owner: 'acme', repo: 'orca' }, + number: 1 + }) + + for (let i = 0; i < 6; i++) { + await Promise.resolve() + } + + expect(store.getState().worktreesByRepo.repo1[0]?.linkedPR).toBeNull() + expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalledWith({ + worktreeId: wt.id, + updates: { linkedPR: 1 } + }) + }) + + it('uses branch confirmation before linking a differently named terminal PR URL', async () => { const store = createTestStore() const fetchPRForBranch = vi.fn().mockResolvedValue({ number: 42 }) const wt = makeWorktree({ @@ -2038,7 +2228,7 @@ describe('worktree remote runtime mutations', () => { force: true, repoId: 'repo1', linkedPRNumber: null, - fallbackPRNumber: 42, + fallbackPRNumber: null, fallbackPRSource: 'explicit' }) diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 8f3727cef..fdb32b16b 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -6,7 +6,6 @@ import type { TerminalLayoutSnapshot, TerminalPaneLayoutNode, LocalBaseRefRefreshResult, - Repo, ForceDeleteWorktreeBranchResult, GitHubPrStartPoint, Worktree, @@ -16,7 +15,6 @@ import type { WorktreeLineage, WorktreeMeta } from '../../../../shared/types' -import type { TerminalGitHubPRLink } from '@/lib/terminal-github-pr-link-detector' import type { RuntimeWorktreeListResult } from '../../../../shared/runtime-types' import { findWorktreeById, @@ -37,7 +35,6 @@ import { moveFocusToRendererBeforeFocusedWebviewHidden } from './browser-webview import { toast } from 'sonner' import { requestVirtualizedScrollAnchorRecord } from '@/hooks/requestVirtualizedScrollAnchorRecord' import { branchName } from '@/lib/git-utils' -import { basename } from '@/lib/path' export type { WorktreeSlice, WorktreeDeleteState } from './worktree-helpers' // Why: old runtime servers only have `worktree.list`; preserve the large-list @@ -121,63 +118,6 @@ function arraysShallowEqual(a: string[] | undefined, b: string[] | undefined): b return a.every((v, i) => v === b[i]) } -function normalizeGitHubRepoName(value: string | null | undefined): string | null { - const trimmed = value?.trim() - if (!trimmed) { - return null - } - return trimmed.replace(/\.git$/i, '').toLowerCase() -} - -function parseGitHubRemoteSlug( - remoteUrl: string | null | undefined -): { owner: string; repo: string } | null { - const trimmed = remoteUrl?.trim() - if (!trimmed) { - return null - } - const withoutGitSuffix = trimmed.replace(/\.git(?:[?#].*)?$/i, '') - const match = - /^git@github\.com:([^/]+)\/([^/?#]+)$/i.exec(withoutGitSuffix) ?? - /^ssh:\/\/(?:[^@/]+@)?github\.com[:/]+([^/]+)\/([^/?#]+)$/i.exec(withoutGitSuffix) ?? - /^https?:\/\/(?:[^@/]+@)?github\.com\/([^/]+)\/([^/?#]+)$/i.exec(withoutGitSuffix) - if (!match) { - return null - } - return { owner: match[1], repo: match[2] } -} - -function githubSlugsEqual( - left: { owner: string; repo: string } | null, - right: { owner: string; repo: string } -): boolean { - return ( - left !== null && - left.owner.toLowerCase() === right.owner.toLowerCase() && - left.repo.toLowerCase() === right.repo.toLowerCase() - ) -} - -function shouldOptimisticallyLinkTerminalGitHubPR( - repo: Repo, - worktree: Pick, - link: TerminalGitHubPRLink -): boolean { - if (githubSlugsEqual(parseGitHubRemoteSlug(worktree.pushTarget?.remoteUrl), link.slug)) { - return true - } - - const observedRepo = normalizeGitHubRepoName(link.slug.repo) - if (!observedRepo) { - return false - } - const localRepoNames = [repo.displayName, basename(repo.path), basename(worktree.path)] - .map(normalizeGitHubRepoName) - .filter((name): name is string => name !== null) - - return localRepoNames.includes(observedRepo) -} - function areLineageRecordsEqual( a: WorktreeLineage | null | undefined, b: WorktreeLineage | null | undefined @@ -1485,8 +1425,12 @@ export const createWorktreeSlice: StateCreator }) }, - updateWorktreeMeta: async (worktreeId, updates) => { + updateWorktreeMeta: async (worktreeId, updates, options) => { + const shouldApplyUpdate = options?.shouldApply const existingWorktree = get().getKnownWorktreeById(worktreeId) + if (shouldApplyUpdate && !shouldApplyUpdate(existingWorktree)) { + return + } // Why: manual PR linking only supplies the PR number. Resolve the PR head // branch here so Push targets the review branch, but don't repeat that // network lookup for no-op linkedPR metadata saves. @@ -1506,12 +1450,16 @@ export const createWorktreeSlice: StateCreator linkedPrForPushTarget ) : undefined + const worktreeForUpdate = get().getKnownWorktreeById(worktreeId) + if (shouldApplyUpdate && !shouldApplyUpdate(worktreeForUpdate)) { + return + } const shouldRefreshHostedReview = - updates.linkedPR === null && existingWorktree?.linkedPR !== null + updates.linkedPR === null && worktreeForUpdate?.linkedPR !== null const reviewRepo = shouldRefreshHostedReview - ? get().repos.find((repo) => repo.id === existingWorktree?.repoId) + ? get().repos.find((repo) => repo.id === worktreeForUpdate?.repoId) : undefined - const reviewBranch = existingWorktree?.branch.replace(/^refs\/heads\//, '') + const reviewBranch = worktreeForUpdate?.branch.replace(/^refs\/heads\//, '') // Why: editing a comment is meaningful interaction with the worktree. // Without refreshing lastActivityAt, the time-decay score has decayed @@ -1526,7 +1474,12 @@ export const createWorktreeSlice: StateCreator ? { ...targetEnriched, lastActivityAt: Date.now() } : targetEnriched + let didApply = false set((s) => { + if (shouldApplyUpdate && !shouldApplyUpdate(findKnownWorktreeById(s, worktreeId))) { + return {} + } + didApply = true const nextWorktrees = applyWorktreeUpdates(s.worktreesByRepo, worktreeId, enriched) const nextDetectedWorktrees = applyDetectedWorktreeUpdates( s.detectedWorktreesByRepo, @@ -1603,6 +1556,9 @@ export const createWorktreeSlice: StateCreator ...(nextPRCache !== prCache ? { prCache: nextPRCache } : {}) } }) + if (shouldApplyUpdate && !didApply) { + return + } try { await persistWorktreeMeta(get().settings, worktreeId, enriched) @@ -1613,7 +1569,7 @@ export const createWorktreeSlice: StateCreator void get().fetchHostedReviewForBranch(reviewRepo.path, reviewBranch, { repoId: reviewRepo.id, linkedGitHubPR: null, - linkedGitLabMR: existingWorktree?.linkedGitLabMR ?? null, + linkedGitLabMR: worktreeForUpdate?.linkedGitLabMR ?? null, force: true }) } @@ -1741,58 +1697,49 @@ export const createWorktreeSlice: StateCreator } const branch = branchName(worktree.branch) - const shouldLinkNow = - worktree.linkedPR === link.number || - shouldOptimisticallyLinkTerminalGitHubPR(repo, worktree, link) - - if (shouldLinkNow && worktree.linkedPR !== link.number) { - set((s) => { - const nextWorktrees = applyWorktreeUpdates(s.worktreesByRepo, worktreeId, { - linkedPR: link.number - }) - const nextDetectedWorktrees = applyDetectedWorktreeUpdates( - s.detectedWorktreesByRepo, - worktreeId, - { linkedPR: link.number } - ) - return { - ...(nextWorktrees !== s.worktreesByRepo - ? { worktreesByRepo: nextWorktrees, sortEpoch: s.sortEpoch + 1 } - : {}), - ...(nextDetectedWorktrees !== s.detectedWorktreesByRepo - ? { detectedWorktreesByRepo: nextDetectedWorktrees } - : {}) - } - }) - // Why: `gh pr create` prints the canonical PR URL before the agent is - // done. Persist the exact number immediately so the workspace card can - // show it without waiting for the completion-time GitHub refresh. - void get().updateWorktreeMeta(worktreeId, { linkedPR: link.number }) - } + const alreadyLinked = worktree.linkedPR === link.number const fetchPRForBranch = get().fetchPRForBranch if (typeof fetchPRForBranch === 'function') { void fetchPRForBranch(repo.path, branch, { force: true, repoId: repo.id, - linkedPRNumber: shouldLinkNow ? link.number : null, - fallbackPRNumber: shouldLinkNow ? null : link.number, - fallbackPRSource: shouldLinkNow ? null : 'explicit' + linkedPRNumber: alreadyLinked ? link.number : null, + fallbackPRNumber: null, + fallbackPRSource: alreadyLinked ? null : 'explicit' }).then((pr) => { - if (!shouldLinkNow && pr?.number === link.number) { - void get().updateWorktreeMeta(worktreeId, { linkedPR: link.number }) + if (!alreadyLinked && pr?.number === link.number) { + // Why: terminal output can include arbitrary PR URLs from docs, + // agents, or logs. Persist only after branch lookup confirms it and + // the user has not picked a different PR while lookup was in flight. + void get().updateWorktreeMeta( + worktreeId, + { linkedPR: link.number }, + { + shouldApply: (currentWorktree) => + Boolean( + currentWorktree && + !currentWorktree.isBare && + !currentWorktree.isArchived && + (currentWorktree.linkedPR == null || currentWorktree.linkedPR === link.number) + ) + } + ) } }) + return } const fetchHostedReviewForBranch = get().fetchHostedReviewForBranch if (typeof fetchHostedReviewForBranch === 'function') { + // Why: full app stores always have fetchPRForBranch, which syncs the + // GitHub hosted-review cache. Keep this only as a slice-test fallback. void refreshHostedReviewCard(fetchHostedReviewForBranch, { repoPath: repo.path, repoId: repo.id, branch, - linkedGitHubPR: shouldLinkNow ? link.number : null, - fallbackGitHubPR: shouldLinkNow ? null : link.number, + linkedGitHubPR: alreadyLinked ? link.number : null, + fallbackGitHubPR: null, linkedGitLabMR: worktree.linkedGitLabMR ?? null }) }