Resume agents after PTY cold restore (#5045)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-06-09 14:30:49 -07:00
committed by GitHub
co-authored by Orca
parent 7ed829ee67
commit 280db4a1a6
2 changed files with 178 additions and 29 deletions
@@ -65,6 +65,7 @@ type StoreState = {
suppressWhenFocused?: boolean
customSoundPath?: string | null
}
agentCmdOverrides?: Record<string, string>
} | null
codexRestartNoticeByPtyId: Record<
string,
@@ -2850,6 +2851,100 @@ describe('connectPanePty', () => {
expect(window.api.pty.ackColdRestore).toHaveBeenCalledWith('tab-pty')
})
it('resumes the provider agent session when daemon reattach cold-restores a fresh shell', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('fresh-pty')
transport.connect.mockImplementation(async ({ sessionId }: { sessionId?: string }) => {
if (sessionId) {
return {
id: 'fresh-pty',
coldRestore: { scrollback: 'cold-payload', cwd: '/tmp/wt-1' }
}
}
return 'fresh-pty'
})
transportFactoryQueue.push(transport)
const paneKey = makePaneKey('tab-1', LEAF_1)
mockStoreState = {
...mockStoreState,
tabsByWorktree: {
'wt-1': [{ id: 'tab-1', ptyId: 'lost-pty' }]
},
settings: {
...mockStoreState.settings,
agentCmdOverrides: {}
},
agentStatusByPaneKey: {
[paneKey]: {
state: 'working',
prompt: 'finish the task',
agentType: 'codex',
paneKey,
updatedAt: 1,
stateStartedAt: 1,
stateHistory: [],
providerSession: { key: 'session_id', id: 'codex-session-1' }
}
}
} as StoreState
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps({
restoredLeafId: LEAF_1,
restoredPtyIdByLeafId: { [LEAF_1]: 'lost-pty' }
})
connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks(20)
await new Promise((resolve) => setTimeout(resolve, 70))
expect(pane.terminal.write).toHaveBeenCalledWith('cold-payload', expect.any(Function))
expect(transport.sendInput).toHaveBeenCalledWith("codex 'resume' 'codex-session-1'\r")
})
it('does not resume the provider session when daemon reattach returns a live snapshot', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('tab-pty')
transport.connect.mockImplementation(async ({ sessionId }: { sessionId?: string }) => {
if (sessionId) {
return { id: sessionId, snapshot: 'live-snapshot' }
}
return null
})
transportFactoryQueue.push(transport)
const paneKey = makePaneKey('tab-1', LEAF_1)
mockStoreState = {
...mockStoreState,
agentStatusByPaneKey: {
[paneKey]: {
state: 'working',
prompt: 'finish the task',
agentType: 'codex',
paneKey,
updatedAt: 1,
stateStartedAt: 1,
stateHistory: [],
providerSession: { key: 'session_id', id: 'codex-session-1' }
}
}
} as StoreState
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps({
restoredLeafId: LEAF_1,
restoredPtyIdByLeafId: { [LEAF_1]: 'tab-pty' }
})
connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks(20)
await new Promise((resolve) => setTimeout(resolve, 70))
expect(pane.terminal.write).toHaveBeenCalledWith('live-snapshot', expect.any(Function))
expect(transport.sendInput).not.toHaveBeenCalled()
})
it('keeps non-visible local PTY bytes on the live xterm path for release', async () => {
const pendingTimeouts: (() => void)[] = []
const originalSetTimeout = globalThis.setTimeout
@@ -81,6 +81,13 @@ import {
cancelScheduledHiddenOutputRestore,
scheduleHiddenOutputRestore
} from './hidden-output-restore-scheduler'
import { CLIENT_PLATFORM } from '@/lib/new-workspace'
import { buildAgentResumeStartupPlan } from '@/lib/tui-agent-startup'
import {
isResumableTuiAgent,
normalizeAgentProviderSession
} from '../../../../shared/agent-session-resume'
import { isWslUncPath } from '../../../../shared/wsl-paths'
const pendingSpawnByPaneKey = new Map<string, Promise<string | null>>()
const SSH_SESSION_EXPIRED_ERROR = 'SSH_SESSION_EXPIRED'
@@ -1749,6 +1756,70 @@ export function connectPanePty(
// stay renderer-delivered so xterm can apply bracketed-paste semantics.
let pendingStartupCommand =
shouldDeliverStartupViaTerminalPaste || connectionId ? (paneStartup?.command ?? null) : null
const getColdRestoreAgentResumePlatform = (): NodeJS.Platform => {
if (connectionId || (worktree?.path && isWslUncPath(worktree.path))) {
return 'linux'
}
return CLIENT_PLATFORM
}
const prepareColdRestoreAgentResumeCommand = (): boolean => {
if (pendingStartupCommand) {
return false
}
const entry = useAppStore.getState().agentStatusByPaneKey[cacheKey]
if (!entry || entry.state === 'done' || !isResumableTuiAgent(entry.agentType)) {
return false
}
const providerSession = normalizeAgentProviderSession(entry.providerSession)
if (!providerSession) {
return false
}
const startupPlan = buildAgentResumeStartupPlan({
agent: entry.agentType,
providerSession,
cmdOverrides: useAppStore.getState().settings?.agentCmdOverrides ?? {},
platform: getColdRestoreAgentResumePlatform()
})
if (!startupPlan) {
return false
}
// Why: cold restore means the PTY process is gone but the agent provider
// session is still resumable, so the replacement shell must launch it.
pendingStartupCommand = startupPlan.launchCommand
return true
}
const schedulePendingStartupCommandDelivery = (): void => {
if (!pendingStartupCommand) {
return
}
if (startupInjectTimer !== null) {
clearTimeout(startupInjectTimer)
}
startupInjectTimer = setTimeout(() => {
startupInjectTimer = null
void (async () => {
const command = pendingStartupCommand
if (!command || disposed) {
return
}
if (shouldDeliverStartupViaTerminalPaste) {
await waitForTerminalOutputParsed(pane.terminal)
}
if (pendingStartupCommand !== command || disposed) {
return
}
if (shouldDeliverStartupViaTerminalPaste) {
// Why: this mode must pass through xterm so bracketed-paste
// wrapping is applied before the submit Enter.
pasteTerminalText(pane.terminal, command)
transport.sendInput('\r')
} else {
transport.sendInput(`${command}\r`)
}
pendingStartupCommand = null
})()
}, 50)
}
const startFreshSpawn = (): void => {
// Why: pre-signal the main process so its cooperation gate suppresses
@@ -2553,35 +2624,7 @@ export function connectPanePty(
writePtyOutputToXterm(data, foreground)
}
if (pendingStartupCommand) {
if (startupInjectTimer !== null) {
clearTimeout(startupInjectTimer)
}
startupInjectTimer = setTimeout(() => {
startupInjectTimer = null
void (async () => {
const command = pendingStartupCommand
if (!command || disposed) {
return
}
if (shouldDeliverStartupViaTerminalPaste) {
await waitForTerminalOutputParsed(pane.terminal)
}
if (pendingStartupCommand !== command || disposed) {
return
}
if (shouldDeliverStartupViaTerminalPaste) {
// Why: this mode must pass through xterm so bracketed-paste
// wrapping is applied before the submit Enter.
pasteTerminalText(pane.terminal, command)
transport.sendInput('\r')
} else {
transport.sendInput(`${command}\r`)
}
pendingStartupCommand = null
})()
}, 50)
}
schedulePendingStartupCommandDelivery()
}
unregisterE2ePtyDataInjection = registerE2eTerminalPtyDataInjection(cacheKey, (data, meta) => {
if (!disposed) {
@@ -2615,6 +2658,7 @@ export function connectPanePty(
if (staleSessionId) {
deps.clearTabPtyId(deps.tabId, staleSessionId)
}
prepareColdRestoreAgentResumeCommand()
startFreshSpawn()
return
}
@@ -2626,6 +2670,7 @@ export function connectPanePty(
// Why: SSH sleep/reconnect can invalidate the relay-held PTY while
// leaving the tab mounted. Replace the dead lease in-place instead of
// stranding the pane behind a stale expired-session overlay.
prepareColdRestoreAgentResumeCommand()
startFreshSpawn()
return
}
@@ -2696,6 +2741,9 @@ export function connectPanePty(
if (!isRemoteRuntimePtyId(ptyId)) {
window.api.pty.ackColdRestore(ptyId)
}
if (prepareColdRestoreAgentResumeCommand()) {
schedulePendingStartupCommandDelivery()
}
}
// Why: when a mobile-fit override is active, skip sending desktop dims
// to the PTY — the PTY is already at phone dimensions and must stay there.
@@ -2916,6 +2964,7 @@ export function connectPanePty(
}
deps.syncPanePtyLayoutBinding(pane.id, null)
deps.clearTabPtyId(deps.tabId, pendingSessionId)
prepareColdRestoreAgentResumeCommand()
startFreshSpawn()
return
}
@@ -2939,9 +2988,11 @@ export function connectPanePty(
if (isSshSessionExpiredError(err)) {
deps.syncPanePtyLayoutBinding(pane.id, null)
deps.clearTabPtyId(deps.tabId, pendingSessionId)
prepareColdRestoreAgentResumeCommand()
startFreshSpawn()
return
}
prepareColdRestoreAgentResumeCommand()
startFreshSpawn()
})
} else {
@@ -3042,6 +3093,7 @@ export function connectPanePty(
}
deps.syncPanePtyLayoutBinding(pane.id, null)
deps.clearTabPtyId(deps.tabId, deferredReattachSessionId)
prepareColdRestoreAgentResumeCommand()
startFreshSpawn()
return
}
@@ -3070,10 +3122,12 @@ export function connectPanePty(
deps.syncPanePtyLayoutBinding(pane.id, null)
deps.clearTabPtyId(deps.tabId, deferredReattachSessionId)
if (connectionId && isSshSessionExpiredError(err)) {
prepareColdRestoreAgentResumeCommand()
startFreshSpawn()
return
}
reportError(message)
prepareColdRestoreAgentResumeCommand()
startFreshSpawn()
})
} else if (detachedRemoteLeafPtyId || detachedLivePtyId) {