diff --git a/src/main/providers/ssh-pty-id.ts b/src/main/providers/ssh-pty-id.ts index 992111cd6..7b1f430c1 100644 --- a/src/main/providers/ssh-pty-id.ts +++ b/src/main/providers/ssh-pty-id.ts @@ -1,54 +1,2 @@ -const SSH_PTY_ID_PREFIX = 'ssh:' -const SSH_PTY_ID_SEPARATOR = '@@' - -// Why: SSH relays allocate target-local ids like "pty-1"; app-wide routing -// needs the target id embedded so two relays cannot collide after restore. -export type ParsedSshPtyId = { - connectionId: string - relayPtyId: string -} - -export function parseAppSshPtyId(ptyId: string): ParsedSshPtyId | null { - if (!ptyId.startsWith(SSH_PTY_ID_PREFIX)) { - return null - } - const separatorIndex = ptyId.indexOf(SSH_PTY_ID_SEPARATOR, SSH_PTY_ID_PREFIX.length) - if (separatorIndex === -1) { - return null - } - const encodedConnectionId = ptyId.slice(SSH_PTY_ID_PREFIX.length, separatorIndex) - const relayPtyId = ptyId.slice(separatorIndex + SSH_PTY_ID_SEPARATOR.length) - if (!encodedConnectionId || !relayPtyId) { - return null - } - try { - return { - connectionId: decodeURIComponent(encodedConnectionId), - relayPtyId - } - } catch { - return null - } -} - -export function toAppSshPtyId(connectionId: string, relayPtyId: string): string { - const parsed = parseAppSshPtyId(relayPtyId) - if (parsed) { - if (parsed.connectionId !== connectionId) { - throw new Error(`PTY ${relayPtyId} belongs to SSH connection "${parsed.connectionId}"`) - } - return relayPtyId - } - return `${SSH_PTY_ID_PREFIX}${encodeURIComponent(connectionId)}${SSH_PTY_ID_SEPARATOR}${relayPtyId}` -} - -export function toRelaySshPtyId(connectionId: string, ptyId: string): string { - const parsed = parseAppSshPtyId(ptyId) - if (!parsed) { - return ptyId - } - if (parsed.connectionId !== connectionId) { - throw new Error(`PTY ${ptyId} belongs to SSH connection "${parsed.connectionId}"`) - } - return parsed.relayPtyId -} +export { parseAppSshPtyId, toAppSshPtyId, toRelaySshPtyId } from '../../shared/ssh-pty-id' +export type { ParsedSshPtyId } from '../../shared/ssh-pty-id' diff --git a/src/renderer/src/components/settings/SshPane.tsx b/src/renderer/src/components/settings/SshPane.tsx index 00526abaf..c415def44 100644 --- a/src/renderer/src/components/settings/SshPane.tsx +++ b/src/renderer/src/components/settings/SshPane.tsx @@ -53,6 +53,7 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element { const [testingIds, setTestingIds] = useState>(new Set()) const setSshTargetsMetadata = useAppStore((s) => s.setSshTargetsMetadata) + const clearRemovedSshTargetState = useAppStore((s) => s.clearRemovedSshTargetState) const loadTargets = useCallback( async (opts?: { signal?: AbortSignal }) => { @@ -152,6 +153,9 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element { const handleRemove = async (id: string): Promise => { try { await removeSshTargetWithBestEffortCleanup(window.api.ssh, id) + // Why: a deleted passphrase-gated target may still have deferred + // reconnect metadata; clear it so focused SSH tabs stop retrying it. + clearRemovedSshTargetState(id) toast.success('Target removed') await loadTargets() } catch (err) { diff --git a/src/renderer/src/hooks/useIpcEvents.test.ts b/src/renderer/src/hooks/useIpcEvents.test.ts index 25a073dad..3e3f15881 100644 --- a/src/renderer/src/hooks/useIpcEvents.test.ts +++ b/src/renderer/src/hooks/useIpcEvents.test.ts @@ -329,6 +329,22 @@ describe('useIpcEvents updater integration', () => { it('clears stale remote PTYs when an SSH connection fully disconnects', async () => { const clearTabPtyId = vi.fn() const setSshConnectionState = vi.fn() + const setSshTargetsMetadata = vi.fn() + const clearRemovedSshTargetState = vi.fn() + const pendingListTargets: { + resolve: (targets: { id: string; label: string }[]) => void + reject: (err: unknown) => void + }[] = [] + let listTargetsCallCount = 0 + const listTargets = vi.fn(() => { + listTargetsCallCount += 1 + if (listTargetsCallCount === 1) { + return Promise.resolve([{ id: 'conn-1', label: 'Remote' }]) + } + return new Promise<{ id: string; label: string }[]>((resolve, reject) => { + pendingListTargets.push({ resolve, reject }) + }) + }) const sshStateListenerRef: { current: ((data: { targetId: string; state: unknown }) => void) | null } = { @@ -355,12 +371,14 @@ describe('useIpcEvents updater integration', () => { setRateLimitsFromPush: vi.fn(), setSshConnectionState, setSshTargetLabels: vi.fn(), + setSshTargetsMetadata, setPortForwards: vi.fn(), clearPortForwards: vi.fn(), setDetectedPorts: vi.fn(), enqueueSshCredentialRequest: vi.fn(), removeSshCredentialRequest: vi.fn(), clearRemoteDetectedAgents: vi.fn(), + clearRemovedSshTargetState, clearTabPtyId, repos: [{ id: 'repo-1', connectionId: 'conn-1' }], worktreesByRepo: { @@ -500,7 +518,7 @@ describe('useIpcEvents updater integration', () => { onBrowserDriverChanged: () => () => {} }, ssh: { - listTargets: () => Promise.resolve([]), + listTargets, listPortForwards: () => Promise.resolve([]), listDetectedPorts: () => Promise.resolve([]), getState: () => Promise.resolve(null), @@ -538,6 +556,116 @@ describe('useIpcEvents updater integration', () => { expect(clearTabPtyId).toHaveBeenCalledWith('tab-1') expect(clearTabPtyId).not.toHaveBeenCalledWith('tab-2') expect(storeState.clearRemoteDetectedAgents).toHaveBeenCalledWith('conn-1') + + setSshConnectionState.mockClear() + sshStateListenerRef.current({ + targetId: 'conn-removed', + state: { status: 'disconnected', error: null, reconnectAttempt: 0 } + }) + expect(pendingListTargets).toHaveLength(1) + pendingListTargets.shift()!.resolve([]) + await Promise.resolve() + await Promise.resolve() + + expect(setSshConnectionState).not.toHaveBeenCalled() + expect(clearRemovedSshTargetState).toHaveBeenCalledWith('conn-removed') + + clearRemovedSshTargetState.mockClear() + setSshConnectionState.mockClear() + + const connectingState = { + targetId: 'conn-new', + status: 'connecting', + error: null, + reconnectAttempt: 0 + } + const errorState = { + targetId: 'conn-new', + status: 'error', + error: 'Connection failed', + reconnectAttempt: 0 + } + sshStateListenerRef.current({ + targetId: 'conn-new', + state: connectingState + }) + sshStateListenerRef.current({ + targetId: 'conn-new', + state: errorState + }) + + expect(pendingListTargets).toHaveLength(2) + const resolveConnectingTargets = pendingListTargets.shift()!.resolve + const resolveErrorTargets = pendingListTargets.shift()!.resolve + const targets = [{ id: 'conn-new', label: 'New remote' }] + resolveErrorTargets(targets) + await Promise.resolve() + await Promise.resolve() + resolveConnectingTargets(targets) + await Promise.resolve() + await Promise.resolve() + + expect(clearRemovedSshTargetState).not.toHaveBeenCalled() + expect(setSshTargetsMetadata).toHaveBeenCalledWith(targets) + expect(setSshConnectionState).toHaveBeenCalledTimes(1) + expect(setSshConnectionState).toHaveBeenCalledWith('conn-new', errorState) + + setSshTargetsMetadata.mockClear() + setSshConnectionState.mockClear() + + const staleState = { + targetId: 'conn-known-late', + status: 'connecting', + error: null, + reconnectAttempt: 0 + } + const latestState = { + targetId: 'conn-known-late', + status: 'error', + error: 'Connection failed', + reconnectAttempt: 1 + } + sshStateListenerRef.current({ + targetId: 'conn-known-late', + state: staleState + }) + expect(pendingListTargets).toHaveLength(1) + storeState.sshTargetLabels.set('conn-known-late', 'Late remote') + sshStateListenerRef.current({ + targetId: 'conn-known-late', + state: latestState + }) + pendingListTargets.shift()!.resolve([{ id: 'conn-known-late', label: 'Late remote' }]) + await Promise.resolve() + await Promise.resolve() + + expect(setSshTargetsMetadata).not.toHaveBeenCalled() + expect(setSshConnectionState).toHaveBeenCalledTimes(1) + expect(setSshConnectionState).toHaveBeenCalledWith('conn-known-late', latestState) + + setSshConnectionState.mockClear() + const refreshFailureState = { + targetId: 'conn-refresh-failure', + status: 'connecting', + error: null, + reconnectAttempt: 0 + } + sshStateListenerRef.current({ + targetId: 'conn-refresh-failure', + state: refreshFailureState + }) + expect(pendingListTargets).toHaveLength(1) + pendingListTargets.shift()!.reject(new Error('first refresh failed')) + await Promise.resolve() + expect(pendingListTargets).toHaveLength(1) + pendingListTargets.shift()!.reject(new Error('second refresh failed')) + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + + expect(setSshConnectionState).toHaveBeenCalledTimes(1) + expect(setSshConnectionState).toHaveBeenCalledWith('conn-refresh-failure', refreshFailureState) }) it('activates the target worktree when CLI creates a terminal there', async () => { diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 1db0c4867..fae33213b 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -1692,93 +1692,124 @@ export function useIpcEvents(): void { }) ) + const applySshConnectionStateChange = (targetId: string, state: SshConnectionState): void => { + const store = useAppStore.getState() + store.setSshConnectionState(targetId, state) + const remoteRepos = store.repos.filter((r) => r.connectionId === targetId) + + if (['disconnected', 'auth-failed', 'reconnection-failed', 'error'].includes(state.status)) { + // Why: the remote agent list is tied to a live SSH connection. On + // disconnect the relay is gone, so clear the cached list and dedup + // promise. When the user reconnects and opens the quick-launch menu, + // ensureRemoteDetectedAgents will re-detect against the new relay. + store.clearRemoteDetectedAgents(targetId) + + // Why: defensive — clear port forward and detected port state in case + // the broadcast from removeAllForwards races with the state change. + store.clearPortForwards(targetId) + store.setDetectedPorts(targetId, []) + + // Why: an explicit disconnect or terminal failure tears down the SSH + // PTY provider without emitting per-PTY exit events. Clear the stale + // PTY ids in renderer state so a later reconnect remounts TerminalPane + // instead of keeping a dead remote PTY attached to the tab. + const remoteWorktreeIds = new Set( + Object.values(store.worktreesByRepo) + .flat() + .filter((w) => remoteRepos.some((r) => r.id === w.repoId)) + .map((w) => w.id) + ) + for (const worktreeId of remoteWorktreeIds) { + const tabs = useAppStore.getState().tabsByWorktree[worktreeId] ?? [] + for (const tab of tabs) { + if (tab.ptyId) { + useAppStore.getState().clearTabPtyId(tab.id) + } + } + } + } + + if (state.status === 'connected') { + void Promise.all(remoteRepos.map((r) => store.fetchWorktrees(r.id))).then(async () => { + await useAppStore.getState().fetchWorktreeLineage() + // Why: terminal panes that failed to spawn (no PTY provider on cold + // start) sit inert. Bumping generation forces TerminalPane to remount + // and retry pty:spawn. Only bump tabs with no live ptyId. + const freshStore = useAppStore.getState() + const remoteRepoIds = new Set(remoteRepos.map((r) => r.id)) + const worktreeIds = Object.values(freshStore.worktreesByRepo) + .flat() + .filter((w) => remoteRepoIds.has(w.repoId)) + .map((w) => w.id) + + for (const worktreeId of worktreeIds) { + const tabs = freshStore.tabsByWorktree[worktreeId] ?? [] + const hasDead = tabs.some((t) => !t.ptyId) + if (hasDead) { + useAppStore.setState((s) => ({ + tabsByWorktree: { + ...s.tabsByWorktree, + [worktreeId]: (s.tabsByWorktree[worktreeId] ?? []).map((t) => + t.ptyId ? t : { ...t, generation: (t.generation ?? 0) + 1 } + ) + } + })) + } + } + void syncRemoteWorkspaceAfterConnect(targetId).catch((err) => { + useAppStore.getState().setRemoteWorkspaceSyncStatus(targetId, { + phase: 'error', + message: err instanceof Error ? err.message : 'Workspace sync failed' + }) + }) + }) + } + } + + let sshTargetStateEventId = 0 + const latestSshTargetStateEventByTargetId = new Map() + unsubs.push( window.api.ssh.onStateChanged((data: { targetId: string; state: unknown }) => { const store = useAppStore.getState() const state = data.state as SshConnectionState - store.setSshConnectionState(data.targetId, state) - const remoteRepos = store.repos.filter((r) => r.connectionId === data.targetId) - - // Why: targets added after boot aren't in the labels map. Re-fetch - // so the status bar popover shows the new target immediately. + const stateEventId = ++sshTargetStateEventId + latestSshTargetStateEventByTargetId.set(data.targetId, stateEventId) if (!store.sshTargetLabels.has(data.targetId)) { + // Why: targets added after boot aren't in the labels map, while + // removed targets can still race a final disconnect event. Confirm + // with main before mutating renderer state for an unknown target id. window.api.ssh .listTargets() + // Why: this refresh is now a deletion guard, not just a label fetch. + // Retry once so a transient IPC failure does not drop a real added-target event. + .catch(() => window.api.ssh.listTargets()) .then((targets) => { - useAppStore.getState().setSshTargetsMetadata(targets) - }) - .catch(() => {}) - } - - if ( - ['disconnected', 'auth-failed', 'reconnection-failed', 'error'].includes(state.status) - ) { - // Why: the remote agent list is tied to a live SSH connection. On - // disconnect the relay is gone, so clear the cached list and dedup - // promise. When the user reconnects and opens the quick-launch menu, - // ensureRemoteDetectedAgents will re-detect against the new relay. - store.clearRemoteDetectedAgents(data.targetId) - - // Why: defensive — clear port forward and detected port state in case - // the broadcast from removeAllForwards races with the state change. - store.clearPortForwards(data.targetId) - store.setDetectedPorts(data.targetId, []) - - // Why: an explicit disconnect or terminal failure tears down the SSH - // PTY provider without emitting per-PTY exit events. Clear the stale - // PTY ids in renderer state so a later reconnect remounts TerminalPane - // instead of keeping a dead remote PTY attached to the tab. - const remoteWorktreeIds = new Set( - Object.values(store.worktreesByRepo) - .flat() - .filter((w) => remoteRepos.some((r) => r.id === w.repoId)) - .map((w) => w.id) - ) - for (const worktreeId of remoteWorktreeIds) { - const tabs = useAppStore.getState().tabsByWorktree[worktreeId] ?? [] - for (const tab of tabs) { - if (tab.ptyId) { - useAppStore.getState().clearTabPtyId(tab.id) + if (latestSshTargetStateEventByTargetId.get(data.targetId) !== stateEventId) { + return } - } - } - } - - if (state.status === 'connected') { - void Promise.all(remoteRepos.map((r) => store.fetchWorktrees(r.id))).then(async () => { - await useAppStore.getState().fetchWorktreeLineage() - // Why: terminal panes that failed to spawn (no PTY provider on cold - // start) sit inert. Bumping generation forces TerminalPane to remount - // and retry pty:spawn. Only bump tabs with no live ptyId. - const freshStore = useAppStore.getState() - const remoteRepoIds = new Set(remoteRepos.map((r) => r.id)) - const worktreeIds = Object.values(freshStore.worktreesByRepo) - .flat() - .filter((w) => remoteRepoIds.has(w.repoId)) - .map((w) => w.id) - - for (const worktreeId of worktreeIds) { - const tabs = freshStore.tabsByWorktree[worktreeId] ?? [] - const hasDead = tabs.some((t) => !t.ptyId) - if (hasDead) { - useAppStore.setState((s) => ({ - tabsByWorktree: { - ...s.tabsByWorktree, - [worktreeId]: (s.tabsByWorktree[worktreeId] ?? []).map((t) => - t.ptyId ? t : { ...t, generation: (t.generation ?? 0) + 1 } - ) - } - })) + latestSshTargetStateEventByTargetId.delete(data.targetId) + const latestStore = useAppStore.getState() + if (!targets.some((target) => target.id === data.targetId)) { + // Why: disconnect/state events can race after target removal. + // Treat absence from main's target list as deletion, not a new target. + latestStore.clearRemovedSshTargetState(data.targetId) + return } - } - void syncRemoteWorkspaceAfterConnect(data.targetId).catch((err) => { - useAppStore.getState().setRemoteWorkspaceSyncStatus(data.targetId, { - phase: 'error', - message: err instanceof Error ? err.message : 'Workspace sync failed' - }) + latestStore.setSshTargetsMetadata(targets) + applySshConnectionStateChange(data.targetId, state) }) - }) + .catch(() => { + if (latestSshTargetStateEventByTargetId.get(data.targetId) === stateEventId) { + latestSshTargetStateEventByTargetId.delete(data.targetId) + applySshConnectionStateChange(data.targetId, state) + } + }) + return } + + latestSshTargetStateEventByTargetId.delete(data.targetId) + applySshConnectionStateChange(data.targetId, state) }) ) diff --git a/src/renderer/src/store/slices/ssh-target-cleanup.ts b/src/renderer/src/store/slices/ssh-target-cleanup.ts new file mode 100644 index 000000000..4ac4c97c7 --- /dev/null +++ b/src/renderer/src/store/slices/ssh-target-cleanup.ts @@ -0,0 +1,205 @@ +import type { AppState } from '../types' +import type { SshConnectionState, SshTarget } from '../../../../shared/ssh-types' +import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' + +export function sshConnectionStatesEqual( + a: SshConnectionState | undefined, + b: SshConnectionState +): boolean { + return ( + a?.targetId === b.targetId && + a?.status === b.status && + a?.error === b.error && + a?.reconnectAttempt === b.reconnectAttempt + ) +} + +export function sshTargetLabelsEqual( + labels: Map, + targets: Pick[] +): boolean { + if (labels.size !== targets.length) { + return false + } + return targets.every((target) => labels.get(target.id) === target.label) +} + +function collectSshTargetTerminalTabIds(state: AppState, targetId: string): Set { + const repoIds = new Set( + state.repos.filter((repo) => repo.connectionId === targetId).map((repo) => repo.id) + ) + const tabIds = new Set() + for (const [repoId, worktrees] of Object.entries(state.worktreesByRepo)) { + if (!repoIds.has(repoId)) { + continue + } + for (const worktree of worktrees) { + for (const tab of state.tabsByWorktree[worktree.id] ?? []) { + tabIds.add(tab.id) + } + } + } + return tabIds +} + +function isSshTargetSessionId(sessionId: string, targetId: string): boolean { + return parseAppSshPtyId(sessionId)?.connectionId === targetId +} + +function shouldRemoveDeferredSshSession( + tabId: string, + sessionId: string, + targetId: string, + targetTabIds: Set +): boolean { + return targetTabIds.has(tabId) || isSshTargetSessionId(sessionId, targetId) +} + +function clearSshTargetTabPtyState( + state: AppState, + targetId: string, + targetTabIds: Set +): Pick< + AppState, + | 'tabsByWorktree' + | 'ptyIdsByTabId' + | 'lastKnownRelayPtyIdByTabId' + | 'pendingCodexPaneRestartIds' + | 'codexRestartNoticeByPtyId' +> & { changed: boolean } { + let nextTabsByWorktree = state.tabsByWorktree + const nextPtyIdsByTabId = { ...state.ptyIdsByTabId } + const nextLastKnownRelayPtyIdByTabId = { ...state.lastKnownRelayPtyIdByTabId } + const nextPendingCodexPaneRestartIds = { ...state.pendingCodexPaneRestartIds } + const nextCodexRestartNoticeByPtyId = { ...state.codexRestartNoticeByPtyId } + let changed = false + + for (const [worktreeId, tabs] of Object.entries(state.tabsByWorktree)) { + let nextTabs = tabs + for (const [index, tab] of tabs.entries()) { + const lastKnownPtyId = state.lastKnownRelayPtyIdByTabId[tab.id] + const ptyIds = [ + ...new Set([ + ...(state.ptyIdsByTabId[tab.id] ?? []), + ...(tab.ptyId ? [tab.ptyId] : []), + ...(lastKnownPtyId ? [lastKnownPtyId] : []) + ]) + ] + const shouldClearTab = + targetTabIds.has(tab.id) || ptyIds.some((ptyId) => isSshTargetSessionId(ptyId, targetId)) + if (!shouldClearTab) { + continue + } + if (!tab.ptyId && ptyIds.length === 0 && nextLastKnownRelayPtyIdByTabId[tab.id] == null) { + continue + } + changed = true + if (nextTabs === tabs) { + nextTabs = [...tabs] + } + const { pendingActivationSpawn: _pendingActivationSpawn, ...tabWithoutActivationSpawn } = tab + void _pendingActivationSpawn + nextTabs[index] = { ...tabWithoutActivationSpawn, ptyId: null } + nextPtyIdsByTabId[tab.id] = [] + delete nextLastKnownRelayPtyIdByTabId[tab.id] + for (const ptyId of ptyIds) { + delete nextPendingCodexPaneRestartIds[ptyId] + delete nextCodexRestartNoticeByPtyId[ptyId] + } + } + if (nextTabs !== tabs) { + nextTabsByWorktree = { ...nextTabsByWorktree, [worktreeId]: nextTabs } + } + } + + return { + changed, + tabsByWorktree: nextTabsByWorktree, + ptyIdsByTabId: nextPtyIdsByTabId, + lastKnownRelayPtyIdByTabId: nextLastKnownRelayPtyIdByTabId, + pendingCodexPaneRestartIds: nextPendingCodexPaneRestartIds, + codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId + } +} + +export function buildRemovedSshTargetCleanupPatch( + state: AppState, + targetId: string +): Partial | null { + const targetTabIds = collectSshTargetTerminalTabIds(state, targetId) + const tabPtyState = clearSshTargetTabPtyState(state, targetId, targetTabIds) + const nextDeferredSessions: Record = {} + 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 nextDeferredTargets = state.deferredSshReconnectTargets.filter((id) => id !== targetId) + const nextConnectionStates = new Map(state.sshConnectionStates) + const removedConnectionState = nextConnectionStates.delete(targetId) + const nextLabels = new Map(state.sshTargetLabels) + const removedLabel = nextLabels.delete(targetId) + const nextHydrated = new Set(state.remoteWorkspaceHydratedTargetIds) + const removedHydrated = nextHydrated.delete(targetId) + const removedSyncStatus = Object.prototype.hasOwnProperty.call( + state.remoteWorkspaceSyncStatusByTargetId, + targetId + ) + const removedPortForwards = Object.prototype.hasOwnProperty.call( + state.portForwardsByConnection, + targetId + ) + const removedDetectedPorts = Object.prototype.hasOwnProperty.call( + state.detectedPortsByConnection, + targetId + ) + const nextSyncStatus = { ...state.remoteWorkspaceSyncStatusByTargetId } + delete nextSyncStatus[targetId] + const nextPortForwards = { ...state.portForwardsByConnection } + delete nextPortForwards[targetId] + const nextDetectedPorts = { ...state.detectedPortsByConnection } + delete nextDetectedPorts[targetId] + const nextCredentialQueue = state.sshCredentialQueue.filter((req) => req.targetId !== targetId) + const removedCredentialRequest = nextCredentialQueue.length !== state.sshCredentialQueue.length + const removedDeferredTarget = + nextDeferredTargets.length !== state.deferredSshReconnectTargets.length + const changed = + removedConnectionState || + removedLabel || + removedHydrated || + removedSyncStatus || + removedPortForwards || + removedDetectedPorts || + tabPtyState.changed || + removedCredentialRequest || + removedDeferredTarget || + removedDeferredSession + if (!changed) { + return null + } + + return { + ...(removedConnectionState ? { sshConnectionStates: nextConnectionStates } : {}), + ...(removedLabel ? { sshTargetLabels: nextLabels } : {}), + ...(removedHydrated ? { remoteWorkspaceHydratedTargetIds: nextHydrated } : {}), + ...(removedSyncStatus ? { remoteWorkspaceSyncStatusByTargetId: nextSyncStatus } : {}), + ...(removedPortForwards ? { portForwardsByConnection: nextPortForwards } : {}), + ...(removedDetectedPorts ? { detectedPortsByConnection: nextDetectedPorts } : {}), + ...(tabPtyState.changed + ? { + tabsByWorktree: tabPtyState.tabsByWorktree, + ptyIdsByTabId: tabPtyState.ptyIdsByTabId, + lastKnownRelayPtyIdByTabId: tabPtyState.lastKnownRelayPtyIdByTabId, + pendingCodexPaneRestartIds: tabPtyState.pendingCodexPaneRestartIds, + codexRestartNoticeByPtyId: tabPtyState.codexRestartNoticeByPtyId + } + : {}), + ...(removedCredentialRequest ? { sshCredentialQueue: nextCredentialQueue } : {}), + ...(removedDeferredTarget ? { deferredSshReconnectTargets: nextDeferredTargets } : {}), + ...(removedDeferredSession ? { deferredSshSessionIdsByTabId: nextDeferredSessions } : {}) + } +} diff --git a/src/renderer/src/store/slices/ssh.test.ts b/src/renderer/src/store/slices/ssh.test.ts new file mode 100644 index 000000000..af8f17fd3 --- /dev/null +++ b/src/renderer/src/store/slices/ssh.test.ts @@ -0,0 +1,234 @@ +import { describe, expect, it } from 'vitest' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' +import { createTestStore, makeTab, makeWorktree, TEST_REPO } from './store-test-helpers' + +describe('createSshSlice', () => { + it('clears renderer state and deferred reconnect metadata for a removed SSH target', () => { + const store = createTestStore() + const targetId = 'ssh-1' + const otherTargetId = 'ssh-2' + const worktreeId = 'repo-ssh::/remote/project' + const otherWorktreeId = 'repo-other::/remote/project' + const removedPtyId = toAppSshPtyId(targetId, 'pty-live') + const staleLastKnownPtyId = toAppSshPtyId(targetId, 'pty-last-known') + const otherPtyId = toAppSshPtyId(otherTargetId, 'pty-other') + + store.setState({ + repos: [ + { ...TEST_REPO, id: 'repo-ssh', connectionId: targetId }, + { ...TEST_REPO, id: 'repo-other', connectionId: otherTargetId } + ], + worktreesByRepo: { + 'repo-ssh': [makeWorktree({ id: worktreeId, repoId: 'repo-ssh' })], + 'repo-other': [makeWorktree({ id: otherWorktreeId, repoId: 'repo-other' })] + }, + tabsByWorktree: { + [worktreeId]: [ + makeTab({ + id: 'tab-ssh', + worktreeId, + ptyId: removedPtyId, + pendingActivationSpawn: true + }) + ], + [otherWorktreeId]: [ + makeTab({ id: 'tab-other', worktreeId: otherWorktreeId, ptyId: otherPtyId }), + makeTab({ id: 'tab-stale-last-known', worktreeId: otherWorktreeId }) + ] + }, + ptyIdsByTabId: { + 'tab-ssh': [removedPtyId], + 'tab-other': [otherPtyId] + }, + lastKnownRelayPtyIdByTabId: { + 'tab-ssh': removedPtyId, + 'tab-stale-last-known': staleLastKnownPtyId, + 'tab-other': otherPtyId + }, + pendingCodexPaneRestartIds: { + [removedPtyId]: true, + [otherPtyId]: true + }, + codexRestartNoticeByPtyId: { + [removedPtyId]: { previousAccountLabel: 'Old', nextAccountLabel: 'New' }, + [otherPtyId]: { previousAccountLabel: 'Other old', nextAccountLabel: 'Other new' } + }, + sshConnectionStates: new Map([ + [targetId, { targetId, status: 'disconnected', error: null, reconnectAttempt: 0 }], + [ + otherTargetId, + { targetId: otherTargetId, status: 'connected', error: null, reconnectAttempt: 0 } + ] + ]), + sshTargetLabels: new Map([ + [targetId, 'Removed target'], + [otherTargetId, 'Other target'] + ]), + remoteWorkspaceHydratedTargetIds: new Set([targetId, otherTargetId]), + remoteWorkspaceSyncStatusByTargetId: { + [targetId]: { phase: 'offline' }, + [otherTargetId]: { phase: 'synced' } + }, + portForwardsByConnection: { + [targetId]: [ + { + id: 'pf-1', + connectionId: targetId, + localPort: 3000, + remoteHost: '127.0.0.1', + remotePort: 3000 + } + ], + [otherTargetId]: [ + { + id: 'pf-2', + connectionId: otherTargetId, + localPort: 4000, + remoteHost: '127.0.0.1', + remotePort: 4000 + } + ] + }, + detectedPortsByConnection: { + [targetId]: [{ port: 3000, host: '127.0.0.1' }], + [otherTargetId]: [{ port: 4000, host: '127.0.0.1' }] + }, + sshCredentialQueue: [ + { requestId: 'req-1', targetId, kind: 'passphrase', detail: 'key' }, + { requestId: 'req-2', targetId: otherTargetId, kind: 'password', detail: 'password' } + ], + deferredSshReconnectTargets: [targetId, otherTargetId], + deferredSshSessionIdsByTabId: { + 'tab-ssh': 'legacy-session-without-target-prefix', + 'tab-stale-encoded': toAppSshPtyId(targetId, 'pty-1'), + 'tab-other': toAppSshPtyId(otherTargetId, 'pty-2') + } + }) + + store.getState().clearRemovedSshTargetState(targetId) + + const state = store.getState() + expect(state.sshConnectionStates.has(targetId)).toBe(false) + expect(state.sshTargetLabels.has(targetId)).toBe(false) + expect(state.remoteWorkspaceHydratedTargetIds.has(targetId)).toBe(false) + expect(state.remoteWorkspaceSyncStatusByTargetId[targetId]).toBeUndefined() + expect(state.portForwardsByConnection[targetId]).toBeUndefined() + expect(state.detectedPortsByConnection[targetId]).toBeUndefined() + expect(state.sshCredentialQueue.map((req) => req.targetId)).toEqual([otherTargetId]) + expect(state.deferredSshReconnectTargets).toEqual([otherTargetId]) + expect(state.deferredSshSessionIdsByTabId).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([]) + expect(state.lastKnownRelayPtyIdByTabId['tab-ssh']).toBeUndefined() + expect(state.lastKnownRelayPtyIdByTabId['tab-stale-last-known']).toBeUndefined() + expect(state.pendingCodexPaneRestartIds[removedPtyId]).toBeUndefined() + expect(state.codexRestartNoticeByPtyId[removedPtyId]).toBeUndefined() + + expect(state.sshConnectionStates.get(otherTargetId)?.status).toBe('connected') + expect(state.sshTargetLabels.get(otherTargetId)).toBe('Other target') + expect(state.remoteWorkspaceHydratedTargetIds.has(otherTargetId)).toBe(true) + expect(state.remoteWorkspaceSyncStatusByTargetId[otherTargetId]).toEqual({ phase: 'synced' }) + expect(state.portForwardsByConnection[otherTargetId]).toHaveLength(1) + expect(state.detectedPortsByConnection[otherTargetId]).toHaveLength(1) + expect(state.tabsByWorktree[otherWorktreeId][0]?.ptyId).toBe(otherPtyId) + expect(state.ptyIdsByTabId['tab-other']).toEqual([otherPtyId]) + expect(state.lastKnownRelayPtyIdByTabId['tab-other']).toBe(otherPtyId) + expect(state.pendingCodexPaneRestartIds[otherPtyId]).toBe(true) + expect(state.codexRestartNoticeByPtyId[otherPtyId]).toEqual({ + previousAccountLabel: 'Other old', + nextAccountLabel: 'Other new' + }) + }) + + it('keeps SSH target label references stable when refreshed metadata is unchanged', () => { + const store = createTestStore() + const labels = new Map([['ssh-1', 'Remote']]) + store.setState({ sshTargetLabels: labels }) + const previousState = store.getState() + + store.getState().setSshTargetsMetadata([{ id: 'ssh-1', label: 'Remote' }]) + + expect(store.getState()).toBe(previousState) + expect(store.getState().sshTargetLabels).toBe(labels) + }) + + it('keeps SSH connection state references stable when duplicate state arrives', () => { + const store = createTestStore() + const sshConnectionStates = new Map([ + [ + 'ssh-1', + { targetId: 'ssh-1', status: 'connected' as const, error: null, reconnectAttempt: 0 } + ] + ]) + store.setState({ sshConnectionStates, sshConnectedGeneration: 1 }) + const previousState = store.getState() + + store.getState().setSshConnectionState('ssh-1', { + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + + expect(store.getState()).toBe(previousState) + expect(store.getState().sshConnectionStates).toBe(sshConnectionStates) + expect(store.getState().sshConnectedGeneration).toBe(1) + }) + + it('does not publish state when cleanup finds no removed SSH target state', () => { + const store = createTestStore() + const previousState = store.getState() + + store.getState().clearRemovedSshTargetState('missing-target') + + expect(store.getState()).toBe(previousState) + }) + + it('preserves untouched cleanup slice references while removing deferred target metadata', () => { + const store = createTestStore() + const sshConnectionStates = new Map([ + [ + 'ssh-2', + { targetId: 'ssh-2', status: 'connected' as const, error: null, reconnectAttempt: 0 } + ] + ]) + const sshTargetLabels = new Map([['ssh-2', 'Other']]) + const remoteWorkspaceHydratedTargetIds = new Set(['ssh-2']) + const remoteWorkspaceSyncStatusByTargetId = { 'ssh-2': { phase: 'synced' as const } } + const portForwardsByConnection = { 'ssh-2': [] } + const detectedPortsByConnection = { 'ssh-2': [] } + const sshCredentialQueue = [ + { requestId: 'req-2', targetId: 'ssh-2', kind: 'password' as const, detail: 'password' } + ] + const deferredSshSessionIdsByTabId = { + 'tab-other': toAppSshPtyId('ssh-2', 'pty-2') + } + store.setState({ + sshConnectionStates, + sshTargetLabels, + remoteWorkspaceHydratedTargetIds, + remoteWorkspaceSyncStatusByTargetId, + portForwardsByConnection, + detectedPortsByConnection, + sshCredentialQueue, + deferredSshReconnectTargets: ['ssh-1'], + deferredSshSessionIdsByTabId + }) + + store.getState().clearRemovedSshTargetState('ssh-1') + + const state = store.getState() + expect(state.deferredSshReconnectTargets).toEqual([]) + expect(state.sshConnectionStates).toBe(sshConnectionStates) + expect(state.sshTargetLabels).toBe(sshTargetLabels) + expect(state.remoteWorkspaceHydratedTargetIds).toBe(remoteWorkspaceHydratedTargetIds) + expect(state.remoteWorkspaceSyncStatusByTargetId).toBe(remoteWorkspaceSyncStatusByTargetId) + expect(state.portForwardsByConnection).toBe(portForwardsByConnection) + expect(state.detectedPortsByConnection).toBe(detectedPortsByConnection) + expect(state.sshCredentialQueue).toBe(sshCredentialQueue) + expect(state.deferredSshSessionIdsByTabId).toBe(deferredSshSessionIdsByTabId) + }) +}) diff --git a/src/renderer/src/store/slices/ssh.ts b/src/renderer/src/store/slices/ssh.ts index 0b28d74f9..b7d2b9eb4 100644 --- a/src/renderer/src/store/slices/ssh.ts +++ b/src/renderer/src/store/slices/ssh.ts @@ -6,6 +6,11 @@ import type { EnrichedDetectedPort, SshTarget } from '../../../../shared/ssh-types' +import { + buildRemovedSshTargetCleanupPatch, + sshConnectionStatesEqual, + sshTargetLabelsEqual +} from './ssh-target-cleanup' export type RemoteWorkspaceSyncStatus = { phase: 'idle' | 'pulling' | 'pushing' | 'synced' | 'conflict' | 'error' | 'offline' @@ -46,6 +51,7 @@ export type SshSlice = { setSshConnectionState: (targetId: string, state: SshConnectionState) => void setSshTargetLabels: (labels: Map) => void setSshTargetsMetadata: (targets: Pick[]) => void + clearRemovedSshTargetState: (targetId: string) => void markRemoteWorkspaceHydrated: (targetId: string) => void clearRemoteWorkspaceHydrated: (targetId: string) => void setRemoteWorkspaceSyncStatus: (targetId: string, status: RemoteWorkspaceSyncStatus) => void @@ -70,6 +76,9 @@ export const createSshSlice: StateCreator = (set) => set((s) => { const next = new Map(s.sshConnectionStates) const previous = next.get(targetId) + if (sshConnectionStatesEqual(previous, state)) { + return s + } next.set(targetId, state) return { sshConnectionStates: next, @@ -82,9 +91,16 @@ export const createSshSlice: StateCreator = (set) => setSshTargetLabels: (labels) => set({ sshTargetLabels: labels }), setSshTargetsMetadata: (targets) => - set({ - sshTargetLabels: new Map(targets.map((target) => [target.id, target.label])) + set((s) => { + if (sshTargetLabelsEqual(s.sshTargetLabels, targets)) { + return s + } + return { + sshTargetLabels: new Map(targets.map((target) => [target.id, target.label])) + } }), + clearRemovedSshTargetState: (targetId) => + set((s) => buildRemovedSshTargetCleanupPatch(s, targetId) ?? s), markRemoteWorkspaceHydrated: (targetId) => set((s) => { const next = new Set(s.remoteWorkspaceHydratedTargetIds) diff --git a/src/shared/ssh-pty-id.ts b/src/shared/ssh-pty-id.ts new file mode 100644 index 000000000..992111cd6 --- /dev/null +++ b/src/shared/ssh-pty-id.ts @@ -0,0 +1,54 @@ +const SSH_PTY_ID_PREFIX = 'ssh:' +const SSH_PTY_ID_SEPARATOR = '@@' + +// Why: SSH relays allocate target-local ids like "pty-1"; app-wide routing +// needs the target id embedded so two relays cannot collide after restore. +export type ParsedSshPtyId = { + connectionId: string + relayPtyId: string +} + +export function parseAppSshPtyId(ptyId: string): ParsedSshPtyId | null { + if (!ptyId.startsWith(SSH_PTY_ID_PREFIX)) { + return null + } + const separatorIndex = ptyId.indexOf(SSH_PTY_ID_SEPARATOR, SSH_PTY_ID_PREFIX.length) + if (separatorIndex === -1) { + return null + } + const encodedConnectionId = ptyId.slice(SSH_PTY_ID_PREFIX.length, separatorIndex) + const relayPtyId = ptyId.slice(separatorIndex + SSH_PTY_ID_SEPARATOR.length) + if (!encodedConnectionId || !relayPtyId) { + return null + } + try { + return { + connectionId: decodeURIComponent(encodedConnectionId), + relayPtyId + } + } catch { + return null + } +} + +export function toAppSshPtyId(connectionId: string, relayPtyId: string): string { + const parsed = parseAppSshPtyId(relayPtyId) + if (parsed) { + if (parsed.connectionId !== connectionId) { + throw new Error(`PTY ${relayPtyId} belongs to SSH connection "${parsed.connectionId}"`) + } + return relayPtyId + } + return `${SSH_PTY_ID_PREFIX}${encodeURIComponent(connectionId)}${SSH_PTY_ID_SEPARATOR}${relayPtyId}` +} + +export function toRelaySshPtyId(connectionId: string, ptyId: string): string { + const parsed = parseAppSshPtyId(ptyId) + if (!parsed) { + return ptyId + } + if (parsed.connectionId !== connectionId) { + throw new Error(`PTY ${ptyId} belongs to SSH connection "${parsed.connectionId}"`) + } + return parsed.relayPtyId +}