Skip to content

fix: prune workspace session state when a project is removed (#9024) - #9025

Merged
nwparker merged 4 commits into
stablyai:mainfrom
PannenetsF:fix/prune-workspace-session-on-project-delete
Jul 24, 2026
Merged

nwparker merged 4 commits into
stablyai:mainfrom
PannenetsF:fix/prune-workspace-session-on-project-delete

Conversation

@PannenetsF

@PannenetsF PannenetsF commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Deleting a project no longer leaves an orphaned "unknown" workspace that reappears in the sidebar after every restart (#9024).

ELI5: When you removed a project, the app forgot to fully forget it — a ghost copy kept coming back each time you reopened the app. Now it's cleaned up completely.

Root cause & fix: removeProject → pruneWorktreeStateForRepo only cleaned worktreeMeta and the lineage maps, but never removed the deleted repo's worktrees from the workspace session state (the legacy workspaceSession blob and the per-host workspaceSessionsByHostId partitions). Because lastVisitedAtByWorktreeId still referenced the gone worktrees, the next launch treated them as recently-active and re-materialized worktreeMeta, rendering them as an orphaned "unknown" workspace.

The fix collects the repo's owner keys (${repoId}::${path}) before the worktreeMeta delete loop — from worktreeMeta, the legacy session, and every host partition — so host classification can still read meta.hostId (including orphan keys present only in the session maps). It then runs the existing session-owner cleanup against the legacy/local session and every matching host partition, reusing the path already used by removeFolderWorkspace and deleteProjectGroup. Host gating is preserved: a host-scoped removal (hostId != null) only prunes that host's partition; a full removal (hostId === null) clears every host, so a shared repo id/path on a surviving host keeps its session.

This session also added a behavior-preserving refactor: removeWorkspaceSessionOwner is split into deleteOwnerKeyedSessionFields (O(1) owner-keyed deletes) and deleteScannedSessionFieldsForOwners (single pass over the pane-key maps and the shutdown list), plus a new batch removeWorkspaceSessionOwners. This drops the per-owner structuredClone (previously O(worktrees × hosts)) to one clone + one scan per session partition.

Original fix by @PannenetsF; validated, rebased onto latest main during 2026-07-23 bug-bash triage, and optimized as described above.

Screenshots

No visual change. This PR only touches main-process persistence logic (src/main/persistence.ts and its tests); no renderer UI is affected. The user-observable behavior change is the absence of the orphaned "unknown" sidebar workspace after restart, which cannot be captured as a static screenshot here.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests for the change, or explained why not.

Author-reported (I cannot run pnpm in this environment, so these reflect the original body's claims, and the commands run were scoped to the changed file rather than the full pnpm scripts):

  • Lint: oxlint src/main/persistence.ts exit 0, no max-lines disable added.
  • Types: tsc --noEmit -p config/tsconfig.node.json exit 0.
  • Tests: npx vitest run --config config/vitest.config.ts src/main/persistence.test.ts → 407 passed, including the 2 removeProject session-prune regression tests and the 3 host-scoped removeProjectForHost prune tests. The 2 regression tests were confirmed to fail on main (stale keys survive) and pass with the fix.
  • pnpm build was not reported as run.

AI Review Report

Reviewed the full diff for correctness and edge cases:

  • Owner-key collection ordering is correct: keys are gathered from worktreeMeta, the legacy session, and all host partitions before the worktreeMeta delete loop, so orphan keys that exist only in session maps (and would otherwise lose their meta.hostId classification) are still captured. This is the crux of the fix.
  • Host gating is sound. pruneLegacyLocalSession fires for hostId === null or the local host id; pruneAllHostPartitions only for hostId === null; otherwise partitions are skipped unless partitionHostId === hostId. This prevents wiping a surviving host's session for a shared repo id/path — directly covered by the three new removeProjectForHost tests.
  • Refactor is behavior-preserving. The split of removeWorkspaceSessionOwner threads removedTabIds through the O(1) deletes into the scan phase, matching the prior single-owner behavior; the isRemovedOwner predicate generalizes the old worktreeId === ownerKey check to set membership for the batch path. The terminalPtyIncarnationsByPaneKey lastIndexOf(':') / separator < 1 guard is carried over unchanged.
  • Edge cases: empty owner-key set and undefined sessions short-circuit in removeWorkspaceSessionOwners (returns the original reference), preserving prior semantics. advanceTerminalTopologyRevision is only forwarded on the single-owner path, matching pre-existing behavior (the batch project-removal path did not advance it before, either).
  • Cross-platform (macOS/Linux/Windows): confirmed checked. No platform-dependent code is touched — no keyboard shortcuts, shortcut labels, filesystem path construction, shell invocation, or Electron main/renderer boundary changes. Owner keys are opaque ${repoId}::${path} strings compared by equality/prefix; no path separator assumptions are introduced. Nothing here diverges by OS.

No fabricated results; the above is based solely on the diff.

Security Audit

No security-relevant surface is changed. The diff is pure in-memory state pruning:

  • No new input handling, deserialization of untrusted data, or parsing.
  • No command/shell execution.
  • No filesystem path resolution or traversal (owner keys are compared as opaque strings, never resolved to disk paths).
  • No auth, secrets, credentials, or network calls.
  • No dependency changes.
  • No IPC handlers added or modified.

The change only removes stale entries from existing persisted session structures, which is a strict cleanup with no widening of trust boundaries.

Notes

  • No platform-specific behavior introduced; SSH/remote hosts are explicitly handled via the per-host partition gating (workspaceSessionsByHostId).
  • Follow-up: pnpm build and the full pnpm lint / pnpm typecheck / pnpm test suites should be confirmed green in CI, since the author's local runs were scoped to the changed file.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Project removal now collects affected worktree owner keys before deleting worktree metadata. It prunes matching entries from global workspace session state and host-scoped workspace session partitions. Tests cover global and host-scoped cleanup, including shared repository identities across local and multiple remote hosts while preserving unrelated entries.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy #9024 by clearing workspaceSession and workspaceSessionsByHostId state with host-scoped cleanup preserved.
Out of Scope Changes check ✅ Passed The changes stay focused on project-removal persistence cleanup and regression tests, with no unrelated scope introduced.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly matches the main change: pruning workspace session state when a project is removed.
Description check ✅ Passed The description follows the required template and includes summary, screenshots, testing, AI review, security audit, and notes.

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.

@e-jung

e-jung commented Jul 16, 2026

Copy link
Copy Markdown

Thanks for tackling #9024. I tested the current head and confirmed that the full removeProject path fixes the orphaned-workspace problem: the new tests pass with this change and fail against the parent commit.

I found one cross-host regression in the host-scoped removeProjectForHost path. Owner keys do not include the host ID, but the new cleanup applies each matching key to the local session and every workspaceSessionsByHostId partition.

Reproduction: register the same repo ID and path on local and ssh:ssh-a, with local lastVisitedAt=111 and SSH lastVisitedAt=222. After removeProjectForHost("shared", "ssh:ssh-a"), the surviving local value is unexpectedly removed instead of remaining 111. This can also discard the surviving host's tabs, sleeping-agent state, and active-worktree pointer.

Could the cleanup be scoped to the selected host when hostId is non-null, while retaining the all-partitions cleanup for full removeProject? A regression test using the same owner key on two hosts should cover the distinction.

Otherwise, the fix looks focused and the full-removal behavior appears correct.

@PannenetsF

Copy link
Copy Markdown
Contributor Author

@e-jung Thanks for the careful review and the concrete repro — you're right, that was a real cross-host bug.

I pushed 53e7f18 to scope the host-partition cleanup to the removed host:

  • When hostId is non-null, cleanup now only touches that host's workspaceSessionsByHostId partition and skips the others, so a surviving host sharing the same repo id + path keeps its lastVisitedAt, tabs, sleeping-agent state, and active-worktree pointer.
  • The legacy/local session blob is only pruned when hostId === null || hostId === LOCAL_EXECUTION_HOST_ID.
  • Full removeProject (hostId === null) still clears every partition, as before.

I also added the two regression tests you suggested, both using the same owner key on two hosts:

  • removeProjectForHost keeps the surviving host session for a shared repo id + path — removing ssh:ssh-a keeps local 111.
  • removeProjectForHost on the local host keeps a surviving SSH host session — removing local keeps SSH 222.

Would you mind taking another look when you have a moment? Thanks again.

@e-jung e-jung left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-reviewed commit 53e7f18. The host-scoped cleanup now preserves surviving local, SSH, and paired-remote session partitions while full remove still clears every partition.

I verified both new regression tests fail against the previously reviewed head 4b05fa0 and pass on the current head. The complete persistence suite passes 375 of 375 tests, the touched files pass node TypeScript checking and oxlint, and an additional two-SSH-host reproduction also passes.

The earlier cross-host blocker is resolved. The remaining observations are non-blocking: worktreeMeta still has a pre-existing identical-path cross-host ambiguity, and a third-surviving-host fixture could be useful future coverage. Approving this revision. Thanks for the careful fix.

@PannenetsF

Copy link
Copy Markdown
Contributor Author

Sure. I will add a /3rd host/ test case to cover it :)

@PannenetsF

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @e-jung 🙏 This is approved and green (the host-scoped cleanup regression you caught is resolved, and the persistence suite passes). I don't have merge access on the upstream — could you (or another maintainer) squash-merge this when you have a moment? Happy to rebase if it's gone stale.

@PannenetsF

Copy link
Copy Markdown
Contributor Author

Hi @e-jung — main moved and this picked up a conflict, so I merged latest main in and resolved it. The conflict was only in the test file: main and this branch each appended a removeProject test at the same spot (session-state/per-host pruning vs. the new topology-authority case) — I kept all three, they're independent. persistence.ts merged cleanly. Full persistence suite passes (400/400) and node typecheck is clean. Since the update likely dismissed your earlier approval, could you re-approve and squash-merge when you have a moment? Thanks again for the careful review!

hiBDFY11Qsa2a and others added 4 commits July 23, 2026 02:46
removeProject → pruneWorktreeStateForRepo cleared worktreeMeta, lineage,
and workspace lineage, but left the removed repo's worktrees behind in
workspaceSession (lastVisitedAtByWorktreeId, sleepingAgentSessionsByPaneKey,
tab state, …) and in every workspaceSessionsByHostId partition.

Those dangling references caused the runtime to treat the deleted repo's
worktrees as recently-active on the next launch and re-materialize their
worktreeMeta. With no owning project left, the UI rendered them as an
orphaned "unknown" workspace that returned after every restart.

Reuse the existing removeWorkspaceSessionOwner cleanup (already used by
removeFolderWorkspace and deleteProjectGroup) against the legacy session
blob and each per-host partition, collecting owner keys before the
worktreeMeta delete loop so host classification still works.

Fixes stablyai#9024

Co-Authored-By: Claude Fable 5 <[email protected]>
The workspace-session cleanup applied every collected owner key to the legacy
(local) session blob AND every workspaceSessionsByHostId partition. Owner keys
are `${repoId}::${path}` and carry no host, so a host-scoped removal
(removeProjectForHost) of one host wrongly wiped a surviving host's session for
a shared repo id/path — discarding its lastVisitedAt, tabs, sleeping-agent
state, and active-worktree pointer.

Scope the session prune to the removed host: prune the legacy blob only when the
target host is local (or on a full removeProject where hostId is null), and
prune only the matching workspaceSessionsByHostId partition for a non-local
host; a full removal still clears every partition. Collect session owner keys by
`${repoId}::` prefix (not belongsToHost, which is worktreeMeta-host-classified)
so a partition-only key is still prunable.

Adds regression tests for a shared repo id + path across local and an SSH host,
covering removeProjectForHost on the SSH host (local session survives) and on
the local host (SSH session survives).

Addresses review feedback on stablyai#9024.

Co-Authored-By: Claude Fable 5 <[email protected]>
Add a regression case where a shared repo id + path exists on local and two
SSH hosts. Removing one non-local host must prune only that host's session
partition, leaving both the legacy/local session and the other surviving SSH
host's partition intact. Locks in that the host-scoped cleanup never touches a
non-targeted third partition (per review feedback on stablyai#9024).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Project removal collected every owner key to prune, then called
removeWorkspaceSessionOwner once per owner AND per host partition. Each
call structuredClones and scans the entire session, so removal was
O(worktrees x hosts x session size) in full-session clones on the main
thread.

Add removeWorkspaceSessionOwners(session, ownerKeys) which clones once
and scans each collection once for the whole set, and route
pruneWorktreeStateForRepo through it. The per-owner O(1) field deletes
and the single-scan pane-key passes are factored into shared functions
so removeWorkspaceSessionOwner keeps identical behavior for its other
callers. No behavior change.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the fix/prune-workspace-session-on-project-delete branch from c0adefa to 1e8fdd4 Compare July 23, 2026 11:48
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
nwparker merged commit 253ccd2 into stablyai:main Jul 24, 2026
@nwparker

Copy link
Copy Markdown
Contributor

Thanks so much for this, @PannenetsF — prune workspace session state when a project is removed (#9024). Verified (fail-on-main/pass-on-branch), rebased on latest main, reviewed, and merged. Really appreciate it! 🙏

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]>
PannenetsF added a commit to PannenetsF/orca that referenced this pull request Aug 12, 2026
`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]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…i#9024) (stablyai#9025)

* fix: prune workspace session state when a project is removed

removeProject → pruneWorktreeStateForRepo cleared worktreeMeta, lineage,
and workspace lineage, but left the removed repo's worktrees behind in
workspaceSession (lastVisitedAtByWorktreeId, sleepingAgentSessionsByPaneKey,
tab state, …) and in every workspaceSessionsByHostId partition.

Those dangling references caused the runtime to treat the deleted repo's
worktrees as recently-active on the next launch and re-materialize their
worktreeMeta. With no owning project left, the UI rendered them as an
orphaned "unknown" workspace that returned after every restart.

Reuse the existing removeWorkspaceSessionOwner cleanup (already used by
removeFolderWorkspace and deleteProjectGroup) against the legacy session
blob and each per-host partition, collecting owner keys before the
worktreeMeta delete loop so host classification still works.

Fixes stablyai#9024

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: scope session cleanup to the removed host in removeProjectForHost

The workspace-session cleanup applied every collected owner key to the legacy
(local) session blob AND every workspaceSessionsByHostId partition. Owner keys
are `${repoId}::${path}` and carry no host, so a host-scoped removal
(removeProjectForHost) of one host wrongly wiped a surviving host's session for
a shared repo id/path — discarding its lastVisitedAt, tabs, sleeping-agent
state, and active-worktree pointer.

Scope the session prune to the removed host: prune the legacy blob only when the
target host is local (or on a full removeProject where hostId is null), and
prune only the matching workspaceSessionsByHostId partition for a non-local
host; a full removal still clears every partition. Collect session owner keys by
`${repoId}::` prefix (not belongsToHost, which is worktreeMeta-host-classified)
so a partition-only key is still prunable.

Adds regression tests for a shared repo id + path across local and an SSH host,
covering removeProjectForHost on the SSH host (local session survives) and on
the local host (SSH session survives).

Addresses review feedback on stablyai#9024.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test: cover third surviving host in removeProjectForHost session prune

Add a regression case where a shared repo id + path exists on local and two
SSH hosts. Removing one non-local host must prune only that host's session
partition, leaving both the legacy/local session and the other surviving SSH
host's partition intact. Locks in that the host-scoped cleanup never touches a
non-targeted third partition (per review feedback on stablyai#9024).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf: prune workspace session in a single clone+scan per partition

Project removal collected every owner key to prune, then called
removeWorkspaceSessionOwner once per owner AND per host partition. Each
call structuredClones and scans the entire session, so removal was
O(worktrees x hosts x session size) in full-session clones on the main
thread.

Add removeWorkspaceSessionOwners(session, ownerKeys) which clones once
and scans each collection once for the whole set, and route
pruneWorktreeStateForRepo through it. The per-owner O(1) field deletes
and the single-scan pane-key passes are factored into shared functions
so removeWorkspaceSessionOwner keeps identical behavior for its other
callers. No behavior change.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: PannenetsF <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Neil <[email protected]>
Co-authored-by: Orca <[email protected]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants