Skip to content

fix(editor): heal duplicate and mis-owned editor records at restore - #21125

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

BearMett wants to merge 16 commits into
stablyai:mainfrom
BearMett:fix/stale-editor-tab-resurrection

Conversation

@BearMett

@BearMett BearMett commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Stores that already contain duplicate or mis-owned editor records (a local worktree's file stamped with a remote runtime as its owner) kept restoring ghost tabs on every launch. This repairs them once at restore time, without touching the file on disk and without losing any unsaved draft.

Stacked on the "stop the leak" PR (#21124). This PR is opened against main from a fork, so its diff currently includes that PR's commits; the commits new here are heal duplicate and mis-owned editor records at restore, add a background repro … and the three review follow-ups after them. It will be rebased once #21124 merges. Of this PR's own added lines, roughly 800 are source and the rest (about 2200) are tests, the scrubbed fixture, locale keys and the repro tool.

What Changed

  • Owner resolution from stamped evidence only (editor/file-ids/hydrated-editor-owner-healing.ts): per worktree, resolve the owner with both UI-focus signals suppressed (activeWorkspaceExecutionHostId, settings.activeRuntimeEnvironmentId). Git worktrees go through resolveExplicitWorktreeOperationRouteResult; folder workspaces through their written executionHostId / connectionId / restored runtime host, never the resolver's local default. If nothing stamped resolves, nothing is rewritten.
  • Heal plan (same module): when the route resolves, normalize the records' owners to it and merge siblings that share the document identity key from fix(editor): stop duplicate editor records from resurrecting closed tabs #21124 (editorDocumentIdentityKey, keyed on the bucket's worktree so a drifted worktreeId cannot split a group). Tie-break: draft (preferring one that carries a disk baseline), then active file, then first. Read-only, live-tail and external-SSH records are never re-owned. Two records with the same owner but different drafts cannot both hydrate (the restored id is a function of owner + path), so the non-surviving writable draft is returned as recoverable (a read-only row's draft is never recovered: read-only tabs must restore clean); such a survivor keeps its verbatim owner and its tab is not re-stamped onto the route.
  • Applying the plan (hydrate-editor-session.ts): superseded ids — merged siblings and the survivor's own pre-heal identity — are fed into the existing addEditorFileIdMigration, so unifiedTabs / tabOrder / recentTabIds / activeTabId are redirected onto the survivor; editor tabs that now share one entity are collapsed per group with the same dedupe the tab hydration uses (a dropped twin's pin, label and color are carried onto the survivor); a tab executionHostId that contradicts the route (alias-aware, so runtime:<hub> on an SSH route is left alone) is corrected, unstamped tabs stay unstamped; recoverable drafts become recently-closed snapshots for that worktree, as does a writable draft the pre-existing id index would otherwise have skipped behind a read-only row of the same path. One warning per healed worktree.
  • Draft recovery (types/open-file.ts, recently-closed-editor-tabs.ts, parked-recovered-editor-drafts.ts): ClosedEditorTabSnapshot gains an optional dirtyDraftContent and carries the draft's lastKnownDiskSignature; reopenClosedEditorTab restores the buffer with the tab (Mod+Shift+T) and re-verifies the disk baseline the same way a hydrated dirty record does. If the document is already open with different unsaved text (decided before openFile, by the shared identity key), nothing is opened or written: the live record is activated, the snapshot is deferred to the back of both reopen stacks (deferRecoveredEditorDraft, beside the parkRecoveredEditorDrafts hydration uses, so the two stacks stay paired and other tab types are not blocked) and a localized toast says to save or close the live tab first. A snapshot whose document is open read-only is deferred the same way instead of being consumed. The two reopen stacks are kept paired at the cap, and the heal warning reports any recovered draft that fell off it.
  • Repro tool (tests/tools/editor-ghost-tab-heal-repro.mjs + editor-ghost-tab-session-scan.mjs): copies an orca-data.json into an isolated user-data dir (drafts and disk baselines stripped from the copy and autosave forced off, so the launched app cannot write the user's real files), auto-detects duplicate or mixed-owner editor records, launches Orca in the background (ORCA_BACKGROUND_LAUNCH=1) and records the heal line, store snapshots around close + Control+Tab, the flushed session and a restart pass. Same shape as terminal-garble-production-repro.mjs.

Why

The real store behind this had records for a local worktree's files stamped with a paired remote runtime's id (UI focus had leaked into ownership), alongside one correctly null-owned record, and both composite and uuid tabs for the same path. #17370's exact-tuple dedupe cannot see owner-mismatched siblings, and without the id migration a re-owned record's tab is left orphaned. Healing at hydration is idempotent, changes no persisted shape, and rewrites an owner only when stamped evidence proves it.

Linked Issue

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

Visual Proof

N/A — hydration-time repair of persisted session state; no new visual surface.

Testing

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

stale-editor-tab-owner-healing.test.ts is driven by a scrubbed copy of the real corrupted store (stale-editor-tab-resurrection-fixture.ts): 6 records → 2 documents with local owners, composite ids redirected, tab strip and MRU sanitized. Controls: runtime-owned worktree keeps the runtime owner; ambiguous git route and unstamped folder row leave owners verbatim while the app's own resolver would have said runtime:…; stamped local/runtime folder rows heal; read-only live-tail log never re-owned; a single re-owned record's tab is redirected instead of orphaned; a divergent-draft survivor's tab is not re-stamped; same-owner divergent drafts survive a real buildEditorSessionData → hydrate → reopen round trip with their disk baseline and a pending verification. editor-recently-closed-tabs.test.ts covers restoring a parked buffer, applying it to a clean live record, activating instead of rewriting when the live record already holds the text, and deferring it (no second tab, live tab untouched, other tab types still reopenable) when the live record holds different unsaved text. parked-recovered-editor-drafts.test.ts pins the pairing of the two reopen stacks.

Focused files, the 12-file 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 the production orca-data.json behind this report): the git worktree's route resolved local from stamped catalog rows (the worktree scan completes before session hydration), and the renderer logged once:

[editor-hydration] one-time heal of persisted editor state for <worktreeId>: dropped 4 duplicate record(s), re-owned 2, kept 0 divergent-draft group(s) apart, 0 draft(s) moved to the reopen stack

6 records → 2 (one per path, runtimeEnvironmentId: null); the two composite editor:… tab ids and the uuid tab collapsed onto the survivors' ids and their executionHostId went from runtime:<remote> to local. Relaunching from the flushed session produced no heal line and 0 records for either path, so the heal is one-shot.

Reproduce against your own store (the original store is only read):

npx electron-vite build --mode e2e
ORCA_BACKGROUND_LAUNCH=1 node tests/tools/editor-ghost-tab-heal-repro.mjs --data <profile-dir-or-json>

--data accepts a profile directory (…/orca/profiles/local-default, the default) or a JSON file (an orca-data.json or an exported profile).

Profiles migrated to SQLite keep their state in profile-state.db; their orca-data.json is refreshed only at clean shutdown, so while Orca runs it is stale. When both files exist the tool warns and reads the database. For a consistent snapshot, quit Orca first, or pass a retained JSON export (orca profile state exports lists them; an export can be older than the live state). Reading the database needs Node 22.13+.

The database is copied to a temp dir before it is opened, and every write goes to a fresh temp profile seeded from a sanitized copy (agent relaunch, drafts and autosave stripped).

Real-app evidence (store snapshots, paths abbreviated)

Baseline in the copied store: 2 records for fileA.csv (both owned by the remote runtime), 4 for fileB.txt (1 × null, 3 × remote); three editor tabs for those paths, two with composite editor:<worktreeId>:<remote-runtime>:<path> ids and one uuid, all stamped executionHostId: "runtime:<remote-runtime>".

Route evidence read from the live store before the heal ran:

"worktreeCatalogRows": [ { "hostId": "local", "runtimeOwnerEnvironmentId": null } ],
"detectedWorktreeRows": [ { "hostId": "local" } ]

Renderer console during hydration (once):

[editor-hydration] one-time heal of persisted editor state for <worktreeId>: dropped 4 duplicate record(s), re-owned 2, kept 0 divergent-draft group(s) apart, 0 draft(s) moved to the reopen stack

After hydration:

{ "openFileRecords": [
    { "id": "<repo>/…/fileA.csv", "runtimeEnvironmentId": null, "isDirty": false },
    { "id": "<repo>/…/fileB.txt", "runtimeEnvironmentId": null, "isDirty": false } ],
  "editorTabsForPaths": [
    { "id": "<repo>/…/fileA.csv", "executionHostId": "local", "contentType": "editor" },
    { "id": "<repo>/…/fileB.txt", "executionHostId": "local", "contentType": "editor" } ],
  "tabsByContentType": { "editor": 2, "terminal": 5 } }

Restart pass from the flushed session: healLines: [], openFileCountByPath: { "<repo>/…/fileA.csv": 0, "<repo>/…/fileB.txt": 0 }, editorTabsForPaths: [].

Review

Please look hardest at resolveHealableWorktreeOwnerRoute (fail-closed for folders) and planHealedPersistedEditorFiles (owner normalization + tie-breaks). Healing is deliberately asymmetric: an unstamped folder row does not heal, an unstamped git worktree does not heal; only written-down ownership does.

Agent skill upstream boundary

  • Not applicable.

Notes

No wire, RPC, dependency or platform-specific change. Persisted shape unchanged (no stateSchemaVersion bump). Remote/SSH records are never stat'ed or pruned on loss of contact; owners are rewritten only when the worktree's stamped route positively resolves.

Recovered drafts live on the in-memory reopen stack (capped at 10) for the session in which the heal ran; one that is not reopened before the app exits is gone. Before this PR the same draft was dropped outright at hydration, so this is strictly better, but not durable; persisting the reopen stack would be a schema change and is out of scope. The collision message is a toast rather than an inline notice for the same reason; it repeats on every reopen press until the live tab is saved or closed.

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
📝 Walkthrough

Walkthrough

The change deduplicates persisted editor records and remaps active and front-matter state to surviving IDs. Hydration heals eligible owner routes, aligns editor tab hosts, preserves divergent drafts for reopening, and removes clean orphan records. Closing a document sweeps its same-document siblings and tabs. Active-file selection rejects unknown IDs. Tests cover these paths, and an Electron tool reproduces ghost-tab behavior across hydration, close, flush, and restart.

Fixed issue severity: Medium

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟠 High · up to 9bdaa

The change still risks restored ghost tabs and loss or incorrect conflict handling of unsaved editor state. These issues should be fixed before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR implements the duplicate collapse, stamped-owner healing, reference migration, atomic close sweep, orphan cleanup, and divergent-draft recovery requirements in [#21122] and [#17185]. The hydrat… Add restore-time handling for missing local editor files so deleted documents do not enter restored editor or recent-tab state. Preserve records that cannot be verified, such as remote records. Add an automated hydration test for a persiste…
Docstring Coverage ⚠️ Warning Docstring coverage is 35.63% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 87 functions across 28 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed The production changes, tests, draft recovery logic, and reproduction tool support [#21122] and [#17185]. They address duplicate records, owner healing, reference migration, close behavior, orphan cle…
Title check ✅ Passed The title clearly and concisely describes the main change: healing duplicate and mis-owned editor records during restore.
Description check ✅ Passed The description is comprehensive and covers the required explanation, changes, rationale, linked issues, visual proof, testing, review notes, compatibility considerations, and checklist. It also docum…
Full details: Linked Issues check

Explanation

The PR implements the duplicate collapse, stamped-owner healing, reference migration, atomic close sweep, orphan cleanup, and divergent-draft recovery requirements in [#21122] and [#17185]. The hydration code only removes clean records that have no editor tab. It does not verify that a local editor path exists, so a persisted tab for a deleted file can still restore or remain available to recent-tab navigation. The reviewed tests do not cover a missing local path.

Resolution

Add restore-time handling for missing local editor files so deleted documents do not enter restored editor or recent-tab state. Preserve records that cannot be verified, such as remote records. Add an automated hydration test for a persisted tab with a missing local path.

  • 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: 5


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 5c9ebd69-0c41-4a54-be90-90a2dcd59795

📥 Commits

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

📒 Files selected for processing (20)
  • 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-recently-closed-tabs.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/actions/recently-closed-editor-tabs.ts
  • src/renderer/src/store/slices/editor/file-ids/editor-file-ids.ts
  • src/renderer/src/store/slices/editor/file-ids/hydrated-editor-owner-healing.ts
  • src/renderer/src/store/slices/editor/file-ids/orphan-editor-file-ids.ts
  • src/renderer/src/store/slices/editor/types/open-file.ts
  • src/renderer/src/store/slices/stale-editor-tab-owner-healing.test.ts
  • src/renderer/src/store/slices/stale-editor-tab-resurrection-fixture.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
  • tests/tools/editor-ghost-tab-heal-repro.mjs

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

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
@BearMett
BearMett force-pushed the fix/stale-editor-tab-resurrection branch from dc708d1 to 4d1b135 Compare September 17, 2026 02:18

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

Important

One correctness issue in the heal plan that the current tests do not catch, plus two lower-severity notes.

Reviewed changes

Hydration-time repair of duplicate / mis-owned persisted editor records, together with the stacked writer and close-sweep changes from #21124 that ship in this diff.

  • Owner healing module (hydrated-editor-owner-healing.ts, new) — resolves a worktree owner from stamped evidence only (focus suppressed) and plans owner normalization, sibling merges, and recoverable drafts.
  • Hydration integration (hydrate-editor-session.ts) — applies the plan, redirects superseded ids onto the survivor, re-stamps contradicting editor tabs, sweeps clean orphans, and parks recoverable drafts on the reopen stack.
  • Orphan sweep (orphan-editor-file-ids.ts, new) — drops clean documents with no editor-family tab at hydration and reconciliation.
  • Writer collapse (workspace-session-editor-records.ts, workspace-session.ts) — the session writer merges live records that restore as a single document.
  • Close sweep (close-file-action.ts, editor-file-ids.ts) — a close takes every same-document record and its tabs while keeping unsaved siblings.
  • Draft recovery (recently-closed-editor-tabs.ts, open-file.ts) — ClosedEditorTabSnapshot.dirtyDraftContent plus reopen restores the buffer.
  • Tests, fixture, repro tool — stale-editor-tab-owner-healing.test.ts, stale-editor-tab-resurrection-fixture.ts, editor-close-file-sibling-sweep.test.ts, tabs-reconciliation-orphan-editor-files.test.ts, tests/tools/editor-ghost-tab-heal-repro.mjs.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek 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: 5


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 73fa0443-0fb3-484b-87ec-34488bb9850e

📥 Commits

Reviewing files that changed from the base of the PR and between dc708d14c0709b8d3aedb18cb5c77b9acc74e6df and 4d1b135cc5c374d47abfc13e288d2881db0606f5.

📒 Files selected for processing (17)
  • src/renderer/src/lib/workspace-session-editor-records.ts
  • src/renderer/src/lib/workspace-session.test.ts
  • src/renderer/src/store/slices/editor-close-file-sibling-sweep.test.ts
  • src/renderer/src/store/slices/editor-recently-closed-tabs.test.ts
  • src/renderer/src/store/slices/editor/actions/hydrate-editor-session.ts
  • src/renderer/src/store/slices/editor/actions/recently-closed-editor-tabs.ts
  • 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/editor-file-ids.ts
  • src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts
  • src/renderer/src/store/slices/editor/file-ids/hydrated-editor-owner-healing.ts
  • src/renderer/src/store/slices/editor/file-ids/orphan-editor-file-ids.test.ts
  • src/renderer/src/store/slices/editor/file-ids/orphan-editor-file-ids.ts
  • src/renderer/src/store/slices/stale-editor-tab-owner-healing.test.ts
  • src/renderer/src/store/slices/tabs/tabs-reconciliation-orphan-editor-files.test.ts
  • src/renderer/src/store/slices/tabs/tabs-session-actions.ts
  • tests/tools/editor-ghost-tab-heal-repro.mjs

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

@pullfrog

pullfrog Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Run failed. View the logs →

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…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
@BearMett
BearMett force-pushed the fix/stale-editor-tab-resurrection branch from 4d1b135 to a928e41 Compare September 17, 2026 02:55

@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: 2

Caution

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

⚠️ Outside diff range comments (1)

🟠 Major · Include dirty draft content in close-all snapshots. · recently-closed-editor-tabs.ts:197-204

src/renderer/src/store/slices/editor/actions/recently-closed-editor-tabs.ts:197-204
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Include dirty draft content in close-all snapshots.

closeAllFiles omits s.editorDrafts[f.id] from each snapshot, then removes the closed files' drafts from editorDrafts. Reopening restores content only from snapshot.dirtyDraftContent, so the unsaved buffer is lost.

Add the draft content before removing it from editorDrafts.

Proposed fix
           const { id: _id, isDirty: _dirty, mirroredFromRuntimeSession: _mirrored, ...snap } = f
+          const dirtyDraftContent = s.editorDrafts[f.id]
           const position = positionIndex.positionFor(f.id)
           nextRecentClosed = [
             {
               ...(snap as ClosedEditorTabSnapshot),
               reopenId: f.id,
+              ...(dirtyDraftContent !== undefined ? { dirtyDraftContent } : {}),
               ...(position ? { position } : {})
             },

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: c17c7695-cbb2-455e-845e-0a2cbebec8a8

📥 Commits

Reviewing files that changed from the base of the PR and between 4d1b135cc5c374d47abfc13e288d2881db0606f5 and a928e41ec99b02a5f83cc5e669f9ffe86fe49318.

📒 Files selected for processing (11)
  • src/renderer/src/store/slices/editor-recently-closed-tabs.test.ts
  • src/renderer/src/store/slices/editor/actions/hydrate-editor-session.ts
  • src/renderer/src/store/slices/editor/actions/parked-recovered-editor-drafts.test.ts
  • src/renderer/src/store/slices/editor/actions/parked-recovered-editor-drafts.ts
  • src/renderer/src/store/slices/editor/actions/recently-closed-editor-tabs.ts
  • 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/hydrated-editor-owner-healing.ts
  • src/renderer/src/store/slices/editor/file-ids/orphan-editor-file-ids.ts
  • src/renderer/src/store/slices/stale-editor-tab-owner-healing.test.ts
  • tests/tools/editor-ghost-tab-heal-repro.mjs

Included review availability: Your plan provides up to 10 included reviews per hour; 6 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

The delta since the prior pullfrog review is the single commit a928e41ec9 ("keep a parked recovered draft reachable and re-verify its disk baseline"), which closes out the last open finding from the initial review and hardens the recovered-draft reopen path.

  • Recovered drafts carry their disk baseline — buildRecoveredDraftSnapshot now includes lastKnownDiskSignature, and reopenClosedEditorTab sets it plus pendingDiskBaselineVerification when a baseline exists, so a restored dirty buffer gets the same changed-on-disk protection as a hydrated dirty record.
  • Shared parkRecoveredEditorDrafts — the editor snapshot stack and the cross-type kind stack now move through one helper used by both hydration and the already-open reopen branch, so a re-parked snapshot keeps a matching 'editor' kind entry instead of becoming unreachable.
  • No-op apply for an identical live draft — when a reused live record already holds the snapshot's exact text, reopen applies it instead of parking a duplicate it could never reach.
  • Stale position dropped on park — the park branch no longer calls restoreRecentlyClosedTabPosition, so the user's live tab is not dragged by the snapshot's old index.
  • Repro tool reports dangling entries — the ghost-tab repro falls back to an encoded-path match for tab-order entries whose tab is gone from unifiedTabs, which is the ghost it exists to find.

The three prior findings (ownerNormalized on divergent-draft survivors, the missing recovered-draft baseline, and the coarser close-sweep identity) are all resolved, and the open thread from the initial review was retired. The 35 focused tests for the touched modules pass locally.

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

@BearMett
BearMett force-pushed the fix/stale-editor-tab-resurrection branch from e425beb to 2b6c27d Compare September 17, 2026 03:33

@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

The delta since the prior pullfrog review is the single commit e425bebf64 ("decide a recovered draft's collision before opening it"), which corrects the collision handling the previous commit had placed after openFile.

  • Collision decided before the open — reopenClosedEditorTab now resolves the live record by editorDocumentIdentityKey before calling openFile, so a colliding snapshot can no longer grow a second unified tab in its own group, and an identical live draft is activated without rewriting the live record's newer lastKnownDiskSignature.
  • Unlandable drafts defer to the tail — the new deferRecoveredEditorDraft (backed by appendRecentlyClosedTabKind) queues the snapshot and its kind at the back of both reopen stacks, so a draft that cannot land yet no longer blocks terminal/browser reopens behind it.
  • liveTail dropped from isOwnerHealable — a writable live-tail record is now treated as writable (the identity key already reads liveTail only on read-only rows), with a test that its stale owner is healed.
  • Repro tool hardened — the dangling-entry path fallback is wrapped in safeDecode, so one opaque id containing a stray % cannot abort the scan.

The prior finding that a colliding draft parked at the head blocked other tab types is resolved. The 76 focused tests for the touched modules pass locally, and pnpm tc:web reports only the pre-existing NativeChatMessageList.windowing.test.tsx unused-import error present on main.

Pullfrog  | View workflow run | Using DeepSeek 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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 9c0ac6ef-ef15-45bd-b1a6-60b6432ed348

📥 Commits

Reviewing files that changed from the base of the PR and between a928e41ec99b02a5f83cc5e669f9ffe86fe49318 and 2b6c27dbd24fbd0e94166cd86797713ec5116319.

📒 Files selected for processing (9)
  • src/renderer/src/store/slices/editor-recently-closed-tabs.test.ts
  • src/renderer/src/store/slices/editor/actions/parked-recovered-editor-drafts.test.ts
  • src/renderer/src/store/slices/editor/actions/parked-recovered-editor-drafts.ts
  • src/renderer/src/store/slices/editor/actions/recently-closed-editor-tabs.ts
  • src/renderer/src/store/slices/editor/file-ids/editor-document-identity.test.ts
  • src/renderer/src/store/slices/editor/file-ids/hydrated-editor-owner-healing.ts
  • src/renderer/src/store/slices/recently-closed-tabs.test.ts
  • src/renderer/src/store/slices/recently-closed-tabs.ts
  • tests/tools/editor-ghost-tab-heal-repro.mjs

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

…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
@BearMett
BearMett force-pushed the fix/stale-editor-tab-resurrection branch from 2b6c27d to 9bdaadf Compare September 17, 2026 03:44

@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

The delta since the prior pullfrog review is the amended 2b6c27dbd2 ("decide a recovered draft's collision before opening it"), which adds one piece to the previous commit's collision path.

  • Collision activation raises the editor surface — the new activateLiveRecord runs setActiveFile and then buildEditorActiveResult (setActiveFile alone promotes the tab within its group but leaves the active surface on a terminal), so the toast naming the document the user must act on is actually shown. Tests now seed activeTabType: 'terminal' and assert both activeTabType and activeTabTypeByWorktree come back as 'editor' for the identical-draft and deferred-draft branches.

The 47 focused tests for the touched modules pass locally.

Pullfrog  | View workflow run | Using DeepSeek 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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: c9233823-3015-4254-ac4b-3f77c02dc4f3

📥 Commits

Reviewing files that changed from the base of the PR and between 2b6c27dbd24fbd0e94166cd86797713ec5116319 and 9bdaadf29ad5e4375eb8f8c9d421d3df22ca4ce5.

📒 Files selected for processing (5)
  • 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/file-ids/orphan-editor-file-ids.test.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

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

@pullfrog

pullfrog Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Run failed. View the logs →

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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
@BearMett
BearMett force-pushed the fix/stale-editor-tab-resurrection branch from 9bdaadf to 127e16f Compare September 17, 2026 04:18
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
Stores written before the write-path dedupe already hold duplicate and
mis-owned OpenFile records, so hydration repairs them once:

- Normalize record owners to the worktree's stamped route only (git: the
  explicit catalog route; folder: the written executionHostId/connectionId or
  restored runtime host). Unresolvable routes and read-only/live-tail/
  external-SSH records are never rewritten.
- Merge the siblings that normalization exposes and redirect their superseded
  ids through the existing editor-file-id migration, so tabs and groups
  pointing at a dropped record follow the survivor.
- Correct tab executionHostIds that contradict the record's route.
- Park same-owner divergent drafts on the reopen stack, where Mod+Shift+T
  restores the buffer along with the tab.

Refs stablyai#17185 stablyai#17778
… workspace session

Copies an orca-data.json into an isolated user-data dir, auto-detects
(worktree, path) pairs with more than one OpenFile record or mixed
runtimeEnvironmentId owners, launches Orca with ORCA_BACKGROUND_LAUNCH=1,
and records: the hydration heal line, openFiles/unifiedTabs/tabGroups
for those paths before and after, closeFile + Control+Tab, the flushed
session, and a restart pass. Persisted terminal tabs lose launchAgent so
a dead PTY cannot relaunch an agent CLI. The real profile is only read.

Refs stablyai#17185 stablyai#17778

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY
- The heal groups records with the shared editorDocumentIdentityKey, so its
  notion of one document is the same one the session write and the close sweep
  use. It keys on the bucket's worktreeId: a record whose own worktreeId drifted
  is the corruption being merged, not a reason to split the group.
- A recovered draft no longer overwrites a live record. reopenClosedEditorTab
  now checks whether openFile reused a record that already holds unsaved work;
  if it did, the snapshot goes back on the reopen stack and the user is told the
  document is already open with unsaved changes.
- ownerNormalized is true only when the survivor's own owner equals the route's,
  so a divergent-draft survivor that kept a verbatim owner no longer has its tabs
  re-stamped onto a host its record does not follow.
- The ghost-tab repro matches group tab-order entries through their tab entityId
  instead of a substring of the id text, and checks survival per tracked path.

Refs stablyai#17185 stablyai#17778

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY
…s disk baseline

A draft the restore heal could not give a tab of its own is parked on the
editor reopen stack. Three things kept it from coming back intact:

- The snapshot dropped `lastKnownDiskSignature`, so the restored tab had no
  baseline for the conflict scan and autosave could clobber an offline write.
  The snapshot now carries it, and reopen re-verifies it the way a hydrated
  dirty record does.
- Re-parking a snapshot the live record could not absorb pushed it back onto
  the editor stack without its cross-type reopen entry, which made the draft
  unreachable and sent later editor closes to the back of the queue. Both
  stacks now move through one `parkRecoveredEditorDrafts`, shared with
  hydration, and the toast tells the user how to get the draft back.
- The park branch also restored the snapshot's stale tab position, moving the
  user's live tab; and a snapshot identical to the live draft parked instead of
  applying as the no-op it is.

The ghost-tab repro tool reports a dangling tab-order entry again: an entry
whose tab is gone from `unifiedTabs` is exactly the ghost it exists to find.

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY
The park branch in reopenClosedEditorTab detected the collision after
openFile had already run, so the snapshot's group could grow a second
unified tab for the live record, the identical-draft fall-through
overwrote the live record's newer disk baseline, and the re-pushed
'editor' kind sat at the head of the cross-type reopen stack until the
user saved that one document.

Resolve the live record by document identity before the open, and queue
a draft that cannot land yet at the back of both reopen stacks.

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY
Four ways an unsaved buffer could still be lost or corrupted around the restore
heal:

- A read-only row and a writable row for one path resolve to the same owned id,
  so the writable row was skipped and its draft dropped. Park it on the reopen
  stack instead, and report it in the heal warning.
- The divergent-draft branch parked read-only rows too, and a reopen snapshot
  restores writable: a log tab came back as a dirty editable buffer. Never park
  a read-only row's draft.
- Reopen onto a clean read-only record consumed the snapshot: openFile's reuse
  rule ignores readOnly, and setEditorDraft/markFileDirty hard no-op there.
  Defer the snapshot and tell the user to close the log first.
- The editor id migration can redirect a local tab and a runtime-owned tab in
  one group onto the same document, which the tabs-hydration dedupe ran too
  early to see. Dedupe again after the migration and repoint the group's order,
  MRU and active tab at the survivor.

Also: align healed tab hosts by execution-host alias, so an SSH worktree with a
paired hub stops rewriting correct `runtime:<hub>` stamps on every hydration;
sanitize drafts, disk baselines and `editorAutoSave` out of the repro tool's
copy, since its rows keep absolute paths into the developer's real files; and
correct the "one-time heal" and "the close could not keep this buffer open"
wording, neither of which was true.

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

The delta since the last pullfrog review is 9bdaadf..127e16f (7 commits): draft-preservation hardening at hydrate and reopen, the pinned-sibling close-sweep rule, dedupe within groups after the id rewrite, alias-aware tab host alignment, and repro-tool sanitization.

  • Read-only drafts are never parked — the heal's divergent-draft branch skips a read-only row's draft (a reopen snapshot restores writable), and the hydration id-collision skip now parks a writable row's draft when a read-only row for the same path claimed the id.
  • Reopen never consumes a draft it cannot apply — when openFile reuses a read-only record, reopenClosedEditorTab defers the snapshot back onto the reopen stack and toasts instead of writing a draft that would hard no-op.
  • Pinned same-document siblings survive the close sweep — a pinned editor-family tab for the swept document is kept (the named id still closes), matching the isPinned "survives close others" contract.
  • Post-migration tab dedupe — migrateHydratedEditorTabsAndGroups collapses a redirected local/runtime pair into one editor tab per group and repoints tabOrder / recentTabIds / activeTabId through the dedupe aliases.
  • Alias-aware host alignment — an SSH route transported through a paired hub accepts either the ssh: host or the runtime: hub stamp, so those tabs are no longer re-stamped on every hydration.
  • Repro tool hardening — the copied store drops dirtyDraftContent / lastKnownDiskSignature and forces editorAutoSave off, so a restored draft cannot be autosaved into the developer's real file.
  • Tests — new coverage for the pinned sweep (3), read-only draft parking at hydration (4), the reopen read-only guard (2), host alignment (2), and a new hydrated-editor-file-ids.test.ts (3).

102 focused tests across the touched modules pass. pnpm run typecheck:web reports only the pre-existing NativeChatMessageList.windowing.test.tsx unused-import error present on main. All three prior pullfrog threads are addressed and resolved.

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

A duplicate group can hold the same draft twice with only one copy carrying the
disk baseline, and the heal kept whichever came first — the restored draft then
had nothing for the conflict scan to verify. The survivor is now the equal-draft
copy that still has a baseline.

The pre-open collision check keyed on the full document identity, which includes
readOnly, so a writable snapshot never matched a live read-only log even though
openFile reuses that record anyway — the reopen then hung a second tab for the
log in the snapshot's group. It now compares the path and owner only, and treats
a read-only match like a rival draft: activate, defer, tell the user. A reused
record already holding the snapshot's exact text consumes it instead of
rewriting its newer baseline, and both collision toasts are localized.

Parking pushed one reopen-stack kind per recovered draft even when the cap threw
the draft away, leaving the cross-type reopen popping editors that were not
there; kinds now follow what the stack kept, and the heal warning reports what
the cap lost. The heal's tab dedupe carries a dropped twin's pin and labelling
onto the survivor, so a pinned duplicate no longer comes back unpinned.

The repro tool matched tabs to paths by bare file path, so every healed tab
carrying an owned composite id was invisible to it; it now resolves both shapes,
counts a tab with no record left as affected, and checks the restart snapshots
for survivors. Its session reading moved into a module of its own.

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY
@BearMett
BearMett force-pushed the fix/stale-editor-tab-resurrection branch from 127e16f to c684961 Compare September 17, 2026 05:00

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

Important

hydrated-editor-file-ids.ts gained a literal NUL byte at line 142, which makes Git treat the whole file as binary. It now has no diff hunks and no blame, and the changed-lines quality gate silently skips every future edit to it — including the pin-carry logic added in this very commit.

Reviewed changes

The delta since the prior pullfrog review (127e16f) is the rebased eight-commit tail of the branch ending at c684961, which re-lands the heal/collision/lifecycle work plus this commit.

  • Merged baselines are carried — the session writer and the heal's pickSurvivor now keep the equal-draft copy that still has lastKnownDiskSignature, so a merged duplicate no longer restores a draft with nothing for the conflict scan to verify.
  • Collision is decided on a surface-blind key — editorDocumentPathOwnerKey ignores readOnly/liveTail to match openFile's reuse rule, a read-only twin is treated like a rival draft (activate + defer + toast), and recoveredDraftBlockedMessage localizes both toasts.
  • Reopen-stack kinds stay paired — parkRecoveredEditorDrafts counts only retained snapshots, deferRecoveredEditorDraft no-ops on a full stack, and the heal warning reports drafts lost to the cap.
  • Deduped editor tabs keep a dropped twin's decoration — pin, custom label, and colour are moved onto the survivor before dedupeEditorTabsWithinGroups.
  • Orphan sweeps are per worktree — collectHydratedOrphanEditorFileIds returns a Map<worktreeId, Set<id>> with isOrphanEditorFile, and the reconciliation fold filters each worktree with its own set, so a bare-path id live in another workspace is no longer swept.
  • Every mirrored tab is closed — notifyHostOfMirroredEditorClose filters all matching tabs instead of the first.
  • Repro tool split — session reading moved to editor-ghost-tab-session-scan.mjs, matched to paths through editorEntityPath, and the survivor check now scans every post-close snapshot.

⚠️ A raw NUL byte makes hydrated-editor-file-ids.ts undiffable

carryEditorTwinDecorationOntoSurvivor builds its key with a literal NUL byte between groupId and entityId. Git auto-detects the file as -text (git diff --stat reports Bin 7128 -> 9737 bytes, the PR's own diff renders (binary file or no changes)), so reviewers and the changed-lines lint gate see no hunks for this file at all. Functionally the separator works, but it permanently costs the file its diff/blame and silently exempts it from the repo's changed-code quality checks.

Technical details
# Raw NUL byte in source makes Git treat the file as binary

## Affected sites
- `src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts:142` — the dedupe key `` `${tab.groupId}<0x00>${tab.entityId}` `` embeds a literal NUL byte.
- Verified: `HEAD` has one NUL at byte 4641; `HEAD~1` and `origin/main` have zero — this commit introduced it.
- Consequence: the full PR diff for this file is `(binary file or no changes)`, so the pin-carry change is invisible to review tooling and to the changed-lines code-quality gate.

## Required outcome
- Keep the separator unambiguous without a raw control byte so the file stays text, e.g. `${tab.groupId}\u0000${tab.entityId}` (escape, not the byte) or `JSON.stringify([tab.groupId, tab.entityId])`.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…e diffable

A raw NUL byte sat inside the twin-decoration key template, so git classified
the file as binary and no review surface could render its diff. The escape
sequence builds the same key at runtime and keeps the file text.

An equal-draft collision consumed the snapshot without applying its disk
baseline. When the live record carried no baseline of its own, the restored
draft had nothing for the conflict scan to verify, so autosave resumed over an
unknown disk state. Both consumed branches now adopt the snapshot's baseline —
only when the record has none, since a stale one would manufacture a conflict.

A deferred recovered draft was dropped silently once the reopen stack hit its
cap, which the post-open defer can reach. It now evicts the oldest entry that
holds no unsaved text, so the only copy of the recovered draft survives, and
warns either way — a stack full of drafts still drops the incoming one rather
than trading one unrecoverable buffer for another.

Claude-Session: https://claude.ai/code/session_01JZkq8eDTYZ5WUMEs7yRKEY
The path-owner variant was inserted between the comment and
editorDocumentIdentityKey, leaving the comment on the wrong function.

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

Copy link
Copy Markdown
Contributor Author

Replying to the Pullfrog review posted on c684961979: the literal NUL byte in hydrated-editor-file-ids.ts is replaced with the escape sequence in ace34df, so the PR diff for that file renders again (git show of the intermediate commit still reports binary because its parent blob holds the byte).

@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 this increment. The only outstanding item is the prior review's JSDoc-placement note on editor-document-identity.ts, which this commit did not touch — its thread stays open, so this is not an approval.

Reviewed changes

The delta since the prior pullfrog review is ace34dfe2c ("keep the recovered-draft baseline and the healed tab file diffable"), which resolves the previous review's raw-NUL finding and closes two draft-preservation gaps on the reopen path.

  • The healed tab file is diffable again — carryEditorTwinDecorationOntoSurvivor now builds its dedupe key with the \u0000 escape instead of a literal NUL byte, so Git classifies hydrated-editor-file-ids.ts as text and the full-vs-main diff renders it (the c684961→ace34df commit diff is still binary only because the parent blob held the byte). The runtime key is unchanged.
  • A baseline-less equal-draft collision keeps its baseline — both equal-draft branches in reopenClosedEditorTab now call adoptSnapshotDiskBaseline, which copies the snapshot's lastKnownDiskSignature and sets pendingDiskBaselineVerification only when the live record has no baseline of its own, so autosave cannot resume over an unverified disk state.
  • A deferred draft survives the reopen cap — deferRecoveredEditorDraft now evicts the oldest draft-less entry and appends the incoming snapshot rather than dropping it silently; if every entry holds unsaved text it drops the incoming one and warns. The kind stack is left untouched because the snapshot-stack length is unchanged, preserving cross-type pairing.
  • Frontmatter survivor filtering simplified — hydrate-editor-session.ts passes survivingFileIds straight through; the removed usedOpenFileIds ∩ survivingFileIds intersection was identical to it.
  • Tests — two baseline-adoption tests (direct record and WSL-alias reuse) plus two cap-eviction tests. All 81 focused tests across the touched modules pass locally.

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

@BorjaLL

BorjaLL commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Field data from a real store on Orca 1.4.212 (macOS arm64), with the Mac paired to a Windows PC and two MacBook Airs. The same symptom shows up on the PC's own store (two README.md tabs that reopen after close).

I ran tests/tools/editor-ghost-tab-session-scan.mjs from this PR, read-only, against profiles/local-default/orca-data.json. It flagged 5 worktrees. All are local Mac worktrees, but the records are stamped with remote owners:

worktree (masked) records for one path owners on the records editor tabs repeated in group
A 8 PC, MacAir2, PC (second pairing) 5 1
B 8 PC, MacAir2, PC (second pairing) 5 1
C 8 PC, MacAir2, PC (second pairing) 5 1
C (second path) 6 MacAir2, PC (second pairing) 4 1
D 7 none, MacAir2, PC (second pairing) 4 1
E 4 MacAir2, PC (second pairing) 3 1

Correction to my first read: b0c12031 is not stale, it is the same Windows PC paired a second time over Wi-Fi (Ethernet and Wi-Fi addresses, two environment ids). So one physical remote host contributes two owner ids for the same local file, which is why the user sees exactly two tabs. This matches the mis-owned plus duplicate shape the heal in #21125 targets, and the growth that #21124 stops at the write path.

I'm going to run a local build of main + #21124 + #21125 on both the Mac and the PC and will report back whether the tabs stay closed across restarts and host sync. It would be great to get a maintainer review on #21124 and #21125, since this affects anyone with paired hosts. Related issue: #17778.

@BorjaLL

BorjaLL commented Sep 26, 2026

Copy link
Copy Markdown
Contributor

Follow-up from running main (f9a4ca5, 2026-09-26) + #21124 + #21125 as a local Windows build on the PC host. The Mac client paired to it is still on 1.4.212.

What the heal fixed: the affected README's openFilesByWorktree records went from 4 identical rows to 1, and no duplicate (path, runtimeEnvironmentId) keys are left anywhere in the migrated workspaceSession document.

What still resurrects the tab: after a close, and after restarts, the same README reopens. The persisted unifiedTabs for that worktree hold the editor tab twice with the identical tab id:

editor:<worktreeId>:b0c12031-...:<path>/README.md   (contentType editor)
editor:<worktreeId>:b0c12031-...:<path>/README.md   (contentType editor)

The surviving OpenFile record for the same path is owned by a different runtime (757d6600-...), not b0c12031-.... b0c12031 is the environment id the Mac client uses to address this PC (its second pairing, over Wi-Fi). So the host keeps a tab owned by the client's environment id for a host-local file, repeated inside one group, and its entity no longer matches the healed record.

It looks like the heal handles the OpenFile side but leaves (a) repeated identical tab ids inside one group and (b) a tab whose owner segment disagrees with the healed record's owner. One open question on my side: the paired Mac client still runs 1.4.212, so it could be the thing re-pushing the tab. I haven't ruled that out yet.

Side note for anyone else building locally: main now migrates the profile to profile-state.db on first launch, so testing this branch against a real profile is effectively one-way for a 1.4.212 install.

…g owner-leaked records

Upstream moved profile state into SQLite (profiles/<id>/profile-state.db). A migrated
profile keeps a stale orca-data.json that is only refreshed at clean shutdown, so a
repro that reads that JSON while Orca runs scans an outdated session. The heal itself is
unaffected: workspaceSession is stored as an opaque JSON document, not reshaped.

The repro now takes a profile directory (the default) or a JSON file. It classifies the
profile like main's classifyProfileStateStorage (any .db/-wal/-shm/-journal counts as
migrated), reads every domain from profile_state_documents when a database exists
(warning and preferring it when the JSON also exists), and falls back to the JSON
otherwise. All domains are loaded, not just the session, because the seeded app needs
the catalog to route the heal. The source is never opened in place: the database and its
WAL are copied to a temp dir first, since even a read-only WAL open touches -shm. The
isolated copy is still seeded as orca-data.json, and the post-flush reads go through the
same loader so a SQLite-capable build's flush is not missed.

This branch predates main's profile-state helpers, so the tool-side reader uses
node:sqlite directly. It has no bun:sqlite path because the tool runs under Node.

The scan gains two owner-leak rules. A record created through the UI-focus fallback
keeps the bare-path id of its first opener, so a scan keyed on duplicate ids misses it:
- tab-id-owner-mismatch: a path's editor tab ids encode owners (bare path = none,
  editor:<wt>:<runtime>:<path> = runtime) that differ from its records' owners.
- owner-differs-in-worktree: an owned record while another path in the same worktree
  has a different owner. The session has no worktree owner, so this cannot say which
  side leaked; auto-tracking may widen to those paths, which is harmless for the repro.
Each affected entry now lists its reasons.
@BearMett

Copy link
Copy Markdown
Contributor Author

Thank you for running this against a real store. Your second report is what let us find the layer that is still broken.

What your data shows. The record layer is now healed, which is what #21124/#21125 target. The tab that still comes back is a different shape: a unified editor tab whose entityId carries an owner (b0c12031) that no surviving OpenFile record has, so the tab has no backing record. Neither PR prunes that. The only startup code that drops such a tab is the worktree reconciliation, and at boot it runs only for worktrees with persisted terminal rows (reconcile-hydrated-workspace-tab-models.ts iterates session.tabsByWorktree). An editor-only worktree is never swept, so the orphan renders and is re-written on the next save.

On the identical tab id appearing twice in unifiedTabs. We booted our own pre-cleanup store, which had the same shape (two byte-identical tab ids, four tab ids naming a stale runtime, nine duplicate records), through this branch: it heals to one tab per file with no stale id, with or without terminal rows. The session writer does not dedupe by id, so the duplicate reaches disk, but hydration collapses it every boot. It is a real but self-healing defect, not what resurrects your tab.

On the 1.4.212 Mac. Snapshots flow from the host to paired clients, not back, so the Mac cannot push a tab into the PC's store. The orphan on the PC is store-side.

Next. The follow-up is up as #23361: it makes the boot-time sweep cover every worktree with persisted tabs and dedupes tab ids at write, with a regression test built from your shape. It targets main directly so it can land independently of these two.

@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

The delta since the prior pullfrog review is the single commit 1ef4a33 ("test(tools): read ghost-tab repro input from profile-state.db and flag owner-leaked records"). It touches only tests/tools/ — no src/ change.

  • Profile source loader — new editor-ghost-tab-profile-source.mjs reads a profile from either the legacy orca-data.json or the migrated profile-state.db, classifying storage the way main's classifyProfileStateStorage does and copying the database (plus -wal/-journal) to a temp dir before opening it. loadProfileState prefers the database and warns when both exist.
  • Owner-leak detection — editor-ghost-tab-session-scan.mjs gains editorEntityOwner and two more affected-pair reasons (tab-id-owner-mismatch, owner-differs-in-worktree) so the repro flags records whose owner leaked from UI focus, not just duplicate/mixed owners.
  • Repro driver — the heal repro now loads its input through loadProfileState, and reads its own post-flush state through it too (a SQLite-capable build flushes to profile-state.db, not the seeded JSON).
  • Tests — new editor-ghost-tab-session-scan.test.mjs covers the owner rules and the JSON/SQLite loader paths; 12/12 pass locally and it is picked up by config/vitest.config.ts's tests/tools/**/*.test.mjs include.

I verified the loader against origin/main: the storage-classification suffix family, the profile_state_documents columns, and the domain-keyed state shape all match readProfileStateParsedSnapshot. All prior pullfrog threads are resolved.

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

@pullfrog

pullfrog Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

Run failed. View the logs →

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@BearMett

Copy link
Copy Markdown
Contributor Author

Closing this PR. No replacement PR is open yet; this closes the proposal, not the underlying issue. I am considering a different approach to the same corrupted stores as a separate PR once #23361 lands, so it does not stack on an open PR.

This PR proposed restore-time owner normalization: moving records onto the workspace's stamped route and merging records for the same path. The locally prepared alternative instead saves each record's id, and restore keeps the saved owner fields. Same-path local, runtime and external-SSH records stay separate. Equivalent duplicates merge, and different unsaved drafts each come back in their own tab with autosave paused.

I deliberately dropped from this PR's approach:

  • Collapsing owners by path. Proving the right owner from stamped evidence is fragile, and a wrong guess attaches a draft to the wrong host.
  • Pruning records that no tab references. A missing reference is not evidence of a close.
  • Parking divergent drafts on the recently-closed stack. It holds at most 10 entries and is not saved, so a draft could still be lost at quit.
  • The background repro tool (tests/tools/editor-ghost-tab-heal-repro.mjs).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants