Skip to content

fix: reclaim orphaned worktree/session state on load (duplicate workspace that returns after restart) - #9200

Closed
PannenetsF wants to merge 8 commits into
stablyai:mainfrom
PannenetsF:fix/gc-orphaned-repo-state-on-load
Closed

PannenetsF wants to merge 8 commits into
stablyai:mainfrom
PannenetsF:fix/gc-orphaned-repo-state-on-load

Conversation

@PannenetsF

@PannenetsF PannenetsF commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

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 worktreeMeta by hand. This is the already-orphaned sibling of #9024: the repo id is gone from repos, but its worktreeMeta row and workspaceSession owner 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 from repos, because the function it patches is unreachable in that state.

Root cause

Two gaps combine so an ownerless entry becomes permanently unreclaimable:

  1. pruneWorktreeStateForRepo is unreachable once the repo leaves repos. Its only callers are removeProject and removeProjectForHost (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 left repos by any other path — a partial/interrupted delete, a repo-id re-key/migration (renameWorktreeId), or a crash between the repos filter 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.

  2. gcStaleWorktreeMeta deliberately keeps the entry. The only automatic worktreeMeta cleanup skips an unowned key when the meta carries a non-local hostId, and — critically — when existsSync(worktreePath) is true. For a duplicate that shares a live repo's path, existsSync is 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 to worktreeMeta).

The visible duplicate comes from session state, which prune never touched: hydrateHeadlessMobileSessionTabsFromWorkspaceSession iterates workspaceSession.tabsByWorktree with no repo gate, so a leftover ${repoId}::${path} owner key re-creates a live workspace on boot — with no session-created event. That is the second card.

Fix

Add gcOrphanedRepoState, a load-time sweep (runs right after gcStaleWorktreeMeta) that enforces the missing invariant: worktree and session state must not outlive its owning repo/project id. For every worktreeMeta / worktreeLineageById / workspaceLineageByChildKey key and every workspaceSession (+ workspaceSessionsByHostId) owner key whose parsed repo id is absent from both repos and projects, it removes the entry — reusing the session-owner cleanup so the sweep and the delete path share one implementation. Unlike gcStaleWorktreeMeta it 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-repos load can never wipe all worktree/session state.

This PR also refactors removeWorkspaceSessionOwner into a reusable removeWorkspaceSessionOwnerInPlace / removeWorkspaceSessionOwners pair (and now also clears remoteSessionIdsByTabId for 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 lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests for my change (or explained below why not)

New persistence.test.ts coverage (author-described):

  • orphan worktreeMeta sharing a live repo's path is swept (the case gcStaleWorktreeMeta keeps because existsSync is true), as is one carrying a remote hostId;
  • workspaceSession owner 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;
  • the empty-owner gate keeps everything when repos is empty;
  • a lineage-only orphan is swept and the load is marked for persistence.

Existing gcStaleWorktreeMeta tests are unaffected (a repo still present on any host stays "owned" and is never swept). Note: pnpm checks 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:

  • Owner-id parsing. ownerIdOf returns null for folder-scoped keys (correctly excluding them from the repo-membership check) and slices the id before the first ::. Keys without a :: separator yield null and are treated as non-orphan (kept), which is conservative and safe.
  • Empty-owner guard. The early return when liveOwnerIds.size === 0 is the key safety property — it prevents a corrupt/empty-repos load from deleting all worktree and session state. Covered by a dedicated test.
  • Lineage sweeps. Both worktreeLineageById (checks child id and parentWorktreeId) and workspaceLineageByChildKey (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.
  • Session cleanup reuse. Refactoring single-owner removal into an in-place helper reused by the batch sweep reduces divergence risk. The added remoteSessionIdsByTabId cleanup closes a real leak (tab-scoped remote session ids previously outlived removed tabs).
  • activeRepoId reset. Reset to null when the active repo id is not a live owner, per session partition — consistent with the sweep's intent.
  • Residual consideration: the sweep depends on WORKSPACE_SESSION_OWNER_RECORD_KEYS staying in sync with the WorkspaceSessionState shape; the satisfies 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.

  • No command execution, no shell, no network, no new dependencies.
  • No IPC surface change — the sweep runs internally during store load; no new handlers or renderer-exposed APIs.
  • Path handling is pure in-memory string parsing of persisted keys, not filesystem access (no new existsSync/fs calls; the sweep intentionally omits the existsSync guard). No path traversal or injection surface.
  • Data-loss risk is the only material concern and is directly mitigated by the empty-owner guard, which prevents wiping all state on an anomalous load; a targeted test asserts this. The sweep only deletes state whose owning repo/project id is provably absent from both repos and projects.
  • No secrets, credentials, or auth logic touched.

No security issues found.

Notes

  • Persistence-layer only; effect is observed on next app load (orphaned state is swept and the load is flagged for save).
  • SSH / remote hosts are covered: the sweep iterates workspaceSessionsByHostId partitions and intentionally sweeps orphan keys regardless of hostId (including remote), since an ownerless key is never legitimately enumerable.
  • Optional follow-up (not in this PR): gate hydrateHeadlessMobileSessionTabsFromWorkspaceSession on 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.

@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The 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 repo1 and ssh-repo.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the load-time reclamation of orphaned worktree and session state and the restart duplicate symptom.
Description check ✅ Passed The description explains the problem, cause, fix, safety guard, testing, review, security, and lack of visual change, but it omits some template headings and a Fixes # link.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b6aefde1-26fd-4055-95e5-ed556b7f43d1

📥 Commits

Reviewing files that changed from the base of the PR and between 1c54171 and e8577c7.

📒 Files selected for processing (2)
  • src/main/persistence.test.ts
  • src/main/persistence.ts

Comment thread src/main/persistence.ts Resolved
@brennanb2025

Copy link
Copy Markdown
Contributor

Taking a look!

PannenetsF and others added 3 commits July 20, 2026 18:24
`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]>
@brennanb2025
brennanb2025 force-pushed the fix/gc-orphaned-repo-state-on-load branch from 15aa6d5 to 29772a0 Compare July 21, 2026 01:32
@brennanb2025

Copy link
Copy Markdown
Contributor

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.

nwparker pushed a commit to PannenetsF/orca that referenced this pull request Jul 23, 2026
…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]>
nwparker pushed a commit that referenced this pull request Jul 24, 2026
…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]>
@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
# Conflicts:
#	src/main/persistence.ts
@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 346e59c and 8922382.

📒 Files selected for processing (5)
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/renderer/src/components/right-sidebar/FileExplorer.tsx
  • src/renderer/src/components/right-sidebar/file-explorer-inline-input-outside-click.test.tsx
  • src/renderer/src/components/sidebar/worktree-keyboard-cycle.test.ts

Comment thread src/main/persistence.ts Resolved
Comment thread src/main/persistence.ts Resolved
PannenetsF and others added 2 commits August 12, 2026 23:52
…(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
@coderabbitai

coderabbitai Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d3a2bf3 and 605d3fd.

📒 Files selected for processing (2)
  • src/main/persistence.test.ts
  • src/main/persistence.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/persistence.ts

Comment thread src/main/persistence.test.ts Outdated
Comment on lines +6418 to +6433
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()
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

@PannenetsF
PannenetsF force-pushed the fix/gc-orphaned-repo-state-on-load branch from 605d3fd to a45441a Compare August 18, 2026 16:53
@PannenetsF

Copy link
Copy Markdown
Contributor Author

@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
@PannenetsF
PannenetsF force-pushed the fix/gc-orphaned-repo-state-on-load branch from a45441a to a4d707d Compare August 25, 2026 04:49
# Conflicts:
#	src/main/persistence/tracking-repos/worktree-metadata-normalization.ts
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
@nwparker

Copy link
Copy Markdown
Contributor

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, collectDeregisteredRepoIds gathers repo ids that own worktreeMeta, lineage, mobile selections or workspace-session owner keys (tabs, layouts, active/shutdown ids, across the legacy blob and host partitions) but are no longer in repos, and sweepDeregisteredRepoResidue prunes them without an existsSync check. That means a phantom row sharing a live repo's path no longer survives a restart. Paired-runtime-host rows are deliberately kept, since their catalog lives on the remote host. If you still see the duplicate card coming back on the latest build, please comment or reopen with details.

@nwparker nwparker closed this Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants