From b4718dd05c4893f43808eec34faa1109e434f8a5 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 24 Jul 2026 18:40:05 -0700 Subject: [PATCH] fix(terminal): resume hibernated agents that reattach with no payload (#9648) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(terminal): resume hibernated agents that reattach with no payload When agent hibernation is on, a stopped (done) agent's PTY is killed and a passive sleeping record is kept; returning to the worktree relies on the pane reattaching on remount. On the daemon path (Windows/local worktrees) the daemon can reattach the hibernation-killed session as already-live (isReattach, isNew:false) and return no snapshot/replay/coldRestore — and, being a reattach rather than a fresh spawn, it silently drops the --resume command passed on connect. The renderer adopted that empty session, leaving a blank terminal with nothing running and the sidebar history still pointing at the dead tab (the sleeping record never cleared). A reopened pane that owns a resumable slept session must always be re-driven with its resume command, never left as a bare empty attach. handleReattachResult now discards a contentless isReattach for a pane with a hibernation record and re-drives the prepared resume. This excludes the healthy cases: a fresh session the daemon created (isReattach falsy — it already ran the command) and a live reattach (carries a snapshot/replay). Forward the isReattach signal the transport was dropping so the two cases are distinguishable. Adds a deterministic regression test that fails without the guard and passes with it. * fix(terminal): preserve provider ownership on resume * chore(skills): refresh generated skill bundle manifests Regenerate the skill bundle artifacts against the full release-tag set so the freshness verify check passes. Append-only additions for the newer release tags; no released snapshot history is rewritten. --- .../terminal-pane/pty-connection.test.ts | 211 ++++++++++++++++++ .../terminal-pane/pty-connection.ts | 36 ++- .../terminal-pane/pty-transport-types.ts | 3 + .../terminal-pane/pty-transport.test.ts | 17 ++ .../components/terminal-pane/pty-transport.ts | 2 + 5 files changed, 263 insertions(+), 6 deletions(-) diff --git a/src/renderer/src/components/terminal-pane/pty-connection.test.ts b/src/renderer/src/components/terminal-pane/pty-connection.test.ts index 62c49f55f..cd03a7669 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.test.ts @@ -245,6 +245,7 @@ type MockTransport = { impl: (opts: { callbacks?: ConnectCallbacks } & Record) => Promise ) => unknown } + disconnect: ReturnType sendInput: ReturnType sendInputImmediate: ReturnType sendInputAccepted?: ReturnType @@ -377,6 +378,9 @@ function createMockTransport(initialPtyId: string | null = null): MockTransport } return ptyId }), + disconnect: vi.fn(() => { + ptyId = null + }), sendInput: vi.fn(() => true), claimViewport: vi.fn(() => true), resize: vi.fn(() => true), @@ -6422,6 +6426,213 @@ describe('connectPanePty', () => { } }) + it('re-runs the resume command when a hibernated local session reattaches with no payload', async () => { + // Why: the daemon drops startup commands on reattach, so a passive hibernation record must replace a contentless adopted shell. + const pendingTimeouts: (() => void)[] = [] + const originalSetTimeout = globalThis.setTimeout + globalThis.setTimeout = vi.fn((fn: () => void) => { + pendingTimeouts.push(fn) + return 999 as unknown as ReturnType + }) as unknown as typeof setTimeout + + try { + const { connectPanePty } = await import('./pty-connection') + const paneKey = makePaneKey('tab-1', LEAF_2) + let activePtyId: string | null = 'restored-session' + const transport = createMockTransport('restored-session') + transport.getPtyId.mockImplementation(() => activePtyId) + transport.disconnect.mockImplementation(() => { + activePtyId = null + }) + transport.connect.mockImplementation(async (opts: { sessionId?: string }) => { + if (opts.sessionId) { + activePtyId = opts.sessionId + return { + id: opts.sessionId, + isReattach: true, + snapshot: undefined, + replay: undefined, + coldRestore: undefined + } + } + activePtyId = 'fresh-resume-pty' + const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as + | ((ptyId: string) => void) + | undefined + onPtySpawn?.('fresh-resume-pty') + return 'fresh-resume-pty' + }) + transportFactoryQueue.push(transport) + mockStoreState = { + ...mockStoreState, + tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'restored-session' }] }, + settings: { + ...mockStoreState.settings, + agentCmdOverrides: {} + }, + sleepingAgentSessionsByPaneKey: { + [paneKey]: { + paneKey, + tabId: 'tab-1', + worktreeId: 'wt-1', + agent: 'codex', + providerSession: { key: 'session_id', id: 'codex-session-1' }, + prompt: 'finish the task', + // Mirrors the user's scenario: a stopped/completed agent that hibernated. + state: 'done', + origin: 'worktree-sleep', + capturedAt: 1, + updatedAt: 1 + } + } + } as StoreState + const pane = createPane(2) + const manager = createManager(2) + const deps = createDeps({ + restoredLeafId: LEAF_2, + restoredPtyIdByLeafId: { [LEAF_2]: 'restored-session' } + }) + vi.mocked(window.api.pty.declarePendingPaneSerializer) + .mockResolvedValueOnce(1) + .mockResolvedValueOnce(2) + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks(20) + for (const fn of pendingTimeouts) { + fn() + } + await flushAsyncTicks(10) + + expect(transport.disconnect).toHaveBeenCalledTimes(1) + expect(transport.connect).toHaveBeenCalledTimes(2) + expect(transport.connect).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ + command: "codex '--dangerously-bypass-approvals-and-sandbox' 'resume' 'codex-session-1'", + env: expect.objectContaining({ + ORCA_PANE_KEY: paneKey, + ORCA_AGENT_LAUNCH_TOKEN: expect.stringMatching(new RegExp(`^${UUID_RE}$`)) + }) + }) + ) + // The dead session is not adopted as the pane's live PTY. + expect(deps.clearExitedPanePtyLayoutBinding).toHaveBeenCalledWith(2, 'restored-session') + expect(deps.clearTabPtyId).toHaveBeenCalledWith('tab-1', 'restored-session') + expect(deps.syncPanePtyLayoutBinding).not.toHaveBeenCalledWith(2, 'restored-session') + expect(deps.syncPanePtyLayoutBinding).toHaveBeenCalledWith(2, 'fresh-resume-pty') + expect(mockStoreState.clearSleepingAgentSession).toHaveBeenCalledWith(paneKey) + expect(window.api.pty.clearPendingPaneSerializer).toHaveBeenCalledWith(paneKey, 1) + } finally { + globalThis.setTimeout = originalSetTimeout + } + }) + + it('keeps a contentless reattach when the sleeping record represents a live session', async () => { + const { connectPanePty } = await import('./pty-connection') + const paneKey = makePaneKey('tab-1', LEAF_2) + const transport = createMockTransport('restored-session') + transport.connect.mockResolvedValue({ + id: 'restored-session', + isReattach: true, + snapshot: undefined, + replay: undefined, + coldRestore: undefined + }) + transportFactoryQueue.push(transport) + mockStoreState = { + ...mockStoreState, + tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'restored-session' }] }, + settings: { ...mockStoreState.settings, agentCmdOverrides: {} }, + sleepingAgentSessionsByPaneKey: { + [paneKey]: { + paneKey, + tabId: 'tab-1', + worktreeId: 'wt-1', + agent: 'codex', + providerSession: { key: 'session_id', id: 'codex-session-1' }, + prompt: 'finish the task', + state: 'working', + origin: 'live', + capturedAt: 1, + updatedAt: 1 + } + } + } as StoreState + const pane = createPane(2) + const manager = createManager(2) + const deps = createDeps({ + restoredLeafId: LEAF_2, + restoredPtyIdByLeafId: { [LEAF_2]: 'restored-session' } + }) + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks(20) + + expect(transport.connect).toHaveBeenCalledTimes(1) + expect(transport.disconnect).not.toHaveBeenCalled() + expect(deps.syncPanePtyLayoutBinding).toHaveBeenCalledWith(2, 'restored-session') + expect(mockStoreState.clearSleepingAgentSession).not.toHaveBeenCalled() + }) + + it('keeps a contentless reattach when a live status supersedes passive sleep evidence', async () => { + const { connectPanePty } = await import('./pty-connection') + const paneKey = makePaneKey('tab-1', LEAF_2) + const transport = createMockTransport('restored-session') + transport.connect.mockResolvedValue({ + id: 'restored-session', + isReattach: true, + snapshot: undefined, + replay: undefined, + coldRestore: undefined + }) + transportFactoryQueue.push(transport) + mockStoreState = { + ...mockStoreState, + tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'restored-session' }] }, + settings: { ...mockStoreState.settings, agentCmdOverrides: {} }, + agentStatusByPaneKey: { + [paneKey]: { + state: 'working', + prompt: 'new live task', + agentType: 'codex', + providerSession: { key: 'session_id', id: 'live-codex-session' }, + paneKey, + updatedAt: 2, + stateStartedAt: 2, + stateHistory: [] + } + }, + sleepingAgentSessionsByPaneKey: { + [paneKey]: { + paneKey, + tabId: 'tab-1', + worktreeId: 'wt-1', + agent: 'codex', + providerSession: { key: 'session_id', id: 'old-codex-session' }, + prompt: 'old completed task', + state: 'done', + origin: 'worktree-sleep', + capturedAt: 1, + updatedAt: 1 + } + } + } as StoreState + const pane = createPane(2) + const manager = createManager(2) + const deps = createDeps({ + restoredLeafId: LEAF_2, + restoredPtyIdByLeafId: { [LEAF_2]: 'restored-session' } + }) + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks(20) + + expect(transport.connect).toHaveBeenCalledTimes(1) + expect(transport.disconnect).not.toHaveBeenCalled() + expect(deps.syncPanePtyLayoutBinding).toHaveBeenCalledWith(2, 'restored-session') + expect(mockStoreState.clearSleepingAgentSession).not.toHaveBeenCalled() + }) + it('clears the pending serializer when disposed before non-deferred SSH reattach expiry resolves', async () => { const { connectPanePty } = await import('./pty-connection') const reattach = createDeferred() diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index f97e63e86..90c7aa097 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -7294,6 +7294,30 @@ export function connectPanePty( if (!isCurrentReattachPayload()) { return false } + // Strict precedence snapshot > replay > coldRestore: paint exactly one, else overlapping tails duplicate TUI output on worktree switch. + const hasStructuralReplay = Boolean( + connectResult?.snapshot || connectResult?.replay || connectResult?.coldRestore + ) + const resumeComesFromPassiveHibernation = Boolean( + coldRestoreStartup && + !coldRestoreStartup.useLiveEntry && + coldRestoreStartup.sleepingRecordEntry && + isPassiveCompletedHibernationEvidence(coldRestoreStartup.sleepingRecordEntry.record) + ) + // Why: reattach drops startup commands; only passive hibernation is authority to retire an empty adopted shell and resume its provider session. + if (!hasStructuralReplay && connectResult?.isReattach && resumeComesFromPassiveHibernation) { + transport.disconnect() + if (staleSessionId) { + deps.clearExitedPanePtyLayoutBinding(pane.id, staleSessionId) + deps.clearTabPtyId(deps.tabId, staleSessionId) + } else { + deps.syncPanePtyLayoutBinding(pane.id, null) + } + startFreshColdRestoreAgentResume(coldRestoreStartup, { + forceBlankRestoredViewport: true + }) + return false + } setPanePtyFitBinding(ptyId) reportPanePtyVisibility(ptyId, deps.isVisibleRef.current) registerSideEffectFactConsumerForPty(ptyId) @@ -7306,10 +7330,6 @@ export function connectPanePty( // Why: mobile streaming needs xterm's exact screen state; install the serializer + lastTitle source for main-process hydration parity. registerPaneSerializerFor(ptyId) - // Strict precedence snapshot > replay > coldRestore: paint exactly one, else overlapping tails duplicate TUI output on worktree switch. - const hasStructuralReplay = Boolean( - connectResult?.snapshot || connectResult?.replay || connectResult?.coldRestore - ) let reattachPayloadApplied = !hasStructuralReplay const applyReattachPayload = async (): Promise => { if (!isCurrentReattachPayload()) { @@ -7739,7 +7759,9 @@ export function connectPanePty( finishReattachLiveDataDeferral(accepted, outputCallbacks.generation) const gen = await preSignalPromise if (typeof gen === 'number') { - if (!isRemoteRuntimePtyId(pendingSessionId)) { + if (!accepted) { + await window.api.pty.clearPendingPaneSerializer(cacheKey, gen).catch(() => {}) + } else if (!isRemoteRuntimePtyId(pendingSessionId)) { const settledPtyId = result && typeof result === 'object' && 'id' in result ? result.id @@ -7950,7 +7972,9 @@ export function connectPanePty( finishReattachLiveDataDeferral(accepted, outputCallbacks.generation) const gen = await preSignalPromise if (typeof gen === 'number') { - if (!isRemoteRuntimePtyId(deferredReattachSessionId)) { + if (!accepted) { + await window.api.pty.clearPendingPaneSerializer(cacheKey, gen).catch(() => {}) + } else if (!isRemoteRuntimePtyId(deferredReattachSessionId)) { const settledPtyId = result && typeof result === 'object' && 'id' in result ? result.id diff --git a/src/renderer/src/components/terminal-pane/pty-transport-types.ts b/src/renderer/src/components/terminal-pane/pty-transport-types.ts index 3359e579d..2b835045c 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport-types.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport-types.ts @@ -50,6 +50,9 @@ export type PtyConnectResult = { /** The requested session exited while it had no primary pane handler. Its * buffered final data/exit were delivered, so callers must not fresh-spawn. */ exitedBeforeAttach?: boolean + /** The provider adopted an existing session rather than creating a fresh one. + * Startup commands may be ignored; recovery still requires separate ownership evidence. */ + isReattach?: boolean launchAgent?: TuiAgent launchConfig?: SleepingAgentLaunchConfig snapshot?: string diff --git a/src/renderer/src/components/terminal-pane/pty-transport.test.ts b/src/renderer/src/components/terminal-pane/pty-transport.test.ts index cedcaac48..3df5d04c0 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport.test.ts @@ -100,6 +100,21 @@ describe('createIpcPtyTransport', () => { expect(kill).not.toHaveBeenCalled() }) + it('retires an adopted PTY when recovery disconnects before a replacement spawn', async () => { + const { createIpcPtyTransport } = await import('./pty-transport') + const spawn = window.api.pty.spawn as unknown as ReturnType + const kill = window.api.pty.kill as unknown as ReturnType + spawn.mockResolvedValueOnce({ id: 'empty-reattach', isReattach: true }) + const transport = createIpcPtyTransport({}) + + await transport.connect({ url: '', sessionId: 'empty-reattach', callbacks: {} }) + transport.disconnect() + + expect(kill).toHaveBeenCalledWith('empty-reattach') + expect(transport.getPtyId()).toBeNull() + expect(transport.isConnected()).toBe(false) + }) + it('forwards requested environment deletions to the PTY spawn', async () => { const { createIpcPtyTransport } = await import('./pty-transport') const spawn = window.api.pty.spawn as unknown as ReturnType @@ -1389,6 +1404,7 @@ describe('createIpcPtyTransport', () => { expect(result).toEqual({ id: 'pty-reattach', + isReattach: true, launchAgent: 'droid', snapshot: 'snapshot data', snapshotCols: 132, @@ -1413,6 +1429,7 @@ describe('createIpcPtyTransport', () => { expect(result).toEqual({ id: 'pty-unknown-launch-agent', + isReattach: true, snapshot: undefined, snapshotCols: undefined, snapshotRows: undefined, diff --git a/src/renderer/src/components/terminal-pane/pty-transport.ts b/src/renderer/src/components/terminal-pane/pty-transport.ts index 3d97f90f1..d3bdd6082 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport.ts @@ -772,6 +772,8 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra if (spawnResult.isReattach || spawnResult.coldRestore || spawnResult.sessionExpired) { return { id: spawnResult.id, + // Why: recovery needs to distinguish an attach that ignored startup intent from a fresh spawn that ran it. + ...(spawnResult.isReattach ? { isReattach: true } : {}), ...(resultLaunchAgent ? { launchAgent: resultLaunchAgent } : {}), ...(spawnResult.launchConfig ? { launchConfig: spawnResult.launchConfig } : {}), snapshot: spawnResult.snapshot,