From 6bce33dc66b232a5401ead98c29adef33eb895fd Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Sun, 29 Nov 2026 19:12:12 +0000 Subject: [PATCH] slop: Draw a bar for each node A deploy drew a bar for each phase of each node, so bars came and went as nodes moved from copying to comparing to activating. Each node now keeps one bar, labelled with its name, through all three, saying what it's doing like the web app's rows; it goes once the node is activated or has failed. Lines for agents are unchanged. Bars tick every 100 ms: `indicatif` drops draws that come too close together, which left a stale bar until the next update. Tests draw on `indicatif`'s in-memory terminal, at stderr's rate, and check the screen through a node's steps. Refs #21 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 22 +++++ Cargo.toml | 2 + docs/architecture.md | 7 +- src/terminal.rs | 217 +++++++++++++++++++++++++++++++++++-------- 4 files changed, 206 insertions(+), 42 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9346e92..d8e8d81 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2083,6 +2083,7 @@ dependencies = [ "portable-atomic", "unicode-width", "unit-prefix", + "vt100", "web-time", ] @@ -4664,6 +4665,27 @@ dependencies = [ "nix", ] +[[package]] +name = "vt100" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "054ff75fb8fa83e609e685106df4faeffdf3a735d3c74ebce97ec557d5d36fd9" +dependencies = [ + "itoa", + "unicode-width", + "vte", +] + +[[package]] +name = "vte" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd" +dependencies = [ + "arrayvec", + "memchr", +] + [[package]] name = "walkdir" version = "2.5.1" diff --git a/Cargo.toml b/Cargo.toml index 3d5350e..4dcc737 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,4 +41,6 @@ web-push = { version = "0.11", default-features = false } x25519-dalek = { version = "3.0.0", features = ["static_secrets"] } [dev-dependencies] +# Its in-memory terminal, for testing what `slop` draws +indicatif = { version = "0.18", features = ["in_memory"] } tempfile = "3" diff --git a/docs/architecture.md b/docs/architecture.md index 8cff61f..ea1b92e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -115,9 +115,10 @@ a time: the evaluation and the build, then a copy, comparison and activation for the running requests (`templates/running.html`) in a region of the main page, both kept current by the page's event stream (`web/events.rs`). The bars are `` elements, since the content security policy allows no inline styles. -- `slop` shows it with `terminal::Board`. On a terminal, `indicatif` draws a bar for each running - phase below other output; the bars hide while other output is mid-line, which they would - overwrite. Otherwise (for agents) a running phase gets a plain line every 30 seconds, and one +- `slop` shows it with `terminal::Board`. On a terminal, `indicatif` draws bars below other + output: one for each running phase that isn't about a node, and one for each node through its + copy, comparison and activation, from `Phases` like the web app's rows. The bars hide while + other output is mid-line, which they would overwrite. Otherwise (for agents) a running phase gets a plain line every 30 seconds, and one when it ends. ```mermaid diff --git a/src/terminal.rs b/src/terminal.rs index 2964574..6288bae 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -1,8 +1,9 @@ //! What `slop` shows of progress on stderr. //! -//! - On a terminal, a bar for each running phase stays below other output, drawn by `indicatif`. -//! Other output can stop mid-line, and bars drawn then would overwrite the rest of the line, so -//! they're hidden until the line ends. +//! - On a terminal, bars stay below other output, drawn by `indicatif`: one for each running +//! phase that isn't about a node (evaluating, building, pushing), and one for each node, through +//! its copy, comparison and activation. Other output can stop mid-line, and bars drawn then +//! would overwrite the rest of the line, so they're hidden until the line ends. //! - Otherwise (for agents), a phase gets a plain line every [`SUMMARY_INTERVAL`] while it runs, //! and one when it ends, with no control characters. use std::collections::HashMap; @@ -11,11 +12,14 @@ use std::time::{Duration, Instant}; use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle}; -use crate::progress::{Phase, Progress, State, elapsed}; +use crate::progress::{NodeRow, Phase, Phases, Progress, State, elapsed}; /// How often a running phase gets a line without a terminal. pub const SUMMARY_INTERVAL: Duration = Duration::from_secs(30); +/// How often the bars are drawn again. +const TICK: Duration = Duration::from_millis(100); + pub struct Board { /// The bars, on a terminal. bars: Option, @@ -25,22 +29,36 @@ pub struct Board { struct Bars { multi: MultiProgress, - running: Vec<(Phase, ProgressBar)>, + /// Where they're drawn: stderr, except in tests. + target: Box ProgressDrawTarget + Send>, + phases: Phases, + /// The bars, with what they're for and their labels. + bars: Vec<(Key, String, ProgressBar)>, /// Whether other output stopped mid-line, which hides the bars. mid_line: bool, } +/// What a bar is for. +#[derive(Debug, Clone, PartialEq)] +enum Key { + Phase(Phase), + Node(String), +} + impl Board { /// Bars if `indicatif` would draw them on stderr, lines otherwise: it draws nothing at all, /// not even lines above the bars, if stderr isn't a terminal or `TERM` is `dumb`. pub fn new() -> Board { - Board::with_terminal(!ProgressDrawTarget::stderr().is_hidden()) + Board::with_target(ProgressDrawTarget::stderr) } - fn with_terminal(terminal: bool) -> Board { - let bars = terminal.then(|| Bars { - multi: MultiProgress::with_draw_target(ProgressDrawTarget::stderr()), - running: Vec::new(), + /// Bars drawn on `target`, unless it's hidden. + fn with_target(target: impl Fn() -> ProgressDrawTarget + Send + 'static) -> Board { + let bars = (!target().is_hidden()).then(|| Bars { + multi: MultiProgress::with_draw_target(target()), + target: Box::new(target), + phases: Phases::default(), + bars: Vec::new(), mid_line: false, }); Board { bars, said: HashMap::new() } @@ -68,35 +86,27 @@ impl Board { // Progress always starts on a line of its own. bars.line_ended(true); - - let position = bars.running.iter().position(|(phase, _)| *phase == progress.phase); + bars.phases.record(progress); if ended { - if let Some(index) = position { - let (_, bar) = bars.running.remove(index); - bar.finish_and_clear(); - bars.multi.remove(&bar); - } let _ = bars.multi.println(line); - return; } - let bar = match position { - Some(index) => bars.running[index].1.clone(), + match progress.phase.node() { + None if ended => bars.remove(&Key::Phase(progress.phase.clone())), None => { - let bar = bars.multi.add(ProgressBar::no_length().with_style(style())); - bar.set_prefix(progress.phase.doing()); - bars.running.push((progress.phase.clone(), bar.clone())); - bar + let bar = bars.bar(Key::Phase(progress.phase.clone()), progress.phase.doing()); + show(&bar, progress, details(progress)); } - }; - // The text first, so the bar and its count move together - bar.set_message(details(progress)); - match progress.bar() { - Some(count) => { - bar.set_length(count.total); - bar.set_position(count.done); + Some(node) => { + let row = bars.phases.node(node).expect("just recorded"); + let key = Key::Node(node.to_owned()); + if row.ended() { + bars.remove(&key); + } else { + let bar = bars.bar(key, node.to_owned()); + show(&bar, &row.latest, node_details(&row)); + } } - None => bar.unset_length(), } } @@ -132,7 +142,7 @@ impl Board { /// Takes the bars off the terminal, before `slop` exits. pub fn clear(&mut self) { if let Some(bars) = &mut self.bars { - for (_, bar) in bars.running.drain(..) { + for (_, _, bar) in bars.bars.drain(..) { bar.finish_and_clear(); } let _ = bars.multi.clear(); @@ -147,6 +157,37 @@ impl Default for Board { } impl Bars { + /// The bar for `key`, added with `label` if there isn't one. + fn bar(&mut self, key: Key, label: String) -> ProgressBar { + if let Some((_, _, bar)) = self.bars.iter().find(|(k, _, _)| *k == key) { + return bar.clone(); + } + let bar = self.multi.add(ProgressBar::no_length().with_style(style())); + // `indicatif` drops draws that come too close together, which would leave a stale bar + // until the next update; ticking draws the latest soon after. + bar.enable_steady_tick(TICK); + self.bars.push((key, label, bar.clone())); + self.align(); + bar + } + + fn remove(&mut self, key: &Key) { + if let Some(index) = self.bars.iter().position(|(k, _, _)| k == key) { + let (_, _, bar) = self.bars.remove(index); + bar.finish_and_clear(); + self.multi.remove(&bar); + self.align(); + } + } + + /// Pads the labels to the longest, so the bars line up. + fn align(&self) { + let width = self.bars.iter().map(|(_, label, _)| label.chars().count()).max().unwrap_or(0); + for (_, label, bar) in &self.bars { + bar.set_prefix(format!("{label:width$}")); + } + } + /// Notes whether other output ended its line, hiding the bars until it does. When a line is /// due and the last one didn't end, it ends it. fn line_ended(&mut self, ended: bool) { @@ -160,7 +201,7 @@ impl Bars { if self.mid_line { // The line other output left unfinished, for what comes next eprintln!(); - self.multi.set_draw_target(ProgressDrawTarget::stderr()); + self.multi.set_draw_target((self.target)()); self.mid_line = false; } } @@ -171,6 +212,32 @@ fn style() -> ProgressStyle { ProgressStyle::with_template("{prefix} ▕{bar:20}▏ {wide_msg}").unwrap().progress_chars("█▉▊▋▌▍▎▏ ") } +/// Moves a bar to a phase's progress: its count, empty while it has none, or full once it's +/// done. The length and position change together. +fn show(bar: &ProgressBar, progress: &Progress, message: String) { + // The text first, so the bar and its count move together + bar.set_message(message); + match (progress.state, progress.bar()) { + (State::Running, Some(count)) => bar.update(|state| { + state.set_len(count.total); + state.set_pos(count.done); + }), + (State::Running, None) => bar.unset_length(), + _ => bar.update(|state| { + state.set_len(1); + state.set_pos(1); + }), + } +} + +/// What follows a node's bar: what it's doing, and while it runs, the counts and the time. +fn node_details(row: &NodeRow) -> String { + match row.latest.state { + State::Running => format!("{} · {}", row.state, details(&row.latest)), + _ => row.state.to_owned(), + } +} + /// What follows a bar: the counts, what's running now and the time. fn details(progress: &Progress) -> String { let counted = progress.counted(false); @@ -182,6 +249,7 @@ fn details(progress: &Progress) -> String { mod tests { use super::*; use crate::progress::{Count, Counts}; + use indicatif::InMemoryTerm; fn running(done: u64) -> Progress { Progress { @@ -204,14 +272,28 @@ mod tests { assert_eq!(details(&starting), "0s"); } + /// A board drawing on a terminal in memory, 80 columns wide, at most 20 times a second like + /// on stderr. + fn on_screen() -> (Board, InMemoryTerm) { + let term = InMemoryTerm::new(12, 80); + let target = term.clone(); + (Board::with_target(move || ProgressDrawTarget::term_like_with_hz(Box::new(target.clone()), 20)), term) + } + + /// What's on the screen once the bars have ticked, without trailing spaces. + fn screen(term: &InMemoryTerm) -> Vec { + std::thread::sleep(TICK * 3); + term.contents().lines().map(|l| l.trim_end().to_owned()).filter(|l| !l.is_empty()).collect() + } + #[test] fn keeps_track_of_bars() { - let mut board = Board::with_terminal(true); + let (mut board, _term) = on_screen(); board.update(&running(3)); board.update(&running(4)); let bars = board.bars.as_ref().unwrap(); - assert_eq!(bars.running.len(), 1); - assert_eq!(bars.running[0].1.position(), 4); + assert_eq!(bars.bars.len(), 1); + assert_eq!(bars.bars[0].2.position(), 4); // Output stopping mid-line hides the bars until the line ends. board.write(&mut Vec::new(), b"partial").unwrap(); @@ -220,16 +302,73 @@ mod tests { assert!(!board.bars.as_ref().unwrap().mid_line); board.update(&Progress { state: State::Done, ..running(8) }); - assert!(board.bars.as_ref().unwrap().running.is_empty()); + assert!(board.bars.as_ref().unwrap().bars.is_empty()); + } + + #[test] + fn keeps_a_bar_for_each_node() { + let (mut board, _term) = on_screen(); + let phase = |phase, state| Progress { phase, state, elapsed: 1, counts: Counts::default() }; + let labels = |board: &Board| -> Vec { + board.bars.as_ref().unwrap().bars.iter().map(|(_, _, bar)| bar.prefix()).collect() + }; + + board.update(&phase(Phase::Copy("river".into()), State::Running)); + board.update(&phase(Phase::Copy("stream".into()), State::Running)); + board.update(&phase(Phase::Copy("river".into()), State::Done)); + board.update(&phase(Phase::Compare("river".into()), State::Running)); + board.update(&phase(Phase::Push, State::Running)); + assert_eq!(labels(&board), ["river ", "stream ", "pushing to the cache"]); + assert_eq!(board.bars.as_ref().unwrap().bars[0].2.message(), "comparing · 1s"); + + // A node's bar goes once it's activated, or failed. + board.update(&phase(Phase::Activate("river".into()), State::Done)); + board.update(&phase(Phase::Copy("stream".into()), State::Failed)); + assert_eq!(labels(&board), ["pushing to the cache"]); } #[test] fn says_little_without_a_terminal() { - let mut board = Board::with_terminal(false); + // As when stderr isn't a terminal, or `TERM` is `dumb` + let mut board = Board::with_target(ProgressDrawTarget::hidden); + assert!(board.bars.is_none()); board.update(&running(3)); board.update(&running(4)); assert!(board.said.contains_key(&Phase::Build)); board.update(&Progress { state: State::Failed, ..running(4) }); assert!(board.said.is_empty()); } + + #[test] + fn draws_a_node_through_its_steps() { + let (mut board, term) = on_screen(); + let paths = |done| Counts { paths: Some(Count { done, total: 4 }), ..Counts::default() }; + let copy = + |state, done| Progress { phase: Phase::Copy("river".into()), state, elapsed: 2, counts: paths(done) }; + let phase = |phase, state| Progress { phase, state, elapsed: 1, counts: Counts::default() }; + + board.update(©(State::Running, 1)); + assert_eq!(screen(&term), ["river ▕█████▏ ▏ copying · 1/4 paths · 2s"]); + + // Comparing has no count, so its bar is empty, not the copy's. Updates coming fast use up + // the draws `indicatif` allows, which mustn't leave the screen behind. + for _ in 0..50 { + board.update(©(State::Running, 3)); + } + board.update(©(State::Done, 4)); + board.update(&phase(Phase::Compare("river".into()), State::Running)); + assert_eq!( + screen(&term), + ["slop: copied to river: 4 paths in 2s", "river ▕ ▏ comparing · 1s"] + ); + + // Compared, and waiting for the deploy's approval + board.update(&phase(Phase::Compare("river".into()), State::Done)); + assert_eq!(screen(&term)[2], "river ▕████████████████████▏ ready"); + + // Activated: the bar goes, and the line stays. + board.update(&phase(Phase::Activate("river".into()), State::Running)); + board.update(&phase(Phase::Activate("river".into()), State::Done)); + assert_eq!(screen(&term).last().unwrap(), "slop: activated river in 1s"); + } }