Skip to content

fix(daemon): rebase durable checkpoints on the live terminal - #22732

Merged
Jinwoo-H merged 3 commits into
mainfrom
scroll-freeze
Sep 25, 2026
Merged

Jinwoo-H merged 3 commits into
mainfrom
scroll-freeze

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​733 $\color{#cf222e}{\Huge{\mathbf{−}}}$​50 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​683
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​212 $\color{#cf222e}{\Huge{\mathbf{−}}}$​180 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​32

ELI5

Orca keeps two copies of every terminal: a live one in memory and a saved one on disk that holds deeper history. The saved copy was built from its own previous version, so a mistake in it stayed forever. After a restart it could still say "the mouse belongs to the program" for a program that had been killed. When you came back to the pane, Orca believed the saved copy, and your scroll wheel went to a program that ignored it, so scrolling froze. Now every save takes the screen and settings from the live copy, and only older history from disk.

What Changed

Before: a Claude Code pane could stop scrolling with the mouse wheel (typing still worked) after the terminal daemon restarted, and restarting Orca didn't help. Reproduced on a live session: the daemon's live emulator showed alt screen off and no mouse tracking, while the durable checkpoint showed alt screen on and ?1003h ?1006h.

Mechanism: each durable checkpoint was replay(previous checkpoint) + recorded output. After a daemon restart killed a full-screen TUI and a new process started inline, the new process never sent "mode off" sequences, so the checkpoint kept the dead TUI's alt screen and mouse modes on every compaction. Reattach and getBufferSnapshot served that checkpoint, and the renderer re-armed mouse tracking.

After: each full checkpoint is the daemon's live snapshot verbatim (screen, layout, alt frame, modes, owner). The only thing added from the durable replay is the normal-buffer rows the live window has already evicted. Consequences:

  • A checkpoint can no longer carry a dead process's modes, and checkpoints already poisoned on users' disks heal on the next compaction. That unfreezes panes that are stuck today.
  • The first fold after a cold restore replays the same seed bytes live was given, so rows line up even over a dead TUI's alt screen (this fixes a case that lost rows).
  • Idle folds with no new output keep the disk copy when it already agrees with live, so a quit or relaunch doesn't replay every session.
  • Held teardown bytes, which are already in the drained records, are no longer replayed twice or appended as a log tail.
  • The fold's ownership scanner and frame-merge code are deleted; owner and frame come from live.
  • A request for less history trims the saved checkpoint instead of rebuilding from disk, and trimming now keeps the kitty keyboard flags.
  • Saved link positions are no longer re-applied during a save: once older rows scrolled off they pointed at the wrong text. Links are carried by the OSC 8 escapes in the saved text instead.

Why

Other approaches we considered:

  • Override modes at reattach time, taking live's modes over the checkpoint's. This adds another read-time rule, and the disk copy stays wrong for crash recovery, mobile and the main-process mirror.
  • Record the cold-restore seed into the log. This duplicates history and can overflow the 2 MB pending-output cap.

Making live the authority for everything it holds, and letting disk add only rows live evicted, is the pattern other terminal hosts use (Superset, herdr, iTerm2). It removes a class of divergence rather than one symptom. It's the first of three planned changes; the next two unify the "process is gone" reset (which also fixes stale focus and keypad modes after a cold restore) and broaden the daemon's crash detector.

Linked Issue

Related: #13077, the same stale-checkpoint path, where the recipient is a shell that prints the mouse reports as garbage. This PR removes the stale checkpoint modes; the in-stream crash detector for normal-buffer programs is a follow-up, so this doesn't close #13077.

Visual Proof

N/A: this is a daemon persistence change and has not been demoed in the running app. The behavior is covered by adapter-level tests that go through getBufferSnapshot, the on-disk checkpoint and a relaunch reattach.

Testing

  • New tests fail on main and pass here: a poisoned checkpoint (alt screen plus ?1003h?1006h) over a clean live snapshot heals in one compaction for the fold, getBufferSnapshot, the on-disk checkpoint and a relaunch reattach; a zero-record boundary fold serves live modes; the live alt frame, modes and owner are kept verbatim.

  • Also covered: cold restores from an 80x24 checkpoint into 80x40 and 100x30 panes and over an alt-screen base (consecutive rows, nothing duplicated or lost); held bytes appear once; depth stays at the restore limit; OSC link row offsets; the seam after a reflow; the bounded-depth path (trimming the saved checkpoint keeps the same rows as the old rebuild); kitty flags survive a trim; a link stays on its text across two saves that evict rows; agreeing idle folds don't replay; xterm headless _core.writeSync exists (guards the synchronous-parse assumption).

  • src/main/daemon: everything passes except two repro-13767 tests. They time out on this machine because local sqlite3 3.54 prints a different prompt; they don't touch the changed code.

  • pnpm tc:node, oxlint, and check:code-quality:changed are clean.

  • Platform: tests run on macOS only. The change is in main-process history code with no platform branches.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Two independent review passes. The first found a lost-rows case, an idle-fold slowdown, and double-applied held bytes; all three are fixed. The second pass found one remaining low issue (phantom link rows on the bounded path), also fixed.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • SSH: the relay has no host emulator and is unchanged.
  • Remote wire: no new fields or opcodes. Snapshot content changes only by dropping stale modes; cross-version-terminal-wire passes.
  • Daemon version skew: all of this runs in app main, so it ships with the app.
  • Folder workspaces and WSL: same daemon history path.
  • Known remaining gap, for the next PR: after a cold restore the seed still inherits the dead process's focus, bracketed-paste and keypad modes, because today's seed reset only clears pen and mouse. The next PR unifies and widens that reset.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

A durable checkpoint was folded from the previous checkpoint plus recorded
output, so it inherited that checkpoint's modes forever. After a daemon
restart killed a full-screen TUI and a new process started inline, the chain
kept the dead TUI's alt screen and mouse tracking (?1049h ?1003h ?1006h)
while the live emulator was clean. Every reattach and getBufferSnapshot
served the stale chain, the renderer re-armed mouse tracking, and wheel
scrolling went to a program that never asked for it: scrolling froze.

Each full checkpoint is now the live snapshot verbatim (screen, layout,
alt frame, modes, owner) with only the normal-buffer rows live has evicted
taken from the durable replay. A checkpoint can no longer carry a dead
process's modes, and checkpoints already poisoned on disk heal on the next
compaction.

- The first fold after a cold restore replays the same seed segments live
  was given, so rows line up even over a dead TUI's alt screen.
- Idle zero-record folds keep the disk copy when it already agrees with
  live, so quit and relaunch bursts don't replay every session.
- Held teardown bytes are already in the drained records and the live
  snapshot, so they are no longer replayed twice or appended as a tail.
- The bounded getBufferSnapshot path honors the requested depth even when
  the live window is deeper, without phantom link rows.
- The fold's ownership scanner and frame merge are removed; owner and
  frame come from live.
@coderabbitai

coderabbitai Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

Durable checkpoint construction now rebases older history onto live terminal snapshots and bounds snapshots to a requested scrollback depth. Snapshot replay supports scrollback limits, preserves Kitty keyboard flags, and handles OSC-link ranges. Checkpoint persistence reconstructs history from drained records and uses first-take state. Added tests cover replay, restore, rebasing, remount, and teardown behavior.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to eb75c

A checkpoint can restore stale terminal content instead of the live screen. Check screen agreement before reusing the disk checkpoint; this should be fixed before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to eb75c

The checkpoint change is contained to terminal sessions and does not increase the accepted scrollback limit. The main recovery paths preserve the live screen, but not every interrupted or stale-checkpoint case has direct verification.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The evidenced checkpoint effect is scoped by session ID to that session's persisted terminal display and reattach; the changed scrollback ceiling does not increase the configured capacity.

Security Findings and Attack Paths

  • observed — A metadata-compatible stale normal-screen checkpoint can still supply displayed cells on a zero-record take. The target-branch baseline also reused disk screen content without checking live cells, so the evidence does not establish this as an introduced or worsened exposure.

Trust Boundaries and Controls

  • observed — Recorded terminal output and disk restore data feed checkpoint reconstruction. On the replay path, disk contributes older rows while the live snapshot retains current-screen and identity authority; failed replay returns live state.

Resilience and Maintainability Implications

  • observed — Missing drained-record evidence, overflow, and a requested force-live checkpoint avoid reconstructing from potentially incomplete records; retryable commits retain a route to a later full checkpoint.

Hardening Proposals

  • proposed — Before reusing a zero-record normal-screen disk snapshot, establish equivalence with the live screen and add a regression case with differing disk and live cells. This addresses an inherited gap, not a verified new PR finding.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 14 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main change: rebasing durable daemon checkpoints on the live terminal.
Description check ✅ Passed The description is detailed and mostly complete. It explains the user impact, mechanism, rationale, linked issue, testing coverage, platform scope, known limitations, and checklist status. Minor gaps …
Linked Issues check ✅ Passed Issue #13077 reports mouse movement producing terminal characters. The PR makes the live terminal snapshot authoritative during durable checkpoint rebasing. Replay contributes only evicted normal-buff…
Out of Scope Changes check ✅ Passed The changes stay within durable checkpoint rebasing and restore correctness for issue #13077. Snapshot reconstruction, row bounding, OSC-link handling, Kitty keyboard flags, teardown records, and emul…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: c07b19e9-3dd4-4ed4-849e-da7bc8da6dac

📥 Commits

Reviewing files that changed from the base of the PR and between 29480cd and 432da23.

📒 Files selected for processing (12)
  • src/main/daemon/daemon-durable-checkpoint-live-rebase.test.ts
  • src/main/daemon/daemon-durable-history-ownership-seed.test.ts
  • src/main/daemon/daemon-durable-history-snapshot.ts
  • src/main/daemon/daemon-pty-adapter-live-rebased-checkpoint.test.ts
  • src/main/daemon/daemon-pty-buffer-snapshots.ts
  • src/main/daemon/daemon-pty-checkpoint-persistence.ts
  • src/main/daemon/daemon-pty-runtime-state.ts
  • src/main/daemon/daemon-restore-scrollback-depth.test.ts
  • src/main/daemon/durable-history-replay-emulator.ts
  • src/main/daemon/headless-emulator.ts
  • src/main/daemon/headless-osc-link-ranges.ts
  • src/main/daemon/terminal-checkpoint-serializer.ts
💤 Files with no reviewable changes (1)
  • src/main/daemon/daemon-durable-history-ownership-seed.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one minor suggestion inline.

Reviewed changes

  • Live-first durable checkpoint — buildDurableCheckpointSnapshot now derives the screen, modes, alt frame, owner, cwd/title and outputSequence from the live daemon snapshot; a durable replay only prepends the normal-buffer rows the live window evicted (rebaseOnOlderRows, DurableHistoryReplayEmulator.serializeNormalBufferHead).
  • Ownership/frame scanners deleted — the replayed-output TerminalShellLifecycleScanner ownership pass and frame merge are gone; owner comes from live, whose recovery barrier already revokes it when a TUI starts.
  • Idle-fold fast path — diskCheckpointAgreesWithLive/diskCheckpointWithLiveIdentity reuse the disk copy with live's identity when grid, all mode keys, rehydrateSequences and the alt frame already match, avoiding a full replay.
  • Persistence uses drained records only — a teardown take's held bytes are already in drainedRecords, so take.records is no longer replayed/appended; SnapshotCheckpointResult gains liveSnapshot for bounded remounts and compactDurableRestoreSnapshot rebases on it instead of the deep durable copy.
  • Bounded-read handling — boundLiveSnapshot trims the live snapshot directly when live is deeper than the requested depth; replayTerminalSnapshot's trimmed path skips seeded OSC ranges and relies on re-emitted OSC 8.
  • Tests — new daemon-durable-checkpoint-live-rebase.test.ts and daemon-pty-adapter-live-rebased-checkpoint.test.ts, plus reworked depth/ownership cases; the deleted ownership-seed test is replaced by coverage that takes ownership from live.

Verification: the full src/main/daemon vitest directory passes (187 files / 2087 tests), along with pnpm run typecheck:node, oxlint, and check:code-quality:changed.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…t folds and trims

Stop seeding persisted OSC link ranges into the fold replay: they index the
base buffer, so rows evicted by pending output left a link on the wrong text.
The serializer already writes OSC 8 into the ANSI the fold replays.

Re-apply kitty keyboard flags when replaying a snapshot for trimming, since
rehydrateSequences omits them.

Bound a smaller restore request by trimming the committed checkpoint instead
of re-reading disk and rebasing the live window at a smaller depth.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Since the prior pullfrog review at 432da239, one commit (916a9b2) landed:

  • OSC links survive folds and trims — the fold replay no longer seeds persisted restoreInfo.oscLinks; links are reconstructed from the OSC 8 the serializer re-emits, and collectNormalBufferOscLinkRanges drops its restoredLinks parameter.
  • Kitty keyboard flags carried through replay — replayTerminalSnapshot re-applies modes.kittyKeyboardFlags (which rehydrateSequences omits) before snapshotting, so boundSnapshot and the oversized-checkpoint trim keep the negotiated flags.
  • Bounded reads trim the committed checkpoint — compactDurableRestoreSnapshot bounds the durable snapshot with boundSnapshot instead of re-reading disk and rebasing live at a smaller depth; SnapshotCheckpointResult.liveSnapshot is removed.
  • Mode-agreement check narrowed — diskCheckpointAgreesWithLive now compares only kittyKeyboardFlags plus rehydrateSequences (which encodes the other seven modes), replacing the explicit TERMINAL_MODE_KEYS sweep.

The prior kitty-flags thread is resolved, and both CodeRabbit threads were addressed in this commit. I re-ran daemon-durable-checkpoint-live-rebase.test.ts, terminal-checkpoint-serializer.test.ts and terminal-snapshot-osc8-roundtrip.test.ts (24 tests) at 916a9b2 — all pass. I also verified the OSC 8 re-emission assumption directly against the patched @xterm/addon-serialize: it emits OSC 8 for every cell carrying a urlId, spaces included, and erased cells never retain a urlId, so dropping the seeded ranges loses no hyperlink.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…ble fold

The live window's override cap now derives from the restore depth, so live can
never be deeper than the fold. pendingRecords and isFirstTake are required.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Since the prior pullfrog review at 916a9b2, one commit (eb75ca4) landed:

  • Dropped the unreachable deep-live branch — buildDurableCheckpointSnapshot no longer early-returns a boundSnapshot(liveSnapshot, DAEMON_RESTORE_SCROLLBACK_ROWS) when liveSnapshot.scrollbackLines exceeds the restore depth. Verified unreachable: the live session's emulator scrollback is resolveDaemonSessionScrollbackRows() (capped at MAX_OVERRIDE_ROWS), getSnapshot().scrollbackLines = buffer.normal.length - rows <= scrollback, and MAX_OVERRIDE_ROWS is now exactly DAEMON_RESTORE_SCROLLBACK_ROWS, so live can never be deeper than the fold.
  • Tied the live-window override cap to the restore depth — MAX_OVERRIDE_ROWS = DAEMON_RESTORE_SCROLLBACK_ROWS replaces the literal 5000 (same runtime value, now an explicit coupling with a new import in daemon-session-scrollback-window.ts; no module cycle).
  • Made checkpoint inputs required — pendingRecords and isFirstTake are now required on buildDurableCheckpointSnapshot, removing the silent []/undefined defaults; every caller and test was updated accordingly.

Verification at eb75ca4: daemon-durable-checkpoint-live-rebase.test.ts (13), daemon-restore-scrollback-depth.test.ts (23) and daemon-session-scrollback-window.test.ts (3) all pass (39 total); pnpm tc:node clean. The prior kitty-flags thread remains resolved and the refactor introduces no behavioral change.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 Major · Check the live normal-buffer screen before reusing the… · daemon-durable-history-snapshot.ts:90

src/main/daemon/daemon-durable-history-snapshot.ts:90
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Check the live normal-buffer screen before reusing the disk checkpoint.

If a zero-record fold has different disk and live screen cells but matching dimensions and modes, this check accepts the disk checkpoint. diskCheckpointWithLiveIdentity then persists the disk snapshotAnsi instead of the live screen. The early return also bypasses the new first-take seed replay. Compare the visible screen before reuse, while allowing the disk checkpoint to retain older scrollback. Add a zero-record regression case with different normal-buffer screens.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: e846c747-656b-4d0c-a37c-178183950aaf

📥 Commits

Reviewing files that changed from the base of the PR and between 916a9b2 and eb75ca4.

📒 Files selected for processing (4)
  • src/main/daemon/daemon-durable-checkpoint-live-rebase.test.ts
  • src/main/daemon/daemon-durable-history-snapshot.ts
  • src/main/daemon/daemon-restore-scrollback-depth.test.ts
  • src/main/daemon/daemon-session-scrollback-window.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@Jinwoo-H
Jinwoo-H merged commit 1c1b782 into main Sep 25, 2026
35 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Orca terminals start spawning random characters

1 participant