Skip to content

[CTX-1903] fix(term-state): keep scroll margins per screen (divergence D-1) - #3260

Merged
Xuepoo merged 2 commits into
mainfrom
ctx-1903/fix-scroll-region
Nov 19, 2026
Merged

Xuepoo merged 2 commits into
mainfrom
ctx-1903/fix-scroll-region

Conversation

@Xuepoo

@Xuepoo Xuepoo commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Priority: P1 | Area: term | Labels: fix,P1,area:term | Milestone: v0.1.0 | RFC: none | Task: CTX-1903

Refs #3259

Problem

A TUI that sets a DECSTBM scroll region and then takes the alternate screen hands its margins to the primary screen: scroll_region_top / scroll_region_bottom were a single pair for the whole terminal, they were not part of ScreenSave, and switch_alt_screen neither saved nor restored them. After ?1049l the shell clipped every line to the TUI's region, so the pane stopped updating and looked frozen.

Reproduced headlessly (24 rows): fill the primary screen, ?1049h, CSI 1;5r, ?1049l, then print 27 lines — rows 0..19 kept the old content and only the region's rows moved.

Fix (divergence D-1)

Scroll margins are primary-screen state that the TUI overwrote, so:

  • ScreenSave carries the primary pair; ?1049h / ?47h give the alternate screen full margins; ?1049l / ?47l restore the primary pair (clamped when the grid shrank).
  • DECSTR clears the stashed pair as well (device-scope soft reset); RIS drops it with primary_save.
  • Resize keeps resetting the active screen's margins (TERM-ENG-005) and only clamps the stash: the inactive screen's application receives no SIGWINCH and cannot re-set its margins.

Index and reverse index at a screen edge are deliberately unchanged. xterm (ptyx.h, charproc.c, cursor.c), ghostty (Terminal.zig) and kitty (screen.c) all keep one margin register and clamp at the edges, so this is a recorded divergence, documented in lib.rs and the field docs, not a parity fix. Scrolling the whole screen at the edge would destroy rows an application deliberately excluded from its region (status and progress lines) and push them into scrollback; the discarded thing is the index, never a row.

CANONICAL_HASH_VERSION 14 → 15 (the stashed pair is hashed; it decides the next primary scroll). New InvariantViolation::SavedScrollRegionInvalid bounds the stash.

Tests

16 integration + 2 unit, grid-truth assertions only, in crates/bitty-term-state/tests/scroll_region_per_screen.rs. Against a pristine HEAD tree the suite is 11 failed / 5 passed — every D-1 discriminator fails, the guards (region-only scroll on a margin, edge discard, RIS, DECSTR) pass by design.

Coverage: both leak directions, ?47 and ?1049 entry/exit/re-entry, the mixed ?47h+?1049l pair, RIS with a stash, DECSTR inside the alternate screen, stash behaviour across taller and shorter resizes, resize while the primary screen is active, region-only scrolling on a margin, and the edge-discard guard that keeps the rejected divergence from creeping back.

Gates

cargo fmt --all -- --check                                     clean
cargo test -p bitty-term-state                                 272 lib + all suites, 0 failed
cargo clippy -p bitty-term-state --all-targets -- -D warnings   clean
cargo nextest run --workspace --locked                          11719 passed, 28 skipped, 0 failed
cargo test --workspace --doc --locked                          no failures
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps     clean

One flaky pair (terminal_app::wall_recovery_wiring_1855_tests, timer-based, unrelated crate) failed once and passes in isolation; the repeat full run is 11719/11719.

Follow-ups

  • DECSTBM with top == bottom is accepted, although xterm and ghostty reject it. Pre-existing, tracked separately.
  • The divergence record in bitty-terminal-docs (terminal-state invariants and the compatibility matrix) is not in this PR; it follows as a docs-only change and this PR does not depend on it.

@Xuepoo Xuepoo added this to the v0.1.0 milestone Nov 19, 2026
@Xuepoo Xuepoo added fix Bug fix P1 Priority: high area:term Area: terminal state / VT labels Nov 19, 2026
@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 22 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 415d7e8d-c7fc-4287-ab68-ff9f45f07146
Commits

Reviewing files that changed from the base of the PR and between 2f6fae3 and 4468fa8.

Files selected for processing: 9

  • crates/bitty-render/tests/bidi_paint.rs
  • crates/bitty-term-state/src/canonical.rs
  • crates/bitty-term-state/src/lib.rs
  • crates/bitty-term-state/src/state.rs
  • crates/bitty-term-state/src/state/hash.rs
  • crates/bitty-term-state/src/state/invariants.rs
  • crates/bitty-term-state/src/state/tests.rs
  • crates/bitty-term-state/tests/bidi_visual_order.rs
  • crates/bitty-term-state/tests/scroll_region_per_screen.rs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@Xuepoo Xuepoo left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Verdict: APPROVE

Round-3 verification of PR #3260 at 9d0c6aff against my review of the first cut (issue #3259 comment 7016426619). Every finding is closed in code; the remaining item is one sentence in this PR body (see "Required before merge", not code). No code changes were made by this review; nothing was merged.

Per-finding status

Finding Status Evidence
B1 drop change 2 (whole-screen scroll at the edges) + its tests, pin the reference behaviour CLOSED index_linefeed (state.rs:3621) and reverse_index (state.rs:3637) are body-identical to origin/main (diffed function bodies, ignoring the new /// docs). scroll_up_screen / scroll_down_screen / scroll_up_span / scroll_down_span are gone (rg → no match). The two divergence tests are gone; the new guard index_at_a_screen_edge_outside_the_region_is_discarded (tests/scroll_region_per_screen.rs:484-511) asserts grid truth (rows unchanged) and scrollback_len() == 0 for both LF-at-23 and RI-at-0. Docs make no parity claim: lib.rs:76-79 "Index/reverse index do not diverge … The index is what is discarded, never a row"; index_linefeed doc repeats it; canonical.rs:63 says "divergence D-1".
B2 durable record claimed parity CLOSED Issue #3259 rewritten: reference table matches the sources (xterm ptyx.h:2833-2834 / charproc.c:9528-9557 / cursor.c:292-312, ghostty Terminal.zig:68, kitty screen_index), states "This is not an xterm-parity defect, and the earlier description … was wrong", and records D-1 with a rationale plus "Deliberately not diverging: index/reverse-index … keep the reference clamp". CTX-1903 title/description likewise: "per-screen scroll margins (divergence D-1)", "so this is a recorded divergence, not parity; index/reverse-index stay unchanged per review". No parity claim left in either.
B3 divergence not recorded in bitty-terminal-docs OPEN as intended, not in this PR git grep D-1 origin/main (bitty-terminal-docs, 1114ec9) finds no scroll-margin record and gh pr list shows no docs PR yet. The PR body lists it under Follow-ups, so the merge is not blocked on another repository. One wording defect: the bullet says the divergence "is recorded in bitty-terminal-docs", which is false today (see below).
M1 DECSTR must clear the stash CLOSED, device scope soft_reset (state.rs:4407-4410) clears primary_save margins as well, with a DEC STD 070 device-scope justification. Test decstr_inside_the_alternate_screen_clears_the_stashed_primary_margins:336-367 checks both screens and the scrollback count. Mutation check: deleting only that block makes the test fail at :360 ("DECSTR did not clear the stashed primary margins").
M2 resize asymmetry needs a decision and a test CLOSED Decision documented twice (state.rs:311-345 field docs "Resize is asymmetric by design … the inactive screen's application receives no SIGWINCH", and the resize comment state.rs:758-771), mirrored in lib.rs:81-84 and the PR body. Both directions are tested: taller (:374-392, absolute rows untouched), shorter (:395-414, bottom trimmed to 18..19), and the previously untested "resize while the primary screen is active, then alt, then exit" case (resize_while_the_primary_screen_is_active_leaves_full_margins_after_an_alt_exit:417-444, which asserts a pre-resize partial region is not resurrected). Mutation check: replacing the clamp with a reset-to-full fails :412 ("stored margins were not clamped").
M3 wording ("clamps and drops the row") CLOSED lib.rs:79, state.rs:3616-3620, :3633-3636 now say the index is discarded, never a row. No remaining "drops the row" (or equivalent) anywhere in the crate docs.
M4 test gaps CLOSED RIS with a live stash (:314-333, also pins scrollback_len() == 1), DECSTR inside alt (:336-367), mixed ?47h+?1049l (:276-307, margins restored, cursor explicitly not), negative invariant case (state/tests.rs:3195-3225, corrupts the stash white-box and asserts the exact SavedScrollRegionInvalid { top, bottom, height }, then the top > bottom shape), and every fixture now uses multi-row regions (CSI 1;5r) because "xterm's set_tb_margins and ghostty both reject top == bottom" (:13-15) — :103, :132, :238 changed accordingly.

Discrimination

Pristine git archive origin/main tree + the new test file, cargo test --test scroll_region_per_screen: 11 failed / 5 passed, matching the PR body exactly. The five passers are the intended guards: the two margin-only scroll tests, the edge-discard guard, RIS, and DECSTR (both of which also passed pre-patch because the old single register was reset for a different reason). The DECSTR and resize-clamp guards do discriminate their own decisions — verified by mutation on a copy of the branch tree:

  • delete the DECSTR stash clear → decstr_inside… fails (:360), 0 passed / 1 failed;
  • reset instead of clamp the stash on resize → stored_primary_margins_clamp… fails (:412), 0 passed / 1 failed;
  • reintroduce the rejected whole-screen scroll at the edge → index_at_a_screen_edge_outside_the_region_is_discarded fails (:494), 0 passed / 1 failed.

So the guard genuinely keeps the dropped divergence from creeping back.

Gates (branch 9d0c6aff, CARGO_TARGET_DIR=/tmp/bitty/1903-round3-target)

cargo fmt --all -- --check                                     clean
cargo test -p bitty-term-state                                 272 lib passed; 16/16 scroll_region_per_screen; all suites 0 failed
cargo clippy -p bitty-term-state --all-targets -- -D warnings   clean (Finished dev profile)

Does D-1 alone make the reported agy exit path recover?

Yes — if the TUI used the alternate screen, which is the reported shape. Trace: the TUI enters ?1049h, ScreenSave snapshots the primary pair (full 0..23) and the shell's cursor; the TUI sets 5..10 and exits ?1049l with the cursor at row 23 outside that region. On exit the live pair becomes the primary's full 0..23, so the shell's first LF at row 23 hits the row == scroll_region_bottom branch and scrolls the whole screen, capturing one row into scrollback. Output lands correctly and keeps scrolling; the region that clipped it is gone. alt_screen_status_region_does_not_leak_into_primary_after_exit is that path end to end (27 lines after ?1049l, rows after-3..after-26), and it fails on main.

It does not recover if the region was installed on the primary screen (an inline/full-screen-in-primary app, or a stale region from a previous primary-screen app) and the cursor then sits on the last row outside it: there is nothing to restore, the index is discarded by design, and the last row freezes again — the exact pair of conditions pinned by the new guard test. Nothing short of the dropped change 2 (or an app-side ESC[r, or a DECSET-gated safety net) recovers that case. So the public wording must stay "recovers after any alternate-screen TUI exits", not "any TUI", and #3259 still owes the byte-sequence recording the issue body already calls for before it can be called closed. If that recording shows agy drawing its status row on the primary screen, D-1 will not be enough and the follow-up needs a decision (recommended: parity first — reject top == bottom like xterm/ghostty — and only then consider a gated safety net).

Required before merge (PR body only, no code)

  • The last Follow-ups bullet reads "The divergence itself is recorded in bitty-terminal-docs …". It is not recorded yet: bitty-terminal-docs origin/main (1114ec9) has no D-1 scroll-margin entry and no docs PR is open. Rewrite it as pending (name the planned docs change), and keep #3259 open until it lands. Everything else in the body is accurate.

Advisories (no action required for this merge)

  • out_save_cursor_fields appends the stash fields before write_modes (state/hash.rs:270-292 is followed by write_modes at :77), so the byte prefix of an existing state is not preserved. Harmless because CANONICAL_HASH_VERSION is bumped to 15 and no consumer compares hashes across versions, but the round-1 note "appended at the end, stable prefix" is not literally what landed.
  • Hash pins are complete and consistent: canonical.rs:73 and :238, lib.rs:52 (re-export :135), bitty-render/tests/bidi_paint.rs:254, tests/bidi_visual_order.rs:477; no stale 14 (rg over crates/, the only other == 14 is an unrelated mouse opcode in bitty-runtime/src/runtime/pty.rs:2047).
  • Nothing else changed: the only edits outside the crate are the two version pins, and no test now asserts the opposite of what it used to (git diff --stat: 9 files, all accounted for).
  • PR is MERGEABLE but mergeStateStatus: BEHIND origin/main (11 commits). Not a review blocker; the commander should rebase/update before merge so CI runs on the merged shape.
  • CodeRabbit has posted only its summary comment (0 inline comments); CI (Quality gates, MSRV, Linux, Windows, CodeQL) was still in progress at review time — merge only on green.

…e D-1)

A TUI that sets a DECSTBM region on the alternate screen handed its
margins to the primary screen on ?1049l, so the shell afterwards clipped
every line to that region and the pane could not render (agy in Swarm
mode, bitty#3259).

Scroll margins are primary-screen state the TUI overwrote: Save the pair
in ScreenSave, give the alternate screen full margins on ?47/?1049 entry,
and restore the primary pair on exit (clamped on shrink). DECSTR clears
the stashed pair as a device-scope soft reset; RIS drops it with
primary_save. Resize keeps resetting the active screen's margins per
TERM-ENG-005 and only clamps the stash, because the inactive screen's
application gets no SIGWINCH and cannot re-set its margins.

This is a recorded divergence from xterm (one TScreen register),
ghostty (Terminal.scrolling_region) and kitty, all of which leave the
primary screen clipped. Index and reverse index at a screen edge stay on
the reference clamp behaviour: the discarded thing is the index, never a
row, so status and progress rows outside the region are not scrolled
away or pushed into scrollback.

Closes #3259
@Xuepoo
Xuepoo force-pushed the ctx-1903/fix-scroll-region branch from 9d0c6af to ecdd140 Compare November 19, 2026 17:33
…nvariant

MSRV 1.85 rejects `if let … && …` (stabilised in 1.88), so the CI MSRV
job failed on the new invariant check. Nested if instead; no behaviour
change.

@Xuepoo Xuepoo left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Delta review at head 4468fa8f, covering only what changed since the approved 9d0c6aff.

This review covers head 4468fa8 (not the 9d0c6af that @Xuepoo approved). Scratch worktree at .targets/ctx1903-review/bitty, own CARGO_TARGET_DIR; the owner's .worktrees/ctx-1903 was not touched and no cargo ran inside it.

Delta classification (9d0c6af → 4468fa8)

git diff 9d0c6aff 4468fa8f = 59 files, 9230+/242-. It decomposes cleanly into two parts, and nothing else:

Part Size Evidence Verdict
Rebase artifact (main 3c588f2 → 2f6fae3 replayed) 58 files, 9221+/234- git diff 9d0c6aff ecdd1402 has patch-id 4e8ee407; git diff 3c588f26 2f6fae3d (main's own landed commits) has the same patch-id 4e8ee407. Name sets identical. Byte-for-byte main's work; zero authored change.
The let-chain fix crates/bitty-term-state/src/state/invariants.rs, 9+/8- git diff ecdd1402 4468fa8f touches that one file and nothing else The only new authored delta.

Two more facts that pin the rebase down:

  • The PR's own change is unchanged by the rebase: git diff 3c588f26 9d0c6aff and git diff 2f6fae3d ecdd1402 both have patch-id 72c14f41 (9 files, 790+/12- each).
  • git diff 9d0c6aff ecdd1402 -- crates/bitty-term-state/ is empty — the crate's tree at ecdd1402 is identical to the reviewed 9d0c6aff. So the 16-test suite and every source line Xuepoo verified are still exactly the lines under review, minus the one hunk below.

The let-chain fix

Pre-fix (ecdd1402 / 9d0c6aff):

if let Some(save) = &self.primary_save
    && !(save.scroll_region_top <= save.scroll_region_bottom
        && (save.scroll_region_bottom as usize) < self.height)
{

Post-fix (4468fa8f):

if let Some(save) = &self.primary_save {
    if !(save.scroll_region_top <= save.scroll_region_bottom
        && (save.scroll_region_bottom as usize) < self.height)
    {
  • MSRV 1.85: correct. if let … && … is E0658 on 1.85 (issue #53667). Proved directly: rustc +1.85.1 --edition 2024 and --edition 2021 both reject the shape, and running the workspace's own MSRV gate on the pre-fix file fails with error[E0658]: let expressions in this position are unstable / could not compile bitty-term-state (lib test). The same gate on the fixed file exits 0.
  • No remaining let-chains or if-let guards in the crate: cargo +1.85 check -p bitty-term-state --tests builds the lib, the lib test harness and every integration test target, so any such construct anywhere in the crate would have failed. It finishes clean.
  • Behaviour preserved. if A && !B { return Err } ≡ if A { if !B { return Err } } — same borrow (&self.primary_save), no side effects in the condition, no early return between them, and the SavedScrollRegionInvalid { top, bottom, height } payload is byte-identical (the same save.* fields, same order). The two negative invariant tests in state/tests.rs (:3210, :3225) that assert the exact payload still pass.

Gates (scratch tree, CARGO_TARGET_DIR=.targets/ctx1903-review/target*)

cargo test -p bitty-term-state --offline
  → 272 lib passed; 16/16 scroll_region_per_screen; all 17 integration suites 0 failed (400 total, 0 failed)
cargo +1.85 check -p bitty-term-state --tests --offline --locked
  → Finished, exit 0
cargo clippy -p bitty-term-state --all-targets --offline -- -D warnings
  → Finished, no warnings, exit 0

Sanity checks I added on top of the ask:

  • pre-fix file + the 1.85 gate → E0658 (the fix is necessary, not cosmetic);
  • rustc +1.85.1 on a minimal snippet, editions 2024 and 2021 → E0658 both.

CI at head is green apart from one job still running: MSRV 1.85 check pass, Windows pass, macOS ARM64 pass, Linux Wayland/X11 pass, CodeQL/Supply chain/AUR pass; Quality gates (2) still pending at the time of writing.

PR body honesty

  • Divergence wording: FIXED. The last Follow-ups bullet now reads "The divergence record in bitty-terminal-docs … is not in this PR; it follows as a docs-only change and this PR does not depend on it." That is the pending wording Xuepoo required, and "does not depend on it" matches the diff (no docs files, only crates/ + Cargo.lock). Checked independently: bitty-terminal-docs at 457135b has no per-screen scroll-margin entry — the only D-1 hits there are the unrelated AI-surface demotion list — so claiming it is pending is accurate.
  • Claim set matches the code. CANONICAL_HASH_VERSION 15 (canonical.rs:73, pin at :238, lib.rs:52, :135); InvariantViolation::SavedScrollRegionInvalid defined (invariants.rs:37) and raised (:228); DECSTR clears the stash (state.rs:4407-4410); RIS drops it with primary_save (full_reset at :4414, primary_save = None at :4420); resize clamps the stash and never grows it (state.rs:844-845); both ?47 and ?1049 entry/exit paths covered; top == bottom accepted on 2f6fae3d too (set_scroll_region rejects only t > b), so "pre-existing" is right; "16 integration + 2 unit" matches (16 #[test] in scroll_region_per_screen.rs, 272 lib tests); the gate numbers listed in the body reproduce here.
  • #3259 is not kept open. Line 3 of the body still reads Closes #3259, so merging closes it. That contradicts the previous review's "keep #3259 open until it lands", and the issue's own body: fix item 4 is the bitty-terminal-docs record (explicitly not in this PR), and the Report section says the mechanism "must be confirmed against a recording before the defect is called closed". The PR leaves work in that issue, so it must not close it.

Required before merge (body only, one line)

Change Closes #3259 to Refs #3259 (e.g. Refs #3259 — the docs record and the byte-sequence recording keep it open). Nothing else in the body needs editing, and no code change is needed for this verdict: the delta compiles, lints, tests and satisfies MSRV 1.85, and everything Xuepoo verified is unchanged.

verdict for head 4468fa8 only: the code delta is correct and mergeable; the PR body still auto-closes an issue the record says must stay open.

VERDICT: CHANGES-REQUESTED

@Xuepoo Xuepoo left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Guard closeout note (cron tick, bitty blitz).

The round-4 delta re-review of head 4468fa8f returned its only blocking item as PR-body metadata: the body's Closes #3259 would have auto-closed an issue whose docs-record item is explicitly not in this PR (and whose DECSTBM top == bottom half is tracked separately as #3261).

Resolution: the body now reads Refs #3259 (edited by the guard; nothing else in the body changed). The code verdict itself stands from that review — the reviewed tree at ecdd1402 is byte-identical to the approved 9d0c6aff for bitty-term-state, the only authored delta being the MSRV-1.85 let-chain desugar in state/invariants.rs (verified: E0658 on the pre-fix file under rustc +1.85.1, exit 0 after, identical SavedScrollRegionInvalid payload).

Checks at 4468fa8f: pass 18 / fail 0 / pending 0 (CodeRabbit, VM tier (main), VM tier (nightly ARM64) skipping). Merging on that head.

@Xuepoo
Xuepoo merged commit 81e6aed into main Nov 19, 2026
34 of 35 checks passed
@Xuepoo
Xuepoo deleted the ctx-1903/fix-scroll-region branch November 19, 2026 18:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:term Area: terminal state / VT fix Bug fix P1 Priority: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant