Skip to content

fix(terminal): ground the emulator to the snapshot's baseline after a byte gap - #14374

Merged
nwparker merged 1 commit into
mainfrom
nwparker/terminal-byte-gap-replay-baseline
Aug 14, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/terminal-byte-gap-replay-baseline

Conversation

@nwparker

@nwparker nwparker commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

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 ?1049l with restoreCursor(), which reloads the pen, all four G-set designations, GL, origin mode and wraparound from the register saved at ?1049h (InputHandler.ts restoreCursor, and the case 1049 fall-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[0m and then \x1b[?1049l, so a TUI that was bold when it entered the alt screen has its bold handed straight back:

prologue                                    replayed "qqq scrollback" renders as
PR #14241  \x1b[0m\x1b[?1049l\x1b[2J\x1b[3J\x1b[H   "─── ⎽␌⎼⎺┌┌␉▒␌┐"   bold=YES
this PR                                            "qqq scrollback"   bold=no

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 ?1049h does not bank the gap's state for a later ?1049l to 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: SerializeAddon diffs 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

Stranded by the gap What the user sees Severity
Pen, on the split alt-screen path Regular text renders bold — the original STA-4042 symptom, unfixed by #14241 High
ESC(0 charset The entire restored pane renders as line-drawing glyphs (qqq lqk → ─── ┌─┐) — unreadable High
ESC[?1049h (renderer stuck on alt) Restored history paints into the alt buffer. Looks correct, but normal-buffer scrollback is empty and the content vanishes on the next buffer switch High — scrollback loss
ESC[?1049h — keyboard side of the same divergence Panes run with vtExtensions.kittyKeyboard on, and xterm swaps the kitty flag registers on the ?1049 transition. 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-encoded High — broken input
DECSTBM scroll region Restored frame scrolls inside a stale 2-row window; 6 replayed rows land as [A, E, F, "", "", ""] — most of the frame is gone High
DECAWM off Every character past the right margin overwrites the last cell; ABCDEFGHIJKLMNO → ABCDEFGHIJO High
DECOM origin mode Restored content offset by the stale margin; later TUI cursor addressing stays margin-relative Medium
DECRWM reverse wraparound The live app's next backspace at column 0 chews into the row above the restored frame Medium
Truncated OSC #14241 removed a pre-existing \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) Medium

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.ts

  • RESET_AFTER_BYTE_GAP is now \x18\x1b[0m. The CAN is not decoration: xterm dispatches OSC_END/DCS_UNHOOK/APC_END with success = code !== 0x18 && code !== 0x1a, so a bare ESC grounds the parser and commits whatever the gap truncated. Only CAN discards it. This restores the \x18 that 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).
  • New REPLAY_BASELINE_TERMINAL_RESET (\x1b[0m\x0f\x1b(B\x1b[?6l\x1b[?7h\x1b[?45l\x1b[4l) and REPLAY_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 ?1049h only 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 — one buildSnapshotReplayPrologue for all three branches, in a load-bearing order: CAN → baseline → buffer switch → baseline → \x1b[r → clear → DECSC.

  • CAN must lead. An ESC would commit the truncated control string it exists to discard. It leads the first write only; later writes follow well-formed snapshot payloads.
  • The baseline brackets the switch, and neither copy is redundant. ?1049h runs saveCursor(), banking whatever is live into the register the TUI's eventual ?1049l restores 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. ?1049l runs restoreCursor(), which would otherwise reapply that register over the grounding.
  • \x1b[r is 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.
  • The trailing DECSC grounds the saved-cursor register, so a stranded ESC 7 cannot be reached through the live TUI's next ESC 8. A snapshot carrying the model's own DECSC epilogue overwrites it, so it only ever acts as a floor.
  • The buffer switch is conditional. ?1049 is not a no-op when the pane is already on the target: xterm skips only the buffer swap and still runs restoreCursor() 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 ?1049h bank 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 an else 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/_ALT still 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/4l qualify — 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 (?45l provably cannot cause a frame failure — xterm wires reverse-wraparound only into backspace() 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: ?6l and 4l are in only because the model restores those bits conditionally — buildTerminalFrameRestoreSequences emits \x1b[4h only 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:

  • DECSTR (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 ?7h here is better defined than DECSTR would have been.
  • DECSCNM (?5l) — xterm.js carries a FIXME: implement DECSCNM; reverse video cannot be stranded in this emulator, so the byte would be dead weight.
  • Mouse modes, bracketed paste, cursor visibility — already owned by the 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 --check clean. 12,480 tests pass across terminal-pane + shared + main/daemon + main/ipc; 42 in terminal-snapshot-replay-paint.test.ts, 584 in pty-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 real infocmp capability strings for xterm-256color, alacritty, screen-256color, tmux-256color, vt100 and linux, so the two ACS strategies (G0-swapping vs enacs + 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 mirrors HeadlessEmulator.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:

  • the field path end to end, through the actual builder output, for a split alt-screen snapshot whose TUI entered alt with a pen set
  • the delayed arm: the agent exits the alt screen long after the repaint, and the prompt must still not be bold
  • a post-replay SO must not paint line drawing (the G1–G3 case)
  • a stranded ESC 7 followed by the live TUI's ESC 8
  • kitty flags preserved when the pane is already on the target buffer
  • one case per stranded state (pen, charset, margins, origin, autowrap, insert), on both the normal and alt branches — they need separate coverage, because ?1049l restores saved modes and so grounds some state for free while ?1049h grounds none
  • every field restoreCursor() writes, poisoned simultaneously
  • kitty flag + buffer-type convergence against a model terminal that saw the whole stream
  • the truncated-OSC case, asserting the title is not set
  • the alt/normal buffer divergence, asserting buffer.active.type and that buffer.normal actually received the history
  • the ordering itself: grounding before the switch must fail

Coverage verified non-vacuous by mutation. Removing each element independently breaks tests, so nothing here is dead weight:

removed tests failing
\x18 (CAN) 2
\x0f\x1b(B (SI + G0→ASCII) 10
\x1b[?6l (DECOM) 1
\x1b[?7h (DECAWM) 3
\x1b[?45l (DECRWM) 1
\x1b[4l (IRM) 1
\x1b[r (DECSTBM) 6
\x1b7 (DECSC) 2
grounding placed only before the buffer switch 8

Reverting buildMainModelSnapshotReplayWrites to #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.ts is 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

  • snapshotCarriesNoImage skips 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.
  • The alt branch cannot promise kitty preservation. The prologue no longer contributes a switch, but production alt payloads carry their own \x1b[0m\x1b[?1049h (buildRehydrateSequences, and frameRestoreAnsi), 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 ?1049 transition 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.
  • The daemon-snapshot and raw-relay reattach paints still bare-clear with \x1b[2J\x1b[3J\x1b[H before 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.
  • The live-stream constant is a mitigation, not a restoration: a gap could equally have swallowed a mode set, half a DECSTBM, or an OSC 4 palette write. The honest recovery on that path is a repaint, which is what the snapshot path does; the pen reset is what is safe to do when no snapshot is coming.

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.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Review

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

  • Cross-platform / SSH / mobile: renderer-side and protocol-level — bytes written into the local xterm, identical on every platform and transport. No mobile surface imports these profiles.
  • Remote wire: nothing crosses the wire. No RPC params, stream opcodes, or published host content change; the snapshot shape is untouched. Old clients and old hosts are unaffected.
  • Backwards compatibility: the added bytes prefix writes that already cleared the screen in the same chunk. A live TUI re-arms its own state on its next write; a shell inherits a defined baseline instead of an undefined one.
  • Performance: ~20 bytes per recovery event, still not emitted per-marker under flood.
  • Security: the CAN restores discarding of truncated control strings, which removes a path where a half-read OSC 52 could write the clipboard.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)

@nwparker
nwparker force-pushed the nwparker/terminal-byte-gap-replay-baseline branch from 6735938 to 6ef77c2 Compare August 13, 2026 22:48
@coderabbitai

coderabbitai Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Terminal 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The description identifies STA-4042, STA-4060, and follow-up #14241, satisfying the requirement to reference a linked issue.
Out of Scope Changes check ✅ Passed All summarized changes support snapshot replay recovery, reset-profile centralization, parity coverage, or targeted diagnostics.
Title check ✅ Passed The title clearly and concisely describes the main terminal snapshot replay recovery change.
Description check ✅ Passed The description substantially follows the template and clearly documents the change, rationale, testing, visual proof, review considerations, and checklist.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

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.

🧹 Nitpick comments (2)
src/shared/terminal-mode-reset-profiles.ts (1)

117-145: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce 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 win

Fail loudly when the private kitty state path changes.

If kittyKeyboard is renamed or removed, both reads return undefined, 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.ts
  • src/renderer/src/components/terminal-pane/hidden-reveal-reconciliation.fuzz.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.ts
  • src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts
  • src/shared/terminal-mode-reset-profiles.ts
  • src/shared/terminal-restore-parity-fixture.ts

@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.

🧹 Nitpick comments (1)
src/shared/terminal-mode-reset-profiles.ts (1)

123-151: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense 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.ts
  • src/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

@nwparker
nwparker force-pushed the nwparker/terminal-byte-gap-replay-baseline branch from 6ef77c2 to efea3a5 Compare August 13, 2026 22:54

@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: 1

🧹 Nitpick comments (1)
src/shared/terminal-mode-reset-profiles.ts (1)

43-108: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten 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.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.ts
  • src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts
  • src/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

@brennanb2025

Copy link
Copy Markdown
Contributor

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 confirmed

"ESC[0m then ESC[?1049l"   -> replayed scrollback bold=YES
 reset AFTER ?1049l        -> bold=no

ESC[0m only    -> window title = "TRUNCATED-TITLE-FROM-A-GAP"   (committed)
CAN + ESC[0m   -> window title = "(unset)"                      (aborted)

Driving the real builder with an alt-screen TUI that was bold + line-drawing when it entered alt: paneOnAlternateScreen true and false both come back clean; the ordering I shipped comes back bold. So the hole was real, on the reported path, and this closes it.

Mutation-tested the tests too — they are not vacuous. Blanking ABORT_TRUNCATED_CONTROL_STRING fails 1; removing the post-switch reset fails 5, including grounds after the buffer switch, not before, so ?1049l cannot restore the stale pen. SAVE_GROUNDED_CURSOR is a sharp catch and I confirmed the back-door it closes: without the trailing ESC 7, the app's next ESC 8 resurrects the stranded pen.

One finding: \x1b)B\x1b*B\x1b+B is unjustified and I believe harmful

No frame failure is constructible without them. \x0f sets GL=G0 and \x1b(B makes G0 ASCII, which together cover every stranded-GL case — including stranded SO, LS2 and LS3. Ablating G1-G3 from the baseline leaves the restored frame correct in every case I could build.

There is a failing-with case. screen-256color, tmux-256color and vt100 use enacs=\E(B\E)0 — designate G1 = line-drawing once at init — then bare SO/SI for smacs/rmacs. Nothing re-runs enacs, not even a SIGWINCH repaint:

app pre-gap:  ESC(B ESC)0        (enacs, once)
replay:       prologue
app live:     SO lqqqk SI

WITH  ESC)B (this PR) -> "lqqqk"    <- app's box drawn as letters
WITHOUT ESC)B         -> "┌───┐"    <- correct

It survives the app's own DECRC as well. And these are live-session paths — the three call sites in pty-connection.ts (hidden-restore, SSH preconnect paint, reattach) all have live-agent branches — so this reaches running TUIs, not just dead-shell restores.

Conditional harm, worth stating: the default TERM here is xterm-256color, whose smacs=\E(0/rmacs=\E(B re-designates G0 each time and therefore self-heals. The SO/SI terminfo family is reachable but not the common case.

The docstring's own reasoning also doesn't quite land. The restoreCursor() mechanism is real — I reproduced it — but what it argues for is bracketing the ?1049 switch, which the code already does, and the second copy's \x0f\x1b(B re-grounds anything the payload can render. G1-G3 only change what a later app-issued SO paints, which is the app's state. There's an internal tension too: the ?45l/4l justification is "the model re-emits those only when SET" — true, and what makes them safe — but for charsets the model re-emits nothing at all, so there's no re-assertion to complete.

Suggested: drop \x1b)B\x1b*B\x1b+B. Frame-correct minimal set is \x1b[0m\x0f\x1b(B\x1b[?7h; keep ?6l/?45l/4l for model-mode parity but the docstring should say they're mode-sync rather than frame-correctness (I couldn't construct a frame failure for any of the three — ?45l provably can't have one, since xterm wires reverse-wraparound only into backspace() and the payload contains no BS).

The harness that should have caught this can't — and that predates this PR

Not caused by this PR, but worth knowing since it explains both my bug and the constants drifting:

  • droppedOutput is declared and assigned in hidden-reveal-reconciliation.fuzz.test.ts and read nowhere. The harness never actually drops a byte, so there is no gap to ground.
  • It always replays into a pristine terminal, so nothing is ever stranded.
  • Its generator emits no SO/SI, no ISO-2022 designation, no ?6h, no ?45h, and explicitly excludes DECAWM and IRM — none of the state this baseline exists to fix.
  • It hand-assembles the preamble rather than calling buildMainModelSnapshotReplayWrites.

Smaller things

  • The fixture now omits the \x18 that production emits first (abortGapBeforeFirstWrite). Inert today — CAN into a grounded parser is a no-op — but the comment says "re-exported, never re-spelled" to end drift, and this re-opens exactly that gap.
  • pty-connection.test.ts previously pinned that an alt snapshot restore hops off the alt screen (?1049l); the new NORMAL_BUFFER_PROLOGUE contains no ?1049l. Correct for the mocked state, but that integration assertion is gone.
  • isPaneOnAlternateScreen() is never exercised as true — the pane mock hardcodes type: 'normal', so a stubbed () => false would pass the whole suite. Given the conditional switch is the riskiest logic here, that wiring deserves a test that flips the mock buffer.
  • On the alt path the conditional switch buys less than stated: the payload itself begins \x1b[0m\x1b[?1049h, so the saveCursor + kitty-flag swap happens one write later anyway. It genuinely helps only on the ?1049l side.

Green otherwise: 622 tests across the two suites, 9509 across terminal-pane + shared + daemon (3 local env-dependent zsh/daemon failures, green in CI).

Thanks for catching this — the ordering bug was mine, and "no reported symptom" was the wrong reason to drop the CAN byte.

@nwparker
nwparker force-pushed the nwparker/terminal-byte-gap-replay-baseline branch 4 times, most recently from d4b5f82 to 697ecbd Compare August 14, 2026 02:21

@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

🧹 Nitpick comments (1)
_probe_replay_prologue.cjs (1)

306-312: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Exercise CAN while the parser has an open control string.

This section only inspects JavaScript array output. It does not leave @xterm/headless in 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.cjs
  • src/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

Comment thread _probe_replay_prologue.cjs Outdated
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`

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.

🎯 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.

Suggested change
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`

Comment thread _probe_replay_prologue.cjs Outdated
Comment on lines +22 to +24
function abortGapBeforeFirstWrite(writes) {
return [`${CAN}${writes[0]}`, ...writes.slice(1)]
}

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.

🎯 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.cjs

Repository: 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)))
PY

Repository: 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 || true

Repository: 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.

@nwparker
nwparker force-pushed the nwparker/terminal-byte-gap-replay-baseline branch 7 times, most recently from 3649113 to 74143a7 Compare August 14, 2026 04:43
@nwparker

Copy link
Copy Markdown
Contributor Author

You are right, and this is the best catch in the thread — thank you. \x1b)B\x1b*B\x1b+B is dropped in 74143a7.

Why you are right, in my own words

I reproduced both of your cases:

enacs (ESC(B ESC)0 once) then SO lqqqk SI
  WITH  ESC)B  -> "lqqqk"
  WITHOUT      -> "┌───┐"

stranded G1 then a later SO
  WITH  ESC)B  -> "qqq"
  WITHOUT      -> "───"

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 screen-256color/tmux-256color/vt100 is not a trade.

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:

ground state the model re-asserts. ?6l/?7h/?45l/4l qualify — the model re-emits those when SET, so grounding plus its re-assertion leaves the renderer matching the model. Charsets do not: the model never speaks about them, so resetting is unilateral.

I also took your framing that ?6l/?45l/4l are mode-sync, not frame-correctness. You are right that ?45l provably cannot cause a frame failure — xterm wires reverse-wraparound only into backspace() and the payload contains no BS.

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

  • isPaneOnAlternateScreen() never exercised as true. Correct, and a stubbed () => false did pass the whole suite — I checked. The pane mock's buffer type is now mutable and there is an integration test that puts the pane on alt with a normal-buffer snapshot and pins the ?1049l unstick. Stubbing it false now fails that test.
  • Fixture omitted the \x18. Fixed — it now composes ABORT_TRUNCATED_CONTROL_STRING + the prologue, so the "never re-spelled" promise actually holds.
  • CodeRabbit's vacuous kitty read (same class): readKittyFlags now asserts the value is defined, so a renamed private path fails instead of comparing undefined to undefined.

Mutation matrix after the drop, on the touched suite: CAN 2, SI+G0 10, ?6l 1, ?7h 3, ?45l 1, 4l 1, ESC[r 6, ESC7 2. 12,457 green across terminal-pane + shared + daemon + ipc.

On the fuzz harness

Your droppedOutput finding is the uncomfortable one, and I agree it explains a lot: the harness that nominally covers this path never drops a byte, always replays into a pristine terminal, and hand-assembles the preamble instead of calling the builder. That is why the preambles drifted two PRs running and why neither of us was caught by it. I have not touched it here — it is a bigger change than this PR should carry — but it is the highest-value follow-up on this code, above the daemon-snapshot bare-clear I already listed.

Standing correction

Your 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 \x1b[0m\x1b[?1049h and the saveCursor + kitty swap happen one write later regardless. It genuinely helps only on the ?1049l side. I had already had to retract one alt-side kitty claim during review for the same reason — the payload's own bytes — so that is twice the same blind spot.

Nothing to apologise for on the ordering bug; restoreCursor() reloading all four G-sets is not something you would find without going into InputHandler. My first implementation had the identical bug and my tests passed, because their saved registers happened to hold defaults.

@nwparker
nwparker force-pushed the nwparker/terminal-byte-gap-replay-baseline branch from 74143a7 to 77d3b5b Compare August 14, 2026 04:52
… 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.
@nwparker
nwparker force-pushed the nwparker/terminal-byte-gap-replay-baseline branch from 77d3b5b to fc02968 Compare August 14, 2026 06:36
@nwparker
nwparker merged commit 87bafb5 into main Aug 14, 2026
50 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… 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.
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.

2 participants