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
Reduce terminal idle wakeups and repeated formatting work (#512)
Deeef1a245db6d3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5099ec2ef..876f16648 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -159,6 +159,11 @@ jobs:HN_PANE_UI_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tuiHN_PANE_UI_PORT: 19783run: python3 -u tests/pane-ui.py+ - name: Animation, timed messages and idle input+ env:+ HARNESS_TUI_BIN: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tui+ HN_REPAINT_TEST_PORT: 19794+ run: python3 -u tests/repaint.py- name: New Harness popup, draft and launch recoveryenv:HN_NEW_UI_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tuidiff --git a/tui/src/event.rs b/tui/src/event.rsindex 13e11acfd..39637e7dd 100644--- a/tui/src/event.rs+++ b/tui/src/event.rs@@ -22,6 +22,4 @@ pub enum Event {/// The result of background work, applied on the app loop.Apply(Box<dyn FnOnce(&mut App) + Send>),Tick,- /// Repaint moving indicators without running the maintenance timers.- Animate,}diff --git a/tui/src/format.rs b/tui/src/format.rsindex 079ce3d96..de7c818f1 100644--- a/tui/src/format.rs+++ b/tui/src/format.rs@@ -460,12 +460,12 @@ fn replace(es: &mut Es, key: &str) -> Option<String> {v} else if f.windows && es.session.is_some() {// format_loop_windows in a session not in front (a #{S:} loop's): its own windows.- let (all, active) = match choose(es, copy, false) { Some((a, b)) => (a, Some(b)), None => (copy.to_string(), None) };+ let (all, active) = match choose(copy) { Some((a, b)) => (a, Some(b)), None => (copy, None) };let sid = es.session.unwrap_or_default();let current = es.app.stash_value(sid, "window_index");let mut v = String::new();for (k, (num, _, _)) in es.app.session_windows(sid).into_iter().enumerate() {- let use_ = if Some(num.to_string()) == current { active.as_deref().unwrap_or(&all) } else { &all };+ let use_ = if Some(num.to_string()) == current { active.unwrap_or(all) } else { all };let mut next = es.at(es.window, None);next.window_of = Some(k);next.format_type = Some(crate::tree::FORMAT_WINDOW);@@ -473,10 +473,10 @@ fn replace(es: &mut Es, key: &str) -> Option<String> {}v} else if f.windows {- let (all, active) = match choose(es, copy, false) { Some((a, b)) => (a, Some(b)), None => (copy.to_string(), None) };+ let (all, active) = match choose(copy) { Some((a, b)) => (a, Some(b)), None => (copy, None) };let mut v = String::new();for w in 0..es.app.tabs.len() {- let use_ = if w == es.app.active { active.as_deref().unwrap_or(&all) } else { &all };+ let use_ = if w == es.app.active { active.unwrap_or(all) } else { all };let mut next = es.at(w, None);next.format_type = Some(crate::tree::FORMAT_WINDOW);v.push_str(&expand1(&mut next, use_));@@ -484,23 +484,23 @@ fn replace(es: &mut Es, key: &str) -> Option<String> {v} else if f.panes && es.session.and_then(|id| es.app.stash_panes(id, es.window_of)).is_some() {// format_loop_panes in a session not in front (a #{S:} loop's): its window's own panes.- let (all, active) = match choose(es, copy, false) { Some((a, b)) => (a, Some(b)), None => (copy.to_string(), None) };+ let (all, active) = match choose(copy) { Some((a, b)) => (a, Some(b)), None => (copy, None) };let (panes, focus, _) = es.session.and_then(|id| es.app.stash_panes(id, es.window_of)).unwrap_or_default();let mut v = String::new();for p in panes {- let use_ = if Some(p) == focus { active.as_deref().unwrap_or(&all) } else { &all };+ let use_ = if Some(p) == focus { active.unwrap_or(all) } else { all };let mut next = es.at(es.window, Some(p));next.format_type = Some(crate::tree::FORMAT_PANE);v.push_str(&expand1(&mut next, use_));}v} else if f.panes {- let (all, active) = match choose(es, copy, false) { Some((a, b)) => (a, Some(b)), None => (copy.to_string(), None) };+ let (all, active) = match choose(copy) { Some((a, b)) => (a, Some(b)), None => (copy, None) };let tab = es.app.tabs.get(es.window);let focus = tab.and_then(|t| t.focus);let mut v = String::new();for p in tab.map(|t| t.panes()).unwrap_or_default() {- let use_ = if Some(p) == focus { active.as_deref().unwrap_or(&all) } else { &all };+ let use_ = if Some(p) == focus { active.unwrap_or(all) } else { all };let mut next = es.at(es.window, Some(p));next.format_type = Some(crate::tree::FORMAT_PANE);v.push_str(&expand1(&mut next, use_));@@ -516,7 +516,7 @@ fn replace(es: &mut Es, key: &str) -> Option<String> {let term = expand1(es, copy);search_pane(es, fm, &term)} else if let Some(fm) = cmp {- let (left, right) = choose(es, copy, true)?;+ let (left, right) = choose_expanded(es, copy)?;let t = |b: bool| if b { "1".to_string() } else { "0".to_string() };match fm.m.as_str() {"||" => t(truthy(&left) || truthy(&right)),@@ -537,8 +537,8 @@ fn replace(es: &mut Es, key: &str) -> Option<String> {// Not a name: expanded; if that changes nothing, false.None => { let v = expand1(es, condition); if v == condition { String::new() } else { v } }};- let (left, right) = choose(es, &rest[k + 1..], false)?;- if truthy(&found) { expand1(es, &left) } else { expand1(es, &right) }+ let (left, right) = choose(&rest[k + 1..])?;+ if truthy(&found) { expand1(es, left) } else { expand1(es, right) }} else if let Some(fm) = mexp {expression(es, fm, copy).unwrap_or_default()} else if copy.contains("#{") {@@ -569,11 +569,16 @@ fn replace(es: &mut Es, key: &str) -> Option<String> {Some(value)}-/// `a,b`: the two sides at the first comma outside `#{…}`, expanded when asked (format_choose).-fn choose(es: &mut Es, s: &str, expand: bool) -> Option<(String, String)> {+/// `a,b`: borrow the two templates at the first comma outside `#{…}`. Conditions+/// and loops expand only the selected template, without copying either side.+fn choose(s: &str) -> Option<(&str, &str)> {let k = skip(s.as_bytes(), b",")?;- let (l, r) = (&s[..k], &s[k + 1..]);- Some(if expand { (expand1(es, l), expand1(es, r)) } else { (l.to_string(), r.to_string()) })+ Some((&s[..k], &s[k + 1..]))+}++fn choose_expanded(es: &mut Es, s: &str) -> Option<(String, String)> {+ let (l, r) = choose(s)?;+ Some((expand1(es, l), expand1(es, r)))}fn truthy(v: &str) -> bool { !v.is_empty() && v != "0" }@@ -741,7 +746,7 @@ fn expression(es: &mut Es, fm: &Mod, copy: &str) -> Option<String> {let fp = fm.argv.get(1).map(|a| a.contains('f')).unwrap_or(false);let mut prec: usize = if fp { 2 } else { 0 };if let Some(p) = fm.argv.get(2) { prec = p.trim().parse().ok()? }- let (l, r) = choose(es, copy, true)?;+ let (l, r) = choose_expanded(es, copy)?;let num = |s: &str| -> Option<f64> { if s.is_empty() { Some(0.0) } else { s.trim_start().parse::<f64>().ok() } };let (mut a, mut b) = (num(&l)?, num(&r)?);if !fp { a = (a as i64) as f64; b = (b as i64) as f64 }@@ -754,10 +759,41 @@ fn expression(es: &mut Es, fm: &Mod, copy: &str) -> Option<String> {Some(if fp { format!("{v:.prec$}") } else { format!("{:.prec$}", (v as i64) as f64) })}+type Substitutions = std::collections::VecDeque<(String, bool, Option<Rc<regex::Regex>>)>;+thread_local! {+ static SUBSTITUTIONS: RefCell<Substitutions> = RefCell::new(Default::default());+}++/// Status formats reuse their patterns on every frame. Keep a small LRU of+/// compiled expressions, never their match results. Larger expressions retain+/// the original compiler limits and run uncached rather than growing the cache.+fn substitution_regex(pattern: &str, icase: bool) -> Option<Rc<regex::Regex>> {+ let uncached = || regex::RegexBuilder::new(pattern).case_insensitive(icase).build().ok().map(Rc::new);+ if pattern.len() > 2048 { return uncached() }+ SUBSTITUTIONS.with(|cache| {+ let mut cache = cache.borrow_mut();+ if let Some(at) = cache.iter().position(|(p, i, _)| p == pattern && *i == icase) {+ let entry = cache.remove(at).unwrap();+ let re = entry.2.clone();+ cache.push_front(entry);+ return re;+ }+ let re = match regex::RegexBuilder::new(pattern).case_insensitive(icase)+ .size_limit(32 * 1024).dfa_size_limit(32 * 1024).build() {+ Ok(re) => Some(Rc::new(re)),+ Err(regex::Error::CompiledTooBig(_)) => return uncached(),+ Err(_) => None,+ };+ if cache.len() == 8 { cache.pop_back(); }+ cache.push_front((pattern.to_string(), icase, re.clone()));+ re+ })+}+/// tmux's regsub: every match replaced; `\0`–`\9` in the replacement are the groups.fn regsub(pattern: &str, with: &str, text: &str, icase: bool) -> Option<String> {if text.is_empty() { return Some(String::new()) }- let re = regex::RegexBuilder::new(pattern).case_insensitive(icase).build().ok()?;+ let re = substitution_regex(pattern, icase)?;let (mut start, mut last, end) = (0usize, 0usize, text.len());let mut empty = false;let mut buf = String::new();@@ -1343,9 +1379,12 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<Vlet mut parts = Vec::new();let n = app.fleet.count(NeedsInput);if n > 0 { parts.push(format!("#[bold]?{n}#[nobold]")) }- for (state, glyph) in [(Failed, "✗"), (Done, "✓"), (Working, crate::theme::spinner(app.tick))] {+ for state in [Failed, Done, Working] {let n = app.fleet.count(state);- if n > 0 { parts.push(format!("{glyph}{n}")) }+ if n > 0 {+ let glyph = match state { Failed => "✗", Done => "✓", _ => crate::theme::spinner(app.tick) };+ parts.push(format!("{glyph}{n}"));+ }}parts.join(" ")}@@ -1710,6 +1749,21 @@ fn restyle(mut style: Style, base: Style, spec: &str) -> Style {#[cfg(test)]mod tests {+ #[test]+ fn fleet_only_requests_animation_while_working_and_motion_is_enabled() {+ let mut app = status_fixture(1, 1);+ for working in [false, true, false] {+ app.fleet.agents.values_mut().next().unwrap().working = working;+ crate::theme::begin_animation_frame(true);+ super::expand(&app, "#{fleet}/#{fleet}", 0, Some(1), false);+ assert_eq!(crate::theme::needs_animation_frame(), working);+ }+ app.fleet.agents.values_mut().next().unwrap().working = true;+ crate::theme::begin_animation_frame(false);+ assert_eq!(super::expand(&app, "#{fleet}", 0, Some(1), false), "⠋1");+ assert!(!crate::theme::needs_animation_frame());+ }+fn status_fixture(windows: usize, agents: usize) -> crate::app::App {let (sink, _) = tokio::sync::mpsc::unbounded_channel();let mut app = crate::app::App::new(19789, sink, (200, 60));@@ -1762,6 +1816,48 @@ mod tests {assert_eq!(super::expand(&app, "#{window_name}/#{window_active}/#{pane_id}", 1, Some(2), false), "Project 1/1/%1");}+ #[test]+ fn loop_alternatives_keep_nested_commas_and_only_expand_the_selected_branch() {+ let mut app = status_fixture(2, 2);+ app.options.global_session.insert("@selected".into(), "live,✓".into());+ let fmt = "#{W:#{window_name},#{?window_active,#{@selected},#(printf unexpected)}}";+ assert_eq!(super::expand(&app, fmt, 0, None, false), "live,✓Project 1");+ app.active = 1;+ app.options.global_session.insert("@selected".into(), "changed,✓".into());+ assert_eq!(super::expand(&app, fmt, 0, None, false), "Project 0changed,✓");+ assert!(app.jobs.borrow().is_empty(), "the untaken branch must not run its shell command");+ }++ #[test]+ fn compiled_substitutions_keep_fresh_text_replacements_and_case_flags() {+ assert_eq!(super::regsub("(foo)", "[\\1]", "foo FOO", false).as_deref(), Some("[foo] FOO"));+ assert_eq!(super::regsub("(foo)", "new", "FOO foo", false).as_deref(), Some("FOO new"));+ assert_eq!(super::regsub("(foo)", "new", "FOO foo", true).as_deref(), Some("new new"));+ assert_eq!(super::regsub("^foo", "✓", "foo foo", false).as_deref(), Some("✓ foo"));+ assert_eq!(super::regsub("(", "x", "text", false), None);+ assert_eq!(super::regsub("(", "x", "", false).as_deref(), Some(""));+ }++ #[test]+ fn substitution_cache_stays_bounded_without_rejecting_larger_expressions() {+ super::SUBSTITUTIONS.with(|cache| cache.borrow_mut().clear());+ for n in 0..32 {+ let pattern = format!("a{n}");+ assert_eq!(super::regsub(&pattern, "hit", &pattern, false).as_deref(), Some("hit"));+ }+ assert_eq!(super::regsub("a0", "again", "a0", false).as_deref(), Some("again"));+ super::SUBSTITUTIONS.with(|cache| assert!(cache.borrow().len() <= 8));+ // Unicode word classes exceed the cache's small compiled-size budget.+ assert_eq!(super::regsub(r"\w+", "word", "café 東京", false).as_deref(), Some("word word"));+ let long = "a".repeat(2049);+ assert_eq!(super::regsub(&long, "long", &long, false).as_deref(), Some("long"));+ super::SUBSTITUTIONS.with(|cache| {+ let cache = cache.borrow();+ assert!(cache.len() <= 8);+ assert!(!cache.iter().any(|(pattern, _, _)| pattern == r"\w+" || pattern == &long));+ });+ }+#[test]fn each_expansion_observes_new_agent_option_and_environment_values() {let mut app = status_fixture(1, 2);diff --git a/tui/src/main.rs b/tui/src/main.rsindex e495e77b6..44edb7ce0 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -187,7 +187,7 @@ async fn run_headless(config: config::Config, port: u16) -> io::Result<()> {_ = tokio::time::sleep(Duration::from_millis(500)) => None,};let apply = |app: &mut app::App, event: Event| match event {- Event::Input(_) | Event::Animate => {}+ Event::Input(_) => {}Event::Machine { machine_id, generation, event } => app.on_machine(machine_id, generation, event),Event::Apply(f) => f(app),Event::Tick => app.on_tick(),@@ -400,13 +400,6 @@ async fn run(config: config::Config) -> io::Result<()> {loop { interval.tick().await; if ticks.send(Event::Tick).is_err() { break } }});- // Animation frames do not speed up the maintenance timers (reconnects, RPCs and saves).- let animation = tx.clone();- tokio::spawn(async move {- let mut interval = tokio::time::interval(Duration::from_millis(100));- loop { interval.tick().await; if animation.send(Event::Animate).is_err() { break } }- });-mark("terminal ready");// Its ids ($N @N %N) from this server name's counters: unique among its clients.ids::use_file(&app::sessions_path(None));@@ -470,6 +463,9 @@ async fn run(config: config::Config) -> io::Result<()> {let frame_budget = Duration::from_millis(6);let mut last_draw = Instant::now() - frame_budget;let mut need_draw = true;+ // Rendered animation and timed UI messages schedule their next frame.+ // Maintenance and incoming input/output keep their own cadence.+ let mut next_repaint: Option<Instant> = None;let mut mouse_all = false;let mut cursor_colour: Option<String> = None;let mut startup_input = std::collections::VecDeque::new();@@ -477,10 +473,15 @@ async fn run(config: config::Config) -> io::Result<()> {loop {// Wait for something — or for the frame we owe to come due.let wait = if need_draw { frame_budget.saturating_sub(last_draw.elapsed()) } else { Duration::from_secs(3600) };+ let wait = next_repaint.map(|at| wait.min(at.saturating_duration_since(Instant::now()))).unwrap_or(wait);let first = tokio::select! {event = rx.recv() => event,_ = tokio::time::sleep(wait) => None,};+ if next_repaint.is_some_and(|at| Instant::now() >= at) {+ next_repaint = None;+ need_draw = true;+ }let mut refill = false;let apply = |app: &mut app::App, event: Event, refill: &mut bool, startup: &mut std::collections::VecDeque<crossterm::event::Event>| {match event {@@ -496,7 +497,6 @@ async fn run(config: config::Config) -> io::Result<()> {}Event::Apply(f) => { f(app); *refill = true }Event::Tick => app.on_tick(),- Event::Animate => {},}};if let Some(event) = first { apply(&mut app, event, &mut refill, &mut startup_input); need_draw = true }@@ -549,6 +549,7 @@ async fn run(config: config::Config) -> io::Result<()> {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))?;// 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);@@ -568,6 +569,8 @@ async fn run(config: config::Config) -> io::Result<()> {execute!(term.backend_mut(), terminal::SetTitle(&title))?;app.title = title;}+ // Include custom terminal-title formats: they can animate too.+ next_repaint = ui::next_repaint(&app, frame_started);}}// Its #() jobs ended, as tmux's server ends its jobs.diff --git a/tui/src/term_input.rs b/tui/src/term_input.rsindex 28b417194..ed749af69 100644--- a/tui/src/term_input.rs+++ b/tui/src/term_input.rs@@ -13,9 +13,18 @@ enum InternalEvent { Event(Event), CursorPosition(u16, u16), KeyboardEnhancement#[derive(Debug, PartialEq)]enum Item { Input(Event), Terminal(Option<String>), Foreground(Option<String>), Background(Option<String>), Palette(u8, Option<String>) }+const ESCAPE_DELAY: Duration = Duration::from_millis(50);+#[derive(Default)]struct Decoder { pending: Vec<u8> }impl Decoder {+ /// Only an ambiguous Escape/Alt-P prefix can produce input without another+ /// byte. Other partial sequences and an idle reader wait for the fd itself.+ fn poll_timeout(&self, since_read: Duration) -> libc::c_int {+ if self.pending.is_empty() || self.pending.len() >= 4 || !b"\x1bP>|".starts_with(&self.pending) { return -1 }+ ESCAPE_DELAY.saturating_sub(since_read).as_nanos().div_ceil(1_000_000) as libc::c_int+ }+fn push(&mut self, bytes: &[u8], more: bool) -> Vec<Item> {let mut out = Vec::new();for b in bytes {@@ -136,10 +145,10 @@ pub fn read(keys: tokio::sync::mpsc::UnboundedSender<crate::event::Event>) {let mut buf = [0u8; 8192];loop {let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 };- let n = unsafe { libc::poll(&mut pfd, 1, 50) };+ let n = unsafe { libc::poll(&mut pfd, 1, decoder.poll_timeout(last.elapsed())) };if n < 0 { if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted { continue } break }let items = if n == 0 {- if last.elapsed() >= Duration::from_millis(50) { decoder.escape() } else { Vec::new() }+ if last.elapsed() >= ESCAPE_DELAY { decoder.escape() } else { Vec::new() }} else {let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };if n <= 0 { break }@@ -175,6 +184,51 @@ pub fn read(keys: tokio::sync::mpsc::UnboundedSender<crate::event::Event>) {mod tests {use super::*;use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};++ #[test]+ fn idle_and_finished_input_have_no_poll_deadline() {+ let mut decoder = Decoder::default();+ assert_eq!(decoder.poll_timeout(Duration::ZERO), -1);+ let input = decoder.push("hello 🐯".as_bytes(), false);+ assert_eq!(input.len(), 7);+ assert_eq!(decoder.poll_timeout(Duration::from_secs(1)), -1);+ assert_eq!(decoder.push(b"\x1b", false), vec![Item::Input(Event::Key(KeyCode::Esc.into()))]);+ assert_eq!(decoder.poll_timeout(Duration::ZERO), -1);+ }++ #[test]+ fn ambiguous_prefixes_keep_one_fifty_ms_deadline_after_full_reads() {+ for prefix in [b"\x1b".as_slice(), b"\x1bP", b"\x1bP>"] {+ let mut decoder = Decoder::default();+ assert!(decoder.push(prefix, true).is_empty());+ assert_eq!(decoder.poll_timeout(Duration::ZERO), 50);+ assert_eq!(decoder.poll_timeout(Duration::from_millis(37)), 13);+ assert_eq!(decoder.poll_timeout(Duration::from_micros(49_999)), 1);+ assert_eq!(decoder.poll_timeout(Duration::from_millis(50)), 0);+ assert_eq!(decoder.poll_timeout(Duration::from_secs(1)), 0);+ assert!(!decoder.escape().is_empty(), "{prefix:?}");+ assert_eq!(decoder.poll_timeout(Duration::ZERO), -1);+ }+ }++ #[test]+ fn partial_text_paste_and_terminal_replies_wait_for_more_bytes() {+ let cases: Vec<(&[u8], &[u8], Item)> = vec![+ (b"\xc3", b"\xa9", Item::Input(Event::Key(KeyCode::Char('é').into()))),+ (b"\x1b[", b"A", Item::Input(Event::Key(KeyCode::Up.into()))),+ (b"\x1b[200~first", b" second\x1b[201~", Item::Input(Event::Paste("first second".into()))),+ (b"\x1bP>|Terminal", b"\x1b\\", Item::Terminal(Some("Terminal".into()))),+ (b"\x1b]11;rgb:ffff/", b"0000/0000\x07", Item::Background(Some("#ff0000".into()))),+ ];+ for (prefix, suffix, expected) in cases {+ let mut decoder = Decoder::default();+ assert!(decoder.push(prefix, false).is_empty());+ assert_eq!(decoder.poll_timeout(Duration::from_secs(60)), -1, "{prefix:?}");+ assert_eq!(decoder.push(suffix, false), vec![expected]);+ assert_eq!(decoder.poll_timeout(Duration::ZERO), -1);+ }+ }+#[test]fn query_replies_do_not_consume_interleaved_typeahead() {let mut decoder = Decoder::default();diff --git a/tui/src/theme.rs b/tui/src/theme.rsindex ab257458b..7d664b465 100644--- a/tui/src/theme.rs+++ b/tui/src/theme.rs@@ -1302,16 +1302,52 @@ pub fn most_urgent(states: impl Iterator<Item = State>) -> Option<State> {states.min_by_key(rank)}-thread_local! { static ANIMATIONS: std::cell::Cell<bool> = const { std::cell::Cell::new(true) }; }-pub fn set_animations(on: bool) { ANIMATIONS.with(|a| a.set(on)) }+thread_local! {+ static ANIMATIONS: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };+ static ANIMATION_USED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };+}+pub fn begin_animation_frame(on: bool) {+ ANIMATIONS.with(|a| a.set(on));+ ANIMATION_USED.with(|a| a.set(false));+}pub fn animations() -> bool { ANIMATIONS.with(|a| a.get()) }+pub fn needs_animation_frame() -> bool { ANIMATION_USED.with(|a| a.get()) }++/// Reading an animated frame records demand for the next one. Static screens+/// and reduced-motion indicators do not keep an animation timer running.+pub fn animation_frame() -> usize {+ if !animations() { return 0 }+ ANIMATION_USED.with(|a| a.set(true));+ (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() / 100).unwrap_or(0)) as usize+}/// A spinner frame for things in motion (working dots, connecting cards).pub fn spinner(_tick: u64) -> &'static str {// fzf's frames, in its order.const FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];- let frame = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() / 100).unwrap_or(0);- FRAMES[if animations() { frame as usize % FRAMES.len() } else { 0 }]+ FRAMES[animation_frame() % FRAMES.len()]+}++#[cfg(test)]+mod animation_tests {+ #[test]+ fn only_moving_content_requests_animation_and_each_frame_starts_fresh() {+ use super::*;+ begin_animation_frame(true);+ state_mark(State::Ready, 0);+ state_mark(State::NeedsInput, 0);+ assert!(!needs_animation_frame());+ state_mark(State::Working, 0);+ assert!(needs_animation_frame());+ begin_animation_frame(true);+ assert!(!needs_animation_frame());+ animation_frame(); // the picker's ASCII and Unicode loading frames+ assert!(needs_animation_frame());+ begin_animation_frame(false);+ assert_eq!(spinner(0), "⠋");+ assert_eq!(animation_frame(), 0);+ assert!(!needs_animation_frame());+ }}#[cfg(test)]diff --git a/tui/src/ui.rs b/tui/src/ui.rsindex 45c966f07..9b5314000 100644--- a/tui/src/ui.rs+++ b/tui/src/ui.rs@@ -2,7 +2,7 @@//! The tmux split tree remains intact beneath presentation insets. Classic and tmux looks//! retain line borders; the search keeps fzf's layout and colours with a preview window.-use std::time::{Duration, SystemTime, UNIX_EPOCH};+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};use alacritty_terminal::term::cell::Flags;use alacritty_terminal::term::TermMode;@@ -24,6 +24,123 @@ use crate::picker::Picker;use crate::theme::{self, bold, fg, engine_mark, state_mark};use crate::input::{home_rows, HomeRow};+/// Time-dependent content asks for its next repaint; a static surface asks for+/// none. Hints and messages are deadlines, independent of reduced motion.+pub fn next_repaint(app: &App, frame_started: Instant) -> Option<Instant> {+ // A deadline crossed during rendering still needs one more frame. The next+ // draw starts after it, so expired messages cannot create a repaint loop.+ let now = frame_started;+ let mut next = theme::needs_animation_frame().then(|| now + Duration::from_millis(100));+ let mut deadline = |at: Instant, ms: u64| {+ if let Some(at) = at.checked_add(Duration::from_millis(ms)).filter(|at| *at > now) {+ next = Some(next.map_or(at, |old| old.min(at)));+ }+ };+ if let Some((_, _, at)) = app.toast.as_ref().filter(|_| app.toast_ms() != u64::MAX) {+ deadline(*at, app.toast_ms());+ }+ let hints = !(app.options.tmux_look() && app.options.get("@hn-hint-time", "", None).is_none());+ if app.prefix && hints {+ if let Some(at) = app.prefix_at { deadline(at, app.keymap.hint_ms); }+ }+ next+}++#[cfg(test)]+mod repaint_tests {+ use super::*;++ fn app() -> App {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, (100, 30));+ app.started = Instant::now() - Duration::from_secs(4);+ app+ }++ fn render(app: &mut App) {+ let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();+ term.draw(|frame| draw(frame, app)).unwrap();+ }++ #[test]+ fn rendered_formats_start_and_stop_motion_and_terminal_titles_count_too() {+ let mut app = app();+ render(&mut app);+ assert!(next_repaint(&app, Instant::now()).is_none(), "an empty, settled home is static");+ app.options.global_session.insert("status-right".into(), "#{spinner}".into());+ render(&mut app);+ assert!(next_repaint(&app, Instant::now()).is_some());+ app.options.global_session.insert("@hn-animations".into(), "off".into());+ render(&mut app);+ assert!(next_repaint(&app, Instant::now()).is_none());+ app.options.global_session.insert("@hn-animations".into(), "on".into());+ app.options.global_session.insert("status".into(), "off".into());+ render(&mut app);+ assert!(next_repaint(&app, Instant::now()).is_none(), "a hidden status must not keep its spinner alive");+ app.options.global_session.insert("set-titles-string".into(), "#{spinner}".into());+ assert!(app.window_title().is_some());+ assert!(next_repaint(&app, Instant::now()).is_some(), "terminal titles are expanded after the screen");+ app.options.global_session.insert("set-titles-string".into(), "Harness".into());+ render(&mut app);+ app.window_title();+ assert!(next_repaint(&app, Instant::now()).is_none());+ }++ #[test]+ fn timed_notices_and_hints_keep_their_deadlines_without_motion() {+ let mut app = app();+ theme::begin_animation_frame(false);+ let at = Instant::now();+ app.toast = Some(("notice".into(), Color::Yellow, at));+ app.display_ms = 2500;+ app.prefix = true;+ app.prefix_at = Some(at);+ app.keymap.hint_ms = 1000;+ assert_eq!(next_repaint(&app, Instant::now()), Some(at + Duration::from_millis(1000)));+ app.prefix = false;+ assert_eq!(next_repaint(&app, Instant::now()), Some(at + Duration::from_millis(2500)));+ app.toast_exact = Some(0);+ assert!(next_repaint(&app, Instant::now()).is_none(), "until-keypress notices have no expiry timer");+ app.toast_exact = Some(20);+ app.toast.as_mut().unwrap().2 = at - Duration::from_secs(1);+ app.prefix = true;+ app.prefix_at = Some(at - Duration::from_secs(2));+ assert!(next_repaint(&app, Instant::now()).is_none(), "expired deadlines must not spin the loop");+ app.keymap.hint_ms = u64::MAX;+ next_repaint(&app, Instant::now()); // user-configured delays must not overflow Instant+ }++ #[test]+ fn a_deadline_crossed_during_drawing_gets_one_more_frame() {+ let mut app = app();+ theme::begin_animation_frame(false);+ let now = Instant::now();+ let at = now - Duration::from_millis(100);+ app.toast = Some(("notice".into(), Color::Yellow, at));+ app.toast_exact = Some(90);+ assert_eq!(next_repaint(&app, at), Some(at + Duration::from_millis(90)));+ assert!(next_repaint(&app, now).is_none());+ app.toast = None;+ app.prefix = true;+ app.prefix_at = Some(at);+ app.keymap.hint_ms = 90;+ assert_eq!(next_repaint(&app, at), Some(at + Duration::from_millis(90)));+ assert!(next_repaint(&app, now).is_none());+ }++ #[test]+ fn tmux_hints_only_request_a_frame_when_enabled() {+ let mut app = app();+ theme::begin_animation_frame(false);+ app.options.global_session.insert("@hn-look".into(), "tmux".into());+ app.prefix = true;+ app.prefix_at = Some(Instant::now());+ assert!(next_repaint(&app, Instant::now()).is_none());+ app.options.global_session.insert("@hn-hint-time".into(), "600".into());+ assert_eq!(next_repaint(&app, Instant::now()), app.prefix_at.map(|at| at + Duration::from_millis(600)));+ }+}+/// screen_write_box_border_set: a box's corners, sides and its rule's joins, for tmux's box/// lines (single, double, heavy, simple, rounded, padded, none).fn box_set(lines: &str) -> (&'static str, &'static str, &'static str, &'static str, &'static str, &'static str, &'static str, &'static str) {@@ -38,7 +155,7 @@ fn box_set(lines: &str) -> (&'static str, &'static str, &'static str, &'static s}pub fn draw(frame: &mut Frame, app: &mut App) {- theme::set_animations(app.options.animations());+ theme::begin_animation_frame(app.options.animations());app.renumber();// automatic-rename as of this frame: a pane that went into a mode ([tmux]) or out of one is// named so in the window list it is drawn with.@@ -1297,7 +1414,7 @@ fn fzf(buf: &mut Buffer, body: Rect, picker: &mut Picker, kind: &PickerKind, seaconst SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];const ASCII_SPINNER: [&str; 8] = ["-", "\\", "|", "/", "-", "\\", "|", "/"];let frames: &[&str] = if theme::fzf().unicode { &SPINNER } else { &ASCII_SPINNER };- let spinner = frames[if theme::animations() { (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0) / 100) as usize % frames.len() } else { 0 }];+ let spinner = frames[if reading { theme::animation_frame() % frames.len() } else { 0 }];let w = ia.width as i32;let put = |pbuf: &mut Buffer, x: i32, y: u16, s: &str, st: Style| { if x >= 0 && x < w && !s.is_empty() { pbuf.set_stringn(ia.x + x as u16, y, s, (w - x) as usize, st); } };let bar = |pbuf: &mut Buffer, x: i32, y: u16, n: i32| {@@ -2709,6 +2826,21 @@ mod fzf_list_tests {p.set_query("zzz");assert!(!screen(&mut p).contains("(empty)"));}++ #[test]+ fn only_loading_pickers_ask_for_animation_frames() {+ let mut p = Picker::new("t", "");+ for busy in [false, true, false] {+ theme::begin_animation_frame(true);+ p.busy = busy.then(|| "loading".into());+ screen(&mut p);+ assert_eq!(theme::needs_animation_frame(), busy);+ }+ theme::begin_animation_frame(false);+ p.busy = Some("loading".into());+ screen(&mut p);+ assert!(!theme::needs_animation_frame());+ }}#[cfg(test)]diff --git a/tui/tests/native-terminal.py b/tui/tests/native-terminal.pyindex d990f7300..5a98e28a4 100644--- a/tui/tests/native-terminal.py+++ b/tui/tests/native-terminal.py@@ -120,7 +120,11 @@ class Terminal:self.data.extend(chunk)def write(self, text):- os.write(self.fd, text)+ pending = memoryview(text)+ while pending:+ written = os.write(self.fd, pending)+ assert written > 0, 'PTY input closed'+ pending = pending[written:]def stop(self):if self.proc.poll() is None:@@ -137,6 +141,81 @@ def stop_servers():wait(lambda: not owned(), 'native processes cleaned')+def idle_input():+ """Exercise the real input fd after idle, with byte-exact delivery to a raw PTY."""+ program = BASE / 'record-input.py'+ program.write_text('''import os, signal, sys, tty+from pathlib import Path+tty.setraw(0)+def resized(*_):+ size = os.get_terminal_size(0)+ Path(sys.argv[2]).write_text(f"{size.columns}x{size.lines}")+signal.signal(signal.SIGWINCH, resized)+resized()+with open(sys.argv[1], "ab", buffering=0) as output:+ os.write(1, b"\\x1b[?2004hINPUT_READY")+ while chunk := os.read(0, 65536):+ output.write(chunk)+''')+ for kind in ('hn', 'tmux'):+ recorded = BASE / f'{kind}-input-bytes'+ size_file = BASE / f'{kind}-input-size'+ ui = Terminal(kind, 'new-session', '-s', 'input',+ shlex.join(['python3', str(program), str(recorded), str(size_file)]))+ wait(lambda: b'INPUT_READY' in ui.data, f'{kind} raw input program ready')+ # tmux also applies escape-time (10 ms by default) to partial UTF-8.+ # Allow the deliberate 100 ms fragmentation below in the reference.+ if kind == 'tmux':+ cli(kind, 'set-option', '-s', 'escape-time', '500')+ expected = bytearray()++ def received():+ return recorded.read_bytes() if recorded.exists() else b''++ def send(parts, result):+ for chunk, delay in parts:+ ui.write(chunk)+ if delay:+ time.sleep(delay)+ expected.extend(result)+ wait(lambda: received() == expected, f'{kind} byte-exact input {result[:30]!r}')++ time.sleep(.2)+ send([(b'after-idle', 0)], b'after-idle')+ send([(b'\x1b', 0)], b'\x1b')+ send([(b'\x1bP', 0)], b'\x1bP')+ send([(b'\xc3', .1), (b'\xa9', 0)], 'é'.encode())+ send([(b'\x1b[', .1), (b'A', 0)], b'\x1b[A')+ # Use terminal return bytes; this test isolates buffering/timing from+ # the client's existing normalization of clipboard line endings.+ paste = 'first line\rsecond 🐯'.encode()+ send([(b'\x1b[200~' + paste[:5], .1), (paste[5:] + b'\x1b[201~', 0)],+ b'\x1b[200~' + paste + b'\x1b[201~')+ # A full input buffer may end with Escape: without a deadline that final+ # key could remain stuck until somebody types again.+ burst = b'x' * 8191 + b'\x1b'+ send([(burst, 0)], burst)+ print(f'PASS {kind} idle input: Escape, Alt-P, split UTF-8/arrow/paste and full-buffer typeahead', flush=True)++ time.sleep(.15)+ fcntl.ioctl(ui.fd, termios.TIOCSWINSZ, struct.pack('HHHH', 27, 91, 0, 0))+ wait(lambda: size_file.read_text() == '91x27', f'{kind} resize with no keyboard activity')+ os.kill(ui.proc.pid, signal.SIGSTOP)+ try:+ time.sleep(.1)+ finally:+ os.kill(ui.proc.pid, signal.SIGCONT)+ send([(b'after-resume', 0)], b'after-resume')+ time.sleep(.15)+ # A server command ends the client while its input thread has nothing+ # to read. A blocking wait must not prevent shutdown.+ cli(kind, 'kill-server')+ ui.proc.wait(timeout=4)+ ui.stop()+ assert received() == expected+ print(f'PASS {kind} idle input: resize, process resume and shutdown without another key', flush=True)++def async_creation():"""Hold only our supervisor so pending creation ownership is deterministic."""requests = []@@ -384,6 +463,7 @@ try:print('PASS retained exits/signals, hooks, history, crash recovery and respawn', flush=True)async_creation()+ idle_input()for delay in (0, .1):for kind in ('hn', 'tmux'):diff --git a/tui/tests/repaint.py b/tui/tests/repaint.pynew file mode 100644index 000000000..0c6f98ec1--- /dev/null+++ b/tui/tests/repaint.py@@ -0,0 +1,175 @@+#!/usr/bin/env python3+"""Animation, timed UI and idle-input checks in an isolated real terminal.++Run after a release build. HARNESS_TUI_BIN can select a frozen comparison build.+Only a private HOME, named hn/tmux sockets, and a guarded mock port are used.+"""+import os+from pathlib import Path+import re+import shlex+import shutil+import socket+import subprocess+import tempfile+import time+import urllib.request++ROOT = Path(__file__).resolve().parents[1]+PORT = int(os.environ.get('HN_REPAINT_TEST_PORT', '19794'))+assert 19794 <= PORT <= 19799, 'refusing non-test repaint port'+PREFIX = f'hn-repaint-{os.getpid()}'+BASE = Path(tempfile.mkdtemp(prefix='hn-repaint-', dir='/tmp')).resolve()+HN = BASE / 'hn'+shutil.copy2(os.environ.get('HARNESS_TUI_BIN', ROOT / 'target/release/harness-tui'), HN)+TMUX = shutil.which('tmux')+assert TMUX+ENV = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'TZ') if k in os.environ}+ENV.update(HOME=str(BASE), HN_TMPDIR=str(BASE), HN_SOCKET_NAME=PREFIX, PORT=str(PORT),+ TERM='xterm-256color', SHELL='/bin/sh', HARNESS_TUI_DESK='off',+ HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off', HARNESS_TUI_ASK_TERMINAL='off',+ HARNESS_TUI_KITTY_KEYS='off')+CONF = BASE / 'tmux.conf'+CONF.write_text('set -g automatic-rename off\nset -g status-right "REPAINT_IDLE"\n'+ 'set -g set-titles-string "REPAINT_TITLE"\n')+COMMAND = [str(HN), '-L', PREFIX, '--port', str(PORT), '-f', str(CONF)]+OUTER = [TMUX, '-L', PREFIX + '-outer', '-f', '/dev/null']+++def run(args, ok=True):+ p = subprocess.run(args, env=ENV, cwd=BASE, text=True, capture_output=True, timeout=12)+ if ok:+ assert p.returncode == 0, (args, p.stdout, p.stderr)+ return p.stdout+++def hn(*args):+ return run(COMMAND + list(args))+++def outer(*args):+ return run(OUTER + list(args))+++def screen():+ return outer('capture-pane', '-p', '-t', 'view')+++def wait(fn, label, seconds=5):+ end = time.monotonic() + seconds+ while time.monotonic() < end:+ value = fn()+ if value:+ return value+ time.sleep(.025)+ raise AssertionError(label + '\n' + screen())+++def changes(read, seconds=1.3):+ """Read only the outer terminal, so observing never repaints the application."""+ prior = read()+ count = 0+ end = time.monotonic() + seconds+ while time.monotonic() < end:+ time.sleep(.03)+ value = read()+ if value is None: # tmux can capture between the cells of a terminal update+ continue+ if value != prior:+ count += 1+ prior = value+ return count+++def spinner():+ match = re.search(r'REPAINT_ANIM=([⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏])', screen())+ return match[1] if match else None+++def clock():+ match = re.search(r'REPAINT_CLOCK=\d\d:\d\d:\d\d', screen())+ return match[0] if match else None+++mock = None+started = False+try:+ with socket.socket() as probe:+ probe.bind(('127.0.0.1', PORT))+ with (BASE / 'mock.log').open('w') as log:+ mock = subprocess.Popen(['node', str(ROOT / 'tests/mock-daemon.mjs'), str(PORT)],+ env=ENV, cwd=BASE, stdout=log, stderr=log)+ for _ in range(100):+ assert mock.poll() is None, (BASE / 'mock.log').read_text()+ try:+ with urllib.request.urlopen(f'http://127.0.0.1:{PORT}/api/status', timeout=.2):+ break+ except OSError:+ time.sleep(.05)+ else:+ raise AssertionError('mock startup timeout')+ launch = ['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',+ *[f'{k}={v}' for k, v in ENV.items()], *COMMAND]+ outer('new-session', '-d', '-s', 'view', '-x', '120', '-y', '32', shlex.join(launch))+ started = True+ wait(lambda: 'Mock terminal' in screen() and 'REPAINT_IDLE' in screen(), 'initial frame')++ hn('set', '-g', 'status-right', 'REPAINT_ANIM=#{spinner}')+ wait(lambda: 'REPAINT_ANIM=' in screen(), 'custom spinner visible')+ assert changes(spinner) >= 8, 'animation fell back to maintenance-tick speed'+ hn('set', '-g', '@hn-animations', 'off')+ wait(lambda: spinner() == '⠋', 'reduced motion first frame')+ assert changes(spinner, .6) == 0, 'reduced motion still animates'+ hn('set', '-g', '@hn-animations', 'on')+ assert changes(spinner) >= 8, 'animation did not restart'+ print('PASS repaint: live animation, reduced motion and restarting motion', flush=True)++ hn('set', '-g', 'status-right', 'REPAINT_IDLE')+ hn('set', '-g', 'set-titles-string', 'REPAINT_TITLE=#{spinner}')+ title = lambda: outer('display-message', '-p', '-t', 'view', '#{pane_title}')+ wait(lambda: 'REPAINT_TITLE=' in title(), 'animated terminal title')+ assert changes(title) >= 8, 'terminal title lost its animation timer'+ hn('set', '-g', 'set-titles-string', 'REPAINT_TITLE')+ hn('set', '-g', '@hn-animations', 'off')+ print('PASS repaint: animation used only in the terminal title', flush=True)++ hn('set', '-g', 'status-right', 'REPAINT_CLOCK=%H:%M:%S')+ first = wait(clock, 'clock visible')+ wait(lambda: (value := clock()) is not None and value != first, 'clock advances without animation', seconds=2)+ hn('set', '-g', 'status-right', 'REPAINT_IDLE')+ hn('display-message', '-d', '180', 'REPAINT_NOTICE')+ wait(lambda: 'REPAINT_NOTICE' in screen(), 'notice appears', seconds=.5)+ wait(lambda: 'REPAINT_IDLE' in screen(), 'notice expires', seconds=.7)+ hn('display-message', '-d', '0', 'REPAINT_UNTIL_KEY')+ wait(lambda: 'REPAINT_UNTIL_KEY' in screen(), 'persistent notice appears')+ time.sleep(.4)+ assert 'REPAINT_UNTIL_KEY' in screen()+ # The mock echoes input as output; use C-g so an echoed Escape cannot leave+ # its VT parser inside an unfinished output sequence.+ outer('send-keys', '-t', 'view', 'C-g')+ wait(lambda: 'REPAINT_IDLE' in screen(), 'key dismisses persistent notice')+ hn('bind-key', '-N', 'REPAINT_HINT', 'c', 'new-window')+ hn('set', '-g', '@hn-hint-time', '180')+ outer('send-keys', '-t', 'view', 'C-b')+ wait(lambda: 'REPAINT_HINT' in screen(), 'prefix hints appear', seconds=.7)+ outer('send-keys', '-t', 'view', 'C-g')+ wait(lambda: 'REPAINT_HINT' not in screen(), 'prefix hints disappear')+ print('PASS repaint: clock, timed and persistent notices, delayed key hints', flush=True)++ time.sleep(.4)+ outer('send-keys', '-t', 'view', 'Enter', 'REPAINT_INPUT_READY')+ wait(lambda: 'REPAINT_INPUT_READY' in screen(), 'typing after idle', seconds=1)+ for width, height in [(1, 1), (120, 32)]:+ outer('resize-window', '-t', 'view', '-x', str(width), '-y', str(height))+ wait(lambda: hn('display-message', '-p', '#{client_width} #{client_height}').strip()+ == f'{width} {height}', 'resize')+ wait(lambda: 'REPAINT_INPUT_READY' in screen(), 'content after resize')+ print('PASS repaint: input after idle and recovery from a one-cell terminal', flush=True)+finally:+ if started:+ run(COMMAND + ['kill-server'], ok=False)+ run(OUTER + ['kill-server'], ok=False)+ if mock is not None:+ mock.terminate()+ mock.wait(timeout=5)+ shutil.rmtree(BASE)