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
term,config: bound the kitty image store with a per-pane memory budget
RoversX6a5c4d4f3100
diff --git a/config/src/config.rs b/config/src/config.rsindex c2073499..22c5a230 100644--- a/config/src/config.rs+++ b/config/src/config.rs@@ -269,6 +269,14 @@ pub struct Config {#[dynamic(default = "default_true")]pub enable_kitty_graphics: bool,+ /// MiB of kitty image data each pane may keep. Past it the oldest+ /// unplaced images go first; if the placed ones alone exceed it, the+ /// least recently placed or transmitted picture is removed from the+ /// screen too (kitty's own rule), except the newest. One animation is+ /// additionally capped at the smaller of this budget and 256 MiB.+ /// 0 means unlimited. Default 128.+ #[dynamic(default = "default_kitty_image_memory_budget_mib")]+ pub kitty_image_memory_budget_mib: u32,#[dynamic(default)]pub enable_kitty_keyboard: bool,@@ -2347,6 +2355,10 @@ fn default_glyph_cache_image_cache_size() -> usize {256}+fn default_kitty_image_memory_budget_mib() -> u32 {+ (wezterm_term::config::DEFAULT_KITTY_IMAGE_MEMORY_BUDGET / (1024 * 1024)) as u32+}+fn default_note_reading_max_width() -> usize {820}diff --git a/config/src/terminal.rs b/config/src/terminal.rsindex 81e6b513..cbb4385c 100644--- a/config/src/terminal.rs+++ b/config/src/terminal.rs@@ -82,6 +82,15 @@ impl wezterm_term::TerminalConfiguration for TermConfig {self.configuration().enable_kitty_graphics}+ fn kitty_image_memory_budget(&self) -> usize {+ match self.configuration().kitty_image_memory_budget_mib {+ // The natural reading of 0, and the safe one: taking it+ // literally would evict every picture on arrival.+ 0 => usize::MAX,+ mib => (mib as usize).saturating_mul(1024 * 1024),+ }+ }+fn enable_title_reporting(&self) -> bool {self.configuration().enable_title_reporting}diff --git a/term/src/config.rs b/term/src/config.rsindex 78c68a57..d48a4d34 100644--- a/term/src/config.rs+++ b/term/src/config.rs@@ -132,6 +132,9 @@ impl Default for NewlineCanon {/// The configuration can be changed at runtime; provided that the implementation/// increments the generation counter appropriately, the changes will be detected/// and applied at the next appropriate opportunity.+/// See [`TerminalConfiguration::kitty_image_memory_budget`].+pub const DEFAULT_KITTY_IMAGE_MEMORY_BUDGET: usize = 128 * 1024 * 1024;+pub trait TerminalConfiguration: Downcast + std::fmt::Debug + Send + Sync {/// Returns a generation counter for the active/// configuration. If the implementation may be@@ -176,6 +179,17 @@ pub trait TerminalConfiguration: Downcast + std::fmt::Debug + Send + Sync {false}+ /// How many bytes of kitty image data one terminal may keep. Beyond it+ /// the oldest unplaced images are evicted first; if the placed ones+ /// alone exceed it, the least recently placed or transmitted picture is+ /// detached from its cells and dropped as well, newest excepted. A+ /// streaming client that sends every frame under a fresh id relies on+ /// this to bound its footprint: a 1632x1026 RGBA frame is 6.7MiB, so the+ /// default keeps roughly twenty of them.+ fn kitty_image_memory_budget(&self) -> usize {+ DEFAULT_KITTY_IMAGE_MEMORY_BUDGET+ }+fn enable_kitty_keyboard(&self) -> bool {false}diff --git a/term/src/terminalstate/image.rs b/term/src/terminalstate/image.rsindex e0d5aad6..873db676 100644--- a/term/src/terminalstate/image.rs+++ b/term/src/terminalstate/image.rs@@ -14,6 +14,11 @@ pub struct PlacementInfo {pub first_row: StableRowIndex,pub rows: usize,pub cols: usize,+ /// Which screen the cells live on. Removal must target that screen:+ /// the budget sweep can fire while the other one is active, and+ /// detaching rows on the wrong screen frees nothing while the picture+ /// comes back with the screen switch.+ pub alt_screen: bool,}#[derive(Debug, PartialEq, Eq)]@@ -274,6 +279,7 @@ impl TerminalState {first_row,rows: height_in_cells,cols: width_in_cells,+ alt_screen: self.screen.is_alt_screen_active(),})}diff --git a/term/src/terminalstate/kitty.rs b/term/src/terminalstate/kitty.rsindex 9d9cd433..f3b23b55 100644--- a/term/src/terminalstate/kitty.rs+++ b/term/src/terminalstate/kitty.rs@@ -57,18 +57,70 @@ pub struct KittyImageState {max_image_id: u32,number_to_id: HashMap<u32, u32>,id_to_data: HashMap<u32, Arc<ImageData>>,+ /// Transmission order of each stored image, so eviction drops the+ /// oldest unplaced image first. A HashMap walk would evict at random,+ /// which for a frame stream means keeping stale frames over fresh ones.+ id_seq: HashMap<u32, u64>,+ next_seq: u64,placements: HashMap<(u32, Option<u32>), PlacementInfo>,used_memory: usize,}impl KittyImageState {+ /// Bytes actually held: small pictures with identical pixels share one+ /// `ImageData` through the content-hash cache, so summing per id would+ /// count a logo re-emitted under fresh ids once per prompt, and the+ /// sweep acting on that phantom total would detach real pictures.+ fn recompute_used_memory(&mut self) {+ let mut seen: HashSet<*const ImageData> = HashSet::new();+ self.used_memory = self+ .id_to_data+ .values()+ .filter(|data| seen.insert(Arc::as_ptr(data)))+ .map(|data| data.len())+ .sum();+ }+fn remove_data_for_id(&mut self, image_id: u32) {- if let Some(data) = self.id_to_data.remove(&image_id) {- self.used_memory = self.used_memory.saturating_sub(data.len());+ self.id_to_data.remove(&image_id);+ self.id_seq.remove(&image_id);+ self.recompute_used_memory();+ }++ /// Eviction, as opposed to replacement: an image number that named the+ /// evicted id must not keep resolving to it, or every later `a=p,I=n`+ /// fails on an id that no longer exists.+ fn evict(&mut self, image_id: u32) {+ self.remove_data_for_id(image_id);+ self.number_to_id.retain(|_, id| *id != image_id);+ }++ /// The stored image that was transmitted earliest, skipping the most+ /// recent one (it is about to be placed).+ fn oldest_stored_image_except_newest(&self) -> Option<u32> {+ let newest = self.next_seq;+ self.id_to_data+ .keys()+ .filter_map(|id| {+ let seq = self.id_seq.get(id).copied().unwrap_or(0);+ (seq != newest).then_some((seq, *id))+ })+ .min()+ .map(|(_, id)| id)+ }++ /// An appended animation frame is the newest image data in the store,+ /// even though it arrived through `a=f` rather than a transmit. Without+ /// this the sweep would protect some later still picture and evict the+ /// animation that is being streamed into, mid-stream.+ fn mark_newest(&mut self, image_id: u32) {+ if self.id_seq.contains_key(&image_id) {+ self.next_seq += 1;+ self.id_seq.insert(image_id, self.next_seq);}}- fn record_id_to_data(&mut self, image_id: u32, data: Arc<ImageData>) {+ fn record_id_to_data(&mut self, image_id: u32, data: Arc<ImageData>, budget: usize) {// Unconditionally, id 0 included. The insert below replaces whatever// was at this key either way, so skipping the bookkeeping for the// anonymous-transmission key does not keep that image alive — it only@@ -77,9 +129,23 @@ impl KittyImageState {// evicting every unplaced image on every transfer, which breaks// transmit-now-place-later.self.remove_data_for_id(image_id);- self.prune_unreferenced();- self.used_memory += data.len();self.id_to_data.insert(image_id, data);+ self.recompute_used_memory();+ self.next_seq += 1;+ self.id_seq.insert(image_id, self.next_seq);+ if self.next_seq % 100 == 0 {+ log::info!(+ "kitty store: images={} bytes={} placements={} (after {} transmits)",+ self.id_to_data.len(),+ self.used_memory,+ self.placements.len(),+ self.next_seq+ );+ }+ // After the insert, so the budget holds strictly; the image just+ // stored is the newest and prune never evicts that one, which keeps+ // transmit-now-place-later working.+ self.prune_unreferenced(budget);}#[cfg(test)]@@ -87,28 +153,73 @@ impl KittyImageState {self.used_memory}- pub(crate) fn prune_unreferenced(&mut self) {- let budget = 320 * 1024 * 1024; // FIXME: make this configurable- if self.used_memory > budget {- let referenced: HashSet<u32> = self.placements.keys().map(|(k, _)| *k).collect();- let target = self.used_memory - budget;- let mut freed = 0;- self.id_to_data.retain(|id, data| {- if referenced.contains(id) || freed > target {- true- } else {- freed += data.len();- false- }- });+ /// Evict unplaced images, oldest transmission first, until the stored+ /// bytes fit `budget`. Placed images and the most recently transmitted+ /// image are never touched.+ pub(crate) fn prune_unreferenced(&mut self, budget: usize) {+ if self.used_memory <= budget {+ return;+ }+ let referenced: HashSet<u32> = self.placements.keys().map(|(k, _)| *k).collect();+ let newest = self.next_seq;+ let before = self.used_memory;+ let mut candidates: Vec<(u64, u32)> = self+ .id_to_data+ .keys()+ .filter(|id| !referenced.contains(id) && self.id_seq.get(id).copied() != Some(newest))+ .map(|id| (self.id_seq.get(id).copied().unwrap_or(0), *id))+ .collect();+ candidates.sort_unstable();+ // Re-measured after every eviction rather than summed from lengths:+ // dropping one id of a shared picture frees nothing.+ for (_, id) in candidates {+ if self.used_memory <= budget {+ break;+ }+ self.evict(id);+ }+ // Debug, not info: a frame stream prunes on nearly every transfer.+ log::debug!(+ "using {} RAM for images, pruned {} (budget {})",+ self.used_memory,+ before.saturating_sub(self.used_memory),+ budget+ );+ }+}- log::info!(- "using {} RAM for images, pruned {}",- self.used_memory,- freed- );- self.used_memory = self.used_memory.saturating_sub(freed);+#[cfg(test)]+mod prune_tests {+ use super::KittyImageState;+ use std::sync::Arc;+ use wezterm_cell::image::{ImageData, ImageDataType};++ fn image(side: u32) -> Arc<ImageData> {+ Arc::new(ImageData::with_data(ImageDataType::new_single_frame(+ side,+ side,+ vec![0u8; (side * side * 4) as usize],+ )))+ }++ #[test]+ fn the_oldest_unplaced_images_go_first_and_placed_ones_never() {+ let mut state = KittyImageState::default();+ let one = image(16).len();+ let budget = 3 * one;+ for id in 1..=5 {+ state.record_id_to_data(id, image(16), budget);}+ // Five transfers against a three-image budget hold the three newest.+ let mut kept: Vec<u32> = state.id_to_data.keys().copied().collect();+ kept.sort();+ assert_eq!(kept, vec![3, 4, 5]);+ assert_eq!(state.used_memory, budget);++ // Re-transmitting an id replaces it without double counting.+ state.record_id_to_data(5, image(16), budget);+ assert_eq!(state.used_memory, budget);+ assert_eq!(state.id_to_data.len(), 3);}}@@ -137,6 +248,30 @@ impl TerminalState {self.kitty_img.used_memory()}+ /// Kitty's own rule for a full image store: the oldest images go,+ /// placed ones included, placements and all. Without it an application+ /// that never deletes -- a frame stream placing every frame under a+ /// fresh id, so every frame stays attached to its cells under the next+ /// one -- grows the terminal without bound until it happens to clear+ /// the screen. Unplaced images go first; the image transmitted last is+ /// always kept.+ pub(crate) fn kitty_enforce_image_budget(&mut self) {+ let budget = self.config.kitty_image_memory_budget();+ self.kitty_img.prune_unreferenced(budget);+ while self.kitty_img.used_memory > budget {+ let Some(victim) = self.kitty_img.oldest_stored_image_except_newest() else {+ break;+ };+ log::debug!(+ "kitty store over budget ({} > {}): evicting placed image {victim}",+ self.kitty_img.used_memory,+ budget+ );+ self.kitty_remove_placement(victim, None);+ self.kitty_img.evict(victim);+ }+ }+fn kitty_img_place(&mut self,image_id: Option<u32>,@@ -197,6 +332,10 @@ impl TerminalState {let (image_width, image_height) = img.data().dimensions()?;+ // Kitty evicts by last use, not by transmit order: a picture sent+ // once and re-placed on every redraw must outlive frames streamed+ // after it, or the client's next `a=p` fails on a missing id.+ self.kitty_img.mark_newest(image_id);let info = self.assign_image_to_cells(ImageAttachParams {image_width,image_height,@@ -608,7 +747,10 @@ impl TerminalState {info: PlacementInfo,) {let seqno = self.seqno;- let screen = self.screen_mut();+ // The recorded screen, not the active one: the sweep can run while+ // the other screen is up (a stream in one pane, btop in this one),+ // and StableRowIndex only means anything on the screen it came from.+ let screen = self.screen.screen_for_alt_mut(info.alt_screen);let range =screen.stable_range(&(info.first_row..info.first_row + info.rows as StableRowIndex));for idx in range {@@ -655,6 +797,7 @@ impl TerminalState {}if delete {self.kitty_img.id_to_data.clear();+ self.kitty_img.id_seq.clear();self.kitty_img.used_memory = 0;self.kitty_img.number_to_id.clear();}@@ -914,11 +1057,6 @@ impl TerminalState {}};- // Measured before and after, because frames are appended behind the- // Mutex: the size reported to the memory budget when the image was- // transmitted goes stale the moment an animation grows.- let bytes_before = image.len();-let mut anim = image.data();let x = frame.x.unwrap_or(0);let y = frame.y.unwrap_or(0);@@ -1021,8 +1159,15 @@ impl TerminalState {.saturating_mul(*height as usize).saturating_mul(4);let held = frames.len().saturating_mul(frame_bytes);+ // The animation caps bound one image; the pane budget+ // bounds the store, and an appended frame grows the+ // store without passing through the transmit path that+ // enforces it. One image is never allowed to fill the+ // whole budget on its own, and the sweep below the+ // append reclaims older images for what does fit.+ let budget = self.config.kitty_image_memory_budget();if frames.len() + 1 > MAX_ANIM_FRAMES- || held.saturating_add(frame_bytes) > MAX_ANIM_BYTES+ || held.saturating_add(frame_bytes) > MAX_ANIM_BYTES.min(budget){// Answered from here because the caller only logs// errors; a refusal the client never hears leaves it@@ -1040,7 +1185,7 @@ impl TerminalState {image_id,held.saturating_add(frame_bytes),frames.len() + 1,- MAX_ANIM_BYTES,+ MAX_ANIM_BYTES.min(budget),MAX_ANIM_FRAMES);}@@ -1100,14 +1245,15 @@ impl TerminalState {drop(anim);- let bytes_after = image.len();- self.kitty_img.used_memory = self- .kitty_img- .used_memory- .saturating_add(bytes_after)- .saturating_sub(bytes_before);+ // Frames are appended behind the Mutex, so the total measured when+ // the image was transmitted is stale the moment an animation grows.+ self.kitty_img.recompute_used_memory();self.kitty_touch_placements_for_image(image_id);+ // A grown animation is a bigger store: apply the same sweep a+ // transmit gets, so appends cannot carry the pane past its budget.+ self.kitty_img.mark_newest(image_id);+ self.kitty_enforce_image_budget();Ok(())}@@ -1163,10 +1309,22 @@ impl TerminalState {}};- let data = transmit- .data- .load_data()- .context("data should have been materialized in coalesce_kitty_accumulation")?;+ let data = match transmit.data.load_data() {+ Ok(data) => data,+ Err(err) => {+ // A client that counts one answer per transmission (q=0, or+ // a stream pacing itself on ACKs) would otherwise wait on a+ // reply that never comes; kitty answers a failed read too.+ // The number allocated above must not outlive the image it+ // never got.+ if let Some(no) = no {+ self.kitty_img.number_to_id.remove(&no);+ }+ self.kitty_send_response(verbosity, false, Some(id), no, format!("EBADF:{err}"));+ return Err(anyhow::Error::new(err)+ .context("data should have been materialized in coalesce_kitty_accumulation"));+ }+ };let data = match transmit.compression {KittyImageCompression::None => data,@@ -1219,6 +1377,11 @@ impl TerminalState {width * height * 4);+ // The buffer keeps whatever capacity reading it left behind,+ // and this image may sit in the store for a long time; the+ // memory accounting counts len(), so make the two agree.+ let mut data = data;+ data.shrink_to_fit();ImageDataType::new_single_frame(width, height, data)}Some(KittyImageFormat::Png) => {@@ -1248,7 +1411,9 @@ impl TerminalState {let img = self.raw_image_to_image_data(img).context("storing image data")?;- self.kitty_img.record_id_to_data(image_id, img);+ self.kitty_img+ .record_id_to_data(image_id, img, self.config.kitty_image_memory_budget());+ self.kitty_enforce_image_budget();Ok((image_id, image_number))}diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rsindex 58870094..63c299a8 100644--- a/term/src/terminalstate/mod.rs+++ b/term/src/terminalstate/mod.rs@@ -230,6 +230,16 @@ impl ScreenOrAlt {self.alt_screen_is_active}+ /// The named screen, active or not: image placements record which one+ /// their cells live on, and eviction must reach that one.+ pub fn screen_for_alt_mut(&mut self, alt_screen: bool) -> &mut Screen {+ if alt_screen {+ &mut self.alt_screen+ } else {+ &mut self.screen+ }+ }+pub fn saved_cursor(&mut self) -> &mut Option<SavedCursor> {if self.alt_screen_is_active {&mut self.alt_screen.saved_cursor@@ -810,7 +820,7 @@ impl TerminalState {// budget sweep — with the placements gone the images are// unreferenced, and anything over the budget is reclaimed right now.self.kitty_remove_all_placements(false);- self.kitty_img.prune_unreferenced();+ self.kitty_enforce_image_budget();self.kitty_reset_accumulator();self.erase_in_display(EraseInDisplay::EraseScrollback);diff --git a/term/src/terminalstate/performer.rs b/term/src/terminalstate/performer.rsindex b69cfab4..744ca592 100644--- a/term/src/terminalstate/performer.rs+++ b/term/src/terminalstate/performer.rs@@ -281,7 +281,18 @@ impl<'a> Performer<'a> {Action::KittyImage(img) => {self.flush_print();if let Err(err) = self.kitty_img(*img) {- log::error!("kitty_img: {:#}", err);+ // A frame the parser discarded as superseded carries an+ // Interrupted io error: expected under a backlog, and+ // hundreds per second when it happens.+ let superseded = err+ .root_cause()+ .downcast_ref::<std::io::Error>()+ .is_some_and(|e| e.kind() == std::io::ErrorKind::Interrupted);+ if superseded {+ log::debug!("kitty_img: {:#}", err);+ } else {+ log::error!("kitty_img: {:#}", err);+ }}}}diff --git a/term/src/test/graphics.rs b/term/src/test/graphics.rsindex 8d96b21b..99fbad8c 100644--- a/term/src/test/graphics.rs+++ b/term/src/test/graphics.rs@@ -15,6 +15,7 @@ use std::sync::{Arc, Mutex};#[derive(Debug)]struct GraphicsConfig {kitty: bool,+ image_budget: usize,}impl TerminalConfiguration for GraphicsConfig {@@ -29,9 +30,27 @@ impl TerminalConfiguration for GraphicsConfig {fn enable_kitty_graphics(&self) -> bool {self.kitty}++ fn kitty_image_memory_budget(&self) -> usize {+ self.image_budget+ }}fn term(pixel_width: usize, pixel_height: usize, kitty: bool) -> Terminal {+ term_with_budget(+ pixel_width,+ pixel_height,+ kitty,+ crate::config::DEFAULT_KITTY_IMAGE_MEMORY_BUDGET,+ )+}++fn term_with_budget(+ pixel_width: usize,+ pixel_height: usize,+ kitty: bool,+ image_budget: usize,+) -> Terminal {Terminal::new(TerminalSize {rows: 24,@@ -40,7 +59,10 @@ fn term(pixel_width: usize, pixel_height: usize, kitty: bool) -> Terminal {pixel_height,dpi: 96,},- Arc::new(GraphicsConfig { kitty }),+ Arc::new(GraphicsConfig {+ kitty,+ image_budget,+ }),"ThinkTerm","O_o",Box::new(Vec::new()),@@ -118,7 +140,10 @@ fn term_with_tap(pixel_width: usize, pixel_height: usize) -> (Terminal, Tap) {pixel_height,dpi: 96,},- Arc::new(GraphicsConfig { kitty: true }),+ Arc::new(GraphicsConfig {+ kitty: true,+ image_budget: crate::config::DEFAULT_KITTY_IMAGE_MEMORY_BUDGET,+ }),"ThinkTerm","O_o",Box::new(tap.clone()),@@ -859,3 +884,127 @@ fn clearing_the_scrollback_and_viewport_keeps_reusable_image_data() {"the stored image data should still be placeable after a clear");}++#[test]+fn eviction_reaches_a_placement_on_the_inactive_screen() {+ // Budget: two 2x2 frames. Image 1 is placed on the primary screen;+ // the stream that busts the budget runs on the alt screen. Eviction+ // must detach image 1 from the primary screen's cells even though the+ // alt screen is active when the sweep fires -- aiming at the active+ // screen would free nothing and the picture would revive on switch.+ let mut term = term_with_budget(640, 384, true, 2 * 16);+ let one = base64_of(&[1u8; 16]);+ term.advance_bytes(format!("\x1b[H\x1b_Ga=T,i=1,f=32,s=2,v=2;{one}\x1b\\"));+ term.advance_bytes("\x1b[?1049h");+ for id in 2..=5 {+ let pixels = base64_of(&[id as u8; 16]);+ term.advance_bytes(format!(+ "\x1b[H\x1b_Ga=T,i={id},f=32,s=2,v=2;{pixels}\x1b\\"+ ));+ }+ assert!(+ term.kitty_used_memory() <= 2 * 16,+ "stored image bytes {} exceed the budget",+ term.kitty_used_memory()+ );+ term.advance_bytes("\x1b[?1049l");+ let line = term.screen_mut().line_mut(0);+ let cell = line.get_cell(0).expect("cell 0,0");+ let holds_evicted = cell+ .attrs()+ .images()+ .map(|imgs| imgs.iter().any(|img| img.image_id() == Some(1)))+ .unwrap_or(false);+ assert!(+ !holds_evicted,+ "the evicted image is still attached to the primary screen"+ );+}++#[test]+fn appended_animation_frames_stay_within_the_image_budget() {+ // Budget: four 2x2 RGBA frames (64 bytes). Two still images fill half+ // of it; growing the first into an animation must reclaim the other+ // (unreferenced) picture before it is allowed to grow further, and+ // must be refused once the animation alone would fill the budget.+ let mut term = term_with_budget(640, 384, true, 4 * 16);+ // Placed, so the sweep treats it as in use and reclaims image 2 instead.+ term.advance_bytes("\x1b[H\x1b_Ga=T,i=1,f=32,s=2,v=2;AAAAAAAAAAAAAAAAAAAAAA==\x1b\\");+ // Different pixels from image 1: identical small images are content-+ // deduplicated into one shared object, and growing that object would+ // grow both.+ term.advance_bytes("\x1b_Ga=t,i=2,f=32,s=2,v=2;/////////////////////w==\x1b\\");+ k9::assert_equal!(term.kitty_used_memory(), 32);+ for _ in 0..6 {+ term.advance_bytes("\x1b_Ga=f,i=1,f=32,s=2,v=2;AAAAAAAAAAAAAAAAAAAAAA==\x1b\\");+ assert!(+ term.kitty_used_memory() <= 4 * 16,+ "stored image bytes {} exceed the budget after an append",+ term.kitty_used_memory()+ );+ }+ // Four frames of image 1 are exactly the budget; image 2 made room.+ k9::assert_equal!(term.kitty_used_memory(), 4 * 16);+}++/// Standard base64 for test payloads; the crate has no encoder of its own.+fn base64_of(bytes: &[u8]) -> String {+ const ALPHABET: &[u8; 64] =+ b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ let mut out = String::new();+ for chunk in bytes.chunks(3) {+ let mut word = 0u32;+ for (i, byte) in chunk.iter().enumerate() {+ word |= (*byte as u32) << (16 - 8 * i);+ }+ for i in 0..4 {+ if i <= chunk.len() {+ out.push(ALPHABET[((word >> (18 - 6 * i)) & 63) as usize] as char);+ } else {+ out.push('=');+ }+ }+ }+ out+}++#[test]+fn a_frame_stream_with_fresh_ids_is_capped_by_the_image_budget() {+ // Every frame is transmitted-and-displayed under a new id on the same+ // cells and never deleted, the way a streaming client behaves. Placed+ // images stack, so without a hard cap each cell keeps every frame ever+ // shown. Budget: three 2x2 RGBA images (16 bytes each).+ let mut term = term_with_budget(640, 384, true, 3 * 16);+ for id in 1..=20 {+ // Home first: a=T advances the cursor, and the point is to stack+ // every frame on the same cells like a redrawing client does.+ // Distinct pixels per frame, as a real stream has: identical small+ // payloads are content-deduplicated into one shared object, which+ // the budget correctly counts once.+ let pixels = base64_of(&[id as u8; 16]);+ term.advance_bytes(format!(+ "\x1b[H\x1b_Ga=T,i={id},f=32,s=2,v=2;{pixels}\x1b\\"+ ));+ }+ assert!(+ term.kitty_used_memory() <= 3 * 16,+ "stored image bytes {} exceed the budget",+ term.kitty_used_memory()+ );+ let line = term.screen_mut().line_mut(0);+ let cell = line.get_cell(0).expect("cell 0,0");+ let stacked = cell.attrs().images().map(|v| v.len()).unwrap_or(0);+ assert!(+ (1..=3).contains(&stacked),+ "cell keeps {} frames; expected the newest few, not all twenty",+ stacked+ );+ assert!(+ cell.attrs()+ .images()+ .unwrap()+ .iter()+ .any(|img| img.image_id() == Some(20)),+ "the newest frame must survive eviction"+ );+}