Repository navigation
fix: reclaim orphaned worktree/session state on load (duplicate workspace that returns after restart) - #9200
PannenetsF wants to merge 8 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe persistence store now performs host-aware garbage collection during load. It removes orphaned worktree metadata, lineage, workspace-session ownership, terminal-session data, and stale active repository state. Cleanup preserves live repositories, folder-scoped data, duplicate repository ids on valid hosts, and metadata when no live repositories exist. Persistence tests cover these cases and align repository fixtures on 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: b6aefde1-26fd-4055-95e5-ed556b7f43d1
📒 Files selected for processing (2)
src/main/persistence.test.tssrc/main/persistence.ts
|
Taking a look! |
`pruneWorktreeStateForRepo` only runs via `removeProject`/`removeProjectForHost`, both of which require the repo to still be in `repos`. A repo id that leaves `repos` by any other path (a partial/interrupted delete, a repo-id re-key migration, or a crash between the filter and the save) is never routed through prune again, so its `worktreeMeta`/lineage rows and `workspaceSession` owner keys are orphaned permanently. `gcStaleWorktreeMeta` cannot reclaim them either: it keeps an entry whose path still exists on disk (a duplicate that shares a live repo's path — `existsSync` is true) or whose meta carries a remote `hostId`. The ownerless `worktreeMeta` row is then restored verbatim on every load, and its `workspaceSession` `tabsByWorktree` twin is re-materialized into a phantom "unknown"/duplicate workspace on the next launch (`hydrateHeadlessMobileSessionTabsFromWorkspaceSession` iterates `tabsByWorktree` with no repo gate). Add `gcOrphanedRepoState`, a load-time sweep that removes `worktreeMeta` / lineage / `workspaceLineage` entries and `workspaceSession`(+ByHostId) owner keys whose repo id is absent from both `repos` and `projects`, reusing `removeWorkspaceSessionOwner` so the sweep and the delete path share one cleanup. Skips when there are zero live owners so an anomalous empty-`repos` load can never wipe all state. This is the load-side companion to stablyai#9025, which fixes only the forward delete path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Increment `removed` when pruning `worktreeLineageById` / `workspaceLineageByChildKey`. Without it, a profile whose only orphaned state is a lineage entry (no `worktreeMeta` or session-owner key) cleaned in memory but left `loadNeedsSave` unset, so the sweep was not persisted and the orphan lineage returned on the next load. Adds a regression test. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
15aa6d5 to
29772a0
Compare
|
Thanks for the thorough report and regression coverage! I rebased the branch onto current main and tightened the load-time reconciliation so repos/projects remain authoritative across worktree metadata, lineage, all owner-keyed session fields, and host partitions. The follow-up preserves the lineage dirty-count fix, handles canonical workspace keys and dependent relay state, and batches cleanup to one clone per session instead of one per orphan key. Coverage now includes editor-only orphan state, canonical active keys, relay IDs, host partitions, live/remote paths, empty-owner safety, and lineage-only persistence; all 386 persistence tests, node typecheck, touched-file lint, and the max-lines ratchet pass. |
…r exists
`hydrateHeadlessMobileSessionTabsFromWorkspaceSession` iterates
`workspaceSession.tabsByWorktree` with no repo gate. Those keys are
`${repoId}::${path}` and are not pruned when a repo disappears from this
client's view, so a stale key re-materializes a phantom "unknown"/duplicate
workspace with no live repo behind it, on boot, with no `session-created` event.
Skip entries whose parsed repoId is not in the live `repos`; leave unparseable
keys alone (conservative). Defensive complement to the delete-path (stablyai#9025) and
load-time (stablyai#9200) fixes — this closes the mobile/headless hydration path.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…r exists (#9343) `hydrateHeadlessMobileSessionTabsFromWorkspaceSession` iterates `workspaceSession.tabsByWorktree` with no repo gate. Those keys are `${repoId}::${path}` and are not pruned when a repo disappears from this client's view, so a stale key re-materializes a phantom "unknown"/duplicate workspace with no live repo behind it, on boot, with no `session-created` event. Skip entries whose parsed repoId is not in the live `repos`; leave unparseable keys alone (conservative). Defensive complement to the delete-path (#9025) and load-time (#9200) fixes — this closes the mobile/headless hydration path. Co-authored-by: fanyunqian.1 <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # src/main/persistence.ts
cd32fab to
8922382
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 994be87b-7541-4c74-8999-fcd734b4b954
📒 Files selected for processing (5)
src/main/persistence.test.tssrc/main/persistence.tssrc/renderer/src/components/right-sidebar/FileExplorer.tsxsrc/renderer/src/components/right-sidebar/file-explorer-inline-input-outside-click.test.tsxsrc/renderer/src/components/sidebar/worktree-keyboard-cycle.test.ts
…(CodeRabbit) Repo ids are host-scoped in the store, so the same id can be live locally and removed on an SSH host. The orphan sweep collapsed owners to bare ids, letting a live local repo keep the removed SSH twin's host-tagged worktreeMeta and its SSH session partition alive. Detect orphans per (repoId, host): host-tagged metas and each host partition scope to their host, while the legacy session blob and lineage (which can hold any host's owners and carry no host of their own) keep the conservative any-host check. Also collect tombstone-only session owners so a worktree that survives only as a terminal-surface tombstone is swept. Adds duplicate-id local/SSH and tombstone-only regression tests. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…state-on-load # Conflicts: # src/main/persistence.ts
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d2134b6e-fa27-4f53-be8e-425a805245b3
📒 Files selected for processing (2)
src/main/persistence.test.tssrc/main/persistence.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/persistence.ts
| it('sweeps and persists a lineage entry whose parent repo id is gone (no worktreeMeta/session twin)', async () => { | ||
| const liveKey = `live-repo::${testState.dir}` | ||
| // Why: lineage-only deletion must still mark the loaded state for persistence. | ||
| writeDataFile({ | ||
| repos: [makeRepo({ id: 'live-repo', path: testState.dir })], | ||
| worktreeMeta: { [liveKey]: { displayName: '', comment: '', lastActivityAt: 1 } }, | ||
| worktreeLineageById: { [liveKey]: { parentWorktreeId: 'orphan-repo::/home/tiger/gone' } } | ||
| }) | ||
|
|
||
| const store = await createStore() | ||
| expect(store.getWorktreeLineage(liveKey)).toBeUndefined() | ||
|
|
||
| store.flush() | ||
| const persisted = readDataFile() as { worktreeLineageById?: Record<string, unknown> } | ||
| expect(persisted.worktreeLineageById?.[liveKey]).toBeUndefined() | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Cover workspaceLineageByChildKey cleanup.
This test covers worktreeLineageById only. gcOrphanedRepoState uses a separate cleanup loop for workspaceLineageByChildKey. Add a lineage entry with an orphaned parent workspace key, then assert that load removes it and flush() persists the removal.
605d3fd to
a45441a
Compare
|
@brennanb2025 Rebased onto the latest main and resolved all conflicts. Verified locally (typecheck + targeted tests pass); CI is pending maintainer approval to run. Ready for review whenever you have a moment — thanks! |
…state-on-load # Conflicts: # src/main/persistence.test.ts # src/main/persistence.ts
a45441a to
a4d707d
Compare
# Conflicts: # src/main/persistence/tracking-repos/worktree-metadata-normalization.ts
…r exists (stablyai#9343) `hydrateHeadlessMobileSessionTabsFromWorkspaceSession` iterates `workspaceSession.tabsByWorktree` with no repo gate. Those keys are `${repoId}::${path}` and are not pruned when a repo disappears from this client's view, so a stale key re-materializes a phantom "unknown"/duplicate workspace with no live repo behind it, on boot, with no `session-created` event. Skip entries whose parsed repoId is not in the live `repos`; leave unparseable keys alone (conservative). Defensive complement to the delete-path (stablyai#9025) and load-time (stablyai#9200) fixes — this closes the mobile/headless hydration path. Co-authored-by: fanyunqian.1 <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
|
Thanks @PannenetsF for the detailed root-cause analysis! This is already handled on main by the load-time sweep that landed with #17901 (a2aea5d). On every load, |
Summary
A project can appear twice in the sidebar — one real card plus a phantom duplicate at the same path — and the phantom returns after every restart, even after you delete it from
worktreeMetaby hand. This is the already-orphaned sibling of #9024: the repo id is gone fromrepos, but itsworktreeMetarow andworkspaceSessionowner keys survive forever and get re-materialized on load.This is the load-side companion to #9025. #9025 fixes the forward path — deleting a project that is still in
repos. It does not help a repo id that is already gone fromrepos, because the function it patches is unreachable in that state.Root cause
Two gaps combine so an ownerless entry becomes permanently unreclaimable:
pruneWorktreeStateForRepois unreachable once the repo leavesrepos. Its only callers areremoveProjectandremoveProjectForHost(persistence.ts), and every external entry point into those resolves a live repo first (ipc/repos.ts,orca-runtime.ts). So a repo id that leftreposby any other path — a partial/interrupted delete, a repo-id re-key/migration (renameWorktreeId), or a crash between thereposfilter and the save — is never routed through prune again. fix: prune workspace session state when a project is removed (#9024) #9025's added session-owner cleanup never runs for such an id.gcStaleWorktreeMetadeliberately keeps the entry. The only automatic worktreeMeta cleanup skips an unowned key when the meta carries a non-localhostId, and — critically — whenexistsSync(worktreePath)is true. For a duplicate that shares a live repo's path,existsSyncis always true (the surviving repo occupies that path), so the orphan is never collected. It is then restored verbatim on every load (the load path applies no repo-membership filter toworktreeMeta).The visible duplicate comes from session state, which prune never touched:
hydrateHeadlessMobileSessionTabsFromWorkspaceSessioniteratesworkspaceSession.tabsByWorktreewith no repo gate, so a leftover${repoId}::${path}owner key re-creates a live workspace on boot — with nosession-createdevent. That is the second card.Fix
Add
gcOrphanedRepoState, a load-time sweep (runs right aftergcStaleWorktreeMeta) that enforces the missing invariant: worktree and session state must not outlive its owning repo/project id. For everyworktreeMeta/worktreeLineageById/workspaceLineageByChildKeykey and everyworkspaceSession(+workspaceSessionsByHostId) owner key whose parsed repo id is absent from bothreposandprojects, it removes the entry — reusing the session-owner cleanup so the sweep and the delete path share one implementation. UnlikegcStaleWorktreeMetait does not apply the host/existsSync/grace guards, because a truly ownerless key can never be legitimately displayed (enumeration is repo-driven) regardless of host or path existence.Safety guard: the sweep is skipped when there are zero live owners, so an anomalous empty-
reposload can never wipe all worktree/session state.This PR also refactors
removeWorkspaceSessionOwnerinto a reusableremoveWorkspaceSessionOwnerInPlace/removeWorkspaceSessionOwnerspair (and now also clearsremoteSessionIdsByTabIdfor removed tabs), so the single-owner delete path and the multi-owner sweep share one cleanup routine.Screenshots
No visual change. The change is entirely in the main-process persistence layer (
src/main/persistence.ts); no renderer UI is touched. The user-observable effect is behavioral: a phantom duplicate project card that previously reappeared after every restart is now removed on load.Testing
pnpm lintpnpm typecheckpnpm testpnpm buildNew
persistence.test.tscoverage (author-described):worktreeMetasharing a live repo's path is swept (the casegcStaleWorktreeMetakeeps becauseexistsSyncis true), as is one carrying a remotehostId;workspaceSessionowner keys are swept across the legacy blob and a host partition (tabs, layouts,lastVisitedAtByWorktreeId,activeWorktreeId,activeWorktreeIdsOnShutdown,remoteSessionIdsByTabId,openFilesByWorktree), leaving the live repo's session intact;reposis empty;Existing
gcStaleWorktreeMetatests are unaffected (a repo still present on any host stays "owned" and is never swept). Note:pnpmchecks were not run in this environment and the boxes above are left unchecked accordingly.AI Review Report
Reviewed the full diff. It is confined to
src/main/persistence.ts(+149/-8) and its test file (+131/-8).Correctness / edge cases examined:
ownerIdOfreturnsnullfor folder-scoped keys (correctly excluding them from the repo-membership check) and slices the id before the first::. Keys without a::separator yieldnulland are treated as non-orphan (kept), which is conservative and safe.liveOwnerIds.size === 0is the key safety property — it prevents a corrupt/empty-reposload from deleting all worktree and session state. Covered by a dedicated test.worktreeLineageById(checks child id andparentWorktreeId) andworkspaceLineageByChildKey(checks parsed child and parent worktree scopes) are handled; a lineage-only orphan with no meta/session twin is exercised by a test that also asserts the change is persisted.remoteSessionIdsByTabIdcleanup closes a real leak (tab-scoped remote session ids previously outlived removed tabs).activeRepoIdreset. Reset tonullwhen the active repo id is not a live owner, per session partition — consistent with the sweep's intent.WORKSPACE_SESSION_OWNER_RECORD_KEYSstaying in sync with theWorkspaceSessionStateshape; thesatisfies readonly (keyof WorkspaceSessionState)[]annotation gives compile-time protection against typos, though a newly-added owner-keyed record would still need to be appended manually.Cross-platform (macOS / Linux / Windows): checked. No keyboard shortcuts, shortcut labels, shell invocation, or Electron main/renderer boundary behavior are touched. Path handling is limited to string parsing of the existing
${repoId}::${path}key format (splitting on::), not filesystem path construction, so it is platform-agnostic; test fixtures use Linux-style paths but exercise pure string logic. No platform-specific code paths were introduced or modified.Security Audit
Reviewed for input handling, command execution, path handling, auth, secrets, dependency, and IPC changes.
existsSync/fscalls; the sweep intentionally omits theexistsSyncguard). No path traversal or injection surface.reposandprojects.No security issues found.
Notes
workspaceSessionsByHostIdpartitions and intentionally sweeps orphan keys regardless ofhostId(including remote), since an ownerless key is never legitimately enumerable.hydrateHeadlessMobileSessionTabsFromWorkspaceSessionon repo membership as defense-in-depth. The load-time sweep already removes the orphan before that runtime consumer sees it, so it is not required for the fix.🤖 Generated with Claude Code
ELI5
A deleted project could leave a phantom duplicate workspace that came back after every restart. On load, Orca reclaims orphaned worktree and session rows so ghosts do not reappear.