A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
perf(term): batch printable ASCII runs while preserving compact storage
RoversX23514ec0b4ef
diff --git a/docs/thinkterm/parser-throughput-results.json b/docs/thinkterm/parser-throughput-results.jsonnew file mode 100644index 00000000..7a1fb2d1--- /dev/null+++ b/docs/thinkterm/parser-throughput-results.json@@ -0,0 +1,97 @@+{+ "baseline_commit": "06bdaa4",+ "platform": "macOS, Apple M1 Pro, 16 GiB RAM",+ "kitten": "0.49.0",+ "size": [+ 120,+ 32+ ],+ "scrollback_lines": 3500,+ "repetitions": 100,+ "renderer": "none (isolated mux server)",+ "runs": {+ "baseline": [+ {+ "rates_mib_per_second": {+ "Only ASCII chars": 24.4,+ "Unicode chars": 46.9,+ "Unique multi-codepoint Unicode cells": 63.1,+ "CSI codes with few chars": 15.6,+ "Long escape codes": 202.1,+ "Images": 280.4+ },+ "peak_rss_bytes": 463372288+ },+ {+ "rates_mib_per_second": {+ "Only ASCII chars": 24.4,+ "Unicode chars": 46.4,+ "Unique multi-codepoint Unicode cells": 61.9,+ "CSI codes with few chars": 15.6,+ "Long escape codes": 201.6,+ "Images": 274.2+ },+ "peak_rss_bytes": 465534976+ },+ {+ "rates_mib_per_second": {+ "Only ASCII chars": 24.5,+ "Unicode chars": 46.9,+ "Unique multi-codepoint Unicode cells": 63.2,+ "CSI codes with few chars": 15.7,+ "Long escape codes": 201.0,+ "Images": 277.8+ },+ "peak_rss_bytes": 464502784+ }+ ],+ "candidate": [+ {+ "rates_mib_per_second": {+ "Only ASCII chars": 43.3,+ "Unicode chars": 48.0,+ "Unique multi-codepoint Unicode cells": 69.7,+ "CSI codes with few chars": 20.3,+ "Long escape codes": 200.7,+ "Images": 278.4+ },+ "peak_rss_bytes": 461225984+ },+ {+ "rates_mib_per_second": {+ "Only ASCII chars": 43.4,+ "Unicode chars": 48.0,+ "Unique multi-codepoint Unicode cells": 69.5,+ "CSI codes with few chars": 20.0,+ "Long escape codes": 198.6,+ "Images": 281.4+ },+ "peak_rss_bytes": 462503936+ },+ {+ "rates_mib_per_second": {+ "Only ASCII chars": 43.4,+ "Unicode chars": 48.0,+ "Unique multi-codepoint Unicode cells": 69.7,+ "CSI codes with few chars": 20.3,+ "Long escape codes": 214.8,+ "Images": 278.7+ },+ "peak_rss_bytes": 462192640+ }+ ]+ },+ "baseline_sha256": "67bf4f4be556eec5c4ffa568c894af8aa046917c21c430e8244fc2c1265d3dae",+ "candidate_sha256": "98d5209cd4a41b4a1f9cf78f48d9b88592811f35c49ddaeaf0f0307e8f61d186",+ "scrollback_check": {+ "baseline": {+ "repetitions": 200,+ "peak_rss_bytes": 447905792+ },+ "candidate": {+ "repetitions": 200,+ "peak_rss_bytes": 448315392+ }+ },+ "invalid_workload": "Images: both builds reported Invalid padding; rates measure a rejected transfer and are not successful image throughput."+}diff --git a/docs/thinkterm/parser-throughput.md b/docs/thinkterm/parser-throughput.mdnew file mode 100644index 00000000..88bf77fb--- /dev/null+++ b/docs/thinkterm/parser-throughput.md@@ -0,0 +1,105 @@+# Parser throughput: ASCII and CSI batching++Measured on 2026-09-23 with an Apple M1 Pro (16 GiB RAM), macOS, and kitten+0.49.0. The baseline is commit `06bdaa4`, before the parser optimizations. Both+binaries were built locally with the same Cargo release profile. The measured+binary hashes and individual runs are in [the results JSON](parser-throughput-results.json).++## What changed++CSI erase and REP now batch consecutive single-width writes within a row. The+first write still performs the original wide-cell boundary handling, hyperlink+invalidation, zone invalidation, and sequence-number update. REP keeps the+existing wrapping, scrolling, image-placement behavior, and oversized-count cap.+Wide cells and compact append storage retain the scalar path.++Printable ASCII runs now write a row at a time and append compact text and+attribute runs in bulk. `PrintString` also appends to the existing print/title+buffer directly. Mixed Unicode, DEC/UK character sets, insertion mode, and custom+character-width mappings retain the grapheme path. No new cache, persistent+buffer, unsafe code, or protocol change was introduced. Image placements are+preserved when writing text; erase operations still clear them.++## Method and results++An isolated foreground mux server hosted a real PTY at 120 columns by 32 rows,+with 3,500 scrollback lines. Each server had a temporary socket and a macOS+sandbox denying writes to the existing settings/session files. No GUI client was+attached. Each baseline/candidate pair ran sequentially, three pairs in total,+with 100 repetitions per workload. Builds and test suites did not run during the+benchmarks. Kitten generates random ASCII/CSI data, so runs are comparable+workloads, not byte-identical replays.++Median throughput, in MiB/s (kitten labels these values MB/s):++| Workload | Baseline | Optimized | Change |+| --- | ---: | ---: | ---: |+| ASCII | 24.4 | 43.4 | +77.9% |+| Unicode | 46.9 | 48.0 | +2.3% |+| Unique multi-codepoint cells | 63.1 | 69.7 | +10.5% |+| CSI with few characters | 15.6 | 20.3 | +30.1% |+| Long escape codes | 201.6 | 200.7 | -0.4% |++The mux process's median peak RSS, recorded with `wait4`, was 443.0 MiB before and+440.8 MiB after. A separate 200-repetition ASCII/CSI check with scrollback enabled+measured 427.2/427.5 MiB and 24.5/43.6 MiB/s ASCII, 15.6/20.3 MiB/s CSI+(baseline/optimized). These observations show no material peak-memory regression+in these workloads; they are not a long-duration leak test or GUI/GPU memory measurement.++**Images is excluded from the performance conclusion.** The baseline and+optimized binaries both logged `Invalid padding` while decoding the benchmark+images. Their roughly 278 MiB/s scores measure a rejected transfer, not successful+image processing. This pre-existing compatibility issue is separate from the+text/CSI changes and remains unresolved.++The benchmark waits for terminal status replies after parsing. These results do+not establish foreground frame rate, input latency, or the cost of synchronizing+rendered content through a mux client. The installed application was not replaced.+For the benchmark's timing contract, see [Kitty's benchmark source](https://github.com/kovidgoyal/kitty/blob/master/tools/cmd/benchmark/main.go).++## Reproduce and validate++Save the baseline release binary before changing revisions, then build the+candidate with the same compiler/profile:++```sh+cargo build --offline --release -p wezterm-gui -p wezterm-mux-server+```++Within a PTY hosted by each respective binary, use identical dimensions and+configuration and alternate at least three runs:++```sh+kitten __benchmark__ --repetitions 100+kitten __benchmark__ --repetitions 200 --with-scrollback ascii csi+```++Use separate temporary mux sockets for automated runs, prevent writes to existing+settings/session data, capture the server's stderr, and terminate only the test+processes. Do not accept a workload score when its data was rejected. `--render`+can be tested separately in a visible GUI, but its elapsed time is still not a+frame-rate measurement.++Differential tests compare the batched writes with the original scalar behavior,+including storage representation, shape hashes, semantic zones, hyperlinks,+image placements, compact attribute runs crossing the 65,535-cell boundary,+terminal snapshots, scrollback, cursor/margins, ConPTY wrapping, Unicode+normalization, custom widths, and fragmented input. Invalid ASCII runs are+rejected without mutation; very large REP counts retain their existing cap.++```sh+cargo test --offline -p wezterm-gui -p wezterm-term -p wezterm-surface --features wezterm-term/use_serde+cargo test --offline -p wezterm-escape-parser --all-features+cargo check --offline -p wezterm-surface --no-default-features --target wasm32-unknown-unknown+```++Validation passed: 901 GUI tests (one existing ignored test), 126 terminal tests,+47 surface tests, and 78 escape-parser tests, plus the release build and WASM+check.++The shared-memory cleanup tests require native shared-memory access; a sandbox+that denies `shm_open` produces an environment failure rather than exercising+that cleanup path.++Native Windows execution and foreground GUI visual QA were not performed for+these changes. ConPTY behavior is covered by model-level differential tests.diff --git a/term/src/terminalstate/performer.rs b/term/src/terminalstate/performer.rsindex 3c3752bf..02aa525f 100644--- a/term/src/terminalstate/performer.rs+++ b/term/src/terminalstate/performer.rs@@ -33,6 +33,8 @@ use wezterm_escape_parser::{pub(crate) struct Performer<'a> {pub state: &'a mut TerminalState,print: String,+ #[cfg(test)]+ disable_ascii_batch: bool,}impl<'a> Deref for Performer<'a> {@@ -60,6 +62,8 @@ impl<'a> Performer<'a> {Self {state,print: String::new(),+ #[cfg(test)]+ disable_ascii_batch: false,}}@@ -131,108 +135,159 @@ impl<'a> Performer<'a> {p.as_str()};- for g in Graphemes::new(text) {- let g = self.remap_grapheme(g);+ // Mixed Unicode must still be segmented as a whole: an ASCII base may+ // belong to a combining sequence or emoji. Special character sets and+ // insert mode retain the existing grapheme path as well.+ let charset = if self.shift_out {+ self.g1_charset+ } else {+ self.g0_charset+ };+ let ascii_batch = !self.insert+ && charset == CharSet::Ascii+ && self.unicode_version.cell_widths.is_none()+ && text.bytes().all(|b| (b' '..=b'~').contains(&b));+ #[cfg(test)]+ let ascii_batch = ascii_batch && !self.disable_ascii_batch;+ if ascii_batch {+ self.flush_ascii(text);+ } else {+ for g in Graphemes::new(text) {+ let g = self.remap_grapheme(g);- let mut print_width = grapheme_column_width(g, Some(&self.unicode_version));- if print_width == 0 {- // We got a zero-width grapheme.+ let mut print_width = grapheme_column_width(g, Some(&self.unicode_version));+ if print_width == 0 {+ // We got a zero-width grapheme.- // Relevant reading:- // <https://github.com/wezterm/wezterm/issues/1422>- // <https://github.com/wezterm/wezterm/issues/6637>- // <https://github.com/harfbuzz/harfbuzz/issues/4279>- // <https://www.unicode.org/faq/unsup_char.html#2>- //- // For White_Space we want to ensure that we display as a space.- // Other non-printing, zero-width characters can be elided- // to avoid presentation problems, but may introduce potential- // weirdness elsewhere. For example, U+2068 is a BIDI control- // character and will be elided by this logic. A consequence- // of that is that when the user copies the surrounding text- // from the terminal, that BIDI control will not be present.- // We do not currently have a solution for that.- if is_white_space_grapheme(g) {- // Ensure that White_Space shows as a space- print_width = 1;- } else {- log::trace!("Eliding zero-width grapheme {:?}", g);- continue;+ // Relevant reading:+ // <https://github.com/wezterm/wezterm/issues/1422>+ // <https://github.com/wezterm/wezterm/issues/6637>+ // <https://github.com/harfbuzz/harfbuzz/issues/4279>+ // <https://www.unicode.org/faq/unsup_char.html#2>+ //+ // For White_Space we want to ensure that we display as a space.+ // Other non-printing, zero-width characters can be elided+ // to avoid presentation problems, but may introduce potential+ // weirdness elsewhere. For example, U+2068 is a BIDI control+ // character and will be elided by this logic. A consequence+ // of that is that when the user copies the surrounding text+ // from the terminal, that BIDI control will not be present.+ // We do not currently have a solution for that.+ if is_white_space_grapheme(g) {+ // Ensure that White_Space shows as a space+ print_width = 1;+ } else {+ log::trace!("Eliding zero-width grapheme {:?}", g);+ continue;+ }}- }- if self.wrap_next {- // Since we're implicitly moving the cursor to the next- // line, we need to tag the current position as wrapped- // so that we can correctly reflow it if the window is- // resized.- {- let y = self.cursor.y;- let is_conpty = self.state.enable_conpty_quirks;- let screen = self.screen_mut();- let y = screen.phys_row(y);+ self.wrap_if_needed();- fn makes_sense_to_wrap(s: &str) -> bool {- let len = s.len();- match (len, s.chars().next()) {- (1, Some(c)) => c.is_alphanumeric() || c.is_ascii_punctuation(),- _ => true,- }- }+ let x = self.cursor.x;+ let y = self.cursor.y;+ let width = self.left_and_right_margins.end;++ let pen = self.pen.clone();- let should_mark_wrapped = !is_conpty- || screen- .line_mut(y)- .visible_cells()- .last()- .map(|cell| makes_sense_to_wrap(cell.str()))- .unwrap_or(false);- if should_mark_wrapped {- screen.line_mut(y).set_last_cell_was_wrapped(true, seqno);+ let wrappable = x + print_width >= width;++ if self.insert {+ let margin = self.left_and_right_margins.end;+ let screen = self.screen_mut();+ for _ in x..x + print_width as usize {+ screen.insert_cell(x, y, margin, seqno);}}- self.new_line(true);- }- let x = self.cursor.x;- let y = self.cursor.y;- let width = self.left_and_right_margins.end;-- let pen = self.pen.clone();+ // Assign the cell+ log::trace!(+ "print x={} y={} print_width={} width={} cell={} {:?}",+ x,+ y,+ print_width,+ width,+ g,+ self.pen+ );+ self.screen_mut()+ .set_cell_grapheme(x, y, g, print_width, pen, seqno);- let wrappable = x + print_width >= width;+ if !wrappable {+ self.cursor.x += print_width;+ self.wrap_next = false;+ } else {+ self.wrap_next = self.dec_auto_wrap;+ }+ }+ }+ std::mem::swap(&mut self.print, &mut p);+ self.print.clear();+ }- if self.insert {- let margin = self.left_and_right_margins.end;+ fn wrap_if_needed(&mut self) {+ let seqno = self.seqno;+ if self.wrap_next {+ // Since we're implicitly moving the cursor to the next+ // line, we need to tag the current position as wrapped+ // so that we can correctly reflow it if the window is+ // resized.+ {+ let y = self.cursor.y;+ let is_conpty = self.state.enable_conpty_quirks;let screen = self.screen_mut();- for _ in x..x + print_width as usize {- screen.insert_cell(x, y, margin, seqno);+ let y = screen.phys_row(y);++ fn makes_sense_to_wrap(s: &str) -> bool {+ let len = s.len();+ match (len, s.chars().next()) {+ (1, Some(c)) => c.is_alphanumeric() || c.is_ascii_punctuation(),+ _ => true,+ }+ }++ let should_mark_wrapped = !is_conpty+ || screen+ .line_mut(y)+ .visible_cells()+ .last()+ .map(|cell| makes_sense_to_wrap(cell.str()))+ .unwrap_or(false);+ if should_mark_wrapped {+ screen.line_mut(y).set_last_cell_was_wrapped(true, seqno);}}+ self.new_line(true);+ }+ }- // Assign the cell- log::trace!(- "print x={} y={} print_width={} width={} cell={} {:?}",- x,- y,- print_width,- width,- g,- self.pen- );- self.screen_mut()- .set_cell_grapheme(x, y, g, print_width, pen, seqno);+ fn flush_ascii(&mut self, mut text: &str) {+ let seqno = self.seqno;+ while !text.is_empty() {+ self.wrap_if_needed();- if !wrappable {- self.cursor.x += print_width;+ let x = self.cursor.x;+ let y = self.cursor.y;+ let width = self.left_and_right_margins.end;+ let count = text.len().min(width.saturating_sub(x).max(1));+ let pen = self.pen.clone();+ let screen = self.screen_mut();+ let row = screen.phys_row(y);+ let written = screen+ .line_mut(row)+ .set_ascii_cells(x, &text[..count], &pen, seqno);+ debug_assert!(written);+ if x + count < width {+ self.cursor.x += count;self.wrap_next = false;} else {+ // The scalar path leaves the cursor on the final cell, even+ // when wrapping is disabled or the cursor is past the margin.+ self.cursor.x += count - 1;self.wrap_next = self.dec_auto_wrap;}+ text = &text[count..];}-- std::mem::swap(&mut self.print, &mut p);- self.print.clear();}/// ConPTY, at the time of writing, does something horrible to rewrite@@ -267,8 +322,10 @@ impl<'a> Performer<'a> {match action {Action::Print(c) => self.print(c),Action::PrintString(s) => {- for c in s.chars() {- self.print(c)+ if let Some(title) = self.accumulating_title.as_mut() {+ title.push_str(&s);+ } else {+ self.print.push_str(&s);}}Action::Control(code) => self.control(code),@@ -1155,3 +1212,118 @@ fn selection_to_selection(sel: Selection) -> ClipboardSelection {_ => ClipboardSelection::Clipboard,}}++#[cfg(all(test, feature = "use_serde"))]+mod ascii_tests {+ use super::*;+ use crate::{TerminalConfiguration, TerminalSize};+ use std::sync::Arc;+ use wezterm_cell::UnicodeVersion;+ use wezterm_escape_parser::parser::Parser;++ #[derive(Debug)]+ struct TestConfig {+ normalize: bool,+ custom_widths: bool,+ }+ impl TerminalConfiguration for TestConfig {+ fn scrollback_size(&self) -> usize {+ 4+ }+ fn color_palette(&self) -> crate::color::ColorPalette {+ Default::default()+ }+ fn normalize_output_to_unicode_nfc(&self) -> bool {+ self.normalize+ }+ fn unicode_version(&self) -> UnicodeVersion {+ let mut version = UnicodeVersion::new(9);+ if self.custom_widths {+ version.cell_widths = Some(Arc::new(+ [('a' as u32, 2), ('z' as u32, 0)].iter().copied().collect(),+ ));+ }+ version+ }+ }++ #[test]+ fn ascii_batch_matches_grapheme_path_across_modes_and_chunk_boundaries() {+ for (rows, cols) in [(1, 1), (1, 7), (3, 7)] {+ for setup in [+ "",+ "a界",+ "\x1b[?7l",+ "\x1b[4h",+ "\x1b(0",+ "\x1b(A",+ "\x1b)0\x0e",+ "\x1b)A\x0e",+ "\x1b[?1049h",+ "\x1b[44m",+ "\x1b[2;3r\x1b[3;6H",+ "\x1b[?69h\x1b[2;6s\x1b[3;7H",+ "\x1b]8;;https://example.com\x1b\\",+ "\x1b]133;A\x07",+ ] {+ for (normalize, custom_widths, conpty) in [+ (false, false, false),+ (true, false, false),+ (false, true, false),+ (false, false, true),+ ] {+ for chunk_size in [1, 3, 17, 4096] {+ let make = || {+ let mut state = TerminalState::new(+ TerminalSize {+ rows,+ cols,+ pixel_width: cols * 8,+ pixel_height: rows * 16,+ dpi: 96,+ },+ Arc::new(TestConfig {+ normalize,+ custom_widths,+ }),+ "test",+ "test",+ Box::new(Vec::new()),+ );+ state.enable_conpty_quirks = conpty;+ state+ };+ let mut expected = make();+ let mut actual = make();+ let mut parser = Parser::new();+ let input = format!("{setup}abc #q~0123456789az next\rOVERWRITE\nmore\te\u{301}1\u{fe0f}\u{20e3}界\x1b[0m\x1bkASCII title界\x1b\\end");+ for chunk in input.as_bytes().chunks(chunk_size) {+ let mut actions = Vec::new();+ parser.parse(chunk, |action| action.append_to(&mut actions));+ actual.increment_seqno();+ expected.increment_seqno();+ {+ let mut scalar = Performer::new(&mut expected);+ scalar.disable_ascii_batch = true;+ let mut batched = Performer::new(&mut actual);+ for action in actions {+ batched.perform(action.clone());+ match action {+ Action::PrintString(text) => {+ for c in text.chars() {+ scalar.perform(Action::Print(c));+ }+ }+ other => scalar.perform(other),+ }+ }+ }+ assert_eq!(actual.snapshot(), expected.snapshot(),+ "rows={rows}, cols={cols}, setup={setup:?}, normalize={normalize}, custom_widths={custom_widths}, conpty={conpty}, chunk_size={chunk_size}");+ }+ }+ }+ }+ }+ }+}diff --git a/wezterm-surface/src/line/clusterline.rs b/wezterm-surface/src/line/clusterline.rsindex 2ca71750..b660955c 100644--- a/wezterm-surface/src/line/clusterline.rs+++ b/wezterm-surface/src/line/clusterline.rs@@ -216,6 +216,33 @@ impl ClusteredLine {}}+ /// Append printable ASCII that has already been validated by Line.+ pub fn append_ascii(&mut self, text: &str, attrs: &CellAttributes) {+ debug_assert!(text.bytes().all(|b| (b' '..=b'~').contains(&b)));+ if text.is_empty() {+ return;+ }+ let mut remaining = text.len();+ if let Some(cluster) = self.clusters.last_mut() {+ if cluster.attrs == *attrs {+ let count = remaining.min((u16::MAX - cluster.cell_width) as usize);+ cluster.cell_width += count as u16;+ remaining -= count;+ }+ }+ while remaining > 0 {+ let count = remaining.min(u16::MAX as usize);+ self.clusters.push(Cluster {+ attrs: attrs.clone(),+ cell_width: count as u16,+ });+ remaining -= count;+ }+ self.text.push_str(text);+ self.len += text.len() as u32;+ self.last_cell_width = NonZeroU8::new(1);+ }+pub fn append_grapheme(&mut self, text: &str, cell_width: usize, attrs: CellAttributes) {let cell_width = cell_width as u16;let new_cluster = match self.clusters.last() {diff --git a/wezterm-surface/src/line/line.rs b/wezterm-surface/src/line/line.rsindex 655a48ab..62f765ca 100644--- a/wezterm-surface/src/line/line.rs+++ b/wezterm-surface/src/line/line.rs@@ -792,6 +792,55 @@ impl Line {self.set_cell(idx, Cell::new_grapheme_with_width(text, width, attr), seqno);}+ /// Write a run of printable ASCII with the same semantics as individual+ /// `set_cell_grapheme` calls. Invalid input returns false without mutation.+ /// Appending keeps compact storage; overwriting preserves image placements.+ pub fn set_ascii_cells(+ &mut self,+ idx: usize,+ text: &str,+ attr: &CellAttributes,+ seqno: SequenceNo,+ ) -> bool {+ if !text.bytes().all(|b| (b' '..=b'~').contains(&b)) {+ return false;+ }+ if text.is_empty() {+ return true;+ }+ // Establish the same wide-cell boundary and line metadata as a scalar+ // write before taking either storage-specific path.+ self.set_cell_grapheme(idx, &text[..1], 1, attr.clone(), seqno);+ match &mut self.cells {+ CellStorage::C(cl) if cl.len() == idx + 1 => {+ cl.append_ascii(&text[1..], attr);+ }+ CellStorage::V(cells) => {+ let end = idx + text.len();+ if end > cells.len() {+ cells.resize_with(end, Cell::blank);+ }+ for (offset, byte) in text.bytes().enumerate().skip(1) {+ cells.set_cell(idx + offset, Cell::new(byte as char, attr.clone()), false);+ }+ }+ _ => {+ // A default blank beyond the end of compact storage is elided.+ // Retain that behavior if the first write did not append.+ for offset in 1..text.len() {+ self.set_cell_grapheme(+ idx + offset,+ &text[offset..offset + 1],+ 1,+ attr.clone(),+ seqno,+ );+ }+ }+ }+ true+ }+pub fn set_cell_clearing_image_placements(&mut self,idx: usize,diff --git a/wezterm-surface/src/line/test.rs b/wezterm-surface/src/line/test.rsindex 798cb96b..adba5340 100644--- a/wezterm-surface/src/line/test.rs+++ b/wezterm-surface/src/line/test.rs@@ -759,3 +759,118 @@ Line {"#);}++fn check_ascii_against_scalar(base: &Line, start: usize, text: &str, attrs: &CellAttributes) {+ let mut expected = base.clone();+ for offset in 0..text.len() {+ expected.set_cell_grapheme(+ start + offset,+ &text[offset..offset + 1],+ 1,+ attrs.clone(),+ 42,+ );+ }+ let mut actual = base.clone();+ assert!(actual.set_ascii_cells(start, text, attrs, 42));+ assert_eq!(actual, expected, "start={start}, text={text:?}");+ assert_eq!(+ actual.semantic_zone_ranges(),+ expected.semantic_zone_ranges()+ );+ assert_eq!(actual.compute_shape_hash(), expected.compute_shape_hash());+}++#[test]+fn ascii_runs_match_scalar_storage_links_and_wide_boundaries() {+ let mut linked = CellAttributes::default();+ linked.set_hyperlink(Some(Arc::new(Hyperlink::new("https://example.org"))));+ linked.set_semantic_type(wezterm_cell::SemanticType::Prompt);+ for text in [+ "",+ "abc ",+ "a界b🙂c",+ "界界",+ "e\u{301}x",+ "https://example.com",+ ] {+ for compressed in [false, true] {+ let mut base: Line = text.into();+ base.scan_and_create_hyperlinks(&[Rule::new(r"https://\S+", "$0").unwrap()]);+ if compressed {+ base.compress_for_scrollback();+ } else {+ base.coerce_vec_storage();+ }+ base.semantic_zone_ranges();+ for start in 0..base.len() + 3 {+ for replacement in [+ "",+ "x",+ " ",+ " ab ~",+ "0123456789abcdefghijklmnopqrstuvwxyz",+ ] {+ for attrs in [CellAttributes::default(), linked.clone()] {+ check_ascii_against_scalar(&base, start, replacement, &attrs);+ }+ }+ }+ }+ }+}++#[test]+fn ascii_append_keeps_compact_storage_and_splits_full_attribute_clusters() {+ let mut base = Line::new(0);+ let attrs = CellAttributes::default();+ for len in [65534, 65535, 65536, 131073] {+ let text = "x".repeat(len);+ check_ascii_against_scalar(&base, base.len(), &text, &attrs);+ assert!(base.set_ascii_cells(base.len(), &text, &attrs, 42));+ assert!(base.is_compressed_for_scrollback());+ }+}++#[test]+fn invalid_ascii_input_is_rejected_without_mutating_the_line() {+ for text in ["a\nb", "a\0b", "a\x7fb", "a界", "e\u{301}"] {+ let mut line: Line = "original".into();+ let original = line.clone();+ assert!(!line.set_ascii_cells(3, text, &CellAttributes::default(), 42));+ assert_eq!(line, original);+ }+}++#[cfg(feature = "use_image")]+#[test]+fn ascii_overwrite_preserves_image_placements() {+ use wezterm_cell::image::{ImageCell, ImageData, ImageDataType, TextureCoordinate};+ let data = Arc::new(ImageData::with_data(ImageDataType::new_single_frame(+ 1,+ 1,+ vec![255; 4],+ )));+ let mut base: Line = "a界b cdef".into();+ for x in 0..base.len() {+ for placement in [None, Some(7)] {+ base.cells_mut()[x]+ .attrs_mut()+ .attach_image(Box::new(ImageCell::with_z_index(+ TextureCoordinate::new_f32(0.0, 0.0),+ TextureCoordinate::new_f32(1.0, 1.0),+ Arc::clone(&data),+ 0,+ 0,+ 0,+ 0,+ 0,+ Some(3),+ placement,+ )));+ }+ }+ for start in 0..base.len() + 2 {+ check_ascii_against_scalar(&base, start, "0123456789", &CellAttributes::default());+ }+}