Skip to content

fix(editor): close duplicate document siblings - #23347

Closed
Pr1p wants to merge 1 commit into
stablyai:mainfrom
Pr1p:codex/editor-close-ghost-tabs
Closed

Pr1p wants to merge 1 commit into
stablyai:mainfrom
Pr1p:codex/editor-close-ghost-tabs

Conversation

@Pr1p

@Pr1p Pr1p commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When Orca accidentally has multiple tabs for the same file, closing one now closes the clean leftover copies too. This stops the file from returning through Ctrl+Tab or after a restart.

What Changed

Before: a local file could receive a second identity after a remote runtime had focus. Closing one identity removed only its first tab, leaving clean sibling OpenFile records and tabs available to restore later.

After: closing an editable file sweeps clean, same-worktree, same-path sibling records and every linked unified tab. It removes their per-file UI state and tab-bar entries while recording one recently-closed snapshot. Divergent unsaved drafts remain available for recovery, and external SSH files remain isolated by id.

Why

This is a narrow containment fix for the live close-path leak in #21121. It prevents a stale clean sibling from being reactivated without changing owner derivation, hydration normalization, or missing-file UX. Keeping dirty siblings is safer than deduplicating all same-path records because their draft content may differ.

Linked Issue

Fixes #21121 — the close-path containment slice only; owner-route correction and missing-file UX remain out of scope.

Visual Proof

N/A — this changes persisted editor-record cleanup, with focused store regression coverage rather than a visual surface change.

Testing

node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/renderer/src/store/slices/editor-close-file-cleanup.test.ts --reporter=verbose (21 passed)

  • oxfmt and oxlint on the changed files

  • Full web typecheck is currently blocked by existing missing dependency/type exports for
    remark-cjk-friendly/parseOnly, @xterm/addon-image, and ORDERED_LIST_MARKER_PATTERN; none are touched by this PR.

  • I manually tested these changes locally

  • Automated tests added/updated

Risk

Level: Medium

Scope: 1 file(s), includes UI surfaces. Reverting is a plain revert; no persisted state is rewritten.

AI Disclosure

Authored with AI assistance (GLM coding agent) under the contributor's direction.

Review

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

  • Security: closing duplicate document siblings removes a stale-buffer path that could overwrite an unrelated file.
  • Cross-platform: the close path runs the same on every renderer.
  • Remote SSH: remote editor sessions benefit the same way through the shared tab manager.
  • Mobile: no mobile surface change.
  • Backwards compatibility: documents that weren't duplicated still close the same way.
  • Performance: one extra sibling check on tab close.

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)
  • I stated the risk: what could break, for whom, and how to back it out
  • 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)

@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

The test suite adds closeFile cases for duplicate editor siblings. It checks removal of clean same-owner duplicates and their linked tabs, retention of siblings with drafts or different SSH targets or runtime owners, and worktree selection updates after duplicate removal.

Merge Risk: Minimal · previous review 02285

This change adds tests without changing runtime behavior. A tab-retention assertion would strengthen coverage; the change is mergeable.

Security architecture risk: Low · up to f64f5

The cleanup is limited to clean duplicates and preserves unsaved sibling drafts. The remaining uncertainty is whether closing a mirrored sibling always targets its owning runtime when its recorded ownership differs from the worktree’s current owner.

Retained concerns

  • Low · architecture · inferred: Expanded host notifications rely on an unresolved ownership invariant. Eligible siblings need not share runtimeEnvironmentId, while each mirrored close is routed through the worktree’s current runtime owner. If a mismatched mirrored sibling survives into this state, notification can target a runtime other than its recorded owner. Reachability and an actual incorrect host close remain unproven.
Security review details

Security Blast Radius

  • observed — The automatic local sweep is bounded to eligible records sharing a worktree and exact path. Host-side effects additionally require mirrored provenance and a linked editor tab; non-mirrored siblings do not generate host-close calls.

Trust Boundaries and Controls

  • observed — The host call captures an environment and pairing revision. Host-tab lookup is environment/worktree scoped, but falls back to converting the supplied tab ID when lookup fails; this path does not independently validate the OpenFile runtime owner.

Resilience and Maintainability Implications

  • observed — Existing host failure handling distinguishes transient failures from definitive tab absence: transient failures clear close intents, definitive absence makes suppression durable, and a republished refusal releases suppression. Batch closes reuse these per-tab controls rather than adding all-or-nothing host rollback.

Hardening Proposals

  • proposed — Establish the authoritative runtime ownership invariant for mirrored siblings, including stale file ownership and route changes. If equivalence is not guaranteed, validate or resolve each host close against its authoritative provenance before dispatch.
Pre-merge checks: Passed 5

Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: closing duplicate document siblings.
Docstring Coverage Passed No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
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.
Description check Passed The description follows the repository template and fills most sections with specific content. It has an ELI5, a What Changed section with before and after behavior, a Why section that explains the sc…
Full details: Docstring Coverage

Explanation

No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 0 functions across 1 files.

Full details: Description check

Explanation

The description follows the repository template and fills most sections with specific content. It has an ELI5, a What Changed section with before and after behavior, a Why section that explains the scope and rejected alternative (keeping dirty siblings), a linked issue (Fixes #21121, scoped to the close-path slice), a Visual Proof N/A with reason, Testing notes with a vitest command and 21 passing tests, a Risk section with level Medium and a revert path, an AI Disclosure, and the Agent skill boundary checkbox. The Notes section covers security, cross-platform, SSH, mobile, backwards compatibility, and performance. Gaps: the manual testing checkbox is unchecked and the 'pnpm lint, typecheck, test, build' checklist item is unchecked, and the Testing section does not say which platforms were tested. The full web typecheck was reported as blocked, so typecheck is not confirmed. The Risk section says 'no persisted state is rewritten' but the change does alter persisted editor-record cleanup, so the revert note could be clearer on what a revert does not undo. The 'Visual Proof' N/A reason is given, though the change does affect UI tab-bar entries, which the author acknowledges.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: bf3bb485-947f-4eee-a5e1-9edc9ebe315b

📥 Commits

Reviewing files that changed from the base of the PR and between 459410a and 6dff30d88446c648549777626a87a7ba0b5d6a1b.

📒 Files selected for processing (73)
  • src/main/ipc/rate-limits.ts
  • src/main/ipc/register-core-handlers/register-core-handlers.test.ts
  • src/main/ipc/register-core-handlers/register-core-handlers.ts
  • src/main/ipc/zhipu-credentials.ts
  • src/main/rate-limits/rate-limit-service-test-harness.ts
  • src/main/rate-limits/service-account-target-selection.test.ts
  • src/main/rate-limits/service-inactive-account-previews.test.ts
  • src/main/rate-limits/service-live-claude-usage.test.ts
  • src/main/rate-limits/service-minimax-usage.test.ts
  • src/main/rate-limits/service-refresh-orchestration.test.ts
  • src/main/rate-limits/service-window-activation.test.ts
  • src/main/rate-limits/service-zhipu-usage.test.ts
  • src/main/rate-limits/service/service-account-refresh.ts
  • src/main/rate-limits/service/service-configuration.ts
  • src/main/rate-limits/service/service-fetch-policy.ts
  • src/main/rate-limits/service/service-full-cycle-application.ts
  • src/main/rate-limits/service/service-full-cycle-preparation.ts
  • src/main/rate-limits/service/service-polling.ts
  • src/main/rate-limits/service/service-result-policy.ts
  • src/main/rate-limits/service/service-state.ts
  • src/main/rate-limits/service/service-types.ts
  • src/main/rate-limits/zhipu-fetcher.test.ts
  • src/main/rate-limits/zhipu-fetcher.ts
  • src/main/runtime/rpc/methods/client-ui.test.ts
  • src/main/zhipu/cc-switch-import.test.ts
  • src/main/zhipu/cc-switch-import.ts
  • src/main/zhipu/zhipu-credential-store.ts
  • src/preload/api-types.ts
  • src/preload/api/agent-account-api.ts
  • src/preload/api/agent-usage-api.ts
  • src/preload/api/rate-limits-bridge.ts
  • src/preload/api/zhipu-credentials-bridge.ts
  • src/preload/index.ts
  • src/renderer/src/components/settings/AccountsPane.tsx
  • src/renderer/src/components/settings/AppearanceWindowSidebarSection.tsx
  • src/renderer/src/components/settings/ZhipuAccountsSection.test.tsx
  • src/renderer/src/components/settings/ZhipuAccountsSection.tsx
  • src/renderer/src/components/settings/accounts-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-minimax-toggle-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-zhipu-toggle-search.ts
  • src/renderer/src/components/stats/GrokUsagePane.test.tsx
  • src/renderer/src/components/status-bar/StatusBarProviderSegment.tsx
  • src/renderer/src/components/status-bar/StatusBarVisibilityMenu.tsx
  • src/renderer/src/components/status-bar/icons.tsx
  • src/renderer/src/components/status-bar/status-bar-agent-gating.test.ts
  • src/renderer/src/components/status-bar/status-bar-provider-visibility.test.ts
  • src/renderer/src/components/status-bar/status-bar-provider-visibility.ts
  • src/renderer/src/components/status-bar/tooltip.test.ts
  • src/renderer/src/components/status-bar/tooltip.tsx
  • src/renderer/src/components/status-bar/usage-error-copy.test.ts
  • src/renderer/src/components/status-bar/usage-error-copy.ts
  • src/renderer/src/components/status-bar/usage-provider-settings-target.test.ts
  • src/renderer/src/components/status-bar/usage-provider-settings-target.ts
  • src/renderer/src/components/status-bar/use-status-bar-controller.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/store/slices/editor-close-file-cleanup.test.ts
  • src/renderer/src/store/slices/editor/actions/close-file-action.ts
  • src/renderer/src/store/slices/rate-limits.test.ts
  • src/renderer/src/store/slices/rate-limits.ts
  • src/renderer/src/store/slices/ui-hydration-workspace-preferences.test.ts
  • src/renderer/src/store/slices/ui/ui-slice-hydration-actions.ts
  • src/renderer/src/web/preload-api/web-agent-accounts-api.ts
  • src/renderer/src/web/preload-api/web-rate-limits-api.ts
  • src/renderer/src/web/web-preload-api-agent-providers.test.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/persisted-ui-state-types.ts
  • src/shared/rate-limit-state-factory.ts
  • src/shared/rate-limit-types.test.ts
  • src/shared/rate-limit-types.ts
  • src/shared/status-bar-defaults.ts
  • src/shared/ui-chrome-types.ts
  • src/shared/zhipu-usage.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.

Comment thread src/main/rate-limits/zhipu-fetcher.ts Resolved

@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

This PR ships 71 files of an unrelated Zhipu / Z.AI usage-monitoring feature (commit 86cbc5f) that is not in main, alongside the editor close-path fix the title and body describe. The description calls the change "small and focused" and lists only the editor test, so the bundle looks accidental (or is an undeclared stack). It should be split into its own PR, or the branch rebased onto main, before this is reviewed as the containment fix it advertises.

Reviewed changes

  • Editor close-path containment (src/renderer/src/store/slices/editor/actions/close-file-action.ts): closing an editable file now sweeps clean, same-worktree, same-path sibling OpenFile records (owner-agnostic across runtimeEnvironmentId, skipped when either side carries externalSshTargetId), removes their per-file UI state, prunes the tab-bar order, drops a pending focus request, and closes every linked unified editor/diff/conflict-review/check-details tab instead of only the first. Dirty or draft-bearing siblings are preserved.
  • Regression tests (editor-close-file-cleanup.test.ts): a clean cross-runtime sibling is swept, an unsaved-draft sibling is kept, and external-SSH siblings with the same path do not collapse. Verified all 21 pass locally, and that the first case fails against the old behavior.
  • Bundled Zhipu feature (commit 86cbc5f, 71 files): new provider rate-limit fetcher, credential store, cc-switch import, IPC/preload/renderer surfaces. Not part of the stated change; see the callout and section below.

⚠️ A second, unreviewed feature is included

The branch is two commits: the editor fix sits directly on top of 86cbc5f, which never reached main (merge-base 646e9a5; git branch --contains 86cbc5f330 matches only this branch). The PR diff against main therefore registers 2245 additions across 73 files. Merging as-is would land the entire Zhipu feature — main-process network/credential paths, IPC channels, preload API, and renderer surfaces — under an editor-fix title, with none of the testing evidence the body lists for it.

Technical details
# Unrelated Zhipu feature bundled into the editor-fix PR

## Affected sites
- `src/main/rate-limits/zhipu-fetcher.ts`, `src/main/zhipu/zhipu-credential-store.ts`, `src/main/zhipu/cc-switch-import.ts`, `src/main/ipc/zhipu-credentials.ts`, `src/preload/**`, `src/renderer/src/components/settings/ZhipuAccountsSection.tsx`, `src/renderer/src/components/status-bar/**`, `src/shared/**` — all newly added by commit `86cbc5f`.

## Required outcome
- The PR review surface should match the stated change: only the editor close-path files (`close-file-action.ts` + `editor-close-file-cleanup.test.ts`).
- Either split commit `86cbc5f` (and its 71 files) into its own PR, or rebase `codex/editor-close-ghost-tabs` onto `main` so the editor fix is the sole commit. If the Zhipu work is intentionally stacked, say so in the body and add its test/verification evidence.

## Open questions for the human
- Is `86cbc5f` intended to be part of this PR (a stack that should be declared), or an accidental base?

ℹ️ Active-tab neighbor selection assumes a single removal

In the reworked close path, closedWorktreeIdx is still computed against s.openFiles while the list it indexes (worktreeFiles = newFiles) has already had the swept siblings removed. With the previous one-file removal the two stayed aligned; now that fileIdsToClose can drop several entries, the adjacency pick can land on a non-adjacent tab. Cosmetic, but a direct consequence of widening the close set.

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

@Pr1p
Pr1p force-pushed the codex/editor-close-ghost-tabs branch from 6dff30d to 21d3e20 Compare September 27, 2026 12:56

@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 revision. The unrelated provider feature the prior review flagged has been dropped by the rebase, and the editor close-path files are unchanged from the reviewed revision.

Reviewed changes

  • Provider-feature bundle removed: the branch was rebased so the PR now contains only close-file-action.ts and editor-close-file-cleanup.test.ts; the 71-file Zhipu / Z.AI feature no longer rides along. This clears the prior review's main concern.
  • Editor close-path fix unchanged: both files are byte-identical to the previously reviewed 6dff30d revision, so the prior analysis still applies.

The one item still open from the prior review — the active-tab neighbor pick mixing a pre-removal index (closedWorktreeIdx against s.openFiles) with the post-removal list (worktreeFiles) — is unchanged and remains cosmetic (it can land on a valid but non-adjacent tab). It stays tracked in its existing thread; no new inline comments.

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

@Pr1p
Pr1p force-pushed the codex/editor-close-ghost-tabs branch from 21d3e20 to f64f5bb Compare October 4, 2026 06:45

@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

What changed since the prior pullfrog review at 21d3e20: the branch was rebased onto main (3cc5e1d) and the close path was rewritten. I re-read both files against the previous revision (git show 21d3e20:...) to isolate the branch delta from base-advance changes.

  • Neighbor selection rewritten (close-file-action.ts): the inline closedWorktreeIdx index (which mixed a pre-removal index with the post-removal list) is replaced by findAdjacentOpenFileId, which scans the pre-removal list and skips every id in fileIdsToClose. This resolves the open pullfrog thread and picks the immediate survivor when several siblings are swept.
  • Empty-draft siblings preserved: the keep check is now !(file.id in editorDrafts) instead of a truthiness test, so a sibling with an empty-string draft is no longer swept. Covered by a new test that fails against the previous code.
  • Per-worktree active repair: a new block repairs activeFileIdByWorktree for the closed file's worktree when its remembered file was among the swept ids, so a non-active worktree doesn't keep a stale selection.
  • Tests: four new cases (empty draft kept, inactive-worktree selection repaired, immediate surviving neighbor selected, external-SSH siblings untouched); the file now has 25 passing tests. I ran both editor-close-file-cleanup.test.ts (25 passed) and the pre-existing editor-close-file-stale-active.test.ts (3 passed).

The prior [!IMPORTANT] about the bundled 71-file provider feature was already cleared by the earlier rebase; this revision keeps the PR to the two editor files.

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

nwparker added a commit that referenced this pull request Oct 5, 2026
Adapt the document-sibling cleanup from Pr1p's #23347 with exact owner and
captured provenance checks. Preserve divergent drafts and the backing bytes
needed by retained views, and keep one-pane close behavior intact.

Co-authored-by: Chen <[email protected]>
nwparker added a commit that referenced this pull request Oct 6, 2026
Adapt the document-sibling cleanup from Pr1p's #23347 with exact owner and
captured provenance checks. Preserve divergent drafts and the backing bytes
needed by retained views, and keep one-pane close behavior intact.

Co-authored-by: Chen <[email protected]>
nwparker added a commit that referenced this pull request Oct 7, 2026
Adapt the document-sibling cleanup from Pr1p's #23347 with exact owner and
captured provenance checks. Preserve divergent drafts and the backing bytes
needed by retained views, and keep one-pane close behavior intact.

Co-authored-by: Chen <[email protected]>
@Pr1p
Pr1p force-pushed the codex/editor-close-ghost-tabs branch from 4a3d4fa to 02285a1 Compare November 3, 2026 20:45

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

Follow-up Comments

Nitpick Assert that the dirty sibling keeps its unified tab.

290-295: Trivial · Maintainability & Code Quality · Quick win

Assert that the dirty sibling keeps its unified tab.

Add a linked editor tab to this fixture and assert that it remains after closeFile. The separate sibling test creates a tab, but does not assert its retention, so it does not detect this regression.

Suggested fix
     store.setState({
       openFiles: [localFile, { ...localFile, id: duplicateFileId, isDirty: true }],
       editorDrafts: { [duplicateFileId]: 'unsaved draft' }
     })
+    store.getState().createUnifiedTab('wt-1', 'editor', {
+      id: 'duplicate-editor-tab',
+      entityId: duplicateFileId,
+      label: 'a.ts',
+      activate: false
+    })
 
     store.getState().closeFile(localFile.id)
 
     expect(store.getState().openFiles).toEqual([
       expect.objectContaining({ id: duplicateFileId, isDirty: true })
     ])
+    expect(store.getState().unifiedTabsByWorktree['wt-1'].map((tab) => tab.id)).toContain(
+      'duplicate-editor-tab'
+    )

Open the source location

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cf710ce5-e1fd-4dfe-8e13-bf58c5699c30
Commits

Reviewing files that changed from the base of the PR and between 4a3d4fa and 02285a1.

Files selected for processing: 1
  • src/renderer/src/store/slices/editor-close-file-cleanup.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.

@Pr1p
Pr1p force-pushed the codex/editor-close-ghost-tabs branch 2 times, most recently from 9364e9b to 92497c9 Compare November 11, 2026 02:50
Rebased onto latest main. The duplicate-document close sweep landed via
c9f4cd7, adapted from this PR, and its regression coverage moved into
src/renderer/src/store/slices/editor/closing/ — since reduced by stablyai#40981's
low-value test cull. Conflicts resolve to main's side; nothing from the
fork-only editor-close-file-cleanup.test.ts remains to port.

Co-Authored-By: Claude Code <[email protected]>
@Pr1p
Pr1p force-pushed the codex/editor-close-ghost-tabs branch from 92497c9 to 202a8bc Compare November 11, 2026 09:34
@nwparker

Copy link
Copy Markdown
Contributor

Thanks for this! The change already landed on main in c9f4cd7, so I'm closing this PR. We appreciate the contribution.

@nwparker nwparker closed this Nov 16, 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]: Editor tabs for deleted/duplicated files resurrect across restarts (duplicate OpenFile records + UI-focus owner leak)

2 participants