Skip to content

[CTX-1456] [0.0.27] fix(term-state): preserve rows and anchors across resize (#2529) - #2534

Merged
Xuepoo merged 5 commits into
mainfrom
ctx-1456/fix-resize-reflow
Oct 23, 2026
Merged

Xuepoo merged 5 commits into
mainfrom
ctx-1456/fix-resize-reflow

Conversation

@Xuepoo

@Xuepoo Xuepoo commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #2529: resizing a panel width/height permanently corrupted terminal output. A height-only resize used the primary grid's truncate/pad primitive, which drops the newest viewport rows (the bottom) instead of moving the oldest rows into scrollback. A divider drag that momentarily solved a pane to a single row therefore kept only that one row and destroyed everything above it; growing back just padded blanks, so the content never recovered. Width reflow additionally trimmed spaces at soft-wrap boundaries, merging words on the next unwrap.

Priority: P1 | Area: render | Labels: fix, P1, area:render | Milestone: v0.0.27 | RFC: — | Task: CTX-1456

Closes #2529

Root cause

  • State::resize height-only branch called Grid::resize for the primary grid, which copies the top new_rows and discards the bottom. No scrollback capture, no round-trip.
  • take_logical_lines trimmed trailing blanks on every physical segment, including soft-wrap continuations, so a space printed in the last column disappeared when the logical line was unwrapped at a wider size.
  • Kitty placements kept their old cell anchors across row rebuilds, and wide reflow invalidated them entirely.

Changes

  • Height-only primary resize now moves rows, never content off the end (State::resize_height_only):
    • shrink absorbs unused padding below the used height first (tmux-style used-height accounting), then moves the remaining oldest rows into scrollback with their soft-wrap flags;
    • grow is bottom-anchored when the viewport is full: the newest history rows re-enter the grid (blank filler only when history runs out); otherwise it pads below the cursor so top-aligned output stays put;
    • cursor, saved cursor, primary-save cursor, and alt-screen bounds stay coherent.
  • Width reflow preserves wrap-boundary spaces: only the final segment of a logical line drops trailing padding; continuation segments keep their spaces, so words never merge.
  • Image placements: height changes shift primary placements with their content and clip rows that left the viewport; width reflow clears anchored placements safely while U=1 virtual prototypes (and image data) survive.
  • Inspection: State::row_soft_wrapped(row) exposes the continuation bit used by tests/accessibility to join physical rows into logical lines.
  • Alt screen keeps the application-owned truncate/pad policy and remains bounded.

Selection anchors continue through the existing clamp_view_bindings_to_geometry path; a width reflow bumps buffer_epoch, so stale zone anchors fail closed instead of resolving onto new content.

Tests

New deterministic coverage in crates/bitty-term-state/tests/resize_reflow_2529.rs:

  • height-only shrink keeps the newest output and round-trips every line in order;
  • transient one-row viewport never squashes rows into one line;
  • top-aligned content does not drift when growing;
  • width round-trip preserves a space in the final column of a soft-wrapped line;
  • ls/Markdown fixture survives 80 -> 33 -> 120 -> 41 -> 80 with exact logical lines;
  • 40 wide CJK glyphs + combining mark survive odd widths (41/23/1/80) with no orphan halves;
  • OSC 8 hyperlink ids travel with every cell across a width round-trip and the table entry still resolves;
  • image placement follows height, restores on grow, and clears safely (prototype retained) on width reflow;
  • alt-screen aggressive resize stays bounded and primary history survives.

New runtime test two_pane_height_resize_roundtrips_pane_content reproduces the multi-panel divider drag on a real pane session and proves the content round-trips.

Commands run (scoped CARGO_TARGET_DIR=/mnt/data/Workspace/Projects/bitty-terminal/.targets/ctx-reflow):

cargo test -p bitty-term-state                                  # 224 lib + all integration suites: ok
cargo test -p bitty-ui --test resize_scrollback                 # 13 passed
cargo test -p bitty-runtime --test resize_scrollback            # 5 passed
cargo test -p bitty-runtime --test border_drag_resize ...       # 20/4/5/9 passed
cargo test -p bitty-terminal --bin bitty reflow                 # 2 passed
RUSTFLAGS="-D warnings" cargo clippy -p bitty-term-state -p bitty-ui -p bitty-runtime --all-targets
cargo fmt --all -- --check && git diff --check

Live evidence

Headless runtime with a real /bin/sh PTY (isolated HOME/XDG under /tmp), ls --color=never plus a Markdown cat that soft-wraps, resized through three geometries and back:

===== initial 87x30 =====
alpha.txt  cache   data          gamma.log  README.md
beta.md    config  evidence.txt  home       state

--- README ---
# Bitty resize evidence

This Markdown paragraph is long enough to soft-wrap across several physical rows whe
n the panel is narrow, and it must stay readable after width and height changes.

- item one
- item two
- item three

END-2529

===== narrow 60x16 =====
beta.md    config  evidence.txt  home       state

--- README ---
# Bitty resize evidence

This Markdown paragraph is long enough to soft-wrap acros
s several physical rows when the panel is narrow, and it
must stay readable after width and height changes.

- item one
- item two
- item three

END-2529

===== wide 120x40 =====
alpha.txt  cache   data          gamma.log  README.md
beta.md    config  evidence.txt  home       state

--- README ---
# Bitty resize evidence

This Markdown paragraph is long enough to soft-wrap across several physical rows when the panel is narrow, and it mus
t stay readable after width and height changes.

- item one
- item two
- item three

END-2529

===== restored 87x30 =====
(identical non-empty rows to the initial capture; all four fixture names and END-2529 present)

Notes

  • A one-column reflow still degrades a wide glyph to width 1 by the existing bounded-representation rule; text is preserved and widening restores readable ASCII, but wide pairs cannot re-expand from a one-column grid.
  • Repeated drags through tiny heights now churn scrollback ids (rows move out and back) instead of losing data; the buffer's configured capacity remains the only bound.

@Xuepoo Xuepoo added this to the v0.0.27 milestone Oct 22, 2026
@Xuepoo Xuepoo added fix Bug fix P1 Priority: high area:render Area: rendering labels Oct 22, 2026
@coderabbitai

coderabbitai Bot commented Oct 22, 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 2 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: 50870609-6836-49ce-a995-d23124b6a1f8
📥 Commits

Reviewing files that changed from the base of the PR and between 7173d7e and 3e5f37f.

📒 Files selected for processing: 11
  • crates/bitty-runtime/tests/resize_scrollback.rs
  • crates/bitty-term-state/src/canonical.rs
  • crates/bitty-term-state/src/cell.rs
  • crates/bitty-term-state/src/grid.rs
  • crates/bitty-term-state/src/lib.rs
  • crates/bitty-term-state/src/placement.rs
  • crates/bitty-term-state/src/scrollback.rs
  • crates/bitty-term-state/src/state.rs
  • crates/bitty-term-state/src/state/tests.rs
  • crates/bitty-term-state/tests/resize_reflow_2529.rs
  • crates/bitty-ui/src/selection.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

Comment @coderabbitai help to get the list of available commands.

@Xuepoo
Xuepoo force-pushed the ctx-1456/fix-resize-reflow branch 3 times, most recently from 685c74d to 9ea2502 Compare October 22, 2026 19:16

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

Independent review — NEEDS-FIX

Reviewed head acb425cb (base 23a7acb1, 6 files, +894/−19) for 0.0.27 / #2529. No changes pushed, nothing merged.

Method: full diff read, targeted suites on the PR head, plus a pre-fix spot check in a separate worktree where source was reverted to 23a7acb1 and only the new test files were kept (the lone new accessor row_soft_wrapped was shimmed so the tests compile). Scoped CARGO_TARGET_DIR=.targets/review-2534.

Verified behavior

  • Height-only shrink/grow keeps rows and order. Shrink absorbs unused rows below the used height first, then pushes the oldest rows into scrollback with their wrap flags; grow re-enters the newest history rows bottom-anchored. The newest viewport rows are never dropped. push ≤ used − new_rows and absorb ≤ old_rows − used, so remove_top_rows/truncate_bottom can never empty the grid — verified by construction and by invariant checks on every probe resize.
  • Cursor / saved cursor / primary-save. Live cursor, saved_cursors[0], and the alt-screen primary_save cursor all shift with the primary content; the live alt cursor is clamped. enforce_cursor_invariants + the post-resize check_invariants debug assert hold on all tested paths.
  • Extremes. resize(usize::MAX, usize::MAX) clamps to 1000×1000, resize(0,0) clamps to 1×1, and 80×24 → 1000×1000 → 1×1 → 80×24 round-trips all 50 fixture lines with no panic and no invariant failure. Same with the alt screen active (1×1 and back, primary content preserved).
  • No reflow when the width is unchanged. The cols == old_cols branch never calls take_logical_lines; wrap flags and row text are unchanged across a height shrink/grow (probe over 40 wrapped lines).
  • Bounded. 10 000-line scrollback width reflow: 8.7 ms narrow / 17.4 ms widen (release, 79→80) vs 2 000 lines: 1.5 ms / 2.7 ms — ≈linear in cells, no quadratic term. Height-only shrink+grow: ~14 µs per pair at both 2 k and 10 k scrollback lines (independent of history depth). Height-only time is O(rows·cols) for the used-height scan plus the row moves; width reflow is unchanged O(total cells).
  • Images. Height shifts primary anchors with the content, restores on grow, clips rows that left the viewport; width reflow clears anchors and keeps U=1 virtual prototypes and image data. Alt placements are only clipped. Test and probe agree.
  • Alt screen. Keeps the application-owned truncate/pad path and stays bounded; primary history survives repeated aggressive resizes.
  • Pre-fix spot check (source reverted, tests kept): 5 of 9 new tests fail — height_only_shrink_keeps_newest_output_and_roundtrips, transient_one_row_height_never_squashes_output, width_roundtrip_preserves_wrap_boundary_spaces, width_roundtrip_preserves_ls_and_markdown_output, image_placement_follows_height_and_clears_on_width_reflow; 4 pass pre-fix (alt screen, hyperlink, wide-count, top-aligned). The tests genuinely gate the fix.

Blocker — progressive space insertion into wide-glyph (CJK/emoji) text

take_logical_lines now keeps every trailing blank on a soft-wrapped segment (trim_owned(&mut segment, !wrapped)), but rewrap_one_logical itself synthesizes a padding blank when a width-2 glyph straddles the right margin (if w == 2 && used + 1 == new_cols { push erased; flush wrapped }). The next unwrap therefore reads that padding as real content, and every pass through a width where a wide glyph lands at the margin materializes one space.

Deterministic repro (bitty-term-state; logical() joins rows via row_soft_wrapped and keeps intermediate boundary spaces):

let mut s = State::new();
prints(&mut s, "这是一段很长的中文段落,用来检查窗口宽度变化时是否会在字符之间插入多余的空格,从而破坏可复制文本。");
newline(&mut s);
let start = logical(&s);                    // exact printed paragraph
for _ in 0..5 { s.resize(37, 24); s.resize(80, 24); }
let end = logical(&s);
// end: "…中文段落,用来检查窗口 宽度变化时是否会在字符之间插入多余的 空格…"
// start != end — two spaces inserted

Simpler one-step form: print AAAA中 at width 5, then resize(80, 24) → the line becomes AAAA 中.

  • The same cycles on the pre-fix source are exact (that probe passes at 23a7acb1), so this is a regression introduced by this PR, not pre-existing behavior.
  • It changes visible and copy/search text — the exact “logical line corrupted by resize” class the issue targets — and issue #2529 explicitly names wide glyphs.
  • The new wide_and_combining_glyphs_survive_odd_width_roundtrip test cannot see it: it only counts 中 and asserts no orphan halves, not exact text.

Suggested direction: keep synthetic padding distinguishable from content. Either drop at most one trailing blank per wrapped segment only when the next segment starts with a width-2 lead at column 0 (this case; reflow padding is always exactly one blank), or mark padded cells in rewrap_one_logical and trim only marked cells. Both keep the PR's 79×'a' + space + "tail" case intact. Add an exact-text test (long CJK paragraph, repeated 37↔80 cycles, assert equality with the printed line) and tighten the existing wide test to compare exact logical text, not glyph counts.

Non-blocking findings (follow-ups)

  1. Selection does not follow the height-driven content shift. clamp_view_bindings_to_geometry only clamps to the new bounds; Selection is stored in grid/viewport coordinates, so after a shrink/grow a held selection keeps its coordinates while the content moves under it (copy/search text silently changes identity). Zone/search anchors already fail closed via buffer_epoch; either shift the selection by the resize delta or drop it on height change. The PR body’s “selection anchors continue through the existing path” is only true for bounds, not content.
  2. Stale scrollback.rs module doc: “Lines enter scrollback only via scroll-under-region operations” and “contents are immutable once written. The single exception is wholesale removal by ED 3 / FullReset” are now false — height-only resize pushes rows, clear_last_wrap mutates the newest line, and pop_back_line removes it.
  3. resize_scrollback is not in the nextest live-pty group even though it now spawns a real /bin/sh PTY; .config/nextest.toml states that group covers “runtime integration harnesses that spawn shells”. Low flake risk today (no polling), but the grouping should be consistent.
  4. Cursor-detach edge case: when non-blank content exists below the cursor, a shrink larger than the absorbable padding pushes the cursor’s own row into scrollback and the cursor clamps to row 0 (content intact, cursor no longer on its row). Rare; document or clamp against the cursor’s materialized row.
  5. 1-column reflow + line-count scrollback cap: a 1×1 round trip repacks history into ~80× more physical rows, so deep scrollback is pruned by max_lines (500-line fixture: 586 → 225 rows after 1×1). Bounded-memory tradeoff, not new, but worth a note next to the existing wide-pair limitation.

Gates run on acb425cb

cargo test -p bitty-term-state                                  # 224 lib + all integration suites: pass
cargo test -p bitty-runtime --test resize_scrollback            # 5 passed (incl. new two-pane test)
cargo test -p bitty-ui --test resize_scrollback                 # 13 passed
cargo test -p bitty-terminal --bin bitty reflow                 # 2 passed
rustfmt --check (6 changed files); git diff --check              # clean
cargo clippy -p bitty-term-state -p bitty-runtime -p bitty-ui --all-targets -- -D warnings  # exit 0

Remote CI is green on this head and CodeRabbit was rate-limited (no review comments to disposition). Approval is blocked only on the wide-glyph padding item above.

@Xuepoo

Xuepoo commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the wide-glyph padding blocker in head 7cc3fd96. Cell::padding now distinguishes synthesized layout/erase cells from printed spaces, and both reflow collection and cursor row bookkeeping trim only marked padding. Added exact CJK paragraph 37↔80 repeated-cycle coverage, emoji/mixed ASCII/meaningful-space coverage, width-4/5/6 margin-boundary cases, exact wide+combining text assertion, and selection-copy regressions for the Chinese repro and mixed emoji text over five repeated cycles. Focused term-state, UI resize, runtime resize, selection-copy tests, fmt and Clippy pass. No heuristic stripping of user spaces. No merge.

@Xuepoo
Xuepoo force-pushed the ctx-1456/fix-resize-reflow branch from acb425c to 7cc3fd9 Compare October 23, 2026 03:45
@Xuepoo

Xuepoo commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the canonical-hash finding in head dedd6e54. write_cell now serializes Cell::padding, and the canonical hash version is bumped to v12 with the established cumulative version history documented in canonical.rs; the public crate-level register and pin test are synchronized. Added layout_padding_marker_changes_state_hash, which clones an otherwise-identical State and toggles only the padding marker, asserting different hashes. Fixture/compatibility search found no checked-in state-hash golden values; only version references were canonical.rs and the stale crate register (now updated). Verified canonical tests (2), padding hash regression (1), all 12 resize_reflow_2529 tests, fmt, git diff --check, and cargo clippy -p bitty-term-state --all-targets --locked -- -D warnings. Bounded target was cleaned. No full CI run due disk pressure; no merge.

…2529)

Height-only resizes used the truncate/pad primitive on the primary grid,
dropping the newest viewport rows. A divider drag that momentarily solved
a pane to one row destroyed everything above the cursor row, and growing
back only padded blanks, so the content never recovered.

- Shrink now absorbs unused padding below the used height, then moves the
  remaining oldest rows into scrollback with their wrap flags. Grow is
  bottom-anchored when the viewport is full: the newest history rows re-enter
  the grid (blank filler only when history is exhausted).
- Width reflow keeps spaces at soft-wrap boundaries (only the final segment
  of a logical line drops trailing padding), so narrowing/widening no longer
  merges words.
- Kitty placements follow height shifts, clip when they no longer fit, and
  are cleared safely on width reflow while virtual prototypes survive.
- Add State::row_soft_wrapped for logical-line inspection.
- Regression tests: height-only round-trip, transient one-row viewport,
  width round-trip with boundary spaces, ls/Markdown fixtures, wide glyphs
  plus combining marks at odd widths, image placement, alt-screen bounds,
  and a two-pane runtime divider round-trip.
…exact (#2529)

The 37<->80 reflow regression inserted spaces between CJK/emoji glyphs:
`rewrap_one_logical` synthesizes a margin pad when a width-2 glyph does
not fit in the last column, and the previous trailing-blank preservation
treated that pad as content on the next unwrap.

Distinguish padding from printed content at the cell level:

- `Cell::padding` is true for erased/grid-fill/rewrap filler blanks and
  false for application output (including printed spaces).
- `take_logical_lines` drops trailing padding cells from every physical
  segment, so synthetic margin pads vanish while real spaces at a wrap
  boundary survive exactly.
- Rewrap copies printed cells verbatim; only fillers are erased/padding.

Tests added first (they failed on the prior head, including the reviewer's
paragraph repro and the `AAAA中` one-step case): exact CJK 37<->80 cycles,
emoji + mixed ASCII + real space runs through boundary widths and a
one-column pass, and the synthetic-pad versus printed-space distinction.
The wide/combining test now also compares exact logical text.
@Xuepoo
Xuepoo force-pushed the ctx-1456/fix-resize-reflow branch from dedd6e5 to 3e5f37f Compare October 23, 2026 04:17
@Xuepoo
Xuepoo merged commit 2289df4 into main Oct 23, 2026
20 checks passed
@Xuepoo
Xuepoo deleted the ctx-1456/fix-resize-reflow branch October 23, 2026 05:01
Xuepoo added a commit that referenced this pull request Oct 23, 2026
Semantic merge conflict between #2534 (new Cell::padding field) and #2506 (wide-glyph selection fixture) left main failing E0063 at present.rs:7480. The fixture is a real printed glyph, so padding is false.
Xuepoo added a commit that referenced this pull request Oct 23, 2026
#2551)

* [CTX-1464] [0.0.27] fix(runtime,term-state): remap selections on height resize (#2543)

* [CTX-1464] [0.0.27] fix(term-state): correct cursor-detach condition and add regression (#2543)

* [CTX-1464] [0.0.27] fix(test): gate Selection import for Windows (#2543)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:render Area: rendering fix Bug fix P1 Priority: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[0.0.27] Resizing panels permanently corrupts/reflows terminal output

1 participant