Skip to content

Fix Vim alternate-screen terminal redraw recovery - #7142

Merged
nwparker merged 2 commits into
stablyai:mainfrom
nwparker:nwparker/vim-issue
Jul 3, 2026
Merged

nwparker merged 2 commits into
stablyai:mainfrom
nwparker:nwparker/vim-issue

Conversation

@nwparker

@nwparker nwparker commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #7070 — Vim (and other full-screen TUIs) ghosting/garbled redraws in Orca's terminal.

Vim redraws with plain-ASCII cursor-move/erase rewrites that xterm parses correctly, but the shared WebGL glyph atlas can keep stale glyphs until it is rebuilt, so erased cells ghost ("eepo" over "expo"). Orca already forced a viewport refresh for in-place rewrites; this PR additionally schedules the existing coalesced WebGL atlas recovery for rewrites that touch the alternate screen.

How the alternate-screen check works. Whether a rewrite touched the alternate screen is decided at parse completion, not by scanning raw chunk bytes. xterm's write(data, callback) contract runs the callback after the parser has processed that chunk (FIFO per chunk), and the alternate-screen switch (DECSET 47/1047/1049) happens synchronously inside the parse — so buffer.active.type read inside the callback is authoritative. Two captures make the coverage complete: the pre-parse buffer type (so a TUI's final frame — redraw + ?1049l restore in one chunk — still rebuilds the atlas for the restored prompt), and a buffer.onBufferChange switch count (so a full enter→draw→exit cycle parsed in one write — e.g. a coalesced backlog flush — is still seen even though the buffer type nets back to normal).

This supersedes the first revision of this PR, which scanned each raw chunk for ?47h/?1047h/?1049h enter sequences. That scan missed sequences split across PTY chunk boundaries — and real vim output does split CSI sequences at 1024-byte PTY read boundaries (see Evidence). The post-parse check closes that gap and deletes the hand-rolled CSI parser outright; xterm's parser is the single authority on alternate-screen state.

Screenshots

No visual change (bug fix; live-app verification below confirms clean vim rendering).

Testing

  • pnpm exec oxlint 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-alternate-screen-parse.test.ts
  • pnpm exec tsgo --noEmit -p config/tsconfig.tc.web.json
  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.ts (334 tests)
  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-alternate-screen-parse.test.ts src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts
  • Added regression tests that fail without the fix (details below)

Evidence of fix

1. Real PTY capture proves the failure mode is real. Captured a real vim -u NONE -N package.json session through node-pty (120×34, macOS, TERM=xterm-256color): vim enters with \x1b[?1049h, redraws via plain-ASCII \x1b[K/cursor-move rewrites, and a 1024-byte PTY read boundary split the cursor move \x1b[30;5H across two onData chunks (…\x1b[K\x1b[30 + ;5H…). Any sequence — including the alternate-screen enter — can straddle a chunk boundary, which is exactly what byte scanning cannot see. The captured bytes are now regression fixtures.

2. Before/after regression test. schedules WebGL atlas recovery when the alternate-screen enter sequence splits across chunks fails against the first revision's chunk scanner (scheduleTerminalWebglAtlasRecovery called 0 times) and passes with the post-parse check. Additional tests pin: already-in-alternate redraws, the exit chunk (recovery for the restored prompt), the single-write enter+exit cycle (switch-count path), the real captured split-mid-CSI redraw bytes, and the negative case (ordinary shell rewrites never schedule recovery).

3. Parser contract pin. terminal-alternate-screen-parse.test.ts runs the real @xterm/headless parser and locks the semantics the fix depends on: buffer.active.type reflects alternate-screen enter/exit by write-callback time, including the split-chunk case and the captured vim enter/redraw/exit chunks. If a future xterm upgrade changed this, the pin fails before ghosting could return.

4. Live app verification. Dev build with scheduleTerminalWebglAtlasRecovery temporarily instrumented (call + coalesced-burst counters), real vim driven through the rendered terminal via keyboard events, exercising the exact repro from #7070 (open JSON file, scroll G/gg/Ctrl-D/Ctrl-U, ciw edit, :q!):

Step recovery calls coalesced bursts Meaning
Baseline after startup 1 1 —
Shell commands incl. \r in-place rewrite 1 1 no recovery outside alternate screen
vim opens 3 2 recovery on entry paint
Scroll + ciw edit (issue repro) 19 7 16 calls coalesced into 5 bursts
:q! exit chunk 23 9 recovery for restored prompt
Shell after quit 23 9 scoping restored, no further recovery

Rendering stayed pixel-clean throughout — no ghosting on scroll, on the in-place edit, or on the restored prompt. The instrumentation was removed before commit.

AI Review Report

Multi-agent adversarial review over four lenses (correctness, performance, test quality, codebase consistency), each finding independently verified against the real control flow before acceptance:

  • Correctness: traced the scheduler's queue/coalesce/split paths — a split chunk fires onParsed more than once, which the parse-time predicate self-corrects (the final firing sees fully parsed state); the hidden-pane recovery path and Windows branches (ConPTY synchronized frames, East-Asian refresh) are untouched; snapshot-restore/replay writes bypass this path entirely. The review surfaced the single-write enter+exit cycle gap; fixed with the onBufferChange switch count plus regression tests (mock wiring + real-parser pin).
  • Performance: foreground writes already always pass a write callback, so no new xterm callback is introduced; the change allocates one closure per in-place-rewrite chunk in place of the removed per-chunk scan; recovery-burst frequency in the alternate screen is identical to the first revision (same gate, same single-burst latch).
  • Cross-platform: no keyboard, path, label, or shell behavior involved; the decision logic is byte-stream based and identical across macOS/Linux/Windows and SSH (verified the Windows-specific branches keep their existing semantics).
  • Consistency: formatter (oxfmt) clean, dead code from the removed scanner fully gone, comment/naming conventions checked against AGENTS.md.

Security Audit

No input execution, path handling, auth, secrets, or IPC surface touched. The change consumes already-parsed terminal state from xterm's public buffer API instead of pattern-matching raw PTY bytes, which removes a bespoke escape-sequence parser (strictly less code interpreting untrusted terminal output). Recovery scheduling remains coalesced (single-burst latch), so hostile output storms cannot queue unbounded timers.

Notes

  • Recovery stays scoped: it requires an in-place-rewrite chunk (backspace / standalone CR / erase sequence) that touched the alternate screen, so ordinary prompt rewrites never pay for it. Repeated TUI frames coalesce into the existing recovery latch (measured above: 16 calls → 5 bursts under continuous scrolling).
  • The known follow-up about global atlas-recovery cost on tab resume (Improve Windows terminal performance: retain WebGL contexts, warm first ConPTY #7085) is unaffected — this PR fires recovery no more often than the first revision did.
  • SSH sessions take the same renderer path (the decision runs on renderer-side PTY chunks regardless of transport).

@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds alternate-screen switch tracking in pty-connection.ts, routes WebGL atlas recovery decisions through a parse-completion callback, and disposes the new buffer-change subscription during teardown. It also adds Vitest coverage for split and coalesced alternate-screen transitions, Vim-style redraw timing, and ordinary foreground rewrites that refresh the terminal without scheduling atlas recovery.

Estimated code review effort: Medium

Related issues: None specified

Related PRs: None specified

Suggested labels: terminal, webgl, tests

Suggested reviewers: None specified

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address #7070 by improving alternate-screen redraw recovery for Vim and other TUIs, with regression tests.
Out of Scope Changes check ✅ Passed The PR stays focused on terminal redraw recovery and supporting tests, with no obvious unrelated changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly and concisely matches the main change: fixing Vim alternate-screen redraw recovery.
Description check ✅ Passed The description follows the template and includes the required Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections.

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

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/pty-connection.test.ts (1)

8919-9036: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Good coverage for the primary scenarios; consider a split-chunk regression test.

The three cases (already-alternate buffer, single-chunk enter sequence, ordinary rewrite) match the new decision logic well. Given the chunk-boundary gap flagged in pty-connection.ts (containsAlternateScreenEnterSequence), consider adding a case that delivers \x1b[?1049h across two onData calls to lock in that fix once made.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 8e8dd19f-cbd9-4847-940e-cc46d901d8b7

📥 Commits

Reviewing files that changed from the base of the PR and between 98a78f1 and 81f051c.

📒 Files selected for processing (2)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts

Replace the raw-chunk scan for alternate-screen enter sequences with the
xterm parser's own verdict: in-place rewrite chunks check
buffer.active.type (plus a parse-time buffer-switch count) inside the
write callback, where the buffer is authoritative. Covers enter/exit
sequences split across PTY chunk boundaries and full enter-exit cycles
coalesced into one write, and deletes the hand-rolled CSI parser.

Adds regression tests from a real captured vim session (including a
CSI sequence split at a 1024-byte PTY read boundary) and a contract
pin against the real @xterm/headless parser.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker merged commit 4c4cbf2 into stablyai:main Jul 3, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* Fix Vim alternate-screen terminal redraw recovery

* Decide alternate-screen atlas recovery from parsed buffer state

Replace the raw-chunk scan for alternate-screen enter sequences with the
xterm parser's own verdict: in-place rewrite chunks check
buffer.active.type (plus a parse-time buffer-switch count) inside the
write callback, where the buffer is authoritative. Covers enter/exit
sequences split across PTY chunk boundaries and full enter-exit cycles
coalesced into one write, and deletes the hand-rolled CSI parser.

Adds regression tests from a real captured vim session (including a
CSI sequence split at a 1024-byte PTY read boundary) and a contract
pin against the real @xterm/headless parser.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
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]: Vim renders/redraws incorrectly in Orca's terminal, making it unusable

1 participant