Skip to content

[0.1.0] term-state: scroll margins must be per-screen so a TUI cannot strand the primary screen #3259

Closed

Description

@Xuepoo

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

Report

Running agy (Antigravity CLI, 1.5.12) in Swarm mode and leaving it with Esc leaves the pane permanently damaged:

  • the screen keeps showing only what was drawn before Esc; what the application draws afterwards is invisible;
  • after the TUI exits, the shell still cannot render — the prompt and typed characters stay on a single line and new output never appears;
  • an [Image 1] [Image 2] [Image 3] row stays pinned to the first line.

That last row is the application's own attachment header, not a Bitty artefact. The pane stays broken until the session is recreated. The exact byte sequence agy emits has not been captured yet (the reporter's session is the only place the Swarm view renders); the mechanism below is reproduced synthetically and must be confirmed against a recording before the defect is called closed.

Mechanism (reproduced headlessly)

State::scroll_region_top / scroll_region_bottom (crates/bitty-term-state/src/state.rs:300-301) are a single pair for the whole terminal, they are not part of ScreenSave (:256-266), and switch_alt_screen (:4009) neither saves nor restores them. A TUI that sets a scroll region on the alternate screen therefore hands its margins to the primary screen when it exits (?1049l), and the shell is left clipping its output to that region.

Reproduction in a 24-row state:

fill primary with main-0 .. main-23      (cursor at the last row)
?1049h                                   (enter the alternate screen)
CSI 1 ; 5 r                              (a status-line region)
?1049l                                   (leave the alternate screen)
print after-0 .. after-26

observed: rows 0..19 still show main-*, only the region's rows move
expected: the primary screen scrolls with its own margins

Reference behaviour (checked against the sources, 2026-11-20)

This is not an xterm-parity defect, and the earlier description in this issue claiming otherwise was wrong:

margins index on the last row, outside the region
xterm one pair in TScreen (ptyx.h:2833-2834); ToAlternate/FromAlternate only swap buffers (charproc.c:9528-9557); CursorSave2 stores no margins xtermIndex → CursorDown, clamps at max_row (cursor.c:292-312)
ghostty scrolling_region on Terminal (Terminal.zig:68); switchScreenMode never touches it index() moves only while y < rows-1
kitty — screen_index clamps

So a terminal that follows the references exactly also freezes here. Bitty will deliberately diverge on one point only:

Divergence D-1: scroll margins are per-screen. Entering the alternate screen gives it full margins; leaving restores the primary screen's own margins. Rationale: the margins are primary-screen state the TUI overwrote, restoring them cannot lose information, and it is what makes a pane recoverable after any TUI exits.

Deliberately not diverging: index/reverse-index at the screen edge keep the reference clamp behaviour. Scrolling the whole screen at the last row would destroy rows an application deliberately excluded from its region (status and progress lines) and push them into scrollback.

Fix

  1. Per-screen margins: save the primary pair in ScreenSave, give the alternate screen full margins on entry, restore the primary pair on exit (clamped on shrink).
  2. Keep the index/reverse-index paths as they are.
  3. Regression tests: a region set on the alternate screen must not survive ?1049l; margins set on the primary screen must not clip the alternate screen; the region survives a resize within its screen; ?47 and the mixed ?47h+?1049l pair behave consistently; RIS/DECSTR interact correctly with the saved pair.
  4. Record D-1 in bitty-terminal-docs (terminal-state invariants and the compatibility matrix) as a divergence with its rationale.

Verification

  • Headless: the reproduction above, plus the cases in item 3.
  • Live: agy in Swarm mode → Esc → the shell renders and scrolls normally; a full-screen vim open/close cycle and clear stay clean.

Activity

  1. added this to the v0.1.0 milestone on Nov 19, 2026
  2. added
    fix
    P1
    area:term
    on Nov 19, 2026
  3. Xuepoo commented on Nov 19, 2026

    @Xuepoo
    ContributorAuthor

    Verdict: NEEDS-FIX

    Independent review of the uncommitted ctx-1903/fix-scroll-region worktree (CTX-1903). Reviewed adversarially against the real xterm, ghostty and kitty sources, not against the issue text.

    Bottom line: change 1 (per-screen margins) is correct, well-tested and should land. Change 2 (whole-screen scroll when the cursor sits at a screen edge outside the region) is a divergence from every reference I could check, is not needed to fix the reported defect, and can silently destroy rows an application deliberately put out of the region's reach. Drop change 2, keep change 1, correct the durable record.


    Reference behaviour (settled from source)

    The implementer's reading is correct; the issue text and the task title are wrong on both points.

    xterm (ThomasDickey/xterm-snapshots, master):

    • One margin register for the whole terminal: TScreen.top_marg / bot_marg (ptyx.h:2833-2834). There is exactly one TScreen (ptyx.h:3672, TScreen screen;).
    • ToAlternate / FromAlternate (charproc.c:9528-9557) only swap buffer pointers (SwitchBufs), scroll-jump and optionally clear. Neither touches top_marg/bot_marg.
    • ?1049 is CursorSave(xw); ToAlternate(xw, True); ClearScreen(xw) and on reset FromAlternate(...); CursorRestore(xw) (charproc.c:7733-7741). CursorSave2 (cursor.c:396-419) stores row/col, IFlags, charsets and wrap — no margins. ?47 ( srm_ALTBUF, charproc.c:7759-7770) saves and restores nothing.
    • xtermIndex (cursor.c:292-312): if (cur_row > bot_marg) CursorDown(...). CursorDown (cursor.c:248-262) clamps at max_row — no scroll, no movement. RevIndex (cursor.c:319-340) mirrors it through CursorUp, which clamps at 0.
    • DECSTR does not touch margins at all (ReallyReset's DECSTR branch, charproc.c:14548-14562); RIS and DECCOLM do (resetMargins, charproc.c:1376, 7469, 4849).
    • Margins are also not clamped on resize (set_max_row, charproc.c:1407-1413, has no margin logic) — so Bitty's "resize resets the active region" (TERM-ENG-005) is already a recorded divergence, independent of this patch.

    ghostty:

    • scrolling_region: ScrollingRegion lives on Terminal (Terminal.zig:68), not on Screen.
    • switchScreenMode (Terminal.zig:5749-5830, explicitly derived from xterm's srm_ALTBUF* arms) never touches scrolling_region; saveCursor (Terminal.zig:2703-2717) stores no margins.
    • index() (Terminal.zig:3017, region test at 3052-3062): outside the region it moves the cursor down only if cursor.y < rows - 1; at the last row it does nothing. reverseIndex (Terminal.zig:3217-3226) → cursorUp(1), which clamps.

    kitty (third data point, kovidgoyal/kitty, kitty/screen.c):

    • screen_index (screen.c:2741-2748): if (cursor->y == bottom) INDEX_UP(...) else screen_cursor_down(self, 1) — no whole-screen scroll when the cursor is below the region.

    So: per-screen margins is a divergence from xterm/ghostty; whole-screen index at the edge is a divergence from xterm, ghostty and kitty.

    Judgement per change

    Change 1 — per-screen DECSTBM margins: ACCEPTED as a recorded divergence.

    • What is gained: the primary screen always owns its own region. A TUI's status-line region can no longer clip the shell, and a shell's region can no longer clip a TUI. This is the direct fix for the report and it cannot lose information — it only restores state the primary screen itself set.
    • What can break: an application that sets a region on the primary screen, enters the alternate screen and expects the region to still bound its scrolling now scrolls full-screen instead (ncurses smcup without a fresh setscrreg). The failure direction is benign (content scrolls more of the screen, nothing is clipped or lost), and such an app is by construction confused about which screen it is drawing on. Low risk, acceptable.
    • Residual consequence (not a defect): on ?47l/mixed-pair exit the cursor is not restored but the margins are, so an origin-mode cursor that the alt screen left outside the restored region is clamped by dispatch's enforce_cursor_invariants (state.rs:2148) — a silent cursor jump to the restored region top. I verified with a probe against the built rlib that this path stays invariant-clean (Ok(())), so the new invariant cannot be tripped from here.

    Change 2 — whole-screen index/reverse-index at the edge: NOT ACCEPTED. Drop it.

    • It is not needed for [0.1.0] term-state: scroll margins must be per-screen so a TUI cannot strand the primary screen #3259: change 1 alone restores full margins on exit, so the next LF on the primary takes the ordinary region path (row == bottom == last_row) and the shell scrolls. The issue's reproduction is entirely explained by the leak.
    • It is a divergence from all three references, and it is the destructive direction: an application that installs a region specifically to protect rows (status/progress/input row at the last screen row) and then emits a linefeed there gets, under this patch, a full-screen scroll that shifts the region's content and the protected rows up one line, plus (on the primary screen) a row pushed into scrollback (scroll_up_span capture branch, state.rs:3874-3889, asserted by scroll_up_screen's new test). Under xterm/ghostty/kitty the linefeed is simply discarded and the protected rows stay put.
    • The stated rationale ("output landing there would be dropped silently", state.rs:3596-3599) is inaccurate: nothing is dropped; the index is discarded and the next glyph overwrites the last row.
    • If the commander wants a robustness net for degenerate regions on the primary screen only, narrow it to that (never the alternate screen, where the region is the TUI's explicit policy) and record it; but the cleaner alternative is to stop accepting one-row regions at all (set_scroll_region accepts t == b, state.rs:3938-3956; xterm set_tb_margins requires bottom > top, charproc.c:1335-1349, and ghostty if (top >= bottom) return;, Terminal.zig:3335-3343). That is a parity fix that removes the worst freeze path instead of inventing new scrolling.

    Findings

    # Severity Location Finding
    B1 Blocker crates/bitty-term-state/src/state.rs:3604-3617, 3625-3649, 3855-3858, 3907-3910 Whole-screen index/reverse-index at an edge outside the region diverges from xterm, ghostty and kitty, silently scrolls rows an app excluded from its region, and captures scrollback on the primary where the reference captures nothing. Not required for #3259. Drop change 2 (and the scroll_up_screen / scroll_down_screen helpers and the two tests that cover only it).
    B2 Blocker (record) issue #3259 §1/§2; CTX-1903 title + description The durable record claims parity the code does not implement ("In xterm the margins belong to the screen", "xterm's Index scrolls the whole screen", title "xterm-compatible index outside the region"). The rustdoc correctly says divergence. Fix the issue body (gh issue edit 3259) and the task description/title before merge.
    B3 Major (DoD) bitty-terminal-docs specifications/terminal-state-rfc.md (invariants 4/5), reference/compatibility-matrix.md The divergence is documented only in rustdoc (lib.rs:54-70, the State::scroll_region_top field doc, state.rs:4129-4137). Canonical docs must record it: invariant 4 ("lines enter scrollback only via scroll-under-region operations") now also has to describe a whole-screen scroll triggered by a cursor outside the installed region, and invariant 5's save set gains margins. Needs a tracked follow-up or a docs PR before the task closes.
    M1 Minor state.rs:4402-4414 DECSTR now clears only the active pair; the stashed primary pair survives. VT510/DEC STD 070 scope DECSTR's scrolling-region reset to the device, so a DECSTR issued inside a TUI no longer clears what ?1049l restores. Either clear both pairs or state the deliberate scope in the comment (it currently says "active screen's margins cleared" without justifying the asymmetry). RIS is fine: full_reset drops primary_save.
    M2 Minor state.rs:745-760 vs 823-829 Resize resets the active margins to full (TERM-ENG-005) but only clamps the stashed pair, so after ?1049l the primary can come back with a non-full region in a grid that was resized. Internally defensible (the inactive screen's app is not getting SIGWINCH), but it is a conditional reading of TERM-ENG-005 and no test asserts it. Document it; the two resize tests cover grow and shrink of the stash, not "shrink while primary active, then alt, then exit".
    M3 Minor lib.rs:68-69; state.rs:3596-3599, 3618-3624 "where xterm clamps and drops the row" / "output landing there would be dropped silently" overstates the reference: xterm discards the index, not the row. Reword (also moot if B1 drops the path).
    M4 Minor (tests) tests/scroll_region_per_screen.rs Gaps: no RIS-with-live-stash test, no DECSTR-inside-alt test, no mixed ?47h/?1049l margins test, no negative test that SavedScrollRegionInvalid actually fires (a white-box one would prove the check exists rather than trusting it). The reproductions use a one-row region set_region(.., 0, 0) (:99), a configuration xterm itself rejects; use a 2-row region so the fixture models something a reference terminal accepts.
    N1 Nit state.rs:3938-3956 DECSTBM accepts top == bottom; xterm and ghostty reject it. Pre-existing, but it is the configuration that made the freeze total, so a parity fix here is worth a tracked task.

    Verified good (no action)

    • Semantics matrix internally consistent and commented: ?1049h/l (save/restore + clear), ?47h/l (retained grid, full margins on every entry, primary margins restored without the cursor), mixed ?47h/?1049l (margins restored, cursor not — explicitly justified at state.rs:4188-4199), alt re-entry with a retained ?47 grid (grid kept, margins reset, commented at state.rs:4129-4137), resize while alt active (stash clamped, never grown/reset), RIS (full_reset drops primary_save), DECSTR/DECCOLM (active screen only, commented at state.rs:4021-4028).
    • Clamp ordering cannot produce top > bottom: state.rs:823-829 clamps bottom to rows - 1 first, then top to bottom; resize_with_report clamps rows to >= 1 (state.rs:595-599), so rows - 1 never underflows. The exit path re-clamps defensively (state.rs:4194-4199).
    • New invariant is real and enforced: added at state/invariants.rs:29-47, checked at invariants.rs:220-233, reached by finalize_batch's debug_assert! after every action (state.rs:2166-2170) and after resize (state.rs:857-861), and by the debug/CI corpus+proptest regime. Release builds do not check it, matching the existing invariant regime.
    • Whole-screen path reuses the region machinery correctly: damage_scroll_move with (0, height-1) (the ordinary full-screen scroll shape), scrollback capture gated on !alt && bottom == height-1 (unchanged policy), kitty placements scrolled over the span, inline_top_row decremented only for a top == 0 span, sync-update bookkeeping untouched. No complexity change: IND/RI stay O(1) for a cursor move and O(rows) for a scroll.
    • Region path unchanged when the cursor is on a margin: first branch still calls scroll_up_region/scroll_down_region; index_on_the_region_bottom_margin_scrolls_only_the_region and the reverse test pin it.
    • Hash: the stash is truth-bearing (it decides the region restored on ?1049l, hence where the next scroll moves content), so hashing it is justified. CANONICAL_HASH_VERSION = 15 is complete — all four pins updated (canonical.rs:73, canonical.rs:238, lib.rs:52, bitty-render/tests/bidi_paint.rs:254, tests/bidi_visual_order.rs:477); rg 'CANONICAL_HASH_VERSION|hash_version|== 14' finds no stale 14. The two fields are appended at the end of out_save_cursor_fields (state/hash.rs:280-286), so the prefix of the byte stream is unchanged.
    • No existing test weakened or deleted: the only non-additive edits are the two version pins.
    • Tests assert grid truth, not damage counts, and every discriminating test really fails pre-patch: I ran the new file against a pristine git archive HEAD tree (/tmp/bitty/1903-baseline) and got 11 failed, 2 passed — the only two that pass are the two "the region path is unchanged" guards (index_on_the_region_bottom_margin…, reverse_index_on_the_region_top_margin…), which is exactly the intended result. alt_screen_status_region_does_not_leak_into_primary_after_exit reproduces the report end to end.
    • No fallout in other crates: nothing outside bitty-term-state reads the margins (rg 'scroll_region' crates/bitty-render crates/bitty-runtime crates/bitty-ui → only unrelated test/ident names; runtime/present.rs's scroll_region_copy_tests is damage-shape work, not DECSTBM). Snapshot (state.rs:168-185) carries no margins, so SNAPSHOT_VERSION needs no bump; no persisted/serde state includes ScreenSave.

    Commands run (worktree .worktrees/ctx-1903)

    cargo fmt --all -- --check                                   # OK
    cargo test -p bitty-term-state                                # 271 unit + all integration suites pass, 13/13 new
    cargo clippy -p bitty-term-state --all-targets -- -D warnings  # clean
    

    with CARGO_TARGET_DIR=/tmp/bitty/1903-review-target. Also cargo test --test scroll_region_per_screen on a pristine git archive HEAD tree: 11 failed / 2 passed, i.e. every change-1 and change-2 test is a real regression test. Plus a standalone probe linked against the built rlib for the origin-mode exit path (no invariant violation).

    Required before merge

    1. Drop change 2 (B1) and its two tests; keep change 1 and the rest of the suite untouched.
    2. Correct issue [0.1.0] term-state: scroll margins must be per-screen so a TUI cannot strand the primary screen #3259 §1/§2 and the CTX-1903 title/description (B2).
    3. Record the per-screen margins divergence in bitty-terminal-docs (B3); resolve M1/M2 as either a code tweak or an explicit comment, and fix the wording in M3.
  4. changed the title [-][0.1.0] term-state: the scroll region leaks across alternate-screen switches and freezes the pane[/-] [+][0.1.0] term-state: scroll margins must be per-screen so a TUI cannot strand the primary screen[/+] on Nov 19, 2026
  5. Xuepoo commented on Nov 19, 2026

    @Xuepoo
    ContributorAuthor

    Closeout note (guard tick).

    Merged as 81e6aedb via PR #3260 ([CTX-1903]), CI-green at head 4468fa8f (pass 18 / fail 0 / pending 0). What landed is the D-1 half: ScreenSave stashes the primary margin pair, alternate-screen entry (?47/?1049) gets full margins, exit restores the primary pair clamped on shrink, DECSTR clears the stash and RIS drops it with primary_save. Resize keeps resetting the active screen only (TERM-ENG-005) and clamps the stash.

    Two residuals are not in this PR, so the thread stays traceable:

    1. The divergence record is still owed in docs — filed as bitty-terminal-docs#453 (terminal-state invariants + compatibility matrix entry, naming both divergences: per-screen margins, and the clamped index at a screen edge).
    2. DECSTBM with top == bottom is still accepted here although xterm and ghostty reject it — code-repo [term-state] DECSTBM accepts top == bottom, which xterm and ghostty reject #3261 tracks that parity gap; this PR deliberately left it untouched (it is the pre-existing behaviour, not the reported defect).

    The report in the issue body also asks for a byte-sequence recording before the defect is called closed. The merged tests pin the published wording — "recovers after any alternate-screen TUI exits" (alt_screen_status_region_does_not_leak_into_primary_after_exit) — and the unfixed case (a region installed on the primary screen, cursor on the last row outside it) is pinned by its own guard row, so neither claim is wider than the code. A recording that showed agy drawing its status row on the primary screen would mean this fix is not sufficient for that report; nothing in the merge assumes otherwise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1area:termfix

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions