Repository navigation
fix(terminal): ground the emulator to the snapshot's baseline after a byte gap - #14374
Conversation
6735938 to
6ef77c2
Compare
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughTerminal snapshot replay now uses shared reset profiles and generated buffer-aware prologues. Replay aborts truncated control strings before writing data and restores terminal baseline state across normal and alternate buffers. PTY restoration paths pass the current alternate-screen state and prevent duplicate gap resets. Tests and diagnostic probes cover replay ordering, buffer transitions, terminal modes, cursor state, truncated controls, and parity fixtures. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/shared/terminal-mode-reset-profiles.ts (1)
117-145: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce the changed TypeScript comments.
Keep one short comment for each non-obvious terminal invariant. Remove repeated implementation walkthroughs.
src/shared/terminal-mode-reset-profiles.ts#L117-L145: reduce the prologue rationale to brief invariant comments.src/shared/terminal-mode-reset-profiles.ts#L44-L53: shorten the CAN rationale.src/shared/terminal-mode-reset-profiles.ts#L57-L73: shorten the live byte-gap rationale.src/shared/terminal-mode-reset-profiles.ts#L76-L94: shorten the terminal baseline rationale.src/shared/terminal-mode-reset-profiles.ts#L98-L114: shorten the buffer and saved-cursor rationale.src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts#L8-L12: shorten the first-write abort rationale.src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts#L95-L121: shorten the normal-buffer replay rationale.src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts#L133-L147: shorten the split and alternate replay rationale.src/shared/terminal-restore-parity-fixture.ts#L174-L179: shorten the parity-fixture rationale.As per coding guidelines, TypeScript comments must be concise, non-obvious, and brief—prefer one line.
Source: Coding guidelines
src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.ts (1)
183-216: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFail loudly when the private kitty state path changes.
If
kittyKeyboardis renamed or removed, both reads returnundefined, so the equality assertion still passes. Assert that the read value is defined before comparing both terminals, including the check at lines 244–275.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f5554ec4-b8ea-421a-9b35-06cb786ce705
📥 Commits
Reviewing files that changed from the base of the PR and between 953cfab and 6735938ee446ac785288690dd93fc1d5b4adc9db.
📒 Files selected for processing (8)
src/main/daemon/terminal-snapshot-color-parity.test.tssrc/renderer/src/components/terminal-pane/hidden-reveal-reconciliation.fuzz.test.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.tssrc/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.tssrc/shared/terminal-mode-reset-profiles.tssrc/shared/terminal-restore-parity-fixture.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/shared/terminal-mode-reset-profiles.ts (1)
123-151: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCondense the protocol comments.
Keep comments for non-obvious invariants only. Move detailed parser behavior, xterm implementation notes, and incident history to tests or design documentation.
src/shared/terminal-mode-reset-profiles.ts#L123-L151: Reduce the prologue rationale to the buffer-switch and reset-order invariant.src/shared/terminal-mode-reset-profiles.ts#L44-L53: Reduce the CAN explanation to its required replay-boundary behavior.src/shared/terminal-mode-reset-profiles.ts#L57-L73: Reduce the live-stream reset rationale to the intentional scope difference.src/shared/terminal-mode-reset-profiles.ts#L76-L101: Retain only the required serialized-snapshot baseline assumptions.src/shared/terminal-mode-reset-profiles.ts#L104-L120: Retain only the per-buffer margin and saved-cursor invariants.As per coding guidelines, comments must be concise, non-obvious, and brief—prefer one line.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c95eda30-1af4-40ef-a375-d737396e25aa
📥 Commits
Reviewing files that changed from the base of the PR and between 6735938ee446ac785288690dd93fc1d5b4adc9db and 6ef77c254725bb2d54947ec5b3417b1c28b6edcf.
📒 Files selected for processing (2)
src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.tssrc/shared/terminal-mode-reset-profiles.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts
6ef77c2 to
efea3a5
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/shared/terminal-mode-reset-profiles.ts (1)
43-108: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten the new comments.
Keep the terminal-specific constraint in each comment. Remove the detailed behavior walkthroughs and historical context.
As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ee9e5a22-24e5-44ee-915f-4a14637d2a51
📥 Commits
Reviewing files that changed from the base of the PR and between 6ef77c254725bb2d54947ec5b3417b1c28b6edcf and efea3a5ea0d944e62d87b5dff006e58c9d12c039.
📒 Files selected for processing (5)
src/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.tssrc/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.tssrc/shared/terminal-mode-reset-profiles.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/renderer/src/components/terminal-pane/pty-connection.ts
- src/renderer/src/components/terminal-pane/pty-connection.test.ts
- src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.ts
- src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts
|
Reviewed this properly — I merged the PR it corrects, so I verified everything against a real emulator rather than reading. Both original claims reproduce, the fix works end-to-end, and I found one element I think is actively harmful. Both claims confirmedDriving the real builder with an alt-screen TUI that was bold + line-drawing when it entered alt: Mutation-tested the tests too — they are not vacuous. Blanking One finding:
|
d4b5f82 to
697ecbd
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
_probe_replay_prologue.cjs (1)
306-312: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winExercise CAN while the parser has an open control string.
This section only inspects JavaScript array output. It does not leave
@xterm/headlessin an unterminated OSC or DCS state before the replay write. Add a scenario that writes a truncated control string, applies the CAN-prefixed replay write, and verifies that the control string does not commit or consume replay payload.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3fb47713-2008-4a01-98c2-c56440add977
📥 Commits
Reviewing files that changed from the base of the PR and between 1c11c28 and d4b5f82004cb8428797eb825d902783c403ba3b9.
📒 Files selected for processing (2)
_probe_replay_prologue.cjssrc/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.ts
| const { Terminal } = require('@xterm/headless') | ||
|
|
||
| const RESET_GRAPHIC = '\x1b[0m' | ||
| const BASELINE = `${RESET_GRAPHIC}\x0f\x1b(B\x1b)B\x1b*B\x1b+B\x1b[?6l\x1b[?7h\x1b[?45l\x1b[4l` |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Do not reset G1 through G3 in BASELINE.
ESC ) B, ESC * B, and ESC + B redesignate G1-G3 to ASCII. Applications that retain G1 line drawing and later use SO/SI will render box-drawing characters as letters. Keep SI and ESC ( B for GL/G0 grounding, but remove the G1-G3 designations.
Proposed fix
-const BASELINE = `${RESET_GRAPHIC}\x0f\x1b(B\x1b)B\x1b*B\x1b+B\x1b[?6l\x1b[?7h\x1b[?45l\x1b[4l`
+const BASELINE = `${RESET_GRAPHIC}\x0f\x1b(B\x1b[?6l\x1b[?7h\x1b[?45l\x1b[4l`📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const BASELINE = `${RESET_GRAPHIC}\x0f\x1b(B\x1b)B\x1b*B\x1b+B\x1b[?6l\x1b[?7h\x1b[?45l\x1b[4l` | |
| const BASELINE = `${RESET_GRAPHIC}\x0f\x1b(B\x1b[?6l\x1b[?7h\x1b[?45l\x1b[4l` |
| function abortGapBeforeFirstWrite(writes) { | ||
| return [`${CAN}${writes[0]}`, ...writes.slice(1)] | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- file listing ---'
git ls-files -- '_probe_replay_prologue.cjs'
printf '%s\n' '--- relevant source ---'
cat -n _probe_replay_prologue.cjs | sed -n '1,80p'
printf '%s\n' '--- symbol references ---'
rg -n -C 3 'abortGapBeforeFirstWrite|CAN' -- _probe_replay_prologue.cjsRepository: stablyai/orca
Length of output: 406
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- candidate files ---'
fd -i -t f '_probe_replay_prologue\.cjs$|probe.*replay.*prologue.*\.cjs$' . || true
printf '%s\n' '--- repository references ---'
rg -n --hidden --glob '!*node_modules*' 'abortGapBeforeFirstWrite|_probe_replay_prologue' . || true
printf '%s\n' '--- top-level paths ---'
git ls-files | sed -n '1,120p'Repository: stablyai/orca
Length of output: 5626
🏁 Script executed:
#!/bin/bash
set -eu
file='src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts'
printf '%s\n' '--- outline ---'
ast-grep outline "$file" | sed -n '1,160p'
printf '%s\n' '--- implementation and callers ---'
cat -n "$file" | sed -n '1,175p'
printf '%s\n' '--- standalone empty-input behavior ---'
python3 - <<'PY'
CAN = '\x18'
def abort_gap_before_first_write(writes):
return [f'{CAN}{writes[0]}', *writes[1:]]
result = abort_gap_before_first_write([])
print(repr(result[0]))
print(repr(''.join(result)))
PYRepository: stablyai/orca
Length of output: 8634
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- JavaScript empty-input behavior ---'
node - <<'JS'
const CAN = '\x18'
function abortGapBeforeFirstWrite(writes) {
return [`${CAN}${writes[0]}`, ...writes.slice(1)]
}
const result = abortGapBeforeFirstWrite([])
console.log(JSON.stringify(result))
console.log(JSON.stringify(result[0]))
JS
printf '%s\n' '--- all call sites and argument shapes ---'
rg -n -C 4 'abortGapBeforeFirstWrite\(' src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts
printf '%s\n' '--- direct tests or exports ---'
rg -n --glob '*.{ts,tsx,js,cjs,mjs}' 'buildMainModelSnapshotReplayWrites|abortGapBeforeFirstWrite' src test tests 2>/dev/null || trueRepository: stablyai/orca
Length of output: 6138
Handle empty replay writes in abortGapBeforeFirstWrite at src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts:14. When writes is empty, the helper returns "\x18undefined". Return an array containing only ABORT_TRUNCATED_CONTROL_STRING for this case.
3649113 to
74143a7
Compare
|
You are right, and this is the best catch in the thread — thank you. Why you are right, in my own wordsI reproduced both of your cases: The two are indistinguishable to the emulator, so it is a choice about which to favour — and the decisive fact is the one you identified: the payload never leaves G0, because SerializeAddon emits already-translated Unicode and never SO. So G1-G3 have zero frame-correctness value. All they can change is what a later app-issued SO paints, which is the app's state, not mine. Against zero benefit, breaking Your point about the internal tension is the part I should have caught myself. I wrote the live-path constant with the rule "a live TUI owns its charset — forcing it back would break an app that declares its state once", and then violated exactly that rule in the replay baseline. The docstring now states the actual rule:
I also took your framing that The test that "justified" G1-G3 was asserting the harmful behaviour as if it were correct. It is now inverted into a regression guard: an app-designated G1 must survive the replay and still draw boxes. Also fixed from your review
Mutation matrix after the drop, on the touched suite: CAN 2, SI+G0 10, On the fuzz harnessYour Standing correctionYour other note is right too and I have removed the claim from the PR body: on the alt path the conditional switch buys much less than I said, because the payload itself opens with Nothing to apologise for on the ordering bug; |
74143a7 to
77d3b5b
Compare
… byte gap A hidden-delivery byte gap can strand more than the SGR pen, and the reset #14241 added to the split alt-screen replay is undone before any content is painted: xterm answers `?1049l` with restoreCursor(), which reloads the pen, all four G-set designations, GL, origin mode and wraparound from the register saved at `?1049h`. - Bracket the buffer switch with the baseline: before, so `?1049h` banks grounded state rather than the gap's; after, so `?1049l`'s restore cannot reapply it. - Ground everything a serialized payload is diffed against, not just the pen: SGR, GL, all four G-sets, origin, autowrap, insert, the per-buffer scroll region, and the saved-cursor register. - Switch buffers only when the pane is actually on the other one. `?1049` is not a no-op otherwise — it still swaps the kitty flag registers, which would park the flags of an agent that negotiated them on the normal screen. - Return to the normal buffer when the gap ate the TUI's exit sequence; the restored history was painting into the alt buffer with scrollback left empty. - Restore the CAN #14241 dropped, so a control string the gap truncated is discarded instead of committed by the next ESC. - Ground the abandon path exactly once instead of twice. - Derive the parity/fuzz preambles from the same builder; they had drifted and were asserting against bytes production no longer emits.
77d3b5b to
fc02968
Compare
… byte gap (stablyai#14374) A hidden-delivery byte gap can strand more than the SGR pen, and the reset stablyai#14241 added to the split alt-screen replay is undone before any content is painted: xterm answers `?1049l` with restoreCursor(), which reloads the pen, all four G-set designations, GL, origin mode and wraparound from the register saved at `?1049h`. - Bracket the buffer switch with the baseline: before, so `?1049h` banks grounded state rather than the gap's; after, so `?1049l`'s restore cannot reapply it. - Ground everything a serialized payload is diffed against, not just the pen: SGR, GL, all four G-sets, origin, autowrap, insert, the per-buffer scroll region, and the saved-cursor register. - Switch buffers only when the pane is actually on the other one. `?1049` is not a no-op otherwise — it still swaps the kitty flag registers, which would park the flags of an agent that negotiated them on the normal screen. - Return to the normal buffer when the gap ate the TUI's exit sequence; the restored history was painting into the alt buffer with scrollback left empty. - Restore the CAN stablyai#14241 dropped, so a control string the gap truncated is discarded instead of committed by the next ESC. - Ground the abandon path exactly once instead of twice. - Derive the parity/fuzz preambles from the same builder; they had drifted and were asserting against bytes production no longer emits.
ELI5
When you switch away from a terminal, Orca stops sending it output. If it stops mid-way through styled text, the pane is left holding a "bold pen" it never put down. #14241 taught the recovery paths to put the pen down.
It turns out the pen is not the only thing left in mid-air — the pane can also be left holding the wrong alphabet, the wrong margins, and the wrong screen. And on the path the bug was actually reported on, the pen never got put down at all: the very next byte after the reset picks it straight back up.
Severity: High — silent corruption and content loss, default config, no user mitigation
This follows up #14241 by @brennanb2025 (fix(terminal): clear the SGR pen on hidden-output restore and abandon). That PR correctly identified the layer and the mechanism, and its diagnosis work is what made this findable. Two things did not hold:
1. The reset it added is undone before any content is painted, on the branch the field reports come from.
xterm answers
?1049lwithrestoreCursor(), which reloads the pen, all four G-set designations, GL, origin mode and wraparound from the register saved at?1049h(InputHandler.tsrestoreCursor, and thecase 1049fall-through in the DEC reset handler — note it runs unconditionally for 1049, not only when the buffer actually switches). #14241's split alt-screen branch emits\x1b[0mand then\x1b[?1049l, so a TUI that was bold when it entered the alt screen has its bold handed straight back:That is the reported symptom, on the reported path — an alt-screen agent whose snapshot splits normal scrollback from the alt frame — surviving the fix. Grounding has to bracket the buffer switch: after it, so the restore cannot undo it; and before it, so
?1049hdoes not bank the gap's state for a later?1049lto hand back.2. Scoping to the pen was right for one call site and wrong for the other.
#14241 used one constant for both live-stream recovery and full-frame replay, and argued against widening it because "each changes what a live TUI sees." That is correct for the live paths and I have kept it there. It is backwards for the replay prologue:
SerializeAddondiffs every cell against the default attribute set and emits no charset designation at all — serializing plain text yields the bare text with zero SGR bytes. The payload is only correct on a terminal at default pen,GL=G0,G0=ASCII, origin off, autowrap on, insert off. A replay runs precisely because bytes were dropped, so none of that can be assumed.User-visible effects this fixes
ESC(0charsetqqq lqk→─── ┌─┐) — unreadableESC[?1049h(renderer stuck on alt)ESC[?1049h— keyboard side of the same divergencevtExtensions.kittyKeyboardon, and xterm swaps the kitty flag registers on the?1049transition. Staying on alt keeps the exited agent's negotiated flags, so the pane sends CSI-u key encodings to a plain shell that never asked for them — typing is mis-encodedDECSTBMscroll region[A, E, F, "", "", ""]— most of the frame is goneDECAWMoffABCDEFGHIJKLMNO→ABCDEFGHIJODECOMorigin modeDECRWMreverse wraparound\x18, so a half-read control string is now committed instead of discarded: wrong window/tab title (OSC 0/2), wrong cwd (OSC 7), wrong link target (OSC 8), and truncated clipboard writes (OSC 52)Reachability is ordinary use: hide a pane (switch worktree or tab), let it produce output, reveal it. No user action prevents or works around any of these.
What Changed
src/shared/terminal-mode-reset-profiles.tsRESET_AFTER_BYTE_GAPis now\x18\x1b[0m. The CAN is not decoration: xterm dispatchesOSC_END/DCS_UNHOOK/APC_ENDwithsuccess = code !== 0x18 && code !== 0x1a, so a bare ESC grounds the parser and commits whatever the gap truncated. Only CAN discards it. This restores the\x18that led the warning constant before fix(terminal): clear the SGR pen on hidden-output restore and abandon #14241. Still deliberately parser + pen only — the live paths hand the emulator back to a running TUI that owns its own charset and margins, and it is still not DECSTR (xterm's soft reset wipes the kitty flags and stacks that agents negotiate only at startup).REPLAY_BASELINE_TERMINAL_RESET(\x1b[0m\x0f\x1b(B\x1b[?6l\x1b[?7h\x1b[?45l\x1b[4l) andREPLAY_BASELINE_BUFFER_RESET(\x1b[r), used only by the replay prologue. Split in two because scroll margins are per buffer, so that half has to follow the buffer switch — and?1049honly clears them when it actually switches, which on a pane already in alt screen (the field case) it does not.buildSnapshotReplayPrologue(...), so the renderer and the parity/fuzz harnesses cannot spell the contract differently again.terminal-snapshot-replay-paint.ts— onebuildSnapshotReplayProloguefor all three branches, in a load-bearing order: CAN → baseline → buffer switch → baseline →\x1b[r→ clear → DECSC.?1049hrunssaveCursor(), banking whatever is live into the register the TUI's eventual?1049lrestores from — ground it first, or the gap's state is saved for later and comes back as a bold prompt long after the repaint looked clean.?1049lrunsrestoreCursor(), which would otherwise reapply that register over the grounding.\x1b[ris emitted on both sides because margins are per buffer and the switch does not carry them across: an alt-target replay from a normal pane must ground the buffer it leaves, or the stale region resurfaces the moment the TUI exits.ESC 7cannot be reached through the live TUI's nextESC 8. A snapshot carrying the model's own DECSC epilogue overwrites it, so it only ever acts as a floor.?1049is not a no-op when the pane is already on the target: xterm skips only the buffer swap and still runsrestoreCursor()and swaps the kitty flag registers. Emitting it unconditionally would park the flags of an agent that negotiated kitty on the normal screen — flags 1 → 0, Option chords dead — on every normal-buffer restore. Switching only on a genuine mismatch is exactly the divergence the gap creates, and there the swap is what makes the pane match the model again.restoreCursor()is the riskiest surface, so one test poisons every field it writes at once — pen fg/bg/bold, all four G-sets, GL, origin, wraparound, cursor, insert, margins — lets?1049hbank the lot, and asserts the prologue neutralises all of it. G1–G3 are in the baseline for exactly this reason: the payload never leaves G0 so the frame looks right, but a single SO from the live TUI afterwards selects the stranded designation, and the trailing DECSC would otherwise bank it too. Two further tests assert the renderer lands on byte-identical kitty flag registers and buffer type to a model terminal that ingested the whole stream — in both directions: converge when the pane is stranded on alt, and leave the registers untouched when it is not.pty-connection.ts— the abandon path grounded the gap twice (verified: count = 2). Now anelse if, so it grounds exactly once on each of the three arms: warning, remote re-arm, quiet flood-abandon. All three call sites of the replay builder now pass the pane's real buffer type.terminal-restore-parity-fixture.ts—SNAPSHOT_REPLAY_PREAMBLE_NORMAL/_ALTstill held pre-#14241 literals, so the fuzz and colour-parity harnesses guarding this exact path were asserting against bytes production no longer emitted. They are now derived from the same builder, which is what this module's own header (#12101) asks for.Why not wider
The rule is ground state the model re-asserts.
?6l/?7h/?45l/4lqualify — the model re-emits those only when SET, so grounding plus its re-assertion leaves the renderer matching the model; they are mode-sync rather than frame-correctness (?45lprovably cannot cause a frame failure — xterm wires reverse-wraparound only intobackspace()and the payload contains no BS). G-set designations do not qualify and are deliberately not grounded: the payload never leaves G0, so they cannot affect the frame, and the model never speaks about them. An earlier revision reset G1–G3 and that was actively harmful —enacs=\E(B\E)0(screen/tmux/vt100 terminfo) designates G1 once at init and then uses bare SO/SI, so grounding it renders a live app's box drawing as letters. Caught in review by @brennanb2025.The old wording, kept for the other bits:
?6land4lare in only because the model restores those bits conditionally —buildTerminalFrameRestoreSequencesemits\x1b[4honly when the model has insert mode on — so a stranded-on renderer keeps it and every later TUI repaint shifts cells instead of overwriting. Anything I could not tie to a demonstrable effect is out:CSI ! p) — xterm's soft reset wipes the kitty flags and stacks agents negotiate only at startup. Portability is the stronger reason though: it is unimplemented in several current terminals, and DEC's own definition sets autowrap off while xterm restores it to the resource default, so the explicit?7hhere is better defined than DECSTR would have been.?5l) — xterm.js carries aFIXME: implement DECSCNM; reverse video cannot be stranded in this emulator, so the byte would be dead weight.POST_REPLAY_*profiles written after the payload, and deliberately left alone for live agents.Every byte is mutation-verified below; nothing is in on theory.
Testing
pnpm typecheck,oxlint,oxfmt --checkclean. 12,480 tests pass acrossterminal-pane+shared+main/daemon+main/ipc; 42 interminal-snapshot-replay-paint.test.ts, 584 inpty-connection.test.ts. A full-repo run was green apart from one pre-existing flake in an unrelated virtual-file-list suite, which passes in isolation on this branch and on the base commit and shares no code with this change.A second suite,
terminal-replay-application-continuity.test.ts, covers what a live application sees after its pane is restored — the class of defect adversarial review kept missing. Its line-drawing cases are parameterised over realinfocmpcapability strings forxterm-256color,alacritty,screen-256color,tmux-256color,vt100andlinux, so the two ACS strategies (G0-swapping vsenacs+ bare SO/SI) are both exercised. Re-introducing the G1–G3 reset fails 8 of them and correctly leaves the self-healing xterm/alacritty cases green.Headline coverage is a convergence test built through the same composer production uses (
buildParityMainBufferSnapshot, which mirrorsHeadlessEmulator.getSnapshot: absolute cursor + DECSC epilogue, alt frame split from normal scrollback, rehydrate prefix owning the single?1049h): a renderer dirtied by any of eleven stranded states must land on the byte-identical frame a clean one produces, on both branches. Around it, per-element tests drive a real headless emulator, not a mock, and assert rendered cells:ESC 7followed by the live TUI'sESC 8?1049lrestores saved modes and so grounds some state for free while?1049hgrounds nonerestoreCursor()writes, poisoned simultaneouslybuffer.active.typeand thatbuffer.normalactually received the historyCoverage verified non-vacuous by mutation. Removing each element independently breaks tests, so nothing here is dead weight:
\x18(CAN)\x0f\x1b(B(SI + G0→ASCII)\x1b[?6l(DECOM)\x1b[?7h(DECAWM)\x1b[?45l(DECRWM)\x1b[4l(IRM)\x1b[r(DECSTBM)\x1b7(DECSC)Reverting
buildMainModelSnapshotReplayWritesto #14241's exact shape fails 9, including the behavioural field-path test.Several existing tests pinned the literal replay write arrays and were updated. The SSH reattach replay clear in
pty-transport.tsis deliberately untouched: it replays raw eager-buffered PTY bytes, which carry their own SGR, so the serializer-baseline argument does not apply there.Visual Proof
N/A — the defect is a transient render state, so a static screenshot cannot show it. The before/after is the byte-level A/B above, measured from the emulator's buffer rather than pixels.
Known adjacent gaps, deliberately not in scope
snapshotCarriesNoImageskips the repaint for an empty normal-buffer snapshot. That path now still grounds the gap — with the live-path constant, since nothing repaints over whatever is running — but it deliberately does not clear or switch buffers, so a pane stranded on alt with nothing to replay still does not return to normal. Closing that would trade a stale frame for a blank one, which is what the guard exists to prevent.\x1b[0m\x1b[?1049h(buildRehydrateSequences, andframeRestoreAnsi), so an agent that negotiated kitty on the alt screen still has its flags pushed into the main register by the payload. Fixing that means changing what the daemon emits, not the prologue. An earlier revision of this PR claimed the conditional switch fixed it — that was wrong, and only looked right because the test used synthetic payload data.isPaneOnAlternateScreen()is a best-effort read: xterm parses asynchronously, so a?1049transition still queued reads stale and the switch scopes wrong. Draining first with a write sentinel was implemented and reverted — it puts the repaint behind xterm's queue (a wedged terminal stalls recovery) and breaks the disposal/cancellation ordering the restore paths rely on. A stale read costs one mis-scoped switch; the barrier costs the repaint.\x1b[2J\x1b[3J\x1b[Hbefore their payload. The daemon one replays a serialized snapshot, so on an in-place reattach into a dirty emulator it has the same bleed this PR fixes for the model-snapshot sibling. Left out deliberately: different trigger, and it touches cold-restore/SSH choreography with its own test surface. Worth a follow-up.Linked Issue
Related: STA-4042 / STA-4060. Follow-up to #14241.
Still not marked as fixing them. #14241 could not attribute the field reports to this path, and neither can I; what has changed is that the reported symptom is now shown to survive #14241 on the branch those reports come from, which makes this path a materially better candidate than it was. Treat it as a correctness fix on the recovery paths.
Review
Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)