Skip to content

fix(editor): stop duplicate editor records from resurrecting closed tabs - #21124

Closed
BearMett wants to merge 6 commits into
stablyai:mainfrom
BearMett:fix/stale-editor-tab-leak
Closed

BearMett wants to merge 6 commits into
stablyai:mainfrom
BearMett:fix/stale-editor-tab-leak

Conversation

@BearMett

@BearMett BearMett commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Closing an editor tab sometimes didn't stick: the same file could quietly hold several records, each with its own tab, and pressing Ctrl+Tab brought a "closed" file back. This makes a close take the whole document with it and stops the duplicate records from multiplying on every save.

What Changed

  • One document identity (editor/file-ids/editor-document-identity.ts): editorDocumentIdentityKey is the single definition of "same edit document" (worktree, runtime owner, external SSH target, path, read-only, read-only live-tail). The session write and the close sweep both call it, so a rule added to one path cannot be missing from the other.
  • Write path (lib/workspace-session-editor-records.ts, workspace-session.ts): persisted editor records carry no id, so live OpenFiles that share an identity key serialize to indistinguishable rows and are merged before writing. Tie-break: an unsaved draft wins, then a non-preview record, then the active file, then first-wins; records with different drafts are kept apart as separate variants, a later duplicate merges into whichever variant it agrees with, and an equal-draft merge keeps whichever disk baseline exists. The active-file id and front-matter overrides follow the merged record to its survivor.
  • Orphan elimination (editor/file-ids/orphan-editor-file-ids.ts, tabs/tabs-reconciliation.ts, tabs-session-actions.ts, hydrate-editor-session.ts): an OpenFile no editor-family tab references is dropped at the end of hydration and at the multi-workspace reconciliation boundary. Dirty buffers, records with a pending draft (isDirty lags the buffer behind a debounce) and the workspace's active file are never swept; a workspace with no hydrated tab model is skipped, and orphans are reported and removed per workspace (an editor id can repeat across workspaces). Reconciliation reports orphans and never writes openFiles inside the batch fold. The single-worktree reconcileWorktreeTabModel deliberately does not prune: it can observe an in-flight open whose tab is not published yet.
  • Atomic close (close-file-action.ts, editor-file-ids.ts): closeFile sweeps every sibling of an edit-mode file that shares its identity key from openFiles, drafts, view-mode maps, tabBarOrder, pending focus, and every worktree's active-file map, then closes all of their unified tabs (replacing the previous find-first-and-break). A sibling that holds unsaved work, or whose tab is pinned, is left open (the save/discard prompt and the "pinned tabs survive close-others" contract still apply to it); a read-only live-tail log and diff/combined-diff variants are never treated as siblings. One recently-closed snapshot; the host is notified for every mirrored tab of every swept sibling (runtime/close-mirrored-editor-tab.ts). The tab scan is scoped to the file's worktree, so close-others over many tabs stays linear.
  • Hardening (open-file-mutations.ts): setActiveFile ignores and warns on an id with no backing OpenFile.

No persisted owner is rewritten in this PR. The restore-time heal of already-corrupted stores is the follow-up PR stacked on this one.

Why

Reproduced from a real persisted store: one local worktree held 2 + 4 records for two deleted files plus composite and uuid tabs for the same path in one group; the .bak.N rotation showed the counts growing each session and collapsing at each restart. #17370 dedupes only exact tuples at restore, so live minting during a session, orphaned records and one-of-N closes all survived. Fixing the write path, the orphan invariant and the close path together stops the leak without a schema change.

Linked Issue

Fixes #21121
Fixes #17778
Related: #17185, #16205, #16480

Visual Proof

N/A — persisted-session serialization and store actions; no new visual surface.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated

New: editor-document-identity.test.ts (table of records whose key, session write and close sweep must agree), editor-close-file-sibling-sweep.test.ts (incl. split view, mirrored sibling, dirty sibling kept, pinned sibling kept, read-only live-tail log kept, diff variants untouched, other worktrees untouched, neighbour reselect, setActiveFile guard), orphan-editor-file-ids.test.ts and tabs/tabs-reconciliation-orphan-editor-files.test.ts (incl. pending-draft orphan kept, identity-preserving no-op and tab-strip order cleanup), plus cases in workspace-session.test.ts (merge tie-breaks, divergent drafts kept as variants, [A, B, B] → 2 rows, read-only live-tail never merged, preview ordering) and ipc-tab-switch.test.ts.

Of the added lines, roughly 600 are source and 1200 are tests.

Focused files, the 12-file hydration/tab regression guard set, pnpm tc (one pre-existing unused import in NativeChatMessageList.windowing.test.tsx, present on main) and pnpm run check:code-quality:changed pass.

Real-app check (macOS arm64, electron-vite build --mode e2e, background launch with ORCA_BACKGROUND_LAUNCH=1 against an isolated copy of a production orca-data.json that reproduces the bug): with the two ghost documents open, closeFile on each removed every record and tab; five real Control+Tab presses through the window keydown listener switched between the remaining terminal tabs and brought neither file back (activeFileId: null); after session.flush() the persisted openFilesByWorktree, unifiedTabs, tabOrder and recentTabIds held 0 references to either path while the 5 terminal tabs stayed intact. Relaunching from that flushed state restored 0 editor records.

Real-app evidence (store snapshots, paths abbreviated)

Baseline in the copied store (before launch):

"openFileCountByPath": { "<repo>/…/fileA.csv": 2, "<repo>/…/fileB.txt": 4 }

After closeFile on both records:

{ "activeFileId": null, "activeTabType": "terminal",
  "openFileRecords": [], "openFileCountByPath": { "<repo>/…/fileA.csv": 0, "<repo>/…/fileB.txt": 0 },
  "editorTabsForPaths": [], "tabsByContentType": { "terminal": 5 } }

After 5 × Control+Tab through the window keydown listener (each press switched the active terminal tab, e.g. 0621f040… → 4d444daa…):

{ "activeFileId": null, "activeTabType": "terminal",
  "openFileRecords": [], "editorTabsForPaths": [], "tabsByContentType": { "terminal": 5 } }

Persisted orca-data.json after session.flush():

{ "openFileRecords": [], "openFileCountByPath": { "<repo>/…/fileA.csv": 0, "<repo>/…/fileB.txt": 0 },
  "editorTabsForPaths": [], "totalUnifiedTabsForWorktree": 5,
  "tabGroups": [ { "tabOrderLength": 5, "recentTabIdsLength": 5, "pathReferences": [] } ] }

Produced with tests/tools/editor-ghost-tab-heal-repro.mjs (added in the stacked heal PR).

Review

Please look hardest at the tie-breaks in buildPersistedEditorFileRecords and at the orphan prune's guards (dirty, active, un-hydrated workspace).

Agent skill upstream boundary

  • Not applicable.

Notes

No wire, RPC, dependency or platform-specific change. Persisted shape unchanged. Remote/SSH records are never stat'ed, pruned on loss of contact, or re-owned.

Known limits, left for follow-ups: openFile's own reuse rule (open-file-apply.ts) still matches on path + mode + owner only, so it is coarser than the identity key; and a Windows path and its WSL alias are two identities in the key (live opens never create that pair, but a legacy store holding both keeps both).

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • N/A for screenshots, with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • pnpm tc, pnpm test, changed-code quality gate pass locally

https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY

Editor tabs for the same file could accumulate several OpenFile records and
tab identities, and a closed tab came back on Ctrl+Tab or restart. Four
mechanisms stop new duplicates from being created:

- Merge live records that would persist as indistinguishable rows (no id is
  persisted) before writing the workspace session; keep divergent drafts apart.
- Drop OpenFiles no editor-family tab references at the hydration and
  multi-workspace reconciliation boundaries; dirty buffers and the active
  file are never swept.
- closeFile sweeps every same-document edit-mode sibling and all of their
  unified tabs, leaving siblings with unsaved work open for the prompt.
- setActiveFile ignores an id with no open document.

Refs stablyai#17185 stablyai#17778 stablyai#16205
@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview 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: 62b1d2d4-335d-49f0-a2a4-65cc9aea7d20

📥 Commits

Reviewing files that changed from the base of the PR and between 2bb422b and 7b7d6f6.

📒 Files selected for processing (2)
  • src/renderer/src/store/slices/editor-close-file-sibling-sweep.test.ts
  • src/renderer/src/store/slices/editor/actions/close-file-action.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The change deduplicates compatible editor records during session persistence and remaps merged file IDs. It expands closeFile to sweep duplicate editor identities while preserving unsaved or pinned siblings. Hydration and tab reconciliation remove clean orphan editor files only for hydrated worktrees. setActiveFile rejects missing IDs, and MRU tab switching skips stale entries. Tests cover persistence, close behavior, orphan cleanup, activation, drafts, ownership, and tab state.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to 7b7d6

Clean editor records without tabs can persist after workspace activation and reappear through active-surface fallback. Address orphan cleanup for settled reconciliation before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 35 functions across 17 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 The PR meets the coding requirements in [#21122] and [#17778]. Persistence merges equivalent editor records and preserves divergent drafts. closeFile removes same-document clean siblings and their e…
Out of Scope Changes check ✅ Passed The production changes and tests support the objectives in [#21122] and [#17778]. They cover persistence deduplication, editor identity matching, atomic close cleanup, orphan cleanup, active-file vali…
Title check ✅ Passed The title clearly and concisely describes the primary change: preventing duplicate editor records from bringing closed tabs back.
Description check ✅ Passed The description is complete and aligned with the template. It explains the user impact, implementation, motivation, linked issues, testing, visual proof, review focus, compatibility considerations, an…
  • Fix all pre-merge checks with AI

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 Major · Apply orphan cleanup in the singular reconciliation action. · tabs-session-actions.ts:109-113

src/renderer/src/store/slices/tabs/tabs-session-actions.ts:109-113
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Apply orphan cleanup in the singular reconciliation action.

projectWorktreeTabModelReconciliation reports orphanEditorFileIds for hydrated worktrees, but reconcileWorktreeTabModel applies only reconciliation.patch. Direct callers use this action for close and activation decisions without a batch cleanup step. A clean orphan can remain in openFiles, and its ID can remain in tabBarOrderByWorktree. Reuse the batch cleanup for one worktree or apply equivalent cleanup before set, while preserving the returned renderable-tab values.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 73367862-6823-436d-9f2b-a2d1e1afb8c9

📥 Commits

Reviewing files that changed from the base of the PR and between 4b87675 and e6df89b.

📒 Files selected for processing (13)
  • src/renderer/src/hooks/ipc-tab-switch.test.ts
  • src/renderer/src/lib/workspace-session-editor-records.ts
  • src/renderer/src/lib/workspace-session.test.ts
  • src/renderer/src/lib/workspace-session.ts
  • src/renderer/src/store/slices/editor-close-file-sibling-sweep.test.ts
  • src/renderer/src/store/slices/editor/actions/close-file-action.ts
  • src/renderer/src/store/slices/editor/actions/hydrate-editor-session.ts
  • src/renderer/src/store/slices/editor/actions/open-file-mutations.ts
  • src/renderer/src/store/slices/editor/file-ids/editor-file-ids.ts
  • src/renderer/src/store/slices/editor/file-ids/orphan-editor-file-ids.ts
  • src/renderer/src/store/slices/tabs/tabs-reconciliation-orphan-editor-files.test.ts
  • src/renderer/src/store/slices/tabs/tabs-reconciliation.ts
  • src/renderer/src/store/slices/tabs/tabs-session-actions.ts

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

@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

  • Write-path dedupe — buildPersistedEditorFileRecords (workspace-session-editor-records.ts) merges live edit OpenFiles that serialize to the same (worktree, owner, ssh target, path, readOnly, liveTail) row, with draft > non-preview > active > first-wins tie-breaks and divergent-draft separation; buildEditorSessionData follows a merged-away active id and front-matter override onto the survivor.
  • Orphan elimination — collectOrphanEditorFileIds / collectHydratedOrphanEditorFileIds drop tab-less documents after hydration and at the batched multi-workspace reconciliation, protecting dirty buffers, the worktree's active file, and worktrees with no hydrated tab model.
  • Atomic close — closeFile sweeps every same-document sibling's OpenFile, drafts, view-mode maps, cursor lines, tab-bar order, pending focus and per-worktree active selection, then closes all sibling tabs; dirty siblings stay open. setActiveFile now ignores ids with no backing document.
  • Tests — new editor-close-file-sibling-sweep, tabs-reconciliation-orphan-editor-files, write-path merge cases, and an MRU regression case.

The tie-breaks and orphan guards requested in the description were the focus of this pass. Two things I specifically tried to falsify and could not: the close sweep's identity omits readOnly/liveTail while the writer's key includes them, but a same-path/owner writable + read-only twin cannot coexist because applyOpenFileToState reuses the existing record by (mode, owner, path) and hydration's path+owner dedupe collapses such rows; and neither orphan path can drop unsaved work because, at hydration, editorDrafts[id] exists iff isDirty === true, the reconcile sweep runs only from the single startup call site, and active selections are produced with the same map the guard reads. Changed tests (37) and adjacent editor/tabs suites (48) pass locally.

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

Document identity was written three times, so a rule added to one copy (the
read-only/live-tail split) was missing from the others. One shared key now
backs every caller:

- editorDocumentIdentityKey is the single definition of "same edit document";
  the session write and the close sweep both call it, so closing a writable tab
  no longer sweeps the read-only live-tail log for the same path.
- The session write tracks every retained variant per identity, not just the
  first: three drafts [A, B, B] now persist as two rows instead of three.
- Orphan sweeps (hydration and the reconciliation batch) treat a pending
  editorDrafts entry as unsaved work; isDirty is set by a debounced callback and
  lags the buffer.
- Document why the single-worktree reconcile deliberately prunes no orphans.

Refs stablyai#17185 stablyai#17778 stablyai#16205

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY
…isted

The identity key separated a writable record flagged `liveTail` from one
without it, but the session writer persists `liveTail` only for a read-only
row. The two records therefore serialized to indistinguishable rows that the
write path kept as duplicates and the close sweep left behind.

Also correct the orphan collector's draft-guard comment: it claimed `isDirty`
is set by a debounced callback, which is not true of its caller.

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 Major · Preserve every persisted editor variant during… · workspace-session-editor-records.ts:90-141

src/renderer/src/lib/workspace-session-editor-records.ts:90-141
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Preserve every persisted editor variant during hydration. buildPersistedEditorFileRecords keeps SSH-target, read-only/live-tail, and divergent-draft variants. Hydration skips later rows through LegacyHydratedEditorFileIndex.hasOwner, which keys only by path, worktree, and runtime owner. Even if that check uses editorDocumentIdentityKey, usedOpenFileIds still rejects variants because buildOwnedEditorFileId also omits those fields. editorDocumentIdentityKey does not include draft content, so divergent drafts need a separate variant check and distinct hydrated IDs. Otherwise the skipped row is absent after restart and its dirtyDraftContent is not restored.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 153218c1-9dc8-409f-9d13-649c9b4673b7

📥 Commits

Reviewing files that changed from the base of the PR and between 0c8e3c3 and a593c09.

📒 Files selected for processing (3)
  • src/renderer/src/store/slices/editor/file-ids/editor-document-identity.test.ts
  • src/renderer/src/store/slices/editor/file-ids/editor-document-identity.ts
  • src/renderer/src/store/slices/editor/file-ids/orphan-editor-file-ids.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/store/slices/editor/file-ids/orphan-editor-file-ids.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@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

Re-reviewed the commits that landed after the prior pullfrog review (0c8e3c34 and a593c09), which act on the earlier review findings and CodeRabbit's single-worktree reconcile note.

  • Shared document identity — editorDocumentIdentityKey (new store/slices/editor/file-ids/editor-document-identity.ts) is now the single definition of "same edit document", imported by both the session write and the close sweep, so a close can no longer sweep a read-only live-tail log together with the writable tab for the same path.
  • liveTail gated on readOnly in the key — the identity's last component is readOnly === true && liveTail === true, matching what toPersistedOpenFile actually writes, so a record flagged liveTail without readOnly groups with the writable row it serializes to instead of leaving a duplicate the sweep cannot see.
  • Per-identity variant tracking — buildPersistedEditorFileRecords keeps a list of retained variants per identity rather than only the first, so a repeated draft merges into the variant it agrees with instead of stacking another row.
  • Draft-aware orphan sweeps — hydration and the multi-workspace reconciliation batch treat a pending editorDrafts entry as unsaved work, so a just-typed buffer survives before isDirty flushes.
  • Report-only single-worktree reconcile — documented why reconcileWorktreeTabModel prunes no orphans (it can observe an in-flight open where the OpenFile is published before its tab).
  • Tests — new editor-document-identity.test.ts and orphan-editor-file-ids.test.ts, plus cases in workspace-session.test.ts, editor-close-file-sibling-sweep.test.ts, and tabs-reconciliation-orphan-editor-files.test.ts; ran the five changed suites locally (58 pass).

The tie-breaks in buildPersistedEditorFileRecords and the orphan guards read correctly: the kept-record draft check blocks all later candidates, a candidate draft beats a clean kept record, preview loses to non-preview, and the active id wins only over a non-active kept record; survivingFileIdByMergedId chain-resolves when the survivor is later replaced. The prior latent note about the sweep identity omitting readOnly/liveTail is now resolved by construction. Remaining gap (restore still dedupes by path+owner) is explicitly scoped to the stacked heal PR.

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

…ndary

closeFile ran a get() per sibling candidate and, after the sweep dropped the
early break, flatMapped every worktree's tab array on every close. Both are paid
once per tab by the close-others / close-to-right loops. Read the pre-set()
state once and scan only the closed file's worktree, which also stops a foreign
tab that merely reuses the entity id from being closed.

The adjacent-file reselect indexed the post-sweep list with the closed file's
pre-sweep position, so each swept sibling ahead of it skipped a tab; count the
survivors ahead of it instead.

Pin the orphan-prune boundary with tests: a worktree missing from the hydrated
tab map is unknown and skipped, while a present-but-empty tab list is known and
prunes its clean records.

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY
A pinned tab survives every bulk close, but the duplicate-record sweep took
pinned siblings with it: closing an unpinned duplicate also closed the sibling
whose unified tab the user had pinned. Treat a pinned sibling like one holding a
rival draft — keep it and its tabs. The named record still closes when pinned.

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY

@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

Incremental re-review of 2bb422b (fix(editor): keep the close sweep linear and pin the orphan-prune boundary), the only commit that landed after the prior pullfrog review at a593c09.

  • Single pre-close snapshot — closeFile now reads get() once into preCloseState instead of re-reading per candidate, so the sweep identity, draft checks and mirrored-close notifications all describe the same pre-set() state.
  • Survivor-relative neighbour reselect — when the active document is swept, the replacement index is counted over post-sweep survivors ahead of the closed file rather than the raw pre-sweep index, so a close no longer skips a tab per swept duplicate that sat before it.
  • Kept siblings as a Set — the unsaved-sibling filter and the untitled-delete guard use keptSiblingIds.has(...) instead of Array.includes.
  • Worktree-scoped tab sweep — the unified-tab close scan walks only preClose.worktreeId and collects every closable tab id before closing, so a foreign workspace tab that happens to reuse the entity id is left untouched.
  • Pinned orphan-prune boundary — the hydrated/orphan collector keeps its documented "missing tab map = unknown, skip; present-but-empty list = known, prune" contract, now covered by tests on both the hydration collector and the batched reconciliation prune.

Verification: ran the five changed suites plus tabs-model-reconciliation, hydrated-workspace-reconciliation-batch and editor-close-file-cleanup — 95 tests pass. The new neighbour-reselect and empty-tab-list cases fail against the pre-commit logic, so they are genuine regression guards. I also traced the post-set() closeUnifiedTab loop against buildActiveSurfacePatch/deriveActiveSurfaceForWorktree: an intermediate close can momentarily derive activeFileId from a still-present swept sibling tab, but the final close for that worktree always re-derives from a post-sweep tab set and clears it, so no swept id survives in the returned state.

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

@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

Follow-up review of 7b7d6f6 (fix(editor): keep a pinned sibling open when its document is closed), which landed while the previous review was posting.

  • Pinned siblings survive the sweep — closeFile now keeps a same-document sibling whose unified editor tab is pinned, treating the sibling sweep as a bulk close the user did not aim at that record; the named id still closes even when its own tab is pinned.
  • Tests — pinned duplicate kept, the same duplicate swept once unpinned, and a pinned named record still closing.

Verification: editor-close-file-sibling-sweep.test.ts passes all 15 cases. The rule matches the existing isPinned?: boolean // pinned tabs survive "close others" contract in src/shared/tab-types.ts and the pinned filter in the tab-group bulk-close commands; the kept-pinned path also correctly suppresses the untitled-placeholder delete through keptSiblingIds.size === 0.

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

An unowned editor id is the bare file path, so the hydrate and reconcile
orphan sweeps collected ids into one flat set and removed the live record
sharing that id in another workspace. Both collectors now report orphans per
worktree and every consumer matches on (worktreeId, id); the id-keyed draft
and front-matter cleanups follow survivorship instead of orphan ids, and the
tab-strip prune is scoped to the worktree that swept.

Two duplicate records with the same draft merge into one row, which dropped a
disk baseline only the merged-away record carried; the survivor now inherits
it. The mirrored-close notifier closed only the first unified tab for a file
id, so a second mirrored tab stayed open on the host and re-mirrored the file
on the next snapshot; it now closes every match.

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY

@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

Incremental re-review of ad2f3375a9 (fix(editor): scope orphan sweeps per worktree and keep merged baselines), the only commit that landed after the prior pullfrog review at 7b7d6f6f.

  • Per-worktree orphan scoping — collectHydratedOrphanEditorFileIds now returns Map<worktreeId, Set<fileId>> instead of a flat Set, with a new isOrphanEditorFile membership test. An unowned editor id is the bare file path, so the same id can name a live document in another worktree; the previous flat set swept that one. The batched reconciliation fold builds sweptFileIdsByWorktree, and pruneTabBarOrderEntries now prunes each worktree's strip order by its own swept set. Both changes are strictly more conservative (fewer ids swept), so they cannot newly drop unsaved work.
  • Disk-baseline carry on merge — withCarriedDiskBaseline copies an equal-draft duplicate's lastKnownDiskSignature onto the kept record when the kept record has no baseline. Only reachable for an equal-draft merge onto a record that itself has a draft; a record with a draft can never be won over, and a record without a draft never carries a signature, so no baseline can be lost when a later candidate replaces the survivor.
  • Mirrored close covers every tab — notifyHostOfMirroredEditorClose now records the close intent and calls closeWebRuntimeSessionTab for every editor tab whose entityId === fileId, not just the first, so a split view's other mirrored tabs no longer re-mirror the file on the next host snapshot.
  • Tests — equal-draft baseline carry, per-worktree orphan isolation on both the hydration collector and the batch prune, every-mirrored-tab close, and an MRU entry that names a tab no longer rendered.

Verification: the seven changed suites pass (96 passed). I traced the baseline carry's reachability and the per-worktree map through hydrate-editor-session.ts and tabs-session-actions.ts, and confirmed the broadened notifier's host-close set is a subset of what closeFile removes locally (pinned/dirty siblings carry distinct entityIds and are never passed to it; closeAllFiles and the path-move rekey already relied on closing every tab for a file id).

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

@BearMett

Copy link
Copy Markdown
Contributor Author

Replying here to the two CodeRabbit items that were posted outside the diff range.

Apply orphan cleanup in the singular reconciliation action (tabs-session-actions.ts)

Left as is, on purpose, and documented in 0c8e3c3. reconcileWorktreeTabModel runs from setActiveWorktree and empty-group checks, which can observe an in-flight open where the OpenFile is already published but its unified tab is not yet. Pruning there would delete a live document. The batch fold at the hydration boundary is the only point where the tab model is settled, so it is the only place that prunes; the singular action keeps reporting orphanEditorFileIds without acting on them. There is now a WHY comment at the action explaining this.

PR #21125 (branch B)

Preserve every persisted editor variant during hydration (workspace-session-editor-records.ts)

Not changed here, on purpose. The hydrated editor id is a function of owner + path and is what every unified tab references, so giving read-only, SSH-target or divergent-draft variants their own ids means changing the id format across tabs, groups and the host mirror. That is a separate change. What this stack does instead: the writer keeps those variants apart so nothing is lost on save, and the stacked heal PR (#21125) parks a writable draft the id index would otherwise skip on the reopen stack (hydrate-editor-session.ts, 7494434), so the text is recoverable rather than dropped. Listed under Notes in the description as a known limit.

nwparker added a commit that referenced this pull request Oct 6, 2026
Adapt the document identity, persistence dedupe, and orphan boundaries from #21124. Preserve current workspace-selection behavior, scope closes when legacy IDs repeat across workspaces, and use the captured file owner for mirrored closes.

Co-authored-by: 김영민 <[email protected]>
@BearMett

Copy link
Copy Markdown
Contributor Author

Closing in favour of #28120.

Most of this PR is now on main through @nwparker's commits c9f4cd7e27, 8bd567a015, 31d85749b4 and 14bae2e172. They sweep the same document's clean duplicates on close, with exact owner checks, and handle drafts, backing files and mirrored closes. Two pieces were missing from main, and #28120 carries just those:

  • a pinned duplicate stays open when its twin is closed;
  • setActiveFile ignores an id with no open file.

I deliberately dropped two pieces:

  • Merging same-document records when the session is written. Saving each record's id instead keeps same-path records distinguishable on disk, while equivalent duplicates still merge and divergent drafts stay separate records. That record-identity change is prepared locally; its publication is still under consideration.
  • Pruning open-file records that no tab references. A missing tab reference is not evidence that the user closed the file.

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

Labels

None yet

Projects

None yet

1 participant