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
gui: empty the line quad scratch on every exit and cap what it keeps
RoversX6115d00174f1
diff --git a/thinkterm-render/src/quad.rs b/thinkterm-render/src/quad.rsindex 6baa44d3..519c5f9b 100644--- a/thinkterm-render/src/quad.rs+++ b/thinkterm-render/src/quad.rs@@ -712,10 +712,18 @@ impl HeapQuadAllocator {/// draws one per visible card, every frame -- this makes re-recording/// allocation-free.pub fn recycle(&mut self) {- self.layer0.clear();- self.layer1.clear();- self.layer2.clear();- self.position_transform = None;+ // Destructured so that a new field cannot be forgotten here and leak+ // from one recording into the next.+ let Self {+ layer0,+ layer1,+ layer2,+ position_transform,+ } = self;+ layer0.clear();+ layer1.clear();+ layer2.clear();+ *position_transform = None;}/// Move the recording into a new allocator whose vectors have no spare@@ -729,22 +737,31 @@ impl HeapQuadAllocator {/// moved, not cloned: `BoxedQuad::clone` deep-copies every corner/// gradient box, so a clone would trade the doubling slack for an/// allocation per gradient quad.+ ///+ /// The position transform is a recording-time setting (applied as quads+ /// are allocated), so it is cleared on both sides: the finished surface+ /// is only ever replayed, and the recorder starts its next line clean.pub fn take_exact(&mut self) -> Self {- fn drain_exact(src: &mut Vec<BoxedQuad>) -> Vec<BoxedQuad> {- // with_capacity + extend rather than collect: the exactness is+ fn move_exact(src: &mut Vec<BoxedQuad>) -> Vec<BoxedQuad> {+ // with_capacity + append rather than collect: the exactness is// the point, and must not depend on an iterator specialisation.let mut out = Vec::with_capacity(src.len());- out.extend(src.drain(..));+ out.append(src);out}- let out = Self {- layer0: drain_exact(&mut self.layer0),- layer1: drain_exact(&mut self.layer1),- layer2: drain_exact(&mut self.layer2),- position_transform: self.position_transform,- };- self.position_transform = None;- out+ let Self {+ layer0,+ layer1,+ layer2,+ position_transform,+ } = self;+ *position_transform = None;+ Self {+ layer0: move_exact(layer0),+ layer1: move_exact(layer1),+ layer2: move_exact(layer2),+ position_transform: None,+ }}/// Estimated resident heap bytes for the recorded quads. Counts vector@@ -1062,7 +1079,6 @@ impl TripleLayerQuadAllocatorTrait for HeapQuadAllocator {let src_quads: &[[Vertex; VERTICES_PER_CELL]] =unsafe { std::slice::from_raw_parts(vertices.as_ptr().cast(), vertices.len() / 4) };- dest_quads.reserve(src_quads.len());for quad in src_quads {let mut quad = BoxedQuad::from_vertices(quad);if let Some(transform) = position_transform {@@ -1090,7 +1106,7 @@ fn size() {#[cfg(test)]fn record_quads(heap: &mut HeapQuadAllocator, per_layer: [usize; 3]) {- let mut layers = heap;+ let layers = heap;for (layer_num, count) in per_layer.into_iter().enumerate() {for i in 0..count {let x = (layer_num * 1000 + i * 10) as f32;@@ -1106,14 +1122,13 @@ fn take_exact_produces_exact_capacity_and_keeps_the_scratch_buffers() {let mut scratch = HeapQuadAllocator::default();record_quads(&mut scratch, [5, 3, 0]);let grown = scratch.resident_bytes();- // Doubling from zero leaves slack behind; that slack is the point.- assert!(grown > 8 * std::mem::size_of::<BoxedQuad>());let out = scratch.take_exact();assert_eq!(out.quad_count(), 8);assert_eq!(out.resident_bytes(), 8 * std::mem::size_of::<BoxedQuad>());assert_eq!(scratch.quad_count(), 0);assert_eq!(scratch.resident_bytes(), grown, "the scratch keeps its buffers");+ assert!(grown >= out.resident_bytes());}#[cfg(test)]@@ -1135,7 +1150,7 @@ fn take_exact_preserves_layer_assignment_and_recorded_order() {fn take_exact_moves_corner_gradients_intact() {let mut scratch = HeapQuadAllocator::default();{- let mut layers = &mut scratch;+ let layers = &mut scratch;let mut quad = layers.allocate(1).unwrap();quad.set_corner_gradient(LinearRgba::with_components(0.1, 0.0, 0.0, 1.0),@@ -1183,24 +1198,28 @@ fn a_recycled_scratch_records_the_same_surface_as_a_fresh_allocator() {#[cfg(test)]#[test]-fn take_exact_clears_the_position_transform() {+fn take_exact_clears_the_position_transform_on_both_sides() {let source = QuadClipRect::from_top_left_pixels(0.0, 0.0, 100.0, 100.0, &TEST_ORIGIN);let target = QuadClipRect::from_top_left_pixels(0.0, 0.0, 200.0, 200.0, &TEST_ORIGIN);let mut scratch = HeapQuadAllocator::default();{- let mut layers = &mut scratch;+ let layers = &mut scratch;layers.set_position_transform(Some(QuadPositionTransform::new(source, target).unwrap()));let mut quad = layers.allocate(0).unwrap();quad.set_position(10.0, 10.0, 20.0, 20.0);}- let out = scratch.take_exact();+ let mut out = scratch.take_exact();+ // Recorded under the transform, so mapped.assert_eq!(out.layer0[0].position, (20.0, 20.0, 40.0, 40.0));- {- let mut layers = &mut scratch;- let mut quad = layers.allocate(0).unwrap();+ // Neither side keeps the transform: a quad recorded into either+ // afterwards lands where it was placed.+ for heap in [&mut scratch, &mut out] {+ let layers = heap;+ let mut quad = layers.allocate(1).unwrap();quad.set_position(10.0, 10.0, 20.0, 20.0);}- assert_eq!(scratch.layer0[0].position, (10.0, 10.0, 20.0, 20.0));+ assert_eq!(scratch.layer1[0].position, (10.0, 10.0, 20.0, 20.0));+ assert_eq!(out.layer1[0].position, (10.0, 10.0, 20.0, 20.0));}#[cfg(test)]diff --git a/wezterm-gui/src/glyphcache.rs b/wezterm-gui/src/glyphcache.rsindex 2768be9f..850dbe72 100644--- a/wezterm-gui/src/glyphcache.rs+++ b/wezterm-gui/src/glyphcache.rs@@ -662,9 +662,10 @@ pub struct GlyphCacheStats {}impl GlyphCache {- /// Entry count only; `stats()` builds strings and is not per-frame- /// material. This is the counter for the one unbounded map in the- /// renderer, which is only cleared when the atlas is rebuilt.+ /// Entry count of the main glyph map only; `stats()` builds strings and+ /// is not per-frame material. Like the other maps in this struct it is+ /// unbounded and only cleared when the atlas is rebuilt; it is the one+ /// that grows with the text being rendered.pub fn glyph_entries(&self) -> usize {self.glyph_cache.len()}diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 56b897fd..bb46509b 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -2419,9 +2419,14 @@ pub struct TermWindow {/// steady state allocation-free apart from the exact-size copy that/// becomes the entry.///- /// Exactly one line is recorded at a time: `LineRender::render_line` is- /// the only borrower and nothing under `render_screen_line` re-enters- /// it, so a double borrow would be a real bug and should panic.+ /// Exactly one line is recorded at a time: `LineRender::render_line`+ /// borrows it for the duration of a line and nothing under+ /// `render_screen_line` re-enters it (it falls back to a private+ /// allocator if that ever changes). The other borrowers, the perf+ /// counter and the occlusion release, run outside a paint. Empty+ /// between lines; its buffers are capped by+ /// `LINE_QUAD_SCRATCH_MAX_BYTES` in pane.rs and dropped when the window+ /// is occluded.line_quad_scratch: RefCell<HeapQuadAllocator>,last_status_call: Instant,@@ -2998,6 +3003,13 @@ impl TermWindow {self.pane_font_cache.borrow().len(),self.semantic_zones.len(),));+ lines.push(format!(+ "{label}: line_quad_scratch={}KiB (entries are stored at exact size; line_quad above no longer includes doubling slack)",+ self.line_quad_scratch+ .try_borrow()+ .map_or(0, |scratch| scratch.resident_bytes())+ / 1024,+ ));{let ui = self.ui_shape_caches.borrow();lines.push(format!(diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex e3f8d2db..70b0a3d7 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -935,9 +935,16 @@ impl crate::TermWindow {"glyph_cache_entries",glyphs.glyph_entries(),);- crate::perf::log_counter("atlas_side", glyphs.atlas.size());+ // Texel counts, not bytes: the atlas is+ // side x side x 4 bytes, and allocated_px+ // is a high-water mark of packed area+ // that only Atlas::clear resets.crate::perf::log_counter(- "atlas_packed_px",+ "atlas_side_texels",+ glyphs.atlas.size(),+ );+ crate::perf::log_counter(+ "atlas_allocated_texels_high_water",glyphs.atlas.usage().allocated_px,);}diff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rsindex 89513880..d2eb4569 100644--- a/wezterm-gui/src/termwindow/render/pane.rs+++ b/wezterm-gui/src/termwindow/render/pane.rs@@ -125,6 +125,12 @@ const COLLAPSED_EDGE_PADDING: usize = 8;/// Gap the collapsed strip leaves between its tabs and its action button.const COLLAPSED_SECTION_GAP: usize = 10;+/// Most the line quad scratch recorder may keep between lines. A line of+/// ordinary width needs a few tens of KiB across its three layers; one+/// exceptionally wide line grows the buffers past this and they are+/// released rather than pinned for the window's life.+const LINE_QUAD_SCRATCH_MAX_BYTES: usize = 512 * 1024;+impl crate::TermWindow {/// Height of the nav bar for this pane: the metric height, clamped so/// that at least one terminal row of the pane's cell remains visible.@@ -1939,10 +1945,13 @@ impl crate::TermWindow {// Recorded into the window's one scratch recorder and// moved out at exact size below, rather than growing a// fresh allocator from zero on every miss. Recycled on- // entry so an early `?` return leaves nothing stale.+ // entry as well as on exit, so an early `?` return+ // leaves nothing stale for the next line.// No painter re-enters this while a line is being- // recorded; should one ever do so, that line falls back- // to a private allocator rather than panicking mid-paint.+ // recorded (the only other borrowers run outside a+ // paint); should one ever do so, that line falls back to+ // a private allocator rather than panicking mid-paint,+ // which costs the old doubling churn for that line only.let mut scratch_guard = self.term_window.line_quad_scratch.try_borrow_mut();let mut fallback = HeapQuadAllocator::default();let buf: &mut HeapQuadAllocator = match scratch_guard.as_mut() {@@ -2049,7 +2058,6 @@ impl crate::TermWindow {None},};- drop(scratch_guard);let weight = crate::termwindow::render::estimate_line_quad_entry_bytes(&quad_key,&quad_value,@@ -2058,6 +2066,17 @@ impl crate::TermWindow {.line_quad_cache.borrow_mut().put_weighted(quad_key, quad_value, weight);+ } else {+ // Not cached: leave the scratch empty rather than+ // holding this line's quads until the next miss.+ buf.recycle();+ }+ // The scratch keeps its buffers between lines on purpose,+ // but one unusually wide line must not pin them for the+ // life of the window (only macOS and Windows report the+ // occlusion that otherwise releases it).+ if buf.resident_bytes() > LINE_QUAD_SCRATCH_MAX_BYTES {+ *buf = HeapQuadAllocator::default();}Ok(())