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
mux: carry kitty animation frames to remote panes (codec 64)
RoversXc60cc96426b6
diff --git a/codec/src/lib.rs b/codec/src/lib.rsindex 893f3d90..132ed833 100644--- a/codec/src/lib.rs+++ b/codec/src/lib.rs@@ -487,7 +487,12 @@ macro_rules! pdu {/// cold-start delivery and for `thinkterm cli agent list`./// 62: Projects carry an archived state in the shared ThinkTerm tree/// (TtProject.archived_at, TreeOp::SetProjectArchived).-pub const CODEC_VERSION: usize = 63;+/// 64: Image cells carry the image's generation, so a client notices when+/// an animation it already fetched has grown; GetImageCell can ask for+/// only the frames it lacks and is told the generation it received.+/// The server probes silent clients with Ping and a client answers+/// Pong; a remote pane reports its keyboard encoding.+pub const CODEC_VERSION: usize = 64;// Defines the Pdu enum.// Each struct has an explicit identifying number.@@ -1395,6 +1400,10 @@ pub struct SerializedImageCell {pub bottom_right: TextureCoordinate,/// Image::data::hash() for the ImageCell::data fieldpub data_hash: [u8; 32],+ /// `ImageData::generation()` at serialization: the payload behind a+ /// hash changes in place as an animation grows, and this is how a+ /// client that has the hash learns its copy is behind.+ pub data_generation: u64,pub z_index: i32,pub padding_left: u16,pub padding_top: u16,@@ -1526,6 +1535,7 @@ impl From<Vec<(StableRowIndex, Line)>> for SerializedLines {image_id: imcell.image_id(),placement_id: imcell.placement_id(),data_hash: imcell.image_data().hash(),+ data_generation: imcell.image_data().generation(),});}}@@ -1582,12 +1592,24 @@ pub struct GetImageCell {pub line_idx: StableRowIndex,pub cell_idx: usize,pub data_hash: [u8; 32],+ /// The generation the client saw on the cell; informational.+ pub data_generation: u64,+ /// Animation frames the client already holds for this hash, so the+ /// server can send only the ones after them. 0 asks for everything.+ pub have_frames: u32,}#[derive(Deserialize, Serialize, PartialEq, Debug)]pub struct GetImageCellResponse {pub pane_id: PaneId,pub data: Option<Arc<ImageData>>,+ /// The generation `data` was taken from.+ pub data_generation: u64,+ /// 0: `data` is the whole image. Otherwise `data` is an AnimRgba8+ /// holding only the frames from this index on, together with the+ /// durations and per-frame hashes of *every* frame, so the client can+ /// check the frames it holds are still the ones in front.+ pub frames_from: u32,}#[cfg(test)]@@ -2128,7 +2150,7 @@ mod test {// The exact assertion is the tripwire: whoever bumps the codec must// come here, confirm the round-trips still cover the new version,// and advance it deliberately.- assert_eq!(CODEC_VERSION, 63);+ assert_eq!(CODEC_VERSION, 64);use thinkterm_proto::{AgentEvidence, AgentState, AgentStatus};fn round_trip(pdu: Pdu) {diff --git a/term/src/terminalstate/kitty.rs b/term/src/terminalstate/kitty.rsindex 97f8685d..91f4329c 100644--- a/term/src/terminalstate/kitty.rs+++ b/term/src/terminalstate/kitty.rs@@ -732,6 +732,12 @@ impl TerminalState {/// it doubles as the glyph cache's key, and changing it per frame would/// rebuild the decoded image on every paint and reset the animation clock.fn kitty_touch_placements_for_image(&mut self, image_id: u32) {+ // The identity stays; the generation says the pixels moved. A mux+ // client holds a copy of the image, not the shared Arc, and this is+ // the only signal that its copy has fallen behind.+ if let Some(data) = self.kitty_img.id_to_data.get(&image_id) {+ data.bump_generation();+ }let placements: Vec<PlacementInfo> = self.kitty_img.placementsdiff --git a/term/src/test/graphics.rs b/term/src/test/graphics.rsindex f027ea5f..862a39d6 100644--- a/term/src/test/graphics.rs+++ b/term/src/test/graphics.rs@@ -1080,6 +1080,37 @@ fn a_frame_dirties_the_rows_holding_its_placement() {);}+#[test]+fn a_frame_moves_the_image_generation_but_not_its_hash() {+ // A mux client holds a copy of the image and sees only the hash on the+ // wire. The hash must stay (it is the glyph cache's key, and a new one+ // per frame would restart the animation), so the generation is what+ // tells the client its copy fell behind.+ let mut term = term(640, 384, true);+ term.advance_bytes("\x1b[H");+ term.advance_bytes(XMIT_2X2);+ term.advance_bytes("\x1b_Ga=p,i=1\x1b\\");+ let image = term+ .screen()+ .lines_in_phys_range(0..1)+ .remove(0)+ .get_cell(0)+ .and_then(|c| c.attrs().images())+ .and_then(|imgs| imgs.into_iter().next())+ .map(|img| Arc::clone(img.image_data()))+ .expect("the placement attached the image");+ let (hash, generation) = (image.hash(), image.generation());++ term.advance_bytes(FRAME_2X2);+ std::assert_eq!(image.hash(), hash, "the identity must not change");+ assert!(+ image.generation() > generation,+ "the generation must move: {} -> {}",+ generation,+ image.generation()+ );+}+#[test]fn a_frame_for_a_placement_on_the_other_screen_dirties_that_screen() {// Frames keep arriving for a picture on the primary screen while adiff --git a/wezterm-cell/src/image.rs b/wezterm-cell/src/image.rsindex b9a5805b..d667d1b9 100644--- a/wezterm-cell/src/image.rs+++ b/wezterm-cell/src/image.rs@@ -15,6 +15,7 @@ use ordered_float::NotNan;#[cfg(feature = "use_serde")]use serde::{Deserialize, Deserializer, Serialize, Serializer};use std::hash::{Hash, Hasher};+use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, Mutex, MutexGuard};use std::time::Duration;#[cfg(feature = "std")]@@ -327,8 +328,8 @@ impl ImageDataType {/// minted by different processes (this GUI, every mux server) from/// colliding in the client- and GPU-side caches that mix all sources.fn nonce_key() -> [u8; 32] {- use std::sync::atomic::{AtomicU64, Ordering};use std::sync::OnceLock;+ use std::sync::atomic::{AtomicU64, Ordering};static SALT: OnceLock<[u8; 16]> = OnceLock::new();static COUNTER: AtomicU64 = AtomicU64::new(0);let salt = SALT.get_or_init(|| {@@ -624,6 +625,14 @@ pub enum ImageCellError {pub struct ImageData {data: Mutex<ImageDataType>,hash: [u8; 32],+ /// Moves on every in-place change to `data`: an animation frame+ /// appended or edited. The hash cannot carry that news, because it is+ /// the picture's identity and the glyph cache's key, and a new one per+ /// frame would restart the animation on every frame. So a holder of a+ /// copy (a mux client) compares generations instead. Not serialized:+ /// the copy is told the generation it was made from alongside.+ #[cfg_attr(feature = "use_serde", serde(skip))]+ generation: AtomicU64,}struct HexSlice<'a>(&'a [u8]);@@ -641,6 +650,7 @@ impl std::fmt::Debug for ImageData {fmt.debug_struct("ImageData").field("data", &self.data).field("hash", &format_args!("{}", HexSlice(&self.hash)))+ .field("generation", &self.generation()).finish()}}@@ -667,6 +677,7 @@ impl ImageData {Self {data: Mutex::new(data),hash,+ generation: AtomicU64::new(0),}}@@ -675,9 +686,28 @@ impl ImageData {Self {data: Mutex::new(data),hash,+ generation: AtomicU64::new(0),}}+ /// How many in-place changes `data` has seen. See the field.+ pub fn generation(&self) -> u64 {+ self.generation.load(Ordering::Acquire)+ }++ /// Record an in-place change to `data`. Called after the change, not+ /// under the data lock, so a reader that takes the generation first and+ /// the payload second can only end up believing it is *behind*, never+ /// ahead.+ pub fn bump_generation(&self) -> u64 {+ self.generation.fetch_add(1, Ordering::AcqRel) + 1+ }++ /// For a copy: adopt the generation of the original it was made from.+ pub fn set_generation(&self, generation: u64) {+ self.generation.store(generation, Ordering::Release);+ }+/// Returns the in-memory footprintpub fn len(&self) -> usize {match &*self.data() {@@ -737,10 +767,7 @@ mod tests {let b = mk(vec![vec![0xff, 0, 0, 0xff]; 2], hashes.clone());assert_eq!(a.compute_hash(), b.compute_hash());// Different per-frame keys must change the identity.- let c = mk(- vec![vec![0, 0, 0, 0xff]; 2],- vec![[1u8; 32], [3u8; 32]],- );+ let c = mk(vec![vec![0, 0, 0, 0xff]; 2], vec![[1u8; 32], [3u8; 32]]);assert_ne!(a.compute_hash(), c.compute_hash());}}diff --git a/wezterm-client/src/pane/images.rs b/wezterm-client/src/pane/images.rsnew file mode 100644index 00000000..23342f29--- /dev/null+++ b/wezterm-client/src/pane/images.rs@@ -0,0 +1,212 @@+//! Keeping a remote pane's copy of an image in step with the original.+//!+//! The server shares one `Arc<ImageData>` between its terminal and every+//! cell that shows the picture, and an animation grows inside it: frames+//! are appended behind the mutex while the hash, which is the picture's+//! identity and the glyph cache's key, stays put. This side holds a copy+//! made from the wire, which nothing grows. So the copy is grown here: a+//! fetch brings the frames the copy lacks, and they are written into the+//! very Arc the cached lines and the glyph cache already point at. The+//! painter then sees the new frames the way it does for a local pane.++use std::sync::Arc;+use termwiz::image::{ImageData, ImageDataType};++/// The animation frames a copy holds: what to tell the server we have.+pub(crate) fn frame_count(data: &ImageDataType) -> u32 {+ match data {+ ImageDataType::AnimRgba8 { frames, .. } => frames.len() as u32,+ ImageDataType::Rgba8 { .. } => 1,+ _ => 0,+ }+}++/// Bring `held` up to date from `fetched`, in place. `frames_from` is 0+/// when `fetched` is the whole image, otherwise the index its frames start+/// at, in which case its durations and hashes cover every frame and the+/// hashes of the frames in front must match the ones held.+///+/// False means `fetched` could not be applied: the frames in front no+/// longer match, or the fetch would leave fewer frames than are held --+/// the painter indexes into the frame list by a cursor it keeps, and the+/// list must never shrink under it. `held` and `fetched` are untouched+/// then; the caller fetches the whole image or adopts `fetched` as is.+pub(crate) fn merge_into(+ held: &Arc<ImageData>,+ fetched: &Arc<ImageData>,+ frames_from: u32,+ generation: u64,+) -> bool {+ // Both locks, held first. `fetched` is private to this task, so the+ // order cannot cross anyone else's.+ let mut mine = held.data();+ let mut theirs = fetched.data();++ let merged = if frames_from == 0 {+ if frame_count(&theirs) < frame_count(&mine) {+ return false;+ }+ std::mem::replace(&mut *theirs, ImageDataType::EncodedFile(Vec::new()))+ } else {+ let from = frames_from as usize;+ let matches = match (&*theirs, &*mine) {+ (+ ImageDataType::AnimRgba8 {+ frames: tail,+ hashes,+ ..+ },+ ImageDataType::AnimRgba8 {+ hashes: held_hashes,+ ..+ },+ ) => {+ hashes.len() == from + tail.len()+ && held_hashes.len() == from+ && held_hashes[..] == hashes[..from]+ }+ (+ ImageDataType::AnimRgba8 {+ frames: tail,+ hashes,+ ..+ },+ ImageDataType::Rgba8 { hash, .. },+ ) => from == 1 && hashes.len() == 1 + tail.len() && hashes[0] == *hash,+ _ => false,+ };+ if !matches {+ return false;+ }+ let taken = std::mem::replace(&mut *theirs, ImageDataType::EncodedFile(Vec::new()));+ let ImageDataType::AnimRgba8 {+ width,+ height,+ durations,+ frames: tail,+ hashes,+ } = taken+ else {+ unreachable!("checked above");+ };+ let mut frames = match std::mem::replace(&mut *mine, ImageDataType::EncodedFile(Vec::new()))+ {+ ImageDataType::AnimRgba8 { frames, .. } => frames,+ ImageDataType::Rgba8 { data, .. } => vec![data],+ _ => unreachable!("checked above"),+ };+ frames.extend(tail);+ ImageDataType::AnimRgba8 {+ width,+ height,+ durations,+ frames,+ hashes,+ }+ };++ *mine = merged;+ drop(theirs);+ drop(mine);+ held.set_generation(generation);+ true+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::time::Duration;++ fn still(pixel: u8) -> Arc<ImageData> {+ Arc::new(ImageData::with_data(+ ImageDataType::new_single_frame_content_hashed(1, 1, vec![pixel; 4]),+ ))+ }++ fn frame_hash(pixel: u8) -> [u8; 32] {+ let image = still(pixel);+ let data = image.data();+ match &*data {+ ImageDataType::Rgba8 { hash, .. } => *hash,+ _ => unreachable!(),+ }+ }++ fn anim(pixels: &[u8]) -> ImageDataType {+ ImageDataType::AnimRgba8 {+ width: 1,+ height: 1,+ durations: vec![Duration::from_millis(40); pixels.len()],+ frames: pixels.iter().map(|p| vec![*p; 4]).collect(),+ hashes: pixels.iter().map(|p| frame_hash(*p)).collect(),+ }+ }++ /// A delta as the server builds it: frames from `from` on, every+ /// duration and hash.+ fn delta(pixels: &[u8], from: usize, hash: [u8; 32]) -> Arc<ImageData> {+ let ImageDataType::AnimRgba8 {+ width,+ height,+ durations,+ frames,+ hashes,+ } = anim(pixels)+ else {+ unreachable!()+ };+ Arc::new(ImageData::with_data_and_hash(+ ImageDataType::AnimRgba8 {+ width,+ height,+ durations,+ frames: frames[from..].to_vec(),+ hashes,+ },+ hash,+ ))+ }++ #[test]+ fn appended_frames_grow_the_held_copy_in_place() {+ let held = still(1);+ let hash = held.hash();+ assert!(merge_into(&held, &delta(&[1, 2, 3], 1, hash), 1, 7));+ assert_eq!(frame_count(&held.data()), 3);+ assert_eq!(held.generation(), 7);+ // Then two more frames on top of the three.+ assert!(merge_into(&held, &delta(&[1, 2, 3, 4, 5], 3, hash), 3, 9));+ assert_eq!(frame_count(&held.data()), 5);+ let data = held.data();+ let ImageDataType::AnimRgba8 { frames, hashes, .. } = &*data else {+ panic!("expected an animation, got {:?}", &*data);+ };+ assert_eq!(frames[4], vec![5; 4]);+ assert_eq!(hashes[4], frame_hash(5));+ }++ #[test]+ fn a_delta_whose_leading_frames_differ_is_refused() {+ // The frame in front was edited in place on the server: what we+ // hold is no longer the prefix, so appending would splice a stale+ // frame into a fresh animation.+ let held = still(1);+ let hash = held.hash();+ assert!(!merge_into(&held, &delta(&[9, 2], 1, hash), 1, 3));+ assert_eq!(frame_count(&held.data()), 1, "left alone");+ assert_eq!(held.generation(), 0, "left alone");+ }++ #[test]+ fn a_whole_image_replaces_the_copy_but_never_shrinks_it() {+ let held = still(1);+ let hash = held.hash();+ let whole = Arc::new(ImageData::with_data_and_hash(anim(&[1, 2]), hash));+ assert!(merge_into(&held, &whole, 0, 2));+ assert_eq!(frame_count(&held.data()), 2);++ let shorter = Arc::new(ImageData::with_data_and_hash(anim(&[1]), hash));+ assert!(!merge_into(&held, &shorter, 0, 3));+ assert_eq!(frame_count(&held.data()), 2, "a painter may be on frame 2");+ }+}diff --git a/wezterm-client/src/pane/mod.rs b/wezterm-client/src/pane/mod.rsindex eb469327..a13bc9b0 100644--- a/wezterm-client/src/pane/mod.rs+++ b/wezterm-client/src/pane/mod.rs@@ -2,5 +2,6 @@ pub use clientpane::ClientPane;pub(crate) use clientpane::remote_server_identity_matches;mod clientpane;+mod images;mod mousestate;mod renderable;diff --git a/wezterm-client/src/pane/renderable.rs b/wezterm-client/src/pane/renderable.rsindex 98f9dfba..06f3edd8 100644--- a/wezterm-client/src/pane/renderable.rs+++ b/wezterm-client/src/pane/renderable.rs@@ -1191,58 +1191,52 @@ pub(crate) async fn hydrate_lines(let mut requests = HashMap::new();let mut data_by_hash = HashMap::new();for im in &image_cells {- if let Some(data) = IMAGE_LRU.lock().unwrap().get(&im.data_hash) {- data_by_hash.insert(im.data_hash, Arc::clone(data));- } else {- requests- .entry(&im.data_hash)- .or_insert_with(|| GetImageCell {- pane_id,- line_idx: im.line_idx,- cell_idx: im.cell_idx,- data_hash: im.data_hash,+ let held = IMAGE_LRU.lock().unwrap().get(&im.data_hash).cloned();+ match held {+ // A copy at or past the generation the cell was sent with is+ // current. An animation grows behind an unchanging hash, so+ // the hash alone would say "have it" forever.+ Some(data) if data.generation() >= im.data_generation => {+ data_by_hash.insert(im.data_hash, data);+ }+ held => {+ requests.entry(im.data_hash).or_insert_with(|| {+ let have_frames = held+ .as_ref()+ .map(|data| super::images::frame_count(&data.data()))+ .unwrap_or(0);+ (+ held,+ GetImageCell {+ pane_id,+ line_idx: im.line_idx,+ cell_idx: im.cell_idx,+ data_hash: im.data_hash,+ data_generation: im.data_generation,+ have_frames,+ },+ )});+ }}}// Concurrently, not one at a time: these are independent round trips, so// awaiting them serially cost a line with N distinct images N times the- // latency. It also lost the race more often — the server answers by- // matching the hash against whatever occupies that cell *now*, so every- // extra round trip spent waiting is another chance for a newer frame to- // have overwritten it.+ // latency.let fetched = futures::future::join_all(requests.into_values()- .map(|request| client.client.get_image_cell(request)),+ .map(|(held, request)| fetch_image(&client, held, request)),).await;- for result in fetched {- match result {- Ok(GetImageCellResponse {- data: Some(data), ..- }) => {- IMAGE_LRU- .lock()- .unwrap()- .put(data.hash(), Arc::clone(&data));- data_by_hash.insert(data.hash(), data);- }- Ok(GetImageCellResponse { data: None, .. }) => {- // Not an error: the cell holds a different image by the time- // the request lands, which is the ordinary outcome for a pane- // streaming frames faster than the round trip. This cell just- // renders without the image and the next frame supersedes it.- // Logging it at error level buried genuine problems under- // thousands of lines.- log::debug!("image cell no longer holds the requested hash");- }-- Err(err) => {- log::error!("failed to retrieve image {err:#}");- }- }+ for data in fetched.into_iter().flatten() {+ IMAGE_LRU+ .lock()+ .unwrap()+ .put(data.hash(), Arc::clone(&data));+ data_by_hash.insert(data.hash(), data);}let mut line_by_idx = HashMap::new();@@ -1275,6 +1269,64 @@ pub(crate) async fn hydrate_lines(line_by_idx.into_iter().collect()}+/// Fetch the image `request` names and bring `held`, the copy already+/// filed under that hash, up to date in place; the Arc to file is returned.+/// A delta the copy cannot take (its leading frames no longer match) is+/// followed by one fetch of the whole image; a whole image the copy cannot+/// take is adopted as a fresh Arc, and lines hydrated from now on point at+/// that one.+async fn fetch_image(+ client: &Arc<ClientInner>,+ held: Option<Arc<ImageData>>,+ request: GetImageCell,+) -> Option<Arc<ImageData>> {+ let whole = GetImageCell {+ have_frames: 0,+ ..request+ };+ let asked_for_delta = request.have_frames > 0;+ let mut response = client.client.get_image_cell(request).await;+ for _ in 0..2 {+ match response {+ Ok(GetImageCellResponse {+ data: Some(fresh),+ data_generation,+ frames_from,+ ..+ }) => {+ let Some(held) = &held else {+ fresh.set_generation(data_generation);+ return Some(fresh);+ };+ if super::images::merge_into(held, &fresh, frames_from, data_generation) {+ return Some(Arc::clone(held));+ }+ if frames_from > 0 && asked_for_delta {+ log::debug!("image delta did not fit the copy held; fetching the whole image");+ response = client.client.get_image_cell(GetImageCell { ..whole }).await;+ continue;+ }+ fresh.set_generation(data_generation);+ return Some(fresh);+ }+ Ok(GetImageCellResponse { data: None, .. }) => {+ // Not an error: the image has been let go of on the server+ // by the time the request lands, which is the ordinary+ // outcome for a pane streaming frames faster than the round+ // trip. This cell renders without it and the next frame+ // supersedes it.+ log::debug!("image cell no longer holds the requested hash");+ return None;+ }+ Err(err) => {+ log::error!("failed to retrieve image {err:#}");+ return None;+ }+ }+ }+ None+}+impl RenderableState {pub fn get_cursor_position(&self) -> StableCursorPosition {self.inner.borrow().cursor_positiondiff --git a/wezterm-mux-server-impl/src/sent_images.rs b/wezterm-mux-server-impl/src/sent_images.rsindex 8b1b10e5..7e8e007f 100644--- a/wezterm-mux-server-impl/src/sent_images.rs+++ b/wezterm-mux-server-impl/src/sent_images.rs@@ -16,7 +16,7 @@use lru::LruCache;use std::num::NonZeroUsize;use std::sync::Arc;-use termwiz::image::ImageData;+use termwiz::image::{ImageData, ImageDataType};use termwiz::surface::Line;use wezterm_term::StableRowIndex;@@ -93,6 +93,49 @@ impl SentImages {}}+/// What to send for `image` to a client that already holds `have_frames`+/// of it: the generation, the payload, and the index the payload's frames+/// start at (0 for the whole image).+///+/// An animation the client has most of is answered with the frames after+/// the ones it holds, plus the durations and hashes of every frame so it+/// can verify the ones in front are still the same. Anything else, or a+/// client holding nothing, gets the whole image.+pub(crate) fn reply_for(image: &Arc<ImageData>, have_frames: u32) -> (u64, Arc<ImageData>, u32) {+ // Generation first, payload second: a frame landing in between then+ // makes the client ask once more, where the other order would leave+ // it sure a stale copy was current.+ let generation = image.generation();+ if have_frames > 0 {+ let data = image.data();+ if let ImageDataType::AnimRgba8 {+ width,+ height,+ durations,+ frames,+ hashes,+ } = &*data+ {+ let have = have_frames as usize;+ if have < frames.len() {+ let tail = ImageDataType::AnimRgba8 {+ width: *width,+ height: *height,+ durations: durations.clone(),+ frames: frames[have..].to_vec(),+ hashes: hashes.clone(),+ };+ // Carries the original's hash although it is only part of+ // it: the client files it under that hash, and never+ // re-derives the hash from a delta.+ let delta = Arc::new(ImageData::with_data_and_hash(tail, image.hash()));+ return (generation, delta, have_frames);+ }+ }+ }+ (generation, Arc::clone(image), 0)+}+#[cfg(test)]mod tests {use super::*;@@ -161,6 +204,68 @@ mod tests {assert!(sent.get(&big.hash()).is_some());}+ fn animation(pixels: &[u8]) -> Arc<ImageData> {+ Arc::new(ImageData::with_data(ImageDataType::AnimRgba8 {+ width: 1,+ height: 1,+ durations: vec![std::time::Duration::from_millis(40); pixels.len()],+ frames: pixels.iter().map(|p| vec![*p; 4]).collect(),+ hashes: pixels.iter().map(|p| [*p; 32]).collect(),+ }))+ }++ fn frames_of(image: &ImageData) -> Vec<Vec<u8>> {+ match &*image.data() {+ ImageDataType::AnimRgba8 { frames, .. } => frames.clone(),+ _ => vec![],+ }+ }++ #[test]+ fn a_client_holding_some_frames_gets_only_the_rest() {+ let image = animation(&[1, 2, 3, 4]);+ image.bump_generation();+ let (generation, payload, from) = reply_for(&image, 2);+ assert_eq!(generation, 1);+ assert_eq!(from, 2);+ assert_eq!(frames_of(&payload), vec![vec![3; 4], vec![4; 4]]);+ assert_eq!(payload.hash(), image.hash(), "filed under the same hash");+ let data = payload.data();+ let ImageDataType::AnimRgba8 {+ hashes, durations, ..+ } = &*data+ else {+ panic!("expected an animation, got {:?}", &*data);+ };+ assert_eq!(hashes.len(), 4, "every frame's hash, for the prefix check");+ assert_eq!(durations.len(), 4);+ }++ #[test]+ fn a_client_holding_nothing_or_everything_gets_the_whole_image() {+ let image = animation(&[1, 2]);+ let (_, payload, from) = reply_for(&image, 0);+ assert!(Arc::ptr_eq(&payload, &image));+ assert_eq!(from, 0);+ let (_, payload, from) = reply_for(&image, 2);+ assert!(Arc::ptr_eq(&payload, &image));+ assert_eq!(from, 0);+ let (_, payload, from) = reply_for(&image, 5);+ assert!(+ Arc::ptr_eq(&payload, &image),+ "a count from the future is not trusted"+ );+ assert_eq!(from, 0);+ }++ #[test]+ fn a_still_image_is_never_answered_with_a_delta() {+ let image = image(b"still");+ let (_, payload, from) = reply_for(&image, 1);+ assert!(Arc::ptr_eq(&payload, &image));+ assert_eq!(from, 0);+ }+#[test]fn re_sending_an_image_makes_it_recent_again() {let mut sent = SentImages::with_limits(2, usize::MAX);diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rsindex 8ebd1291..c2c95810 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -1510,6 +1510,8 @@ impl SessionHandler {line_idx,cell_idx,data_hash,+ data_generation: _,+ have_frames,}) => {let per_pane = self.per_pane(pane_id);spawn_into_main_thread(async move {@@ -1546,9 +1548,19 @@ impl SessionHandler {.insert(Arc::clone(found));}}+ let (data_generation, data, frames_from) = match &data {+ Some(image) => {+ let (generation, payload, from) =+ crate::sent_images::reply_for(image, have_frames);+ (generation, Some(payload), from)+ }+ None => (0, None, 0),+ };Ok(Pdu::GetImageCellResponse(GetImageCellResponse {pane_id,data,+ data_generation,+ frames_from,}))},send_response,