Skip to content

fix(terminal): removing a workspace prunes that workspace's close records - #23683

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/close-record-prune
Sep 29, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/close-record-prune

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #22955.

ELI5

When you close a terminal tab, Orca keeps a small note that says "this tab was closed". Until now those notes only disappeared after 30 days, or when a host collected more than 500 of them. Removing a worktree, a folder workspace or a whole project left its notes behind. Now removing a workspace takes its notes with it, in the same save that removes the workspace.

What Changed

Before

  • A removed workspace's close records stayed on disk for up to 30 days.
  • Those records filled that host's 500-record cap. A burst of later closes could evict a record for a live workspace. That workspace then read as "never set up" and got a fresh terminal at the next launch, even though you had emptied it on purpose.
  • Worktree ids come from the path. If you removed a worktree and made a new one at the same path, the new one started with the old records attached.

After

  • Removing a workspace's saved state also removes the records that name that workspace. This covers:
    • removing a worktree (git or provider removal, orphan and stale-registration cleanup, and the CLI's orca worktree rm);
    • your explicit Forget;
    • an SSH or runtime host whose git scan succeeds and no longer lists a worktree;
    • removing a folder workspace, or a project group with folder workspaces;
    • removing a whole project, and the startup sweep of a project that is no longer registered.
  • This happens in the same in-memory write and the same save that removes the workspace's rows, in the local partition and in the owning SSH or runtime host's partition.
  • If the same repo and path are registered on another host too, that host's records are kept, just like its rows.
  • An SSH host that does not answer removes nothing. The rule that loss of contact is never evidence a workspace is gone still holds, because an unreachable host never reaches this code. The only host-driven removal runs after the host's own git scan succeeds and reports the worktree missing. A failed, partial or fallback listing never triggers it (see Testing).

Mechanism

  • removeWorkspaceSessionOwner and its batch form now also drop the close records that name the removed owner, in the same scan that already drops the other records naming a worktree (sleeping agents, surface tombstones). Every removal path already goes through these two functions (directly, through the every-partition form, or through Store.removeWorktreeMeta), so no caller changes.
  • The existing rule that skips a partition another host's same-id worktree may still use applies unchanged.
  • Project removal now also collects worktree ids from close records. Before, a worktree whose only remaining trace was a record was missed.
  • The startup sweep for projects that are no longer registered now also looks at close records. A project moved to another profile otherwise leaves its records in the source profile.

Why

  • One place, no flag. A close record exists only to answer for its workspace, so it goes whenever the workspace's rows go. Putting the prune inside the function that removes the rows means no removal path can miss it, and no caller has to know close records exist.
  • Same write, not a separate sweep. The records die in the same write that removes the workspace, so no state exists in which the rows are gone but the records remain, and no second journal is needed.
  • Alternatives considered:
    • A removal "cause" that each caller passes, with the store deciding per cause. Rejected after review: every caller of the removal functions is already an explicit removal or a successful scan, so the cause decided nothing and only threaded a parameter through a dozen files.
    • A background sweep that prunes records whose worktree no longer appears anywhere. Rejected: that is exactly what an unreachable SSH host looks like.

Differences from the common pattern

  • The common pattern stores the close fact on the terminal's own row and deletes it with that row when its thread, environment or host is deleted. This PR does the same at the workspace level: the records go in the same write that removes the workspace's rows.
  • The common pattern's other form clears a thread's closed-terminal state explicitly after the delete succeeds. Here the clear is part of the delete itself, so there is no window where one has happened without the other.
  • Moving a project between profiles has no per-owner removal, so the source profile's records wait for that profile's next startup sweep (noted in profile-project-session-field-disposition.ts).

Linked Issue

No public issue. Follow-up to #22955, requested during its review.

Visual Proof

Live Electron run on a second Mac (isolated profile and home), at 44a755a against main 3c1af16. The close records were read from the saved profile database with sqlite after each step; the screenshots show the app at the same points.

1. Delete a worktree, then recreate it at the same path. Two worktrees, prune-a and prune-keep, each with one closed terminal tab, so each has one close record.

  • On main, after deleting prune-a both records are still saved, including the one naming the deleted worktree. Recreating prune-a gives it the same id, so the new worktree inherits the old record.
  • With this PR, after deleting prune-a only prune-keep's record is saved. The recreated prune-a has no record, opens a working terminal, and after a restart still has none while prune-keep's record survives.

main, after deleting prune-a (its record is still saved):

main: sidebar after deleting prune-a

This PR, before and after deleting prune-a:

PR: sidebar before deleting prune-a

PR: sidebar after deleting prune-a

This PR, prune-a recreated at the same path, with a working terminal, and after a restart:

PR: recreated prune-a running echo OK

PR: after restart

2. Remove a folder workspace. With a closed tab in a folder workspace, removing the workspace drops its record and keeps prune-keep's.

PR: sidebar before removing the folder workspace

PR: sidebar after removing the folder workspace

3. Normal close still works. A tab closed in prune-keep stays closed after a restart, with a reason: "user" record, and new terminals run normally.

PR: closed tab stays closed after restart

Not exercised live: project removal, Forget, and SSH partitions (covered by the unit tests above). The run also saw two things that predate this PR: removing a folder workspace has no confirmation and leaves its empty project group in the sidebar.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New src/main/worktree-removal-close-records.test.ts, on the SQLite test store:

  • A local removal drops only that worktree's records.
  • An SSH removal drops them from the SSH host's partition.
  • A same-id worktree registered locally and on an SSH host keeps its local record when the SSH copy is removed.
  • Folder workspace removal drops them from every partition.
  • Project removal drops that project's records, including a worktree known only by its records, and keeps another project's.
  • The removed worktree's cap slots are freed, so later closes no longer evict a live worktree's record.

Also new:

  • persistence-deregistered-repo-residue.test.ts: a close record that is an unregistered project's only leftover is swept at startup and does not come back.
  • worktrees-runtime-host-metadata-retirement.test.ts: a runtime host that does not answer triggers no removal. Existing tests in that file and in worktrees-fetch-persisted-metadata-fallback.test.ts already cover a failed scan, the SSH fallback listing and a legacy listing.

Each was checked by deleting the code it protects:

  • Removing the close-record scan turns all 6 removal tests red.
  • Removing project removal's collection of worktrees from records turns the project test red.
  • Removing the startup sweep's collection from records turns the sweep test red.
  • Making a failed runtime listing come back as an empty successful git scan turns the unreachable-host test red.

Also run: typecheck (node), the removal, sweep, host-partition, partition-fencing and SSH scan-forget suites (66 tests), the runtime-host retirement suite, the changed-code quality gate and oxlint.

AI Disclosure

Written with Claude.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • SSH: records live in the owning host's partition, and a remote removal prunes them there. An unreachable host never reaches the removal code.
  • Folder workspaces: covered, including project group deletion.
  • Mixed versions: records never cross the paired wire. An older build reading the data just sees fewer records.
  • Performance: one scan of one partition's records (at most 500) per removal, in a write that already happens.
  • Mobile: no mobile-facing surface changes.
  • Not changed here: the renderer keeps its own in-memory copy of close records, which is never saved and is replaced from the app's main process at the next reload. A removal does not clear that copy, so until the next reload, a new workspace at the same path whose terminal list is emptied by something other than a close could read as "emptied on purpose". This predates this PR and belongs with the planned shared "is this tab closed" check.

Author X handle: @BrennanKB5

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

… without one

Both branches now made the same call; the split only existed to keep the old two-argument arity.
…nd the store derives what goes with it

Replaces the pruneCloseRecords boolean with a required cause: removed, forgotten or unlisted.
Only the scan path is unlisted, and it keeps close records; every other cause drops them.
Also pins that removing one host's copy of a same-id worktree leaves the other host's records.
…t the workspace is gone

The runtime removal wrapper hard-coded 'removed' for every caller, including the orphan path that
leaves the directory and its git registration in place. Callers now pass their cause, as the
desktop wrapper's callers already do, and the orphan path says 'forgotten' like the desktop Forget
it mirrors. Pruning is unchanged: both causes drop the close records.
…ne typed helper

Adding the cause argument touched seven calls that each cast their fixture store; one helper now
carries the single justified cast.
…its close records

Every caller of the owner-removal chokepoint is an explicit removal, and the only host-driven one runs after a successful git scan, so the removal cause threaded through the removal paths decided nothing. Drop it, prune unconditionally, and seed the deregistered-repo sweep from close records so a project moved to another profile does not leave them behind.
@brennanb2025 brennanb2025 changed the title fix(terminal): a confirmed workspace removal prunes that workspace's close records fix(terminal): removing a workspace prunes that workspace's close records Sep 28, 2026
…er worktree-named records

The standalone pruner and its shared helper only existed to be skipped for one removal cause; with the cause gone they are a second scan beside the one that already walks every record naming a worktree.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready for review

Head 44a755a2b66. The PR is ready for review; it has not been merged.

What changed during review

  • The first version passed a removal "cause" through every removal path so that one host-driven path would keep the records. An architecture review found that path only runs after the host's own git scan succeeds, so the cause decided nothing. It was removed, and the prune now runs unconditionally in the scan that already drops the other records naming a worktree. The PR went from 46 files to 8.
  • The startup sweep for projects that are no longer registered now also takes their close records.

Reviews

  • Two confirming review passes; the last one found nothing to change.
  • It checked independently that no path removes a workspace's saved state after a failed, partial, fallback or unanswered scan. An SSH host that does not answer still removes nothing.
  • Each new test was confirmed to go red when the code it guards is deleted.

Checks: node typecheck, the changed-code quality gate, oxlint and CI all pass.

Live run on a second Mac: passed.

  • On main, deleting a worktree keeps its close record, and recreating it at the same path inherits the record.
  • With this PR, the deleted worktree's record is gone and the other worktree's record stays. The recreated worktree has no record, opens a working terminal, and still has none after a restart.
  • Removing a folder workspace drops its record. A normally closed tab still stays closed after a restart.

main, after deleting prune-a (its record is still saved):

main: after deleting prune-a

This PR, prune-a recreated at the same path with a working terminal:

PR: recreated prune-a with a working terminal

Known and not changed here: the renderer's in-memory copy of close records is cleared only at the next reload. It predates this PR and belongs with the planned shared "is this tab closed" check. Project removal, Forget and SSH partitions were covered by unit tests, not the live run.

@brennanb2025
brennanb2025 marked this pull request as ready for review September 29, 2026 16:46
@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The change adds close-tab tombstones to workspace-owner pruning and deregistered-repo scanning. Tests cover removal across local and SSH session partitions, folder and project removal, and tombstone capacity. A separate renderer test checks that a rejected runtime-host scan leaves metadata and worktree rows unchanged. Comments describe tombstone removal during workspace-row cleanup.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 44a75

This change prunes terminal close records when a workspace is removed. No blocking risk was found. A small test-strictness improvement is suggested.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 44a75

The cleanup is scoped to workspace records and has evidence that it preserves records belonging to other workspaces and hosts. No new security exposure was established. Recovery after a failed save or an interrupted project move remains unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The supported deletion scope is workspace-session state in the selected local or execution-host partitions. The same-ID host test provides counterevidence to cross-host deletion in that path.

Trust Boundaries and Controls

  • observed — The examined remote-removal path awaits a host worktree listing before proceeding to cleanup; a rejected listing does not itself establish that a worktree was removed.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: removing a workspace also prunes its terminal close records.
Description check ✅ Passed The description is complete and directly addresses the template. It explains the user impact, mechanism, rationale, linked follow-up issue, visual proof, testing, AI disclosure, compatibility consider…
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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: Advanced

Run ID: cf7da067-6f3c-4f9d-a6a0-d5890e27a6dd

📥 Commits

Reviewing files that changed from the base of the PR and between fe7e13d and 44a755a.

📒 Files selected for processing (8)
  • src/main/orca-profiles/profile-project-session-field-disposition.ts
  • src/main/persistence-deregistered-repo-residue.test.ts
  • src/main/persistence/restoring-sessions/session-owner-removal.ts
  • src/main/persistence/tracking-repos/deregistered-repo-residue.ts
  • src/main/persistence/tracking-repos/repo-worktree-pruning.ts
  • src/main/worktree-removal-close-records.test.ts
  • src/renderer/src/store/slices/worktrees-runtime-host-metadata-retirement.test.ts
  • src/shared/closed-terminal-tab-tombstones.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +94 to +97
await store
.getState()
.fetchWorktrees(REPO_ID, { executionHostId: HOST_ID })
.catch(() => undefined)

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

Assert the handled scan failure instead of swallowing a rejection.

fetchWorktreesAttempt catches scan errors and returns false. This test also passes if fetchWorktrees unexpectedly rejects, provided the rows remain unchanged. Assert a false result so the test detects a regression in the fetch error contract.

Proposed change
-    await store
-      .getState()
-      .fetchWorktrees(REPO_ID, { executionHostId: HOST_ID })
-      .catch(() => undefined)
+    await expect(
+      store.getState().fetchWorktrees(REPO_ID, { executionHostId: HOST_ID })
+    ).resolves.toBe(false)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await store
.getState()
.fetchWorktrees(REPO_ID, { executionHostId: HOST_ID })
.catch(() => undefined)
await expect(
store.getState().fetchWorktrees(REPO_ID, { executionHostId: HOST_ID })
).resolves.toBe(false)

@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Cleans up terminal tab records when workspaces are removed.

The PR appears safe to merge based on the reviewed removal, partition, and session-persistence paths.

Summary

The PR removes terminal-close records with their workspace session state and makes project removal and the startup deregistration sweep discover worktrees known only by those records.

  • Adds coverage for local, SSH, folder, and project removal, plus an unreachable runtime host.
  • No actionable regression was identified.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Workspace or project removal] --> B[Identify removed owner keys]
  B --> C[Select affected session partitions]
  C --> D[Remove workspace rows and matching close records]
  D --> E[Save updated profile state]
Loading

Reviews (1) · Last reviewed commit: "refactor(terminal): the owner scan drops..."

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Close records now die with their workspace — deleteScannedSessionFieldsForOwners scans closedTerminalTabTombstonesByTabId and deletes entries whose record.worktreeId matches the removed owner. Both removeWorkspaceSessionOwner (direct, and the every-partition form) and the batch removeWorkspaceSessionOwners route through it, so every removal path prunes records in the same session write that drops the workspace's rows.
  • Repo/project pruning seeds from close records — repo-worktree-pruning.ts collects close-record worktreeIds (host-qualified keys handled by collectPrefixedKeys) so a worktree known only by a record is still pruned, and collectDeregisteredRepoIds seeds orphan repo ids from close records so a moved project's source records no longer await TTL.
  • Disposition doc — closedTerminalTabTombstonesByTabId is reclassified as owner-scoped by the removal scan, and the type JSDoc records the third death path.
  • Tests — 6-case worktree-removal-close-records.test.ts (local, SSH partition, same-id other host, folder workspace, project removal, cap-slot freeing), a deregistered-residue case, and an unreachable-runtime-host regression asserting no retirement on lost contact.

I ran the three touched suites locally (20 tests pass) and confirmed the new removal tests are not theatre by disabling the close-record scan: all 6 turn red, including the project-removal and cap-slot cases. I also traced the same-id-other-host partition gating and the runtime paired-host retention paths; neither regresses.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025
brennanb2025 merged commit c2517a4 into main Sep 29, 2026
65 checks passed
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.

1 participant