Repository navigation
fix(editor): close stale duplicate documents safely - #25509
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:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (1)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughEditor closing now removes eligible clean sibling files and their associated tabs while preserving files with drafts or different ownership. Untitled-file cleanup checks for other views that may share the backing file, including after an asynchronous stat. Mirrored editor closing now handles all linked host tabs and uses the file’s captured runtime environment when available. The PR also updates editor lifetime tests and app server connection test setup. Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to No specific user-facing or operational regression is established in the supplied change context; no actionable merge-blocking risk remains. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to Closing a document now affects multiple matching copies, but pending edits and distinct owners are explicitly protected. No introduced security vulnerability was established. Some ownership-fallback and asynchronous recovery behavior remains unverified. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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 |
1424808 to
baaea5b
Compare
There was a problem hiding this comment.
ℹ️ Minor suggestions only — one confirmed latent regression plus one open design question.
Reviewed changes
- Stale-duplicate close sweep —
closeFilenow also removes clean, writable, same-ownereditrecords (isSameOwnedDocument) and cleans their drafts / cursor / view-mode / tab state, firing the mirrored-close notify per swept id. - Active-file fallback rewrite —
findAdjacentOpenFileIdreplaces the old clamped-index neighbor pick, and the per-worktreeactiveFileIdByWorktreeupdate is restructured around the close set. - Unified-tab close loop — closes every tab across worktrees whose
entityIdis in the close set instead of only the first matching tab. - Backing-file guard — deletion of an untouched untitled placeholder is now suppressed while a
isSameDocumentOwnersurvivor remains. - Regression suite — new
editor-close-document-siblings.test.ts(18 tests) covering duplicates, split/document close, dirty and empty drafts, other owners/provenance, external SSH, disconnected close, and retained placeholder bytes.
The sweep scope itself checks out: a specialist traced the record producers (open-file-apply.ts, resolveEditorFileIdForOwner, hydration, rekey) and found no way for two records satisfying isSameOwnedDocument to be legitimately distinct documents. The new tests are meaningful (they fail against the pre-PR code), and all touched close/tab suites pass locally.
ℹ️ Backing-file guard shares the sweep's route comparison, so a differing-route survivor gets no protection
shouldDeleteFromDisk's survivor guard reuses isSameDocumentOwner, whose route check (actualRoute?.executionHostId === expectedRoute?.executionHostId) is false whenever exactly one side carries operationProvenance or the two routes differ — the same condition under which the sweep deliberately leaves the sibling open. A surviving same-path record with a differing/absent provenance route therefore does not protect an empty untitled backing file: the file can be deleted while that record stays open pointing at the deleted path. This is not a regression from main (which deleted unconditionally) and I could not prove a deterministic sequence that produces the record shape, so treat it as an open question rather than a blocker.
Technical details
# Backing-file guard needs a fail-safe survivor predicate
## Affected sites
- `src/renderer/src/store/slices/editor/actions/close-file-action.ts:18-28` — `isSameDocumentOwner` uses optional-chained route comparison; `undefined === value` is false.
- `src/renderer/src/store/slices/editor/actions/close-file-action.ts:99-104` — guard `.some(file => !fileIdsToClose.has(file.id) && isSameDocumentOwner(file, preClose))`.
- `src/renderer/src/store/slices/editor/actions/close-file-action.ts:30-48` — `isSameOwnedDocument` calls the same predicate, so the preserved class and the protected class are identical.
## Required outcome
- Decide whether the guard should protect *every* surviving record that resolves to the same worktree + runtime + `filePath` (including one with a different/absent provenance route), or whether deleting the placeholder under a differing-owner survivor is acceptable.
- If the former, the survivor predicate should fail safe on absent route (treat missing provenance on either side as matching) rather than inheriting the sweep's strictness; the two predicates should then diverge by design.
## Open questions for the human
- Can an empty untitled placeholder and a same-path record with a different `runtimeEnvironmentId`/route coexist in one `openFiles` list in practice (e.g. mirrored-tab restore, runtime-owner migration)?
- If the guard is intentionally scoped to same-route survivors only, a short comment stating that would close the question.deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
| newActiveId = findAdjacentOpenFileId(worktreeFiles, fileIdsToClose, s.activeFileId) | ||
| } | ||
|
|
||
| const closedWorktreeId = closedFile?.worktreeId |
There was a problem hiding this comment.
The per-worktree activeFileIdByWorktree update is now gated on closedFile?.worktreeId, but the old code used closedFile?.worktreeId ?? s.activeWorktreeId. When closeFile runs with an fileId that is not in openFiles (the orphan promoted by closeUnifiedTab that the removed "stale activeFileId" comment covered), activeFileIdByWorktree[worktree] is never updated: here closedWorktreeId is undefined, so the else if at line 166 can never fire. Reproduced: with activeFileIdByWorktree[WT] = '/ghost', no other WT surface, and closeFile('/ghost'), activeFileId becomes null but activeFileIdByWorktree[WT] stays '/ghost', whereas the old code wrote null. Consumers currently re-validate against openFiles, so it is latent rather than user-visible.
Technical details
# Per-worktree active id left stale on orphan close
## Affected sites
- `src/renderer/src/store/slices/editor/actions/close-file-action.ts:156-168` — block gated on `closedFile?.worktreeId`; the `?? s.activeWorktreeId` fallback used at line 149 for `newActiveId` is dropped here.
- `src/renderer/src/store/slices/editor-close-file-stale-active.test.ts` — covers the orphan close but only asserts the global `activeFileId`, never `activeFileIdByWorktree`.
## Required outcome
- When the closed `fileId` is absent from `openFiles` but equals the stale global/per-worktree active id, `activeFileIdByWorktree[worktree]` must still be recomputed (or set to `null` when the worktree has no remaining surface), matching the pre-PR behavior.
## Suggested approach
- Use `const closedWorktreeId = closedFile?.worktreeId ?? s.activeWorktreeId` (mirroring the `worktreeId` used above), and keep the `else if (fileIdsToClose.has(s.activeFileId))` write reachable for that case. A test asserting `activeFileIdByWorktree[WT]` for the orphan/deactivation path would pin it.There was a problem hiding this comment.
ℹ️ No new issues in the delta. The earlier inline finding on
close-file-action.tsis still open and is not repeated here.
Reviewed changes
- Shared lint repair (
9969240819) — renames the localconfirmhelper toconfirmHookinsrc/renderer/src/lib/worktree-creation-hook-preparation.ts(declaration plus both call sites). This clears the localization-coverage scanner'sUSER_VISIBLE_FUNCTION_NAMESfalse positive onconfirm('setup')/confirm('vmRecipe'); no behavior change, and no bareconfirm(usages remain in the file. - Editor fix (
baaea5b4e6) — theclose-file-action.tspatch andeditor-close-document-siblings.test.tsare unchanged from the previously reviewed1424808d5chead, so the prior review's finding (per-worktreeactiveFileIdByWorktreeleft stale on orphan close) still stands against this head.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
34eb14fc-882d-4005-9f50-743f490e3f85
📒 Files selected for processing (6)
src/renderer/src/components/editor/closed-editor-model-lifetime.test.tssrc/renderer/src/components/editor/editor-model-host-isolation.test.tssrc/renderer/src/components/editor/monaco-cursor-line-lifetime.test.tssrc/renderer/src/lib/worktree-creation-hook-preparation.tssrc/renderer/src/store/slices/editor-close-document-siblings.test.tssrc/renderer/src/store/slices/editor/actions/close-file-action.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| const closedWorktreeId = closedFile?.worktreeId | ||
| if (closedWorktreeId) { | ||
| const worktreeFiles = s.openFiles.filter((file) => file.worktreeId === closedWorktreeId) | ||
| const worktreeActiveFileId = s.activeFileIdByWorktree[closedWorktreeId] | ||
| if (worktreeActiveFileId && fileIdsToClose.has(worktreeActiveFileId)) { | ||
| newActiveFileIdByWorktree[closedWorktreeId] = findAdjacentOpenFileId( | ||
| worktreeFiles, | ||
| fileIdsToClose, | ||
| worktreeActiveFileId | ||
| ) | ||
| } else if (s.activeFileId && fileIdsToClose.has(s.activeFileId)) { | ||
| newActiveFileIdByWorktree[closedWorktreeId] = newActiveId |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Keep the s.activeWorktreeId fallback for the per-worktree active id.
closedWorktreeId uses closedFile?.worktreeId with no fallback. Assume fileId is not in openFiles, as with an orphan id that closeUnifiedTab promotes. In that case the block does not run. activeFileIdByWorktree[worktree] then keeps the stale id, and activeFileId becomes null. The pre-PR code fell back to s.activeWorktreeId, and the newActiveId computation at Line 149 still does. A previous review reported the same issue.
Proposed fix
- const closedWorktreeId = closedFile?.worktreeId
+ const closedWorktreeId = closedFile?.worktreeId ?? s.activeWorktreeId📝 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.
| const closedWorktreeId = closedFile?.worktreeId | |
| if (closedWorktreeId) { | |
| const worktreeFiles = s.openFiles.filter((file) => file.worktreeId === closedWorktreeId) | |
| const worktreeActiveFileId = s.activeFileIdByWorktree[closedWorktreeId] | |
| if (worktreeActiveFileId && fileIdsToClose.has(worktreeActiveFileId)) { | |
| newActiveFileIdByWorktree[closedWorktreeId] = findAdjacentOpenFileId( | |
| worktreeFiles, | |
| fileIdsToClose, | |
| worktreeActiveFileId | |
| ) | |
| } else if (s.activeFileId && fileIdsToClose.has(s.activeFileId)) { | |
| newActiveFileIdByWorktree[closedWorktreeId] = newActiveId | |
| const closedWorktreeId = closedFile?.worktreeId ?? s.activeWorktreeId | |
| if (closedWorktreeId) { | |
| const worktreeFiles = s.openFiles.filter((file) => file.worktreeId === closedWorktreeId) | |
| const worktreeActiveFileId = s.activeFileIdByWorktree[closedWorktreeId] | |
| if (worktreeActiveFileId && fileIdsToClose.has(worktreeActiveFileId)) { | |
| newActiveFileIdByWorktree[closedWorktreeId] = findAdjacentOpenFileId( | |
| worktreeFiles, | |
| fileIdsToClose, | |
| worktreeActiveFileId | |
| ) | |
| } else if (s.activeFileId && fileIdsToClose.has(s.activeFileId)) { | |
| newActiveFileIdByWorktree[closedWorktreeId] = newActiveId |
There was a problem hiding this comment.
ℹ️ Test-only delta — no new issues. The earlier
activeFileIdByWorktreeinline finding onclose-file-action.tsremains open; production code is unchanged since that review, so it is not repeated here.
Reviewed changes
- Custody fixtures aligned with the owner-close sweep (
9442c25b) — the only change since the prior review. Three existing suites adjust their sibling records so the new sweep no longer classifies them as stale duplicates: the shared-URI sibling inclosed-editor-model-lifetime.test.tsbecomesreadOnly(with an added assertion that only it survives), the same-path remote inmonaco-cursor-line-lifetime.test.tsgains a distinctruntimeEnvironmentIdand a seededunifiedTabsByWorktree: {}, andeditor-model-host-isolation.test.tsgives itsfile()helper its route'sruntimeEnvironmentId, mints an owner-scopedmigratedFileid, marks the surviving runtime recordreadOnly, and closes the migrated id rather thanlocal.file.id. Production code is unchanged; the four changed suites' 40 tests pass locally, and each fixture edit keeps the original custody assertion intact rather than weakening it.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
Adapt the document-sibling cleanup from Pr1p's #23347 with exact owner and captured provenance checks. Preserve divergent drafts and the backing bytes needed by retained views, and keep one-pane close behavior intact. Co-authored-by: Chen <[email protected]>
1902bdc to
23cd72b
Compare

ELI5
Closing a document now clears stale clean copies from the tab bar and saved tab order, so Ctrl+Tab cannot bring them back. Pending drafts and separate owners stay intact.
What Changed
The existing document-close action removes writable clean duplicate records only when the document path, workspace, runtime owner, and captured connection information match. It removes their state and every linked tab, prunes both file IDs and tab IDs from saved order, and notifies the owning host about every linked mirrored tab. Closing one split pane still preserves the other intentional view.
Untitled-file cleanup treats an empty draft entry as pending work in both single-document and close-all paths. Bulk close protects backing files used by any dirty or drafted duplicate before removing the records. Its shared deletion guard protects any retained view that might use the same backing file, including overlapping workspaces and missing ownership provenance. It rechecks live references after the asynchronous file-size check, so reopening the document during that check cancels deletion.
Model and cursor fixtures preserve disposal, text, undo, and ownership isolation coverage. Shutdown tests share a deterministic sequence that waits for forced termination before advancing the exit deadline. An identical duplicate callback key was removed from an existing session test fixture.
Mirrored editor closes now use the runtime owner captured by the source snapshot, falling back to workspace inference only for legacy records. Two regressions cover a disagreeing workspace catalog and an explicitly local owner.
Why
A path-only sweep can remove another owner's document or pending edits. The existing close path is the right place to remove stale records and their references; the existing cleanup helper is the right place to protect backing files across every caller. This avoids a second cleanup mechanism or a new remote protocol.
Adapted @Pr1p's approach in #23347 with stricter ownership checks. Reviewed #21626 and #16480; the rendered close path already supplies the unified tab ID, so the callback-only approach was not adopted.
Linked Issue
Related to #16205 and #23405. This addresses stale duplicate closure. Those issues remain open because upstream multi-client creation/synchronization requires separate evidence.
Visual Proof
Earlier hidden Electron CDP validation on macOS opened a real fixture through Explorer, seeded a stale clean duplicate, closed the original through its rendered X, and used Ctrl+Tab twice. A separate split-pane check preserved the other view. These images demonstrate the tab behavior; the subsequent deletion and persistence fixes are covered by regression tests.
Before: the duplicate remains.
After: both stale records and their tabs are gone.
A cold restart keeps the document closed.
Testing
Review
Adversarial review reproduced and fixed empty-draft deletion, unsafe deletion with incomplete provenance or overlapping workspace views, reopening during cleanup, partial mirrored-host closure, and stale saved tab IDs. The fixes extend existing identity, close, and deletion paths. No editor-library patches or wire-format changes.
The full CI run also exposed a timing assumption in an unchanged Codex process-close test under Bun: one fake-clock jump raced real asynchronous teardown. The test now waits for forced termination before advancing the final exit deadline, following its existing neighboring control. The unproven-close and later-exit assertions remain intact. The updated base passes 261 focused tests across 21 suites through the repository's Bun and Node test runners, full typecheck, changed-code quality, and direct lint. The shared shutdown sequence stays within the existing file line limit. CI also caught three existing SQLite fixtures missing from the Node-runtime list, including one added to main during the run. All now use the existing Node runtime; the boundary guard and affected fixtures pass, with the latest omission verified on the exact CI snapshot.
Agent skill upstream boundary
Checklist