Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

term,gui: keep the viewport anchored when rows are renumbered under it

RoversX3ea961069885
diff --git a/term/src/screen.rs b/term/src/screen.rs
index a9ff9f37..5fc9b97b 100644
--- a/term/src/screen.rs
+++ b/term/src/screen.rs
@@ -238,7 +238,26 @@ impl Screen {
// screen (hence the check for allow_scrollback), to avoid
// conflicting screen updates with full screen apps.
if self.allow_scrollback {
- self.rewrap_lines(physical_cols, physical_rows, cursor.x, cursor_phys, seqno)
+ let cursor_stable = self.phys_to_stable_row_index(cursor_phys);
+ let (new_x, new_y) =
+ self.rewrap_lines(physical_cols, physical_rows, cursor.x, cursor_phys, seqno);
+ // Rewrapping renumbers every physical row but used to leave
+ // stable_row_index_offset alone, so every StableRowIndex
+ // anyone saved (a GUI viewport, most visibly) silently
+ // pointed at different content — or below scrollback_top,
+ // where stable_range's fallback draws the top of the
+ // buffer. Re-anchor the offset so the cursor row keeps its
+ // stable index across the rewrap: rows near the live
+ // region, which is what viewports are relative to, then
+ // stay put, and the drift is pushed to the far scrollback
+ // where nobody is looking. Best effort: the offset is
+ // unsigned, so a narrowing rewrap on a screen with little
+ // accumulated scroll history can demand a negative anchor
+ // and floors at zero — the renderer's stale-viewport clamp
+ // covers that residue.
+ self.stable_row_index_offset =
+ (cursor_stable.max(0) as usize).saturating_sub(new_y);
+ (new_x, new_y)
} else {
for line in &mut self.lines {
if physical_cols < self.physical_cols {
diff --git a/term/src/test/mod.rs b/term/src/test/mod.rs
index da6f5da8..d630d489 100644
--- a/term/src/test/mod.rs
+++ b/term/src/test/mod.rs
@@ -922,6 +922,38 @@ fn test_alt_screen_shrink_is_top_anchored() {
term.assert_cursor_pos(3, 3, None, None);
}
+/// Rewrapping on a width change renumbers every physical row; the screen
+/// must re-anchor stable_row_index_offset so the cursor row keeps its
+/// stable index, or every saved StableRowIndex (GUI scroll viewports,
+/// most visibly) silently points at different content after a split or
+/// sidebar drag — the "terminal jumped to the top" reports.
+#[test]
+fn test_rewrap_preserves_cursor_stable_row() {
+ let mut term = TestTerm::new(4, 20, 100);
+ // Enough wrapped output to overflow the scrollback and accumulate a
+ // real stable_row_index_offset first: the anchor is unsigned, so it
+ // is exact only once history has scrolled past (the every-day case
+ // for a long-lived pane).
+ for i in 0..200 {
+ term.print(format!("line {i} padding padding\r\n"));
+ }
+ let cursor = term.cursor_pos();
+ let before = term.screen().visible_row_to_stable_row(cursor.y);
+ term.resize(TerminalSize {
+ rows: 4,
+ cols: 10,
+ pixel_width: 0,
+ pixel_height: 0,
+ dpi: 0,
+ });
+ let cursor = term.cursor_pos();
+ let after = term.screen().visible_row_to_stable_row(cursor.y);
+ assert_eq!(
+ before, after,
+ "cursor row must keep its stable index across a rewrap"
+ );
+}
+
/// This test skips over an edge case with cursor positioning,
/// so it passes even ahead of a fix for issue 2162.
#[test]
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 8d194802..2c423e3f 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -1590,6 +1590,56 @@ fn frame_can_acknowledge_output(outcome: PaintOutcome, presented: bool) -> bool
presented && outcome.draw_submitted && outcome.frame_complete
}
+#[cfg(test)]
+mod stale_viewport_tests {
+ use super::TermWindow;
+ use mux::renderable::RenderableDimensions;
+
+ fn dims(scrollback_top: isize, physical_top: isize) -> RenderableDimensions {
+ RenderableDimensions {
+ scrollback_top,
+ physical_top,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn valid_viewports_pass_through_untouched() {
+ assert_eq!(
+ TermWindow::normalize_stale_viewport(None, &dims(100, 500)),
+ None
+ );
+ assert_eq!(
+ TermWindow::normalize_stale_viewport(Some(100), &dims(100, 500)),
+ None
+ );
+ assert_eq!(
+ TermWindow::normalize_stale_viewport(Some(499), &dims(100, 500)),
+ None
+ );
+ }
+
+ #[test]
+ fn overtaken_viewport_clamps_to_oldest_retained_row() {
+ assert_eq!(
+ TermWindow::normalize_stale_viewport(Some(40), &dims(100, 500)),
+ Some(Some(100))
+ );
+ }
+
+ #[test]
+ fn overtaken_viewport_follows_bottom_when_no_scrollback_remains() {
+ // The app erased its scrollback (agent CLIs do this on redraw):
+ // scrollback_top == physical_top, so "the oldest retained row" IS
+ // the live screen and the pane must convert to follow-bottom
+ // rather than stay artificially pinned.
+ assert_eq!(
+ TermWindow::normalize_stale_viewport(Some(40), &dims(500, 500)),
+ Some(None)
+ );
+ }
+}
+
#[cfg(test)]
mod pane_output_watchdog_tests {
use super::{frame_can_acknowledge_output, pane_output_needs_repaint, PaintOutcome};
@@ -9076,6 +9126,29 @@ impl TermWindow {
self.pane_state(pane_id).viewport
}
+ /// If a saved viewport has fallen below the retained scrollback — the
+ /// trim passed it, the app erased its scrollback, or a rewrap
+ /// renumbered rows beyond what the anchor could compensate — produce
+ /// the corrected position: the oldest retained row, or follow-bottom
+ /// when no scrollback remains at all. `None` means the viewport is
+ /// still valid as-is. Kept as a pure function so the policy is
+ /// testable without a TermWindow.
+ pub(crate) fn normalize_stale_viewport(
+ viewport: Option<StableRowIndex>,
+ dims: &RenderableDimensions,
+ ) -> Option<Option<StableRowIndex>> {
+ match viewport {
+ Some(v) if v < dims.scrollback_top => {
+ Some(if dims.scrollback_top >= dims.physical_top {
+ None
+ } else {
+ Some(dims.scrollback_top)
+ })
+ }
+ _ => None,
+ }
+ }
+
pub fn set_viewport(
&mut self,
pane_id: PaneId,
diff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rs
index ed3fb3de..8839a8ba 100644
--- a/wezterm-gui/src/termwindow/render/pane.rs
+++ b/wezterm-gui/src/termwindow/render/pane.rs
@@ -1321,6 +1321,24 @@ impl crate::TermWindow {
.viewport_rows
.saturating_mul(pane_render_metrics.cell_size.height.max(1) as usize);
+ // A saved viewport can still be overtaken (scrollback trimming
+ // passed it, the app erased its scrollback, or a resize renumbered
+ // rows faster than the rewrap anchoring compensates).
+ // stable_range's fallback would then silently draw physical row 0 —
+ // the notorious "terminal jumped to the top". Degrade by one small
+ // step instead, routed through set_viewport so the correction gets
+ // the same normalization as a user scroll (in particular the
+ // conversion to follow-bottom when no scrollback remains) and the
+ // copy/quickselect overlays hear about it.
+ let current_viewport =
+ match Self::normalize_stale_viewport(current_viewport, &dims) {
+ Some(fixed) => {
+ self.set_viewport(pane_id, fixed, dims);
+ fixed
+ }
+ None => current_viewport,
+ };
+
let gl_state = self.render_state.as_ref().unwrap();
let cursor_border_color = palette.cursor_border.to_linear();