diff --git a/src/renderer/src/store/slices/store-session-cascades.test.ts b/src/renderer/src/store/slices/store-session-cascades.test.ts index ed976943d..cc6bd4bdd 100644 --- a/src/renderer/src/store/slices/store-session-cascades.test.ts +++ b/src/renderer/src/store/slices/store-session-cascades.test.ts @@ -5,6 +5,7 @@ import type { AppState } from '../types' import type * as AgentStatusModule from '@/lib/agent-status' import type { BrowserTab, + DetectedWorktreeListResult, TerminalLayoutSnapshot, TerminalTab, Worktree @@ -212,6 +213,24 @@ function makeLayout(): TerminalLayoutSnapshot { return { root: null, activeLeafId: null, expandedLeafId: null } } +function makeDetectedWorktreeResult( + repoId: string, + worktrees: Worktree[], + authoritative = true +): DetectedWorktreeListResult { + return { + repoId, + authoritative, + source: authoritative ? 'git' : 'metadata-fallback', + worktrees: worktrees.map((worktree) => ({ + ...worktree, + ownership: 'orca-managed', + selectedCheckout: false, + visible: true + })) + } +} + function makeBrowserTab( overrides: Partial & { id: string; worktreeId: string; url: string } ): BrowserTab { @@ -395,6 +414,141 @@ describe('hydrateWorkspaceSession', () => { expect(s.workspaceSessionReady).toBe(false) }) + it('preserves tabs for a known repo whose worktrees have not loaded yet', () => { + // Why (#1158): empty per-repo worktrees can mean a degraded local fetch or + // SSH reconnect race, not that every persisted tab for the repo is stale. + const store = createTestStore() + const stalledWt = 'repo1::/path/wt1' + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { repo1: [] } + }) + + store.getState().hydrateWorkspaceSession({ + activeRepoId: 'repo1', + activeWorktreeId: stalledWt, + activeTabId: 'tab1', + tabsByWorktree: { + [stalledWt]: [makeTab({ id: 'tab1', worktreeId: stalledWt })] + }, + terminalLayoutsByTabId: { + tab1: makeLayout() + } + }) + + const s = store.getState() + expect(s.tabsByWorktree[stalledWt]).toHaveLength(1) + expect(s.tabsByWorktree[stalledWt][0].id).toBe('tab1') + expect(s.terminalLayoutsByTabId['tab1']).toBeDefined() + expect(s.activeWorktreeId).toBe(stalledWt) + expect(s.activeTabId).toBe('tab1') + }) + + it('preserves tabs for a known repo after a non-authoritative worktree fetch', () => { + // Why (#1158): metadata fallback means the runtime did not prove deletion. + const store = createTestStore() + const stalledWt = 'repo1::/path/wt1' + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { repo1: [] }, + detectedWorktreesByRepo: { + repo1: makeDetectedWorktreeResult('repo1', [], false) + } + }) + + store.getState().hydrateWorkspaceSession({ + activeRepoId: 'repo1', + activeWorktreeId: stalledWt, + activeTabId: 'tab1', + tabsByWorktree: { + [stalledWt]: [makeTab({ id: 'tab1', worktreeId: stalledWt })] + }, + terminalLayoutsByTabId: { + tab1: makeLayout() + } + }) + + const s = store.getState() + expect(s.tabsByWorktree[stalledWt]).toHaveLength(1) + expect(s.terminalLayoutsByTabId['tab1']).toBeDefined() + expect(s.activeWorktreeId).toBe(stalledWt) + expect(s.activeTabId).toBe('tab1') + }) + + it('drops tabs when an authoritative scan reports no matching worktrees', () => { + // Why: once git has answered authoritatively, an empty repo list means + // deleted local worktrees, not a startup race. + const store = createTestStore() + const staleWt = 'repo1::/path/deleted' + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { repo1: [] }, + detectedWorktreesByRepo: { + repo1: makeDetectedWorktreeResult('repo1', []) + } + }) + + store.getState().hydrateWorkspaceSession({ + activeRepoId: 'repo1', + activeWorktreeId: staleWt, + activeTabId: 'tab-stale', + tabsByWorktree: { + [staleWt]: [makeTab({ id: 'tab-stale', worktreeId: staleWt })] + }, + terminalLayoutsByTabId: { + 'tab-stale': makeLayout() + } + }) + + const s = store.getState() + expect(s.tabsByWorktree[staleWt]).toBeUndefined() + expect(s.terminalLayoutsByTabId['tab-stale']).toBeUndefined() + expect(s.activeWorktreeId).toBeNull() + expect(s.activeTabId).toBeNull() + }) + + it('drops tabs for an unknown repo', () => { + // Why: the carve-out only forgives missing worktrees for repos that still + // exist in the repos list. If the user removed the whole repo, its tabs + // are genuinely stale and must be dropped. + const store = createTestStore() + const orphanWt = 'repoGone::/path/wt1' + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { repo1: [] } + }) + + store.getState().hydrateWorkspaceSession({ + activeRepoId: 'repo1', + activeWorktreeId: orphanWt, + activeTabId: 'tab-orphan', + tabsByWorktree: { + [orphanWt]: [makeTab({ id: 'tab-orphan', worktreeId: orphanWt })] + }, + terminalLayoutsByTabId: { + 'tab-orphan': makeLayout() + } + }) + + const s = store.getState() + expect(s.tabsByWorktree[orphanWt]).toBeUndefined() + expect(s.terminalLayoutsByTabId['tab-orphan']).toBeUndefined() + expect(s.activeWorktreeId).toBeNull() + expect(s.activeTabId).toBeNull() + }) + it('restores valid activeWorktreeId and activeTabId', () => { const store = createTestStore() const validWt = 'repo1::/path/wt1' diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index e085ba752..2f4d7cb18 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -1774,16 +1774,17 @@ export const createTerminalSlice: StateCreator .flat() .map((worktree) => worktree.id) ) - // Why: SSH repos' worktrees are discovered at runtime via the relay, not - // persisted in orca-data.json. On restart, worktreesByRepo for SSH repos - // may still be empty when hydration runs (the SSH connection and worktree - // fetch race with session hydration). Accept session worktree IDs whose - // SSH-backed repo exists in the repos list — they will be populated once - // SSH reconnects. Without this, tabs for SSH worktrees are silently - // dropped during hydration and the session save overwrites the good data. - // Only SSH repos need this: local worktrees are persisted and a missing - // local worktree genuinely means it was deleted. - const sshRepoIds = new Set(s.repos.filter((r) => r.connectionId).map((r) => r.id)) + const knownRepoIds = new Set(s.repos.map((r) => r.id)) + const repoIdsWithLoadedWorktrees = new Set( + Object.entries(s.worktreesByRepo) + .filter(([, worktrees]) => worktrees.length > 0) + .map(([repoId]) => repoId) + ) + const repoIdsWithAuthoritativeDetectedWorktrees = new Set( + Object.entries(s.detectedWorktreesByRepo) + .filter(([, detected]) => detected.authoritative) + .map(([repoId]) => repoId) + ) // Why: the Floating Workspace is intentionally not a repo worktree, but // its tabs still use the normal terminal session pipeline so daemon PTYs // can survive app restart just like workspace terminals. @@ -1791,7 +1792,13 @@ export const createTerminalSlice: StateCreator for (const worktreeId of Object.keys(session.tabsByWorktree)) { if (!validWorktreeIds.has(worktreeId)) { const repoId = getRepoIdFromWorktreeId(worktreeId) - if (sshRepoIds.has(repoId)) { + // Why (#1158): an empty/missing list can mean degraded hydration; a + // non-empty repo list is authoritative for deleted-worktree cleanup. + if ( + knownRepoIds.has(repoId) && + !repoIdsWithLoadedWorktrees.has(repoId) && + !repoIdsWithAuthoritativeDetectedWorktrees.has(repoId) + ) { validWorktreeIds.add(worktreeId) } } @@ -1941,6 +1948,9 @@ export const createTerminalSlice: StateCreator // placeholder entries from the session's tabsByWorktree so the sidebar // shows them immediately. The placeholders will be replaced with full // data once SSH reconnects and fetchWorktrees runs. + // Why: only SSH needs placeholders; local metadata should come from the + // next successful fetch so the sidebar does not render synthetic entries. + const sshRepoIds = new Set(s.repos.filter((r) => r.connectionId).map((r) => r.id)) const worktreesByRepo = { ...s.worktreesByRepo } for (const worktreeId of Object.keys(tabsByWorktree)) { const repoId = getRepoIdFromWorktreeId(worktreeId) diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index 57858d55b..5872a1c73 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -414,6 +414,55 @@ describe('fetchWorktrees', () => { expect(store.getState().sortEpoch).toBe(7) }) + it('purges session-only tab keys after an authoritative refresh', async () => { + const store = createTestStore() + const deleted = makeWorktree({ + id: 'repo1::/path/deleted', + repoId: 'repo1', + path: '/path/deleted' + }) + const surviving = makeWorktree({ + id: 'repo1::/path/surviving', + repoId: 'repo1', + path: '/path/surviving' + }) + + mockApi.worktrees.listDetected.mockResolvedValueOnce(makeDetectedResult('repo1', [surviving])) + store.setState({ + worktreesByRepo: { repo1: [] }, + detectedWorktreesByRepo: { + repo1: makeDetectedResult('repo1', [], { + authoritative: false, + source: 'metadata-fallback' + }) + }, + tabsByWorktree: { + [deleted.id]: [{ id: 'tab-deleted', worktreeId: deleted.id }], + [surviving.id]: [{ id: 'tab-surviving', worktreeId: surviving.id }] + }, + terminalLayoutsByTabId: { + 'tab-deleted': { root: null, activeLeafId: null, expandedLeafId: null }, + 'tab-surviving': { root: null, activeLeafId: null, expandedLeafId: null } + }, + activeWorktreeId: deleted.id, + activeTabId: 'tab-deleted', + sortEpoch: 7 + } as unknown as Partial) + + await store.getState().fetchWorktrees('repo1') + + expect(store.getState().worktreesByRepo.repo1).toEqual([surviving]) + expect(store.getState().tabsByWorktree).toEqual({ + [surviving.id]: [{ id: 'tab-surviving', worktreeId: surviving.id }] + }) + expect(store.getState().terminalLayoutsByTabId).toEqual({ + 'tab-surviving': { root: null, activeLeafId: null, expandedLeafId: null } + }) + expect(store.getState().activeWorktreeId).toBeNull() + expect(store.getState().activeTabId).toBeNull() + expect(store.getState().sortEpoch).toBe(8) + }) + it('does not purge remembered state from a non-authoritative partial refresh', async () => { const store = createTestStore() const missingFromFallback = makeWorktree({ diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 430030af3..ce82c0a8a 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -239,12 +239,30 @@ function toVisibleWorktrees(result: DetectedWorktreeListResult): Worktree[] { return result.worktrees.filter((worktree) => worktree.visible).map(toVisibleWorktree) } +function getHydratedSessionWorktreeIdsForRepo(state: AppState, repoId: string): string[] { + return Object.keys(state.tabsByWorktree).filter((id) => getRepoIdFromWorktreeId(id) === repoId) +} + function getKnownWorktreeIdsForPurge(state: AppState, repoId: string): string[] { const detected = state.detectedWorktreesByRepo[repoId] + const knownIds = new Set() if (detected?.authoritative === true) { - return detected.worktrees.map((worktree) => worktree.id) + for (const worktree of detected.worktrees) { + knownIds.add(worktree.id) + } + } else { + for (const worktree of state.worktreesByRepo[repoId] ?? []) { + knownIds.add(worktree.id) + } } - return (state.worktreesByRepo[repoId] ?? []).map((worktree) => worktree.id) + if (!state.hasHydratedWorktreePurge) { + // Why (#1158): hydration can preserve tab keys before worktree metadata exists; + // the first authoritative scan still needs to reap deleted session-only keys. + for (const id of getHydratedSessionWorktreeIdsForRepo(state, repoId)) { + knownIds.add(id) + } + } + return [...knownIds] } function getRemovedWorktreeIdsAfterAuthoritativeScan(