fix(session): broaden hydration carve-out beyond SSH repos (#1158) (#2641)

* fix(session): broaden hydration carve-out beyond SSH repos (#1158)

Finish the third deferred follow-up from #1158: preserve persisted terminal tabs when a repo is still known but its worktree list has not loaded yet.

Startup fetches repos and worktrees before hydrating the saved session. If a local repo fetch degrades to an empty list, or an SSH repo has not reconnected yet, the old SSH-only carve-out could drop every tab for that repo and let the session writer persist the loss after hydration succeeded.

Hydration now preserves missing session worktree IDs only when their owning repo is still in s.repos and that repo has not produced a non-empty worktree list. Once a repo has loaded one or more worktrees, that list stays authoritative so genuinely deleted worktrees are still filtered instead of being kept as zombies.

The sidebar placeholder synthesis remains SSH-only: local worktree metadata should come from the next successful fetch rather than a synthetic entry.

Tests cover preserving tabs for a known repo with an unloaded worktree list, dropping tabs for an unknown repo, and the existing invalid-worktree path now also pins the loaded-repo/deleted-worktree case.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Fix authoritative hydration cleanup

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com>
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Borja
2026-05-29 19:53:14 -04:00
committed by GitHub
co-authored by Claude Opus 4.7 Orca Jinwoo-H
parent 22bc5fdc07
commit bd6abeb583
4 changed files with 244 additions and 13 deletions
@@ -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<BrowserTab> & { 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'
+21 -11
View File
@@ -1774,16 +1774,17 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
.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<AppState, [], [], TerminalSlice>
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<AppState, [], [], TerminalSlice>
// 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)
@@ -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<AppState>)
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({
+20 -2
View File
@@ -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<string>()
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(