Improve remote connection terminal error msg and session restore recovery (#7661)

* Robustify SSH terminal reconnect and session restore recovery

- Release the replay guard after a fallback timeout to prevent permanent
  keyboard input lockouts when an unmounted terminal never parses.
- Verify backing process liveness on PTY attach and reap stale entries
  so dead shells cleanly trigger a fresh pane spawn.
- Normalize connection IDs during restore to prevent spurious mismatch
  errors, and treat true mismatches as expired sessions instead of crashing.

* Route disconnected SSH terminal panes through deferred connection gate

Avoid spawning SSH terminal processes against disconnected targets,
which otherwise throws "No PTY provider" and leaves panes stranded.

- Intercept spawning via a new connect gate that triggers the deferred
  connection flow when the SSH target is disconnected.
- Fall back to composite worktree IDs during cold-start hydration to
  ensure deferred SSH session IDs are properly stashed.
- Retry spawning and remounting terminal panes upon SSH reconnect if
  they are stranded or failed to spawn.
This commit is contained in:
Jinjing
2026-07-06 21:41:23 -07:00
committed by GitHub
parent 1a4232fe96
commit aa0993f546
19 changed files with 773 additions and 47 deletions
+69 -1
View File
@@ -14,7 +14,10 @@ import {
const { mockPtySpawn, mockPtyInstance } = vi.hoisted(() => ({
mockPtySpawn: vi.fn(),
mockPtyInstance: {
pid: 12345,
// Why: attach now proves the backing pid is alive before replaying, so the
// default managed PTY must report a live pid. Reuse the test runner's own
// pid — always alive — so unrelated attach tests are not seen as dead.
pid: process.pid,
onData: vi.fn(),
onExit: vi.fn(),
write: vi.fn(),
@@ -609,6 +612,71 @@ describe('PtyHandler', () => {
}
)
it('reports not-found and reaps a reattach whose backing shell is dead', async () => {
// Why: a lingering managed entry whose child died without an onExit would
// otherwise attach-succeed with an empty replay and strand the pane on a
// black shell. A provably-dead pid must surface as not-found so the SSH
// provider maps it to SSH_SESSION_EXPIRED and the pane respawns fresh.
let onExitCb: ((evt: { exitCode: number }) => void) | undefined
mockPtySpawn.mockReturnValue({
...mockPtyInstance,
onData: vi.fn(),
onExit: vi.fn((cb: (evt: { exitCode: number }) => void) => {
onExitCb = cb
})
})
const exits: { id: string; paneKey?: string }[] = []
handler.setExitListener((evt) => exits.push(evt))
await dispatcher.callRequest('pty.spawn', { env: { ORCA_PANE_KEY: 'tab-dead:0' } })
expect(handler.activePtyCount).toBe(1)
expect(onExitCb).toBeDefined()
const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(false)
try {
await expect(
dispatcher.callRequest('pty.attach', { id: 'pty-1', suppressReplayNotification: true })
).rejects.toThrow('PTY "pty-1" not found')
} finally {
aliveSpy.mockRestore()
}
// The stale entry is reaped: cache-eviction observers fire and the map slot
// is freed so a later attach also cleanly reports not-found.
expect(exits).toEqual([{ id: 'pty-1', paneKey: 'tab-dead:0' }])
expect(handler.activePtyCount).toBe(0)
await expect(
dispatcher.callRequest('pty.attach', { id: 'pty-1', suppressReplayNotification: true })
).rejects.toThrow('PTY "pty-1" not found')
})
it('replays for a reattach whose backing shell is still alive', async () => {
// Guard the other direction: a live pid must never be reaped, so a quiet
// but live session still returns its buffered replay on reattach.
let dataCallback: ((data: string) => void) | undefined
mockPtySpawn.mockReturnValue({
...mockPtyInstance,
onData: vi.fn((cb: (data: string) => void) => {
dataCallback = cb
}),
onExit: vi.fn()
})
await dispatcher.callRequest('pty.spawn', {})
dataCallback?.('prompt$ ')
const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(true)
try {
const result = await dispatcher.callRequest('pty.attach', {
id: 'pty-1',
suppressReplayNotification: true
})
expect(result).toEqual({ replay: 'prompt$ ' })
} finally {
aliveSpy.mockRestore()
}
expect(handler.activePtyCount).toBe(1)
})
it('terminates spawned PTY when request becomes stale before response', async () => {
const killSpy = vi.fn()
const term = { ...mockPtyInstance, kill: killSpy, onData: vi.fn(), onExit: vi.fn() }
+17
View File
@@ -10,6 +10,7 @@ import {
resolveProcessCwd,
processHasChildren,
getForegroundProcessName,
isProcessAlive,
listShellProfiles
} from './pty-shell-utils'
import { getRelayShellLaunchConfig } from './pty-shell-launch'
@@ -692,6 +693,22 @@ export class PtyHandler {
throw new Error(`PTY "${id}" not found`)
}
// Why: a reattach can arrive for a relay PTY whose backing shell already
// died without node-pty delivering onExit (e.g. the child was reaped out of
// band while the SSH channel was down). The map entry lingers, so attach
// would otherwise "succeed" with an empty replay and strand the reattached
// pane on a black, unresponsive shell. Prove liveness here; if the pid is
// provably gone, reap the stale entry and report not-found so the caller
// drops the dead lease and spawns fresh — the same recovery path an expired
// grace window already takes.
if (managed.pty.pid && !isProcessAlive(managed.pty.pid)) {
this.notifyExitListener(managed)
disposeManagedPty(managed)
this.ptys.delete(id)
this.clearPtyFlowState(id)
throw new Error(`PTY "${id}" not found`)
}
// Why: PTY ids are a per-relay-process counter (pty-1, pty-2, …). When the
// relay changes generation — an app update deploys a new content-hashed
// relay dir, or a grace-expired relay restarts — the counter resets, so an
+35
View File
@@ -11,6 +11,7 @@ vi.mock('child_process', () => ({
import { resetProcessTableSnapshotForTests } from '../shared/process-table-snapshot'
import {
getForegroundProcessName,
isProcessAlive,
resolveDefaultCwd,
resolveWindowsDefaultShell
} from './pty-shell-utils'
@@ -51,6 +52,40 @@ beforeEach(() => {
resetProcessTableSnapshotForTests()
})
describe('isProcessAlive', () => {
it('reports the test runner process as alive', () => {
expect(isProcessAlive(process.pid)).toBe(true)
})
it('reports a process as dead ONLY on ESRCH', () => {
// Why: attach() reaps a lingering managed PTY based on this, so a false
// positive would kill a live remote shell. Only "no such process" counts.
const spy = vi.spyOn(process, 'kill').mockImplementation(() => {
const err = new Error('no such process') as NodeJS.ErrnoException
err.code = 'ESRCH'
throw err
})
try {
expect(isProcessAlive(2147483646)).toBe(false)
} finally {
spy.mockRestore()
}
})
it('treats an unsignalable process (EPERM) as alive', () => {
const spy = vi.spyOn(process, 'kill').mockImplementation(() => {
const err = new Error('operation not permitted') as NodeJS.ErrnoException
err.code = 'EPERM'
throw err
})
try {
expect(isProcessAlive(1)).toBe(true)
} finally {
spy.mockRestore()
}
})
})
describe('resolveWindowsDefaultShell', () => {
it('uses an existing SHELL override when one is provided', () => {
expect(
+13
View File
@@ -147,6 +147,19 @@ export async function processHasChildren(pid: number): Promise<boolean> {
}
}
// Why: signal 0 probes existence without delivering a signal. Only ESRCH ("no
// such process") proves the pid is gone; EPERM means it exists but is
// unsignalable, so treat every non-ESRCH outcome as alive. Kept conservative so
// a liveness check can only ever declare a *provably* dead process dead.
export function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0)
return true
} catch (err) {
return (err as NodeJS.ErrnoException).code !== 'ESRCH'
}
}
function collectDescendants(
rows: ProcessTableRow[],
rootPid: number
@@ -968,6 +968,34 @@ describe('connectPanePty', () => {
)
})
it('drops keystrokes while the replay guard is engaged, then forwards once it releases', async () => {
// Regression for the cold-restore reattach lockout: handleReattachResult's
// replay writes engaged the per-pane replay guard, and because xterm's parse
// callback never fired for the just-mounted pane the counter stuck non-zero.
// The onData handler then dropped EVERY keystroke — a live but unresponsive
// pane ("can't type after reconnecting"). This locks in the drop-site
// contract: engaged guard suppresses input, released guard forwards it.
const { connectPanePty } = await import('./pty-connection')
const pane = createPane(1)
const transport = createMockTransport('ssh:ssh-1@@pty-1')
transportFactoryQueue.push(transport)
const deps = createDeps()
connectPanePty(pane as never, createManager(1, 1) as never, deps as never)
await flushAsyncTicks()
transport.sendInput.mockClear()
// Engaged (as a stuck reattach would leave it): input must be suppressed.
deps.replayingPanesRef.current.set(pane.id, 3)
sendTerminalInputThroughPane(pane, 'echo hi\r')
expect(transport.sendInput).not.toHaveBeenCalled()
// Released (via the guard's fallback or parse completion): input flows again.
deps.replayingPanesRef.current.delete(pane.id)
sendTerminalInputThroughPane(pane, 'echo hi\r')
expect(transport.sendInput).toHaveBeenCalledWith('echo hi\r')
})
it('normalizes Pi-compatible remote runtime status to OMP after typed omp command', async () => {
const { connectPanePty } = await import('./pty-connection')
enableActiveRuntimeEnvironment()
@@ -4100,7 +4128,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const pane = createPane(1)
@@ -4150,7 +4182,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const pane = createPane(1)
@@ -4288,7 +4324,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const pane = createPane(1)
@@ -4343,7 +4383,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const pane = createPane(1)
@@ -4398,7 +4442,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const pane = createPane(1)
@@ -4450,7 +4498,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const wrapperCommand = 'bash -lc wait-for-setup-wrapper'
@@ -4921,6 +4973,67 @@ describe('connectPanePty', () => {
expect(deps.updateTabPtyId).toHaveBeenCalledWith('tab-1', 'fresh-pty')
})
it('reattaches via the tab-level SSH pty id when deferred bookkeeping missed the tab', async () => {
// Why: restore can miss the deferred maps (e.g. activeConnectionIdsAtShutdown
// wasn't persisted). The tab's own app SSH pty id must still drive a
// connect-then-reattach instead of a fresh spawn into a missing provider.
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'ssh:conn-1@@pty-7' }] },
ptyIdsByTabId: { 'tab-1': [] },
repos: [{ id: 'repo1', connectionId: 'conn-1' }],
sshConnectionStates: new Map()
} as StoreState
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks(12)
const windowApi = (globalThis as unknown as { window: { api: { ssh: { connect: unknown } } } })
.window.api
expect(windowApi.ssh.connect).toHaveBeenCalledWith({ targetId: 'conn-1' })
expect(transport.connect).toHaveBeenCalledWith(
expect.objectContaining({ sessionId: 'ssh:conn-1@@pty-7' })
)
expect(deps.onPtyErrorRef.current).not.toHaveBeenCalled()
})
it('connects a disconnected SSH target before fresh-spawning instead of erroring', async () => {
// Why: spawning against a disconnected target throws "No PTY provider"
// and strands the pane behind a toast that never retries.
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('fresh-ssh-pty')
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
ptyIdsByTabId: { 'tab-1': [] },
repos: [{ id: 'repo1', connectionId: 'conn-1' }],
sshConnectionStates: new Map()
} as StoreState
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(pane as never, manager as never, deps as never)
// Why: no spawn may fire before the SSH connection is established.
expect(transport.connect).not.toHaveBeenCalled()
await flushAsyncTicks(12)
const windowApi = (globalThis as unknown as { window: { api: { ssh: { connect: unknown } } } })
.window.api
expect(windowApi.ssh.connect).toHaveBeenCalledWith({ targetId: 'conn-1' })
expect(transport.connect).toHaveBeenCalledWith(
expect.not.objectContaining({ sessionId: expect.any(String) })
)
expect(deps.onPtyErrorRef.current).not.toHaveBeenCalled()
})
it('spawns a fresh PTY when a non-deferred SSH reattach reports expired via onError', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
@@ -88,6 +88,7 @@ import { makePaneKey, parseLegacyNumericPaneKey } from '../../../../shared/stabl
import { createTerminalCommandLifecycle } from './terminal-command-lifecycle'
import { createPaneForegroundAgentTracker } from './pane-foreground-agent-tracker'
import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id'
import { resolveSshPaneConnectGate } from './ssh-pane-connect-gate'
import { dispatchTerminalCommandFinishedEvent } from '@/hooks/terminal-command-finished-event'
import { e2eConfig } from '@/lib/e2e-config'
import {
@@ -5470,13 +5471,23 @@ export function connectPanePty(
deps.restoredLeafId && deps.restoredPtyIdByLeafId
? (deps.restoredPtyIdByLeafId[deps.restoredLeafId] ?? null)
: null
const pendingSessionId =
restoredLeafSessionId ?? storeState.deferredSshSessionIdsByTabId[deps.tabId]
const isDeferredTarget = storeState.deferredSshReconnectTargets.includes(connectionId)
const gate = resolveSshPaneConnectGate({
connectionId,
sshStatus: storeState.sshConnectionStates.get(connectionId)?.status,
isDeferredTarget: storeState.deferredSshReconnectTargets.includes(connectionId),
restoredLeafSessionId,
deferredTabSessionId: storeState.deferredSshSessionIdsByTabId[deps.tabId],
tabPtyId: storeState.tabsByWorktree[deps.worktreeId]?.find((t) => t.id === deps.tabId)
?.ptyId,
hasLeafSessionMap: Boolean(
deps.restoredPtyIdByLeafId && Object.keys(deps.restoredPtyIdByLeafId).length > 0
)
})
const pendingSessionId = gate.pendingSessionId
console.warn(
`[pty-connection] SSH tab=${deps.tabId} connectionId=${connectionId} pendingSessionId=${pendingSessionId} isDeferredTarget=${isDeferredTarget}`
`[pty-connection] SSH tab=${deps.tabId} connectionId=${connectionId} pendingSessionId=${pendingSessionId} sshConnected=${gate.sshConnected}`
)
if (pendingSessionId || isDeferredTarget) {
if (gate.enterDeferredFlow) {
void (async () => {
// Why: if the target requires a passphrase/password and no credential
// is cached yet, auto-firing ssh.connect would surprise the user —
@@ -1324,6 +1324,50 @@ describe('createIpcPtyTransport', () => {
expect(onError).not.toHaveBeenCalled()
})
it('recovers a stale cross-connection SSH reattach as expired instead of a red error toast', async () => {
// Why: a restored SSH pty id embeds the connection it was created under. If
// the pane reattaches under a different connection the main-side router
// rejects with "belongs to SSH connection" — that session is unreachable, so
// we drop it (sessionExpired) and spawn fresh rather than surfacing a crash.
const { createIpcPtyTransport } = await import('./pty-transport')
const spawnMock = vi
.fn()
.mockRejectedValue(
new Error(
'PTY ssh:ssh-1779863656395-57g1q1@@pty-3 belongs to SSH connection "ssh-1779863656395-57g1q1"'
)
)
;(globalThis as { window: typeof window }).window = {
...originalWindow,
api: {
...originalWindow?.api,
pty: {
...originalWindow?.api?.pty,
spawn: spawnMock,
write: vi.fn(),
resize: vi.fn(),
kill: vi.fn(),
onData: vi.fn(() => () => {}),
onReplay: vi.fn(() => () => {}),
onExit: vi.fn(() => () => {})
}
}
} as unknown as typeof window
const onError = vi.fn()
const result = await createIpcPtyTransport({ connectionId: 'ssh-other' }).connect({
url: '',
sessionId: 'ssh:ssh-1779863656395-57g1q1@@pty-3',
callbacks: { onError }
})
expect(onError).not.toHaveBeenCalled()
expect(result).toEqual({
id: 'ssh:ssh-1779863656395-57g1q1@@pty-3',
sessionExpired: true
})
})
it('surfaces terminal session state save failures without the Electron IPC wrapper', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const wrappedMessage = `Error invoking remote method 'pty:spawn': Error: ${createTerminalSessionStateSaveFailureMessage()}`
@@ -57,6 +57,12 @@ export type {
export { extractLastOscTitle } from '../../../../shared/agent-detection'
const SSH_SESSION_EXPIRED_ERROR = 'SSH_SESSION_EXPIRED'
// Why: an app SSH PTY id embeds the connection it was created under. When a pane
// restored after a workspace/host change reattaches a session that belongs to a
// *different* connection, the main-side id router rejects it with this phrase.
// That session is unreachable from this pane, so it is stale like an expired one
// — recover by spawning fresh rather than surfacing a red "file an issue" crash.
const SSH_PTY_CONNECTION_MISMATCH_MARKER = 'belongs to SSH connection'
const STALE_TITLE_TIMEOUT = 3000 // ms before stale working title is cleared
const MAX_PTY_SIDE_EFFECTS_PER_DRAIN = 64
@@ -677,7 +683,12 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
return spawnResult.id
} catch (err) {
const msg = extractIpcErrorMessage(err, err instanceof Error ? err.message : String(err))
if (connectionId && options.sessionId && msg.includes(SSH_SESSION_EXPIRED_ERROR)) {
if (
connectionId &&
options.sessionId &&
(msg.includes(SSH_SESSION_EXPIRED_ERROR) ||
msg.includes(SSH_PTY_CONNECTION_MISMATCH_MARKER))
) {
return {
id: options.sessionId,
sessionExpired: true
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import type { ManagedPane } from '@/lib/pane-manager/pane-manager'
import { isPaneReplaying, replayIntoTerminal, type ReplayingPanesRef } from './replay-guard'
import {
isPaneReplaying,
replayIntoTerminal,
replayIntoTerminalAsync,
type ReplayingPanesRef
} from './replay-guard'
function makeRef(): ReplayingPanesRef {
return { current: new Map() } as ReplayingPanesRef
@@ -136,6 +141,72 @@ describe('replay-guard', () => {
expect(ref.current.has(1)).toBe(false)
})
it('auto-releases the guard when xterm never fires the parse callback', () => {
// Repro of the cold-restore reattach lockout: handleReattachResult replays
// three chunks into a just-mounted / offscreen pane whose terminal never
// flushes, so xterm's parse callback never runs and the counter would stay
// pinned at 3 — isPaneReplaying() stuck true drops EVERY keystroke. The
// fallback must release the guard so input is not swallowed forever.
vi.useFakeTimers()
try {
const ref = makeRef()
const { pane } = makeFakePane(1)
replayIntoTerminal(pane, ref, '\x1b[2J\x1b[3J\x1b[H')
replayIntoTerminal(pane, ref, 'scrollback bytes')
replayIntoTerminal(pane, ref, '--- session restored ---')
expect(isPaneReplaying(ref, 1)).toBe(true)
// Never flush — simulate the missing parse callback for an unflushed pane.
vi.advanceTimersByTime(1000)
expect(isPaneReplaying(ref, 1)).toBe(false)
expect(ref.current.has(1)).toBe(false)
} finally {
vi.useRealTimers()
}
})
it('parse completion cancels the fallback without over-releasing', () => {
vi.useFakeTimers()
try {
const ref = makeRef()
const { pane, terminal } = makeFakePane(1)
replayIntoTerminal(pane, ref, 'a')
replayIntoTerminal(pane, ref, 'b')
terminal.flush()
expect(isPaneReplaying(ref, 1)).toBe(false)
// The already-cancelled fallback must not fire and underflow the counter.
vi.advanceTimersByTime(1000)
expect(isPaneReplaying(ref, 1)).toBe(false)
expect(ref.current.has(1)).toBe(false)
} finally {
vi.useRealTimers()
}
})
it('async replay resolves even when the parse callback never fires', async () => {
vi.useFakeTimers()
try {
const ref = makeRef()
const { pane } = makeFakePane(1)
let resolved = false
const promise = replayIntoTerminalAsync(pane, ref, 'x').then(() => {
resolved = true
})
expect(isPaneReplaying(ref, 1)).toBe(true)
await vi.advanceTimersByTimeAsync(1000)
await promise
expect(resolved).toBe(true)
expect(isPaneReplaying(ref, 1)).toBe(false)
} finally {
vi.useRealTimers()
}
})
it('schedules a follow-up repaint for replayed cursor restores', () => {
const scheduledFrames: FrameRequestCallback[] = []
const originalRequestAnimationFrame = globalThis.requestAnimationFrame
@@ -27,10 +27,57 @@ import { writeForegroundTerminalChunk } from '@/lib/pane-manager/pane-terminal-f
export type ReplayingPanesRef = React.RefObject<Map<number, number>>
// Why: the guard normally releases in xterm's write-completion callback, but
// that callback never fires for a pane whose terminal has not been flushed —
// e.g. a cold-restore reattach that replays into a just-mounted / offscreen
// pane. Without a ceiling the counter leaks, isPaneReplaying() stays true, and
// the onData handler silently drops EVERY keystroke (the pane looks alive but
// ignores input). Release deterministically after this bound so the guard
// always clears; in the normal path onParsed fires within milliseconds and
// cancels it first. Tradeoff: if the callback is lost and the pane parses the
// replayed buffer only after this bound elapses (e.g. rendering resumes long
// after restore), xterm's auto-replies to any device queries in that buffer can
// leak to the shell as input. Accepted as strictly preferable to a permanent
// input lockout, and bounded by the ~100 KB replay cap.
const REPLAY_GUARD_RELEASE_FALLBACK_MS = 1000
export function isPaneReplaying(ref: ReplayingPanesRef, paneId: number): boolean {
return (ref.current.get(paneId) ?? 0) > 0
}
/** Engage the per-pane replay guard and return a `finish` callback that
* releases it exactly once. The guard also auto-releases after
* REPLAY_GUARD_RELEASE_FALLBACK_MS so a missing xterm parse callback can never
* strand it engaged. `onReleased` runs once when the guard actually releases
* (via `finish` or the fallback), so async callers can settle either way. */
function engageReplayGuard(
replayingPanesRef: ReplayingPanesRef,
paneId: number,
onReleased?: () => void
): () => void {
const map = replayingPanesRef.current
map.set(paneId, (map.get(paneId) ?? 0) + 1)
let released = false
const release = (): void => {
if (released) {
return
}
released = true
const remaining = (map.get(paneId) ?? 1) - 1
if (remaining <= 0) {
map.delete(paneId)
} else {
map.set(paneId, remaining)
}
onReleased?.()
}
const fallback = setTimeout(release, REPLAY_GUARD_RELEASE_FALLBACK_MS)
return () => {
clearTimeout(fallback)
release()
}
}
/** Writes `data` into the pane's terminal with the replay guard engaged,
* so xterm's auto-replies to embedded query sequences do not leak to the
* shell as input. The counter increments/decrements so nested replays
@@ -43,22 +90,13 @@ export function replayIntoTerminal(
if (!data) {
return
}
const map = replayingPanesRef.current
map.set(pane.id, (map.get(pane.id) ?? 0) + 1)
const onParsed = (): void => {
const remaining = (map.get(pane.id) ?? 1) - 1
if (remaining <= 0) {
map.delete(pane.id)
} else {
map.set(pane.id, remaining)
}
}
const finishReplay = engageReplayGuard(replayingPanesRef, pane.id)
// Why: hidden/snapshot replay bypasses the live foreground write path, but
// WebGL/canvas renderers still need a post-parse repaint to drop stale cells.
writeForegroundTerminalChunk(pane.terminal, data, {
forceViewportRefresh: true,
followupViewportRefresh: true,
onParsed
onParsed: finishReplay
})
}
@@ -70,21 +108,15 @@ export function replayIntoTerminalAsync(
if (!data) {
return Promise.resolve()
}
const map = replayingPanesRef.current
map.set(pane.id, (map.get(pane.id) ?? 0) + 1)
return new Promise((resolve) => {
// Why: settle the promise when the guard releases — via parse completion or
// the fallback — so an awaiting caller never hangs if xterm's callback for a
// just-mounted/offscreen pane never arrives.
const finishReplay = engageReplayGuard(replayingPanesRef, pane.id, resolve)
writeForegroundTerminalChunk(pane.terminal, data, {
forceViewportRefresh: true,
followupViewportRefresh: true,
onParsed: () => {
const remaining = (map.get(pane.id) ?? 1) - 1
if (remaining <= 0) {
map.delete(pane.id)
} else {
map.set(pane.id, remaining)
}
resolve()
}
onParsed: finishReplay
})
})
}
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest'
import { resolveSshPaneConnectGate } from './ssh-pane-connect-gate'
const BASE = {
connectionId: 'conn-1',
sshStatus: undefined as string | undefined,
isDeferredTarget: false,
restoredLeafSessionId: null as string | null,
deferredTabSessionId: undefined as string | undefined,
tabPtyId: null as string | null,
hasLeafSessionMap: false
}
describe('resolveSshPaneConnectGate', () => {
it('routes a disconnected target through the deferred flow even without a session id', () => {
const gate = resolveSshPaneConnectGate(BASE)
expect(gate).toEqual({ pendingSessionId: null, enterDeferredFlow: true, sshConnected: false })
})
it('skips the deferred flow for a connected target with no restore state', () => {
const gate = resolveSshPaneConnectGate({ ...BASE, sshStatus: 'connected' })
expect(gate).toEqual({ pendingSessionId: null, enterDeferredFlow: false, sshConnected: true })
})
it('falls back to the tab-level app SSH pty id when the deferred maps missed the tab', () => {
const gate = resolveSshPaneConnectGate({ ...BASE, tabPtyId: 'ssh:conn-1@@pty-7' })
expect(gate.pendingSessionId).toBe('ssh:conn-1@@pty-7')
expect(gate.enterDeferredFlow).toBe(true)
})
it('ignores a tab pty id that belongs to a different connection', () => {
const gate = resolveSshPaneConnectGate({ ...BASE, tabPtyId: 'ssh:conn-2@@pty-7' })
expect(gate.pendingSessionId).toBeNull()
})
it('ignores the tab-level fallback when a per-leaf session map exists', () => {
// Why: every leaf of a split mounts its own pane; the tab-level id must
// not be reattached by all of them.
const gate = resolveSshPaneConnectGate({
...BASE,
tabPtyId: 'ssh:conn-1@@pty-7',
hasLeafSessionMap: true
})
expect(gate.pendingSessionId).toBeNull()
})
it('ignores the tab-level fallback once connected — live panes attach normally', () => {
const gate = resolveSshPaneConnectGate({
...BASE,
sshStatus: 'connected',
tabPtyId: 'ssh:conn-1@@pty-7'
})
expect(gate.pendingSessionId).toBeNull()
expect(gate.enterDeferredFlow).toBe(false)
})
it('prefers the restored leaf session, then the deferred map, then the fallback', () => {
const gate = resolveSshPaneConnectGate({
...BASE,
restoredLeafSessionId: 'ssh:conn-1@@pty-1',
deferredTabSessionId: 'ssh:conn-1@@pty-2',
tabPtyId: 'ssh:conn-1@@pty-3'
})
expect(gate.pendingSessionId).toBe('ssh:conn-1@@pty-1')
})
it('still enters the deferred flow for deferred targets that already connected', () => {
// Why: connecting via Settings does not remove the target from the
// deferred list; the gate consumes it and reattaches.
const gate = resolveSshPaneConnectGate({
...BASE,
sshStatus: 'connected',
isDeferredTarget: true
})
expect(gate.enterDeferredFlow).toBe(true)
})
it('does not force a connect for runtime-owned targets', () => {
// Why: their relay health is owned by the runtime layer; users cannot
// connect to them directly, so a reconnect flow would strand the pane.
const gate = resolveSshPaneConnectGate({
...BASE,
connectionId: 'runtime-ssh-env-1'
})
expect(gate.enterDeferredFlow).toBe(false)
})
})
@@ -0,0 +1,51 @@
import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id'
import { isRuntimeOwnedSshTargetId } from '../../../../shared/execution-host'
export type SshPaneConnectGate = {
/** Session the pane should reattach after connecting (null → fresh spawn). */
pendingSessionId: string | null
/** True when the pane must run the deferred-connect flow before any spawn. */
enterDeferredFlow: boolean
sshConnected: boolean
}
// Why: an SSH pane must never call pty:spawn while its target's provider is
// unregistered — main rejects with "No PTY provider" and the pane strands
// behind an error toast that never retries. This decides, from restore
// bookkeeping plus the live connection state, whether the pane needs the
// deferred-connect flow first and which session it should reattach.
export function resolveSshPaneConnectGate(input: {
connectionId: string
sshStatus: string | undefined
isDeferredTarget: boolean
restoredLeafSessionId: string | null
deferredTabSessionId: string | undefined
tabPtyId: string | null | undefined
hasLeafSessionMap: boolean
}): SshPaneConnectGate {
const sshConnected = input.sshStatus === 'connected'
// Why: the deferred maps can miss a tab (e.g. activeConnectionIdsAtShutdown
// wasn't persisted, so restore registered no deferred target). The tab's own
// restored app SSH pty id still names the session — reattach it rather than
// spawning a replacement shell. Skipped when a per-leaf session map exists:
// leaves carry their own ids and the tab-level id must not be attached by
// every leaf of a split.
const fallbackTabSessionId =
!sshConnected &&
!input.hasLeafSessionMap &&
input.tabPtyId &&
parseAppSshPtyId(input.tabPtyId)?.connectionId === input.connectionId
? input.tabPtyId
: null
const pendingSessionId =
input.restoredLeafSessionId ?? input.deferredTabSessionId ?? fallbackTabSessionId ?? null
// Why: runtime-owned targets are excluded — their relay health is owned by
// the runtime layer and users cannot connect to them directly.
const needsConnectBeforeSpawn = !sshConnected && !isRuntimeOwnedSshTargetId(input.connectionId)
return {
pendingSessionId,
enterDeferredFlow:
Boolean(pendingSessionId) || input.isDeferredTarget || needsConnectBeforeSpawn,
sshConnected
}
}
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'
import { shouldRetryPaneSpawnOnSshReconnect } from './ssh-reconnect-pane-retry'
describe('shouldRetryPaneSpawnOnSshReconnect', () => {
it('retries tabs with no ptyId at all', () => {
expect(
shouldRetryPaneSpawnOnSshReconnect({
targetId: 'conn-1',
tabPtyId: null,
deferredSessionId: undefined
})
).toBe(true)
})
it('retries tabs still holding a deferred session for this target', () => {
// Why: the stale wake-hint ptyId reads as live, but an unconsumed deferred
// entry proves no pane ever reattached — the pane is stranded.
expect(
shouldRetryPaneSpawnOnSshReconnect({
targetId: 'conn-1',
tabPtyId: 'ssh:conn-1@@pty-7',
deferredSessionId: 'ssh:conn-1@@pty-7'
})
).toBe(true)
})
it('leaves tabs whose deferred entry was already consumed alone', () => {
expect(
shouldRetryPaneSpawnOnSshReconnect({
targetId: 'conn-1',
tabPtyId: 'ssh:conn-1@@pty-7',
deferredSessionId: undefined
})
).toBe(false)
})
it('ignores deferred sessions that belong to another target', () => {
expect(
shouldRetryPaneSpawnOnSshReconnect({
targetId: 'conn-1',
tabPtyId: 'ssh:conn-2@@pty-3',
deferredSessionId: 'ssh:conn-2@@pty-3'
})
).toBe(false)
})
})
@@ -0,0 +1,22 @@
import { parseAppSshPtyId } from '../../../shared/ssh-pty-id'
// Why: on SSH (re)connect, panes that never got a live PTY must remount and
// retry. Two shapes qualify: tabs with no ptyId at all (their spawn failed
// outright), and tabs still holding a deferred reattach session for this
// target — their restored wake-hint ptyId reads as live but nothing is
// attached. The deferred entry is consumed synchronously the moment a pane
// starts reattaching, so a remaining entry proves the tab is stranded (e.g.
// the user cancelled the passphrase prompt and connected later via Settings).
export function shouldRetryPaneSpawnOnSshReconnect(args: {
targetId: string
tabPtyId: string | null | undefined
deferredSessionId: string | undefined
}): boolean {
if (!args.tabPtyId) {
return true
}
return (
args.deferredSessionId != null &&
parseAppSshPtyId(args.deferredSessionId)?.connectionId === args.targetId
)
}
+13 -5
View File
@@ -2,6 +2,7 @@
import { useEffect } from 'react'
import { toast } from 'sonner'
import { useAppStore } from '../store'
import { shouldRetryPaneSpawnOnSshReconnect } from './ssh-reconnect-pane-retry'
import { getWorktreeMapFromState, getRepoMapFromState } from '@/store/selectors'
import { applyUIZoom } from '@/lib/ui-zoom'
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
@@ -2615,8 +2616,10 @@ export function useIpcEvents(): void {
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.
// start) or whose deferred reattach never ran sit inert. Bumping
// generation forces TerminalPane to remount and retry; the remount
// routes through the deferred-connect gate, which reattaches the
// stranded session or spawns fresh now that the provider exists.
const freshStore = useAppStore.getState()
const remoteRepoIds = new Set(remoteRepos.map((r) => r.id))
const worktreeIds = Object.values(freshStore.worktreesByRepo)
@@ -2626,13 +2629,18 @@ export function useIpcEvents(): void {
for (const worktreeId of worktreeIds) {
const tabs = freshStore.tabsByWorktree[worktreeId] ?? []
const hasDead = tabs.some((t) => !t.ptyId)
if (hasDead) {
const needsRetry = (t: { id: string; ptyId?: string | null }): boolean =>
shouldRetryPaneSpawnOnSshReconnect({
targetId,
tabPtyId: t.ptyId,
deferredSessionId: freshStore.deferredSshSessionIdsByTabId[t.id]
})
if (tabs.some(needsRetry)) {
useAppStore.setState((s) => ({
tabsByWorktree: {
...s.tabsByWorktree,
[worktreeId]: (s.tabsByWorktree[worktreeId] ?? []).map((t) =>
t.ptyId ? t : { ...t, generation: (t.generation ?? 0) + 1 }
needsRetry(t) ? { ...t, generation: (t.generation ?? 0) + 1 } : t
)
}
}))
@@ -97,7 +97,14 @@ import {
getDefaultWorkspaceSession
} from '../../../../shared/constants'
import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope'
import { createTestStore, makeLayout, makeTab, makeWorktree, seedStore } from './store-test-helpers'
import {
createTestStore,
makeLayout,
makeTab,
makeWorktree,
seedStore,
TEST_REPO
} from './store-test-helpers'
import { canGoBackWorktreeHistory } from './worktree-nav-history'
describe('hydrateWorkspaceSession', () => {
@@ -418,6 +425,40 @@ describe('hydrateWorkspaceSession', () => {
])
})
it('stashes deferred SSH session ids for worktrees not yet in worktreesByRepo', async () => {
// Why: at cold start SSH worktrees are absent from worktreesByRepo (relay
// discovery needs the connection). The deferred stash must fall back to
// the repo id embedded in the composite worktree id — otherwise restored
// SSH panes fresh-spawn into a missing PTY provider and strand an
// "SSH connection is not active" toast.
const store = createTestStore()
const worktreeId = 'repo1::/home/user/remote-project'
const sshSessionId = 'ssh:ssh-target-1@@pty-7'
seedStore(store, {
repos: [{ ...TEST_REPO, connectionId: 'ssh-target-1' }],
worktreesByRepo: {}
})
const session: WorkspaceSessionState = {
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: 'tab-1',
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: null })]
},
terminalLayoutsByTabId: {},
activeWorktreeIdsOnShutdown: [worktreeId],
remoteSessionIdsByTabId: { 'tab-1': sshSessionId }
}
store.getState().hydrateWorkspaceSession(session)
await store.getState().reconnectPersistedTerminals()
expect(store.getState().deferredSshSessionIdsByTabId).toMatchObject({
'tab-1': sshSessionId
})
})
it('resets persisted agent titles to the fallback label on hydration', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
+6 -1
View File
@@ -3315,7 +3315,12 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
const worktree = Object.values(get().worktreesByRepo)
.flat()
.find((entry) => entry.id === worktreeId)
const repo = worktree ? get().repos.find((entry) => entry.id === worktree.repoId) : null
// Why: SSH worktrees aren't in worktreesByRepo at cold start (relay
// discovery needs the connection). Fall back to the repo id embedded in
// the composite worktree id so their sessions still reach the deferred
// map — otherwise panes fresh-spawn into a missing PTY provider.
const repoId = worktree?.repoId ?? getRepoIdFromWorktreeId(worktreeId)
const repo = repoId ? get().repos.find((entry) => entry.id === repoId) : null
if (!repo?.connectionId) {
continue
}
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { toSshExecutionHostId } from './execution-host'
import { parseAppSshPtyId, toAppSshPtyId, toRelaySshPtyId } from './ssh-pty-id'
describe('ssh pty id routing', () => {
const CONNECTION = 'ssh-1779863656395-57g1q1'
const HOST_ID = toSshExecutionHostId(CONNECTION) // "ssh:ssh-1779863656395-57g1q1"
const APP_ID = toAppSshPtyId(CONNECTION, 'pty-3') // "ssh:ssh-1779863656395-57g1q1@@pty-3"
it('encodes the bare target id into the app pty id', () => {
expect(APP_ID).toBe('ssh:ssh-1779863656395-57g1q1@@pty-3')
expect(parseAppSshPtyId(APP_ID)).toEqual({ connectionId: CONNECTION, relayPtyId: 'pty-3' })
})
it('round-trips app <-> relay ids for the matching bare connection', () => {
expect(toRelaySshPtyId(CONNECTION, APP_ID)).toBe('pty-3')
expect(toAppSshPtyId(CONNECTION, APP_ID)).toBe(APP_ID)
})
// Why: reconnect/restore callers may pass the execution-host id form
// ("ssh:<targetId>") from a workspace `hostId`; it names the same connection
// as the bare id embedded in the app pty id and must not throw or misencode.
it('accepts the execution-host id form as the same connection', () => {
expect(toRelaySshPtyId(HOST_ID, APP_ID)).toBe('pty-3')
expect(toAppSshPtyId(HOST_ID, APP_ID)).toBe(APP_ID)
// A fresh app id built from the host-id form still stores the bare id.
expect(toAppSshPtyId(HOST_ID, 'pty-7')).toBe('ssh:ssh-1779863656395-57g1q1@@pty-7')
})
it('still rejects a pty id owned by a genuinely different connection', () => {
expect(() => toRelaySshPtyId('ssh-other', APP_ID)).toThrow(
`belongs to SSH connection "${CONNECTION}"`
)
expect(() => toAppSshPtyId(toSshExecutionHostId('ssh-other'), APP_ID)).toThrow(
`belongs to SSH connection "${CONNECTION}"`
)
})
})
+16 -3
View File
@@ -1,6 +1,18 @@
import { parseExecutionHostId } from './execution-host'
const SSH_PTY_ID_PREFIX = 'ssh:'
const SSH_PTY_ID_SEPARATOR = '@@'
// Why: reconnect/restore paths sometimes hand these routers the execution-host
// id form ("ssh:<targetId>", from a workspace `hostId`) instead of the bare SSH
// target id that app PTY ids embed. Both name the same connection, so collapse
// to the bare id before comparing/encoding — otherwise a valid reattach throws a
// spurious "belongs to SSH connection" error at the user.
function normalizeConnectionId(connectionId: string): string {
const parsed = parseExecutionHostId(connectionId)
return parsed?.kind === 'ssh' ? parsed.targetId : connectionId
}
// 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 = {
@@ -32,14 +44,15 @@ export function parseAppSshPtyId(ptyId: string): ParsedSshPtyId | null {
}
export function toAppSshPtyId(connectionId: string, relayPtyId: string): string {
const normalizedConnectionId = normalizeConnectionId(connectionId)
const parsed = parseAppSshPtyId(relayPtyId)
if (parsed) {
if (parsed.connectionId !== connectionId) {
if (parsed.connectionId !== normalizedConnectionId) {
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}`
return `${SSH_PTY_ID_PREFIX}${encodeURIComponent(normalizedConnectionId)}${SSH_PTY_ID_SEPARATOR}${relayPtyId}`
}
export function toRelaySshPtyId(connectionId: string, ptyId: string): string {
@@ -47,7 +60,7 @@ export function toRelaySshPtyId(connectionId: string, ptyId: string): string {
if (!parsed) {
return ptyId
}
if (parsed.connectionId !== connectionId) {
if (parsed.connectionId !== normalizeConnectionId(connectionId)) {
throw new Error(`PTY ${ptyId} belongs to SSH connection "${parsed.connectionId}"`)
}
return parsed.relayPtyId