Restore slept terminal output on wake

This commit is contained in:
Neil
2026-06-09 17:06:55 -07:00
parent 0cf30df478
commit 57991d13ab
5 changed files with 285 additions and 26 deletions
@@ -676,6 +676,51 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => {
}
})
it('checkpoints before keep-history shutdown so sleep can cold restore latest output', async () => {
const adapterClass = DaemonPtyAdapter as unknown as { CHECKPOINT_INTERVAL_MS: number }
const previousInterval = adapterClass.CHECKPOINT_INTERVAL_MS
adapterClass.CHECKPOINT_INTERVAL_MS = 10_000
try {
historyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir })
const { id } = await historyAdapter.spawn({
cols: 80,
rows: 24,
cwd: '/home/user',
sessionId: 'sleep-checkpoint'
})
const checkpointSpy = vi.spyOn(historyAdapter.getHistoryManager()!, 'checkpoint')
lastSubprocess._simulateData('latest before sleep\r\n')
await historyAdapter.shutdown(id, { immediate: true, keepHistory: true })
expect(checkpointSpy).toHaveBeenCalledWith(
id,
expect.objectContaining({ snapshotAnsi: expect.stringContaining('latest before sleep') })
)
expect(existsSync(join(historyDir, getHistorySessionDirName(id)))).toBe(true)
const restored = await historyAdapter.spawn({
cols: 80,
rows: 24,
cwd: '/home/user',
sessionId: id
})
expect(restored.coldRestore?.scrollback).toContain('latest before sleep')
historyAdapter.ackColdRestore(id)
const remountAfterAck = await historyAdapter.spawn({
cols: 80,
rows: 24,
cwd: '/home/user',
sessionId: id
})
expect(remountAfterAck.coldRestore).toBeUndefined()
} finally {
adapterClass.CHECKPOINT_INTERVAL_MS = previousInterval
}
})
it('writes meta.json with endedAt on exit', async () => {
historyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir })
+44 -18
View File
@@ -7,6 +7,7 @@ import { DaemonClient } from './client'
import { getMacDaemonSystemResolverHealth } from './daemon-health'
import { HistoryManager } from './history-manager'
import { HistoryReader } from './history-reader'
import type { ColdRestoreInfo } from './history-reader'
import { mintPtySessionId, parsePtySessionId } from './pty-session-id'
import { supportsPtyStartupBarrier } from './shell-ready'
import {
@@ -69,6 +70,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
// mount → ??? The sticky cache returns the same cold restore data on the
// second mount until the renderer explicitly acknowledges it.
private coldRestoreCache = new Map<string, { scrollback: string; cwd: string }>()
private sleepRestoreSessionIds = new Set<string>()
private activeSessionIds = new Set<string>()
private dirtySessionVersions = new Map<string, number>()
private checkpointTimer: ReturnType<typeof setTimeout> | null = null
@@ -169,28 +171,14 @@ export class DaemonPtyAdapter implements IPtyProvider {
// an unclean shutdown → return saved scrollback so the renderer can
// display the previous terminal content.
if (result.isNew && restoreInfo) {
// Why: if the checkpoint was captured while an alternate-screen app
// (vim, less, htop) was active, snapshotAnsi is the alt buffer content.
// Replaying that into a fresh shell would show stale TUI content. Use
// scrollbackAnsi (rows above the viewport only) which excludes the alt
// buffer. For normal sessions, use the full snapshot with rehydrate
// sequences to restore terminal modes (colors, cursor position, etc).
// Why: scrollbackAnsi may be empty if the emulator hadn't accumulated
// scrollback before the alt-screen app launched. In that case, skip
// cold restore entirely rather than showing a blank terminal — no
// content is better than confusing the user with an empty restore.
const isAltScreen = restoreInfo.modes.alternateScreen
const scrollback = isAltScreen
? restoreInfo.scrollbackAnsi || null
: restoreInfo.rehydrateSequences + restoreInfo.snapshotAnsi
const coldRestore = this.buildColdRestorePayload(restoreInfo)
// Why: use registerWriter (not openSession) to avoid deleting the
// existing checkpoint.json. If the revived daemon crashes again before
// the next 5s tick, the checkpoint is the only recovery data available.
if (this.historyManager) {
this.historyManager.registerWriter(sessionId)
}
if (scrollback) {
const coldRestore = { scrollback, cwd: restoreInfo.cwd }
if (coldRestore) {
this.coldRestoreCache.set(sessionId, coldRestore)
return { id: sessionId, pid, coldRestore }
}
@@ -256,10 +244,27 @@ export class DaemonPtyAdapter implements IPtyProvider {
}
async shutdown(id: string, opts: { immediate?: boolean; keepHistory?: boolean }): Promise<void> {
if (opts.keepHistory && this.historyManager && this.supportsCheckpoints) {
// Why: sleep kills the live PTY before the periodic checkpoint may run.
// Capture the daemon buffer now so wake can restore the pane users left.
if (this.checkpointInFlight) {
await this.checkpointInFlight
}
await this.checkpointSessions([id])
const restoreInfo = this.historyReader?.detectColdRestore(id) ?? null
const coldRestore = restoreInfo ? this.buildColdRestorePayload(restoreInfo) : null
if (coldRestore) {
this.coldRestoreCache.set(id, coldRestore)
this.sleepRestoreSessionIds.add(id)
}
}
await this.client.request('kill', { sessionId: id })
this.activeSessionIds.delete(id)
this.dirtySessionVersions.delete(id)
this.coldRestoreCache.delete(id)
if (!opts.keepHistory) {
this.coldRestoreCache.delete(id)
this.sleepRestoreSessionIds.delete(id)
}
this.stopCheckpointTimerIfIdle()
this.initialCwds.delete(id)
// Why: history removal is for the "user explicitly closed this terminal"
@@ -289,12 +294,31 @@ export class DaemonPtyAdapter implements IPtyProvider {
ackColdRestore(sessionId: string): void {
this.coldRestoreCache.delete(sessionId)
this.sleepRestoreSessionIds.delete(sessionId)
}
clearTombstone(sessionId: string): void {
this.killedSessionTombstones.delete(sessionId)
}
private buildColdRestorePayload(
restoreInfo: ColdRestoreInfo
): { scrollback: string; cwd: string } | null {
// Why: if the checkpoint was captured while an alternate-screen app
// (vim, less, htop) was active, snapshotAnsi is the alt buffer content.
// Replaying that into a fresh shell would show stale TUI content. Use
// scrollbackAnsi (rows above the viewport only) which excludes the alt
// buffer. For normal sessions, use the full snapshot with rehydrate
// sequences to restore terminal modes (colors, cursor position, etc).
const scrollback = restoreInfo.modes.alternateScreen
? restoreInfo.scrollbackAnsi || null
: restoreInfo.rehydrateSequences + restoreInfo.snapshotAnsi
if (!scrollback) {
return null
}
return { scrollback, cwd: restoreInfo.cwd }
}
async sendSignal(id: string, signal: string): Promise<void> {
await this.client.request('signal', { sessionId: id, signal })
}
@@ -764,7 +788,9 @@ export class DaemonPtyAdapter implements IPtyProvider {
} else if (event.event === 'exit') {
this.activeSessionIds.delete(event.sessionId)
this.dirtySessionVersions.delete(event.sessionId)
this.coldRestoreCache.delete(event.sessionId)
if (!this.sleepRestoreSessionIds.has(event.sessionId)) {
this.coldRestoreCache.delete(event.sessionId)
}
this.stopCheckpointTimerIfIdle()
if (this.historyManager) {
void this.historyManager
@@ -710,6 +710,8 @@ describe('connectPanePty', () => {
onPtyExit?.('pty-pane-2')
expect(deps.consumeSuppressedPtyExit).toHaveBeenCalledWith('pty-pane-2')
expect(deps.syncPanePtyLayoutBinding).not.toHaveBeenCalled()
expect(deps.clearTabPtyId).not.toHaveBeenCalled()
expect(deps.onPtyExitRef.current).not.toHaveBeenCalled()
expect(manager.closePane).not.toHaveBeenCalled()
})
@@ -993,6 +993,13 @@ export function connectPanePty(
const onExit = (ptyId: string): void => {
agentCompletionCoordinator.dispose()
clearPanePtyFitBinding()
// Why: sleep and intentional pane-close/restart paths already record the
// desired lifecycle state before kill. Do not erase wake hints here.
if (deps.consumeSuppressedPtyExit(ptyId)) {
manager.setPaneGpuRendering(pane.id, true)
scheduleRuntimeGraphSync()
return
}
deps.syncPanePtyLayoutBinding(pane.id, null)
deps.clearRuntimePaneTitle(deps.tabId, pane.id)
deps.clearTabPtyId(deps.tabId, ptyId)
@@ -1007,14 +1014,6 @@ export function connectPanePty(
// we must republish when a pane loses its PTY instead of waiting for a
// broader layout change that may never happen.
scheduleRuntimeGraphSync()
// Why: intentional restarts suppress the PTY exit ahead of time so the
// pane stays mounted and can reconnect in place. Without consuming the
// suppression here, split-pane Codex restarts would still close the pane
// because this handler runs before the tab-level close logic sees the exit.
if (deps.consumeSuppressedPtyExit(ptyId)) {
manager.setPaneGpuRendering(pane.id, true)
return
}
manager.setPaneGpuRendering(pane.id, true)
const panes = manager.getPanes()
if (panes.length <= 1) {
@@ -0,0 +1,187 @@
import { randomUUID } from 'node:crypto'
import type { Page } from '@stablyai/playwright-test'
import { test, expect } from './helpers/orca-app'
import {
ensureTerminalVisible,
getAllWorktreeIds,
switchToWorktree,
waitForActiveWorktree,
waitForSessionReady
} from './helpers/store'
import {
getTerminalContent,
sendToTerminal,
waitForActivePanePtyId,
waitForActiveTerminalManager,
waitForTerminalOutput
} from './helpers/terminal'
type SleepWakeTerminalDebug = {
activeTabId: string | null
activeWorktreeId: string | null
tabs: {
id: string
ptyId?: string
generation?: number
pendingActivationSpawn?: boolean | number
}[]
ptyIdsByTabId: Record<string, string[]>
ptyIdsByLeafIdByTabId: Record<string, Record<string, string>>
}
async function sleepWorktreeTerminals(page: Page, worktreeId: string): Promise<void> {
await page.evaluate(async (id) => {
const store = window.__store
if (!store) {
throw new Error('store unavailable')
}
const state = store.getState()
await state.shutdownWorktreeBrowsers(id)
await state.shutdownWorktreeTerminals(id, { keepIdentifiers: true })
}, worktreeId)
}
async function readLivePtyCountForWorktree(page: Page, worktreeId: string): Promise<number> {
return page.evaluate((id) => {
const store = window.__store
if (!store) {
return 0
}
const state = store.getState()
const tabs = state.tabsByWorktree[id] ?? []
return tabs.reduce((count, tab) => count + (state.ptyIdsByTabId[tab.id]?.length ?? 0), 0)
}, worktreeId)
}
async function readSleepWakeTerminalDebug(
page: Page,
worktreeId: string
): Promise<SleepWakeTerminalDebug> {
return page.evaluate((id) => {
const store = window.__store
if (!store) {
return {
activeTabId: null,
activeWorktreeId: null,
tabs: [],
ptyIdsByTabId: {},
ptyIdsByLeafIdByTabId: {}
}
}
const state = store.getState()
const tabs = state.tabsByWorktree[id] ?? []
return {
activeTabId: state.activeTabId,
activeWorktreeId: state.activeWorktreeId,
tabs: tabs.map((tab) => ({
id: tab.id,
ptyId: tab.ptyId,
generation: tab.generation,
pendingActivationSpawn: tab.pendingActivationSpawn
})),
ptyIdsByTabId: Object.fromEntries(
tabs.map((tab) => [tab.id, state.ptyIdsByTabId[tab.id] ?? []])
),
ptyIdsByLeafIdByTabId: Object.fromEntries(
tabs.map((tab) => [tab.id, state.terminalLayoutsByTabId[tab.id]?.ptyIdsByLeafId ?? {}])
)
}
}, worktreeId)
}
async function mainSnapshotContains(page: Page, ptyId: string, text: string): Promise<boolean> {
return page.evaluate(
async ({ targetPtyId, expectedText }) => {
const snapshot = await window.api.pty.getMainBufferSnapshot(targetPtyId, {
scrollbackRows: 200
})
return snapshot?.data.includes(expectedText) ?? false
},
{ targetPtyId: ptyId, expectedText: text }
)
}
function richSleepWakePayload(runId: string): string {
return [
'\x1b[?2026h',
'\x1b[2J\x1b[H',
'╭────────────────────────────╮',
`│ sleep wake restore ${runId.slice(0, 8)} 😀 │`,
'╰────────────────────────────╯',
`SLEEP_WAKE_RESTORE_${runId}`,
'\x1b[?2026l'
].join('\r\n')
}
function nodeWriteCodePointPayloadCommand(payload: string): string {
const codePoints = [...payload].map((char) => char.codePointAt(0) ?? 0)
return `node -e "process.stdout.write(String.fromCodePoint(...${JSON.stringify(codePoints)}))"`
}
test.describe('Terminal sleep wake restore', () => {
test('restores slept terminal output and accepts fresh input after wake', async ({
orcaPage
}) => {
await waitForSessionReady(orcaPage)
const firstWorktreeId = await waitForActiveWorktree(orcaPage)
const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find(
(id) => id !== firstWorktreeId
)
test.skip(!secondWorktreeId, 'sleep wake restore needs the seeded secondary worktree')
if (!secondWorktreeId) {
return
}
await switchToWorktree(orcaPage, secondWorktreeId)
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
const ptyId = await waitForActivePanePtyId(orcaPage)
const runId = randomUUID()
const restoreMarker = `SLEEP_WAKE_RESTORE_${runId}`
const freshMarker = `SLEEP_WAKE_FRESH_${runId}`
await sendToTerminal(
orcaPage,
ptyId,
`${nodeWriteCodePointPayloadCommand(richSleepWakePayload(runId))}\r`
)
await waitForTerminalOutput(orcaPage, restoreMarker, 10_000, 20_000)
const beforeSleepDebug = await readSleepWakeTerminalDebug(orcaPage, secondWorktreeId)
expect(await mainSnapshotContains(orcaPage, ptyId, restoreMarker)).toBe(true)
await switchToWorktree(orcaPage, firstWorktreeId)
await sleepWorktreeTerminals(orcaPage, secondWorktreeId)
const afterSleepDebug = await readSleepWakeTerminalDebug(orcaPage, secondWorktreeId)
await expect
.poll(() => readLivePtyCountForWorktree(orcaPage, secondWorktreeId), {
timeout: 10_000,
message: 'sleep did not release live PTYs for the background worktree'
})
.toBe(0)
await switchToWorktree(orcaPage, secondWorktreeId)
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
const awakePtyId = await waitForActivePanePtyId(orcaPage)
const afterWakeDebug = await readSleepWakeTerminalDebug(orcaPage, secondWorktreeId)
const awakeTerminalContent = await getTerminalContent(orcaPage, 20_000)
expect
.soft(awakeTerminalContent.includes(restoreMarker), {
message: JSON.stringify(
{
ptyId,
awakePtyId,
beforeSleepDebug,
afterSleepDebug,
afterWakeDebug,
terminalTail: awakeTerminalContent.slice(-2000)
},
null,
2
)
})
.toBe(true)
await waitForTerminalOutput(orcaPage, restoreMarker, 15_000, 20_000)
await sendToTerminal(orcaPage, awakePtyId, `printf '\\n${freshMarker}\\n'\r`)
await waitForTerminalOutput(orcaPage, freshMarker, 10_000, 20_000)
})
})