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
Optimize Note and file preview rendering
RoversX246baa055298
diff --git a/config/src/config.rs b/config/src/config.rsindex d3085557..bc8a9c8d 100644--- a/config/src/config.rs+++ b/config/src/config.rs@@ -729,6 +729,11 @@ pub struct Config {/// network-address limits.#[dynamic(default = "default_true")]pub note_remote_images_enabled: bool,+ /// Maximum reading width of the Note editor text column, in design+ /// pixels (2x Retina pixels on macOS). The column is centered when the+ /// Note area is wider than this.+ #[dynamic(default = "default_note_reading_max_width")]+ pub note_reading_max_width: usize,#[dynamic(default)]pub xim_im_name: Option<String>,#[dynamic(default)]@@ -2288,6 +2293,10 @@ fn default_glyph_cache_image_cache_size() -> usize {256}+fn default_note_reading_max_width() -> usize {+ 820+}+fn default_shape_cache_size() -> usize {1024}diff --git a/lfucache/src/lib.rs b/lfucache/src/lib.rsindex c2b32d79..984d6dbd 100644--- a/lfucache/src/lib.rs+++ b/lfucache/src/lib.rs@@ -16,10 +16,23 @@ struct Entry<K, V> {frequency_link: RBTreeLink,freq: RefCell<u16>,last_tick: RefCell<u32>,+ /// Caller-estimated resident size for byte-budgeted caches; 0 for+ /// entries inserted through the unweighted `put`.+ weight: usize,key: K,value: V,}+/// What happened structurally during a `put_weighted` call, so callers can+/// maintain their own cheap diagnostics counters.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]+pub struct PutOutcome {+ /// The entry alone exceeded the whole byte budget and was not cached.+ pub rejected_oversize: bool,+ pub evicted_entries: usize,+ pub evicted_bytes: usize,+}+intrusive_adapter!(RecencyAdapter<K,V> = Rc<Entry<K,V>>: Entry<K,V> { recency_link: LinkedListLink });intrusive_adapter!(FrequenceAdapter<K,V> = Rc<Entry<K,V>>: Entry<K,V> { frequency_link: RBTreeLink });intrusive_adapter!(HashAdapter<K,V> = Rc<Entry<K,V>>: Entry<K,V> { hash_link: LinkedListLink });@@ -55,6 +68,11 @@ pub struct LfuCache<K, V, S = BuildHasherDefault<AHasher>> {len: usize,/// tracks number of operations that affect the frequency/age of entriestick: u32,+ /// Sum of entry weights; only meaningful for byte-budgeted caches.+ total_weight: usize,+ /// Optional byte budget; `None` preserves the classic count-only cache.+ byte_budget: Option<usize>,+ byte_budget_func: Option<CapFunc>,}impl<K: Hash + Eq + Clone + Debug, V, S: Default + BuildHasher> LfuCache<K, V, S> {@@ -82,10 +100,20 @@ impl<K: Hash + Eq + Clone + Debug, V, S: Default + BuildHasher> LfuCache<K, V, Srecency_index: LinkedList::new(RecencyAdapter::new()),len: 0,tick: 0,+ total_weight: 0,+ byte_budget: None,+ byte_budget_func: None,hasher,}}+ #[cfg(test)]+ fn with_capacity_and_budget(cap: usize, budget: usize) -> Self {+ let mut cache = Self::with_capacity(cap);+ cache.byte_budget = Some(budget);+ cache+ }+pub fn new(hit: &'static str,miss: &'static str,@@ -111,10 +139,32 @@ impl<K: Hash + Eq + Clone + Debug, V, S: Default + BuildHasher> LfuCache<K, V, Srecency_index: LinkedList::new(RecencyAdapter::new()),len: 0,tick: 0,+ total_weight: 0,+ byte_budget: None,+ byte_budget_func: None,hasher,}}+ /// A cache limited both by entry count and by a byte budget; use+ /// `put_weighted` to insert entries carrying a resident-size estimate.+ pub fn new_weighted(+ hit: &'static str,+ miss: &'static str,+ cap_func: CapFunc,+ byte_budget_func: CapFunc,+ config: &ConfigHandle,+ ) -> Self {+ let mut cache = Self::new(hit, miss, cap_func, config);+ cache.byte_budget = Some(byte_budget_func(config));+ cache.byte_budget_func = Some(byte_budget_func);+ cache+ }++ pub fn total_weight(&self) -> usize {+ self.total_weight+ }+fn bucket_for_key<Q: Hash>(&self, k: &Q) -> usize {let mut hasher = self.hasher.build_hasher();k.hash(&mut hasher);@@ -147,8 +197,22 @@ impl<K: Hash + Eq + Clone + Debug, V, S: Default + BuildHasher> LfuCache<K, V, Slet new_cap = (self.cap_func)(config);if new_cap != self.cap {self.cap = new_cap;- while self.len > self.cap {- self.evict_one();+ }+ if let Some(budget_func) = self.byte_budget_func {+ self.byte_budget = Some(budget_func(config));+ }+ self.enforce_limits();+ }++ /// Evict until both the entry cap and the byte budget are satisfied.+ fn enforce_limits(&mut self) {+ while self.len > self.cap+ || self+ .byte_budget+ .is_some_and(|budget| self.total_weight > budget)+ {+ if self.evict_one().is_none() {+ break;}}}@@ -194,8 +258,9 @@ impl<K: Hash + Eq + Clone + Debug, V, S: Default + BuildHasher> LfuCache<K, V, S}}- /// Remove the entry with the smallest frequency value- fn evict_one(&mut self) {+ /// Remove the entry with the smallest frequency value, returning its+ /// weight so byte-budgeted callers can account for it.+ fn evict_one(&mut self) -> Option<usize> {self.decay_least_recent();let mut cursor = self.frequency_index.lower_bound_mut(Bound::Included(&0));@@ -210,6 +275,10 @@ impl<K: Hash + Eq + Clone + Debug, V, S: Default + BuildHasher> LfuCache<K, V, Sself.recency_index.cursor_mut_from_ptr(&*entry).remove();}self.len -= 1;+ self.total_weight = self.total_weight.saturating_sub(entry.weight);+ Some(entry.weight)+ } else {+ None}}@@ -220,6 +289,7 @@ impl<K: Hash + Eq + Clone + Debug, V, S: Default + BuildHasher> LfuCache<K, V, Sbucket.clear();}self.len = 0;+ self.total_weight = 0;}pub fn get<'a, Q: ?Sized + Debug>(&'a mut self, k: &Q) -> Option<&'a V>@@ -272,6 +342,16 @@ impl<K: Hash + Eq + Clone + Debug, V, S: Default + BuildHasher> LfuCache<K, V, S}pub fn put(&mut self, k: K, v: V) {+ self.put_weighted(k, v, 0);+ }++ /// Insert an entry carrying a caller-estimated resident size. Evicts by+ /// LFU until both the entry-count cap and the byte budget (when+ /// configured) are satisfied. An entry whose weight alone exceeds the+ /// whole budget is not cached at all — a single pathological item must+ /// not permanently occupy the entire cache.+ pub fn put_weighted(&mut self, k: K, v: V, weight: usize) -> PutOutcome {+ let mut outcome = PutOutcome::default();let bucket = self.bucket_for_key(&k);self.tick += 1;@@ -285,26 +365,44 @@ impl<K: Hash + Eq + Clone + Debug, V, S: Default + BuildHasher> LfuCache<K, V, S.front_mut();while let Some(entry) = cursor.get() {if entry.key == k {+ let old_weight = entry.weight;unsafe {self.frequency_index.cursor_mut_from_ptr(entry).remove();self.recency_index.cursor_mut_from_ptr(entry).remove();}cursor.remove();self.len -= 1;+ self.total_weight = self.total_weight.saturating_sub(old_weight);break;}cursor.move_next();}}- while self.len >= self.cap {- self.evict_one();+ if self.byte_budget.is_some_and(|budget| weight > budget) {+ outcome.rejected_oversize = true;+ return outcome;+ }++ while self.len >= self.cap+ || self+ .byte_budget+ .is_some_and(|budget| self.total_weight + weight > budget)+ {+ match self.evict_one() {+ Some(evicted_weight) => {+ outcome.evicted_entries += 1;+ outcome.evicted_bytes += evicted_weight;+ }+ None => break,+ }}let entry = Rc::new(Entry {key: k,value: v,freq: RefCell::new(0),+ weight,recency_link: LinkedListLink::new(),frequency_link: RBTreeLink::new(),hash_link: LinkedListLink::new(),@@ -314,9 +412,11 @@ impl<K: Hash + Eq + Clone + Debug, V, S: Default + BuildHasher> LfuCache<K, V, Sself.frequency_index.insert(Rc::clone(&entry));self.recency_index.push_front(entry);self.len += 1;+ self.total_weight = self.total_weight.saturating_add(weight);if self.buckets.len() < self.cap && self.len > self.buckets.len() / 2 {self.grow_hash();}+ outcome}}@@ -728,6 +828,102 @@ mod test {);}+ #[test]+ fn weighted_count_cap_still_evicts() {+ let mut cache = LfuCacheU64::<u32>::with_capacity_and_budget(4, 1_000_000);+ for i in 0..6u64 {+ cache.put_weighted(i, i as u32, 10);+ }+ k9::assert_equal!(cache.len(), 4);+ k9::assert_equal!(cache.total_weight(), 40);+ }++ #[test]+ fn weighted_byte_budget_evicts_before_count_cap() {+ let mut cache = LfuCacheU64::<u32>::with_capacity_and_budget(100, 100);+ for i in 0..10u64 {+ let outcome = cache.put_weighted(i, i as u32, 30);+ k9::assert_equal!(outcome.rejected_oversize, false);+ }+ // 100-byte budget holds at most 3 entries of 30 bytes.+ k9::assert_equal!(cache.len(), 3);+ k9::assert_equal!(cache.total_weight(), 90);+ }++ #[test]+ fn weighted_replace_same_key_updates_weight() {+ let mut cache = LfuCacheU64::<u32>::with_capacity_and_budget(8, 1_000);+ cache.put_weighted(1, 1, 100);+ cache.put_weighted(1, 2, 250);+ k9::assert_equal!(cache.len(), 1);+ k9::assert_equal!(cache.total_weight(), 250);+ k9::assert_equal!(cache.get(&1).copied(), Some(2));+ }++ #[test]+ fn weighted_oversize_entry_is_rejected_and_not_cached() {+ let mut cache = LfuCacheU64::<u32>::with_capacity_and_budget(8, 100);+ cache.put_weighted(1, 1, 40);+ let outcome = cache.put_weighted(2, 2, 500);+ k9::assert_equal!(outcome.rejected_oversize, true);+ k9::assert_equal!(cache.get(&2).is_none(), true);+ // The smaller resident entry is unaffected.+ k9::assert_equal!(cache.len(), 1);+ k9::assert_equal!(cache.total_weight(), 40);++ // Replacing an existing key with an oversize value removes the stale+ // entry rather than leaving it behind.+ let outcome = cache.put_weighted(1, 9, 500);+ k9::assert_equal!(outcome.rejected_oversize, true);+ k9::assert_equal!(cache.len(), 0);+ k9::assert_equal!(cache.total_weight(), 0);+ }++ #[test]+ fn weighted_clear_resets_len_and_weight() {+ let mut cache = LfuCacheU64::<u32>::with_capacity_and_budget(8, 1_000);+ cache.put_weighted(1, 1, 100);+ cache.put_weighted(2, 2, 200);+ cache.clear();+ k9::assert_equal!(cache.len(), 0);+ k9::assert_equal!(cache.total_weight(), 0);+ }++ #[test]+ fn weighted_eviction_reports_outcome() {+ let mut cache = LfuCacheU64::<u32>::with_capacity_and_budget(100, 100);+ cache.put_weighted(1, 1, 60);+ cache.put_weighted(2, 2, 30);+ let outcome = cache.put_weighted(3, 3, 60);+ k9::assert_equal!(outcome.evicted_entries >= 1, true);+ k9::assert_equal!(outcome.evicted_bytes >= 60, true);+ k9::assert_equal!(cache.total_weight() <= 100, true);+ }++ #[test]+ fn shrinking_byte_budget_evicts_immediately() {+ let mut cache = LfuCacheU64::<u32>::with_capacity_and_budget(8, 1_000);+ for i in 0..5u64 {+ cache.put_weighted(i, i as u32, 100);+ }+ k9::assert_equal!(cache.total_weight(), 500);+ // Same path update_config takes after re-reading the budget.+ cache.byte_budget = Some(250);+ cache.enforce_limits();+ k9::assert_equal!(cache.total_weight() <= 250, true);+ k9::assert_equal!(cache.len() <= 2, true);+ }++ #[test]+ fn unweighted_put_keeps_zero_weight() {+ let mut cache = LfuCacheU64::<u32>::with_capacity(4);+ for i in 0..10u64 {+ cache.put(i, i as u32);+ }+ k9::assert_equal!(cache.len(), 4);+ k9::assert_equal!(cache.total_weight(), 0);+ }+#[test]fn basic() {let mut cache = LfuCacheU64::<&'static str>::with_capacity(8);diff --git a/wezterm-gui/src/input_diagnostics.rs b/wezterm-gui/src/input_diagnostics.rsindex d4ac0419..99f0bf01 100644--- a/wezterm-gui/src/input_diagnostics.rs+++ b/wezterm-gui/src/input_diagnostics.rs@@ -26,6 +26,9 @@ pub(crate) struct InputDiagnosticsSnapshot {pub(crate) recent_p95: Duration,pub(crate) slowest_stage: Option<StageSnapshot>,pub(crate) stages: Vec<StageSnapshot>,+ /// Gauge values summed across every reporting source (window); each+ /// source publishes its own set so windows never clobber each other.+ pub(crate) gauges: Vec<(&'static str, u64)>,}#[derive(Debug, Clone)]@@ -88,6 +91,9 @@ impl InputDiagnosticsSnapshot {format_duration(stage.max_duration),));}+ for (name, value) in &self.gauges {+ lines.push(format!("gauge.{name}: {value} (process total)"));+ }lines}}@@ -169,6 +175,10 @@ struct InputDiagnosticsState {max_duration: Duration,recent: VecDeque<Duration>,stages: HashMap<&'static str, StageStats>,+ /// Per-source (per-window) gauge sets, keyed by a stable source id such+ /// as `space_owner_id`. Kept separate so multiple windows do not+ /// overwrite each other; snapshots aggregate across sources.+ gauges: HashMap<u64, HashMap<&'static str, u64>>,}impl Default for InputDiagnosticsState {@@ -185,6 +195,7 @@ impl Default for InputDiagnosticsState {max_duration: Duration::ZERO,recent: VecDeque::with_capacity(RECENT_LIMIT),stages: HashMap::new(),+ gauges: HashMap::new(),}}}@@ -200,6 +211,33 @@ impl InputDiagnosticsState {self.max_duration = Duration::ZERO;self.recent.clear();self.stages.clear();+ self.gauges.clear();+ }++ fn set_gauges_for_source(&mut self, source_id: u64, values: &[(&'static str, u64)]) {+ if !self.enabled {+ return;+ }+ let entry = self.gauges.entry(source_id).or_default();+ for (name, value) in values {+ entry.insert(name, *value);+ }+ }++ fn remove_gauges_for_source(&mut self, source_id: u64) {+ self.gauges.remove(&source_id);+ }++ fn aggregated_gauges(&self) -> Vec<(&'static str, u64)> {+ let mut totals: HashMap<&'static str, u64> = HashMap::new();+ for source in self.gauges.values() {+ for (name, value) in source {+ *totals.entry(name).or_default() += value;+ }+ }+ let mut totals: Vec<_> = totals.into_iter().collect();+ totals.sort_by_key(|(name, _)| *name);+ totals}fn set_enabled(&mut self, enabled: bool) {@@ -271,6 +309,7 @@ impl InputDiagnosticsState {recent_p95: percentile_duration(&self.recent, 0.95),slowest_stage,stages,+ gauges: self.aggregated_gauges(),}}}@@ -327,6 +366,18 @@ pub(crate) fn snapshot() -> InputDiagnosticsSnapshot {state().lock().snapshot()}+/// Publish one window's gauge set in a single lock acquisition. Values are+/// stored per source so concurrent windows never overwrite each other;+/// snapshots aggregate across sources.+pub(crate) fn set_gauges_for_source(source_id: u64, values: &[(&'static str, u64)]) {+ state().lock().set_gauges_for_source(source_id, values);+}++/// Drop a closed window's gauges so they do not linger in process totals.+pub(crate) fn remove_gauges_for_source(source_id: u64) {+ state().lock().remove_gauges_for_source(source_id);+}+fn push_recent(recent: &mut VecDeque<Duration>, duration: Duration) {if recent.len() == RECENT_LIMIT {recent.pop_front();@@ -360,3 +411,55 @@ pub(crate) fn format_duration(duration: Duration) -> String {format!("{micros:.0} us")}}++#[cfg(test)]+mod gauge_tests {+ use super::*;++ fn enabled_state() -> InputDiagnosticsState {+ let mut state = InputDiagnosticsState::default();+ state.set_enabled(true);+ state+ }++ #[test]+ fn gauges_are_isolated_per_source_and_summed_in_snapshots() {+ let mut state = enabled_state();+ state.set_gauges_for_source(1, &[("note_cache_len", 10), ("note_cache_bytes", 100)]);+ state.set_gauges_for_source(2, &[("note_cache_len", 5)]);+ // A later publish from source 1 replaces only its own values.+ state.set_gauges_for_source(1, &[("note_cache_len", 7)]);++ let gauges = state.aggregated_gauges();+ assert!(gauges.contains(&("note_cache_len", 12)));+ assert!(gauges.contains(&("note_cache_bytes", 100)));+ }++ #[test]+ fn removed_source_disappears_from_totals() {+ let mut state = enabled_state();+ state.set_gauges_for_source(1, &[("note_cache_len", 10)]);+ state.set_gauges_for_source(2, &[("note_cache_len", 5)]);+ state.remove_gauges_for_source(1);+ assert_eq!(state.aggregated_gauges(), vec![("note_cache_len", 5)]);+ state.remove_gauges_for_source(2);+ assert!(state.aggregated_gauges().is_empty());+ }++ #[test]+ fn reset_clears_stages_and_gauges() {+ let mut state = enabled_state();+ state.record_stage("note_wrap_sync", Duration::from_millis(1), true);+ state.set_gauges_for_source(1, &[("note_cache_len", 10)]);+ state.clear_stats();+ assert!(state.stages.is_empty());+ assert!(state.aggregated_gauges().is_empty());+ }++ #[test]+ fn disabled_state_ignores_gauge_publishes() {+ let mut state = InputDiagnosticsState::default();+ state.set_gauges_for_source(1, &[("note_cache_len", 10)]);+ assert!(state.aggregated_gauges().is_empty());+ }+}diff --git a/wezterm-gui/src/markdown_editor/host.rs b/wezterm-gui/src/markdown_editor/host.rsindex a0003913..eb92b88d 100644--- a/wezterm-gui/src/markdown_editor/host.rs+++ b/wezterm-gui/src/markdown_editor/host.rs@@ -132,6 +132,18 @@ pub(crate) struct NoteHostState {/// for it.reveal_key_cache: Option<(u64, usize, usize)>,background_wrap_preferred: bool,+ /// `estimated_wrap_work_bytes()` of the current visual document, stored+ /// at rebuild so per-frame decisions never re-walk every line. This+ /// estimate deliberately excludes code/table/image/rule component lines,+ /// so it must never be the only input to the sync-vs-background wrap+ /// decision: the cached wrap still hashes and shifts EVERY visual line.+ wrap_work_estimate: usize,+ /// Length of the full displayed snapshot's source (for progressive+ /// previews this is the complete document, not the seeded slice).+ displayed_source_bytes: usize,+ /// Line count of the current visual document — what the cached wrap's+ /// reuse pass actually iterates.+ visual_line_count: usize,background_wrap_requested_key: Option<NoteBackgroundWrapKey>,background_wrap_generation: u64,pub background_wrap_in_flight_key: Option<NoteBackgroundWrapKey>,@@ -147,6 +159,11 @@ const PROGRESSIVE_PREVIEW_BYTES: usize = 6 * 1024;/// Keep small notes immediate, but move ordinary multi-page notes (including/// the 40 KiB regression fixture) off the UI thread.const BACKGROUND_WRAP_THRESHOLD_BYTES: usize = 8 * 1024;+/// Upper bounds for the primed-cache synchronous wrap: beyond any of these+/// the O(all lines) reuse pass itself is too expensive for a keystroke.+const PRIMED_SYNC_WRAP_MAX_SOURCE_BYTES: usize = 256 * 1024;+const PRIMED_SYNC_WRAP_MAX_LINES: usize = 4096;+const PRIMED_SYNC_WRAP_MAX_WORK_BYTES: usize = 256 * 1024;impl Default for NoteHostState {fn default() -> Self {@@ -192,6 +209,9 @@ impl Default for NoteHostState {links_resolution_pending: false,reveal_key_cache: None,background_wrap_preferred: false,+ wrap_work_estimate: 0,+ displayed_source_bytes: 0,+ visual_line_count: 0,background_wrap_requested_key: None,background_wrap_generation: 0,background_wrap_in_flight_key: None,@@ -244,7 +264,7 @@ impl NoteHostState {self.parse_in_flight_revision = None;self.links_resolution_pending = false;self.reveal_key_cache = None;- self.background_wrap_preferred = false;+ self.reset_wrap_work_metrics();self.background_wrap_requested_key = None;let snapshot = self.session@@ -275,8 +295,14 @@ impl NoteHostState {self.view.mode,0,));+ // Record the FULL document size (the gate metrics must not lie about+ // what the display represents), but keep the seed itself on the+ // synchronous wrap path: this visual is deliberately tiny so a+ // multi-megabyte note paints useful first-screen text immediately.+ // The full background parse installs honest metrics right after.+ self.refresh_wrap_work_metrics(snapshot.source.len());self.background_wrap_preferred =- self.visual.estimated_wrap_work_bytes() >= BACKGROUND_WRAP_THRESHOLD_BYTES;+ self.wrap_work_estimate >= BACKGROUND_WRAP_THRESHOLD_BYTES;self.visual_key = Some((snapshot.revision, self.view.mode, active_start));// This is deliberately not the complete revision. The regular// background parse path will replace it with the full projection.@@ -298,7 +324,7 @@ impl NoteHostState {self.parse_in_flight_revision = None;self.links_resolution_pending = false;self.reveal_key_cache = None;- self.background_wrap_preferred = false;+ self.reset_wrap_work_metrics();self.background_wrap_requested_key = None;}@@ -482,8 +508,7 @@ impl NoteHostState {self.view.mode,self.view.selection.focus.byte,));- self.background_wrap_preferred =- self.visual.estimated_wrap_work_bytes() >= BACKGROUND_WRAP_THRESHOLD_BYTES;+ self.refresh_wrap_work_metrics(source.len());self.visual_key = Some(key);self.wrapped_key = None;}@@ -546,14 +571,17 @@ impl NoteHostState {{return false;}+ let display_source_len = self+ .display_snapshot()+ .map(|snapshot| snapshot.source.len())+ .unwrap_or(0);let active_start = projection.caret_reveal_start(caret);self.projection = projection;self.reveal_key_cache = Some((revision, caret, active_start));// The worker performed the authoritative vault-link resolution.self.links_resolution_pending = false;self.visual = Arc::new(visual);- self.background_wrap_preferred =- self.visual.estimated_wrap_work_bytes() >= BACKGROUND_WRAP_THRESHOLD_BYTES;+ self.refresh_wrap_work_metrics(display_source_len);self.projection_revision = Some(revision);self.visual_key = Some((revision, mode, active_start));self.wrapped_key = None;@@ -601,6 +629,48 @@ impl NoteHostState {self.background_wrap_preferred}+ /// Whether the paint path should hand this wrap to the background worker+ /// (accepting one provisional stale frame) instead of wrapping+ /// synchronously.+ ///+ /// A primed cache makes the synchronous wrap re-measure only changed+ /// lines, so typing stays on the immediate path with no per-key flash —+ /// but the reuse pass still hashes and shifts every line (O(total+ /// lines)), so truly huge notes keep the background path even when+ /// primed.+ pub(crate) fn should_background_wrap(&self, wrap_key: usize) -> bool {+ if !self.background_wrap_preferred {+ return false;+ }+ !(self.wrap_cache.is_primed_for(wrap_key)+ && self.displayed_source_bytes <= PRIMED_SYNC_WRAP_MAX_SOURCE_BYTES+ && self.visual_line_count <= PRIMED_SYNC_WRAP_MAX_LINES+ && self.wrap_work_estimate <= PRIMED_SYNC_WRAP_MAX_WORK_BYTES)+ }++ /// Recompute the wrap-decision inputs after installing a new visual+ /// document. `background_wrap_preferred` must trigger on total size and+ /// line count as well: `estimated_wrap_work_bytes` excludes code/table/+ /// image/rule lines, but the cached wrap's reuse pass iterates every+ /// line, so a huge code-only note with a tiny wrap-work estimate must+ /// still stay off the UI thread.+ fn refresh_wrap_work_metrics(&mut self, displayed_source_bytes: usize) {+ self.wrap_work_estimate = self.visual.estimated_wrap_work_bytes();+ self.displayed_source_bytes = displayed_source_bytes;+ self.visual_line_count = self.visual.lines.len();+ self.background_wrap_preferred = self.wrap_work_estimate+ >= BACKGROUND_WRAP_THRESHOLD_BYTES+ || self.displayed_source_bytes > PRIMED_SYNC_WRAP_MAX_SOURCE_BYTES+ || self.visual_line_count > PRIMED_SYNC_WRAP_MAX_LINES;+ }++ fn reset_wrap_work_metrics(&mut self) {+ self.wrap_work_estimate = 0;+ self.displayed_source_bytes = 0;+ self.visual_line_count = 0;+ self.background_wrap_preferred = false;+ }+pub(crate) fn apply_background_wrap(&mut self,key: NoteBackgroundWrapKey,@@ -1266,6 +1336,142 @@ mod state_tests {);}+ #[test]+ fn primed_wrap_cache_keeps_typing_synchronous_but_not_for_huge_notes() {+ let wrap_key = 7usize;+ let measure = |_: super::super::BlockKind, _: super::super::InlineStyle, text: &str| {+ Ok::<f32, ()>(text.chars().count() as f32)+ };++ // Ordinary multi-page note: background-preferred, but once the wrap+ // cache is primed for this width, typing wraps synchronously.+ let mut host = host_with_source(&"ordinary prose that wraps ".repeat(1_000));+ assert!(host.prefers_background_wrap());+ assert!(host.should_background_wrap(wrap_key), "first layout");+ super::super::wrap_visual_document_by_width_cached(+ &Arc::clone(&host.visual),+ 120.0,+ wrap_key,+ &mut host.wrap_cache,+ measure,+ )+ .unwrap();+ assert!(!host.should_background_wrap(wrap_key), "primed → sync");+ assert!(+ host.should_background_wrap(wrap_key + 1),+ "other width is not primed"+ );++ // Huge note: even a primed cache pays O(total lines) per reuse pass,+ // so it stays on the background path. Sources this large parse on the+ // worker, so install the visual through the background-parse flow.+ let mut huge = host_with_source(&"prose ".repeat(60_000));+ let (revision, source, mode, caret, _) =+ huge.background_parse_request().expect("huge parse request");+ let projection = MarkdownProjection::parse(&source);+ let visual = build_visual_document(&source, &projection, mode, caret);+ assert!(huge.apply_background_parse(revision, mode, caret, projection, visual));+ super::super::wrap_visual_document_by_width_cached(+ &Arc::clone(&huge.visual),+ 120.0,+ wrap_key,+ &mut huge.wrap_cache,+ measure,+ )+ .unwrap();+ assert!(huge.should_background_wrap(wrap_key));+ }++ #[test]+ fn component_heavy_notes_stay_on_background_wrap_despite_tiny_work_estimate() {+ let wrap_key = 3usize;+ let measure = |_: super::super::BlockKind, _: super::super::InlineStyle, text: &str| {+ Ok::<f32, ()>(text.chars().count() as f32)+ };++ // ~50 KiB code-only note: estimated_wrap_work_bytes excludes code+ // lines, so it is tiny — but the reuse pass still walks every visual+ // line, so the line count must force the background path.+ let code_source = format!("```text\n{}```", "code line\n".repeat(5_000));+ let mut code_host = host_with_source(&code_source);+ assert!(+ code_host.wrap_work_estimate < BACKGROUND_WRAP_THRESHOLD_BYTES,+ "estimate ignores code lines"+ );+ assert!(code_host.visual_line_count > PRIMED_SYNC_WRAP_MAX_LINES);+ assert!(code_host.prefers_background_wrap());+ super::super::wrap_visual_document_by_width_cached(+ &Arc::clone(&code_host.visual),+ 120.0,+ wrap_key,+ &mut code_host.wrap_cache,+ measure,+ )+ .unwrap();+ assert!(+ code_host.should_background_wrap(wrap_key),+ "primed cache must not pull a huge code note onto the UI thread"+ );++ // Table-heavy note: same rule via the table rows.+ let table_source = format!(+ "| A | B |\n| - | - |\n{}",+ "| aa | bb |\n".repeat(5_000)+ );+ let mut table_host = host_with_source(&table_source);+ assert!(table_host.visual_line_count > PRIMED_SYNC_WRAP_MAX_LINES);+ assert!(table_host.prefers_background_wrap());+ super::super::wrap_visual_document_by_width_cached(+ &Arc::clone(&table_host.visual),+ 120.0,+ wrap_key,+ &mut table_host.wrap_cache,+ measure,+ )+ .unwrap();+ assert!(table_host.should_background_wrap(wrap_key));+ }++ #[test]+ fn wrap_metrics_reset_on_clear_and_track_full_source_for_previews() {+ // Small doc: metrics reflect the synchronous build...+ let mut host = host_with_source("plain prose");+ assert!(host.displayed_source_bytes > 0);+ assert!(host.visual_line_count > 0);+ // ...and clear_document zeroes everything.+ host.clear_document(None);+ assert_eq!(host.displayed_source_bytes, 0);+ assert_eq!(host.visual_line_count, 0);+ assert_eq!(host.wrap_work_estimate, 0);+ assert!(!host.prefers_background_wrap());++ // Progressive preview seeds only the first screen but must gate on+ // the FULL document size.+ let paragraph = "First-screen text with **formatting** and enough words to wrap.\n\n";+ let source = paragraph.repeat(BACKGROUND_PARSE_THRESHOLD_BYTES / paragraph.len() + 8);+ let full_len = source.len();+ let session = Arc::new(Mutex::new(MarkdownDocumentSession::new(+ "large".into(),+ PathBuf::from("Large.md"),+ source,+ )));+ let document = VaultDocument {+ vault_root: PathBuf::from("vault"),+ relative_path: "Large.md".into(),+ document_path: PathBuf::from("vault/Large.md"),+ session,+ };+ let mut host = NoteHostState::default();+ assert!(host.bind_document(document));+ assert_eq!(+ host.displayed_source_bytes, full_len,+ "the metric reports the full document, not the seeded slice"+ );+ // The tiny seed itself still paints via the synchronous wrap so the+ // first screen appears immediately (matches the seed test above).+ assert!(!host.prefers_background_wrap());+ }+#[test]fn nontrivial_note_wrap_is_single_flight_and_latest_width_wins() {let source = "ordinary proportional-font prose ".repeat(1_300);diff --git a/wezterm-gui/src/markdown_editor/surface.rs b/wezterm-gui/src/markdown_editor/surface.rsindex 9aafaf26..7a62f8b0 100644--- a/wezterm-gui/src/markdown_editor/surface.rs+++ b/wezterm-gui/src/markdown_editor/surface.rs@@ -573,6 +573,15 @@ pub(crate) struct VisualWrapCache {source_line_lookup: HashMap<u64, Vec<usize>>,}+impl VisualWrapCache {+ /// Whether a wrap at this key can reuse per-line results, making a+ /// synchronous wrap cheap even for large documents (only changed lines+ /// are re-measured). False after a width change or a size-cap eviction.+ pub(crate) fn is_primed_for(&self, wrap_key: usize) -> bool {+ self.wrap_key == Some(wrap_key) && !self.wrapped.lines.is_empty()+ }+}+pub(crate) fn build_visual_document(source: &str,projection: &MarkdownProjection,diff --git a/wezterm-gui/src/shapecache.rs b/wezterm-gui/src/shapecache.rsindex 67b3037f..2475335f 100644--- a/wezterm-gui/src/shapecache.rs+++ b/wezterm-gui/src/shapecache.rs@@ -118,6 +118,379 @@ impl<'a> std::hash::Hash for dyn ShapeCacheKeyTrait + 'a {}}+/// Which UI surface a piece of proportional text belongs to. Shaping is+/// routed through per-domain caches so a long Note cannot evict tab-bar or+/// sidebar entries (nor the terminal grid's cache), and so Note / File+/// Preview shaping memory can be released independently when hidden.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum UiTextDomain {+ Chrome,+ Note,+ FilePreview,+}++impl UiTextDomain {+ pub fn miss_stage_name(self) -> &'static str {+ match self {+ Self::Chrome => "chrome_shape_miss",+ Self::Note => "note_shape_miss",+ Self::FilePreview => "file_preview_shape_miss",+ }+ }++ pub fn gauge_names(self) -> &'static UiShapeGaugeNames {+ match self {+ Self::Chrome => &CHROME_GAUGE_NAMES,+ Self::Note => &NOTE_GAUGE_NAMES,+ Self::FilePreview => &FILE_PREVIEW_GAUGE_NAMES,+ }+ }+}++/// Static gauge names per domain (the diagnostics API requires+/// `&'static str`).+pub struct UiShapeGaugeNames {+ pub len: &'static str,+ pub bytes: &'static str,+ pub cap: &'static str,+ pub budget: &'static str,+ pub hits: &'static str,+ pub misses: &'static str,+ pub rejected_oversize: &'static str,+ pub evicted_entries: &'static str,+ pub evicted_bytes: &'static str,+}++static CHROME_GAUGE_NAMES: UiShapeGaugeNames = UiShapeGaugeNames {+ len: "chrome_cache_len",+ bytes: "chrome_cache_bytes",+ cap: "chrome_cache_cap",+ budget: "chrome_cache_budget",+ hits: "chrome_cache_hits",+ misses: "chrome_cache_misses",+ rejected_oversize: "chrome_cache_rejected_oversize",+ evicted_entries: "chrome_cache_evictions_count",+ evicted_bytes: "chrome_cache_evictions_bytes",+};++static NOTE_GAUGE_NAMES: UiShapeGaugeNames = UiShapeGaugeNames {+ len: "note_cache_len",+ bytes: "note_cache_bytes",+ cap: "note_cache_cap",+ budget: "note_cache_budget",+ hits: "note_cache_hits",+ misses: "note_cache_misses",+ rejected_oversize: "note_cache_rejected_oversize",+ evicted_entries: "note_cache_evictions_count",+ evicted_bytes: "note_cache_evictions_bytes",+};++static FILE_PREVIEW_GAUGE_NAMES: UiShapeGaugeNames = UiShapeGaugeNames {+ len: "file_preview_cache_len",+ bytes: "file_preview_cache_bytes",+ cap: "file_preview_cache_cap",+ budget: "file_preview_cache_budget",+ hits: "file_preview_cache_hits",+ misses: "file_preview_cache_misses",+ rejected_oversize: "file_preview_cache_rejected_oversize",+ evicted_entries: "file_preview_cache_evictions_count",+ evicted_bytes: "file_preview_cache_evictions_bytes",+};++/// Cumulative counters maintained locally (plain fields, no global locks on+/// the request path) and published in batch to the diagnostics panel.+#[derive(Debug, Default, Clone, Copy)]+pub struct UiShapeCacheStats {+ pub hits: u64,+ pub misses: u64,+ pub rejected_oversize: u64,+ pub evicted_entries: u64,+ pub evicted_bytes: u64,+}++pub type UiShapedValue = anyhow::Result<Rc<Vec<ShapedInfo>>>;++const SHAPE_ENTRY_FIXED_OVERHEAD: usize = 128;+const SHAPE_ERR_ENTRY_BYTES: usize = 256;++fn estimate_text_style_heap_bytes(style: &TextStyle) -> usize {+ style+ .font+ .capacity()+ .saturating_mul(std::mem::size_of::<config::FontAttributes>())+ .saturating_add(+ style+ .font+ .iter()+ .map(|attributes| attributes.family.capacity())+ .sum(),+ )+}++/// Estimated resident bytes for one cache entry. Glyph bitmaps live in the+/// shared glyph atlas behind `Rc<CachedGlyph>` and are deliberately not+/// counted here.+pub fn estimate_shaped_entry_bytes(key: &ShapeCacheKey, value: &UiShapedValue) -> usize {+ let key_bytes = std::mem::size_of::<ShapeCacheKey>()+ .saturating_add(key.text.capacity())+ .saturating_add(estimate_text_style_heap_bytes(&key.style));+ let value_bytes = match value {+ Ok(shaped) => std::mem::size_of::<Vec<ShapedInfo>>()+ .saturating_add(shaped.capacity().saturating_mul(std::mem::size_of::<ShapedInfo>())),+ Err(_) => SHAPE_ERR_ENTRY_BYTES,+ };+ SHAPE_ENTRY_FIXED_OVERHEAD+ .saturating_add(key_bytes)+ .saturating_add(value_bytes)+}++fn chrome_shape_cache_cap(config: &config::ConfigHandle) -> usize {+ config.shape_cache_size+}+fn note_shape_cache_cap(config: &config::ConfigHandle) -> usize {+ config.shape_cache_size.saturating_mul(4)+}+fn file_preview_shape_cache_cap(config: &config::ConfigHandle) -> usize {+ config.shape_cache_size.saturating_mul(2)+}+fn chrome_shape_cache_budget(_: &config::ConfigHandle) -> usize {+ 4 * 1024 * 1024+}+fn note_shape_cache_budget(_: &config::ConfigHandle) -> usize {+ 32 * 1024 * 1024+}+fn file_preview_shape_cache_budget(_: &config::ConfigHandle) -> usize {+ 16 * 1024 * 1024+}++pub struct UiShapeDomainCache {+ cache: lfucache::LfuCache<ShapeCacheKey, UiShapedValue>,+ stats: UiShapeCacheStats,+ cap_func: fn(&config::ConfigHandle) -> usize,+ budget_func: fn(&config::ConfigHandle) -> usize,+ cap: usize,+ byte_budget: usize,+}++impl UiShapeDomainCache {+ fn new(domain: UiTextDomain, config: &config::ConfigHandle) -> Self {+ let (hit, miss, cap_func, budget_func): (+ &'static str,+ &'static str,+ fn(&config::ConfigHandle) -> usize,+ fn(&config::ConfigHandle) -> usize,+ ) = match domain {+ UiTextDomain::Chrome => (+ "chrome_shape_cache.hit.rate",+ "chrome_shape_cache.miss.rate",+ chrome_shape_cache_cap,+ chrome_shape_cache_budget,+ ),+ UiTextDomain::Note => (+ "note_shape_cache.hit.rate",+ "note_shape_cache.miss.rate",+ note_shape_cache_cap,+ note_shape_cache_budget,+ ),+ UiTextDomain::FilePreview => (+ "file_preview_shape_cache.hit.rate",+ "file_preview_shape_cache.miss.rate",+ file_preview_shape_cache_cap,+ file_preview_shape_cache_budget,+ ),+ };+ Self {+ cache: lfucache::LfuCache::new_weighted(hit, miss, cap_func, budget_func, config),+ stats: UiShapeCacheStats::default(),+ cap_func,+ budget_func,+ cap: cap_func(config),+ byte_budget: budget_func(config),+ }+ }++ pub fn get(&mut self, key: &dyn ShapeCacheKeyTrait) -> Option<&UiShapedValue> {+ let value = self.cache.get(key);+ if value.is_some() {+ self.stats.hits += 1;+ } else {+ self.stats.misses += 1;+ }+ value+ }++ pub fn put(&mut self, key: ShapeCacheKey, value: UiShapedValue) {+ let weight = estimate_shaped_entry_bytes(&key, &value);+ let outcome = self.cache.put_weighted(key, value, weight);+ if outcome.rejected_oversize {+ self.stats.rejected_oversize += 1;+ }+ self.stats.evicted_entries += outcome.evicted_entries as u64;+ self.stats.evicted_bytes += outcome.evicted_bytes as u64;+ }++ pub fn clear(&mut self) {+ self.cache.clear();+ }++ pub fn update_config(&mut self, config: &config::ConfigHandle) {+ self.cache.update_config(config);+ self.cap = (self.cap_func)(config);+ self.byte_budget = (self.budget_func)(config);+ }++ pub fn len(&self) -> usize {+ self.cache.len()+ }++ pub fn total_weight(&self) -> usize {+ self.cache.total_weight()+ }++ pub fn cap(&self) -> usize {+ self.cap+ }++ pub fn byte_budget(&self) -> usize {+ self.byte_budget+ }++ pub fn stats(&self) -> UiShapeCacheStats {+ self.stats+ }+}++/// The three per-domain proportional-text shaping caches; the terminal grid+/// keeps its own separate `shape_cache`.+pub struct UiShapeCaches {+ chrome: UiShapeDomainCache,+ note: UiShapeDomainCache,+ file_preview: UiShapeDomainCache,+}++impl UiShapeCaches {+ pub fn new(config: &config::ConfigHandle) -> Self {+ Self {+ chrome: UiShapeDomainCache::new(UiTextDomain::Chrome, config),+ note: UiShapeDomainCache::new(UiTextDomain::Note, config),+ file_preview: UiShapeDomainCache::new(UiTextDomain::FilePreview, config),+ }+ }++ pub fn domain_mut(&mut self, domain: UiTextDomain) -> &mut UiShapeDomainCache {+ match domain {+ UiTextDomain::Chrome => &mut self.chrome,+ UiTextDomain::Note => &mut self.note,+ UiTextDomain::FilePreview => &mut self.file_preview,+ }+ }++ pub fn domain(&self, domain: UiTextDomain) -> &UiShapeDomainCache {+ match domain {+ UiTextDomain::Chrome => &self.chrome,+ UiTextDomain::Note => &self.note,+ UiTextDomain::FilePreview => &self.file_preview,+ }+ }++ pub fn clear_all(&mut self) {+ self.chrome.clear();+ self.note.clear();+ self.file_preview.clear();+ }++ /// Note idle release: only the Note domain is dropped.+ pub fn clear_note(&mut self) {+ self.note.clear();+ }++ /// File Preview idle release: only the preview domain is dropped.+ pub fn clear_file_preview(&mut self) {+ self.file_preview.clear();+ }++ pub fn update_config(&mut self, config: &config::ConfigHandle) {+ self.chrome.update_config(config);+ self.note.update_config(config);+ self.file_preview.update_config(config);+ }+}++#[cfg(test)]+mod ui_shape_cache_tests {+ use super::*;++ fn key(text: &str) -> ShapeCacheKey {+ ShapeCacheKey {+ font_identity: 1,+ style: TextStyle::default(),+ text: text.to_string(),+ }+ }++ fn caches() -> UiShapeCaches {+ UiShapeCaches::new(&config::configuration())+ }++ #[test]+ fn domains_are_isolated_and_release_independently() {+ let mut caches = caches();+ caches+ .domain_mut(UiTextDomain::Chrome)+ .put(key("chrome"), Ok(Rc::new(vec![])));+ caches+ .domain_mut(UiTextDomain::Note)+ .put(key("note"), Ok(Rc::new(vec![])));+ caches+ .domain_mut(UiTextDomain::FilePreview)+ .put(key("preview"), Ok(Rc::new(vec![])));++ caches.clear_note();+ assert_eq!(caches.domain(UiTextDomain::Note).len(), 0);+ assert_eq!(caches.domain(UiTextDomain::Note).total_weight(), 0);+ assert_eq!(caches.domain(UiTextDomain::Chrome).len(), 1);+ assert_eq!(caches.domain(UiTextDomain::FilePreview).len(), 1);++ caches.clear_file_preview();+ assert_eq!(caches.domain(UiTextDomain::FilePreview).len(), 0);+ assert_eq!(caches.domain(UiTextDomain::FilePreview).total_weight(), 0);+ assert_eq!(caches.domain(UiTextDomain::Chrome).len(), 1);++ caches.clear_all();+ assert_eq!(caches.domain(UiTextDomain::Chrome).len(), 0);+ assert_eq!(caches.domain(UiTextDomain::Chrome).total_weight(), 0);+ }++ #[test]+ fn oversize_entries_are_rejected_and_counted() {+ let mut caches = caches();+ let note = caches.domain_mut(UiTextDomain::Note);+ // Exceeds the 32 MiB note budget on its own.+ let huge = "x".repeat(40 * 1024 * 1024);+ note.put(key(&huge), Ok(Rc::new(vec![])));+ assert_eq!(note.len(), 0);+ assert_eq!(note.total_weight(), 0);+ assert_eq!(note.stats().rejected_oversize, 1);+ }++ #[test]+ fn hit_and_miss_counters_track_lookups() {+ let mut caches = caches();+ let chrome = caches.domain_mut(UiTextDomain::Chrome);+ let probe = key("label");+ assert!(chrome+ .get(&probe as &dyn ShapeCacheKeyTrait)+ .is_none());+ chrome.put(key("label"), Ok(Rc::new(vec![])));+ assert!(chrome+ .get(&probe as &dyn ShapeCacheKeyTrait)+ .is_some());+ let stats = chrome.stats();+ assert_eq!(stats.misses, 1);+ assert_eq!(stats.hits, 1);+ }+}+#[cfg(test)]mod test {use crate::glyphcache::CachedGlyph;diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 74607734..1398aa93 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -1031,6 +1031,19 @@ pub struct TermWindow {quad_generation: usize,shape_generation: usize,shape_cache: RefCell<LfuCache<ShapeCacheKey, anyhow::Result<Rc<Vec<ShapedInfo>>>>>,+ /// Per-domain shaping caches for proportional UI text (chrome / Note /+ /// File Preview), separate from the terminal's `shape_cache`. Sharing one+ /// LFU meant a long note's thousands of run strings re-shaped every fling+ /// on the UI thread AND evicted the terminal's and chrome's entries; the+ /// split also gives each domain a byte budget and independent idle+ /// release.+ ui_shape_caches: RefCell<crate::shapecache::UiShapeCaches>,+ /// Which domain cache `cached_ui_shape` routes to; set by the Note and+ /// File Preview paint entry points, Chrome otherwise.+ ui_text_domain: std::cell::Cell<crate::shapecache::UiTextDomain>,+ /// Throttles the periodic paint-time diagnostics publish; clears and+ /// releases publish immediately regardless.+ last_ui_shape_diagnostics_publish: std::cell::Cell<Option<Instant>>,line_to_ele_shape_cache: RefCell<LfuCache<LineToEleShapeCacheKey, LineToElementShapeItem>>,line_state_cache: RefCell<LfuCacheU64<Arc<CachedLineState>>>,@@ -1665,6 +1678,9 @@ impl TermWindow {|config| config.shape_cache_size,&config,)),+ ui_shape_caches: RefCell::new(crate::shapecache::UiShapeCaches::new(&config)),+ ui_text_domain: std::cell::Cell::new(crate::shapecache::UiTextDomain::Chrome),+ last_ui_shape_diagnostics_publish: std::cell::Cell::new(None),line_state_cache: RefCell::new(LfuCacheU64::new("line_state_cache.hit.rate","line_state_cache.miss.rate",@@ -2294,6 +2310,8 @@ impl TermWindow {TermWindowNotif::InvalidateShapeCache => {self.shape_generation += 1;self.shape_cache.borrow_mut().clear();+ self.ui_shape_caches.borrow_mut().clear_all();+ self.publish_ui_shape_cache_diagnostics();self.invalidate_modal();window.invalidate();}@@ -2637,6 +2655,18 @@ impl TermWindow {self.resize_mux_tabs_to_current_terminal_size();self.apply_workspace_thread_font_scales();self.sync_current_workspace_thread();++ // A Space/thread switch can replace the active pane without changing+ // the native window's focus state, so no FocusChanged event follows+ // to focus the newly adopted pane. Do that handoff immediately rather+ // than requiring the user to click the terminal first.+ if self.focused.is_some() {+ if let Some(pane) = self.get_active_pane_or_overlay() {+ pane.advise_focus();+ Mux::get().record_focus_for_current_identity(pane.pane_id());+ }+ }+self.update_title();if let Some(window) = self.window.as_ref() {window.invalidate();@@ -3014,6 +3044,7 @@ impl TermWindow {) -> bool {if self.active_space_id == space_id {if let Some(thread_id) = preferred_thread {+ self.clear_right_sidebar_text_focus();self.activate_workspace_thread(thread_id, window);} else {window.invalidate();@@ -3027,6 +3058,10 @@ impl TermWindow {return false;}let previous_sidebar_width = self.right_sidebar_width();+ // Text focus belongs to the Space being left. Clear it while that+ // Space is still active so Note state is frozen/saved against the+ // correct document and keyboard input can reach the destination pane.+ self.clear_right_sidebar_text_focus();self.set_content_view_active(false);self.active_space_id = space_id.clone();self.refresh_active_space_note_vault_flag();@@ -3352,6 +3387,12 @@ impl TermWindow {shape_cache.update_config(&config);shape_cache.clear();}+ {+ let mut ui_shape_caches = self.ui_shape_caches.borrow_mut();+ ui_shape_caches.update_config(&config);+ ui_shape_caches.clear_all();+ }+ self.publish_ui_shape_cache_diagnostics();self.line_state_cache.borrow_mut().update_config(&config);self.line_quad_cache.borrow_mut().update_config(&config);self.line_to_ele_shape_cache@@ -6331,8 +6372,59 @@ impl TermWindow {}}+impl TermWindow {+ /// Publish this window's per-domain shaping-cache gauges in one batch+ /// (single diagnostics lock). Called unthrottled after cache clears and+ /// idle releases so the panel never shows stale non-zero values.+ pub(crate) fn publish_ui_shape_cache_diagnostics(&self) {+ if !crate::input_diagnostics::enabled() {+ return;+ }+ self.last_ui_shape_diagnostics_publish+ .set(Some(Instant::now()));+ let caches = self.ui_shape_caches.borrow();+ let mut values: Vec<(&'static str, u64)> = Vec::with_capacity(27);+ for domain in [+ crate::shapecache::UiTextDomain::Chrome,+ crate::shapecache::UiTextDomain::Note,+ crate::shapecache::UiTextDomain::FilePreview,+ ] {+ let cache = caches.domain(domain);+ let stats = cache.stats();+ let names = domain.gauge_names();+ values.push((names.len, cache.len() as u64));+ values.push((names.bytes, cache.total_weight() as u64));+ values.push((names.cap, cache.cap() as u64));+ values.push((names.budget, cache.byte_budget() as u64));+ values.push((names.hits, stats.hits));+ values.push((names.misses, stats.misses));+ values.push((names.rejected_oversize, stats.rejected_oversize));+ values.push((names.evicted_entries, stats.evicted_entries));+ values.push((names.evicted_bytes, stats.evicted_bytes));+ }+ crate::input_diagnostics::set_gauges_for_source(self.space_owner_id, &values);+ }++ /// Throttled variant for the per-frame paint path.+ pub(crate) fn publish_ui_shape_cache_diagnostics_throttled(&self) {+ const PUBLISH_INTERVAL: Duration = Duration::from_millis(500);+ if !crate::input_diagnostics::enabled() {+ return;+ }+ if self+ .last_ui_shape_diagnostics_publish+ .get()+ .is_some_and(|last| last.elapsed() < PUBLISH_INTERVAL)+ {+ return;+ }+ self.publish_ui_shape_cache_diagnostics();+ }+}+impl Drop for TermWindow {fn drop(&mut self) {+ crate::input_diagnostics::remove_gauges_for_source(self.space_owner_id);gpu_debug(format!("drop main_window backend={} size={}x{} dpi={}",if self.webgpu.is_some() {diff --git a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rsindex 036897e3..4e703a26 100644--- a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs+++ b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs@@ -1257,9 +1257,17 @@ impl crate::TermWindow {style,text,};+ let domain = self.ui_text_domain.get();- if let Some(cached) = self.lookup_cached_shape(&key) {- return cached.map(|shaped| (shaped, UiShapeCacheLookup::Hit));+ match self+ .ui_shape_caches+ .borrow_mut()+ .domain_mut(domain)+ .get(&key as &dyn crate::shapecache::ShapeCacheKeyTrait)+ {+ Some(Ok(shaped)) => return Ok((Rc::clone(shaped), UiShapeCacheLookup::Hit)),+ Some(Err(err)) => return Err(anyhow!("cached shaper error: {}", err)),+ None => {}}let Some(window) = self.window.as_ref().cloned() else {@@ -1269,6 +1277,9 @@ impl crate::TermWindow {return Ok((Rc::new(Vec::new()), UiShapeCacheLookup::Skipped));};+ // Cache misses shape on the UI thread; surfaced per domain in Input+ // Diagnostics so fast-scroll shaping bursts are attributable.+ let miss_stage = crate::input_diagnostics::StageTimer::begin(domain.miss_stage_name());let infos = match font.shape(text,move || window.notify(TermWindowNotif::InvalidateShapeCache),@@ -1281,11 +1292,16 @@ impl crate::TermWindow {Ok(infos) => infos,Err(err) => {if err.root_cause().downcast_ref::<ClearShapeCache>().is_some() {+ miss_stage.finish(false);return Err(err);}let res = anyhow!("shaper error: {}", err);- self.shape_cache.borrow_mut().put(key.to_owned(), Err(err));+ self.ui_shape_caches+ .borrow_mut()+ .domain_mut(domain)+ .put(key.to_owned(), Err(err));+ miss_stage.finish(false);return Err(res);}};@@ -1295,9 +1311,11 @@ impl crate::TermWindow {self.glyph_infos_to_glyphs(style, &mut glyph_cache, &infos, font, metrics)?};let shaped = Rc::new(ShapedInfo::process(&infos, &glyphs));- self.shape_cache+ self.ui_shape_caches.borrow_mut()+ .domain_mut(domain).put(key.to_owned(), Ok(Rc::clone(&shaped)));+ miss_stage.finish(true);Ok((shaped, UiShapeCacheLookup::Miss))}diff --git a/wezterm-gui/src/termwindow/render/mod.rs b/wezterm-gui/src/termwindow/render/mod.rsindex d6244408..036995ed 100644--- a/wezterm-gui/src/termwindow/render/mod.rs+++ b/wezterm-gui/src/termwindow/render/mod.rs@@ -922,6 +922,8 @@ impl crate::TermWindow {pub fn recreate_texture_atlas(&mut self, size: Option<usize>) -> anyhow::Result<()> {self.shape_generation += 1;self.shape_cache.borrow_mut().clear();+ self.ui_shape_caches.borrow_mut().clear_all();+ self.publish_ui_shape_cache_diagnostics();self.line_to_ele_shape_cache.borrow_mut().clear();if let Some(render_state) = self.render_state.as_mut() {render_state.recreate_texture_atlas(&self.fonts, &self.render_metrics, size)?;diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex 65782db4..9c76a34c 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -136,6 +136,8 @@ impl crate::TermWindow {self.invalidate_modal();self.shape_generation += 1;self.shape_cache.borrow_mut().clear();+ self.ui_shape_caches.borrow_mut().clear_all();+ self.publish_ui_shape_cache_diagnostics();self.line_to_ele_shape_cache.borrow_mut().clear();} else {log::error!("paint_pass failed: {:#}", err);@@ -147,6 +149,7 @@ impl crate::TermWindow {log::debug!("paint_impl before call_draw elapsed={:?}", start.elapsed());self.call_draw(frame).ok();+ self.publish_ui_shape_cache_diagnostics_throttled();self.last_frame_duration = start.elapsed();log::debug!("paint_impl elapsed={:?}, fps={}",diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rsindex 366d6a6a..cd08ec51 100644--- a/wezterm-gui/src/termwindow/resize.rs+++ b/wezterm-gui/src/termwindow/resize.rs@@ -97,6 +97,8 @@ impl super::TermWindow {self.shape_generation += 1;self.pane_font_cache.borrow_mut().clear();self.shape_cache.borrow_mut().clear();+ self.ui_shape_caches.borrow_mut().clear_all();+ self.publish_ui_shape_cache_diagnostics();self.line_to_ele_shape_cache.borrow_mut().clear();self.invalidate_fancy_tab_bar();self.invalidate_modal();@@ -745,6 +747,8 @@ impl super::TermWindow {self.quad_generation += 1;self.shape_generation += 1;self.shape_cache.borrow_mut().clear();+ self.ui_shape_caches.borrow_mut().clear_all();+ self.publish_ui_shape_cache_diagnostics();self.line_to_ele_shape_cache.borrow_mut().clear();self.invalidate_fancy_tab_bar();self.invalidate_modal();diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex d8928604..c45463ac 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -83,7 +83,6 @@ const SNIPPET_CARET_WIDTH: f32 = 3.0;const NOTE_TOOLBAR_HEIGHT: usize = 54;const NOTE_BODY_TOP_GAP: usize = 12;const NOTE_BODY_PADDING: usize = 24;-const NOTE_READING_MAX_WIDTH: usize = 720;const NOTE_LINE_GAP: usize = 5;const NOTE_CARET_WIDTH: f32 = 2.0;const NOTE_TABLE_CELL_HORIZONTAL_PADDING: usize = 10;@@ -252,6 +251,42 @@ fn visible_code_block_rounded_edges((block_top >= viewport_top, block_bottom <= viewport_bottom)}+/// Idle-release decisions extracted as pure functions so the token/visibility+/// logic is unit-testable without a TermWindow or real timers.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum NoteReleaseAction {+ Skip,+ SaveAndReschedule,+ Release,+}++fn note_release_action(token_matches: bool, visible: bool, dirty: bool) -> NoteReleaseAction {+ if !token_matches || visible {+ NoteReleaseAction::Skip+ } else if dirty {+ NoteReleaseAction::SaveAndReschedule+ } else {+ NoteReleaseAction::Release+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum FileReleaseAction {+ Skip,+ RescheduleWhileIndexing,+ Release,+}++fn file_release_action(token_matches: bool, visible: bool, indexing: bool) -> FileReleaseAction {+ if !token_matches || visible {+ FileReleaseAction::Skip+ } else if indexing {+ FileReleaseAction::RescheduleWhileIndexing+ } else {+ FileReleaseAction::Release+ }+}+/// Hash an already-ordered sequence with the same shape as `Vec::hash`/// (length prefix + elements) so adjacent collections cannot alias.fn hash_ordered_iter<H: std::hash::Hasher, T: Hash>(@@ -1095,14 +1130,24 @@ impl crate::TermWindow {/// since scheduling, or if an index build is still in flight. The root and/// expanded-folder set are kept so reopening rebuilds the same view.fn release_right_sidebar_file_memory_if_idle(&mut self, token: u64) {- if token != self.right_sidebar_file_memory_release_token- || self.right_sidebar_file_view_active()- || matches!(+ match file_release_action(+ token == self.right_sidebar_file_memory_release_token,+ self.right_sidebar_file_view_active(),+ matches!(self.right_sidebar_file_index_status,RightSidebarFileIndexStatus::Indexing- )- {- return;+ ),+ ) {+ FileReleaseAction::Skip => return,+ FileReleaseAction::RescheduleWhileIndexing => {+ // The panel is hidden but an index build is still running; a+ // bare return here used to leak the whole File state forever+ // (no timer remained). Re-arm the release so it lands once+ // indexing settles.+ self.schedule_right_sidebar_file_memory_release();+ return;+ }+ FileReleaseAction::Release => {}}// Remember the view (paths/scroll/filter, a few KB) BEFORE the teardown@@ -1122,6 +1167,8 @@ impl crate::TermWindow {self.right_sidebar_file_index_status = RightSidebarFileIndexStatus::Empty;self.right_sidebar_file_browse_rows = Vec::new();self.right_sidebar_file_browse_cache_key = None;+ self.ui_shape_caches.borrow_mut().clear_file_preview();+ self.publish_ui_shape_cache_diagnostics();self.invalidate_window();}@@ -1147,20 +1194,21 @@ impl crate::TermWindow {}fn release_right_sidebar_note_memory_if_idle(&mut self, token: u64) {- if token != self.right_sidebar_note_memory_release_token- || self.right_sidebar_note_visible()- {- return;- }- if self- .right_sidebar_note- .session- .as_ref()- .is_some_and(|session| session.lock().is_dirty())- {- self.save_right_sidebar_note_now();- self.schedule_right_sidebar_note_memory_release();- return;+ match note_release_action(+ token == self.right_sidebar_note_memory_release_token,+ self.right_sidebar_note_visible(),+ self.right_sidebar_note+ .session+ .as_ref()+ .is_some_and(|session| session.lock().is_dirty()),+ ) {+ NoteReleaseAction::Skip => return,+ NoteReleaseAction::SaveAndReschedule => {+ self.save_right_sidebar_note_now();+ self.schedule_right_sidebar_note_memory_release();+ return;+ }+ NoteReleaseAction::Release => {}}self.right_sidebar_note_open_generation =@@ -1184,6 +1232,8 @@ impl crate::TermWindow {self.right_sidebar_note_image_failures.clear();self.right_sidebar_note_code_highlight = NoteCodeHighlightState::default();self.right_sidebar_note_paint_cache = NotePaintCache::default();+ self.ui_shape_caches.borrow_mut().clear_note();+ self.publish_ui_shape_cache_diagnostics();}fn right_sidebar_file_view_state_key(&self) -> Option<(PathBuf, String)> {@@ -3959,7 +4009,9 @@ impl crate::TermWindow {};promise::spawn::spawn(async move {let result = promise::spawn::spawn_into_new_thread(move || {- let stage = crate::input_diagnostics::StageTimer::begin("note_wrap");+ // Worker-side wrap: slow is acceptable here. Decisions about+ // real incremental wrapping must look at note_wrap_sync only.+ let stage = crate::input_diagnostics::StageTimer::begin("note_wrap_background");let wrapped = wrap_visual_document_by_width_cached(&visual,wrap_width,@@ -6133,6 +6185,8 @@ impl crate::TermWindow {/// Paint the Note toolbar and editor body into an arbitrary content rect —/// either inline in the sidebar column or in the expanded Note pane.+ /// Routes all shaping inside (wrap measurement, prose, preedit, toolbar)+ /// through the Note domain cache.#[allow(clippy::too_many_arguments)]fn paint_note_editor_area(&mut self,@@ -6149,6 +6203,45 @@ impl crate::TermWindow {base_font_size: f64,show_tree_button: bool,tree_button_icon: SvgIcon,+ ) -> anyhow::Result<()> {+ let previous_domain = self+ .ui_text_domain+ .replace(crate::shapecache::UiTextDomain::Note);+ let result = self.paint_note_editor_area_impl(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ content_bottom,+ base_font_size,+ show_tree_button,+ tree_button_icon,+ );+ self.ui_text_domain.set(previous_domain);+ result+ }++ #[allow(clippy::too_many_arguments)]+ fn paint_note_editor_area_impl(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ chrome: UiPalette,+ foreground: LinearRgba,+ muted_fg: LinearRgba,+ content_x: usize,+ content_top: usize,+ content_width: usize,+ content_bottom: usize,+ base_font_size: f64,+ show_tree_button: bool,+ tree_button_icon: SvgIcon,) -> anyhow::Result<()> {self.right_sidebar_note.refresh_projection();self.schedule_right_sidebar_note_parse();@@ -6240,7 +6333,8 @@ impl crate::TermWindow {let preedit = self.right_sidebar_note.view.preedit.clone();let padding = self.ui_px(NOTE_BODY_PADDING) as f32;let available_reading_width = (content_width as f32 - padding * 2.0).max(1.0);- let reading_width = available_reading_width.min(self.ui_f32(NOTE_READING_MAX_WIDTH as f32));+ let reading_width = available_reading_width+ .min(self.ui_f32(self.config.note_reading_max_width.max(320) as f32));let text_left = content_x as f32 + (content_width as f32 - reading_width) / 2.0;let clip_left = text_left;let clip_right = text_left + reading_width;@@ -6274,7 +6368,7 @@ impl crate::TermWindow {let wrap_key = wrap_hasher.finish() as usize;let visual = if let Some(visual) = self.right_sidebar_note.cached_wrapped_visual(wrap_key) {visual- } else if self.right_sidebar_note.prefers_background_wrap() {+ } else if self.right_sidebar_note.should_background_wrap(wrap_key) {let normal_approx_metrics = self.note_approximate_text_metrics(ui_font, &ui_metrics)?;let h1_approx_metrics = self.note_approximate_text_metrics(&h1_font, &h1_metrics)?;let h2_approx_metrics = self.note_approximate_text_metrics(&h2_font, &h2_metrics)?;@@ -6292,7 +6386,9 @@ impl crate::TermWindow {);self.right_sidebar_note.provisional_wrapped_visual()} else {- let wrap_stage = crate::input_diagnostics::StageTimer::begin("note_wrap");+ // UI-thread wrap: the number that decides whether real+ // incremental wrapping is ever needed.+ let wrap_stage = crate::input_diagnostics::StageTimer::begin("note_wrap_sync");let mut wrap_cache = std::mem::take(&mut self.right_sidebar_note.wrap_cache);let wrapped = wrap_visual_document_by_width_cached(&self.right_sidebar_note.visual,@@ -8004,6 +8100,29 @@ impl crate::TermWindow {foreground: LinearRgba,muted_fg: LinearRgba,rect: RightSidebarRect,+ ) -> anyhow::Result<()> {+ // All preview shaping (visible slices, horizontal-scroll full lines,+ // syntax-coloured lines) goes through the File Preview domain cache.+ let previous_domain = self+ .ui_text_domain+ .replace(crate::shapecache::UiTextDomain::FilePreview);+ let result = self.paint_right_sidebar_file_preview_pane_impl(+ layers, ui_font, ui_metrics, chrome, foreground, muted_fg, rect,+ );+ self.ui_text_domain.set(previous_domain);+ result+ }++ #[allow(clippy::too_many_arguments)]+ fn paint_right_sidebar_file_preview_pane_impl(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ chrome: UiPalette,+ foreground: LinearRgba,+ muted_fg: LinearRgba,+ rect: RightSidebarRect,) -> anyhow::Result<()> {let sidebar_bg = chrome.workspace_sidebar_bg;if rect.y > 0 {@@ -12037,6 +12156,7 @@ fn snippet_cursor_visible(now_ms: u128, blink_ms: u64) -> bool {#[cfg(test)]mod tests {use super::{+ FileReleaseAction, NoteReleaseAction, file_release_action, note_release_action,FILE_PREVIEW_MAX_BYTES, NOTE_CODE_BLOCK_RADIUS, NOTE_CODE_HEADER_HEIGHT,NoteApproximateTextMetrics, NoteCodeHighlightEntry, NoteCodeHighlightState,approximate_note_text_width, build_right_sidebar_file_index, clip_note_texture,@@ -12075,6 +12195,48 @@ mod tests {}}+ #[test]+ fn idle_release_decisions_respect_token_visibility_and_dirty_state() {+ // Stale token: another open re-armed the timer; never release.+ assert_eq!(+ note_release_action(false, false, false),+ NoteReleaseAction::Skip+ );+ assert_eq!(+ file_release_action(false, false, false),+ FileReleaseAction::Skip+ );+ // Visible feature: never release, even with a matching token.+ assert_eq!(+ note_release_action(true, true, false),+ NoteReleaseAction::Skip+ );+ assert_eq!(+ file_release_action(true, true, true),+ FileReleaseAction::Skip+ );+ // Hidden + idle: release.+ assert_eq!(+ note_release_action(true, false, false),+ NoteReleaseAction::Release+ );+ assert_eq!(+ file_release_action(true, false, false),+ FileReleaseAction::Release+ );+ // Dirty Note saves first and re-arms instead of dropping edits.+ assert_eq!(+ note_release_action(true, false, true),+ NoteReleaseAction::SaveAndReschedule+ );+ // Hidden while still indexing: re-arm so the release eventually+ // happens instead of leaking forever.+ assert_eq!(+ file_release_action(true, false, true),+ FileReleaseAction::RescheduleWhileIndexing+ );+ }+#[test]fn note_virtualization_keeps_modest_overscan_around_the_viewport() {let geometry = (0..1_000)