Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
* never-reused key spaces.
*
* Tab-keyed (evicted via the doomed-tab set):
* lastKnownRelayPtyIdByTabId, pendingInitialCwdByTabId,
* lastKnownRelayPtyIdByTabId, pendingReconnectPtyIdByTabId,
* deferredSshSessionIdsByTabId, pendingInitialCwdByTabId,
* pendingIssueCommandSplitByTabId, pendingSetupSplitByTabId, pendingStartupByTabId
* Pty-keyed (evicted via the doomed-pty set derived from live and durable bindings):
* codexRestartNoticeByPtyId, migrationUnsupportedByPtyId,
Expand Down Expand Up @@ -89,6 +90,8 @@ function seedMaps(store: ReturnType<typeof createTestStore>): void {
}
},
lastKnownRelayPtyIdByTabId: { [TAB1]: PTY1, [TAB2]: PTY2 },
pendingReconnectPtyIdByTabId: { [TAB1]: PTY1, [TAB2]: PTY2 },
deferredSshSessionIdsByTabId: { [TAB1]: 'ssh-sess-1', [TAB2]: 'ssh-sess-2' },
pendingInitialCwdByTabId: { [TAB1]: '/path/wt1', [TAB2]: '/path/wt2' },
pendingIssueCommandSplitByTabId: {
[TAB1]: { command: 'a' },
Expand Down Expand Up @@ -146,6 +149,8 @@ describe('bulk worktree purge evicts the per-tab/per-pty terminal maps it previo

// Removed worktree's tab/pty: every map evicted.
expect(s.lastKnownRelayPtyIdByTabId[TAB1]).toBeUndefined()
expect(s.pendingReconnectPtyIdByTabId[TAB1]).toBeUndefined()
expect(s.deferredSshSessionIdsByTabId[TAB1]).toBeUndefined()
expect(s.pendingInitialCwdByTabId[TAB1]).toBeUndefined()
expect(s.pendingIssueCommandSplitByTabId[TAB1]).toBeUndefined()
expect(s.pendingSetupSplitByTabId[TAB1]).toBeUndefined()
Expand All @@ -161,6 +166,8 @@ describe('bulk worktree purge evicts the per-tab/per-pty terminal maps it previo

// Surviving worktree's tab/pty: every entry retained (no over-eviction).
expect(s.lastKnownRelayPtyIdByTabId[TAB2]).toBe(PTY2)
expect(s.pendingReconnectPtyIdByTabId[TAB2]).toBe(PTY2)
expect(s.deferredSshSessionIdsByTabId[TAB2]).toBe('ssh-sess-2')
expect(s.pendingInitialCwdByTabId[TAB2]).toBe('/path/wt2')
expect(s.pendingIssueCommandSplitByTabId[TAB2]).toEqual({ command: 'b' })
expect(s.pendingSetupSplitByTabId[TAB2]).toEqual({ command: 'setup-b', direction: 'vertical' })
Expand Down
46 changes: 34 additions & 12 deletions src/renderer/src/store/slices/ssh-target-cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,12 @@ function isSshTargetSessionId(sessionId: string, targetId: string): boolean {
return parseAppSshPtyId(sessionId)?.connectionId === targetId
}

function shouldRemoveDeferredSshSession(
// Why: a per-tab session map entry belongs to the removed target if the tab is
// one of the target's, or the session id is an SSH pty id scoped to it. Shared
// by the deferred-session and pending-reconnect cleanups so both drop the same
// dead entries (an uncleared entry would keep a dead tab alive in the orphan
// sweep, which now reads these maps as liveness — #9911).
function isRemovedSshTargetTabSession(
tabId: string,
sessionId: string,
targetId: string,
Expand All @@ -58,6 +63,23 @@ function shouldRemoveDeferredSshSession(
return targetTabIds.has(tabId) || isSshTargetSessionId(sessionId, targetId)
}

function omitRemovedSshTargetTabSessions(
sessions: Record<string, string>,
targetId: string,
targetTabIds: Set<string>
): { next: Record<string, string>; removed: boolean } {
const next: Record<string, string> = {}
let removed = false
for (const [tabId, sessionId] of Object.entries(sessions)) {
if (isRemovedSshTargetTabSession(tabId, sessionId, targetId, targetTabIds)) {
removed = true
continue
}
next[tabId] = sessionId
}
return { next, removed }
}

function clearSshTargetTabPtyState(
state: AppState,
targetId: string,
Expand Down Expand Up @@ -131,15 +153,13 @@ export function buildRemovedSshTargetCleanupPatch(
): Partial<AppState> | null {
const targetTabIds = collectSshTargetTerminalTabIds(state, targetId)
const tabPtyState = clearSshTargetTabPtyState(state, targetId, targetTabIds)
const nextDeferredSessions: Record<string, string> = {}
let removedDeferredSession = false
for (const [tabId, sessionId] of Object.entries(state.deferredSshSessionIdsByTabId)) {
if (shouldRemoveDeferredSshSession(tabId, sessionId, targetId, targetTabIds)) {
removedDeferredSession = true
continue
}
nextDeferredSessions[tabId] = sessionId
}
const { next: nextDeferredSessions, removed: removedDeferredSession } =
omitRemovedSshTargetTabSessions(state.deferredSshSessionIdsByTabId, targetId, targetTabIds)
// Why: pending-reconnect holds each tab's pre-restart session until reconnect
// drains it; if the target is removed first the entry is dead but the orphan
// sweep now reads it as liveness, so clear it here too (#9911).
const { next: nextPendingReconnect, removed: removedPendingReconnect } =
omitRemovedSshTargetTabSessions(state.pendingReconnectPtyIdByTabId, targetId, targetTabIds)

const nextDeferredTargets = state.deferredSshReconnectTargets.filter((id) => id !== targetId)
const nextTransientClearedConnections = {
Expand Down Expand Up @@ -189,7 +209,8 @@ export function buildRemovedSshTargetCleanupPatch(
tabPtyState.changed ||
removedCredentialRequest ||
removedDeferredTarget ||
removedDeferredSession
removedDeferredSession ||
removedPendingReconnect
if (!changed) {
return null
}
Expand All @@ -215,6 +236,7 @@ export function buildRemovedSshTargetCleanupPatch(
: {}),
...(removedCredentialRequest ? { sshCredentialQueue: nextCredentialQueue } : {}),
...(removedDeferredTarget ? { deferredSshReconnectTargets: nextDeferredTargets } : {}),
...(removedDeferredSession ? { deferredSshSessionIdsByTabId: nextDeferredSessions } : {})
...(removedDeferredSession ? { deferredSshSessionIdsByTabId: nextDeferredSessions } : {}),
...(removedPendingReconnect ? { pendingReconnectPtyIdByTabId: nextPendingReconnect } : {})
}
}
13 changes: 13 additions & 0 deletions src/renderer/src/store/slices/ssh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,14 @@ describe('createSshSlice', () => {
'tab-ssh': 'legacy-session-without-target-prefix',
'tab-stale-encoded': toAppSshPtyId(targetId, 'pty-1'),
'tab-other': toAppSshPtyId(otherTargetId, 'pty-2')
},
// Why: a hydrated-but-not-yet-reconnected session for the removed target;
// the orphan sweep reads this map as liveness, so removal must clear it or
// a dead tab is pinned alive forever (#9911).
pendingReconnectPtyIdByTabId: {
'tab-ssh': toAppSshPtyId(targetId, 'pty-1'),
'tab-stale-encoded': toAppSshPtyId(targetId, 'pty-9'),
'tab-other': toAppSshPtyId(otherTargetId, 'pty-2')
}
})

Expand All @@ -126,6 +134,11 @@ describe('createSshSlice', () => {
expect(state.deferredSshSessionIdsByTabId).toEqual({
'tab-other': toAppSshPtyId(otherTargetId, 'pty-2')
})
// Removed target's pending-reconnect sessions cleared (by tab membership and
// by target-scoped session id); the surviving target's entry is retained.
expect(state.pendingReconnectPtyIdByTabId).toEqual({
'tab-other': toAppSshPtyId(otherTargetId, 'pty-2')
})
expect(state.tabsByWorktree[worktreeId][0]).toMatchObject({ id: 'tab-ssh', ptyId: null })
expect('pendingActivationSpawn' in state.tabsByWorktree[worktreeId][0]).toBe(false)
expect(state.ptyIdsByTabId['tab-ssh']).toEqual([])
Expand Down
51 changes: 50 additions & 1 deletion src/renderer/src/store/slices/store-cascades.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ import {
seedStore
} from './store-test-helpers'
import { shutdownBufferCaptures } from '@/components/terminal-pane/shutdown-buffer-captures'
import { buildOrphanTerminalCleanupPatch } from './terminal-orphan-helpers'
import { buildOrphanTerminalCleanupPatch, getOrphanTerminalIds } from './terminal-orphan-helpers'
import {
loadSessionCommitDrafts,
saveSessionCommitDrafts
Expand Down Expand Up @@ -1302,6 +1302,55 @@ describe('setActiveWorktree', () => {
)
})

// Regression for #9911: a split SSH tab's single relay slot points at the
// last-bound pane; when it exits, clearTabPtyId must promote a surviving pane
// instead of clearing, or a later relay-drop bulk-clear leaves the survivor
// visible only in the layout leaf map and the orphan sweep deletes the live tab.
it('promotes a surviving pane into the relay slot so a split tab is not orphaned after a relay drop', () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const tabId = 'tab-split'

seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: { [wt]: [makeTab({ id: tabId, worktreeId: wt, ptyId: 'pty-B' })] },
ptyIdsByTabId: { [tabId]: ['pty-A', 'pty-B'] },
// Newest-bound pane B owns the single relay slot.
lastKnownRelayPtyIdByTabId: { [tabId]: 'pty-B' },
terminalLayoutsByTabId: {
[tabId]: {
root: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: 'leaf-a' },
second: { type: 'leaf', leafId: 'leaf-b' }
},
activeLeafId: 'leaf-a',
expandedLeafId: null,
ptyIdsByLeafId: { 'leaf-a': 'pty-A', 'leaf-b': 'pty-B' }
}
},
// The transiently-absent unified entry is the condition #9911 recovers from.
unifiedTabsByWorktree: { [wt]: [] }
})

// Pane B (the relay-slot owner) exits: the slot must fall back to survivor A.
store.getState().clearTabPtyId(tabId, 'pty-B')
expect(store.getState().ptyIdsByTabId[tabId]).toEqual(['pty-A'])
expect(store.getState().lastKnownRelayPtyIdByTabId[tabId]).toBe('pty-A')

// Relay drop bulk-clears the row + live index but preserves the relay slot.
store.getState().clearTabPtyId(tabId)
const state = store.getState()
expect(state.ptyIdsByTabId[tabId]).toEqual([])
expect(state.tabsByWorktree[wt][0].ptyId).toBeNull()
expect(state.lastKnownRelayPtyIdByTabId[tabId]).toBe('pty-A')
// Survivor A is still reconnectable, so the sweep must not delete the tab.
expect(getOrphanTerminalIds(state, wt)).not.toContain(tabId)
})

it('stores trimmed quick command labels on terminal and unified tabs', () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
Expand Down
39 changes: 39 additions & 0 deletions src/renderer/src/store/slices/tabs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1831,6 +1831,45 @@ describe('TabsSlice', () => {
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBeNull()
})

// Regression for #9911: a reconnecting terminal (ptyId/ptyIdsByTabId cleared
// on SSH-relay drop or hydration, live session held in a reconnect map) whose
// unified entry is transiently absent must not be hard-deleted by the orphan
// sweep before reconnect rebinds it.
it('keeps a reconnecting terminal whose live session survives only in a reconnect map', () => {
store.setState({
tabsByWorktree: {
[WT]: [
{
id: 'reconnecting-terminal',
ptyId: null,
worktreeId: WT,
title: 'claude',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
ptyIdsByTabId: { 'reconnecting-terminal': [] },
pendingReconnectPtyIdByTabId: { 'reconnecting-terminal': 'session-live' },
unifiedTabsByWorktree: { [WT]: [] },
groupsByWorktree: {},
activeGroupIdByWorktree: {}
})

const result = store.getState().reconcileWorktreeTabModel(WT)
const state = store.getState()

// The live tab survives the sweep…
expect(state.tabsByWorktree[WT].map((tab) => tab.id)).toContain('reconnecting-terminal')
// …and is re-migrated into the unified model so it renders and can reattach.
expect(state.unifiedTabsByWorktree[WT].map((tab) => tab.entityId)).toContain(
'reconnecting-terminal'
)
expect(result.renderableTabCount).toBe(1)
})

it('keeps simulator tabs because they reconnect their own backing stream', () => {
const terminalGroupId = 'g-terminal'
const simulatorGroupId = 'g-simulator'
Expand Down
13 changes: 9 additions & 4 deletions src/renderer/src/store/slices/tabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ import {
} from './tab-group-state'
import { isPaneColumnSplitDropNoOp } from './pane-column-split-drop-no-op'
import { buildHydratedTabState, pruneTabGroupLayoutForGroups } from './tabs-hydration'
import { buildOrphanTerminalCleanupPatch, getOrphanTerminalIds } from './terminal-orphan-helpers'
import {
buildOrphanTerminalCleanupPatch,
getOrphanTerminalIds,
terminalTabHasReconnectablePty
} from './terminal-orphan-helpers'
import { createBrowserUuid } from '@/lib/browser-uuid'
import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner'
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants'
Expand Down Expand Up @@ -1759,9 +1763,10 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
if (unifiedTerminalEntityIds.has(tab.id)) {
return false
}
// Why: migration filter — tab.ptyId (preserved sessionId) keeps slept tabs in the sweep for wake reattach; NOT a liveness check (use ptyIdsByTabId).
const livePtyIds = state.ptyIdsByTabId[tab.id] ?? []
return livePtyIds.length > 0 || tab.ptyId != null
// Why: migration filter — keep any tab still owning a live/reconnecting
// PTY (preserved sessionId or a reconnect-map session) so it re-enters the
// unified model for wake/reconnect reattach instead of vanishing (#9911).
return terminalTabHasReconnectablePty(state, tab.id, tab.ptyId)
})
const orphanTerminalIds = getOrphanTerminalIds(state, worktreeId)
const ensuredGroupState =
Expand Down
115 changes: 115 additions & 0 deletions src/renderer/src/store/slices/terminal-orphan-helpers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { describe, expect, it } from 'vitest'
import type { TerminalTab } from '../../../../shared/types'
import { getOrphanTerminalIds } from './terminal-orphan-helpers'
import { buildTerminalTabRetirementPlan } from './terminal-tab-retirement'

// Regression coverage for #9911 ("Terminal window auto-closing. Unable to
// recover."). After hydration / SSH-relay disconnect the tab row's ptyId and
// ptyIdsByTabId are cleared, but the still-live session survives in one of the
// reconnect maps (pendingReconnectPtyIdByTabId / lastKnownRelayPtyIdByTabId /
// deferredSshSessionIdsByTabId). buildTerminalTabRetirementPlan treats those as
// live ownership; the orphan sweep must agree, or it hard-deletes a live tab
// (and its scrollback) before reconnect can rebind it.

// Why: superset state that satisfies both getOrphanTerminalIds (orphan sweep)
// and buildTerminalTabRetirementPlan (retirement authority) so one fixture can
// prove the two agree on liveness.
type TestState = Parameters<typeof buildTerminalTabRetirementPlan>[0]

function makeTab(overrides: Partial<TerminalTab> & { id: string }): TerminalTab {
return {
ptyId: null,
worktreeId: 'wt-1',
title: 'claude',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 0,
...overrides
}
}

function makeState(overrides: Partial<TestState> = {}): TestState {
return {
worktreesByRepo: { repo: [{ id: 'wt-1', repoId: 'repo', hostId: 'local' }] },
tabsByWorktree: {},
unifiedTabsByWorktree: {},
ptyIdsByTabId: {},
terminalLayoutsByTabId: {},
lastKnownRelayPtyIdByTabId: {},
deferredSshSessionIdsByTabId: {},
pendingReconnectPtyIdByTabId: {},
...overrides
} as TestState
}

describe('getOrphanTerminalIds reconnect-map liveness', () => {
it('does not orphan a tab whose live session survives in pendingReconnectPtyIdByTabId', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'T1', ptyId: null })] },
ptyIdsByTabId: { T1: [] },
unifiedTabsByWorktree: { 'wt-1': [] },
pendingReconnectPtyIdByTabId: { T1: 'session-live' }
})

// The retirement authority already treats the reconnecting session as a
// live PTY it must tear down on close…
expect(buildTerminalTabRetirementPlan(state, 'T1').ptyIds).toContain('session-live')
// …so the orphan sweep must not classify the same tab as dead.
expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('T1')
})

it('does not orphan a tab whose live session survives in lastKnownRelayPtyIdByTabId', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'T1' })] },
ptyIdsByTabId: { T1: [] },
unifiedTabsByWorktree: { 'wt-1': [] },
lastKnownRelayPtyIdByTabId: { T1: 'relay:conn@@pty-live' }
})

expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('T1')
})

it('does not orphan a tab whose live session survives in deferredSshSessionIdsByTabId', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'T1' })] },
ptyIdsByTabId: { T1: [] },
unifiedTabsByWorktree: { 'wt-1': [] },
deferredSshSessionIdsByTabId: { T1: 'ssh-session-live' }
})

expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('T1')
})

it('still orphans a tab with no live PTY evidence anywhere', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'dead', ptyId: null })] },
ptyIdsByTabId: { dead: [] },
unifiedTabsByWorktree: { 'wt-1': [] }
})

expect(getOrphanTerminalIds(state, 'wt-1')).toContain('dead')
})

// A persisted layout leaf binding is NOT a liveness signal: SSH-target removal
// nulls ptyId/ptyIdsByTabId/reconnect maps but intentionally leaves the layout
// leaf ptyIds pointing at a relay that is gone. Such a tab must still be swept,
// or it lingers forever bound to a dead relay it can never reattach.
it('still orphans a tab whose only reference is a stale layout leaf binding', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'stale-layout', ptyId: null })] },
ptyIdsByTabId: { 'stale-layout': [] },
unifiedTabsByWorktree: { 'wt-1': [] },
terminalLayoutsByTabId: {
'stale-layout': {
root: { type: 'leaf', leafId: 'leaf-1' },
activeLeafId: 'leaf-1',
expandedLeafId: null,
ptyIdsByLeafId: { 'leaf-1': 'dead-relay-pty' }
}
}
})

expect(getOrphanTerminalIds(state, 'wt-1')).toContain('stale-layout')
})
})
Loading
Loading