From 5c53f2dcb64b4c1d9b1bc45fd16297be8e00285d Mon Sep 17 00:00:00 2001 From: brennanb2025 Date: Fri, 26 Jun 2026 17:35:57 -0700 Subject: [PATCH 1/3] Keep Checks panel aligned with branch switches Co-authored-by: Orca --- .../components/right-sidebar/ChecksPanel.tsx | 109 ++- .../checks-panel-git-status-snapshot.test.ts | 82 ++ .../checks-panel-git-status-snapshot.ts | 58 ++ .../src/store/slices/worktrees.test.ts | 895 +++++++++++++++++- src/renderer/src/store/slices/worktrees.ts | 394 +++++++- 5 files changed, 1525 insertions(+), 13 deletions(-) diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index bdf547c77fad..586462a0adf5 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -110,6 +110,8 @@ import { buildChecksPanelGitStatusContextKey, readChecksPanelPublishActionGitStatus, readChecksPanelGitStatusSnapshot, + readChecksPanelRefreshGitIdentitySnapshot, + hasChecksPanelGitStatusBranchChanged, shouldClearChecksPanelGitStatusSnapshot, shouldCoalesceChecksPanelGitStatusSnapshotRefresh, shouldCommitChecksPanelGitStatusSnapshot, @@ -397,6 +399,7 @@ export default function ChecksPanel(): React.JSX.Element { const setRightSidebarOpen = useAppStore((s) => s.setRightSidebarOpen) const setRightSidebarTab = useAppStore((s) => s.setRightSidebarTab) const updateWorktreeMeta = useAppStore((s) => s.updateWorktreeMeta) + const updateWorktreeGitIdentity = useAppStore((s) => s.updateWorktreeGitIdentity) const openModal = useAppStore((s) => s.openModal) // Why: the sidebar stays mounted when closed (for performance). Gate @@ -1293,6 +1296,17 @@ export default function ChecksPanel(): React.JSX.Element { } void (async () => { const status = await getRuntimeGitStatus(context) + if ( + !stale && + shouldCommitChecksPanelGitStatusSnapshot(panelContextKeyRef.current, requestContextKey) + ) { + // Why: the Checks tab can be the only visible git surface; commit + // branch identity before branch-scoped upstream refresh can fail. + updateWorktreeGitIdentity(activeWorktreeId, { + head: status.head, + branch: status.branch ?? (status.head ? null : undefined) + }) + } let freshRemoteStatus = status.upstreamStatus if (activeWorktreePushTarget) { freshRemoteStatus = await getRuntimeGitUpstreamStatus(context, activeWorktreePushTarget) @@ -1314,7 +1328,11 @@ export default function ChecksPanel(): React.JSX.Element { setGitStatusSnapshot({ contextKey: requestContextKey, hasUncommittedChanges: status.entries.length > 0, - remoteStatus + remoteStatus, + gitIdentity: { + head: status.head, + branch: status.branch ?? (status.head ? null : undefined) + } }) } }) @@ -1375,7 +1393,8 @@ export default function ChecksPanel(): React.JSX.Element { repoConnectionId, remoteStatusInvalidation, runtimeEnvironmentId, - sshConnectionStatus + sshConnectionStatus, + updateWorktreeGitIdentity ]) useEffect(() => { @@ -1843,7 +1862,6 @@ export default function ChecksPanel(): React.JSX.Element { const refreshProvider = isGitLabReviewContext ? 'gitlab' : 'github' let refreshOutcome = 'started' setIsRefreshing(true) - setGitStatusRefreshNonce((value) => value + 1) recordChecksPanelPRRefreshBreadcrumb({ event: 'start', provider: refreshProvider, @@ -1857,6 +1875,81 @@ export default function ChecksPanel(): React.JSX.Element { refreshState: prCacheKey ? useAppStore.getState().prRefreshStates[prCacheKey] : null }) try { + if (activeWorktreeId && activeWorktreePath && !isFolder) { + const snapshotIdentity = readChecksPanelRefreshGitIdentitySnapshot({ + snapshot: gitStatusSnapshot, + contextKey: panelContextKey, + currentBranch: branch + }) + if (snapshotIdentity.kind === 'changed') { + updateWorktreeGitIdentity(activeWorktreeId, { + head: snapshotIdentity.head, + branch: snapshotIdentity.branch + }) + // Why: this click discovered a terminal branch switch. Let the + // branch-keyed render/effects restart instead of refreshing old PR data. + refreshOutcome = 'branch-changed' + return + } + try { + const statusContext = { + settings: ownerSettings, + worktreeId: activeWorktreeId, + worktreePath: activeWorktreePath, + connectionId: activeConnectionId ?? undefined + } + const status = await getRuntimeGitStatus(statusContext) + const observedBranch = status.branch ?? (status.head ? null : undefined) + updateWorktreeGitIdentity(activeWorktreeId, { + head: status.head, + branch: observedBranch + }) + if ( + observedBranch !== undefined && + hasChecksPanelGitStatusBranchChanged({ + observedBranch, + currentBranch: branch + }) + ) { + // Why: this click discovered a terminal branch switch. Let the + // branch-keyed render/effects restart instead of refreshing old PR data. + refreshOutcome = 'branch-changed' + return + } + let freshRemoteStatus = status.upstreamStatus + if (activeWorktreePushTarget) { + freshRemoteStatus = await getRuntimeGitUpstreamStatus( + statusContext, + activeWorktreePushTarget + ) + } else if ( + !freshRemoteStatus || + (freshRemoteStatus.ahead > 0 && + freshRemoteStatus.behind > 0 && + freshRemoteStatus.behindCommitsArePatchEquivalent === undefined) + ) { + freshRemoteStatus = await getRuntimeGitUpstreamStatus(statusContext) + } + if ( + isCurrentRequest() && + shouldCommitChecksPanelGitStatusSnapshot(panelContextKeyRef.current, panelContextKey) + ) { + // Why: the explicit Refresh click already paid for this status read; + // commit it so empty-state Publish/Create eligibility is fresh. + setGitStatusSnapshot({ + contextKey: panelContextKey, + hasUncommittedChanges: status.entries.length > 0, + remoteStatus: freshRemoteStatus, + gitIdentity: { + head: status.head, + branch: observedBranch + } + }) + } + } catch (error) { + console.warn('[ChecksPanel] pre-refresh git identity refresh failed', error) + } + } if (isGitLabReviewContext) { const refreshedReview = await refreshHostedReviewCard(fetchHostedReviewForBranch, { repoPath: repo.path, @@ -2038,7 +2131,10 @@ export default function ChecksPanel(): React.JSX.Element { }, [ repo, branch, + activeConnectionId, activeWorktreeId, + activeWorktreePath, + activeWorktreePushTarget, activeGitLabReview, prNumber, pr?.checksStatus, @@ -2053,13 +2149,18 @@ export default function ChecksPanel(): React.JSX.Element { linkedBitbucketPR, linkedGiteaPR, linkedGitLabMR, + isFolder, isGitLabReviewContext, + gitStatusSnapshot, + panelContextKey, fetchPRForBranch, fetchPRChecks, fetchPRComments, fetchHostedReviewForBranch, expireGitHubPRRefreshState, - isCurrentAsyncResult + isCurrentAsyncResult, + ownerSettings, + updateWorktreeGitIdentity ]) const handleEntryRefresh = useCallback( diff --git a/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.test.ts b/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.test.ts index bea1a7910caf..ffbb647dfb2d 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.test.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.test.ts @@ -2,7 +2,9 @@ import { describe, expect, it } from 'vitest' import { buildChecksPanelGitStatusContextKey, readChecksPanelPublishActionGitStatus, + readChecksPanelRefreshGitIdentitySnapshot, readChecksPanelGitStatusSnapshot, + hasChecksPanelGitStatusBranchChanged, shouldClearChecksPanelGitStatusSnapshot, shouldCoalesceChecksPanelGitStatusSnapshotRefresh, shouldCommitChecksPanelGitStatusSnapshot, @@ -17,6 +19,10 @@ const SNAPSHOT: ChecksPanelGitStatusSnapshot = { hasUpstream: false, ahead: 0, behind: 0 + }, + gitIdentity: { + head: 'abc123', + branch: 'refs/heads/feature/checks' } } @@ -188,6 +194,82 @@ describe('readChecksPanelPublishActionGitStatus', () => { }) }) +describe('readChecksPanelRefreshGitIdentitySnapshot', () => { + it('treats refs/heads display differences as the same branch identity', () => { + expect( + readChecksPanelRefreshGitIdentitySnapshot({ + snapshot: SNAPSHOT, + contextKey: SNAPSHOT.contextKey, + currentBranch: 'feature/checks' + }) + ).toEqual({ kind: 'same' }) + }) + + it('reports missing when the snapshot is from a different execution context', () => { + expect( + readChecksPanelRefreshGitIdentitySnapshot({ + snapshot: SNAPSHOT, + contextKey: 'runtime:env-2::repo::worktree::branch', + currentBranch: 'feature/checks' + }) + ).toEqual({ kind: 'missing' }) + }) + + it('reports changed when the observed branch is a different branch', () => { + expect( + readChecksPanelRefreshGitIdentitySnapshot({ + snapshot: { + ...SNAPSHOT, + gitIdentity: { + head: 'def456', + branch: 'refs/heads/feature/next' + } + }, + contextKey: SNAPSHOT.contextKey, + currentBranch: 'feature/checks' + }) + ).toEqual({ + kind: 'changed', + head: 'def456', + branch: 'refs/heads/feature/next' + }) + }) + + it('reports missing when the snapshot lacks branch/head identity', () => { + expect( + readChecksPanelRefreshGitIdentitySnapshot({ + snapshot: { + contextKey: SNAPSHOT.contextKey, + hasUncommittedChanges: false, + remoteStatus: undefined + }, + contextKey: SNAPSHOT.contextKey, + currentBranch: 'feature/checks' + }) + ).toEqual({ kind: 'missing' }) + }) +}) + +describe('hasChecksPanelGitStatusBranchChanged', () => { + it('does not treat refs/heads display differences as branch changes', () => { + expect( + hasChecksPanelGitStatusBranchChanged({ + observedBranch: 'refs/heads/feature/checks', + currentBranch: 'feature/checks' + }) + ).toBe(false) + }) + + it('treats detached HEAD as changed from the rendered branch', () => { + expect( + hasChecksPanelGitStatusBranchChanged({ + observedBranch: null, + currentBranch: 'feature/checks' + }) + ).toBe(true) + }) +}) + describe('shouldCommitChecksPanelGitStatusSnapshot', () => { it('suppresses stale status refresh completions from an older execution boundary', () => { expect( diff --git a/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.ts b/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.ts index 0cec343bb2a6..897b93b3e22d 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-git-status-snapshot.ts @@ -19,6 +19,10 @@ export type ChecksPanelGitStatusSnapshot = { contextKey: string hasUncommittedChanges: boolean remoteStatus: GitUpstreamStatus | undefined + gitIdentity?: { + head?: string + branch?: string | null + } } export type ChecksPanelGitStatusInputs = { @@ -26,6 +30,19 @@ export type ChecksPanelGitStatusInputs = { remoteStatus: GitUpstreamStatus | undefined } +export type ChecksPanelRefreshGitIdentitySnapshot = + | { + kind: 'missing' + } + | { + kind: 'same' + } + | { + kind: 'changed' + head?: string + branch: string | null + } + export function buildChecksPanelGitStatusContextKey( input: ChecksPanelGitStatusContextInput ): string { @@ -118,3 +135,44 @@ export function readChecksPanelPublishActionGitStatus(input: { remoteStatus: input.fallbackRemoteStatus } } + +function canonicalBranchIdentity(branch: string | null | undefined): string { + return (branch ?? '').replace(/^refs\/heads\//, '').trim() +} + +export function readChecksPanelRefreshGitIdentitySnapshot(input: { + snapshot: ChecksPanelGitStatusSnapshot | null + contextKey: string + currentBranch: string +}): ChecksPanelRefreshGitIdentitySnapshot { + if ( + !input.snapshot || + input.snapshot.contextKey !== input.contextKey || + !input.snapshot.gitIdentity || + input.snapshot.gitIdentity.branch === undefined + ) { + return { kind: 'missing' } + } + + if ( + canonicalBranchIdentity(input.snapshot.gitIdentity.branch) === + canonicalBranchIdentity(input.currentBranch) + ) { + return { kind: 'same' } + } + + return { + kind: 'changed', + head: input.snapshot.gitIdentity.head, + branch: input.snapshot.gitIdentity.branch + } +} + +export function hasChecksPanelGitStatusBranchChanged(input: { + observedBranch: string | null | undefined + currentBranch: string +}): boolean { + return ( + canonicalBranchIdentity(input.observedBranch) !== canonicalBranchIdentity(input.currentBranch) + ) +} diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index f63a5a0e05f7..0fdb2e74c77a 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -83,7 +83,12 @@ const mockApi = { // @ts-expect-error -- test shim globalThis.window = { api: mockApi } -import { createWorktreeSlice } from './worktrees' +import { + createWorktreeSlice, + getHostedReviewLinkMutationGenerationForTests, + getHostedReviewLinkWorktreeAliasCountForTests, + resetHostedReviewLinkMutationGenerationForTests +} from './worktrees' import type { PendingWorktreeCreation } from '@/lib/pending-worktree-creation' import { getHostedReviewCacheKey } from './hosted-review' import { getGitHubPRCacheKey, getLegacyGitHubPRCacheKey } from './github-cache-key' @@ -96,6 +101,7 @@ import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/wor function resetRemoteRuntimeMocks() { clearRuntimeCompatibilityCacheForTests() + resetHostedReviewLinkMutationGenerationForTests() runtimeEnvironmentCall.mockReset() runtimeEnvironmentTransportCall.mockReset() runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { @@ -824,6 +830,33 @@ describe('fetchWorktrees', () => { expect(store.getState().sortEpoch).toBe(8) }) + it('purges hosted review link mutation bookkeeping for worktrees removed by refresh', async () => { + const store = createTestStore() + const removed = makeWorktree({ + id: 'repo1::/path/removed', + repoId: 'repo1', + path: '/path/removed' + }) + const surviving = makeWorktree({ + id: 'repo1::/path/surviving', + repoId: 'repo1', + path: '/path/surviving' + }) + + mockApi.worktrees.list.mockResolvedValue([surviving]) + store.setState({ worktreesByRepo: { repo1: [removed, surviving] } } as Partial) + await store.getState().updateWorktreeMeta(removed.id, { linkedBitbucketPR: 101 }) + await store.getState().updateWorktreeMeta(surviving.id, { linkedAzureDevOpsPR: 202 }) + + expect(getHostedReviewLinkMutationGenerationForTests(removed.id)).toBeGreaterThan(0) + expect(getHostedReviewLinkMutationGenerationForTests(surviving.id)).toBeGreaterThan(0) + + await store.getState().fetchWorktrees('repo1') + + expect(getHostedReviewLinkMutationGenerationForTests(removed.id)).toBe(0) + expect(getHostedReviewLinkMutationGenerationForTests(surviving.id)).toBeGreaterThan(0) + }) + it('purges remembered state for hidden worktrees removed by an authoritative refresh', async () => { const store = createTestStore() const visible = makeWorktree({ @@ -1761,6 +1794,7 @@ describe('updateWorktreeGitIdentity', () => { beforeEach(() => { vi.clearAllMocks() resetRemoteRuntimeMocks() + resetHostedReviewLinkMutationGenerationForTests() }) it('updates branch identity from git status without fetching worktrees', () => { @@ -1789,6 +1823,591 @@ describe('updateWorktreeGitIdentity', () => { expect(mockApi.worktrees.listDetected).not.toHaveBeenCalled() }) + it('does not notify subscribers when git status reports unchanged identity', () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + head: 'old-head', + branch: 'refs/heads/main' + }) + store.setState({ worktreesByRepo: { repo1: [existing] }, sortEpoch: 3 } as Partial) + let notifications = 0 + const unsubscribe = store.subscribe(() => { + notifications += 1 + }) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + head: 'old-head', + branch: 'refs/heads/main' + }) + store.getState().updateWorktreeGitIdentity('repo1::/path/missing', { + head: 'new-head', + branch: 'refs/heads/feature' + }) + + unsubscribe() + expect(notifications).toBe(0) + expect(store.getState().sortEpoch).toBe(3) + }) + + it('clears branch-scoped linked reviews when git status observes a branch switch', () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101, + linkedGitLabMR: 102, + linkedBitbucketPR: 103, + linkedAzureDevOpsPR: 104, + linkedGiteaPR: 105, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/two' + }) + + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + branch: 'refs/heads/stack/two', + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + }) + }) + + it('preserves linked reviews when branch identity only changes ref formatting', () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'stack/one', + linkedPR: 101, + linkedGitLabMR: 102 + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/one' + }) + + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + branch: 'refs/heads/stack/one', + linkedPR: 101, + linkedGitLabMR: 102 + }) + expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalled() + }) + + it('persists cleared branch-scoped linked reviews when git status observes a branch switch', async () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101, + linkedGitLabMR: 102, + linkedBitbucketPR: 103, + linkedAzureDevOpsPR: 104, + linkedGiteaPR: 105, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/two' + }) + await Promise.resolve() + + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + } + }) + }) + + it('persists cleared branch-scoped push target when git status observes a branch switch', async () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/two' + }) + await Promise.resolve() + + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + branch: 'refs/heads/stack/two', + pushTarget: undefined + }) + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + } + }) + }) + + it('does not persist a delayed branch-switch clear over a newer manual relink', async () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101 + }) + let resolveClearPersist!: () => void + const clearPersisted = new Promise((resolve) => { + resolveClearPersist = resolve + }) + mockApi.worktrees.updateMeta.mockImplementation(async ({ updates }) => { + if ( + updates.linkedPR === null && + updates.linkedGitLabMR === null && + updates.linkedBitbucketPR === null && + updates.linkedAzureDevOpsPR === null && + updates.linkedGiteaPR === null + ) { + await clearPersisted + } + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/two' + }) + await Promise.resolve() + await store.getState().updateWorktreeMeta('repo1::/path/wt1', { linkedGitLabMR: 202 }) + resolveClearPersist() + + await vi.waitFor(() => { + expect(mockApi.worktrees.updateMeta).toHaveBeenLastCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: { + linkedPR: null, + linkedGitLabMR: 202, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + } + }) + }) + }) + + it('does not persist a delayed branch-switch clear over a newer push target update', async () => { + const store = createTestStore() + const nextPushTarget = { remoteName: 'fork', branchName: 'next/review-head' } + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + let resolveClearPersist!: () => void + const clearPersisted = new Promise((resolve) => { + resolveClearPersist = resolve + }) + mockApi.worktrees.updateMeta.mockImplementation(async ({ updates }) => { + if ( + updates.linkedPR === null && + updates.pushTarget === undefined && + updates.linkedGitLabMR === null + ) { + await clearPersisted + } + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/two' + }) + await Promise.resolve() + await store.getState().updateWorktreeMeta('repo1::/path/wt1', { pushTarget: nextPushTarget }) + resolveClearPersist() + + await vi.waitFor(() => { + expect(mockApi.worktrees.updateMeta).toHaveBeenLastCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: nextPushTarget + } + }) + }) + }) + + it('clears stale linked reviews rehydrated by a refetch while branch-switch clear persists', async () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + let resolveClearPersist!: () => void + const clearPersisted = new Promise((resolve) => { + resolveClearPersist = resolve + }) + mockApi.worktrees.updateMeta.mockImplementation(async ({ updates }) => { + if (updates.linkedPR === null) { + await clearPersisted + } + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/two' + }) + await Promise.resolve() + const switched = store.getState().worktreesByRepo.repo1[0] + store.setState({ + worktreesByRepo: { + repo1: [ + { + ...switched, + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + } + ] + } + } as Partial) + resolveClearPersist() + + await vi.waitFor(() => { + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + branch: 'refs/heads/stack/two', + linkedPR: null, + pushTarget: undefined + }) + }) + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledTimes(1) + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + } + }) + }) + + it('clears stale linked reviews rehydrated before branch-switch clear starts persisting', async () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/two' + }) + const switched = store.getState().worktreesByRepo.repo1[0] + store.setState({ + worktreesByRepo: { + repo1: [ + { + ...switched, + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + } + ] + } + } as Partial) + + await vi.waitFor(() => { + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + branch: 'refs/heads/stack/two', + linkedPR: null, + pushTarget: undefined + }) + }) + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + } + }) + }) + + it('clears stale linked reviews rehydrated by a late worktree refetch after clear persists', async () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + const staleRefetch = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + head: 'old-head', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + head: 'new-head', + branch: 'refs/heads/stack/two' + }) + await vi.waitFor(() => { + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + } + }) + }) + + mockApi.worktrees.list.mockResolvedValue([staleRefetch]) + await store.getState().fetchWorktrees('repo1') + + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + branch: 'refs/heads/stack/two', + head: 'new-head', + linkedPR: null, + pushTarget: undefined + }) + }) + + it('keeps stale linked reviews cleared after a later observed branch switch', async () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101 + }) + const laterBranch = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101 + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/two' + }) + await vi.waitFor(() => { + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: expect.objectContaining({ linkedPR: null }) + }) + }) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/one' + }) + mockApi.worktrees.list.mockResolvedValue([laterBranch]) + await store.getState().fetchWorktrees('repo1') + + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + branch: 'refs/heads/stack/one', + linkedPR: null + }) + }) + + it('preserves a clean refreshed head when a later stale linked row arrives', async () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101 + }) + const cleanHeadAdvance = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/two', + head: 'newer-head', + linkedPR: null, + pushTarget: undefined + }) + const staleLinkedRow = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/two', + head: 'old-head', + linkedPR: 101 + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + head: 'new-head', + branch: 'refs/heads/stack/two' + }) + await vi.waitFor(() => { + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: expect.objectContaining({ linkedPR: null }) + }) + }) + + mockApi.worktrees.list.mockResolvedValue([cleanHeadAdvance]) + await store.getState().fetchWorktrees('repo1') + mockApi.worktrees.list.mockResolvedValue([staleLinkedRow]) + await store.getState().fetchWorktrees('repo1') + + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + branch: 'refs/heads/stack/two', + head: 'newer-head', + linkedPR: null + }) + }) + + it('allows a clean worktree refresh to observe a later branch after stale-refetch protection', async () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101 + }) + const laterBranch = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/three', + linkedPR: null, + pushTarget: undefined + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/two' + }) + await vi.waitFor(() => { + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: expect.objectContaining({ linkedPR: null }) + }) + }) + + mockApi.worktrees.list.mockResolvedValue([laterBranch]) + await store.getState().fetchWorktrees('repo1') + + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + branch: 'refs/heads/stack/three', + linkedPR: null, + pushTarget: undefined + }) + + mockApi.worktrees.list.mockResolvedValue([ + { + ...existing, + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + } + ]) + await store.getState().fetchWorktrees('repo1') + + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + branch: 'refs/heads/stack/three', + linkedPR: null, + pushTarget: undefined + }) + }) + + it('preserves linked reviews when only the head commit changes', () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + head: 'old-head', + branch: 'refs/heads/stack/one', + linkedPR: 101, + linkedGitLabMR: 102 + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + head: 'new-head', + branch: 'refs/heads/stack/one' + }) + + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + head: 'new-head', + branch: 'refs/heads/stack/one', + linkedPR: 101, + linkedGitLabMR: 102 + }) + }) + it('follows the new branch in the title when displayName was auto-derived from the branch', () => { const store = createTestStore() const existing = makeWorktree({ @@ -2413,6 +3032,31 @@ describe('removeWorktree state cleanup', () => { resetRemoteRuntimeMocks() }) + it('cleans up hosted review link mutation bookkeeping for the removed worktree', async () => { + const store = createTestStore() + const removed = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1' + }) + const surviving = makeWorktree({ + id: 'repo1::/path/wt2', + repoId: 'repo1', + path: '/path/wt2' + }) + store.setState({ worktreesByRepo: { repo1: [removed, surviving] } } as Partial) + await store.getState().updateWorktreeMeta(removed.id, { linkedBitbucketPR: 101 }) + await store.getState().updateWorktreeMeta(surviving.id, { linkedAzureDevOpsPR: 202 }) + + expect(getHostedReviewLinkMutationGenerationForTests(removed.id)).toBeGreaterThan(0) + expect(getHostedReviewLinkMutationGenerationForTests(surviving.id)).toBeGreaterThan(0) + + await store.getState().removeWorktree(removed.id) + + expect(getHostedReviewLinkMutationGenerationForTests(removed.id)).toBe(0) + expect(getHostedReviewLinkMutationGenerationForTests(surviving.id)).toBeGreaterThan(0) + }) + it('cleans up editorDrafts for files in the removed worktree', async () => { const store = createTestStore() const wt = makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', path: '/path/wt1' }) @@ -5304,6 +5948,12 @@ describe('migrateWorktreeIdentity', () => { const OLD = 'repo1::/ws/cunner' const NEW = 'repo1::/ws/worktree-creation-spinner' + beforeEach(() => { + vi.clearAllMocks() + resetRemoteRuntimeMocks() + resetHostedReviewLinkMutationGenerationForTests() + }) + it('re-keys worktree-scoped maps, pointers, the Set, and openFiles old->new', () => { const store = createTestStore() store.setState({ @@ -5407,6 +6057,249 @@ describe('migrateWorktreeIdentity', () => { expect(store.getState().activeWorktreeId).toBe(OTHER) expect(store.getState().tabsByWorktree[NEW]).toEqual([{ id: 'tab1' }]) }) + + it('does not track hosted review aliases for migrations without hosted-review bookkeeping', () => { + const store = createTestStore() + store.setState({ + tabsByWorktree: { [OLD]: [{ id: 'tab1' }] } + } as unknown as Partial) + + store.getState().migrateWorktreeIdentity(OLD, NEW) + + expect(getHostedReviewLinkWorktreeAliasCountForTests()).toBe(0) + }) + + it('re-keys hosted review link generation and clear tombstones', async () => { + const store = createTestStore() + const oldWorktree = makeWorktree({ + id: OLD, + repoId: 'repo1', + path: '/ws/cunner', + branch: 'refs/heads/stack/one', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + + store.setState({ worktreesByRepo: { repo1: [oldWorktree] } } as Partial) + store.getState().updateWorktreeGitIdentity(OLD, { branch: 'refs/heads/stack/two' }) + await vi.waitFor(() => { + expect(getHostedReviewLinkMutationGenerationForTests(OLD)).toBe(0) + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: OLD, + updates: { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + } + }) + }) + + const switched = store.getState().worktreesByRepo.repo1[0] + store.setState({ worktreesByRepo: { repo1: [{ ...switched, id: NEW }] } } as Partial) + store.getState().migrateWorktreeIdentity(OLD, NEW) + mockApi.worktrees.list.mockResolvedValue([ + { + ...switched, + id: NEW, + path: '/ws/worktree-creation-spinner', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + } + ]) + + await store.getState().fetchWorktrees('repo1') + + expect(getHostedReviewLinkMutationGenerationForTests(OLD)).toBe(0) + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + id: NEW, + branch: 'refs/heads/stack/two', + linkedPR: null, + pushTarget: undefined + }) + }) + + it('sanitizes lagging old-id worktree refresh rows after hosted review bookkeeping migrates', async () => { + const store = createTestStore() + const oldWorktree = makeWorktree({ + id: OLD, + repoId: 'repo1', + path: '/ws/cunner', + branch: 'refs/heads/stack/one', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + + store.setState({ worktreesByRepo: { repo1: [oldWorktree] } } as Partial) + store.getState().updateWorktreeGitIdentity(OLD, { + head: 'new-head', + branch: 'refs/heads/stack/two' + }) + await vi.waitFor(() => { + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: OLD, + updates: expect.objectContaining({ linkedPR: null, pushTarget: undefined }) + }) + }) + + const switched = store.getState().worktreesByRepo.repo1[0] + store.setState({ worktreesByRepo: { repo1: [{ ...switched, id: NEW }] } } as Partial) + store.getState().migrateWorktreeIdentity(OLD, NEW) + mockApi.worktrees.list.mockResolvedValue([ + { + ...oldWorktree, + head: 'old-head', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + } + ]) + + await store.getState().fetchWorktrees('repo1') + + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + id: OLD, + branch: 'refs/heads/stack/two', + head: 'new-head', + linkedPR: null, + pushTarget: undefined + }) + }) + + it('prunes hosted review aliases when manual hosted-review updates supersede a migrated clear', async () => { + const store = createTestStore() + const oldWorktree = makeWorktree({ + id: OLD, + repoId: 'repo1', + path: '/ws/cunner', + branch: 'refs/heads/stack/one', + linkedPR: 101 + }) + + store.setState({ worktreesByRepo: { repo1: [oldWorktree] } } as Partial) + store.getState().updateWorktreeGitIdentity(OLD, { branch: 'refs/heads/stack/two' }) + await vi.waitFor(() => { + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: OLD, + updates: expect.objectContaining({ linkedPR: null }) + }) + }) + const switched = store.getState().worktreesByRepo.repo1[0] + store.setState({ worktreesByRepo: { repo1: [{ ...switched, id: NEW }] } } as Partial) + store.getState().migrateWorktreeIdentity(OLD, NEW) + expect(getHostedReviewLinkWorktreeAliasCountForTests()).toBeGreaterThan(0) + + await store.getState().updateWorktreeMeta(NEW, { linkedPR: 202 }) + + expect(getHostedReviewLinkWorktreeAliasCountForTests()).toBe(0) + }) + + it('persists a queued branch-switch clear after worktree id migration', async () => { + const store = createTestStore() + const oldWorktree = makeWorktree({ + id: OLD, + repoId: 'repo1', + path: '/ws/cunner', + branch: 'refs/heads/stack/one', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + + store.setState({ worktreesByRepo: { repo1: [oldWorktree] } } as Partial) + store.getState().updateWorktreeGitIdentity(OLD, { branch: 'refs/heads/stack/two' }) + const switched = store.getState().worktreesByRepo.repo1[0] + store.setState({ + worktreesByRepo: { + repo1: [ + { + ...switched, + id: NEW, + path: '/ws/worktree-creation-spinner' + } + ] + } + } as Partial) + store.getState().migrateWorktreeIdentity(OLD, NEW) + + await vi.waitFor(() => { + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: NEW, + updates: { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + } + }) + }) + }) + + it('persists a queued branch-switch clear when migration happens during the old-id write', async () => { + const store = createTestStore() + const oldWorktree = makeWorktree({ + id: OLD, + repoId: 'repo1', + path: '/ws/cunner', + branch: 'refs/heads/stack/one', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + let releaseOldPersist!: () => void + let oldPersistStarted!: () => void + const oldPersistReleased = new Promise((resolve) => { + releaseOldPersist = resolve + }) + const oldPersistStartedPromise = new Promise((resolve) => { + oldPersistStarted = resolve + }) + mockApi.worktrees.updateMeta.mockImplementation(async ({ worktreeId, updates }) => { + if (worktreeId === OLD && updates.linkedPR === null) { + oldPersistStarted() + await oldPersistReleased + } + }) + + store.setState({ worktreesByRepo: { repo1: [oldWorktree] } } as Partial) + store.getState().updateWorktreeGitIdentity(OLD, { branch: 'refs/heads/stack/two' }) + await oldPersistStartedPromise + const switched = store.getState().worktreesByRepo.repo1[0] + store.setState({ + worktreesByRepo: { + repo1: [ + { + ...switched, + id: NEW, + path: '/ws/worktree-creation-spinner' + } + ] + } + } as Partial) + store.getState().migrateWorktreeIdentity(OLD, NEW) + releaseOldPersist() + + await vi.waitFor(() => { + expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith({ + worktreeId: NEW, + updates: { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + } + }) + }) + expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ + id: NEW, + branch: 'refs/heads/stack/two', + linkedPR: null, + pushTarget: undefined + }) + }) }) function makePendingCreation( diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index c300dcc16031..837caebd1f86 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -449,7 +449,10 @@ function mergeDetectedWorktreesForHost( hostId: ExecutionHostId, options?: WorktreeHostMatchOptions ): DetectedWorktreeListResult { - const refreshedForHost = refreshed.worktrees.map((worktree) => withRepoHostId(worktree, hostId)) + const refreshedForHost = sanitizeHostedReviewLinksForBranchClears( + refreshed.worktrees, + current?.worktrees + ).map((worktree) => withRepoHostId(worktree, hostId)) return { ...refreshed, worktrees: mergeWorktreesForHost(current?.worktrees, refreshedForHost, hostId, options) @@ -1219,6 +1222,250 @@ const HOSTED_REVIEW_LINK_KEYS: readonly HostedReviewLinkKey[] = [ 'linkedGiteaPR' ] +const CLEARED_HOSTED_REVIEW_LINK_UPDATES: Pick = { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined +} + +const hostedReviewLinkMutationGenerationByWorktreeId = new Map() +const hostedReviewLinkClearTombstonesByWorktreeId = new Map< + string, + { branch: string; branchIdentity: string; generation: number; head?: string } +>() +const hostedReviewLinkWorktreeIdAliases = new Map() + +function hasHostedReviewLinks(worktree: Worktree): boolean { + return HOSTED_REVIEW_LINK_KEYS.some((key) => worktree[key] != null) +} + +function hasBranchScopedHostedReviewContext(worktree: Worktree): boolean { + return hasHostedReviewLinks(worktree) || worktree.pushTarget !== undefined +} + +function hasHostedReviewLinkUpdates(updates: Partial): boolean { + return HOSTED_REVIEW_LINK_KEYS.some((key) => key in updates) || 'pushTarget' in updates +} + +function getHostedReviewLinkMutationGeneration(worktreeId: string): number { + return hostedReviewLinkMutationGenerationByWorktreeId.get(worktreeId) ?? 0 +} + +function bumpHostedReviewLinkMutationGeneration(worktreeId: string): void { + hostedReviewLinkMutationGenerationByWorktreeId.set( + worktreeId, + getHostedReviewLinkMutationGeneration(worktreeId) + 1 + ) + hostedReviewLinkClearTombstonesByWorktreeId.delete(worktreeId) + pruneHostedReviewLinkWorktreeAliasesForId(worktreeId) +} + +function pruneHostedReviewLinkMutationGenerations(worktreeIds: Iterable): void { + for (const worktreeId of worktreeIds) { + hostedReviewLinkMutationGenerationByWorktreeId.delete(worktreeId) + hostedReviewLinkClearTombstonesByWorktreeId.delete(worktreeId) + hostedReviewLinkWorktreeIdAliases.delete(worktreeId) + for (const [oldWorktreeId, newWorktreeId] of hostedReviewLinkWorktreeIdAliases) { + if (newWorktreeId === worktreeId) { + hostedReviewLinkWorktreeIdAliases.delete(oldWorktreeId) + } + } + } +} + +function resolveHostedReviewLinkWorktreeId(worktreeId: string): string { + let current = worktreeId + const seen = new Set() + while (!seen.has(current)) { + seen.add(current) + const next = hostedReviewLinkWorktreeIdAliases.get(current) + if (!next) { + return current + } + current = next + } + return worktreeId +} + +function pruneHostedReviewLinkWorktreeAliasesForId(worktreeId: string): void { + for (const [alias, target] of Array.from(hostedReviewLinkWorktreeIdAliases)) { + if ( + alias === worktreeId || + target === worktreeId || + resolveHostedReviewLinkWorktreeId(alias) === worktreeId + ) { + hostedReviewLinkWorktreeIdAliases.delete(alias) + } + } +} + +function migrateHostedReviewLinkMutationGeneration( + oldWorktreeId: string, + newWorktreeId: string +): void { + const tombstone = hostedReviewLinkClearTombstonesByWorktreeId.get(oldWorktreeId) + for (const [alias, target] of hostedReviewLinkWorktreeIdAliases) { + if (target === oldWorktreeId) { + if (tombstone) { + hostedReviewLinkWorktreeIdAliases.set(alias, newWorktreeId) + } else { + hostedReviewLinkWorktreeIdAliases.delete(alias) + } + } + } + const hasGeneration = hostedReviewLinkMutationGenerationByWorktreeId.has(oldWorktreeId) + if (tombstone) { + hostedReviewLinkWorktreeIdAliases.set(oldWorktreeId, newWorktreeId) + } + if (hasGeneration) { + hostedReviewLinkMutationGenerationByWorktreeId.set( + newWorktreeId, + getHostedReviewLinkMutationGeneration(oldWorktreeId) + ) + hostedReviewLinkMutationGenerationByWorktreeId.delete(oldWorktreeId) + } + if (tombstone) { + hostedReviewLinkClearTombstonesByWorktreeId.set(newWorktreeId, tombstone) + hostedReviewLinkClearTombstonesByWorktreeId.delete(oldWorktreeId) + } +} + +export function getHostedReviewLinkMutationGenerationForTests(worktreeId: string): number { + return getHostedReviewLinkMutationGeneration(worktreeId) +} + +export function getHostedReviewLinkWorktreeAliasCountForTests(): number { + return hostedReviewLinkWorktreeIdAliases.size +} + +export function resetHostedReviewLinkMutationGenerationForTests(): void { + hostedReviewLinkMutationGenerationByWorktreeId.clear() + hostedReviewLinkClearTombstonesByWorktreeId.clear() + hostedReviewLinkWorktreeIdAliases.clear() +} + +function hostedReviewLinksAreCleared(worktree: Worktree): boolean { + return HOSTED_REVIEW_LINK_KEYS.every((key) => worktree[key] == null) && !worktree.pushTarget +} + +function getHostedReviewLinkUpdates( + worktree: Worktree +): Pick { + return { + linkedPR: worktree.linkedPR ?? null, + linkedGitLabMR: worktree.linkedGitLabMR ?? null, + linkedBitbucketPR: worktree.linkedBitbucketPR ?? null, + linkedAzureDevOpsPR: worktree.linkedAzureDevOpsPR ?? null, + linkedGiteaPR: worktree.linkedGiteaPR ?? null, + pushTarget: worktree.pushTarget + } +} + +function canonicalHostedReviewBranchIdentity(branch: string): string { + return branchName(branch).trim() +} + +function rememberHostedReviewLinkClear( + worktreeId: string, + branch: string, + generation: number, + head?: string +): void { + hostedReviewLinkClearTombstonesByWorktreeId.set(worktreeId, { + branch, + branchIdentity: canonicalHostedReviewBranchIdentity(branch), + generation, + head + }) +} + +function sanitizeHostedReviewLinksForBranchClear< + T extends Pick & + Partial> +>(worktree: T, currentWorktrees?: readonly T[]): T { + const hostedReviewWorktreeId = resolveHostedReviewLinkWorktreeId(worktree.id) + const tombstone = hostedReviewLinkClearTombstonesByWorktreeId.get(hostedReviewWorktreeId) + const hasBranchScopedContext = + HOSTED_REVIEW_LINK_KEYS.some((key) => worktree[key] != null) || + worktree.pushTarget !== undefined + if ( + !tombstone || + tombstone.generation !== getHostedReviewLinkMutationGeneration(hostedReviewWorktreeId) || + !hasBranchScopedContext + ) { + return worktree + } + const current = currentWorktrees?.find( + (entry) => + entry.id === worktree.id || + resolveHostedReviewLinkWorktreeId(entry.id) === hostedReviewWorktreeId + ) + const currentClean = + current && + !HOSTED_REVIEW_LINK_KEYS.some((key) => current[key] != null) && + current.pushTarget === undefined + ? current + : null + const guardBranch = currentClean ? currentClean.branch : tombstone.branch + const guardHead = currentClean ? currentClean.head : tombstone.head + return { + ...worktree, + branch: guardBranch, + ...(guardHead !== undefined ? { head: guardHead } : {}), + ...CLEARED_HOSTED_REVIEW_LINK_UPDATES + } +} + +function sanitizeHostedReviewLinksForBranchClears< + T extends Pick & + Partial> +>(worktrees: readonly T[], currentWorktrees?: readonly T[]): T[] { + let changed = false + const sanitized = worktrees.map((worktree) => { + const next = sanitizeHostedReviewLinksForBranchClear(worktree, currentWorktrees) + if (next !== worktree) { + changed = true + } + return next + }) + return changed ? sanitized : [...worktrees] +} + +function applyHostedReviewLinkClear( + set: Parameters>[0], + worktreeId: string +): void { + set((s) => { + const nextWorktrees = applyWorktreeUpdates( + s.worktreesByRepo, + worktreeId, + CLEARED_HOSTED_REVIEW_LINK_UPDATES + ) + const nextDetectedWorktrees = applyDetectedWorktreeUpdates( + s.detectedWorktreesByRepo, + worktreeId, + CLEARED_HOSTED_REVIEW_LINK_UPDATES + ) + if ( + nextWorktrees === s.worktreesByRepo && + nextDetectedWorktrees === s.detectedWorktreesByRepo + ) { + return {} + } + return { + ...(nextWorktrees !== s.worktreesByRepo + ? { worktreesByRepo: nextWorktrees, sortEpoch: s.sortEpoch + 1 } + : {}), + ...(nextDetectedWorktrees !== s.detectedWorktreesByRepo + ? { detectedWorktreesByRepo: nextDetectedWorktrees } + : {}) + } + }) +} + function getPositiveHostedReviewLinkUpdateKey( updates: Partial ): HostedReviewLinkKey | null { @@ -1459,6 +1706,7 @@ function buildWorktreeRenameState( function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial { const worktreeIdSet = new Set(worktreeIds) + pruneHostedReviewLinkMutationGenerations(worktreeIdSet) // Collect every tab id (and removed file id) we are about to orphan. const doomedTabIds = new Set() @@ -1769,8 +2017,11 @@ export const createWorktreeSlice: StateCreator if (options?.requireAuthoritative && !detected.authoritative) { return false } - const worktrees = toVisibleWorktrees(detected, hostId) const current = get().worktreesByRepo[repoId] + const worktrees = sanitizeHostedReviewLinksForBranchClears( + toVisibleWorktrees(detected, hostId), + current + ) const currentMatchOptions = worktreeHostMatchOptions(get(), repoId, hostId) const currentForHost = (current ?? []).filter((worktree) => worktreeMatchesHost(worktree, hostId, currentMatchOptions) @@ -1893,7 +2144,10 @@ export const createWorktreeSlice: StateCreator const detected = await listDetectedWorktreesForRepoCoalesced(settings, r.id, { executionHostId: hostId }) - const worktrees = toVisibleWorktrees(detected, hostId) + const worktrees = sanitizeHostedReviewLinksForBranchClears( + toVisibleWorktrees(detected, hostId), + get().worktreesByRepo[r.id] + ) set((s) => { const matchOptions = worktreeHostMatchOptions(s, r.id, hostId) const removedIds = getRemovedWorktreeIdsAfterAuthoritativeScan(s, r.id, detected, hostId) @@ -1953,8 +2207,11 @@ export const createWorktreeSlice: StateCreator r.id, { executionHostId: hostId } ) - const list = toVisibleWorktrees(detected, hostId) const current = get().worktreesByRepo[r.id] + const list = sanitizeHostedReviewLinksForBranchClears( + toVisibleWorktrees(detected, hostId), + current + ) const currentMatchOptions = worktreeHostMatchOptions(get(), r.id, hostId) const currentForHost = (current ?? []).filter((worktree) => worktreeMatchesHost(worktree, hostId, currentMatchOptions) @@ -2074,11 +2331,24 @@ export const createWorktreeSlice: StateCreator }, updateWorktreeGitIdentity: (worktreeId, identity) => { + let shouldPersistHostedReviewClear = false + let clearedBranch: string | null = null + let clearGeneration = getHostedReviewLinkMutationGeneration(worktreeId) + const repoId = getRepoIdFromWorktreeId(worktreeId) + const existing = get().worktreesByRepo[repoId]?.find((worktree) => worktree.id === worktreeId) + if (!existing) { + return + } + const expectedHead = identity.head ?? existing.head + const expectedBranch = identity.branch === null ? '' : (identity.branch ?? existing.branch) + if (expectedHead === existing.head && expectedBranch === existing.branch) { + return + } + set((s) => { - const repoId = getRepoIdFromWorktreeId(worktreeId) const current = s.worktreesByRepo[repoId] if (!current) { - return {} + return s } let changed = false @@ -2092,6 +2362,27 @@ export const createWorktreeSlice: StateCreator return worktree } changed = true + const hostedReviewBranchChanged = + canonicalHostedReviewBranchIdentity(nextBranch) !== + canonicalHostedReviewBranchIdentity(worktree.branch) + const shouldClearHostedReviewContext = + hostedReviewBranchChanged && hasBranchScopedHostedReviewContext(worktree) + if (shouldClearHostedReviewContext) { + shouldPersistHostedReviewClear = true + clearedBranch = nextBranch + clearGeneration = getHostedReviewLinkMutationGeneration(worktreeId) + rememberHostedReviewLinkClear(worktreeId, nextBranch, clearGeneration, nextHead) + } else { + const tombstone = hostedReviewLinkClearTombstonesByWorktreeId.get(worktreeId) + if (tombstone) { + hostedReviewLinkClearTombstonesByWorktreeId.set(worktreeId, { + ...tombstone, + branch: nextBranch, + branchIdentity: canonicalHostedReviewBranchIdentity(nextBranch), + head: nextHead + }) + } + } // Why: terminal branch switches only patch branch/head here; auto-derived // titles need the same branch derivation that full worktree listing uses. const currentBranchName = branchName(worktree.branch) @@ -2109,11 +2400,19 @@ export const createWorktreeSlice: StateCreator } else if (identity.branch !== undefined) { detachedHeadAutoDerivedDisplayNames.delete(worktreeId) } - return { ...worktree, head: nextHead, branch: nextBranch, displayName: nextDisplayName } + return { + ...worktree, + head: nextHead, + branch: nextBranch, + displayName: nextDisplayName, + // Why: linked reviews are branch-scoped hints. If a terminal switches + // branches, keeping the old exact link makes Checks refresh the old PR. + ...(shouldClearHostedReviewContext ? CLEARED_HOSTED_REVIEW_LINK_UPDATES : {}) + } }) if (!changed) { - return {} + return s } return { @@ -2121,6 +2420,80 @@ export const createWorktreeSlice: StateCreator sortEpoch: s.sortEpoch + 1 } }) + if (!shouldPersistHostedReviewClear || clearedBranch === null) { + return + } + + void Promise.resolve() + .then(async () => { + let currentWorktreeId = resolveHostedReviewLinkWorktreeId(worktreeId) + const persistedWorktreeIds = new Set() + while (true) { + currentWorktreeId = resolveHostedReviewLinkWorktreeId(currentWorktreeId) + if (persistedWorktreeIds.has(currentWorktreeId)) { + return + } + persistedWorktreeIds.add(currentWorktreeId) + let current = get().getKnownWorktreeById(currentWorktreeId) + if ( + !current || + current.branch !== clearedBranch || + getHostedReviewLinkMutationGeneration(currentWorktreeId) !== clearGeneration + ) { + return + } + if (!hostedReviewLinksAreCleared(current as Worktree)) { + // Why: a worktree refetch can rehydrate stale linked-review metadata + // before this async clear starts; clear it again instead of bailing out. + applyHostedReviewLinkClear(set, currentWorktreeId) + current = get().getKnownWorktreeById(currentWorktreeId) + if (!current || current.branch !== clearedBranch) { + return + } + } + await persistWorktreeMeta( + settingsForWorktreeOwner(get(), currentWorktreeId), + currentWorktreeId, + CLEARED_HOSTED_REVIEW_LINK_UPDATES + ) + const migratedWorktreeId = resolveHostedReviewLinkWorktreeId(currentWorktreeId) + if (migratedWorktreeId === currentWorktreeId) { + break + } + // Why: worktree creation can migrate ids while this IPC is in flight; + // persist the branch-scoped clear under the new durable id as well. + currentWorktreeId = migratedWorktreeId + } + const latest = get().getKnownWorktreeById(currentWorktreeId) + if ( + !latest || + latest.branch !== clearedBranch || + hostedReviewLinksAreCleared(latest as Worktree) + ) { + return + } + if (getHostedReviewLinkMutationGeneration(currentWorktreeId) !== clearGeneration) { + // Why: a delayed branch-switch clear must not win over a newer manual relink. + await persistWorktreeMeta( + settingsForWorktreeOwner(get(), currentWorktreeId), + currentWorktreeId, + getHostedReviewLinkUpdates(latest as Worktree) + ) + return + } + // Why: a worktree refetch can briefly rehydrate old metadata before + // the branch-switch clear reaches disk; do not write that stale link back. + applyHostedReviewLinkClear(set, currentWorktreeId) + }) + .catch((err) => { + if (isRuntimeSelectorNotFoundError(err)) { + void get().fetchWorktrees( + getRepoIdFromWorktreeId(resolveHostedReviewLinkWorktreeId(worktreeId)) + ) + return + } + console.error('Failed to persist branch-scoped review link clear:', err) + }) }, updateWorktreeBaseStatus: (event) => { @@ -2762,6 +3135,7 @@ export const createWorktreeSlice: StateCreator void get().forceDeletePreservedBranch(worktreeId, branch, expectedHead) }) } + pruneHostedReviewLinkMutationGenerations([worktreeId]) return preservedBranch ? { ok: true as const, preservedBranch } : { ok: true as const } } catch (err) { // Why: git refusing a non-force delete for dirty/untracked files is a @@ -3022,6 +3396,9 @@ export const createWorktreeSlice: StateCreator if (shouldApplyUpdate && !didApply) { return } + if (hasHostedReviewLinkUpdates(enriched)) { + bumpHostedReviewLinkMutationGeneration(worktreeId) + } try { await persistWorktreeMeta(settingsForWorktreeOwner(get(), worktreeId), worktreeId, enriched) @@ -3953,5 +4330,6 @@ export const createWorktreeSlice: StateCreator return } set((s) => buildWorktreeRenameState(s, oldWorktreeId, newWorktreeId)) + migrateHostedReviewLinkMutationGeneration(oldWorktreeId, newWorktreeId) } }) From fa86135a624dde297b06b918c0ff5f76d1a81337 Mon Sep 17 00:00:00 2001 From: brennanb2025 Date: Fri, 26 Jun 2026 17:46:16 -0700 Subject: [PATCH 2/3] Persist hosted review clears after repeated branch switches Co-authored-by: Orca --- .../src/store/slices/worktrees.test.ts | 51 +++++++++++++++++++ src/renderer/src/store/slices/worktrees.ts | 8 ++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index 0fdb2e74c77a..fdf4ee4c71da 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -2075,6 +2075,57 @@ describe('updateWorktreeGitIdentity', () => { }) }) + it('persists a clear when the branch switches again before the first clear write finishes', async () => { + const store = createTestStore() + const existing = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1', + branch: 'refs/heads/stack/one', + linkedPR: 101, + pushTarget: { remoteName: 'fork', branchName: 'old/review-head' } + }) + let releaseFirstClear!: () => void + const firstClearReleased = new Promise((resolve) => { + releaseFirstClear = resolve + }) + let clearCalls = 0 + mockApi.worktrees.updateMeta.mockImplementation(async ({ updates }) => { + if (updates.linkedPR === null && updates.pushTarget === undefined) { + clearCalls += 1 + if (clearCalls === 1) { + await firstClearReleased + } + } + }) + + store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) + + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/two' + }) + await Promise.resolve() + store.getState().updateWorktreeGitIdentity('repo1::/path/wt1', { + branch: 'refs/heads/stack/three' + }) + releaseFirstClear() + + await vi.waitFor(() => { + expect(clearCalls).toBeGreaterThanOrEqual(2) + }) + expect(mockApi.worktrees.updateMeta).toHaveBeenLastCalledWith({ + worktreeId: 'repo1::/path/wt1', + updates: { + linkedPR: null, + linkedGitLabMR: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + pushTarget: undefined + } + }) + }) + it('clears stale linked reviews rehydrated by a refetch while branch-switch clear persists', async () => { const store = createTestStore() const existing = makeWorktree({ diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 837caebd1f86..3ab8e592c4b8 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -2375,12 +2375,18 @@ export const createWorktreeSlice: StateCreator } else { const tombstone = hostedReviewLinkClearTombstonesByWorktreeId.get(worktreeId) if (tombstone) { + const nextBranchIdentity = canonicalHostedReviewBranchIdentity(nextBranch) hostedReviewLinkClearTombstonesByWorktreeId.set(worktreeId, { ...tombstone, branch: nextBranch, - branchIdentity: canonicalHostedReviewBranchIdentity(nextBranch), + branchIdentity: nextBranchIdentity, head: nextHead }) + if (hostedReviewBranchChanged) { + shouldPersistHostedReviewClear = true + clearedBranch = nextBranch + clearGeneration = tombstone.generation + } } } // Why: terminal branch switches only patch branch/head here; auto-derived From 799e5783c4ee0892285533f1abb37611918a3b7e Mon Sep 17 00:00:00 2001 From: brennanb2025 Date: Sun, 28 Jun 2026 11:44:12 -0700 Subject: [PATCH 3/3] Guard Checks refresh against duplicate clicks Co-authored-by: Orca --- .../src/components/right-sidebar/ChecksPanel.tsx | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index 586462a0adf5..627bcf05e50d 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -429,6 +429,7 @@ export default function ChecksPanel(): React.JSX.Element { const commentsRef = useRef([]) const [emptyRefreshing, setEmptyRefreshing] = useState(false) const [isRefreshing, setIsRefreshing] = useState(false) + const refreshInFlightRef = useRef(false) const [conflictDetailsRefreshing, setConflictDetailsRefreshing] = useState(false) const createPrInFlightRef = useRef(null) const [isCreatingPr, setIsCreatingPr] = useState(false) @@ -593,6 +594,7 @@ export default function ChecksPanel(): React.JSX.Element { pollIntervalRef.current = 30_000 prevChecksRef.current = '' conflictSummaryRefreshKeyRef.current = null + refreshInFlightRef.current = false refreshRequestKeyRef.current = null if (gitStatusSnapshotRetryTimerRef.current) { clearTimeout(gitStatusSnapshotRetryTimerRef.current) @@ -1848,6 +1850,12 @@ export default function ChecksPanel(): React.JSX.Element { if (!repo || !branch) { return } + if (refreshInFlightRef.current) { + return + } + // Why: React has not disabled the button until the next render, so a rapid + // double-click must not start duplicate git status/upstream subprocesses. + refreshInFlightRef.current = true const initialRequestKey = checksPanelAsyncResultKey( prCacheKey, branch, @@ -2125,6 +2133,7 @@ export default function ChecksPanel(): React.JSX.Element { currentRequest: isCurrentRequest() }) if (isCurrentRequest()) { + refreshInFlightRef.current = false setIsRefreshing(false) } }