Skip to content

fix(editor): clean inactive restored tabs without hiding valid editors - #23361

Closed
BearMett wants to merge 9 commits into
stablyai:mainfrom
BearMett:fix/orphan-editor-tab-boot-prune
Closed

BearMett wants to merge 9 commits into
stablyai:mainfrom
BearMett:fix/orphan-editor-tab-boot-prune

Conversation

@BearMett

@BearMett BearMett commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When Orca quits, it saves your tabs and tab groups. On the next launch, it rebuilds them from that save. Some saves held tabs that the restore step always threw away, and some listed the same tab in two groups. Now the save step uses the same filter and the same tab-to-group rule as restore, so a saved group only lists tabs that restore keeps. Workspaces that only have editor tabs, with no terminals, are also cleaned at startup.

What Changed

This PR builds on @nwparker's continuation from 2026-10-05. The existing commits, including his, are unchanged. On top of them I added a merge of current main and one new commit.

Before

  • At startup, cleanup visited only workspaces that had saved terminal rows. A workspace with only editor tabs kept tabs whose file record was gone, and wrote them back on every restart. (Fixed by the earlier commits; unchanged here.)
  • The save step removed tabs that restore cannot bring back (invalid terminal ids, old html-preview:: rows, and diff or conflict tabs whose file was not saved). It still built each group's tab list from the unfiltered tabs, though. pullfrog showed the result: unifiedTabs = ['tab-editor'] but tabOrder = ['tab-editor', 'tab-diff'].
  • When one tab id was listed in two groups, the shared workspace-layout loader and the renderer's restore could choose different groups for it.
  • Closing the file behind a diff tab changed only openFiles. That change did not re-run the tab filtering, so the stale diff tab stayed on disk until some other tab change.

After

  • The save step shares the restorability filter and group-ownership rules with restore. It calls restore's own functions for:

    • the restorability check (canRestorePersistedTab);
    • collapsing duplicate views of one document within a group, keeping the pinned copy;
    • assigning each tab to one owning group;
    • picking the active group and layout.

    Group tab lists are now built from the filtered tabs.

  • The tab-to-group rule (resolveTabGroupOwners) moved to src/shared/workspace-layout/tab-group-ownership.ts. Renderer restore, the renderer save step, and the shared layout loader (resolveGroupOrder) all use it now. A valid declared group wins.

  • A tab whose group is missing is re-homed, not dropped. A missing group does not mean the user closed what was in it.

  • Duplicate editor views of the same document in the same group collapse to the pinned copy. Views of that document in other split groups are kept.

  • A change to openFiles alone now re-runs the tab save, so the diff tab above is dropped from disk when its file closes.

Main files: lib/workspace-session-unified-tabs.ts (save step), lib/workspace-session-patch.ts (re-run trigger), store/slices/tab-group-state.ts and tab-group-reference-repair.ts (shared steps pulled out of tabs-hydration.ts, which now calls them), shared/workspace-layout/tab-group-ownership.ts and workspace-layout-load-order.ts.

Why

Restore already repairs inconsistent groups, but the shared loader also consumes these groups, so the writer must keep them consistent.

Alternatives considered:

  • Leave the save step loose and rely on restore. Rejected because a second reader exists. The parity test below checks that the two readers agree on the same stored data.
  • Write separate cleanup rules for the save step. Rejected because they would drift from restore's. The save step calls restore's own functions instead.
  • Drop tabs whose group is missing. Rejected because that can delete live content the user never closed.

Transient tabs (diff, conflict review, html preview) are still kept in the live model. They are filtered only at the point where the renderer writes to disk. Parity case 5 pins that boundary.

Linked Issue

Fixes #27983

Related to #21121 and #23967. Both stay open: owner recovery, peer re-injection, and the many-tab reports are outside this PR.

Visual Proof

Startup cleanup (earlier commits). @nwparker's screenshots: an inactive orphan goes 1 → 0, and the real document still renders.

orca-editor-orphan-boot-before.png
orca-editor-orphan-boot-after.png

Saved groups (new commit). Nothing new is drawn on screen; the change is in what is written to disk. From workspace-session-unified-tabs.test.ts ("drops an unrestorable diff tab from the tab order of the group that still shows an editor"): one group holds an editor tab for an open file and a diff tab whose file is not open.

Before, as pullfrog's probe of the previous writer reported it:

unifiedTabs = ['tab-editor']
tabOrder    = ['tab-editor', 'tab-diff']

After, in the test's fixture (/x/a.ts is the editor tab, diff-tab the diff tab):

unifiedTabs: ['/x/a.ts']
tabGroups:   [{ id: 'group-1', tabOrder: ['/x/a.ts'], activeTabId: null, recentTabIds: ['/x/a.ts'] }]

Restart check on both heads (hidden Electron, temp profile, automated): open src/index.ts, pin its tab, quit, relaunch. On 9691aadf49 and on 22edc79e20 the document comes back in its pinned tab and the saved group lists only that tab. I could not build the orphan-in-group state through the live store (a tab for a file that is not open is refused at creation), so the writer change is shown by the unit test above, not by a screenshot.

Testing

Unit and integration tests, macOS. Earlier validation ran on 83ddb0da76. The appended head 22edc79e20 also includes main's subsequent changes; its own 64-file / 610-test run passed.

On 83ddb0da76:

  • Related suites: 84 test files and 881 tests pass. They cover the renderer workspace-session, tab-group, tab-hydration and orphan-prune suites, src/shared/workspace-layout, and src/renderer/src/store/slices/editor.
  • Broad renderer run (store/slices, lib, app-shell, components/editor): 1,401 files pass and 2 files (3 tests) fail. rich-markdown-escape-fidelity fails the same way on untouched main. palette-match-performance failed in the broad run; its cause has not been confirmed. - pnpm tc, pnpm run check:code-quality:changed, the layout-writer, focus-read and max-lines ratchets (no baseline raised), check:reliability-gates and check:compat-boundary-imports pass.
  • Hidden Electron on a temp profile (ORCA_BACKGROUND_LAUNCH=1): workspace-layout-oracle-headless 9 passed / 9 skipped, workspace-layout-oracle 21 passed, and persisted-session-production-upgrade 3 passed / 2 skipped. The oracle reports findings that are already on main's known list; it reported none outside that list.

On 22edc79e20 (@nwparker's head 9691aadf49, a merge of main 41fc9542b3, and one commit):

  • The A subset (workspace-session, parity, tab-group, hydration, orphan-prune, app-shell reconcile, src/shared/workspace-layout, store/slices/editor): 64 test files and 610 tests pass.
  • pnpm tc, pnpm run check:code-quality:changed, the layout-writer, focus-read and max-lines ratchets, check:reliability-gates and check:compat-boundary-imports pass.

New tests:

  • workspace-session-unified-tabs.test.ts:
    • An unrestorable diff tab is dropped from the group that still shows an editor (pullfrog's case).
    • A tab claimed by two groups is listed only in the group its own groupId names.
    • A group whose tabs were all filtered is removed, along with its active pointer and layout leaf.
    • Valid tabs whose group is gone are recovered.
    • What the save step writes, it reads back, and the shared loader places every tab in the same group.
  • workspace-layout-renderer-parity-tabs.test.ts. On the same stored data:
    • The shared loader and renderer restore pick the same owning group for a tab listed in two groups, whichever group is stored first.
    • The save step's output survives a shared load → save with no round-trip findings, and a second save equals the first.
    • Shared save and renderer restore bring back the same tabs and the same groups.
    • Transient tabs stay in the live model and are filtered only at the disk boundary.
  • workspace-session-patch.test.ts: an openFiles-only change re-runs the tab save. A diff tab is dropped from disk when only its backing file closes.
  • tab-group-state.test.ts: the pinned view and separate split groups are kept.
  • orphan-editor-tab-boot-prune.test.ts: editor-only workspaces are cleaned at boot.

Not run: Linux, Windows, a live SSH host.

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

AI Disclosure

Written with Claude Code (Claude Opus 5.5) and Codex (gpt-6-astra).

Review

Please look hardest at buildPersistedTabsAndGroups in workspace-session-unified-tabs.ts. It shares the filter and group-ownership rules with hydrateUnifiedFormat, and the parity test checks that both readers agree on what it writes.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • SSH and remote: this only changes tab and group records. No host, process, or file is touched. Which host partition a session is saved to is unchanged.
  • Folder workspaces: the save step and the startup cleanup key on the workspace id, whether the workspace is a git worktree or a folder.
  • Wire: No RPC fields or stream opcodes change. An older build reading the saved file gets the subset it would have kept anyway.
  • Performance: an openFiles-only change now also re-runs the tab save for that session write. Not measured.
  • The earlier "Shared CI repair" section is removed: main already has the same confirmHook lint fix, so after the merge the PR diff no longer includes it.

Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

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

@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
Walkthrough

Persisted unified tabs are filtered to valid groups, sorted, and deduplicated by tab ID. Hydrated workspace reconciliation now includes worktree IDs from both terminal rows and unified tabs. Tests cover duplicate tab persistence, workspace key reconciliation, and boot-time removal of editor tabs without a matching open file.

Priority: Low

Merge Risk: Low · up to e345b

Saved tab groups can be inconsistent when a tab ID appears in multiple groups, although startup repairs the state. This is a bounded persistence issue to fix or explicitly accept before merging.

Security architecture risk: Low · up to e345b

The change is confined to workspace-session restoration and saving. It closes a case where orphan editor tabs survived restart, and no new security exposure was established. An existing inconsistency in saved tab-group references remains a reason to treat the persistence contract carefully.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated changed behavior acts on saved tab state for workspace keys in the session. The inspected production startup path does not show a newly exposed request or authentication entrypoint.

Trust Boundaries and Controls

  • observed — Saved tab identity is checked against hydrated, workspace-indexed open-file state before an editor tab remains renderable. This is an existing reconciliation control now applied at startup to unified-tab-only workspaces.

Resilience and Maintainability Implications

  • inferred — Hydration repairs the pre-existing stale-group serialization case, limiting its demonstrated effect on restored renderer state. Whether another production reader uses the serialized groups without that repair remains unestablished.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks (4 passed)
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly describes the primary change: removing invalid restored editor tabs while preserving valid editors. It is concise and related to the pull request objectives.
Description check Passed The description is complete and follows the repository template. It explains the user impact, implementation, rationale, linked issue, testing, visual proof, compatibility considerations, performance …
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b8660273-9f10-4be2-aab3-0719f4641282

📥 Commits

Reviewing files that changed from the base of the PR and between 172083f and e345bc8611d1006e5032ebc72495e03c2afba298.

📒 Files selected for processing (5)
  • src/renderer/src/app-shell/reconcile-hydrated-workspace-tab-models.test.ts
  • src/renderer/src/app-shell/reconcile-hydrated-workspace-tab-models.ts
  • src/renderer/src/lib/workspace-session-unified-tabs.test.ts
  • src/renderer/src/lib/workspace-session-unified-tabs.ts
  • src/renderer/src/store/slices/orphan-editor-tab-boot-prune.test.ts

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ Minor suggestions only — one rough edge inline.

Reviewed changes — reviewed the full diff at e345bc8 (2 commits, 5 files) and verified the new tests fail against the pre-change source.

  • Widen startup tab reconciliation: reconcileHydratedWorkspaceTabModels now unions tabsByWorktree keys with unifiedTabs keys, so editor-only workspaces are reconciled at boot using the existing projectWorktreeTabModelReconciliation projection. Verified equivalent to the activation-time path: both fold the same projection, and hydrateEditorSession (which re-keys editor-family tabs to the owned OpenFile id) runs before the reconcile, so liveEditorIds is populated. No editor-family, markdown-preview, runtime, SSH, or folder-worktree divergence found.
  • Dedupe persisted unified tabs: the writer sorts by sortOrder/createdAt, filters to surviving groups, then reuses dedupeTabsById. See the inline note on the surviving-copy assumption.
  • Tests: confirmed the new orphan and cross-group assertions fail without the source change (4 failing assertions after reverting the two source files), so the coverage is real. The affected suites pass with the change (25 tests).

ℹ️ Nitpicks

  • reconcile-hydrated-workspace-tab-models.test.ts:19 passes unifiedTabs: { 'wt-a': [], 'wt-editor-only': [] } — both empty arrays — so the new assertion proves the key reaches the callback but never exercises a workspace that actually holds a tab. The end-to-end case is covered by orphan-editor-tab-boot-prune.test.ts, so this is purely a note on the unit test's scope.

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

@nwparker
nwparker force-pushed the fix/orphan-editor-tab-boot-prune branch from e345bc8 to eaef9c7 Compare October 5, 2026 10:09
@nwparker nwparker changed the title fix(tabs): prune orphan editor tabs at startup for worktrees without terminal rows fix(editor): clean inactive restored tabs without hiding valid editors Oct 5, 2026
@nwparker

nwparker commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Continued this PR with both @BearMett authored commits preserved, rebased onto c2c7649, and added an adversarial correction: restore admission now runs before persistence deduplication so an invalid row cannot hide a valid editor or its unsaved draft. Related tests: 176 across 18 suites pass. Real hidden cold starts confirm one inactive orphan on the base and none after the fix; the actual editor still renders after selection. Full typecheck/build/changed quality pass; full lint has only the two unchanged findings repaired by #25494. Updated the description with proof, source references, and limits. #21121 and #23967 remain open for their broader peer/ownership reports.

BearMett and others added 3 commits October 5, 2026 03:34
…terminal rows

Boot-time tab reconciliation only visited worktrees with persisted terminal
rows, so an editor-only worktree kept tabs whose OpenFile record no longer
existed; they rendered and were re-persisted on every restart. Reconcile every
worktree with persisted unified tabs too, and dedupe tab records by id when
writing the session.

Refs stablyai#21121
@nwparker
nwparker force-pushed the fix/orphan-editor-tab-boot-prune branch from eaef9c7 to 9691aad Compare October 5, 2026 10:53

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one persistence-hygiene note inline.

Reviewed changes — re-reviewed the commits since the prior pullfrog review at e345bc8. The branch was rebased; the reconciliation widening is unchanged in substance and was already reviewed. The prior inline concern — the writer's dedupe could persist a hydration-droppable copy that hides a live editor — is now addressed.

  • Sort and filter before dedupe: buildPersistedUnifiedTabSessionData now sorts by sortOrder/createdAt and filters to surviving groups before dedupeTabsById, so the surviving duplicate is the copy hydration prefers.
  • Shared validity predicate: extracted canRestorePersistedTab from the hydration filter and applies it writer-side before dedupe; tabs-hydration.ts now calls the same function, so an unrestorable copy (invalid terminal id, html-preview::, transient diff/conflict/check-details) can no longer hide a live editor or its unsaved draft.
  • Tests: added the cross-group dedupe case and an it.each over diff / html-preview:: / terminal duplicates. Ablation (removing the writer filter) fails all three it.each cases, so the coverage is real. 95 tests across the related persistence/hydration suites pass, plus tc:web and oxlint.

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

[...tabs]
.sort((a, b) => a.sortOrder - b.sortOrder || a.createdAt - b.createdAt)
.filter((tab) => groupIds.has(tab.groupId))
.filter((tab) => !snapshot.openFiles || canRestorePersistedTab(tab, persistedEditFileIds))

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.

Because groups is built from the unfiltered tabs (line 95) and persisted as tabGroups[worktreeId] (line 114), a tab this new filter drops can still remain in the group's tabOrder. Verified with a scratch probe: a diff tab sharing a group with a live editor persists unifiedTabs = ['tab-editor'] but tabGroups.wt[0].tabOrder = ['tab-editor', 'tab-diff']. Hydration filters dangling ids out (tabs-hydration.ts:146-147), so there is no runtime effect today, but the persisted record is left inconsistent; building the groups from the filtered tabs would keep it clean.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 22edc79. Group tab lists are now built from the tabs that pass the restorability filter, so a dropped diff tab no longer stays in its group's tabOrder. The shared loader also consumes these groups, so the writer must keep them consistent.

Covered by workspace-session-unified-tabs.test.ts ("drops an unrestorable diff tab from the tab order of the group that still shows an editor", your probe's shape) and workspace-layout-renderer-parity-tabs.test.ts.

Run the writer through the same validity, per-group dedupe and group-ownership
steps hydration uses, so a saved session holds exactly what restore keeps. The
ownership rule moves to shared/workspace-layout and the shared loader uses it
too. A valid declared group wins; a missing group is not evidence of closure,
so its live content is adopted. Same-group duplicate editor views collapse to
the pinned copy while other split groups stay apart. A change to openFiles
alone now re-filters tab chrome.
@BearMett

Copy link
Copy Markdown
Contributor Author

@nwparker thanks for continuing this. I've added a merge of main and one commit on top of your head, so your commits stay as they are. The new commit addresses pullfrog's remaining tabOrder note: the save step now builds groups from the filtered tabs and uses the same tab-to-group rule as restore and the shared layout loader. The description has the details and what is still unverified.

Since this is a fork PR, could you approve the waiting workflow runs when you have a moment?

@BearMett

Copy link
Copy Markdown
Contributor Author

This PR now uses the shared restoresSavedContentTab from #31925 for the restorability rule.

@Jinwoo-H, since your layout-owner work touches the same files, how would you prefer to handle #27983? In addition to the changes in #31925, this PR does two things:

  • Startup cleanup visits every workspace with saved tabs, not only those with terminal rows.
  • The save step applies the same restorability and group-ownership rules as restore.

If you would prefer to address these in your refactor, I'm happy to close this PR or narrow its scope accordingly. If this PR still fits, could you review it and approve the pending workflow runs when you have time?

@BearMett

Copy link
Copy Markdown
Contributor Author

Closing: main's layout-owner work (#31925, #31438) now owns editor tab restore and reconciliation, so this renderer-side hydration fix no longer fits the current design and has drifted ~1.8k commits behind with conflicts in the same files. The restorability rule this PR adopted already landed via #31925. Leaving #27983 open for the assignee to continue on the new architecture. Thanks @nwparker for carrying this earlier.

@BearMett BearMett closed this Oct 30, 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

Development

Successfully merging this pull request may close these issues.

[Bug]: Saved tab groups retain unrestorable tabs, and editor-only workspaces miss startup cleanup

2 participants