fix(daemon): clean stale scrollback.bin on reuse, derive alt-screen scrollback from snapshot

Two fixes from ninth code review cycle:

1. openSession() now deletes both checkpoint.json AND scrollback.bin
   when reusing a session ID. Without cleaning scrollback.bin, a crash
   before the first checkpoint tick would false-restore via the reader's
   scrollback.bin fallback path.

2. HistoryReader now derives scrollbackAnsi for alt-screen checkpoints
   by applying truncateAltScreen to snapshotAnsi when scrollbackAnsi is
   empty (HeadlessEmulator doesn't populate it). This restores the
   normal shell output that existed before the TUI launched, matching
   the behavior of the old scrollback.bin truncation path.

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo-H
2026-04-26 22:23:11 -04:00
co-authored by Orca
parent c46160064b
commit 01c6067598
2 changed files with 24 additions and 8 deletions
+12 -7
View File
@@ -62,15 +62,20 @@ export class HistoryManager {
}
writeFileSync(join(dir, 'meta.json'), JSON.stringify(meta, null, 2))
// Why: if a session ID is reused after a previous clean exit, the old
// checkpoint.json may still be on disk. Without removing it, a crash
// Why: if a session ID is reused after a previous clean exit, stale
// recovery files may still be on disk. Without removing them, a crash
// before the first 5s checkpoint tick would cause detectColdRestore to
// replay stale terminal content from the previous session.
// replay stale terminal content from the previous session. Both
// checkpoint.json and scrollback.bin (legacy) must be cleaned up
// because the reader falls back to scrollback.bin when no checkpoint
// exists.
const checkpointPath = join(dir, 'checkpoint.json')
try {
unlinkSync(checkpointPath)
} catch {
// ENOENT is expected for new sessions
for (const staleFile of [checkpointPath, join(dir, 'scrollback.bin')]) {
try {
unlinkSync(staleFile)
} catch {
// ENOENT is expected for new sessions
}
}
this.writers.set(sessionId, {
+12 -1
View File
@@ -47,9 +47,20 @@ export class HistoryReader {
try {
const checkpoint = JSON.parse(readFileSync(checkpointPath, 'utf-8'))
// Why: HeadlessEmulator.getSnapshot() doesn't populate scrollbackAnsi
// (it's always ''). For alt-screen checkpoints, derive usable scrollback
// by truncating snapshotAnsi at the alt-screen boundary — same logic the
// scrollback.bin fallback uses. This ensures alt-screen cold restores
// recover normal shell output that existed before the TUI launched.
const rawScrollback = checkpoint.scrollbackAnsi ?? ''
const scrollbackAnsi =
rawScrollback ||
(checkpoint.modes?.alternateScreen
? this.truncateAltScreen(checkpoint.snapshotAnsi ?? '')
: (checkpoint.snapshotAnsi ?? ''))
return {
snapshotAnsi: checkpoint.snapshotAnsi,
scrollbackAnsi: checkpoint.scrollbackAnsi ?? '',
scrollbackAnsi,
rehydrateSequences: checkpoint.rehydrateSequences,
cwd: checkpoint.cwd,
cols: checkpoint.cols,