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.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
perf(term): reuse bounded rows when scrolling regions
RoversX83753e3a8b05
diff --git a/term/src/screen.rs b/term/src/screen.rsindex 06b45d66..c30798f2 100644--- a/term/src/screen.rs+++ b/term/src/screen.rs@@ -711,6 +711,28 @@ impl Screen {seqno: SequenceNo,blank_attr: CellAttributes,bidi_mode: BidiMode,+ ) {+ // Specialize the loop so row recycling does not add work or keep+ // extra temporaries live in full-screen or styled scrolling.+ if (scroll_region.start != 0 || scroll_region.end as usize != self.physical_rows)+ && blank_attr == CellAttributes::blank()+ {+ self.scroll_up_impl::<true>(scroll_region, num_rows, seqno, blank_attr, bidi_mode);+ } else {+ self.scroll_up_impl::<false>(scroll_region, num_rows, seqno, blank_attr, bidi_mode);+ }+ }++ // Keep the two loops separate; inlining them into the dispatcher makes+ // the ordinary path pay for the recycling path's stack/register usage.+ #[inline(never)]+ fn scroll_up_impl<const RECYCLE: bool>(+ &mut self,+ scroll_region: &Range<VisibleRowIndex>,+ num_rows: usize,+ seqno: SequenceNo,+ blank_attr: CellAttributes,+ bidi_mode: BidiMode,) {let phys_scroll = self.phys_range(scroll_region);let num_rows = num_rows.min(phys_scroll.end - phys_scroll.start);@@ -768,7 +790,14 @@ impl Screen {for _ in 0..to_move {let mut line = self.lines.remove(remove_idx).unwrap();let line = if default_blank == blank_attr {- Line::new(seqno)+ // Keep full-screen output on its existing allocation path:+ // recycling there regresses sustained ASCII mux throughput.+ if RECYCLE && line.len() < self.physical_cols {+ line.reset_for_scrolling(seqno, self.physical_cols);+ line+ } else {+ Line::new(seqno)+ }} else {// Make the line like a new one of the appropriate widthline.resize_and_clear(self.physical_cols, seqno, blank_attr.clone());@@ -1215,3 +1244,6 @@ fn phys_intersection(r1: &Range<PhysRowIndex>, r2: &Range<PhysRowIndex>) -> Rang0..0}}++#[cfg(test)]+mod scroll_tests;diff --git a/term/src/screen/scroll_tests.rs b/term/src/screen/scroll_tests.rsnew file mode 100644index 00000000..c29af367--- /dev/null+++ b/term/src/screen/scroll_tests.rs@@ -0,0 +1,231 @@+//! Compare recycled rows with the pre-optimization scrolling implementation.+use super::*;+use crate::color::{ColorAttribute, ColorPalette};+use wezterm_bidi::ParagraphDirectionHint;++#[derive(Debug)]+struct Config;+impl TerminalConfiguration for Config {+ fn scrollback_size(&self) -> usize {+ 5+ }+ fn color_palette(&self) -> ColorPalette {+ ColorPalette::default()+ }+}++impl Screen {+ fn reference_scroll_up(+ &mut self,+ scroll_region: &Range<VisibleRowIndex>,+ num_rows: usize,+ seqno: SequenceNo,+ blank_attr: CellAttributes,+ bidi_mode: BidiMode,+ ) {+ let phys_scroll = self.phys_range(scroll_region);+ let num_rows = num_rows.min(phys_scroll.end - phys_scroll.start);+ let scrollback_ok = scroll_region.start == 0 && self.allow_scrollback;+ let insert_at_end = scroll_region.end as usize == self.physical_rows;++ debug!(+ "scroll_up {:?} num_rows={} phys_scroll={:?}",+ scroll_region, num_rows, phys_scroll+ );+ // Invalidate the lines that will move before they move so that+ // the indices of the lines are stable (we may remove lines below)+ // We only need invalidate if the StableRowIndex of the row would be+ // changed by the scroll operation. For normal newline at the bottom+ // of the screen based scrolling, the StableRowIndex does not change,+ // so we use the scroll region bounds to gate the invalidation.+ if !scrollback_ok {+ for y in phys_scroll.clone() {+ self.line_mut(y).update_last_change_seqno(seqno);+ }+ }++ // if we're going to remove lines due to lack of scrollback capacity,+ // remember how many so that we can adjust our insertion point later.+ let lines_removed = if !scrollback_ok {+ // No scrollback available for these;+ // Remove the scrolled lines+ num_rows+ } else {+ let max_allowed = self.physical_rows + self.scrollback_size();+ if self.lines.len() + num_rows >= max_allowed {+ (self.lines.len() + num_rows) - max_allowed+ } else {+ 0+ }+ };++ if scroll_region.start == 0 {+ for y in self.phys_range(&(0..num_rows as VisibleRowIndex)) {+ self.line_mut(y).compress_for_scrollback();+ }+ }++ let remove_idx = if scroll_region.start == 0 {+ 0+ } else {+ phys_scroll.start+ };++ let default_blank = CellAttributes::blank();+ // To avoid thrashing the heap, prefer to move lines that were+ // scrolled off the top and re-use them at the bottom.+ let to_move = lines_removed.min(num_rows);+ let (to_remove, to_add) = {+ for _ in 0..to_move {+ let mut line = self.lines.remove(remove_idx).unwrap();+ let line = if default_blank == blank_attr {+ Line::new(seqno)+ } else {+ // Make the line like a new one of the appropriate width+ line.resize_and_clear(self.physical_cols, seqno, blank_attr.clone());+ line.update_last_change_seqno(seqno);+ line+ };+ if insert_at_end {+ self.lines.push_back(line);+ } else {+ self.lines.insert(phys_scroll.end - 1, line);+ }+ }+ // We may still have some lines to add at the bottom, so+ // return revised counts for remove/add+ (lines_removed - to_move, num_rows - to_move)+ };++ // Perform the removal+ for _ in 0..to_remove {+ self.lines.remove(remove_idx);+ }++ if remove_idx == 0 && scrollback_ok {+ self.stable_row_index_offset += lines_removed;+ }++ for _ in 0..to_add {+ let mut line = if default_blank == blank_attr {+ Line::new(seqno)+ } else {+ Line::with_width_and_cell(+ self.physical_cols,+ Cell::blank_with_attrs(blank_attr.clone()),+ seqno,+ )+ };+ bidi_mode.apply_to_line(&mut line, seqno);+ if insert_at_end {+ self.lines.push_back(line);+ } else {+ self.lines.insert(phys_scroll.end, line);+ }+ }++ // If we have invalidated the StableRowIndex, mark all subsequent lines as dirty+ if to_remove > 0 || (to_add > 0 && !insert_at_end) {+ for y in self.phys_range(&(scroll_region.end..self.physical_rows as VisibleRowIndex)) {+ self.line_mut(y).update_last_change_seqno(seqno);+ }+ }+ }+}++#[test]+fn recycled_scrolling_matches_original_rows_and_stable_indices() {+ let config: Arc<dyn TerminalConfiguration> = Arc::new(Config);+ for rows in [1, 3, 8] {+ for allow_scrollback in [false, true] {+ for bidi in [false, true] {+ let mode = BidiMode {+ enabled: bidi,+ hint: ParagraphDirectionHint::LeftToRight,+ };+ let size = TerminalSize {+ rows,+ cols: 12,+ pixel_width: 120,+ pixel_height: rows * 16,+ dpi: 96,+ };+ let mut base = Screen::new(size, &config, allow_scrollback, 1, mode);+ // Exercise both occupied scrollback and a wrapped VecDeque.+ for _ in 0..rows + 9 {+ base.line_mut(base.lines.len() - 1).set_cell_grapheme(+ 0,+ "x",+ 1,+ CellAttributes::default(),+ 2,+ );+ base.reference_scroll_up(+ &(0..rows as i64),+ 1,+ 2,+ CellAttributes::default(),+ mode,+ );+ }+ for row in 0..rows {+ let idx = base.phys_row(row as i64);+ let line = base.line_mut(idx);+ let mut attrs = CellAttributes::default();+ attrs.set_hyperlink(Some(Arc::new(termwiz::hyperlink::Hyperlink::new(+ "https://example.com",+ ))));+ attrs.set_semantic_type(SemanticType::Prompt);+ line.set_cell(+ 0,+ Cell::new_grapheme(["界", "🙂", "e\u{301}"][row % 3], attrs, None),+ 3,+ );+ if row % 4 == 3 {+ line.set_ascii_cells(+ 0,+ &"x".repeat(size.cols),+ &CellAttributes::default(),+ 3,+ );+ }+ if row % 2 == 0 {+ line.cells_mut();+ }+ line.set_double_width(3);+ line.semantic_zone_ranges();+ }+ for start in 0..rows {+ for end in start + 1..=rows {+ for count in [0, 1, 2, rows, rows + 2] {+ for styled in [false, true] {+ let mut blank = CellAttributes::default();+ if styled {+ blank.set_background(ColorAttribute::PaletteIndex(4));+ }+ let mut expected = base.clone();+ let mut actual = base.clone();+ let region = start as i64..end as i64;+ for seqno in [4, 4, 5, 5] {+ expected.reference_scroll_up(+ ®ion,+ count,+ seqno,+ blank.clone(),+ mode,+ );+ actual.scroll_up(®ion, count, seqno, blank.clone(), mode);+ assert_eq!(actual.lines, expected.lines, "rows={rows} region={region:?} count={count} styled={styled} scrollback={allow_scrollback} bidi={bidi}");+ assert_eq!(+ actual.stable_row_index_offset,+ expected.stable_row_index_offset+ );+ }+ }+ }+ }+ }+ }+ }+ }+}diff --git a/wezterm-surface/src/line/clusterline.rs b/wezterm-surface/src/line/clusterline.rsindex b660955c..242ea333 100644--- a/wezterm-surface/src/line/clusterline.rs+++ b/wezterm-surface/src/line/clusterline.rs@@ -93,6 +93,20 @@ where}impl ClusteredLine {+ /// Reuse only small buffers when a discarded screen row becomes blank.+ /// Drop all attributes and wide-cell metadata, including image/link refs.+ pub(crate) fn clear_for_scrolling(&mut self, max_text_capacity: usize) -> bool {+ if self.text.capacity() > max_text_capacity || self.clusters.capacity() > 4 {+ return false;+ }+ self.text.clear();+ self.clusters.clear();+ self.is_double_wide = None;+ self.len = 0;+ self.last_cell_width = None;+ true+ }+pub fn new() -> Self {Self {text: String::with_capacity(80),@@ -435,6 +449,28 @@ impl<'a> Iterator for ClusterLineCellIter<'a> {mod test {use super::*;+ #[test]+ fn scroll_reuse_keeps_small_buffers_but_rejects_large_ones() {+ let mut line = ClusteredLine::new();+ line.append_ascii("abc", &CellAttributes::default());+ let text = line.text.as_ptr();+ let clusters = line.clusters.as_ptr();+ assert!(line.clear_for_scrolling(160));+ assert_eq!(line, ClusteredLine::new());+ assert_eq!(line.text.as_ptr(), text);+ assert_eq!(line.clusters.as_ptr(), clusters);++ line.text.reserve(4096);+ assert!(!line.clear_for_scrolling(160));+ let mut many_styles = ClusteredLine::new();+ for n in 0..16 {+ let mut attrs = CellAttributes::default();+ attrs.set_foreground(wezterm_cell::color::ColorAttribute::PaletteIndex(n));+ many_styles.append_ascii("x", &attrs);+ }+ assert!(!many_styles.clear_for_scrolling(160));+ }+#[test]#[cfg(target_pointer_width = "64")]fn memory_usage() {diff --git a/wezterm-surface/src/line/line.rs b/wezterm-surface/src/line/line.rsindex d3fc394d..d5042735 100644--- a/wezterm-surface/src/line/line.rs+++ b/wezterm-surface/src/line/line.rs@@ -114,6 +114,25 @@ impl Line {}}+ /// Replace a discarded row with the equivalent of `Line::new`, retaining+ /// only bounded compact buffers. Never retain a vector of cells or a large+ /// historical allocation merely because the row has scrolled off screen.+ pub fn reset_for_scrolling(&mut self, seqno: SequenceNo, columns: usize) {+ if let CellStorage::C(cl) = &mut self.cells {+ if cl.clear_for_scrolling(columns.max(80).saturating_mul(2)) {+ self.bits = LineBits::NONE;+ self.seqno = seqno;+ self.zones = Vec::new();+ #[cfg(feature = "appdata")]+ {+ self.appdata = Mutex::new(None);+ }+ return;+ }+ }+ *self = Self::new(seqno);+ }+/// Computes a hash over the line that will change if the way that/// the line contents are shaped would change./// This is independent of the seqno and is based purely on thediff --git a/wezterm-surface/src/line/test.rs b/wezterm-surface/src/line/test.rsindex 09ea506a..90726385 100644--- a/wezterm-surface/src/line/test.rs+++ b/wezterm-surface/src/line/test.rs@@ -8,6 +8,94 @@ use alloc::sync::Arc;use k9::assert_equal as assert_eq;use wezterm_cell::{Cell, CellAttributes};+#[test]+fn scroll_reset_discards_oversized_storage() {+ let mut line = Line::new(1);+ line.set_ascii_cells(0, &"x".repeat(8192), &CellAttributes::default(), 2);+ line.reset_for_scrolling(3, 116);+ assert_eq!(line, Line::new(3));+ match &line.cells {+ super::storage::CellStorage::C(cl) => assert!(cl.text.capacity() <= 232),+ _ => panic!("reset row should use compact storage"),+ }+}++#[cfg(feature = "use_image")]+#[test]+fn scroll_reset_releases_image_references() {+ use wezterm_cell::image::{ImageCell, ImageData, ImageDataType, TextureCoordinate};+ let data = Arc::new(ImageData::with_data(ImageDataType::new_single_frame(+ 1,+ 1,+ vec![255; 4],+ )));+ for vector in [false, true] {+ let mut attrs = CellAttributes::default();+ attrs.attach_image(Box::new(ImageCell::with_z_index(+ TextureCoordinate::new_f32(0.0, 0.0),+ TextureCoordinate::new_f32(1.0, 1.0),+ Arc::clone(&data),+ 0,+ 0,+ 0,+ 0,+ 0,+ Some(3),+ Some(7),+ )));+ let mut line = Line::new(1);+ line.set_cell_grapheme(0, "x", 1, attrs, 1);+ if vector {+ line.cells_mut();+ }+ line.reset_for_scrolling(2, 116);+ assert_eq!(Arc::strong_count(&data), 1);+ assert_eq!(line, Line::new(2));+ }+}++#[test]+fn recycled_rows_match_new_rows_and_release_links_and_cached_data() {+ for text in ["x", "界🙂e\u{301}", "https://example.com", ""] {+ for vector in [false, true] {+ let link = Arc::new(Hyperlink::new("https://example.org"));+ let mut attrs = CellAttributes::default();+ attrs.set_hyperlink(Some(Arc::clone(&link)));+ attrs.set_semantic_type(wezterm_cell::SemanticType::Prompt);+ let mut line = Line::new(7);+ for g in finl_unicode::grapheme_clusters::Graphemes::new(text) {+ let cell = Cell::new_grapheme(g, attrs.clone(), None);+ line.set_cell(line.len(), cell, 7);+ }+ drop(attrs);+ if vector {+ line.cells_mut();+ }+ line.set_double_width(7);+ line.set_bidi_info(true, wezterm_bidi::ParagraphDirectionHint::RightToLeft, 7);+ line.semantic_zone_ranges();+ #[cfg(feature = "appdata")]+ let appdata = Arc::new(123u32);+ #[cfg(feature = "appdata")]+ line.set_appdata(Arc::clone(&appdata));+ line.reset_for_scrolling(9, 116);+ assert_eq!(line, Line::new(9));+ assert!(line.semantic_zone_ranges().is_empty());+ assert_eq!(Arc::strong_count(&link), 1);+ #[cfg(feature = "appdata")]+ {+ assert!(line.get_appdata().is_none());+ assert_eq!(Arc::weak_count(&appdata), 0);+ }+ // Previously-wide rows must also behave like fresh rows on reuse.+ line.set_cell_grapheme(1, "y", 1, CellAttributes::default(), 10);+ let mut expected = Line::new(9);+ expected.set_cell_grapheme(1, "y", 1, CellAttributes::default(), 10);+ assert_eq!(line, expected);+ }+ }+}+// Keep a scalar reference so the fast path is checked against the old behavior,// including less visible state such as hyperlinks, sequence numbers and zones.fn scalar_range(line: &mut Line, range: core::ops::Range<usize>, cell: &Cell, clear: bool) {