Skip to content

fix(tabs): stop dropping tab closes that have nowhere to route - #11316

Closed
puze8681 wants to merge 2 commits into
stablyai:mainfrom
puze8681:fix/tab-close-silent-no-op
Closed

puze8681 wants to merge 2 commits into
stablyai:mainfrom
puze8681:fix/tab-close-silent-no-op

Conversation

@puze8681

@puze8681 puze8681 commented Jul 29, 2026 •

Copy link
Copy Markdown

Fixes #11308

Summary

Closing a tab was sometimes a completely silent no-op — no prune, no error, no toast, no log — and retrying did not help while the triggering condition held. Two independent dead ends caused it; this PR fixes both. The full trace is in #11308.

1. closeTerminalTab aborted the whole close when the tab's worktree owner could not be routed.

const worktreeRoute = resolveTerminalWorktreeRoute(state, owningWorktreeId)
if (!worktreeRoute) {
  options?.onCancel?.()
  return          // no prune, no error
}

resolveTerminalWorktreeRoute returns null for a tab whose worktree row is absent from worktreesByRepo/detectedWorktreesByRepo when the legacy-local fallback in worktree-operation-route.ts is gated off — during startup hydration (runtimeEnvironmentCatalogHydrated starts false), for the entire session if the fire-and-forget runtimeEnvironments.list() in fetchSettings throws, once any runtime environment has been removed (removedRuntimeEnvironmentIds), or with two or more saved runtimes. The tab-strip X calls closeTerminalTab(tabId) with no onCancel, so hitting this branch is indistinguishable from the click never registering.

The gate bought nothing for safety: provider teardown already fails closed per PTY inside buildTerminalTabRetirementPlan, which routes each PTY through resolveTerminalHostOwnership(..., 'teardown') and drops anything it cannot attribute into unroutablePtyIds (skipped and warned). So an unresolved owner now skips only the host-directed close and keeps the local prune the user asked for, plus a warning that logs the worktree kind, never the id (worktree ids embed absolute paths). activateTerminalTab carried the same guard and could not even select those tabs; same treatment.

2. closeUnifiedTab dead-ended when the tab's group record was missing.

const group = findGroupForTab(state.groupsByWorktree, worktreeId, tab.groupId)
if (!group) {
  return null     // tab stays in unifiedTabsByWorktree forever
}

Every close path funnels through this action, so a tab left pointing at a group id that was collapsed or lost in a host-snapshot desync rendered in the strip (TabBar filters on tab.groupId === resolvedGroupId) and could never be removed — not by the X, not by Close Others / Close to the Right, not after a restart. It now rebuilds a stand-in group from the tabs still referencing that id (never written back to groupsByWorktree) so the close completes, and repoints activeGroupIdByWorktree at a real group once the phantom has no tabs left, so the strip cannot render empty while real groups remain.

Screenshots

No visual change — the tab that used to be stuck now closes.

Testing

  • pnpm lint — oxlint clean and check:max-lines-ratchet OK (354 grandfathered, no new bypasses). The oxlint --config config/oxlint-react-doctor.json step could not run in my checkout: the installed oxlint-plugin-react-doctor is 0.2.10 while package.json pins 0.9.1, so the config fails to parse on any file, including untouched ones. Please let CI adjudicate that gate.
  • pnpm typecheck — no new errors. The 3 pre-existing src/shared/emoji-shortcode-catalog.ts TS18046 errors reproduce on a clean tree at this base.
  • pnpm test — full suite run: 39,741 passed, 46 failed across 10 files. Every one of those 10 files fails identically on origin/main in my environment (same subset re-run on a detached origin/main and on this branch: 43 failed / 26 passed, same per-file statuses; the two that pass in isolation fail only under full-suite parallel load, on both). The cause is local: this machine runs Node 26.5.0 while package.json pins Node 24, and under 26 window.localStorage is unavailable to happy-dom (ExperimentalWarning: localStorage is not available because --localstorage-file was not provided). None of the 10 are in the code this PR touches. The areas that are — src/renderer/src/components/terminal, src/renderer/src/components/terminal-pane (211 files / 2,665 tests) and src/renderer/src/store (142 files / 2,126 tests) — are fully green.
  • pnpm build — not run locally (see the node_modules note above).
  • Added or updated high-quality tests that would catch regressions

New tests, both verified to fail against the pre-fix code (2/4 and 3/4 respectively, the rest being guard-preservation assertions that must pass either way):

  • src/renderer/src/components/terminal/terminal-tab-close-unrouted-owner.test.ts — drives the real owner resolver from a store state with populated-but-empty catalogs and a saved runtime: the close prunes and fires onClosed, the host-directed close stays suppressed, the pinned-tab confirmation guard still rejects, and activation still selects.
  • src/renderer/src/store/slices/unified-tab-orphaned-group-close.test.ts — closes a tab whose group record is gone, checks wasLastTab for the final orphan, checks the active-group repoint, and asserts a live group record is untouched.

AI Review Report

Reviewed with Claude Code, focused on the risk of loosening two fail-closed guards.

  • Does dropping the route guard let a close kill the wrong PTY? No. Read buildTerminalTabRetirementPlan: PTY attribution is independent of this gate and uses the stricter 'teardown' purpose, pushing unattributable ids to unroutablePtyIds where they are skipped and warned. The route gate only ever controlled the host-directed close, which is still skipped. Verified by test that closeWebRuntimeSessionTab is not called on the unresolved path.
  • Does it weaken the pinned-tab confirmation? No — the guard sits after the route resolution and is unchanged; covered by a test on the unresolved path.
  • Can a reconstructed group leak into persisted state? No. The stand-in is a local value; nextGroups maps over groupsByWorktree and finds no match, so nothing is written. The active-group repoint only fires when the record was genuinely missing, the phantom is the active id, no tabs still reference it, and a real group exists.
  • Cross-platform (macOS, Linux, Windows): no platform-dependent code touched — no shortcuts, accelerators, shortcut labels, path handling, or shell behavior. The changes are store/action logic that runs identically on all three. Worktree ids are treated as opaque strings and, per the existing convention, only their kind is logged, never the id.
  • SSH, folder-workspace, and remote coverage: the unresolved-owner path is the one that most often affects SSH and runtime-owned worktrees, which is what the fix targets. Folder workspaces route through resolveFolderWorkspaceOperationRoute and are unaffected. Host-authoritative remote closes still go through closeWebRuntimeSessionTab unchanged.
  • Regression surface: ran src/renderer/src/components/terminal, src/renderer/src/components/terminal-pane (211 files, 2665 tests) and src/renderer/src/store (142 files, 2126 tests) before the full suite; all green.

Security Audit

No new input handling, command execution, path handling, auth, secrets, dependency, or IPC surface. The change removes two early returns and adds one console.warn, which deliberately logs the worktree kind rather than the id because worktree ids embed absolute paths — matching the existing [terminal-retirement] convention. No user-controlled string reaches a shell, filesystem, or network call. The RPC that is skipped on the unresolved path is the only outbound effect touched, and skipping it is strictly less privileged than the previous behavior.

Verifying the regression tests are not vacuous

All four added tests fail against the pre-fix code — confirmed by reverting each change, not assumed:

  • repoints at a group that actually has tabs — fails with nextGroups[0]
  • does not activate a tab that belongs to no worktree at all — fails without the !owningWorktreeId return
  • orders the stand-in group visually / breaks a sortOrder tie by creation time — fail without the toSorted

Note the third case is a contract fix, not a behavior fix: the sole caller discards the reconstructed tabOrder, so it is pinned by direct unit tests rather than a store-level test that would assert nothing. Reasoning is in the review thread.

Notes

No X handle to share — I'm not on X, so there's nothing to shout out. Every other item in CONTRIBUTING's PR checklist is covered above.

Two related-but-separate issues surfaced while tracing this and are not fixed here (documented at the end of #11308):

  • Remote/host-owned worktrees prune locally and fire the host close as void closeWebRuntimeSessionTab(...); the catch in web-runtime-session.ts clears the close intents, so an RPC failure lets the next host snapshot re-add the tab. That is the "closed, then it came back" symptom, distinct from "won't close", and fixing it means reworking close-intent retention.
  • pinned-tab-close-confirm.ts swallows a confirm click landing within its 350ms INTER_REQUEST_ACTION_GUARD_MS when another request is queued. The dialog stays up, so a second click works.

🤖 Generated with Claude Code

Closing a tab was sometimes a silent no-op — no prune, no error, no log —
through two independent dead ends.

`closeTerminalTab` aborted the entire close when `resolveTerminalWorktreeRoute`
could not resolve the tab's worktree owner. That happens whenever the worktree
row is missing from the owner catalogs and the legacy-local fallback is gated
off: during startup hydration, for the whole session if
`runtimeEnvironments.list()` throws, after any runtime environment is removed,
and with two or more saved runtimes. The tab-strip X passes no `onCancel`, so
the click looked like it never registered. Provider teardown already fails
closed per PTY inside the retirement plan (`unroutablePtyIds`), so an
unresolved owner now skips only the host-directed close and keeps the local
prune. `activateTerminalTab` carried the same guard and could not select those
tabs either.

`closeUnifiedTab` returned null when the tab's group record was missing. Every
close path funnels through it, so a tab left pointing at a collapsed or
desynced group id stayed in the strip permanently — unclosable by the X, by
Close Others, or across a restart. It now rebuilds a stand-in group from the
tabs still referencing that id (never persisted) and repoints the worktree's
active group at a real group once the phantom has no tabs left, so the strip
cannot render empty while real groups remain.

Fixes stablyai#11308

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Terminal tab closing and activation now continue local state updates when the terminal owner route cannot be resolved, while host-directed runtime actions are skipped and closing emits a warning. New tests cover unroutable owners, pinned-tab guards, local pruning, and selection updates. Unified tab closure now reconstructs an in-memory group for missing group records and repoints active group state after orphaned tabs are removed. Tests cover partial and final orphan closure and live-group behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title matches the main fix: tab closes that couldn't be routed now prune locally instead of no-oping.
Description check ✅ Passed The description covers all required sections and includes summary, screenshots, testing, AI review, security, and notes.

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/renderer/src/components/terminal/terminal-tab-actions.ts (1)

77-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the new explanatory comments.

  • src/renderer/src/components/terminal/terminal-tab-actions.ts#L77-L82: reduce this rationale to one concise sentence.
  • src/renderer/src/components/terminal/terminal-tab-close-unrouted-owner.test.ts#L28-L32: summarize the fixture state in one concise sentence.

Source: Coding guidelines

src/renderer/src/store/slices/tabs.ts (1)

893-897: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten this implementation walkthrough.

Keep the non-obvious fallback rationale, but reduce this multi-line explanation to one concise comment.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4ea271de-536a-4167-8a09-2a876a466d89

📥 Commits

Reviewing files that changed from the base of the PR and between d07931c and 0c3feb8.

📒 Files selected for processing (5)
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/components/terminal/terminal-tab-close-unrouted-owner.test.ts
  • src/renderer/src/store/slices/tab-group-state.ts
  • src/renderer/src/store/slices/tabs.ts
  • src/renderer/src/store/slices/unified-tab-orphaned-group-close.test.ts

Comment thread src/renderer/src/store/slices/tabs.ts Resolved
Comment on lines +26 to +41
/** Stand-in group for a tab whose group record is missing, rebuilt from the tabs still pointing at
* that id. Lets a close finish instead of dead-ending on the lookup; never persisted. */
export function reconstructGroupForOrphanedTab(
tabs: readonly Tab[],
worktreeId: string,
tab: Tab
): TabGroup {
return {
id: tab.groupId,
worktreeId,
activeTabId: tab.id,
tabOrder: tabs
.filter((candidate) => candidate.groupId === tab.groupId)
.map((candidate) => candidate.id)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 recentTabIds not populated in reconstructed group; MRU fallback degrades to neighbor selection

reconstructGroupForOrphanedTab returns a TabGroup without recentTabIds. In closeUnifiedTab, the non-terminal close path calls pickNextActiveTab(dedupedGroupOrder, group.recentTabIds, tabId), which receives undefined for recentTabIds, causing sanitizeRecentTabIds to return []. The MRU-based selection (most recently visited tab before the one being closed) is silently skipped, and the visual-neighbor fallback is used instead. This only affects multi-tab orphaned groups with non-terminal content — a rare edge case — but the user would land on the positionally-adjacent tab rather than the one they last visited.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Accurate reading of the function, but not actionable as a fix — leaving it as-is deliberately.

Two things:

It is not observable today. pickNextActiveTab(dedupedGroupOrder, group.recentTabIds, tabId) runs, but its result lands in nextGroups = (current.groupsByWorktree[worktreeId] ?? []).map(...) keyed on candidate.id === group.id. A reconstructed group is absent from groupsByWorktree by construction, so the mapped update matches nothing and nextActiveTabId is discarded. Nothing selects a next tab for a phantom group at all, so the MRU path does not degrade to neighbor selection — neither path takes effect. (Same root cause I wrote up on the CodeRabbit tabOrder thread.)

There is nothing to populate it from. The MRU stack lives only on the TabGroup record, and the premise here is that the record is gone. Tabs do not carry per-group MRU, and activeTabId on the stand-in is the tab being closed, so seeding from it would be worse than empty. Synthesizing a plausible-looking recentTabIds would fabricate history rather than recover it.

pickNextActiveTab already documents the empty-MRU case as intended behavior — "falls back to the nearest visual neighbor when the MRU stack is empty (e.g. newly hydrated groups where only the current active tab has been recorded)" — and a group whose record vanished is squarely that case. If a future change does write the reconstructed group back, the neighbor fallback it inherits is now at least in correct visual order, since the tabOrder sort landed in 8c0a456.

@greptile-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes two independent dead-ends that caused tab close events to silently no-op. The first removes an early return in closeTerminalTab / activateTerminalTab that aborted the entire local close when a tab's worktree owner couldn't be routed (during startup hydration, after a failed runtime-env listing, or with multiple saved runtimes). The second fixes closeUnifiedTab returning null when a tab's group record was missing, which left phantom tabs in the strip permanently. Both paths are now patched to continue with local state cleanup and add one console.warn for the unresolvable-owner case.

  • terminal-tab-actions.ts: The unresolvable-owner branch now only skips the host-directed close (which was all it could safely gate anyway — PTY teardown is already fail-closed per PTY inside buildTerminalTabRetirementPlan) and emits a structured warning. activateTerminalTab keeps a hard return only for the "tab in no strip" case (truly absent from tabsByWorktree), not for "tab exists but owner can't be routed".
  • tab-group-state.ts / tabs.ts: reconstructGroupForOrphanedTab rebuilds a stand-in TabGroup from tabs still referencing the phantom group id (sorted by sortOrder then createdAt), and closeUnifiedTab falls back to it when findGroupForTab returns null. After the last orphan closes, the active-group pointer is repointed to the first populated real group so the strip doesn't render empty.
  • Both fixes are covered by new tests (terminal-tab-close-unrouted-owner.test.ts, unified-tab-orphaned-group-close.test.ts) that are confirmed to fail against the pre-fix code.

Confidence Score: 5/5

Safe to merge — both changes are narrowly scoped to removing two silent dead-ends, all guarded paths are preserved, and the key invariant (PTY teardown stays fail-closed per PTY inside the retirement plan) is unaffected.

The route-guard removal in terminal-tab-actions.ts is well-contained: isWebRuntimeSessionActive correctly returns false for null (via optional chaining), the pinned-tab confirmation guard is unchanged, and host-directed closes are still gated behind a live runtimeEnvironmentId. The phantom-group reconstruction in tabs.ts is never persisted, the active-group repoint only fires on precise conditions, and collapseGroupLayout with an absent group id is a safe no-op on the layout tree. Both fixes are covered by new regression tests confirmed to fail against the pre-fix code.

Files Needing Attention: No files require special attention; the logic in tabs.ts around the wasLastTab + phantom group + split layout interaction is an untested edge case but behaves correctly through the collapseGroupLayout fallback.

Important Files Changed

Filename Overview
src/renderer/src/components/terminal/terminal-tab-actions.ts Removes the fail-closed early return on unresolvable owner in closeTerminalTab and activateTerminalTab; correctly gates only host-directed close behind the route check; isWebRuntimeSessionActive(null) safely returns false via optional chaining.
src/renderer/src/store/slices/tab-group-state.ts Adds reconstructGroupForOrphanedTab: correctly sorts by sortOrder then createdAt for visual ordering; the stand-in is never persisted; well-tested.
src/renderer/src/store/slices/tabs.ts closeUnifiedTab now falls back to reconstructGroupForOrphanedTab; the phantom-repoint block correctly fires only when no orphan tabs remain and real groups exist; collapseGroupLayout with a phantom id is a no-op on the layout tree and uses the fallback group id, which is safe.
src/renderer/src/components/terminal/terminal-tab-close-unrouted-owner.test.ts New test file covering both the happy path (prune fires) and the guarded paths (host close skipped, pinned guard honored, activation still works, absent-from-strip still returns early).
src/renderer/src/store/slices/unified-tab-orphaned-group-close.test.ts New test file verifying phantom-group close, wasLastTab semantics, active-group repoint, populated-group preference over empty splits, and live-group-record stability.
src/renderer/src/store/slices/tab-group-state.test.ts Adds three new unit tests for reconstructGroupForOrphanedTab: visual-order correctness, tie-breaking by createdAt, and filtering of tabs belonging to other groups.

Reviews (2): Last reviewed commit: "fix(tabs): repoint at a populated group ..." | Re-trigger Greptile

Three review findings on the orphaned-group close path.

closeUnifiedTab repointed the worktree at nextGroups[0] when the phantom
group emptied, but that can itself be an empty split while another group
holds the remaining tabs — re-creating the empty strip the repoint exists to
prevent. Prefer a group represented in nextTabs, matching the policy
selectHydratedActiveGroupId already applies at hydration.

activateTerminalTab dropped its early return along with the route guard, so a
tabId in no worktree's strip fell through to setActiveTab and pointed the app
at a tab that renders nothing. Missing tab and unroutable owner are different
states; only the latter should degrade to a local-only path.

reconstructGroupForOrphanedTab built tabOrder from backing-array order, but
reordering rewrites sortOrder in place without moving the array element, so
the array stops matching visual order. The sole caller discards this order
today, so this is a contract fix rather than a behavior change — pinned by
direct unit tests instead of a store-level one that would assert nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

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

🧹 Nitpick comments (1)
src/renderer/src/store/slices/tab-group-state.test.ts (1)

154-157: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the test rationale comment.

The visual-order rationale is useful, but the implementation history and future-caller discussion are unnecessary here. Keep only the invariant being tested.

Suggested simplification
-  // Why: `tabOrder` is documented as canonical *visual* order, but reordering rewrites sortOrder in
-  // place without moving the array element — so building it from array order would be wrong for any
-  // group the user has ever dragged. The current caller discards this order, which is exactly why
-  // it needs pinning here: the contract, not the caller, is what a future caller will rely on.
+  // Keep `tabOrder` in visual order because reordering updates `sortOrder` without moving the backing array.

As per coding guidelines, comments in TypeScript files must be concise and limited to non-obvious information.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 58dd3bbe-6c59-4931-9117-0f84b9007fa4

📥 Commits

Reviewing files that changed from the base of the PR and between 0c3feb8 and 8c0a456.

📒 Files selected for processing (6)
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/components/terminal/terminal-tab-close-unrouted-owner.test.ts
  • src/renderer/src/store/slices/tab-group-state.test.ts
  • src/renderer/src/store/slices/tab-group-state.ts
  • src/renderer/src/store/slices/tabs.ts
  • src/renderer/src/store/slices/unified-tab-orphaned-group-close.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/renderer/src/store/slices/tab-group-state.ts
  • src/renderer/src/store/slices/unified-tab-orphaned-group-close.test.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/store/slices/tabs.ts
  • src/renderer/src/components/terminal/terminal-tab-close-unrouted-owner.test.ts

@nwparker

Copy link
Copy Markdown
Contributor

Thanks @puze8681 for the thorough trace in #11308 and this fix! It's already fixed on main by #27132 (274e2f2). On main, closeTerminalTab routes by the host the tab's own PTY ids name and, when no host can be resolved, still prunes the tab locally (per-PTY teardown keeps failing closed), and closeUnifiedTab now closes a tab whose group record is missing instead of returning null. Tab activation also does the local selection first and only skips the owner round trip when there's no routable host. If you can still get a silent no-op close on the latest build, please comment or reopen with the steps.

@nwparker nwparker closed this Oct 26, 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]: Closing a tab is sometimes a silent no-op

3 participants