Repository navigation
Description
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
- 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). - Keep the index/reverse-index paths as they are.
- 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;?47and the mixed?47h+?1049lpair behave consistently;RIS/DECSTRinteract correctly with the saved pair. - 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:
agyin Swarm mode →Esc→ the shell renders and scrolls normally; a full-screenvimopen/close cycle andclearstay clean.
Activity
Xuepoo commentedon Nov 19, 2026
Verdict: NEEDS-FIX
Independent review of the uncommitted
ctx-1903/fix-scroll-regionworktree (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):TScreen.top_marg/bot_marg(ptyx.h:2833-2834). There is exactly oneTScreen(ptyx.h:3672,TScreen screen;).ToAlternate/FromAlternate(charproc.c:9528-9557) only swap buffer pointers (SwitchBufs), scroll-jump and optionally clear. Neither touchestop_marg/bot_marg.?1049isCursorSave(xw); ToAlternate(xw, True); ClearScreen(xw)and on resetFromAlternate(...); 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 atmax_row— no scroll, no movement.RevIndex(cursor.c:319-340) mirrors it throughCursorUp, which clamps at 0.DECSTRdoes not touch margins at all (ReallyReset's DECSTR branch,charproc.c:14548-14562);RISandDECCOLMdo (resetMargins,charproc.c:1376,7469,4849).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: ScrollingRegionlives onTerminal(Terminal.zig:68), not onScreen.switchScreenMode(Terminal.zig:5749-5830, explicitly derived from xterm'ssrm_ALTBUF*arms) never touchesscrolling_region;saveCursor(Terminal.zig:2703-2717) stores no margins.index()(Terminal.zig:3017, region test at3052-3062): outside the region it moves the cursor down only ifcursor.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
DECSTBMmargins: ACCEPTED as a recorded divergence.smcupwithout a freshsetscrreg). 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.?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 bydispatch'senforce_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.
row == bottom == last_row) and the shell scrolls. The issue's reproduction is entirely explained by the leak.scroll_up_spancapture branch,state.rs:3874-3889, asserted byscroll_up_screen's new test). Under xterm/ghostty/kitty the linefeed is simply discarded and the protected rows stay put.state.rs:3596-3599) is inaccurate: nothing is dropped; the index is discarded and the next glyph overwrites the last row.set_scroll_regionacceptst == b,state.rs:3938-3956; xtermset_tb_marginsrequiresbottom > top,charproc.c:1335-1349, and ghosttyif (top >= bottom) return;,Terminal.zig:3335-3343). That is a parity fix that removes the worst freeze path instead of inventing new scrolling.Findings
crates/bitty-term-state/src/state.rs:3604-3617,3625-3649,3855-3858,3907-3910scroll_up_screen/scroll_down_screenhelpers and the two tests that cover only it).Indexscrolls 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.bitty-terminal-docsspecifications/terminal-state-rfc.md(invariants 4/5),reference/compatibility-matrix.mdlib.rs:54-70, theState::scroll_region_topfield 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.state.rs:4402-4414DECSTRnow clears only the active pair; the stashed primary pair survives. VT510/DEC STD 070 scopeDECSTR's scrolling-region reset to the device, so aDECSTRissued inside a TUI no longer clears what?1049lrestores. Either clear both pairs or state the deliberate scope in the comment (it currently says "active screen's margins cleared" without justifying the asymmetry).RISis fine:full_resetdropsprimary_save.state.rs:745-760vs823-829?1049lthe 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".lib.rs:68-69;state.rs:3596-3599,3618-3624tests/scroll_region_per_screen.rsRIS-with-live-stash test, noDECSTR-inside-alt test, no mixed?47h/?1049lmargins test, no negative test thatSavedScrollRegionInvalidactually fires (a white-box one would prove the check exists rather than trusting it). The reproductions use a one-row regionset_region(.., 0, 0)(:99), a configuration xterm itself rejects; use a 2-row region so the fixture models something a reference terminal accepts.state.rs:3938-3956DECSTBMacceptstop == 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)
?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 atstate.rs:4188-4199), alt re-entry with a retained?47grid (grid kept, margins reset, commented atstate.rs:4129-4137), resize while alt active (stash clamped, never grown/reset),RIS(full_resetdropsprimary_save),DECSTR/DECCOLM(active screen only, commented atstate.rs:4021-4028).top > bottom:state.rs:823-829clampsbottomtorows - 1first, thentoptobottom;resize_with_reportclampsrowsto>= 1(state.rs:595-599), sorows - 1never underflows. The exit path re-clamps defensively (state.rs:4194-4199).state/invariants.rs:29-47, checked atinvariants.rs:220-233, reached byfinalize_batch'sdebug_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.damage_scroll_movewith(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_rowdecremented only for atop == 0span, sync-update bookkeeping untouched. No complexity change:IND/RIstay O(1) for a cursor move and O(rows) for a scroll.scroll_up_region/scroll_down_region;index_on_the_region_bottom_margin_scrolls_only_the_regionand the reverse test pin it.?1049l, hence where the next scroll moves content), so hashing it is justified.CANONICAL_HASH_VERSION = 15is 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 ofout_save_cursor_fields(state/hash.rs:280-286), so the prefix of the byte stream is unchanged.git archive HEADtree (/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_exitreproduces the report end to end.bitty-term-statereads the margins (rg 'scroll_region' crates/bitty-render crates/bitty-runtime crates/bitty-ui→ only unrelated test/ident names;runtime/present.rs'sscroll_region_copy_testsis damage-shape work, notDECSTBM).Snapshot(state.rs:168-185) carries no margins, soSNAPSHOT_VERSIONneeds no bump; no persisted/serde state includesScreenSave.Commands run (worktree
.worktrees/ctx-1903)with
CARGO_TARGET_DIR=/tmp/bitty/1903-review-target. Alsocargo test --test scroll_region_per_screenon a pristinegit archive HEADtree: 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
bitty-terminal-docs(B3); resolve M1/M2 as either a code tweak or an explicit comment, and fix the wording in M3.[-][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[/+][CTX-1903] fix(term-state): keep scroll margins per screen (divergenc…
Xuepoo commentedon Nov 19, 2026
Closeout note (guard tick).
Merged as
81e6aedbvia PR #3260 ([CTX-1903]), CI-green at head4468fa8f(pass 18 / fail 0 / pending 0). What landed is the D-1 half:ScreenSavestashes the primary margin pair, alternate-screen entry (?47/?1049) gets full margins, exit restores the primary pair clamped on shrink,DECSTRclears the stash andRISdrops it withprimary_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:
DECSTBMwithtop == bottomis 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 showedagydrawing its status row on the primary screen would mean this fix is not sufficient for that report; nothing in the merge assumes otherwise.