Repository navigation
Conversation
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>
📝 WalkthroughWalkthroughTerminal 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)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
src/renderer/src/components/terminal/terminal-tab-actions.ts (1)
77-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCondense 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 valueShorten 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
📒 Files selected for processing (5)
src/renderer/src/components/terminal/terminal-tab-actions.tssrc/renderer/src/components/terminal/terminal-tab-close-unrouted-owner.test.tssrc/renderer/src/store/slices/tab-group-state.tssrc/renderer/src/store/slices/tabs.tssrc/renderer/src/store/slices/unified-tab-orphaned-group-close.test.ts
| /** 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) | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 SummaryThis PR fixes two independent dead-ends that caused tab close events to silently no-op. The first removes an early return in
Confidence Score: 5/5Safe 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.
|
| 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>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/store/slices/tab-group-state.test.ts (1)
154-157: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten 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
📒 Files selected for processing (6)
src/renderer/src/components/terminal/terminal-tab-actions.tssrc/renderer/src/components/terminal/terminal-tab-close-unrouted-owner.test.tssrc/renderer/src/store/slices/tab-group-state.test.tssrc/renderer/src/store/slices/tab-group-state.tssrc/renderer/src/store/slices/tabs.tssrc/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
|
Thanks @puze8681 for the thorough trace in #11308 and this fix! It's already fixed on main by #27132 (274e2f2). On main, |
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.
closeTerminalTababorted the whole close when the tab's worktree owner could not be routed.resolveTerminalWorktreeRoutereturnsnullfor a tab whose worktree row is absent fromworktreesByRepo/detectedWorktreesByRepowhen the legacy-local fallback inworktree-operation-route.tsis gated off — during startup hydration (runtimeEnvironmentCatalogHydratedstartsfalse), for the entire session if the fire-and-forgetruntimeEnvironments.list()infetchSettingsthrows, once any runtime environment has been removed (removedRuntimeEnvironmentIds), or with two or more saved runtimes. The tab-strip X callscloseTerminalTab(tabId)with noonCancel, 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 throughresolveTerminalHostOwnership(..., 'teardown')and drops anything it cannot attribute intounroutablePtyIds(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).activateTerminalTabcarried the same guard and could not even select those tabs; same treatment.2.
closeUnifiedTabdead-ended when the tab's group record was missing.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 (
TabBarfilters ontab.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 togroupsByWorktree) so the close completes, and repointsactiveGroupIdByWorktreeat 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—oxlintclean andcheck:max-lines-ratchetOK (354 grandfathered, no new bypasses). Theoxlint --config config/oxlint-react-doctor.jsonstep could not run in my checkout: the installedoxlint-plugin-react-doctoris 0.2.10 whilepackage.jsonpins 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-existingsrc/shared/emoji-shortcode-catalog.tsTS18046errors 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 onorigin/mainin my environment (same subset re-run on a detachedorigin/mainand 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 whilepackage.jsonpins Node 24, and under 26window.localStorageis 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) andsrc/renderer/src/store(142 files / 2,126 tests) — are fully green.pnpm build— not run locally (see the node_modules note above).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 firesonClosed, 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, checkswasLastTabfor 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.
buildTerminalTabRetirementPlan: PTY attribution is independent of this gate and uses the stricter'teardown'purpose, pushing unattributable ids tounroutablePtyIdswhere they are skipped and warned. The route gate only ever controlled the host-directed close, which is still skipped. Verified by test thatcloseWebRuntimeSessionTabis not called on the unresolved path.nextGroupsmaps overgroupsByWorktreeand 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.resolveFolderWorkspaceOperationRouteand are unaffected. Host-authoritative remote closes still go throughcloseWebRuntimeSessionTabunchanged.src/renderer/src/components/terminal,src/renderer/src/components/terminal-pane(211 files, 2665 tests) andsrc/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 withnextGroups[0]does not activate a tab that belongs to no worktree at all— fails without the!owningWorktreeIdreturnorders the stand-in group visually/breaks a sortOrder tie by creation time— fail without thetoSortedNote 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):
void closeWebRuntimeSessionTab(...); the catch inweb-runtime-session.tsclears 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.tsswallows a confirm click landing within its 350msINTER_REQUEST_ACTION_GUARD_MSwhen another request is queued. The dialog stays up, so a second click works.🤖 Generated with Claude Code