Skip to content

fix(editor): close stale duplicate documents safely - #25509

Merged
nwparker merged 10 commits into
mainfrom
nwparker/editor-stale-tab-close
Oct 7, 2026
Merged

nwparker merged 10 commits into
mainfrom
nwparker/editor-stale-tab-close

Conversation

@nwparker

@nwparker nwparker commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​483 $\color{#cf222e}{\Huge{\mathbf{−}}}$​27 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​456
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​222 $\color{#cf222e}{\Huge{\mathbf{−}}}$​75 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​147

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.

Before

After: both stale records and their tabs are gone.

After

A cold restart keeps the document closed.

After restart

Testing

  • Earlier rendered macOS validation through hidden Electron CDP; no foreground app launch.
  • Automated regressions added, including reproductions that failed before the review fixes.
  • Latest local validation: 261 tests across 21 suites, full node/CLI/web typecheck, changed-code quality, and pre-commit lint/format checks pass.
  • Tested duplicate closure, dirty and empty drafts, owner/host isolation, disconnected close, split views, persisted order, restart hydration, model/undo/cursor custody, untitled deletion routing, and reopen-during-stat races.
  • SSH routing uses injected filesystem IPC; native Windows/Linux and a live SSH host were not exercised locally. CI validates the current head before merge.

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

  • Not applicable; no upstream skill source is copied.

Checklist

  • Focused on document close and backing-file custody.
  • Explained user behavior, mechanism, and alternatives.
  • Before/after and restart screenshots attached.
  • Self-reviewed correctness, security, and performance.
  • Cross-platform, SSH/remote, folder workspace, and path impact considered.
  • Local regression tests, full typecheck, changed-code quality, and staged lint/format pass; CI covers broader checks and packaging.

@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 95c11f28-c1a9-4afe-8fe5-a730d8eb9ce7
📥 Commits

Reviewing files that changed from the base of the PR and between 7a15bb7 and 9db4517.

📒 Files selected for processing (1)
  • config/scripts/vitest-sqlite-database-runtime-files.mjs

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


📝 Walkthrough

Walkthrough

Editor 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 9db45

No specific user-facing or operational regression is established in the supplied change context; no actionable merge-blocking risk remains.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 9442c

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — One close can now affect all eligible duplicate records for the selected document and their linked tabs, including host-close requests for mirrored records. Selection remains bounded by matching path and owner metadata and excludes pending sibling work. No tenant-wide, credential, or privilege expansion was established in this path.

Trust Boundaries and Controls

  • observed — Automatic sibling removal requires writable edit records without dirty state or any draft key. Backing-file deletion additionally requires an eligible untouched untitled document and no surviving same-owner record. The deletion helper resolves file-operation authority and verifies that the file is still empty before invoking deletion.
  • observed — Mirrored notification requires a mirrored file, resolved runtime environment, and matching editor tab. It records close intent synchronously before the asynchronous request. The downstream client captures environment and pairing ownership for the RPC.

Resilience and Maintainability Implications

  • observed — Local removal does not await host or filesystem cleanup. Existing host-close handling clears suppression on transient RPC failure and makes it durable for definitive tab absence; filesystem cleanup swallows asynchronous errors. These mechanisms predate the PR, while host notifications now run for each selected record. Atomic cross-host rollback and deletion/reopen race safety remain unverified.

Hardening Proposals

  • proposed — Consider requiring captured provenance before automatically sweeping sibling records, while retaining explicit requested-record closing. This would distinguish unknown ownership from verified equality; it is hardening, not an established cross-owner vulnerability.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.76% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 13 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes the main change: safely closing stale duplicate editor documents.
Description check ✅ Passed The description covers the required sections with clear change details, rationale, linked issues, visual proof, testing, review notes, and completed checklist items.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@nwparker
nwparker force-pushed the nwparker/editor-stale-tab-close branch from 1424808 to baaea5b Compare October 5, 2026 10:53

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

ℹ️ Minor suggestions only — one confirmed latent regression plus one open design question.

Reviewed changes

  • Stale-duplicate close sweep — closeFile now also removes clean, writable, same-owner edit records (isSameOwnedDocument) and cleans their drafts / cursor / view-mode / tab state, firing the mirrored-close notify per swept id.
  • Active-file fallback rewrite — findAdjacentOpenFileId replaces the old clamped-index neighbor pick, and the per-worktree activeFileIdByWorktree update is restructured around the close set.
  • Unified-tab close loop — closes every tab across worktrees whose entityId is 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 isSameDocumentOwner survivor 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

newActiveId = findAdjacentOpenFileId(worktreeFiles, fileIdsToClose, s.activeFileId)
}

const closedWorktreeId = closedFile?.worktreeId

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.

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.

@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 in the delta. The earlier inline finding on close-file-action.ts is still open and is not repeated here.

Reviewed changes

  • Shared lint repair (9969240819) — renames the local confirm helper to confirmHook in src/renderer/src/lib/worktree-creation-hook-preparation.ts (declaration plus both call sites). This clears the localization-coverage scanner's USER_VISIBLE_FUNCTION_NAMES false positive on confirm('setup') / confirm('vmRecipe'); no behavior change, and no bare confirm( usages remain in the file.
  • Editor fix (baaea5b4e6) — the close-file-action.ts patch and editor-close-document-siblings.test.ts are unchanged from the previously reviewed 1424808d5c head, so the prior review's finding (per-worktree activeFileIdByWorktree left stale on orphan close) still stands against this head.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@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: 34eb14fc-882d-4005-9f50-743f490e3f85
📥 Commits

Reviewing files that changed from the base of the PR and between e2da3a1 and 9442c25.

📒 Files selected for processing (6)
  • src/renderer/src/components/editor/closed-editor-model-lifetime.test.ts
  • src/renderer/src/components/editor/editor-model-host-isolation.test.ts
  • src/renderer/src/components/editor/monaco-cursor-line-lifetime.test.ts
  • src/renderer/src/lib/worktree-creation-hook-preparation.ts
  • src/renderer/src/store/slices/editor-close-document-siblings.test.ts
  • src/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.

Comment on lines +156 to +167
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

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

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.

Suggested change
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

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

ℹ️ Test-only delta — no new issues. The earlier activeFileIdByWorktree inline finding on close-file-action.ts remains 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 in closed-editor-model-lifetime.test.ts becomes readOnly (with an added assertion that only it survives), the same-path remote in monaco-cursor-line-lifetime.test.ts gains a distinct runtimeEnvironmentId and a seeded unifiedTabsByWorktree: {}, and editor-model-host-isolation.test.ts gives its file() helper its route's runtimeEnvironmentId, mints an owner-scoped migratedFile id, marks the surviving runtime record readOnly, and closes the migrated id rather than local.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.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the nwparker/editor-stale-tab-close branch from 1902bdc to 23cd72b Compare October 6, 2026 22:52
@nwparker
nwparker merged commit f052085 into main Oct 7, 2026
30 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