From 2fb68a6731a2f088ca71c9f6ecc253ad4ef099e2 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sun, 26 Apr 2026 17:32:43 -0400 Subject: [PATCH] fix(daemon): replace per-chunk disk writes with checkpoint-based persistence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The daemon history manager was writing every PTY data chunk to disk via appendFileSync, causing unbounded disk I/O that macOS cached as "App Memory" (reported as 140 GB RAM usage). TUIs emitting CSI 3J on redraws bypassed the 5 MB cap by resetting bytesWritten to 0. Replace the continuous write pipeline with periodic checkpoint-based persistence: serialize HeadlessEmulator state every 5 seconds via a new getSnapshot RPC. This drops disk I/O from O(PTY throughput) to O(1 write/5s/session) and eliminates ~150 lines of CSI 3J detection, partial escape buffering, and byte counting logic. - Add GetSnapshotRequest/Result types and getSnapshot RPC - Rewrite HistoryManager: checkpoint() replaces appendData() - Rewrite HistoryReader: read checkpoint.json, fall back to scrollback.bin - Add checkpoint timer and activeSessionIds tracking in adapter - Write final checkpoints daemon-side in TerminalHost.dispose() - Bump PROTOCOL_VERSION 3→4 for getSnapshot RPC compatibility Co-authored-by: Orca --- src/main/daemon/daemon-pty-adapter.test.ts | 35 +-- src/main/daemon/daemon-pty-adapter.ts | 74 +++-- src/main/daemon/daemon-server.ts | 3 + src/main/daemon/history-manager.test.ts | 306 ++++++++------------- src/main/daemon/history-manager.ts | 201 ++------------ src/main/daemon/history-reader.test.ts | 165 ++++++++--- src/main/daemon/history-reader.ts | 66 ++++- src/main/daemon/terminal-host.ts | 35 +++ src/main/daemon/types.ts | 20 +- 9 files changed, 436 insertions(+), 469 deletions(-) diff --git a/src/main/daemon/daemon-pty-adapter.test.ts b/src/main/daemon/daemon-pty-adapter.test.ts index 8002b869a..610937387 100644 --- a/src/main/daemon/daemon-pty-adapter.test.ts +++ b/src/main/daemon/daemon-pty-adapter.test.ts @@ -434,7 +434,7 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { historyAdapter?.dispose() }) - it('writes scrollback to disk on data events', async () => { + it('does not write to disk on individual data events (checkpoint-based)', async () => { historyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir }) const { id } = await historyAdapter.spawn({ @@ -447,11 +447,11 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { lastSubprocess._simulateData('hello from pty\r\n') await new Promise((r) => setTimeout(r, 50)) - const scrollback = readFileSync( - join(historyDir, getHistorySessionDirName(id), 'scrollback.bin'), - 'utf-8' + // Why: checkpoint-based persistence does not write on every data event. + // No scrollback.bin should exist — checkpoints write checkpoint.json on a timer. + expect(existsSync(join(historyDir, getHistorySessionDirName(id), 'scrollback.bin'))).toBe( + false ) - expect(scrollback).toContain('hello from pty') }) it('writes meta.json with endedAt on exit', async () => { @@ -559,7 +559,7 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { expect(third.coldRestore).toBeUndefined() }) - it('records post-cold-restore data to disk for future restores', async () => { + it('opens session for checkpointing after cold restore', async () => { const sessionId = 'post-restore-data' const sessionDir = join(historyDir, getHistorySessionDirName(sessionId)) mkdirSync(sessionDir, { recursive: true }) @@ -581,24 +581,17 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { const result = await historyAdapter.spawn({ cols: 80, rows: 24, sessionId }) expect(result.coldRestore).toBeDefined() - // Restored scrollback is seeded into the new history file immediately - const seeded = readFileSync( - join(historyDir, getHistorySessionDirName(sessionId), 'scrollback.bin'), - 'utf-8' - ) - expect(seeded).toContain('old output') - - // Simulate new data arriving after cold restore - lastSubprocess._simulateData('new post-restore output\r\n') await new Promise((r) => setTimeout(r, 50)) - // History should now contain both the seeded and new data - const scrollback = readFileSync( - join(historyDir, getHistorySessionDirName(sessionId), 'scrollback.bin'), - 'utf-8' + // Why: checkpoint-based persistence opens the session for future + // checkpointing but does not seed scrollback.bin. New data is persisted + // via periodic checkpoint timer, not per-chunk appendData. + const meta = JSON.parse( + readFileSync(join(historyDir, getHistorySessionDirName(sessionId), 'meta.json'), 'utf-8') ) - expect(scrollback).toContain('old output') - expect(scrollback).toContain('new post-restore output') + expect(meta.cwd).toBe('/tmp') + expect(meta.cols).toBe(80) + expect(meta.rows).toBe(24) }) it('does not cold-restore for clean shutdown (endedAt set)', async () => { diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index 46ce6bf73..89c2e00f8 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -8,7 +8,12 @@ import { DaemonClient } from './client' import { HistoryManager } from './history-manager' import { HistoryReader } from './history-reader' import { supportsPtyStartupBarrier } from './shell-ready' -import type { CreateOrAttachResult, DaemonEvent, ListSessionsResult } from './types' +import type { + CreateOrAttachResult, + DaemonEvent, + GetSnapshotResult, + ListSessionsResult +} from './types' import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from '../providers/types' export type DaemonPtyAdapterOptions = { @@ -56,6 +61,9 @@ 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() + private activeSessionIds = new Set() + private checkpointInterval: ReturnType | null = null + private static CHECKPOINT_INTERVAL_MS = 5_000 constructor(opts: DaemonPtyAdapterOptions) { this.client = new DaemonClient({ @@ -117,23 +125,21 @@ export class DaemonPtyAdapter implements IPtyProvider { return { id: sessionId, coldRestore: cachedRestore } } + this.activeSessionIds.add(sessionId) + // Cold restore: daemon created a new session but disk history shows // an unclean shutdown → return saved scrollback so the renderer can - // display the previous terminal content. Must run BEFORE openSession - // which would overwrite the saved history files. + // display the previous terminal content. if (result.isNew && restoreInfo) { - const coldRestore = { scrollback: restoreInfo.scrollback, cwd: restoreInfo.cwd } + const scrollback = restoreInfo.rehydrateSequences + restoreInfo.snapshotAnsi + const coldRestore = { scrollback, cwd: restoreInfo.cwd } this.coldRestoreCache.set(sessionId, coldRestore) - // Why: seed the reopened history with the recovered metadata, not the - // renderer's transient mount-time size, so a second crash restores the - // same terminal context the daemon just revived. if (this.historyManager) { void this.historyManager .openSession(sessionId, { cwd: restoreInfo.cwd, cols: restoreInfo.cols, - rows: restoreInfo.rows, - initialScrollback: restoreInfo.scrollback + rows: restoreInfo.rows }) .catch((err) => console.warn('[history] openSession failed:', sessionId, err)) } @@ -145,8 +151,7 @@ export class DaemonPtyAdapter implements IPtyProvider { .openSession(sessionId, { cwd: effectiveCwd ?? '', cols: effectiveCols, - rows: effectiveRows, - initialScrollback: result.snapshot?.snapshotAnsi + rows: effectiveRows }) .catch((err) => console.warn('[history] openSession failed:', sessionId, err)) } @@ -188,6 +193,7 @@ export class DaemonPtyAdapter implements IPtyProvider { async shutdown(id: string, _immediate: boolean): Promise { await this.client.request('kill', { sessionId: id }) + this.activeSessionIds.delete(id) this.initialCwds.delete(id) // Why: user explicitly closed this terminal — clean up disk history // so it doesn't trigger a false cold restore on next launch. @@ -357,8 +363,15 @@ export class DaemonPtyAdapter implements IPtyProvider { } dispose(): void { + if (this.checkpointInterval) { + clearInterval(this.checkpointInterval) + this.checkpointInterval = null + } this.removeEventListener?.() this.removeEventListener = null + // Why: final checkpoints are written daemon-side in TerminalHost.dispose() + // which has direct access to sessions. The adapter only marks sessions as + // cleanly ended here so they don't trigger false cold restores. if (this.historyManager) { void this.historyManager .dispose() @@ -372,6 +385,10 @@ export class DaemonPtyAdapter implements IPtyProvider { // restore. disconnectOnly() leaves history files in unclean state so // the next launch detects them as crash-recoverable. disconnectOnly(): void { + if (this.checkpointInterval) { + clearInterval(this.checkpointInterval) + this.checkpointInterval = null + } this.removeEventListener?.() this.removeEventListener = null this.client.disconnect() @@ -380,6 +397,35 @@ export class DaemonPtyAdapter implements IPtyProvider { private async ensureConnected(): Promise { await this.client.ensureConnected() this.setupEventRouting() + this.startCheckpointTimer() + } + + private startCheckpointTimer(): void { + if (this.checkpointInterval || !this.historyManager) { + return + } + this.checkpointInterval = setInterval(() => { + this.checkpointAllSessions() + }, DaemonPtyAdapter.CHECKPOINT_INTERVAL_MS) + } + + // Why: the adapter runs in the Electron main process and does not have direct + // access to daemon Session objects. It calls the getSnapshot RPC over the + // daemon socket per session. + private checkpointAllSessions(): void { + if (!this.historyManager) { + return + } + for (const sessionId of this.activeSessionIds) { + void this.client + .request('getSnapshot', { sessionId }) + .then((result) => { + if (result.snapshot && this.historyManager) { + return this.historyManager.checkpoint(sessionId, result.snapshot) + } + }) + .catch((err) => console.warn('[history] checkpoint failed:', sessionId, err)) + } } // Why: when the daemon process dies, operations fail with ENOENT (socket @@ -425,16 +471,12 @@ export class DaemonPtyAdapter implements IPtyProvider { } if (event.event === 'data') { - if (this.historyManager) { - void this.historyManager - .appendData(event.sessionId, event.payload.data) - .catch((err) => console.warn('[history] appendData failed:', event.sessionId, err)) - } // oxlint-disable-next-line unicorn/no-useless-spread -- copy-safe: listeners may unsubscribe during iteration for (const listener of [...this.dataListeners]) { listener({ id: event.sessionId, data: event.payload.data }) } } else if (event.event === 'exit') { + this.activeSessionIds.delete(event.sessionId) if (this.historyManager) { void this.historyManager .closeSession(event.sessionId, event.payload.code) diff --git a/src/main/daemon/daemon-server.ts b/src/main/daemon/daemon-server.ts index 108f78df2..b845ed232 100644 --- a/src/main/daemon/daemon-server.ts +++ b/src/main/daemon/daemon-server.ts @@ -280,6 +280,9 @@ export class DaemonServer { case 'listSessions': return { sessions: this.host.listSessions() } + case 'getSnapshot': + return { snapshot: this.host.getSnapshot(request.payload.sessionId) } + case 'ping': return { pong: true } diff --git a/src/main/daemon/history-manager.test.ts b/src/main/daemon/history-manager.test.ts index 69cce6146..b9d69588d 100644 --- a/src/main/daemon/history-manager.test.ts +++ b/src/main/daemon/history-manager.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from 'os' import { join } from 'path' import { mkdtempSync, rmSync, readFileSync, existsSync, chmodSync } from 'fs' import { HistoryManager } from './history-manager' +import type { TerminalSnapshot, TerminalModes } from './types' import { getHistorySessionDirName } from './history-paths' function createTestDir(): string { @@ -13,6 +14,27 @@ function sessionPath(baseDir: string, sessionId: string, file: string): string { return join(baseDir, getHistorySessionDirName(sessionId), file) } +const defaultModes: TerminalModes = { + bracketedPaste: false, + mouseTracking: false, + applicationCursor: false, + alternateScreen: false +} + +function makeSnapshot(overrides: Partial = {}): TerminalSnapshot { + return { + snapshotAnsi: 'hello world\r\n', + scrollbackAnsi: '', + rehydrateSequences: '', + cwd: '/tmp', + modes: defaultModes, + cols: 80, + rows: 24, + scrollbackLines: 0, + ...overrides + } +} + describe('HistoryManager', () => { let dir: string let mgr: HistoryManager @@ -43,66 +65,89 @@ describe('HistoryManager', () => { expect(meta.exitCode).toBeNull() }) - it('creates scrollback.bin file', async () => { + it('creates session directory', async () => { await mgr.openSession('sess-1', { cwd: '/tmp', cols: 120, rows: 40 }) - const scrollbackPath = sessionPath(dir, 'sess-1', 'scrollback.bin') - expect(existsSync(scrollbackPath)).toBe(true) - }) - - it('seeds scrollback with initial snapshot', async () => { - await mgr.openSession('sess-1', { - cwd: '/tmp', - cols: 80, - rows: 24, - initialScrollback: 'previous output\r\n' - }) - - const data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).toBe('previous output\r\n') + const sessionDir = join(dir, getHistorySessionDirName('sess-1')) + expect(existsSync(sessionDir)).toBe(true) }) }) - describe('appendData', () => { - it('appends PTY output to scrollback.bin', async () => { + describe('checkpoint', () => { + it('writes checkpoint.json with snapshot data', async () => { await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - await mgr.appendData('sess-1', 'hello ') - await mgr.appendData('sess-1', 'world\r\n') + const snapshot = makeSnapshot({ snapshotAnsi: 'terminal content\r\n' }) + await mgr.checkpoint('sess-1', snapshot) - const data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).toBe('hello world\r\n') + const cpPath = sessionPath(dir, 'sess-1', 'checkpoint.json') + expect(existsSync(cpPath)).toBe(true) + + const data = JSON.parse(readFileSync(cpPath, 'utf-8')) + expect(data.snapshotAnsi).toBe('terminal content\r\n') + expect(data.cols).toBe(80) + expect(data.rows).toBe(24) + expect(data.checkpointedAt).toBeDefined() }) - it('ignores data for unknown sessions', async () => { - // Should not throw - await mgr.appendData('nonexistent', 'data') + it('overwrites previous checkpoint atomically', async () => { + await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) + + await mgr.checkpoint('sess-1', makeSnapshot({ snapshotAnsi: 'first' })) + await mgr.checkpoint('sess-1', makeSnapshot({ snapshotAnsi: 'second' })) + + const data = JSON.parse(readFileSync(sessionPath(dir, 'sess-1', 'checkpoint.json'), 'utf-8')) + expect(data.snapshotAnsi).toBe('second') }) - it('persists the latest cwd from OSC-7 updates', async () => { - await mgr.openSession('sess-1', { cwd: '/tmp/original', cols: 80, rows: 24 }) + it('preserves terminal modes in checkpoint', async () => { + await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - await mgr.appendData('sess-1', '\x1b]7;file:///tmp/updated%20cwd\x07prompt$ ') - - const meta = mgr.readMeta('sess-1') - expect(meta?.cwd).toBe('/tmp/updated cwd') - }) - - it('persists Windows UNC cwd updates from OSC-7', async () => { - const platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'win32' }) - - try { - await mgr.openSession('sess-1', { cwd: 'C:\\start', cols: 80, rows: 24 }) - await mgr.appendData('sess-1', '\x1b]7;file://server/share/project\x07') - } finally { - if (platform) { - Object.defineProperty(process, 'platform', platform) - } + const modes: TerminalModes = { + bracketedPaste: true, + mouseTracking: false, + applicationCursor: true, + alternateScreen: false } + await mgr.checkpoint('sess-1', makeSnapshot({ modes })) - const meta = mgr.readMeta('sess-1') - expect(meta?.cwd).toBe('\\\\server\\share\\project') + const data = JSON.parse(readFileSync(sessionPath(dir, 'sess-1', 'checkpoint.json'), 'utf-8')) + expect(data.modes.bracketedPaste).toBe(true) + expect(data.modes.applicationCursor).toBe(true) + }) + + it('preserves rehydrateSequences in checkpoint', async () => { + await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) + + await mgr.checkpoint('sess-1', makeSnapshot({ rehydrateSequences: '\x1b[?2004h\x1b[?1h' })) + + const data = JSON.parse(readFileSync(sessionPath(dir, 'sess-1', 'checkpoint.json'), 'utf-8')) + expect(data.rehydrateSequences).toBe('\x1b[?2004h\x1b[?1h') + }) + + it('ignores checkpoint for unknown sessions', async () => { + await mgr.checkpoint('nonexistent', makeSnapshot()) + }) + + it('ignores checkpoint for disabled sessions', async () => { + await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) + + const cpPath = sessionPath(dir, 'sess-1', 'checkpoint.json') + chmodSync(join(dir, getHistorySessionDirName('sess-1')), 0o555) + + await mgr.checkpoint('sess-1', makeSnapshot()) + + chmodSync(join(dir, getHistorySessionDirName('sess-1')), 0o755) + + await mgr.checkpoint('sess-1', makeSnapshot({ snapshotAnsi: 'after-error' })) + expect(existsSync(cpPath)).toBe(false) + }) + + it('does not write scrollback.bin', async () => { + await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) + await mgr.checkpoint('sess-1', makeSnapshot()) + + expect(existsSync(sessionPath(dir, 'sess-1', 'scrollback.bin'))).toBe(false) }) }) @@ -116,160 +161,43 @@ describe('HistoryManager', () => { expect(meta.exitCode).toBe(0) }) - it('flushes pending data before closing', async () => { - await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - await mgr.appendData('sess-1', 'final output') - await mgr.closeSession('sess-1', 1) - - const data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).toBe('final output') - }) - - it('flushes buffered partial escape on close', async () => { - await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - // Send data ending with a partial CSI 3J prefix — gets held in buffer - await mgr.appendData('sess-1', 'prompt$ \x1b[') - await mgr.closeSession('sess-1', 0) - - const data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).toBe('prompt$ \x1b[') - }) - it('ignores close for unknown sessions', async () => { - // Should not throw await mgr.closeSession('nonexistent', 0) }) }) - describe('clear-scrollback detection (CSI 3J)', () => { - it('resets scrollback.bin when CSI 3J is detected', async () => { - await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - - await mgr.appendData('sess-1', 'old output\r\n') - // CSI 3J = \x1b[3J (erase scrollback) - await mgr.appendData('sess-1', '\x1b[3J') - await mgr.appendData('sess-1', 'new output\r\n') - - const data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).not.toContain('old output') - expect(data).toContain('new output') - }) - - it('handles multiple CSI 3J in one chunk — resets to content after the last', async () => { - await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - - await mgr.appendData('sess-1', 'old\x1b[3Jmiddle\x1b[3Jfresh\r\n') - - const data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).not.toContain('old') - expect(data).not.toContain('middle') - expect(data).toBe('fresh\r\n') - }) - - it('handles CSI 3J split across chunks', async () => { - await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - - await mgr.appendData('sess-1', 'old stuff\r\n') - await mgr.appendData('sess-1', '\x1b[3') - await mgr.appendData('sess-1', 'J') - await mgr.appendData('sess-1', 'fresh\r\n') - - const data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).not.toContain('old stuff') - expect(data).toContain('fresh') - }) - - it('buffers trailing partial CSI 3J in afterClear content', async () => { - await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - - // CSI 3J followed by content that ends with a partial CSI 3J prefix - await mgr.appendData('sess-1', 'old\x1b[3Jnew-data\x1b[') - // Complete the sequence — should trigger a second reset - await mgr.appendData('sess-1', '3Jfinal') - - const data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).not.toContain('old') - expect(data).not.toContain('new-data') - expect(data).toBe('final') - }) - - it('resets scrollback on CSI 3J even after 5MB cap is hit', async () => { - await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - - const fiveMB = 'x'.repeat(5 * 1024 * 1024) - await mgr.appendData('sess-1', fiveMB) - // Cap is hit — normal writes are blocked - await mgr.appendData('sess-1', 'blocked') - let data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).not.toContain('blocked') - - // CSI 3J should still reset, allowing new writes - await mgr.appendData('sess-1', '\x1b[3Jafter-clear') - data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).toBe('after-clear') - }) - }) - - describe('5MB size cap', () => { - it('stops appending after 5MB', async () => { - await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - - // Write 5MB + some extra - const chunk = 'x'.repeat(1024 * 1024) // 1MB - for (let i = 0; i < 6; i++) { - await mgr.appendData('sess-1', chunk) - } - - const stats = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin')) - expect(stats.length).toBeLessThanOrEqual(5 * 1024 * 1024 + 1024) // some tolerance - }) - }) - describe('multiple sessions', () => { it('manages independent sessions', async () => { await mgr.openSession('a', { cwd: '/a', cols: 80, rows: 24 }) await mgr.openSession('b', { cwd: '/b', cols: 120, rows: 40 }) - await mgr.appendData('a', 'session-a') - await mgr.appendData('b', 'session-b') + await mgr.checkpoint('a', makeSnapshot({ snapshotAnsi: 'session-a' })) + await mgr.checkpoint('b', makeSnapshot({ snapshotAnsi: 'session-b' })) - const dataA = readFileSync(sessionPath(dir, 'a', 'scrollback.bin'), 'utf-8') - const dataB = readFileSync(sessionPath(dir, 'b', 'scrollback.bin'), 'utf-8') + const dataA = JSON.parse(readFileSync(sessionPath(dir, 'a', 'checkpoint.json'), 'utf-8')) + const dataB = JSON.parse(readFileSync(sessionPath(dir, 'b', 'checkpoint.json'), 'utf-8')) - expect(dataA).toBe('session-a') - expect(dataB).toBe('session-b') + expect(dataA.snapshotAnsi).toBe('session-a') + expect(dataB.snapshotAnsi).toBe('session-b') }) }) describe('dispose', () => { it('writes endedAt for open sessions to prevent false cold-restore', async () => { await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - await mgr.appendData('sess-1', 'data') + await mgr.checkpoint('sess-1', makeSnapshot()) await mgr.dispose() - const data = readFileSync(sessionPath(dir, 'sess-1', 'scrollback.bin'), 'utf-8') - expect(data).toBe('data') - const meta = JSON.parse(readFileSync(sessionPath(dir, 'sess-1', 'meta.json'), 'utf-8')) expect(meta.endedAt).not.toBeNull() expect(meta.exitCode).toBeNull() }) - - it('flushes buffered partial escape sequences', async () => { - await mgr.openSession('partial', { cwd: '/tmp', cols: 80, rows: 24 }) - // Send data ending with a partial CSI 3J prefix - await mgr.appendData('partial', 'hello\x1b') - await mgr.dispose() - - const data = readFileSync(sessionPath(dir, 'partial', 'scrollback.bin'), 'utf-8') - expect(data).toBe('hello\x1b') - }) }) describe('removeSession', () => { it('deletes session directory from disk', async () => { await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) - await mgr.appendData('sess-1', 'data') + await mgr.checkpoint('sess-1', makeSnapshot()) await mgr.closeSession('sess-1', 0) await mgr.removeSession('sess-1') @@ -306,48 +234,37 @@ describe('HistoryManager', () => { }) }) - describe('disk-full handling', () => { + describe('error handling', () => { it('disables writes after fs error and does not throw', async () => { await mgr.openSession('disk-full', { cwd: '/tmp', cols: 80, rows: 24 }) - await mgr.appendData('disk-full', 'before-error') - // Make scrollback file read-only to trigger write error - const scrollbackPath = sessionPath(dir, 'disk-full', 'scrollback.bin') - chmodSync(scrollbackPath, 0o444) + const sessionDir = join(dir, getHistorySessionDirName('disk-full')) + chmodSync(sessionDir, 0o555) - // Should not throw — error is caught and session is disabled - await mgr.appendData('disk-full', 'failing-write') + await mgr.checkpoint('disk-full', makeSnapshot()) - // Restore permissions so we can read and clean up - chmodSync(scrollbackPath, 0o644) + chmodSync(sessionDir, 0o755) - // Subsequent writes were skipped because session was disabled - const content = readFileSync(scrollbackPath, 'utf-8') - expect(content).toBe('before-error') + await mgr.checkpoint('disk-full', makeSnapshot({ snapshotAnsi: 'after-error' })) + expect(existsSync(sessionPath(dir, 'disk-full', 'checkpoint.json'))).toBe(false) }) it('disables writes after fs error on openSession', async () => { - // Make base dir read-only so mkdirSync fails chmodSync(dir, 0o555) - // Should not throw await mgr.openSession('disk-full-open', { cwd: '/tmp', cols: 80, rows: 24 }) - // Restore permissions for cleanup chmodSync(dir, 0o755) - // Session writer was never registered, so appendData is a no-op - await mgr.appendData('disk-full-open', 'data-after-failed-open') + await mgr.checkpoint('disk-full-open', makeSnapshot()) }) - it('does not throw on closeSession disk error (prevents false cold-restore)', async () => { + it('does not throw on closeSession disk error', async () => { await mgr.openSession('close-err', { cwd: '/tmp', cols: 80, rows: 24 }) - // Make meta.json read-only so updateMeta's writeFileSync fails const metaPath = sessionPath(dir, 'close-err', 'meta.json') chmodSync(metaPath, 0o444) - // Should not throw await mgr.closeSession('close-err', 0) chmodSync(metaPath, 0o644) @@ -360,14 +277,13 @@ describe('HistoryManager', () => { }) await mgr.openSession('err-cb', { cwd: '/tmp', cols: 80, rows: 24 }) - await mgr.appendData('err-cb', 'before') - const scrollbackPath = sessionPath(dir, 'err-cb', 'scrollback.bin') - chmodSync(scrollbackPath, 0o444) + const sessionDir = join(dir, getHistorySessionDirName('err-cb')) + chmodSync(sessionDir, 0o555) - await mgr.appendData('err-cb', 'trigger-error') + await mgr.checkpoint('err-cb', makeSnapshot()) - chmodSync(scrollbackPath, 0o644) + chmodSync(sessionDir, 0o755) expect(errors).toHaveLength(1) expect(errors[0].sessionId).toBe('err-cb') diff --git a/src/main/daemon/history-manager.ts b/src/main/daemon/history-manager.ts index 4426e1194..d1c44fb1c 100644 --- a/src/main/daemon/history-manager.ts +++ b/src/main/daemon/history-manager.ts @@ -1,6 +1,7 @@ import { join } from 'path' -import { mkdirSync, writeFileSync, appendFileSync, readFileSync, existsSync, rmSync } from 'fs' +import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, renameSync } from 'fs' import { getHistorySessionDirName } from './history-paths' +import type { TerminalSnapshot } from './types' export type SessionMeta = { cwd: string @@ -15,47 +16,11 @@ export type OpenSessionOptions = { cwd: string cols: number rows: number - initialScrollback?: string -} - -const MAX_SCROLLBACK_BYTES = 5 * 1024 * 1024 - -function parseFileUriPath(uri: string): string | null { - try { - const url = new URL(uri) - if (url.protocol !== 'file:') { - return null - } - - const decodedPath = decodeURIComponent(url.pathname) - if (process.platform !== 'win32') { - return decodedPath - } - - // Why: daemon-side cwd persistence must preserve the full Windows target - // path from OSC-7, including UNC hosts, or cold restore can reopen in a - // different directory than the live shell had reached before the crash. - if (url.hostname) { - return `\\\\${url.hostname}${decodedPath.replace(/\//g, '\\')}` - } - if (/^\/[A-Za-z]:/.test(decodedPath)) { - return decodedPath.slice(1) - } - return decodedPath.replace(/\//g, '\\') - } catch { - return null - } } type SessionWriter = { dir: string - scrollbackPath: string - bytesWritten: number - cwd: string - // Why: CSI 3J (erase scrollback) can arrive split across data chunks. - // Buffer the trailing bytes that look like a partial CSI 3J prefix - // so the next chunk can complete the match. - partialEscape: string + checkpointPath: string } export type HistoryManagerOptions = { @@ -89,29 +54,19 @@ export class HistoryManager { } writeFileSync(join(dir, 'meta.json'), JSON.stringify(meta, null, 2)) - const scrollbackPath = join(dir, 'scrollback.bin') - let bytesWritten = 0 - - if (opts.initialScrollback) { - writeFileSync(scrollbackPath, opts.initialScrollback) - bytesWritten = Buffer.byteLength(opts.initialScrollback) - } else { - writeFileSync(scrollbackPath, '') - } - this.writers.set(sessionId, { dir, - scrollbackPath, - bytesWritten, - cwd: opts.cwd, - partialEscape: '' + checkpointPath: join(dir, 'checkpoint.json') }) } catch (err) { this.handleWriteError(sessionId, err) } } - async appendData(sessionId: string, data: string): Promise { + // Why: replaces the old appendData (which wrote every PTY chunk to disk). + // Checkpoints happen every ~5 seconds from a timer, not on every data event, + // so disk I/O drops from O(PTY throughput) to O(1 write per interval). + async checkpoint(sessionId: string, snapshot: TerminalSnapshot): Promise { if (this.disabledSessions.has(sessionId)) { return } @@ -121,57 +76,22 @@ export class HistoryManager { } try { - const combined = writer.partialEscape + data - writer.partialEscape = '' - const nextCwd = this.extractLatestCwd(combined) - if (nextCwd && nextCwd !== writer.cwd) { - writer.cwd = nextCwd - this.updateMeta(writer.dir, { cwd: nextCwd }) - } - - // Why: use lastIndexOf so that multiple CSI 3J sequences in one chunk - // reset to the content after the *last* clear, not the first. - const clearIdx = combined.lastIndexOf('\x1b[3J') - if (clearIdx !== -1) { - const afterClear = combined.slice(clearIdx + 4) - // Why: CSI 3J resets the byte counter — a clear after the 5MB cap - // must still take effect, otherwise the on-disk history is stale. - this.resetScrollback(writer) - // Why: afterClear may itself end with a partial CSI 3J prefix - // (e.g., the chunk was `...\x1b[3Jdata\x1b[`). Buffer it the - // same way the main path does, otherwise the next chunk's - // completion of the sequence won't be detected as a clear. - const partial = this.trailingPartialCsi3J(afterClear) - if (partial) { - writer.partialEscape = partial - const safe = afterClear.slice(0, afterClear.length - partial.length) - if (safe.length > 0) { - this.writeChunk(writer, safe) - } - } else if (afterClear.length > 0) { - this.writeChunk(writer, afterClear) - } - return - } - - // Why: CSI 3J detection (above) must run even when the cap is hit, - // because a clear resets the byte counter. All other writes are - // blocked once the cap is reached. - if (writer.bytesWritten >= MAX_SCROLLBACK_BYTES) { - return - } - - const partial = this.trailingPartialCsi3J(combined) - if (partial) { - writer.partialEscape = partial - const safe = combined.slice(0, combined.length - partial.length) - if (safe.length > 0) { - this.writeChunk(writer, safe) - } - return - } - - this.writeChunk(writer, combined) + const data = JSON.stringify({ + snapshotAnsi: snapshot.snapshotAnsi, + rehydrateSequences: snapshot.rehydrateSequences, + cwd: snapshot.cwd, + cols: snapshot.cols, + rows: snapshot.rows, + modes: snapshot.modes, + scrollbackLines: snapshot.scrollbackLines, + checkpointedAt: new Date().toISOString() + }) + // Why: atomic write via tmp+rename prevents half-written checkpoints + // on crash. Reading a corrupt checkpoint is worse than reading a + // slightly stale one. + const tmpPath = `${writer.checkpointPath}.tmp` + writeFileSync(tmpPath, data) + renameSync(tmpPath, writer.checkpointPath) } catch (err) { this.handleWriteError(sessionId, err) } @@ -184,17 +104,6 @@ export class HistoryManager { } this.writers.delete(sessionId) - // Why: partialEscape may hold buffered bytes from a chunk boundary that - // looked like a CSI 3J prefix. Flush them before closing so they aren't - // silently dropped. (dispose() does the same flush.) - if (writer.partialEscape) { - try { - this.writeChunk(writer, writer.partialEscape) - } catch { - // Best-effort flush — don't block session close - } - writer.partialEscape = '' - } try { this.updateMeta(writer.dir, { endedAt: new Date().toISOString(), exitCode }) } catch (err) { @@ -232,76 +141,17 @@ export class HistoryManager { async dispose(): Promise { // Why: mark all open sessions as cleanly ended so they don't trigger - // false cold-restores on next launch. Flush any buffered partial escape - // data before closing. + // false cold-restores on next launch. for (const [sessionId, writer] of this.writers) { - if (writer.partialEscape) { - try { - this.writeChunk(writer, writer.partialEscape) - } catch { - // Best-effort flush — don't block shutdown - } - writer.partialEscape = '' - } try { this.updateMeta(writer.dir, { endedAt: new Date().toISOString(), exitCode: null }) } catch { - // Best-effort — don't block shutdown this.disabledSessions.add(sessionId) } } this.writers.clear() } - private writeChunk(writer: SessionWriter, data: string): void { - const buf = Buffer.from(data) - const remaining = MAX_SCROLLBACK_BYTES - writer.bytesWritten - if (remaining <= 0) { - return - } - - if (buf.length > remaining) { - appendFileSync(writer.scrollbackPath, buf.subarray(0, remaining)) - writer.bytesWritten = MAX_SCROLLBACK_BYTES - } else { - appendFileSync(writer.scrollbackPath, buf) - writer.bytesWritten += buf.length - } - } - - private resetScrollback(writer: SessionWriter): void { - writeFileSync(writer.scrollbackPath, '') - writer.bytesWritten = 0 - } - - // Why: CSI 3J is 4 bytes (\x1b [ 3 J). If the chunk ends with a prefix - // of this sequence, we must buffer it and check the next chunk. - private trailingPartialCsi3J(data: string): string | null { - const suffixes = ['\x1b[3', '\x1b[', '\x1b'] - for (const suffix of suffixes) { - if (data.endsWith(suffix)) { - return suffix - } - } - return null - } - - private extractLatestCwd(data: string): string | null { - // OSC-7 format: ESC ] 7 ; BEL or ESC ] 7 ; ST - // oxlint-disable-next-line no-control-regex -- terminal escape sequences require control chars - const osc7Re = /\x1b\]7;([^\x07\x1b]*?)(?:\x07|\x1b\\)/g - let match: RegExpExecArray | null - let latest: string | null = null - while ((match = osc7Re.exec(data)) !== null) { - latest = this.parseOsc7Uri(match[1]) - } - return latest - } - - private parseOsc7Uri(uri: string): string | null { - return parseFileUriPath(uri) - } - // Why: history is best-effort — any error should disable the session // rather than crash the app. Callers use fire-and-forget `void` promises, // so a re-thrown error would become an unhandled rejection. @@ -316,7 +166,6 @@ export class HistoryManager { try { meta = JSON.parse(readFileSync(metaPath, 'utf-8')) } catch { - // meta.json missing or corrupt — nothing to update return } Object.assign(meta, updates) diff --git a/src/main/daemon/history-reader.test.ts b/src/main/daemon/history-reader.test.ts index a4e37d0e3..a306358cf 100644 --- a/src/main/daemon/history-reader.test.ts +++ b/src/main/daemon/history-reader.test.ts @@ -10,7 +10,7 @@ function createTestDir(): string { return mkdtempSync(join(tmpdir(), 'history-reader-test-')) } -function writeSessionFiles( +function writeSessionWithScrollback( basePath: string, sessionId: string, meta: SessionMeta, @@ -22,6 +22,18 @@ function writeSessionFiles( writeFileSync(join(dir, 'scrollback.bin'), scrollback) } +function writeSessionWithCheckpoint( + basePath: string, + sessionId: string, + meta: SessionMeta, + checkpoint: Record +): void { + const dir = join(basePath, getHistorySessionDirName(sessionId)) + mkdirSync(dir, { recursive: true }) + writeFileSync(join(dir, 'meta.json'), JSON.stringify(meta)) + writeFileSync(join(dir, 'checkpoint.json'), JSON.stringify(checkpoint)) +} + function makeMeta(overrides: Partial = {}): SessionMeta { return { cwd: '/home/user/project', @@ -34,6 +46,25 @@ function makeMeta(overrides: Partial = {}): SessionMeta { } } +function makeCheckpoint(overrides: Record = {}): Record { + return { + snapshotAnsi: 'hello world\r\n$ ls\r\n', + rehydrateSequences: '', + cwd: '/home/user/project', + cols: 80, + rows: 24, + modes: { + bracketedPaste: false, + mouseTracking: false, + applicationCursor: false, + alternateScreen: false + }, + scrollbackLines: 0, + checkpointedAt: '2026-04-15T11:00:00Z', + ...overrides + } +} + describe('HistoryReader', () => { let dir: string let reader: HistoryReader @@ -47,24 +78,51 @@ describe('HistoryReader', () => { rmSync(dir, { recursive: true, force: true }) }) - describe('detectColdRestore', () => { - it('returns restore info for unclean shutdown (endedAt is null)', () => { - writeSessionFiles(dir, 'sess-1', makeMeta(), 'hello world\r\n$ ls\r\n') + describe('detectColdRestore — checkpoint.json', () => { + it('returns restore info from checkpoint.json for unclean shutdown', () => { + writeSessionWithCheckpoint(dir, 'sess-1', makeMeta(), makeCheckpoint()) const info = reader.detectColdRestore('sess-1') expect(info).not.toBeNull() expect(info!.cwd).toBe('/home/user/project') expect(info!.cols).toBe(80) expect(info!.rows).toBe(24) - expect(info!.scrollback).toContain('hello world') + expect(info!.snapshotAnsi).toContain('hello world') + expect(info!.rehydrateSequences).toBe('') + }) + + it('restores terminal modes from checkpoint', () => { + const modes = { + bracketedPaste: true, + mouseTracking: false, + applicationCursor: true, + alternateScreen: false + } + writeSessionWithCheckpoint(dir, 'sess-1', makeMeta(), makeCheckpoint({ modes })) + + const info = reader.detectColdRestore('sess-1') + expect(info!.modes.bracketedPaste).toBe(true) + expect(info!.modes.applicationCursor).toBe(true) + }) + + it('restores rehydrateSequences from checkpoint', () => { + writeSessionWithCheckpoint( + dir, + 'sess-1', + makeMeta(), + makeCheckpoint({ rehydrateSequences: '\x1b[?2004h' }) + ) + + const info = reader.detectColdRestore('sess-1') + expect(info!.rehydrateSequences).toBe('\x1b[?2004h') }) it('returns null for clean shutdown (endedAt is set)', () => { - writeSessionFiles( + writeSessionWithCheckpoint( dir, 'sess-1', makeMeta({ endedAt: '2026-04-15T12:00:00Z', exitCode: 0 }), - 'old output' + makeCheckpoint() ) expect(reader.detectColdRestore('sess-1')).toBeNull() @@ -78,54 +136,73 @@ describe('HistoryReader', () => { const sessionDir = join(dir, getHistorySessionDirName('corrupt')) mkdirSync(sessionDir, { recursive: true }) writeFileSync(join(sessionDir, 'meta.json'), 'not json') - writeFileSync(join(sessionDir, 'scrollback.bin'), 'data') + writeFileSync(join(sessionDir, 'checkpoint.json'), JSON.stringify(makeCheckpoint())) expect(reader.detectColdRestore('corrupt')).toBeNull() }) - it('returns empty scrollback when scrollback.bin is missing', () => { - const sessionDir = join(dir, getHistorySessionDirName('no-scrollback')) + it('falls back to scrollback.bin when checkpoint.json is corrupt', () => { + const sessionDir = join(dir, getHistorySessionDirName('bad-cp')) mkdirSync(sessionDir, { recursive: true }) writeFileSync(join(sessionDir, 'meta.json'), JSON.stringify(makeMeta())) + writeFileSync(join(sessionDir, 'checkpoint.json'), 'not json') + writeFileSync(join(sessionDir, 'scrollback.bin'), 'fallback data\r\n') - const info = reader.detectColdRestore('no-scrollback') + const info = reader.detectColdRestore('bad-cp') expect(info).not.toBeNull() - expect(info!.scrollback).toBe('') + expect(info!.snapshotAnsi).toBe('fallback data\r\n') + expect(info!.rehydrateSequences).toBe('') }) }) - describe('TUI truncation', () => { - it('truncates before last unmatched alternate-screen-on', () => { - const scrollback = [ - 'normal output\r\n', - '\x1b[?1049h', // alt screen on (vim started) - 'vim content here' - // No matching \x1b[?1049l — vim was running when daemon died - ].join('') + describe('detectColdRestore — scrollback.bin fallback (backward compatibility)', () => { + it('restores from scrollback.bin when checkpoint.json is absent', () => { + writeSessionWithScrollback(dir, 'old-sess', makeMeta(), 'old format data\r\n') - writeSessionFiles(dir, 'tui-sess', makeMeta(), scrollback) + const info = reader.detectColdRestore('old-sess') + expect(info).not.toBeNull() + expect(info!.snapshotAnsi).toContain('old format data') + expect(info!.rehydrateSequences).toBe('') + expect(info!.modes.bracketedPaste).toBe(false) + expect(info!.modes.alternateScreen).toBe(false) + }) + + it('returns null when neither checkpoint.json nor scrollback.bin exist', () => { + const sessionDir = join(dir, getHistorySessionDirName('no-data')) + mkdirSync(sessionDir, { recursive: true }) + writeFileSync(join(sessionDir, 'meta.json'), JSON.stringify(makeMeta())) + + expect(reader.detectColdRestore('no-data')).toBeNull() + }) + + it('truncates alt-screen from scrollback.bin fallback', () => { + const scrollback = ['normal output\r\n', '\x1b[?1049h', 'vim content here'].join('') + + writeSessionWithScrollback(dir, 'tui-sess', makeMeta(), scrollback) const info = reader.detectColdRestore('tui-sess') expect(info).not.toBeNull() - expect(info!.scrollback).toContain('normal output') - expect(info!.scrollback).not.toContain('vim content') + expect(info!.snapshotAnsi).toContain('normal output') + expect(info!.snapshotAnsi).not.toContain('vim content') }) + }) + describe('TUI truncation (scrollback.bin fallback path)', () => { it('preserves content when alt-screen is properly closed', () => { const scrollback = [ 'before vim\r\n', - '\x1b[?1049h', // alt screen on + '\x1b[?1049h', 'vim stuff', - '\x1b[?1049l', // alt screen off + '\x1b[?1049l', 'after vim\r\n' ].join('') - writeSessionFiles(dir, 'closed-tui', makeMeta(), scrollback) + writeSessionWithScrollback(dir, 'closed-tui', makeMeta(), scrollback) const info = reader.detectColdRestore('closed-tui') expect(info).not.toBeNull() - expect(info!.scrollback).toContain('before vim') - expect(info!.scrollback).toContain('after vim') + expect(info!.snapshotAnsi).toContain('before vim') + expect(info!.snapshotAnsi).toContain('after vim') }) it('handles multiple alt-screen cycles with last one unclosed', () => { @@ -137,49 +214,47 @@ describe('HistoryReader', () => { 'line2\r\n', '\x1b[?1049h', 'vim2-still-running' - // No close — daemon crashed while vim2 was open ].join('') - writeSessionFiles(dir, 'multi-tui', makeMeta(), scrollback) + writeSessionWithScrollback(dir, 'multi-tui', makeMeta(), scrollback) const info = reader.detectColdRestore('multi-tui') expect(info).not.toBeNull() - expect(info!.scrollback).toContain('line1') - expect(info!.scrollback).toContain('line2') - expect(info!.scrollback).not.toContain('vim2-still-running') + expect(info!.snapshotAnsi).toContain('line1') + expect(info!.snapshotAnsi).toContain('line2') + expect(info!.snapshotAnsi).not.toContain('vim2-still-running') }) it('truncates at outermost unmatched alt-screen-on for nested sessions', () => { const scrollback = [ 'normal output\r\n', - '\x1b[?1049h', // outer alt screen (e.g., tmux) + '\x1b[?1049h', 'tmux content', - '\x1b[?1049h', // inner alt screen (e.g., vim inside tmux) + '\x1b[?1049h', 'vim inside tmux' - // Neither closed — daemon crashed ].join('') - writeSessionFiles(dir, 'nested-tui', makeMeta(), scrollback) + writeSessionWithScrollback(dir, 'nested-tui', makeMeta(), scrollback) const info = reader.detectColdRestore('nested-tui') expect(info).not.toBeNull() - expect(info!.scrollback).toContain('normal output') - expect(info!.scrollback).not.toContain('tmux content') - expect(info!.scrollback).not.toContain('vim inside tmux') + expect(info!.snapshotAnsi).toContain('normal output') + expect(info!.snapshotAnsi).not.toContain('tmux content') + expect(info!.snapshotAnsi).not.toContain('vim inside tmux') }) it('returns full content when no alt-screen sequences', () => { - writeSessionFiles(dir, 'plain', makeMeta(), 'just normal shell output\r\n') + writeSessionWithScrollback(dir, 'plain', makeMeta(), 'just normal shell output\r\n') const info = reader.detectColdRestore('plain') - expect(info!.scrollback).toBe('just normal shell output\r\n') + expect(info!.snapshotAnsi).toBe('just normal shell output\r\n') }) }) describe('listRestorable', () => { it('lists sessions with unclean shutdown', () => { - writeSessionFiles(dir, 'alive', makeMeta(), 'data') - writeSessionFiles(dir, 'dead', makeMeta({ endedAt: '2026-04-15T12:00:00Z' }), 'data') + writeSessionWithScrollback(dir, 'alive', makeMeta(), 'data') + writeSessionWithScrollback(dir, 'dead', makeMeta({ endedAt: '2026-04-15T12:00:00Z' }), 'data') const restorable = reader.listRestorable() expect(restorable).toEqual(['alive']) @@ -191,7 +266,7 @@ describe('HistoryReader', () => { it('returns decoded session ids for encoded on-disk directories', () => { const sessionId = 'repo-1::C:/Users/dev/feature' - writeSessionFiles(dir, sessionId, makeMeta(), 'data') + writeSessionWithScrollback(dir, sessionId, makeMeta(), 'data') expect(reader.listRestorable()).toEqual([sessionId]) }) diff --git a/src/main/daemon/history-reader.ts b/src/main/daemon/history-reader.ts index c98d5fad8..475cda6b2 100644 --- a/src/main/daemon/history-reader.ts +++ b/src/main/daemon/history-reader.ts @@ -1,13 +1,16 @@ import { join } from 'path' import { readFileSync, existsSync, readdirSync } from 'fs' import type { SessionMeta } from './history-manager' +import type { TerminalModes } from './types' import { getHistorySessionDirName } from './history-paths' export type ColdRestoreInfo = { - scrollback: string + snapshotAnsi: string + rehydrateSequences: string cwd: string cols: number rows: number + modes: TerminalModes } const ALT_SCREEN_ON = '\x1b[?1049h' @@ -29,12 +32,32 @@ export class HistoryReader { return null } - const scrollback = this.readScrollback(sessionId) - return { - scrollback: this.truncateAltScreen(scrollback), - cwd: meta.cwd, - cols: meta.cols, - rows: meta.rows + const checkpointPath = join( + this.basePath, + getHistorySessionDirName(sessionId), + 'checkpoint.json' + ) + if (!existsSync(checkpointPath)) { + // Why: backward compatibility with pre-checkpoint sessions. If the user + // upgrades and then the daemon crashes before a checkpoint is written, + // the old scrollback.bin is still the best recovery data available. + return this.detectColdRestoreFromScrollback(sessionId, meta) + } + + try { + const checkpoint = JSON.parse(readFileSync(checkpointPath, 'utf-8')) + return { + snapshotAnsi: checkpoint.snapshotAnsi, + rehydrateSequences: checkpoint.rehydrateSequences, + cwd: checkpoint.cwd, + cols: checkpoint.cols, + rows: checkpoint.rows, + modes: checkpoint.modes + } + } catch { + // Why: corrupt checkpoint — fall back to scrollback.bin rather than + // discarding recoverable data entirely. + return this.detectColdRestoreFromScrollback(sessionId, meta) } } @@ -77,19 +100,37 @@ export class HistoryReader { } } - private readScrollback(sessionId: string): string { + // Why: handles the upgrade transition where sessions created before the + // checkpoint migration still have scrollback.bin but no checkpoint.json. + private detectColdRestoreFromScrollback( + sessionId: string, + meta: SessionMeta + ): ColdRestoreInfo | null { const scrollbackPath = join( this.basePath, getHistorySessionDirName(sessionId), 'scrollback.bin' ) if (!existsSync(scrollbackPath)) { - return '' + return null } try { - return readFileSync(scrollbackPath, 'utf-8') + const scrollback = readFileSync(scrollbackPath, 'utf-8') + return { + snapshotAnsi: this.truncateAltScreen(scrollback), + rehydrateSequences: '', + cwd: meta.cwd, + cols: meta.cols, + rows: meta.rows, + modes: { + bracketedPaste: false, + mouseTracking: false, + applicationCursor: false, + alternateScreen: false + } + } } catch { - return '' + return null } } @@ -111,9 +152,6 @@ export class HistoryReader { } if (onIdx !== -1 && (offIdx === -1 || onIdx < offIdx)) { - // Why: track where depth first goes above 0 — that's the outermost - // unmatched ON. Nested ONs (depth > 1) are inside the same alt-screen - // block, so we truncate at the outermost boundary. if (depth === 0) { outermostUnmatchedOnIdx = onIdx } diff --git a/src/main/daemon/terminal-host.ts b/src/main/daemon/terminal-host.ts index e1aad9fc3..a15e26f42 100644 --- a/src/main/daemon/terminal-host.ts +++ b/src/main/daemon/terminal-host.ts @@ -33,15 +33,21 @@ export type TerminalHostOptions = { env?: Record command?: string }) => SubprocessHandle + // Why: on graceful shutdown, the host writes final checkpoints for all live + // sessions before killing them. This bypasses the RPC round-trip — the daemon + // writes checkpoints in-process, guaranteeing completion before teardown. + onFinalCheckpoint?: (sessionId: string, snapshot: TerminalSnapshot) => void } export class TerminalHost { private sessions = new Map() private killedTombstones = new Map() private spawnSubprocess: TerminalHostOptions['spawnSubprocess'] + private onFinalCheckpoint: TerminalHostOptions['onFinalCheckpoint'] constructor(opts: TerminalHostOptions) { this.spawnSubprocess = opts.spawnSubprocess + this.onFinalCheckpoint = opts.onFinalCheckpoint } async createOrAttach(opts: CreateOrAttachOptions): Promise { @@ -150,6 +156,17 @@ export class TerminalHost { this.getAliveSession(sessionId).clearScrollback() } + // Why: unlike getAliveSession (which throws), this returns null for dead/missing + // sessions. Checkpoint is best-effort — a session that exited between the timer + // firing and the RPC arriving should not throw. + getSnapshot(sessionId: string): TerminalSnapshot | null { + const session = this.sessions.get(sessionId) + if (!session || !session.isAlive) { + return null + } + return session.getSnapshot() + } + isKilled(sessionId: string): boolean { return this.killedTombstones.has(sessionId) } @@ -177,6 +194,24 @@ export class TerminalHost { } dispose(): void { + // Why: write final checkpoints before killing sessions so graceful shutdown + // has zero data loss. The checkpoint callback writes synchronously to disk. + if (this.onFinalCheckpoint) { + for (const [sessionId, session] of this.sessions) { + if (!session.isAlive) { + continue + } + const snapshot = session.getSnapshot() + if (snapshot) { + try { + this.onFinalCheckpoint(sessionId, snapshot) + } catch { + // Best-effort — don't block shutdown + } + } + } + } + for (const [, session] of this.sessions) { session.detachAllClients() session.kill() diff --git a/src/main/daemon/types.ts b/src/main/daemon/types.ts index 2c896e89c..90ca6019d 100644 --- a/src/main/daemon/types.ts +++ b/src/main/daemon/types.ts @@ -1,8 +1,11 @@ // ─── Protocol Version ──────────────────────────────────────────────── // Why: daemons can survive app updates with long-lived shell env. Bump when // spawn-time env semantics change so stale sessions cannot bypass new behavior. -export const PROTOCOL_VERSION = 3 -export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [1, 2] as const +// Why: bumped from 3 → 4 for the getSnapshot RPC. A surviving v3 daemon +// would reject getSnapshot as unknown, silently failing all checkpoint +// writes. The bump forces a stale daemon to be replaced on reconnect. +export const PROTOCOL_VERSION = 4 +export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [1, 2, 3] as const // ─── Session State Machine ────────────────────────────────────────── export type SessionState = 'created' | 'spawning' | 'running' | 'exiting' | 'exited' @@ -149,6 +152,14 @@ export type PingRequest = { type: 'ping' } +export type GetSnapshotRequest = { + id: string + type: 'getSnapshot' + payload: { + sessionId: string + } +} + export type DaemonRequest = | CreateOrAttachRequest | CancelCreateOrAttachRequest @@ -162,6 +173,7 @@ export type DaemonRequest = | ClearScrollbackRequest | ShutdownRequest | PingRequest + | GetSnapshotRequest // ─── RPC Responses (Daemon → Client, on control socket) ──────────── @@ -186,6 +198,10 @@ export type CreateOrAttachResult = { shellState: ShellReadyState } +export type GetSnapshotResult = { + snapshot: TerminalSnapshot | null +} + export type ListSessionsResult = { sessions: SessionInfo[] }