perf(renderer): sweep suppressedPtyExitIds and pendingCodexPaneRestartIds on bulk worktree purge (#7656)
* perf(renderer): sweep suppressedPtyExitIds and pendingCodexPaneRestartIds on bulk worktree purge Both are ptyId-keyed maps cleared alongside codexRestartNoticeByPtyId on the normal pty-exit path, but buildWorktreePurgeState (remove-project / external authoritative-scan / hydration-stale reconcile) runs no terminal teardown and only swept codexRestartNoticeByPtyId and migrationUnsupportedByPtyId. A suppression / pending-restart flag planted just before a doomed pty's exit therefore stranded one entry per removed pty for the renderer session. Add both to omitByPtyId, matching their two swept siblings; extend the bulk-purge leak regression test to cover them. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(renderer): cover dormant PTYs in bulk purge * Fix worktree-purge PTY id leaks: proportional alias scan and stricter su - purgeWorktreeTerminalState now short-circuits the surviving-alias scan once every doomed remote handle alias is matched, instead of scanning every surviving tab's terminals on each purge. - Repo removal (removeRepo) no longer force-marks killed PTY ids as suppressed/pending-restart; those tabs are gone before async exit events fire, so retaining the guards just leaked entries. - Update tests to cover raw remote-handle aliasing against surviving local PTY ids and to assert the tightened cleanup behavior. * Fix environment-scoped remote PTY id handling for guards and lifecycle s - Canonicalize legacy remote PTY ids at attach time so guard/restart/notice maps stay scoped per runtime environment instead of colliding on raw aliases shared across environments. - Migrate suppressedPtyExitIds, pendingCodexPaneRestartIds, codexRestartNoticeByPtyId, and migrationUnsupportedByPtyId entries when a tab's PTY id transitions from a legacy alias to its scoped id. - Narrow shutdown/purge guard sets to renderer-visible PTY ids only, since raw exact-stop RPC handles never emit pane exit callbacks and previously caused cross-environment leakage and unnecessary alias scanning. - Prevent a late PTY exit from resurrecting a ptyIdsByTabId entry for a tab whose worktree/repo was already purged. --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
Jinjing
parent
ff104e523e
commit
d509ee7abe
@@ -13412,6 +13412,9 @@ describe('connectPanePty', () => {
|
||||
it('attaches remote runtime PTY handles instead of creating a replacement terminal', async () => {
|
||||
const { connectPanePty } = await import('./pty-connection')
|
||||
const transport = createMockTransport()
|
||||
transport.attach.mockImplementation(() => {
|
||||
transport.getPtyId.mockReturnValue('remote:env-1@@terminal-1')
|
||||
})
|
||||
transportFactoryQueue.push(transport)
|
||||
|
||||
mockStoreState = {
|
||||
@@ -13435,7 +13438,8 @@ describe('connectPanePty', () => {
|
||||
expect(transport.attach).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ existingPtyId: 'remote:terminal-1' })
|
||||
)
|
||||
expect(deps.syncPanePtyLayoutBinding).toHaveBeenCalledWith(2, 'remote:terminal-1')
|
||||
expect(deps.updateTabPtyId).toHaveBeenCalledWith('tab-1', 'remote:env-1@@terminal-1')
|
||||
expect(deps.syncPanePtyLayoutBinding).toHaveBeenCalledWith(2, 'remote:env-1@@terminal-1')
|
||||
})
|
||||
|
||||
it('cold-spawns slept remote runtime PTYs instead of reattaching the preserved handle', async () => {
|
||||
|
||||
@@ -7152,12 +7152,13 @@ export function connectPanePty(
|
||||
onError: reportError
|
||||
}
|
||||
})
|
||||
bindActivePanePty(attachPtyId, {
|
||||
const attachedPtyId = transport.getPtyId() ?? attachPtyId
|
||||
bindActivePanePty(attachedPtyId, {
|
||||
updateTabPtyId: 'if-missing',
|
||||
sampleVisibleForegroundAgent: true
|
||||
})
|
||||
if (attachPtyId === eagerLivePtyId) {
|
||||
registerPaneSerializerFor(attachPtyId)
|
||||
registerPaneSerializerFor(attachedPtyId)
|
||||
}
|
||||
} catch (err) {
|
||||
reportError(err instanceof Error ? err.message : String(err))
|
||||
@@ -7207,9 +7208,10 @@ export function connectPanePty(
|
||||
onError: reportError
|
||||
}
|
||||
})
|
||||
const attachedPtyId = transport.getPtyId() ?? spawnedPtyId
|
||||
// Why: this path reuses a PTY spawned by an earlier mount, so no
|
||||
// later spawn event will bind this remounted pane's DOM/container.
|
||||
bindActivePanePty(spawnedPtyId, {
|
||||
bindActivePanePty(attachedPtyId, {
|
||||
updateTabPtyId: 'if-missing',
|
||||
sampleVisibleForegroundAgent: true
|
||||
})
|
||||
|
||||
@@ -167,7 +167,7 @@ describe('createRemoteRuntimePtyTransport', () => {
|
||||
})
|
||||
|
||||
expect(onError).not.toHaveBeenCalled()
|
||||
expect(transport.getPtyId()).toBe('remote:terminal-1')
|
||||
expect(transport.getPtyId()).toBe('remote:env-1@@terminal-1')
|
||||
await vi.waitFor(() =>
|
||||
expect(latestSubscribePayload().capabilities).toEqual({
|
||||
ackOutput: 1,
|
||||
@@ -190,6 +190,18 @@ describe('createRemoteRuntimePtyTransport', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('scopes the same legacy handle independently for each runtime environment', async () => {
|
||||
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
|
||||
const first = createRemoteRuntimePtyTransport('env-1', { worktreeId: 'wt-1' })
|
||||
const second = createRemoteRuntimePtyTransport('env-2', { worktreeId: 'wt-2' })
|
||||
|
||||
first.attach({ existingPtyId: 'remote:terminal-1', callbacks: {} })
|
||||
second.attach({ existingPtyId: 'remote:terminal-1', callbacks: {} })
|
||||
|
||||
expect(first.getPtyId()).toBe('remote:env-1@@terminal-1')
|
||||
expect(second.getPtyId()).toBe('remote:env-2@@terminal-1')
|
||||
})
|
||||
|
||||
it('parks passive peers when another remote desktop owns the grid', async () => {
|
||||
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
|
||||
const { getFitOverrideForPty, setFitOverride } =
|
||||
|
||||
@@ -705,7 +705,9 @@ export function createRemoteRuntimePtyTransport(
|
||||
storedCallbacks.onError?.('Remote runtime terminal id is invalid.')
|
||||
return
|
||||
}
|
||||
remotePtyId = options.existingPtyId
|
||||
// Why: legacy restored ids omitted their runtime owner. Canonicalize at
|
||||
// attach so renderer stores and lifecycle guards never share raw aliases.
|
||||
remotePtyId = toRemoteRuntimePtyId(handle, currentRuntimeEnvironmentId)
|
||||
connected = true
|
||||
desiredViewport = {
|
||||
cols: options.cols ?? 80,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Memory-leak regression: seven per-tab / per-pty terminal+agent store maps were
|
||||
* Memory-leak regression: nine per-tab / per-pty terminal+agent store maps were
|
||||
* evicted on the SINGLE removeWorktree path (via closeTab / shutdownWorktreeTerminals)
|
||||
* but NOT on the BULK path — `buildWorktreePurgeState`, reached by removeProject, the
|
||||
* external-worktree-removal authoritative-scan reconcile, and the hydration-stale
|
||||
@@ -11,11 +11,13 @@
|
||||
* Tab-keyed (evicted via the doomed-tab set):
|
||||
* lastKnownRelayPtyIdByTabId, pendingInitialCwdByTabId,
|
||||
* pendingIssueCommandSplitByTabId, pendingSetupSplitByTabId, pendingStartupByTabId
|
||||
* Pty-keyed (evicted via the doomed-pty set derived from ptyIdsByTabId):
|
||||
* codexRestartNoticeByPtyId, migrationUnsupportedByPtyId
|
||||
* Pty-keyed (evicted via the doomed-pty set derived from live and durable bindings):
|
||||
* codexRestartNoticeByPtyId, migrationUnsupportedByPtyId,
|
||||
* suppressedPtyExitIds, pendingCodexPaneRestartIds
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type * as AgentStatusModule from '@/lib/agent-status'
|
||||
import type * as RuntimeTerminalStreamModule from '@/runtime/runtime-terminal-stream'
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() }
|
||||
@@ -31,6 +33,11 @@ vi.mock('@/lib/agent-status', async (importOriginal) => {
|
||||
return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) }
|
||||
})
|
||||
|
||||
vi.mock('@/runtime/runtime-terminal-stream', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof RuntimeTerminalStreamModule>()
|
||||
return { ...actual, parseRemoteRuntimePtyId: vi.fn(actual.parseRemoteRuntimePtyId) }
|
||||
})
|
||||
|
||||
const mockApi = {
|
||||
worktrees: { list: vi.fn().mockResolvedValue([]), remove: vi.fn().mockResolvedValue(undefined) },
|
||||
pty: { kill: vi.fn().mockResolvedValue(undefined) }
|
||||
@@ -40,12 +47,17 @@ const mockApi = {
|
||||
globalThis.window = { api: mockApi }
|
||||
|
||||
import { createTestStore, seedStore, makeWorktree, makeTab } from './store-test-helpers'
|
||||
import { parseRemoteRuntimePtyId } from '@/runtime/runtime-terminal-stream'
|
||||
|
||||
const WT1 = 'repo1::/path/wt1'
|
||||
const WT2 = 'repo1::/path/wt2'
|
||||
const TAB1 = 'tab-wt1'
|
||||
const TAB2 = 'tab-wt2'
|
||||
const PTY1 = 'pty-wt1'
|
||||
const PTY1_SPLIT = 'pty-wt1-split'
|
||||
const REMOTE_PTY1 = 'remote:env-1@@terminal-wt1'
|
||||
const REMOTE_HANDLE1 = 'terminal-wt1'
|
||||
const REMOTE_PTY2_SAME_HANDLE = 'remote:env-2@@terminal-wt1'
|
||||
const PTY2 = 'pty-wt2'
|
||||
|
||||
function seedMaps(store: ReturnType<typeof createTestStore>): void {
|
||||
@@ -60,8 +72,22 @@ function seedMaps(store: ReturnType<typeof createTestStore>): void {
|
||||
[WT1]: [makeTab({ id: TAB1, worktreeId: WT1, ptyId: PTY1 })],
|
||||
[WT2]: [makeTab({ id: TAB2, worktreeId: WT2, ptyId: PTY2 })]
|
||||
},
|
||||
// Drives the doomed-ptyId derivation in buildWorktreePurgeState.
|
||||
ptyIdsByTabId: { [TAB1]: [PTY1], [TAB2]: [PTY2] },
|
||||
// A slept/stale tab has already left the live index, so purge must recover
|
||||
// its owned PTY ids from the durable tab/layout wake hints instead.
|
||||
ptyIdsByTabId: { [TAB1]: [], [TAB2]: [PTY2] },
|
||||
terminalLayoutsByTabId: {
|
||||
[TAB1]: {
|
||||
root: {
|
||||
type: 'split',
|
||||
direction: 'horizontal',
|
||||
first: { type: 'leaf', leafId: 'leaf-1' },
|
||||
second: { type: 'leaf', leafId: 'leaf-2' }
|
||||
},
|
||||
activeLeafId: 'leaf-1',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { 'leaf-1': PTY1_SPLIT, 'leaf-2': REMOTE_PTY1 }
|
||||
}
|
||||
},
|
||||
lastKnownRelayPtyIdByTabId: { [TAB1]: PTY1, [TAB2]: PTY2 },
|
||||
pendingInitialCwdByTabId: { [TAB1]: '/path/wt1', [TAB2]: '/path/wt2' },
|
||||
pendingIssueCommandSplitByTabId: {
|
||||
@@ -92,6 +118,18 @@ function seedMaps(store: ReturnType<typeof createTestStore>): void {
|
||||
source: 'local',
|
||||
updatedAt: 2
|
||||
}
|
||||
},
|
||||
suppressedPtyExitIds: {
|
||||
[PTY1]: true,
|
||||
[PTY1_SPLIT]: true,
|
||||
[REMOTE_PTY1]: true,
|
||||
[PTY2]: true
|
||||
},
|
||||
pendingCodexPaneRestartIds: {
|
||||
[PTY1]: true,
|
||||
[PTY1_SPLIT]: true,
|
||||
[REMOTE_PTY1]: true,
|
||||
[PTY2]: true
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -114,6 +152,12 @@ describe('bulk worktree purge evicts the per-tab/per-pty terminal maps it previo
|
||||
expect(s.pendingStartupByTabId[TAB1]).toBeUndefined()
|
||||
expect(s.codexRestartNoticeByPtyId[PTY1]).toBeUndefined()
|
||||
expect(s.migrationUnsupportedByPtyId[PTY1]).toBeUndefined()
|
||||
expect(s.suppressedPtyExitIds[PTY1]).toBeUndefined()
|
||||
expect(s.suppressedPtyExitIds[PTY1_SPLIT]).toBeUndefined()
|
||||
expect(s.suppressedPtyExitIds[REMOTE_PTY1]).toBeUndefined()
|
||||
expect(s.pendingCodexPaneRestartIds[PTY1]).toBeUndefined()
|
||||
expect(s.pendingCodexPaneRestartIds[PTY1_SPLIT]).toBeUndefined()
|
||||
expect(s.pendingCodexPaneRestartIds[REMOTE_PTY1]).toBeUndefined()
|
||||
|
||||
// Surviving worktree's tab/pty: every entry retained (no over-eviction).
|
||||
expect(s.lastKnownRelayPtyIdByTabId[TAB2]).toBe(PTY2)
|
||||
@@ -123,5 +167,74 @@ describe('bulk worktree purge evicts the per-tab/per-pty terminal maps it previo
|
||||
expect(s.pendingStartupByTabId[TAB2]).toEqual({ command: 'start-b' })
|
||||
expect(s.codexRestartNoticeByPtyId[PTY2]).toBeDefined()
|
||||
expect(s.migrationUnsupportedByPtyId[PTY2]).toBeDefined()
|
||||
expect(s.suppressedPtyExitIds[PTY2]).toBe(true)
|
||||
expect(s.pendingCodexPaneRestartIds[PTY2]).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps environment-scoped remote guard identities independent', () => {
|
||||
const store = createTestStore()
|
||||
seedMaps(store)
|
||||
store.setState((s) => ({
|
||||
ptyIdsByTabId: {
|
||||
...s.ptyIdsByTabId,
|
||||
[TAB2]: [...s.ptyIdsByTabId[TAB2], REMOTE_PTY2_SAME_HANDLE]
|
||||
},
|
||||
suppressedPtyExitIds: {
|
||||
...s.suppressedPtyExitIds,
|
||||
[REMOTE_PTY2_SAME_HANDLE]: true
|
||||
},
|
||||
pendingCodexPaneRestartIds: {
|
||||
...s.pendingCodexPaneRestartIds,
|
||||
[REMOTE_PTY2_SAME_HANDLE]: true
|
||||
}
|
||||
}))
|
||||
|
||||
store.getState().purgeWorktreeTerminalState([WT1])
|
||||
const s = store.getState()
|
||||
|
||||
expect(s.suppressedPtyExitIds[REMOTE_PTY1]).toBeUndefined()
|
||||
expect(s.pendingCodexPaneRestartIds[REMOTE_PTY1]).toBeUndefined()
|
||||
expect(s.suppressedPtyExitIds[REMOTE_PTY2_SAME_HANDLE]).toBe(true)
|
||||
expect(s.pendingCodexPaneRestartIds[REMOTE_PTY2_SAME_HANDLE]).toBe(true)
|
||||
})
|
||||
|
||||
it('retains a raw remote handle that is also a surviving local PTY id', () => {
|
||||
const store = createTestStore()
|
||||
seedMaps(store)
|
||||
store.setState((s) => ({
|
||||
ptyIdsByTabId: {
|
||||
...s.ptyIdsByTabId,
|
||||
[TAB2]: [...s.ptyIdsByTabId[TAB2], REMOTE_HANDLE1]
|
||||
},
|
||||
pendingCodexPaneRestartIds: {
|
||||
...s.pendingCodexPaneRestartIds,
|
||||
[REMOTE_HANDLE1]: true
|
||||
},
|
||||
suppressedPtyExitIds: {
|
||||
...s.suppressedPtyExitIds,
|
||||
[REMOTE_HANDLE1]: true
|
||||
}
|
||||
}))
|
||||
|
||||
store.getState().purgeWorktreeTerminalState([WT1])
|
||||
const s = store.getState()
|
||||
|
||||
expect(s.suppressedPtyExitIds[REMOTE_PTY1]).toBeUndefined()
|
||||
expect(s.pendingCodexPaneRestartIds[REMOTE_PTY1]).toBeUndefined()
|
||||
expect(s.suppressedPtyExitIds[REMOTE_HANDLE1]).toBe(true)
|
||||
expect(s.pendingCodexPaneRestartIds[REMOTE_HANDLE1]).toBe(true)
|
||||
})
|
||||
|
||||
it('does not parse aliases for environment-scoped remote guard cleanup', () => {
|
||||
const store = createTestStore()
|
||||
seedMaps(store)
|
||||
const parseRemotePtyId = vi.mocked(parseRemoteRuntimePtyId)
|
||||
parseRemotePtyId.mockClear()
|
||||
|
||||
store.getState().purgeWorktreeTerminalState([WT1])
|
||||
|
||||
// Why: guard keys stay scoped to their environment, so purge can delete
|
||||
// exact identities without parsing aliases or scanning surviving terminals.
|
||||
expect(parseRemotePtyId).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2794,7 +2794,6 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
|
||||
// Kill PTYs for all worktrees belonging to this repo
|
||||
const worktreeIds = getKnownRepoWorktreeIds(get(), projectId, ownerHostId)
|
||||
const killedTabIds = new Set<string>()
|
||||
const killedPtyIds = new Set<string>()
|
||||
if (target.kind === 'environment') {
|
||||
await Promise.allSettled(
|
||||
worktreeIds.map((worktreeId) =>
|
||||
@@ -2812,7 +2811,6 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
|
||||
for (const tab of tabs) {
|
||||
killedTabIds.add(tab.id)
|
||||
for (const ptyId of get().ptyIdsByTabId[tab.id] ?? []) {
|
||||
killedPtyIds.add(ptyId)
|
||||
if (!ptyId.startsWith('remote:')) {
|
||||
window.api.pty.kill(ptyId)
|
||||
}
|
||||
@@ -2853,7 +2851,6 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
|
||||
const nextLayouts = { ...s.terminalLayoutsByTabId }
|
||||
const nextPtyIdsByTabId = { ...s.ptyIdsByTabId }
|
||||
const nextRuntimePaneTitlesByTabId = { ...s.runtimePaneTitlesByTabId }
|
||||
const nextSuppressedPtyExitIds = { ...s.suppressedPtyExitIds }
|
||||
for (const wId of worktreeIds) {
|
||||
delete nextTabs[wId]
|
||||
}
|
||||
@@ -2862,9 +2859,6 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
|
||||
delete nextPtyIdsByTabId[tabId]
|
||||
delete nextRuntimePaneTitlesByTabId[tabId]
|
||||
}
|
||||
for (const ptyId of killedPtyIds) {
|
||||
nextSuppressedPtyExitIds[ptyId] = true
|
||||
}
|
||||
// Why: editor state is worktree-scoped. Removing a repo must also
|
||||
// remove open editor files and per-worktree active-file tracking for
|
||||
// all worktrees that belonged to the repo, otherwise orphaned entries
|
||||
@@ -2918,7 +2912,6 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
|
||||
tabsByWorktree: nextTabs,
|
||||
ptyIdsByTabId: nextPtyIdsByTabId,
|
||||
runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId,
|
||||
suppressedPtyExitIds: nextSuppressedPtyExitIds,
|
||||
terminalLayoutsByTabId: nextLayouts,
|
||||
activeTabId: s.activeTabId && killedTabIds.has(s.activeTabId) ? null : s.activeTabId,
|
||||
openFiles: nextOpenFiles,
|
||||
|
||||
@@ -3356,7 +3356,7 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
|
||||
}
|
||||
},
|
||||
ptyIdsByTabId: {
|
||||
'tab-1': ['remote:env-1@@terminal-1', 'remote:env-1@@terminal-2']
|
||||
'tab-1': ['remote:env-1@@terminal-1', 'remote:env-1@@terminal-2', 'terminal-1']
|
||||
}
|
||||
})
|
||||
store
|
||||
@@ -3392,7 +3392,15 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
|
||||
expect(mockApi.runtimeEnvironments.call).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ method: 'terminal.stop' })
|
||||
)
|
||||
expect(store.getState().ptyIdsByTabId['tab-1']).toEqual(['remote:env-1@@terminal-2'])
|
||||
expect(store.getState().ptyIdsByTabId['tab-1']).toEqual([
|
||||
'remote:env-1@@terminal-2',
|
||||
'terminal-1'
|
||||
])
|
||||
expect(mockUnregisterPtyDataHandlers).toHaveBeenCalledWith(['remote:env-1@@terminal-1'])
|
||||
expect(mockUnregisterPtyDataHandlers).not.toHaveBeenCalledWith(['terminal-1'])
|
||||
expect(store.getState().suppressedPtyExitIds['remote:env-1@@terminal-1']).toBe(true)
|
||||
expect(store.getState().suppressedPtyExitIds['remote:runtime-1@@terminal-1']).toBeUndefined()
|
||||
expect(store.getState().suppressedPtyExitIds['terminal-1']).toBeUndefined()
|
||||
expect(mockApi.pty.kill).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -3923,7 +3931,7 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
|
||||
tabsByWorktree: {
|
||||
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
|
||||
},
|
||||
ptyIdsByTabId: { 'tab-1': [] }
|
||||
ptyIdsByTabId: { 'tab-1': ['remote:runtime-1@@pty-1'] }
|
||||
})
|
||||
store.getState().setAgentStatus(
|
||||
'tab-1:live',
|
||||
@@ -3943,14 +3951,15 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
|
||||
sleepingPaneKeys: ['tab-1:live'],
|
||||
expectedRuntimePtyIds: ['pty-1']
|
||||
})
|
||||
expect(store.getState().suppressedPtyExitIds['pty-1']).toBe(true)
|
||||
|
||||
store.getState().updateTabPtyId('tab-1', 'pty-1')
|
||||
|
||||
expect(store.getState().suppressedPtyExitIds['remote:runtime-1@@pty-1']).toBe(true)
|
||||
expect(store.getState().suppressedPtyExitIds['pty-1']).toBeUndefined()
|
||||
|
||||
store.getState().updateTabPtyId('tab-1', 'remote:runtime-1@@pty-1')
|
||||
|
||||
expect(store.getState().suppressedPtyExitIds['remote:runtime-1@@pty-1']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('suppresses wrapped remote PTY exits before exact runtime stop resolves', async () => {
|
||||
it('suppresses only the scoped remote PTY identity before exact runtime stop resolves', async () => {
|
||||
const store = createTestStore()
|
||||
const wt = 'repo1::/path/wt1'
|
||||
let sawWrappedSuppressedDuringStop = false
|
||||
@@ -4014,10 +4023,57 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
|
||||
})
|
||||
|
||||
expect(sawWrappedSuppressedDuringStop).toBe(true)
|
||||
expect(sawRawSuppressedDuringStop).toBe(true)
|
||||
expect(store.getState().suppressedPtyExitIds['remote:runtime-1@@terminal-1']).toBeUndefined()
|
||||
expect(sawRawSuppressedDuringStop).toBe(false)
|
||||
expect(mockUnregisterPtyDataHandlers).toHaveBeenCalledWith(['remote:env-1@@terminal-1'])
|
||||
expect(mockUnregisterPtyDataHandlers).not.toHaveBeenCalledWith(['terminal-1'])
|
||||
})
|
||||
|
||||
it('clears raw and wrapped remote exit suppression when a remote PTY wakes live again', () => {
|
||||
it('still kills a local renderer PTY whose id matches a remote exact-stop handle', async () => {
|
||||
const store = createTestStore()
|
||||
const wt = 'repo1::/path/wt1'
|
||||
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) =>
|
||||
Promise.resolve(
|
||||
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
|
||||
id: 'rpc-default',
|
||||
ok: true,
|
||||
result:
|
||||
args.method === 'terminal.stopExact'
|
||||
? {
|
||||
stoppedPtyIds: ['terminal-1'],
|
||||
livePtyIds: ['terminal-1'],
|
||||
postStopVerified: true
|
||||
}
|
||||
: {},
|
||||
_meta: { runtimeId: 'remote-runtime' }
|
||||
}
|
||||
)
|
||||
)
|
||||
seedStore(store, {
|
||||
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
|
||||
worktreesByRepo: {
|
||||
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
|
||||
},
|
||||
tabsByWorktree: {
|
||||
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt })]
|
||||
},
|
||||
ptyIdsByTabId: {
|
||||
'tab-1': ['remote:runtime-1@@terminal-1', 'terminal-1']
|
||||
}
|
||||
})
|
||||
|
||||
await store.getState().shutdownWorktreeTerminals(wt, {
|
||||
expectedRuntimePtyIds: ['terminal-1']
|
||||
})
|
||||
|
||||
expect(mockApi.pty.kill).toHaveBeenCalledWith('terminal-1', { keepHistory: false })
|
||||
expect(mockUnregisterPtyDataHandlers).toHaveBeenCalledWith([
|
||||
'remote:runtime-1@@terminal-1',
|
||||
'terminal-1'
|
||||
])
|
||||
})
|
||||
|
||||
it('does not consume a colliding raw PTY guard when a scoped remote PTY wakes', () => {
|
||||
const store = createTestStore()
|
||||
const wt = 'repo1::/path/wt1'
|
||||
|
||||
@@ -4036,7 +4092,51 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
|
||||
store.getState().updateTabPtyId('tab-1', 'remote:env-1@@terminal-1')
|
||||
|
||||
expect(store.getState().suppressedPtyExitIds['remote:env-1@@terminal-1']).toBeUndefined()
|
||||
expect(store.getState().suppressedPtyExitIds['terminal-1']).toBeUndefined()
|
||||
expect(store.getState().suppressedPtyExitIds['terminal-1']).toBe(true)
|
||||
})
|
||||
|
||||
it('migrates legacy remote lifecycle state to the scoped PTY identity on attach', () => {
|
||||
const store = createTestStore()
|
||||
const wt = 'repo1::/path/wt1'
|
||||
const legacyPtyId = 'remote:terminal-1'
|
||||
const scopedPtyId = 'remote:env-1@@terminal-1'
|
||||
seedStore(store, {
|
||||
worktreesByRepo: {
|
||||
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
|
||||
},
|
||||
tabsByWorktree: {
|
||||
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, ptyId: legacyPtyId })]
|
||||
},
|
||||
ptyIdsByTabId: { 'tab-1': [legacyPtyId] },
|
||||
suppressedPtyExitIds: { [legacyPtyId]: true },
|
||||
pendingCodexPaneRestartIds: { [legacyPtyId]: true },
|
||||
codexRestartNoticeByPtyId: {
|
||||
[legacyPtyId]: { previousAccountLabel: 'old', nextAccountLabel: 'new' }
|
||||
},
|
||||
migrationUnsupportedByPtyId: {
|
||||
[legacyPtyId]: {
|
||||
ptyId: legacyPtyId,
|
||||
paneKey: 'tab-1:leaf-1',
|
||||
reason: 'legacy-numeric-pane-key',
|
||||
source: 'local',
|
||||
updatedAt: 1
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
store.getState().updateTabPtyId('tab-1', scopedPtyId)
|
||||
const state = store.getState()
|
||||
|
||||
expect(state.ptyIdsByTabId['tab-1']).toEqual([scopedPtyId])
|
||||
expect(state.tabsByWorktree[wt][0]?.ptyId).toBe(scopedPtyId)
|
||||
expect(state.suppressedPtyExitIds[legacyPtyId]).toBeUndefined()
|
||||
expect(state.suppressedPtyExitIds[scopedPtyId]).toBeUndefined()
|
||||
expect(state.pendingCodexPaneRestartIds).toEqual({ [scopedPtyId]: true })
|
||||
expect(state.codexRestartNoticeByPtyId[scopedPtyId]).toEqual({
|
||||
previousAccountLabel: 'old',
|
||||
nextAccountLabel: 'new'
|
||||
})
|
||||
expect(state.migrationUnsupportedByPtyId[scopedPtyId]?.ptyId).toBe(scopedPtyId)
|
||||
})
|
||||
|
||||
it('commits the pre-stop sleeping record when exact-stop exit clears live status', async () => {
|
||||
|
||||
@@ -186,6 +186,8 @@ describe('removeProject cascade', () => {
|
||||
tab1: ['pty1'],
|
||||
tab2: ['pty2']
|
||||
},
|
||||
suppressedPtyExitIds: { pty1: true, pty2: true },
|
||||
pendingCodexPaneRestartIds: { pty1: true, pty2: true },
|
||||
terminalLayoutsByTabId: {
|
||||
tab1: makeLayout(),
|
||||
tab2: makeLayout()
|
||||
@@ -212,9 +214,20 @@ describe('removeProject cascade', () => {
|
||||
expect(mockApi.pty.kill).toHaveBeenCalledWith('pty1')
|
||||
expect(mockApi.pty.kill).toHaveBeenCalledWith('pty2')
|
||||
|
||||
// Killed PTY IDs are suppressed
|
||||
expect(s.suppressedPtyExitIds['pty1']).toBe(true)
|
||||
expect(s.suppressedPtyExitIds['pty2']).toBe(true)
|
||||
// The tabs are gone before async exit events can close them, so retaining
|
||||
// their one-shot guards would leak ephemeral PTY ids for the renderer session.
|
||||
expect(s.suppressedPtyExitIds['pty1']).toBeUndefined()
|
||||
expect(s.suppressedPtyExitIds['pty2']).toBeUndefined()
|
||||
expect(s.pendingCodexPaneRestartIds['pty1']).toBeUndefined()
|
||||
expect(s.pendingCodexPaneRestartIds['pty2']).toBeUndefined()
|
||||
|
||||
store.getState().clearTabPtyId('tab1', 'pty1')
|
||||
store.getState().clearTabPtyId('tab2', 'pty2')
|
||||
|
||||
// Why: exit IPC can arrive after repo purge but before the mounted pane
|
||||
// unmounts. A late exit must not recreate an index for a tab with no owner.
|
||||
expect(store.getState().ptyIdsByTabId['tab1']).toBeUndefined()
|
||||
expect(store.getState().ptyIdsByTabId['tab2']).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ import {
|
||||
} from '@/components/terminal-pane/terminal-layout-leaf-ids'
|
||||
import { shutdownBufferCaptures } from '@/components/terminal-pane/shutdown-buffer-captures'
|
||||
import { callRuntimeRpc } from '@/runtime/runtime-rpc-client'
|
||||
import { parseRemoteRuntimePtyId } from '@/runtime/runtime-terminal-stream'
|
||||
import { parseRemoteRuntimePtyId, toRemoteRuntimePtyId } from '@/runtime/runtime-terminal-stream'
|
||||
import { toRuntimeWorktreeSelector } from '@/runtime/runtime-worktree-selector'
|
||||
import { createBrowserUuid } from '@/lib/browser-uuid'
|
||||
import { getFolderWorkspaceConnectionId } from '@/lib/folder-workspace-connection'
|
||||
@@ -456,6 +456,8 @@ export type TerminalSlice = {
|
||||
/** Agent-completion source marker for focus-return auto-ack. Kept separate
|
||||
* from unreadTerminalPanes so generic terminal bells still show until interact. */
|
||||
unreadAgentCompletionPanes: Record<string, true>
|
||||
// Remote guard keys must use renderer-visible, environment-scoped PTY ids;
|
||||
// raw runtime handles are only valid at the RPC boundary.
|
||||
suppressedPtyExitIds: Record<string, true>
|
||||
pendingCodexPaneRestartIds: Record<string, true>
|
||||
codexRestartNoticeByPtyId: Record<
|
||||
@@ -1868,9 +1870,16 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
const isRemoteRuntimeMirror = isRemoteRuntimePtyId(ptyId)
|
||||
set((s) => {
|
||||
const existingPtyIds = s.ptyIdsByTabId[tabId] ?? []
|
||||
const nextPtyIds = existingPtyIds.includes(ptyId)
|
||||
? existingPtyIds
|
||||
: [...existingPtyIds, ptyId]
|
||||
const remote = parseRemoteRuntimePtyId(ptyId)
|
||||
const legacyRemotePtyId = remote?.environmentId ? toRemoteRuntimePtyId(remote.handle) : null
|
||||
const hasLegacyPtyBinding = legacyRemotePtyId
|
||||
? existingPtyIds.includes(legacyRemotePtyId)
|
||||
: false
|
||||
const nextPtyIds = hasLegacyPtyBinding
|
||||
? [...new Set(existingPtyIds.map((id) => (id === legacyRemotePtyId ? ptyId : id)))]
|
||||
: existingPtyIds.includes(ptyId)
|
||||
? existingPtyIds
|
||||
: [...existingPtyIds, ptyId]
|
||||
let nextTabsByWorktree = s.tabsByWorktree
|
||||
for (const [wId, tabs] of Object.entries(s.tabsByWorktree)) {
|
||||
const index = tabs.findIndex((t) => t.id === tabId)
|
||||
@@ -1891,7 +1900,8 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
// paths. In split panes, later pane spawns must not steal that
|
||||
// primary binding from the original pane or remount/close flows can
|
||||
// reattach the tab to the wrong PTY and appear to "reset" panes.
|
||||
const nextTabPtyId = tab.ptyId ?? nextPtyIds[0] ?? null
|
||||
const currentTabPtyId = tab.ptyId === legacyRemotePtyId ? ptyId : tab.ptyId
|
||||
const nextTabPtyId = currentTabPtyId ?? nextPtyIds[0] ?? null
|
||||
const nextPendingActivationSpawn = consumePendingActivationSpawn(tab.pendingActivationSpawn)
|
||||
if (tab.pendingActivationSpawn || tab.ptyId !== nextTabPtyId) {
|
||||
const nextTabs = [...tabs]
|
||||
@@ -1917,9 +1927,45 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
const shouldBumpSortEpoch = isFirstPty && isActiveWorktree && !wasActivationSpawn
|
||||
const nextSuppressedPtyExitIds = { ...s.suppressedPtyExitIds }
|
||||
delete nextSuppressedPtyExitIds[ptyId]
|
||||
const remoteRuntimePtyHandle = parseRemoteRuntimePtyId(ptyId)?.handle
|
||||
if (remoteRuntimePtyHandle) {
|
||||
delete nextSuppressedPtyExitIds[remoteRuntimePtyHandle]
|
||||
if (legacyRemotePtyId) {
|
||||
delete nextSuppressedPtyExitIds[legacyRemotePtyId]
|
||||
}
|
||||
const hasLegacyPendingRestart = legacyRemotePtyId
|
||||
? legacyRemotePtyId in s.pendingCodexPaneRestartIds
|
||||
: false
|
||||
const hasLegacyRestartNotice = legacyRemotePtyId
|
||||
? legacyRemotePtyId in s.codexRestartNoticeByPtyId
|
||||
: false
|
||||
const hasLegacyMigrationUnsupported = legacyRemotePtyId
|
||||
? legacyRemotePtyId in s.migrationUnsupportedByPtyId
|
||||
: false
|
||||
const nextPendingCodexPaneRestartIds = hasLegacyPendingRestart
|
||||
? { ...s.pendingCodexPaneRestartIds }
|
||||
: s.pendingCodexPaneRestartIds
|
||||
const nextCodexRestartNoticeByPtyId = hasLegacyRestartNotice
|
||||
? { ...s.codexRestartNoticeByPtyId }
|
||||
: s.codexRestartNoticeByPtyId
|
||||
const nextMigrationUnsupportedByPtyId = hasLegacyMigrationUnsupported
|
||||
? { ...s.migrationUnsupportedByPtyId }
|
||||
: s.migrationUnsupportedByPtyId
|
||||
if (legacyRemotePtyId) {
|
||||
if (hasLegacyPendingRestart) {
|
||||
nextPendingCodexPaneRestartIds[ptyId] = true
|
||||
delete nextPendingCodexPaneRestartIds[legacyRemotePtyId]
|
||||
}
|
||||
if (hasLegacyRestartNotice) {
|
||||
const legacyNotice = nextCodexRestartNoticeByPtyId[legacyRemotePtyId]
|
||||
nextCodexRestartNoticeByPtyId[ptyId] ??= legacyNotice
|
||||
delete nextCodexRestartNoticeByPtyId[legacyRemotePtyId]
|
||||
}
|
||||
if (hasLegacyMigrationUnsupported) {
|
||||
const legacyMigrationUnsupported = nextMigrationUnsupportedByPtyId[legacyRemotePtyId]
|
||||
nextMigrationUnsupportedByPtyId[ptyId] ??= {
|
||||
...legacyMigrationUnsupported,
|
||||
ptyId
|
||||
}
|
||||
delete nextMigrationUnsupportedByPtyId[legacyRemotePtyId]
|
||||
}
|
||||
}
|
||||
return {
|
||||
...(nextTabsByWorktree !== s.tabsByWorktree ? { tabsByWorktree: nextTabsByWorktree } : {}),
|
||||
@@ -1932,6 +1978,9 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
[tabId]: ptyId
|
||||
},
|
||||
suppressedPtyExitIds: nextSuppressedPtyExitIds,
|
||||
pendingCodexPaneRestartIds: nextPendingCodexPaneRestartIds,
|
||||
codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId,
|
||||
migrationUnsupportedByPtyId: nextMigrationUnsupportedByPtyId,
|
||||
...(shouldBumpSortEpoch ? { sortEpoch: s.sortEpoch + 1 } : {})
|
||||
}
|
||||
})
|
||||
@@ -1994,7 +2043,13 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
break
|
||||
}
|
||||
const nextPtyIdsByTabId = { ...s.ptyIdsByTabId }
|
||||
nextPtyIdsByTabId[tabId] = remainingPtyIds
|
||||
if (worktreeId) {
|
||||
nextPtyIdsByTabId[tabId] = remainingPtyIds
|
||||
} else {
|
||||
// Why: repo purge can remove the owning tab before its asynchronous
|
||||
// exit arrives. Do not resurrect an orphan PTY index for a retired tab.
|
||||
delete nextPtyIdsByTabId[tabId]
|
||||
}
|
||||
const nextPendingCodexPaneRestartIds = { ...s.pendingCodexPaneRestartIds }
|
||||
const nextCodexRestartNoticeByPtyId = { ...s.codexRestartNoticeByPtyId }
|
||||
if (ptyId) {
|
||||
@@ -2044,8 +2099,12 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
const expectedRuntimePtyIds = sortedUniquePtyIds(
|
||||
opts.expectedRuntimePtyId ? [opts.expectedRuntimePtyId] : []
|
||||
)
|
||||
const shutdownPtyIds = sortedUniquePtyIds([opts.ptyId, ...expectedRuntimePtyIds])
|
||||
const rendererShutdownPtyIds = [opts.ptyId]
|
||||
const state = get()
|
||||
const runtimeEnvironmentId = resolveTerminalStopRuntimeEnvironmentId(state, worktreeId)
|
||||
// Why: pane transports emit renderer PTY ids, never raw exact-stop handles.
|
||||
// Guard only the identity that can actually deliver an exit callback.
|
||||
const exitGuardPtyIds = [opts.ptyId]
|
||||
const tab = (state.tabsByWorktree[worktreeId] ?? []).find(
|
||||
(candidate) => candidate.id === opts.tabId
|
||||
)
|
||||
@@ -2108,7 +2167,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
const rollbackTargetShutdownState = (): void => {
|
||||
set((s) => {
|
||||
const next = { ...s.suppressedPtyExitIds }
|
||||
for (const ptyId of shutdownPtyIds) {
|
||||
for (const ptyId of exitGuardPtyIds) {
|
||||
delete next[ptyId]
|
||||
}
|
||||
const nextSleeping = { ...s.sleepingAgentSessionsByPaneKey }
|
||||
@@ -2127,7 +2186,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
set((s) => ({
|
||||
suppressedPtyExitIds: {
|
||||
...s.suppressedPtyExitIds,
|
||||
...Object.fromEntries(shutdownPtyIds.map((ptyId) => [ptyId, true] as const))
|
||||
...Object.fromEntries(exitGuardPtyIds.map((ptyId) => [ptyId, true] as const))
|
||||
},
|
||||
sleepingAgentSessionsByPaneKey: {
|
||||
...s.sleepingAgentSessionsByPaneKey,
|
||||
@@ -2136,7 +2195,6 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
}))
|
||||
|
||||
if (expectedRuntimePtyIds.length > 0) {
|
||||
const runtimeEnvironmentId = resolveTerminalStopRuntimeEnvironmentId(get(), worktreeId)
|
||||
if (!runtimeEnvironmentId) {
|
||||
rollbackTargetShutdownState()
|
||||
throw new Error('missing_runtime_for_exact_terminal_stop')
|
||||
@@ -2179,11 +2237,11 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
rollbackTargetShutdownState()
|
||||
throw new Error(stopResult.postStopFailure ?? 'exact_terminal_stop_unverified')
|
||||
}
|
||||
unregisterPtyDataHandlers(shutdownPtyIds)
|
||||
unregisterPtyDataHandlers(rendererShutdownPtyIds)
|
||||
} else if (!opts.ptyId.startsWith('remote:')) {
|
||||
// Why: pty.kill can flush final data before exit; unregister first so
|
||||
// pane hibernation cannot fire phantom notifications from stale handlers.
|
||||
const handlerSnapshots = unregisterPtyDataHandlers(shutdownPtyIds)
|
||||
const handlerSnapshots = unregisterPtyDataHandlers(rendererShutdownPtyIds)
|
||||
try {
|
||||
await window.api.pty.kill(opts.ptyId, { keepHistory: true })
|
||||
} catch (err) {
|
||||
@@ -2195,7 +2253,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
|
||||
set((s) => {
|
||||
const existingPtyIds = s.ptyIdsByTabId[opts.tabId] ?? []
|
||||
const shutdownPtyIdSet = new Set(shutdownPtyIds)
|
||||
const shutdownPtyIdSet = new Set(rendererShutdownPtyIds)
|
||||
const remainingPtyIds = existingPtyIds.filter((ptyId) => !shutdownPtyIdSet.has(ptyId))
|
||||
const nextTabsByWorktree = { ...s.tabsByWorktree }
|
||||
const tabs = nextTabsByWorktree[worktreeId] ?? []
|
||||
@@ -2210,7 +2268,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
}
|
||||
|
||||
const nextCodexRestartNoticeByPtyId = { ...s.codexRestartNoticeByPtyId }
|
||||
for (const ptyId of shutdownPtyIds) {
|
||||
for (const ptyId of exitGuardPtyIds) {
|
||||
delete nextCodexRestartNoticeByPtyId[ptyId]
|
||||
}
|
||||
const nextLastKnownRelay =
|
||||
@@ -2253,7 +2311,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
lastKnownRelayPtyIdByTabId: nextLastKnownRelay,
|
||||
suppressedPtyExitIds: {
|
||||
...s.suppressedPtyExitIds,
|
||||
...Object.fromEntries(shutdownPtyIds.map((ptyId) => [ptyId, true] as const))
|
||||
...Object.fromEntries(exitGuardPtyIds.map((ptyId) => [ptyId, true] as const))
|
||||
},
|
||||
codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId,
|
||||
...(nextRuntimePaneTitlesByTabId !== s.runtimePaneTitlesByTabId
|
||||
@@ -2276,8 +2334,12 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
opts?.shutdownReason ?? (keepIdentifiers ? 'manual-sleep' : 'remove-worktree')
|
||||
const tabs = get().tabsByWorktree[worktreeId] ?? []
|
||||
const ptyIds = tabs.flatMap((tab) => get().ptyIdsByTabId[tab.id] ?? [])
|
||||
const rendererShutdownPtyIds = sortedUniquePtyIds(ptyIds)
|
||||
const expectedRuntimePtyIds = sortedUniquePtyIds(opts?.expectedRuntimePtyIds)
|
||||
const shutdownPtyIds = sortedUniquePtyIds([...ptyIds, ...expectedRuntimePtyIds])
|
||||
const runtimeEnvironmentId = resolveTerminalStopRuntimeEnvironmentId(get(), worktreeId)
|
||||
// Why: expectedRuntimePtyIds are raw RPC handles. Only renderer-bound ids
|
||||
// can emit pane exit callbacks, so they are the complete guard identity set.
|
||||
const exitGuardPtyIds = rendererShutdownPtyIds
|
||||
const sleepingAgentSessionRecords = keepIdentifiers
|
||||
? collectSleepingAgentSessionRecordsForWorktree(get(), worktreeId, {
|
||||
paneKeys: opts?.sleepingPaneKeys,
|
||||
@@ -2300,12 +2362,12 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
// the "phantom alerts" users see after shutting down worktrees.
|
||||
// Removing the data handlers first ensures the final flush is a no-op.
|
||||
if (expectedRuntimePtyIds.length === 0) {
|
||||
unregisterPtyDataHandlers(shutdownPtyIds)
|
||||
unregisterPtyDataHandlers(rendererShutdownPtyIds)
|
||||
// Why: parked-tab byte watchers observe the same flush through dispatcher
|
||||
// sidecars, which the call above does not touch — dispose them now or a
|
||||
// just-slept/deleted worktree still gets unread marks and delayed
|
||||
// bell/completion OS notifications from its teardown bytes.
|
||||
disposeParkedTerminalWatchersForPtyIds(shutdownPtyIds)
|
||||
disposeParkedTerminalWatchersForPtyIds(rendererShutdownPtyIds)
|
||||
}
|
||||
|
||||
// Why (ordering invariant — DESIGN_DOC §3.3.c): on sleep, capture every
|
||||
@@ -2332,7 +2394,6 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
}
|
||||
}
|
||||
|
||||
const runtimeEnvironmentId = resolveTerminalStopRuntimeEnvironmentId(get(), worktreeId)
|
||||
if (expectedRuntimePtyIds.length > 0) {
|
||||
if (!runtimeEnvironmentId) {
|
||||
throw new Error('missing_runtime_for_exact_terminal_stop')
|
||||
@@ -2340,7 +2401,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
set((s) => ({
|
||||
suppressedPtyExitIds: {
|
||||
...s.suppressedPtyExitIds,
|
||||
...Object.fromEntries(shutdownPtyIds.map((ptyId) => [ptyId, true] as const))
|
||||
...Object.fromEntries(exitGuardPtyIds.map((ptyId) => [ptyId, true] as const))
|
||||
}
|
||||
}))
|
||||
let stopResult: {
|
||||
@@ -2367,7 +2428,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
} catch (err) {
|
||||
set((s) => {
|
||||
const next = { ...s.suppressedPtyExitIds }
|
||||
for (const ptyId of shutdownPtyIds) {
|
||||
for (const ptyId of exitGuardPtyIds) {
|
||||
delete next[ptyId]
|
||||
}
|
||||
return { suppressedPtyExitIds: next }
|
||||
@@ -2382,7 +2443,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
) {
|
||||
set((s) => {
|
||||
const next = { ...s.suppressedPtyExitIds }
|
||||
for (const ptyId of shutdownPtyIds) {
|
||||
for (const ptyId of exitGuardPtyIds) {
|
||||
delete next[ptyId]
|
||||
}
|
||||
return { suppressedPtyExitIds: next }
|
||||
@@ -2392,14 +2453,14 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
if (stopResult.postStopVerified !== true) {
|
||||
set((s) => {
|
||||
const next = { ...s.suppressedPtyExitIds }
|
||||
for (const ptyId of shutdownPtyIds) {
|
||||
for (const ptyId of exitGuardPtyIds) {
|
||||
delete next[ptyId]
|
||||
}
|
||||
return { suppressedPtyExitIds: next }
|
||||
})
|
||||
throw new Error(stopResult.postStopFailure ?? 'exact_terminal_stop_unverified')
|
||||
}
|
||||
unregisterPtyDataHandlers(shutdownPtyIds)
|
||||
unregisterPtyDataHandlers(rendererShutdownPtyIds)
|
||||
}
|
||||
|
||||
set((s) => {
|
||||
@@ -2420,7 +2481,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
: { ...s.runtimePaneTitlesByTabId }
|
||||
const nextSuppressedPtyExitIds = {
|
||||
...s.suppressedPtyExitIds,
|
||||
...Object.fromEntries(shutdownPtyIds.map((ptyId) => [ptyId, true] as const))
|
||||
...Object.fromEntries(exitGuardPtyIds.map((ptyId) => [ptyId, true] as const))
|
||||
}
|
||||
// Why: pendingCodexPaneRestartIds is keyed by ptyId — under sleep we
|
||||
// preserve it so a mid-restart marker survives wake against the same
|
||||
@@ -2431,7 +2492,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
? s.pendingCodexPaneRestartIds
|
||||
: { ...s.pendingCodexPaneRestartIds }
|
||||
const nextCodexRestartNoticeByPtyId = { ...s.codexRestartNoticeByPtyId }
|
||||
for (const ptyId of shutdownPtyIds) {
|
||||
for (const ptyId of exitGuardPtyIds) {
|
||||
if (!keepIdentifiers) {
|
||||
delete nextPendingCodexPaneRestartIds[ptyId]
|
||||
}
|
||||
@@ -2585,7 +2646,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
})
|
||||
get().clearPaneForegroundAgentByWorktree(worktreeId)
|
||||
|
||||
if (ptyIds.length === 0 && expectedRuntimePtyIds.length === 0) {
|
||||
if (rendererShutdownPtyIds.length === 0 && expectedRuntimePtyIds.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2599,8 +2660,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
}
|
||||
|
||||
await Promise.allSettled(
|
||||
ptyIds
|
||||
.filter((ptyId) => !expectedRuntimePtyIds.includes(ptyId))
|
||||
rendererShutdownPtyIds
|
||||
.filter((ptyId) => !ptyId.startsWith('remote:'))
|
||||
.map((ptyId) => window.api.pty.kill(ptyId, { keepHistory: keepIdentifiers }))
|
||||
)
|
||||
|
||||
@@ -1904,11 +1904,25 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial<Ap
|
||||
|
||||
// Collect every tab id (and removed file id) we are about to orphan.
|
||||
const doomedTabIds = new Set<string>()
|
||||
// Why: some terminal/agent maps are keyed by ptyId, not tabId. Collect the
|
||||
// doomed panes' ptyIds now (while ptyIdsByTabId is still populated) so this
|
||||
// bulk path can evict them the same way shutdownWorktreeTerminals does on the
|
||||
// single-removeWorktree path.
|
||||
// Why: some terminal/agent maps are keyed by ptyId, not tabId. Collect every
|
||||
// durable wake hint too, because slept panes have already left the live index.
|
||||
const doomedPtyIds = new Set<string>()
|
||||
const addDoomedPtyId = (ptyId: string | null | undefined): void => {
|
||||
if (!ptyId) {
|
||||
return
|
||||
}
|
||||
doomedPtyIds.add(ptyId)
|
||||
}
|
||||
const addDoomedTabPtyIds = (tabId: string, tabPtyId: string | null | undefined): void => {
|
||||
for (const ptyId of s.ptyIdsByTabId?.[tabId] ?? []) {
|
||||
addDoomedPtyId(ptyId)
|
||||
}
|
||||
addDoomedPtyId(tabPtyId)
|
||||
addDoomedPtyId(s.lastKnownRelayPtyIdByTabId?.[tabId])
|
||||
for (const ptyId of Object.values(s.terminalLayoutsByTabId?.[tabId]?.ptyIdsByLeafId ?? {})) {
|
||||
addDoomedPtyId(ptyId)
|
||||
}
|
||||
}
|
||||
const doomedBrowserWorkspaceIds = new Set<string>()
|
||||
const doomedPageIds = new Set<string>()
|
||||
const removedFileIds = new Set<string>()
|
||||
@@ -1917,9 +1931,7 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial<Ap
|
||||
doomedTabIds.add(tab.id)
|
||||
// Null-tolerant like the omit* helpers below: some callers pass partial
|
||||
// state that omits this slice; the production store always inits it to {}.
|
||||
for (const ptyId of s.ptyIdsByTabId?.[tab.id] ?? []) {
|
||||
doomedPtyIds.add(ptyId)
|
||||
}
|
||||
addDoomedTabPtyIds(tab.id, tab.ptyId)
|
||||
// Why: a removed worktree's panes are gone for good, so drop their
|
||||
// hibernation output epochs from that module-level map (mirrors the
|
||||
// hosted-review prune above). A future pane mints a fresh leafId at epoch 0.
|
||||
@@ -2130,6 +2142,8 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial<Ap
|
||||
pendingStartupByTabId: omitByTabId(s.pendingStartupByTabId),
|
||||
codexRestartNoticeByPtyId: omitByPtyId(s.codexRestartNoticeByPtyId),
|
||||
migrationUnsupportedByPtyId: omitByPtyId(s.migrationUnsupportedByPtyId),
|
||||
suppressedPtyExitIds: omitByPtyId(s.suppressedPtyExitIds),
|
||||
pendingCodexPaneRestartIds: omitByPtyId(s.pendingCodexPaneRestartIds),
|
||||
// Why: these tab/pane-scoped agent-status, unread, and input maps are only
|
||||
// cleared on the single removeWorktree path (via shutdownWorktreeTerminals /
|
||||
// dropAgentStatusByWorktree / clearPaneForegroundAgentByWorktree, which read
|
||||
|
||||
Reference in New Issue
Block a user