The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(tui): never send a pane's tab cell to the terminal as a tab (#601)
lingrd6cdda1b55edd
diff --git a/tui/Cargo.lock b/tui/Cargo.lockindex 83f85e399..fa1b73495 100644--- a/tui/Cargo.lock+++ b/tui/Cargo.lock@@ -653,7 +653,7 @@ dependencies = [[[package]]name = "harness-tui"-version = "0.1.11"+version = "0.1.12"dependencies = ["alacritty_terminal","crossterm",diff --git a/tui/Cargo.toml b/tui/Cargo.tomlindex 4c0eface0..f0fd6d0d5 100644--- a/tui/Cargo.toml+++ b/tui/Cargo.toml@@ -1,6 +1,6 @@[package]name = "harness-tui"-version = "0.1.11"+version = "0.1.12"edition = "2024"[dependencies]diff --git a/tui/src/copy/mod.rs b/tui/src/copy/mod.rsindex 2924421f9..44c4eb037 100644--- a/tui/src/copy/mod.rs+++ b/tui/src/copy/mod.rs@@ -1924,7 +1924,8 @@ impl Copy {let hsize = self.hsize();let put = |buf: &mut Buffer, x: u32, y: u32, text: &str, st: (Color, Color, Modifier)| {if let Some(cell) = buf.cell_mut((area.x + x as u16, area.y + y as u16)) {- cell.set_symbol(if text.is_empty() { " " } else { text });+ // (A tab the grid kept for copying is drawn as the blank it stands for.)+ cell.set_symbol(if text.is_empty() || text.chars().any(char::is_control) { " " } else { text });cell.fg = if st.0 == Color::Reset { window.0.unwrap_or(Color::Reset) } else { st.0 };cell.bg = if st.1 == Color::Reset { window.1.unwrap_or(Color::Reset) } else { st.1 };cell.modifier = st.2;diff --git a/tui/src/main.rs b/tui/src/main.rsindex ac48d61cf..ba9566e4a 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -49,6 +49,7 @@ mod term_out;mod term_input;mod tmuxconf;mod ui;+mod verify;mod viewer;// ── status bar ──mod bar;@@ -382,6 +383,11 @@ async fn run(config: config::Config) -> io::Result<()> {let backend = term_out::TmuxBackend::new(BufWriter::with_capacity(256 * 1024, term_out::Counted(io::stdout())));let mut term = Terminal::new(backend)?;+ // HARNESS_TUI_VERIFY: each frame's bytes replayed and compared with the frame (verify.rs).+ let mut verifier = verify::Verifier::from_env();+ if verifier.is_some() { verify::listen_for_dump() }+ // Whether some pane was selecting last frame (a selection starting is when a ghost is seen).+ let mut was_selecting = false;term.clear()?;let size = terminal::size()?;@@ -545,6 +551,7 @@ async fn run(config: config::Config) -> io::Result<()> {// A fresh Terminal repaints everything (ratatui's clear() asks the terminal where its// cursor is, and the input reader would eat the answer).term = Terminal::new(term_out::TmuxBackend::new(BufWriter::with_capacity(256 * 1024, term_out::Counted(io::stdout()))))?;+ if let Some(v) = verifier.as_mut() { v.reset() }need_draw = true;}// Every motion asked for only while something wants it.@@ -552,15 +559,24 @@ async fn run(config: config::Config) -> io::Result<()> {if all != mouse_all { execute!(term.backend_mut(), term_out::Mouse(if all { 2 } else { 1 }))?; mouse_all = all }app.flush_acks();if refill && matches!(app.modal, Some(modal::Modal::Picker { .. } | modal::Modal::NewHarness(_))) { input::refill(&mut app) }- // A scroll that has rested: every cell of the screen written again, once. The terminal- // may have kept a ghost of old text through the cell-by-cell updates; this overwrites it.- if app::scroll_settle_in(app.scrolled_at, Instant::now()) == Some(Duration::ZERO) { app.scrolled_at = None; app.redraw_all = true }+ // A scroll that has rested: every row of the screen written again, once — row by row over+ // what is there, not after erasing it, so it never flashes.+ let settle = app::scroll_settle_in(app.scrolled_at, Instant::now()) == Some(Duration::ZERO);+ if settle { app.scrolled_at = None }if std::mem::take(&mut app.redraw_all) { term.clear()?; need_draw = true; }+ else if settle { term.backend_mut().soft_clear_next(); term.clear()?; need_draw = true; }if need_draw && last_draw.elapsed() >= frame_budget {// (The backend makes each frame's changes one synchronized update, and writes nothing// for a frame that changed nothing.)let frame_started = Instant::now();- term.draw(|frame| ui::draw(frame, &mut app))?;+ if let Some(v) = verifier.as_mut() {+ let selecting = app.panes.values().any(|p| p.copy_top());+ if selecting && !was_selecting { v.dump_now("a selection started") }+ if verify::dump_asked() { v.dump_now("SIGUSR2") }+ was_selecting = selecting;+ }+ let done = term.draw(|frame| ui::draw(frame, &mut app))?;+ if let Some(v) = verifier.as_mut() { v.check(done.buffer) }// The focused program's cursor shape (vim's block and bar), passed through as tmux does.let shape = app.focused().filter(|_| app.modal.is_none()).and_then(|f| app.panes.get(&f)).map(|p| p.cursor_style()).unwrap_or(cursor::SetCursorStyle::DefaultUserShape);let code = format!("{shape:?}");diff --git a/tui/src/term_out.rs b/tui/src/term_out.rsindex 3ac0c5b53..8c6356181 100644--- a/tui/src/term_out.rs+++ b/tui/src/term_out.rs@@ -20,12 +20,24 @@ pub struct TmuxBackend<W: Write> {extra_shadow: std::collections::HashMap<(u16, u16), Extra>,/// A frame with several changes is one synchronized update (?2026), closed at its flush.syncing: bool,+ /// Whether that is done at all (`HARNESS_TUI_SYNC=off` turns it off).+ sync_ok: bool,+ /// The next clear-all writes the screen again row by row instead of erasing it first (see+ /// [`TmuxBackend::soft_clear_next`]); `force_whole` is that rewrite waiting for its draw.+ soft: bool,+ force_whole: bool,/// The cursor as last written: a frame that changes nothing writes nothing (an idle hn is/// silent, as tmux is — a terminal's or an outer tmux's activity mark stays clear).cursor_at: Option<Position>,cursor_shown: Option<bool>,}+/// Whether a frame is wrapped in synchronized output (?2026): yes, unless `HARNESS_TUI_SYNC=off`+/// (a terminal that mishandles it, e.g. ghostty-org/ghostty discussion 12062).+fn sync_wanted(setting: &str) -> bool {+ !matches!(setting.to_ascii_lowercase().as_str(), "off" | "0" | "false")+}+/// A cluster whose width terminals may count otherwise than hn does: several code points (a/// base and its marks, ZWJ emoji, a keycap, VS16), or a script whose vowels some count as/// spacing and some as combining (Thai, Lao, Tibetan, Myanmar, Khmer).@@ -84,7 +96,12 @@ impl Pen {match &want_link { Some(uri) => write!(w, "\x1b]8;;{uri}\x1b\\")?, None => w.write_all(b"\x1b]8;;\x1b\\")? }self.link = want_link;}- w.write_all(cell.symbol().as_bytes())+ // A cell is printed, never executed: a control character (a tab a pane's grid keeps, a+ // stray escape) would move the terminal's cursor where hn does not count it, and every+ // cell after it on the row would land elsewhere. It goes as the blank it stands for.+ let symbol = cell.symbol();+ if symbol.chars().any(char::is_control) { return w.write_all(b" ") }+ w.write_all(symbol.as_bytes())}/// Everything back to the terminal's defaults (and so known).@@ -147,7 +164,16 @@ pub fn outer_features(features: &[String]) -> (bool, bool) {}impl<W: Write> TmuxBackend<W> {- pub fn new(writer: W) -> Self { Self { inner: CrosstermBackend::new(writer), shadow: Vec::new(), extra_shadow: Default::default(), syncing: false, cursor_at: None, cursor_shown: None } }+ pub fn new(writer: W) -> Self {+ let sync_ok = sync_wanted(&std::env::var("HARNESS_TUI_SYNC").unwrap_or_default());+ Self { sync_ok, ..Self::with_sync(writer) }+ }++ fn with_sync(writer: W) -> Self { Self { inner: CrosstermBackend::new(writer), shadow: Vec::new(), extra_shadow: Default::default(), syncing: false, sync_ok: true, soft: false, force_whole: false, cursor_at: None, cursor_shown: None } }++ /// The next `clear()` does not erase the screen: every row is written again, each erased and+ /// rewritten in the same write, so a stale cell goes but the screen is never seen blank.+ pub fn soft_clear_next(&mut self) { self.soft = true }fn row_risky(&self, y: u16) -> bool { self.shadow.get(y as usize).map(|r| r.iter().any(|c| risky(c.symbol()))).unwrap_or(false) }@@ -173,6 +199,7 @@ impl<W: Write> Write for Counted<W> {fn write(&mut self, buf: &[u8]) -> io::Result<usize> {let n = self.0.write(buf)?;WRITTEN.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed);+ crate::verify::capture(&buf[..n]);Ok(n)}fn flush(&mut self) -> io::Result<()> { self.0.flush() }@@ -523,17 +550,23 @@ impl<W: Write> Backend for TmuxBackend<W> {}self.extra_shadow = extras;// Nothing changed: nothing written.- if cells.is_empty() { return Ok(()) }+ let all = std::mem::take(&mut self.force_whole);+ if cells.is_empty() && !all { return Ok(()) }// A row that holds (or held) a cluster the terminal may count otherwise is written again// whole from its first column, as fzf writes a line: a cell-by-cell update there would// leave a stale character where the two counts part (a Thai vowel beside a keycap).let touched: std::collections::BTreeSet<u16> = cells.iter().map(|c| c.1).collect();let was: std::collections::HashSet<u16> = touched.iter().copied().filter(|y| self.row_risky(*y)).collect();for (x, y, c) in &cells { self.remember(*x, *y, c) }- let whole: std::collections::BTreeSet<u16> = touched.into_iter().filter(|y| was.contains(y) || self.row_risky(*y)).collect();+ let mut whole: std::collections::BTreeSet<u16> = touched.into_iter().filter(|y| was.contains(y) || self.row_risky(*y)).collect();+ // A soft clear: every row of the screen (the terminal's height; else the rows known).+ if all {+ let rows = self.inner.size().map(|s| s.height as usize).unwrap_or(self.shadow.len()).max(self.shadow.len());+ whole.extend((0..rows).map(|y| y as u16));+ }// A single-cell update fits in the writer's one buffered flush; synchronizing it// adds sixteen bytes to an ordinary one-byte echo without hiding any redraw.- if !self.syncing && (cells.len() > 1 || !whole.is_empty()) { self.inner.write_all(b"\x1b[?2026h")?; self.syncing = true }+ if self.sync_ok && !self.syncing && (cells.len() > 1 || !whole.is_empty()) { self.inner.write_all(b"\x1b[?2026h")?; self.syncing = true }let (usstyle, links) = frame.map(|f| (f.usstyle, f.links)).unwrap_or((false, false));let extra_at = |x: u16, y: u16| frame.and_then(|f| f.extras.get(&(x, y)));// CrosstermBackend writes through to its writer.@@ -548,7 +581,11 @@ impl<W: Write> Backend for TmuxBackend<W> {self.cursor_at = Some(Position::new(x.saturating_add(width), *y));}for y in whole {- let Some(row) = self.shadow.get(y as usize) else { continue };+ // A row of a soft clear with nothing on it is still erased: a stale cell may be there.+ let Some(row) = self.shadow.get(y as usize) else {+ if all { write!(w, "\x1b[{};1H", y + 1)?; pen.reset(w)?; w.write_all(b"\x1b[2K")?; self.cursor_at = None }+ continue+ };write!(w, "\x1b[{};1H", y + 1)?;self.cursor_at = Some(Position::new(0, y));pen.reset(w)?;@@ -583,7 +620,16 @@ impl<W: Write> Backend for TmuxBackend<W> {self.inner.set_cursor_position(p)}fn clear(&mut self) -> io::Result<()> { self.shadow.clear(); self.extra_shadow.clear(); self.cursor_at = None; self.cursor_shown = None; self.inner.clear() }- fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> { if matches!(clear_type, ClearType::All) { self.shadow.clear(); self.extra_shadow.clear() } self.inner.clear_region(clear_type) }+ fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> {+ if matches!(clear_type, ClearType::All) {+ self.shadow.clear();+ self.extra_shadow.clear();+ // A soft clear forgets what was written but erases nothing: the draw that follows writes+ // every row, each erased and rewritten at once, so the screen is never seen blank.+ if std::mem::take(&mut self.soft) { self.cursor_at = None; self.force_whole = true; return Ok(()) }+ }+ self.inner.clear_region(clear_type)+ }fn append_lines(&mut self, n: u16) -> io::Result<()> { self.cursor_at = None; self.inner.append_lines(n) }fn size(&self) -> io::Result<Size> { self.inner.size() }fn window_size(&mut self) -> io::Result<WindowSize> { self.inner.window_size() }@@ -597,6 +643,77 @@ impl<W: Write> Backend for TmuxBackend<W> {mod tests {use super::*;+ #[test]+ fn a_control_character_in_a_cell_is_never_sent_to_the_terminal() {+ // A tab written as a cell moves the terminal's cursor to its next tab stop: every cell after+ // it on the row, written without a cursor move, then lands to the right of where hn put it.+ use alacritty_terminal::index::{Column, Line};+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ let (mut a, mut tab, mut b) = (Cell::default(), Cell::default(), Cell::default());+ a.set_char('a'); tab.set_symbol("\t"); b.set_char('b');+ backend.draw([(0u16, 0u16, &a), (1, 0, &tab), (2, 0, &b)].into_iter()).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ assert!(!written.contains(&b'\t'), "{:?}", String::from_utf8_lossy(&written));+ let mut pane = crate::pane::Pane::new(1, "m", "a", 20, 2);+ pane.feed(&written);+ assert_eq!(pane.term.grid()[Line(0)][Column(2)].c, 'b', "b lands where hn drew it");+ }++ #[test]+ fn a_soft_clear_writes_every_row_over_the_screen_without_erasing_it() {+ use alacritty_terminal::index::{Column, Line};+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ let (mut a, mut b) = (Cell::default(), Cell::default());+ a.set_char('a'); b.set_char('b');+ backend.draw([(0u16, 0u16, &a), (1, 0, &b)].into_iter()).unwrap();+ Backend::flush(&mut backend).unwrap();+ // The next frame is the same (so a normal draw would write nothing), but a cell the terminal+ // holds wrongly — a ghost — is the reason to write the screen again, and with no blank flash.+ backend.soft_clear_next();+ Backend::clear_region(&mut backend, ClearType::All).unwrap();+ backend.draw([(0u16, 0u16, &a), (1, 0, &b)].into_iter()).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let mut pane = crate::pane::Pane::new(1, "m", "a", 20, 4);+ // The terminal before the repaint: the first frame, and a stale X the backend never wrote.+ let first_len = written.iter().position(|&c| c == b'a').unwrap_or(0);+ let _ = first_len;+ pane.feed(b"\x1b[1;6HX\x1b[1;1H");+ pane.feed(&written);+ let text = String::from_utf8_lossy(&written);+ assert!(!text.contains("\x1b[2J"), "a soft clear must not erase the screen: {text:?}");+ assert_eq!(pane.term.grid()[Line(0)][Column(0)].c, 'a');+ assert_eq!(pane.term.grid()[Line(0)][Column(5)].c, ' ', "the stale cell was erased by its row being written again");+ }++ #[test]+ fn synchronized_output_is_on_unless_turned_off() {+ assert!(sync_wanted(""));+ assert!(sync_wanted("on"));+ assert!(!sync_wanted("off"));+ assert!(!sync_wanted("OFF"));+ }++ #[test]+ fn a_frame_is_not_wrapped_in_2026_when_it_is_left_out() {+ let draw = |sync_ok: bool| {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ backend.sync_ok = sync_ok;+ let (mut a, mut b) = (Cell::default(), Cell::default());+ a.set_char('a'); b.set_char('b');+ backend.draw([(0u16, 0u16, &a), (1, 0, &b)].into_iter()).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ String::from_utf8_lossy(&written).to_string()+ };+ assert!(draw(true).contains("\x1b[?2026h") && draw(true).contains("\x1b[?2026l"));+ assert!(!draw(false).contains("2026"));+ }+#[test]fn single_symbols_terminals_count_otherwise_are_risky_too() {// Private-use icons (Nerd Font), arrows/shapes/dingbats of ambiguous width, and emojidiff --git a/tui/src/ui.rs b/tui/src/ui.rsindex 2b1f36300..75a3acbca 100644--- a/tui/src/ui.rs+++ b/tui/src/ui.rs@@ -2487,7 +2487,7 @@ fn preview_grid(buf: &mut Buffer, pane: &Pane, area: Rect, scroll: u16) {if cell.flags.contains(Flags::ITALIC) { style = style.add_modifier(Modifier::ITALIC) }if cell.flags.intersects(Flags::ALL_UNDERLINES) { style = style.add_modifier(Modifier::UNDERLINED) }if cell.flags.contains(Flags::STRIKEOUT) { style = style.add_modifier(Modifier::CROSSED_OUT) }- if let Some(t) = buf.cell_mut((area.x + col, area.y + row as u16)) { t.set_char(if cell.c == '\0' { ' ' } else { cell.c }).set_style(style); }+ if let Some(t) = buf.cell_mut((area.x + col, area.y + row as u16)) { t.set_char(shown_char(cell.c)).set_style(style); }}}@@ -2535,13 +2535,13 @@ pub fn screen_preview(buf: &mut Buffer, pane: &Pane, x: u16, y: u16, nx: u16, nyif cell.flags.contains(Flags::WIDE_CHAR_SPACER) { out += 1; continue }let w = if cell.flags.contains(Flags::WIDE_CHAR) { 2 } else { 1 };if xx + w > px + nx { break }- if let Some(t) = buf.cell_mut((x + out, y + j)) { t.set_char(if cell.c == '\0' { ' ' } else { cell.c }).set_style(style_of(cell)); }+ if let Some(t) = buf.cell_mut((x + out, y + j)) { t.set_char(shown_char(cell.c)).set_style(style_of(cell)); }out += 1;}}if shown && cx >= px && cy >= py && cx < px + nx && cy < py + ny && cx < sx && cy < sy {let cell = &grid[Line(cy as i32)][Column(cx as usize)];- if let Some(t) = buf.cell_mut((x + cx - px, y + cy - py)) { t.set_char(if cell.c == '\0' { ' ' } else { cell.c }).set_style(style_of(cell).add_modifier(Modifier::REVERSED)); }+ if let Some(t) = buf.cell_mut((x + cx - px, y + cy - py)) { t.set_char(shown_char(cell.c)).set_style(style_of(cell).add_modifier(Modifier::REVERSED)); }}}@@ -2748,7 +2748,9 @@ fn pane_body(buf: &mut Buffer, pane: &mut Pane, area: Rect, active: bool, windowif underline != 0 || link.is_some() || overline { crate::term_out::set_extra(area.x + col, area.y + row as u16, crate::term_out::Extra { underline, link, overline }) }let target = buf.cell_mut((area.x + col, area.y + row as u16));let Some(target) = target else { continue };- if cell.c == '\0' {+ // An empty cell, or the tab `ls` aligned a column with (the grid keeps it where the tab+ // jumped from): the blank the screen shows, never the control character itself.+ if shown_char(cell.c) != cell.c {target.set_symbol(" ").set_style(style);continue;}@@ -2798,6 +2800,11 @@ fn pane_body(buf: &mut Buffer, pane: &mut Pane, area: Rect, active: bool, window(row >= 0 && (row as u16) < area.height && col < area.width).then(|| Position::new(area.x + col, area.y + row as u16))}+/// A grid cell's character as it is drawn: alacritty keeps a tab in the cell a tab jumped from (so+/// copying keeps it), and an empty cell holds '\0' — both are the blank the screen shows. Drawn as+/// they are, a tab would reach the terminal and move its cursor to the next tab stop.+pub fn shown_char(c: char) -> char { if c == '\0' || c.is_control() { ' ' } else { c } }+fn card(buf: &mut Buffer, area: Rect, lines: &[(String, Style)]) {let top = area.y + area.height.saturating_sub(lines.len() as u16) / 2;for (index, (text, style)) in lines.iter().enumerate() {@@ -2809,6 +2816,25 @@ fn card(buf: &mut Buffer, area: Rect, lines: &[(String, Style)]) {}}+#[cfg(test)]+mod tab_cell_tests {+ use super::*;++ #[test]+ fn a_tab_in_a_pane_is_drawn_as_the_blank_it_stands_for() {+ // `ls` aligns its columns with tabs; the pane's grid keeps the tab in the cell it jumped from.+ let mut pane = crate::pane::Pane::new(1, "m", "a", 20, 2);+ pane.phase = crate::pane::Phase::Live;+ pane.feed(b"ab\tc");+ let area = Rect::new(0, 0, 20, 2);+ let mut buf = Buffer::empty(area);+ pane_body(&mut buf, &mut pane, area, true, (None, None));+ let row: String = (0..20).map(|x| buf[(x, 0)].symbol().to_string()).collect();+ assert!(!row.contains('\t'), "a tab reached the frame: {row:?}");+ assert_eq!(&row[..9], "ab c");+ }+}+#[cfg(test)]mod fzf_info_tests {use super::{repeat_to_fill, trim_message};diff --git a/tui/src/verify.rs b/tui/src/verify.rsnew file mode 100644index 000000000..3e2c9378a--- /dev/null+++ b/tui/src/verify.rs@@ -0,0 +1,198 @@+//! `HARNESS_TUI_VERIFY=<file>`: what hn writes to the terminal, checked frame by frame. Every byte+//! the terminal is sent is replayed into a reference terminal of the same size; after each frame+//! its cells are compared with the frame hn meant to draw. A cell that differs — text the terminal+//! would still show that hn believes gone, or hn's text landing elsewhere — is logged with the+//! frames that led to it, so a stale cell can be traced to the bytes that left it.+use std::collections::VecDeque;+use std::io::Write;+use std::sync::Mutex;++use alacritty_terminal::grid::Dimensions;+use alacritty_terminal::index::{Column, Line};+use alacritty_terminal::term::cell::Flags;+use ratatui::buffer::Buffer;+use unicode_width::UnicodeWidthStr;++/// The bytes written since the last check; None while verifying is off.+static CAPTURE: Mutex<Option<Vec<u8>>> = Mutex::new(None);++/// Every byte the terminal is sent (term_out::Counted and the writes that bypass it).+pub fn capture(bytes: &[u8]) {+ if let Ok(mut held) = CAPTURE.lock() { if let Some(all) = held.as_mut() { all.extend_from_slice(bytes) } }+}++fn take() -> Vec<u8> { CAPTURE.lock().ok().and_then(|mut held| held.as_mut().map(std::mem::take)).unwrap_or_default() }++pub struct Verifier {+ path: std::path::PathBuf,+ screen: crate::pane::Pane,+ size: (u16, u16),+ frames: VecDeque<Vec<u8>>,+ logged: usize,+ /// The frame last drawn: what is on screen until the next one.+ last: Option<Buffer>,+}++static DUMP: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+extern "C" fn on_usr2(_: libc::c_int) { DUMP.store(true, std::sync::atomic::Ordering::Relaxed) }++/// `kill -USR2 <hn>` asks for a dump of the screen as it is (with verifying on).+pub fn listen_for_dump() { unsafe { libc::signal(libc::SIGUSR2, on_usr2 as extern "C" fn(libc::c_int) as libc::sighandler_t); } }+pub fn dump_asked() -> bool { DUMP.swap(false, std::sync::atomic::Ordering::Relaxed) }++/// One cell where the terminal and hn part: where, what hn drew, what the terminal shows.+#[derive(Debug, PartialEq)]+pub struct Mismatch { pub x: u16, pub y: u16, pub drawn: String, pub shown: String }++impl Verifier {+ pub fn from_env() -> Option<Verifier> {+ let path = std::env::var("HARNESS_TUI_VERIFY").ok().filter(|p| !p.is_empty())?;+ if let Ok(mut held) = CAPTURE.lock() { *held = Some(Vec::new()) }+ Some(Verifier::new(path.into()))+ }++ fn new(path: std::path::PathBuf) -> Verifier {+ Verifier { path, screen: crate::pane::Pane::new(0, "verify", "verify", 1, 1), size: (0, 0), frames: VecDeque::new(), logged: 0, last: None }+ }++ /// The terminal was cleared outside hn's writer (a suspend and resume): start from blank.+ pub fn reset(&mut self) { self.size = (0, 0); let _ = take(); }++ /// After a frame: replay what was written, compare with [drawn], log what differs.+ pub fn check(&mut self, drawn: &Buffer) {+ let bytes = take();+ self.feed_and_compare(bytes, drawn);+ self.last = Some(drawn.clone());+ }++ /// A dump of the frame on screen now (before the next is drawn over it).+ pub fn dump_now(&mut self, reason: &str) {+ // Bytes written since the last frame (a title, a bell) first, so the reference is current.+ let pending = take();+ if !pending.is_empty() { self.screen.feed(&pending); self.frames.push_back(pending); }+ if let Some(last) = self.last.take() { self.dump(&last, reason); self.last = Some(last) }+ }++ fn feed_and_compare(&mut self, bytes: Vec<u8>, drawn: &Buffer) -> Vec<Mismatch> {+ let size = (drawn.area.width, drawn.area.height);+ // A new size: the frame that follows a resize is written whole after a clear.+ if size != self.size { self.screen = crate::pane::Pane::new(0, "verify", "verify", size.0, size.1); self.size = size; self.frames.clear() }+ self.screen.feed(&bytes);+ self.frames.push_back(bytes);+ while self.frames.len() > 8 { self.frames.pop_front(); }+ let wrong = self.compare(drawn);+ if !wrong.is_empty() && self.logged < 40 { self.logged += 1; self.log(drawn, &wrong) }+ wrong+ }++ fn compare(&self, drawn: &Buffer) -> Vec<Mismatch> {+ let grid = self.screen.term.grid();+ let mut wrong = Vec::new();+ for y in 0..drawn.area.height {+ let mut skip = 0usize;+ for x in 0..drawn.area.width {+ if skip > 0 { skip -= 1; continue }+ let cell = &drawn[(drawn.area.x + x, drawn.area.y + y)];+ let symbol = if cell.symbol().is_empty() { " " } else { cell.symbol() };+ skip = symbol.width().max(1) - 1;+ if (y as usize) >= grid.screen_lines() || (x as usize) >= grid.columns() { continue }+ let term_cell = &grid[Line(y as i32)][Column(x as usize)];+ if term_cell.flags.contains(Flags::WIDE_CHAR_SPACER) { continue }+ let mut shown = String::new();+ shown.push(if term_cell.c == '\0' { ' ' } else { term_cell.c });+ if let Some(extra) = term_cell.zerowidth() { shown.extend(extra.iter()) }+ if shown != symbol { wrong.push(Mismatch { x, y, drawn: symbol.to_string(), shown }) }+ }+ }+ wrong+ }++ /// The whole picture now — what hn drew, what the reference terminal shows, the last frames —+ /// whatever the comparison says. Written when a selection starts: people select a stale cell+ /// to clear it, so that is the moment a ghost is on screen.+ pub fn dump(&self, drawn: &Buffer, reason: &str) {+ let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&self.path) else { return };+ let at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);+ let wrong = self.compare(drawn);+ let _ = writeln!(f, "### {at} dump: {reason} · terminal {}x{} · {} cells differ", self.size.0, self.size.1, wrong.len());+ let grid = self.screen.term.grid();+ for y in 0..drawn.area.height {+ let hn: String = (0..drawn.area.width).map(|x| drawn[(drawn.area.x + x, drawn.area.y + y)].symbol().to_string()).collect();+ let term: String = (0..grid.columns()).map(|x| { let c = grid[Line(y as i32)][Column(x)].c; if c == '\0' { ' ' } else { c } }).collect();+ let _ = writeln!(f, " row {y:>3} hn: {hn:?}");+ if term.trim_end() != hn.trim_end() { let _ = writeln!(f, " row {y:>3} term: {term:?}"); }+ }+ for (i, frame) in self.frames.iter().enumerate() {+ let shown: Vec<u8> = frame.iter().take(48_000).copied().collect();+ let _ = writeln!(f, " frame -{} ({} bytes): {}", self.frames.len() - 1 - i, frame.len(), shown.escape_ascii());+ }+ }++ fn log(&self, drawn: &Buffer, wrong: &[Mismatch]) {+ let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&self.path) else { return };+ let at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);+ let _ = writeln!(f, "=== {at} terminal {}x{} · {} cells differ", self.size.0, self.size.1, wrong.len());+ for m in wrong.iter().take(40) { let _ = writeln!(f, " ({},{}) hn drew {:?} · terminal shows {:?}", m.x, m.y, m.drawn, m.shown); }+ let grid = self.screen.term.grid();+ let rows: std::collections::BTreeSet<u16> = wrong.iter().map(|m| m.y).collect();+ for y in rows.into_iter().take(8) {+ let hn: String = (0..drawn.area.width).map(|x| drawn[(drawn.area.x + x, drawn.area.y + y)].symbol().to_string()).collect();+ let term: String = (0..grid.columns()).map(|x| { let c = grid[Line(y as i32)][Column(x)].c; if c == '\0' { ' ' } else { c } }).collect();+ let _ = writeln!(f, " row {y} hn: {hn:?}");+ let _ = writeln!(f, " row {y} term: {term:?}");+ }+ for (i, frame) in self.frames.iter().enumerate() {+ let shown: Vec<u8> = frame.iter().take(24_000).copied().collect();+ let _ = writeln!(f, " frame -{} ({} bytes): {}", self.frames.len() - 1 - i, frame.len(), shown.escape_ascii());+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use ratatui::backend::Backend;+ use ratatui::buffer::Cell;+ use ratatui::layout::Rect;++ fn frame(cells: &[(u16, u16, char)]) -> Buffer {+ let mut buf = Buffer::empty(Rect::new(0, 0, 10, 2));+ for (x, y, c) in cells { buf[(*x, *y)].set_char(*c); }+ buf+ }++ fn written(prev: &Buffer, next: &Buffer) -> Vec<u8> {+ let mut out = Vec::new();+ let mut backend = crate::term_out::TmuxBackend::new(&mut out);+ backend.draw(prev.diff(next).into_iter()).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ out+ }++ #[test]+ fn what_hn_wrote_matches_what_it_drew() {+ let mut v = Verifier::new(std::env::temp_dir().join("hn-verify-test-ok.log"));+ let blank = Buffer::empty(Rect::new(0, 0, 10, 2));+ let one = frame(&[(0, 0, 'l'), (1, 0, 's'), (0, 1, 'x')]);+ assert_eq!(v.feed_and_compare(written(&blank, &one), &one), vec![]);+ // `clear`: the cells go back to blank, and the terminal shows that too.+ assert_eq!(v.feed_and_compare(written(&one, &blank), &blank), vec![]);+ }++ #[test]+ fn a_cell_the_terminal_kept_is_found() {+ let path = std::env::temp_dir().join(format!("hn-verify-test-{}.log", std::process::id()));+ let mut v = Verifier::new(path.clone());+ let blank = Buffer::empty(Rect::new(0, 0, 10, 2));+ let one = frame(&[(3, 1, 'g')]);+ assert_eq!(v.feed_and_compare(written(&blank, &one), &one), vec![]);+ // hn draws blank but the bytes that would erase the cell never reach the terminal.+ let wrong = v.feed_and_compare(Vec::new(), &blank);+ assert_eq!(wrong, vec![Mismatch { x: 3, y: 1, drawn: " ".into(), shown: "g".into() }]);+ let log = std::fs::read_to_string(&path).unwrap();+ assert!(log.contains("(3,1) hn drew \" \" · terminal shows \"g\""), "{log}");+ let _ = std::fs::remove_file(path);+ let _ = Cell::default();+ }+}