From a1c337fc516c99e172ca4fc568adfbff2e90bccb Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Sun, 29 Nov 2026 13:35:01 +0000 Subject: [PATCH] slop: Draw progress bars On a terminal, `slop` keeps a bar for each running phase below other output, drawn by `indicatif`. Remote output can stop mid-line, which bars drawn then would overwrite, so they hide until the line ends. Without a terminal, as for agents, it writes a plain line for a running phase every 30 seconds and one when it ends. Refs #21 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 44 ++++++++ Cargo.toml | 1 + docs/architecture.md | 5 + slop-tools.md | 3 + src/bin/slop.rs | 46 ++++---- src/lib.rs | 1 + src/terminal.rs | 244 +++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 323 insertions(+), 21 deletions(-) create mode 100644 src/terminal.rs diff --git a/Cargo.lock b/Cargo.lock index 7c2a584..9346e92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -697,6 +697,18 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "unicode-width", + "windows-sys 0.61.2", +] + [[package]] name = "const-oid" version = "0.6.2" @@ -1210,6 +1222,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + [[package]] name = "equivalent" version = "1.0.3" @@ -2055,6 +2073,19 @@ dependencies = [ "serde_core", ] +[[package]] +name = "indicatif" +version = "0.18.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9433806cd6b4ec1aba79c021c7e4c58fb4c3b9977c085062e611ac929998fb0c" +dependencies = [ + "console", + "portable-atomic", + "unicode-width", + "unit-prefix", + "web-time", +] + [[package]] name = "inout" version = "0.1.4" @@ -3873,6 +3904,7 @@ dependencies = [ "futures-util", "hex", "humantime", + "indicatif", "nix", "openidconnect", "rand 0.9.5", @@ -4532,12 +4564,24 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + [[package]] name = "unicode-xid" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "unit-prefix" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" + [[package]] name = "universal-hash" version = "0.5.1" diff --git a/Cargo.toml b/Cargo.toml index b77b257..3d5350e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ clap = { version = "4", features = ["derive", "env"] } futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } hex = "0.4" humantime = "2" +indicatif = "0.18" # Already a dependency of `tokio-vsock` nix = { version = "0.31", default-features = false, features = ["signal", "user"] } openidconnect = "4.1" diff --git a/docs/architecture.md b/docs/architecture.md index dd25200..472de83 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -103,6 +103,10 @@ a time: the build, then a copy, comparison and activation for each node, or the answer. The broker's own copies read Nix's log with `exec::run_nix`. - `Reporter` sends a phase's progress to the requester when it starts, at most once a second while it runs, and when it ends. +- `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 + when it ends. ```mermaid flowchart LR @@ -151,6 +155,7 @@ What each request runs, and whose code, decides whether it needs an approval fir | `src/ops/ssh.rs`, `src/ops/query.rs`, `src/ops/deploy.rs`, `src/ops/build.rs` | Operations; `deploy.rs` also parses the comparison script, `src/ops/inspect.sh` | | `src/ops/secret.rs`, `src/ops/secret/format.rs` | Age secrets: what approvers see, encryption, generated values; env and JSON fields | | `src/progress.rs` | Progress of builds, copies and deploys: Nix's JSON log read into counts (`NixLog`), and the `Progress` messages (`Reporter`) | +| `src/terminal.rs` | How `slop` shows progress: bars on a terminal, with `indicatif`, or plain lines (`Board`) | | `src/builder.rs` | Both sides of the builder: the worker (forced command) and the broker's client; also reads secrets and deploy nodes on the main branch | | `src/approve.rs` | Approver connections (many requests each), `slop-approve` client, `approve()` used by every approver | | `src/remote.rs` | SSH transport: the `slop-broker remote` forced command, the remote socket, `connect` for both clients, and `address` (environment, then `~/.config/slop/config.toml`, then the default) | diff --git a/slop-tools.md b/slop-tools.md index 232a7a3..b62262c 100644 --- a/slop-tools.md +++ b/slop-tools.md @@ -61,6 +61,9 @@ applies a policy, and asks a human to approve most requests. and their diff; that may be covered by a lease from an earlier request. Then the build and the copy to the nodes happen, with their progress shown as they go, and the deploy itself waits for approval. Keep commits focused so the diff is quick to review. +- Progress comes as a `slop:` line for each step (the build, and copying, comparing and + activating on each node) every 30 seconds or so while it runs and when it ends, such as + `slop: building: 37/120 derivations (firefox-147.0), 4m 10s`. - Build logs aren't shown, only progress; a failed build shows the end of its log. `--logs` (on `slop deploy` and `slop build`) shows them all as they happen, which is a lot of output. - `--boot` makes it the boot default without switching; the box uses it after its next reboot. diff --git a/src/bin/slop.rs b/src/bin/slop.rs index 745643c..3619ff2 100644 --- a/src/bin/slop.rs +++ b/src/bin/slop.rs @@ -6,16 +6,16 @@ use std::process::exit; use anyhow::{Context, Result, bail}; use clap::{Args, Parser, Subcommand}; use futures_util::{SinkExt, StreamExt}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::io::AsyncReadExt; use tokio::sync::mpsc; -use slop_broker::progress::State; use slop_broker::proto::{ ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, GenKind, HOST_CID, MAX_SSH_SHOWN, OpResult, Operation, PROTOCOL_VERSION, Query, Request, SecretFile, SecretOp, ServerMessage, Target as SecretTarget, decode, encode, transport, }; use slop_broker::remote::{self, Role, Stream}; +use slop_broker::terminal::Board; use slop_broker::types::{ Arg, CommitId, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath, Since, UnitName, UserName, @@ -486,37 +486,41 @@ async fn run(cli: Cli) -> Result { }); tx.send(ClientMessage::Request(request)).await?; - let (mut stdout, mut stderr) = (tokio::io::stdout(), tokio::io::stderr()); + // Progress bars stay below other output on a terminal; `slop`'s own lines go above them. + let mut board = Board::new(); loop { let frame = source.next().await.context("the broker closed the connection")??; - match decode::(&frame)? { + let message = decode::(&frame)?; + + // The end: no more bars + if matches!( + message, + ServerMessage::Finished { .. } + | ServerMessage::Denied(_) + | ServerMessage::Expired + | ServerMessage::Error(_) + ) { + board.clear(); + } + + match message { ServerMessage::Pending { id, summary } => { - eprintln!("slop: waiting for approval of `{summary}` (request {id})…") + board.say(&format!("slop: waiting for approval of `{summary}` (request {id})…")) } ServerMessage::Approved { by, stdin } => { match by { - ApprovedBy::Lease => eprintln!("slop: approved (lease)"), - ApprovedBy::Approver => eprintln!("slop: approved"), + ApprovedBy::Lease => board.say("slop: approved (lease)"), + ApprovedBy::Approver => board.say("slop: approved"), ApprovedBy::Policy => {} } if stdin { tokio::spawn(forward_stdin(tx.clone())); } } - ServerMessage::Info(message) => eprintln!("slop: {message}"), - ServerMessage::Progress(progress) => { - if progress.state != State::Running { - eprintln!("slop: {}", progress.line()); - } - } - ServerMessage::Stdout(data) => { - stdout.write_all(&data).await?; - stdout.flush().await?; - } - ServerMessage::Stderr(data) => { - stderr.write_all(&data).await?; - stderr.flush().await?; - } + ServerMessage::Info(message) => board.say(&format!("slop: {message}")), + ServerMessage::Progress(progress) => board.update(&progress), + ServerMessage::Stdout(data) => board.write(&mut std::io::stdout().lock(), &data)?, + ServerMessage::Stderr(data) => board.write(&mut std::io::stderr().lock(), &data)?, ServerMessage::Finished { exit, result } => { match (result, &secret) { // New ciphertext goes back into the file, never to the terminal. diff --git a/src/lib.rs b/src/lib.rs index aed261b..de30747 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,5 +14,6 @@ pub mod queue; pub mod remote; pub mod server; pub mod targets; +pub mod terminal; pub mod types; pub mod web; diff --git a/src/terminal.rs b/src/terminal.rs new file mode 100644 index 0000000..a71c719 --- /dev/null +++ b/src/terminal.rs @@ -0,0 +1,244 @@ +//! 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. +//! - 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; +use std::io::Write; +use std::time::{Duration, Instant}; + +use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle}; + +use crate::progress::{Bytes, Phase, Progress, State, elapsed}; + +/// How often a running phase gets a line without a terminal. +pub const SUMMARY_INTERVAL: Duration = Duration::from_secs(30); + +pub struct Board { + /// The bars, on a terminal. + bars: Option, + /// When each running phase last had a line, without a terminal. + said: HashMap, +} + +struct Bars { + multi: MultiProgress, + running: Vec<(Phase, ProgressBar)>, + /// Whether other output stopped mid-line, which hides the bars. + mid_line: bool, +} + +impl Board { + /// Bars if stderr is a terminal, lines otherwise. + pub fn new() -> Board { + use std::io::IsTerminal; + Board::with_terminal(std::io::stderr().is_terminal()) + } + + fn with_terminal(terminal: bool) -> Board { + let bars = terminal.then(|| Bars { + multi: MultiProgress::with_draw_target(ProgressDrawTarget::stderr()), + running: Vec::new(), + mid_line: false, + }); + Board { bars, said: HashMap::new() } + } + + /// Shows a phase's progress: its bar, or a line when it's due or the phase ends. + pub fn update(&mut self, progress: &Progress) { + let ended = progress.state != State::Running; + let line = format!("slop: {}", progress.line()); + + let Some(bars) = &mut self.bars else { + let due = self.said.get(&progress.phase).is_none_or(|said| said.elapsed() >= SUMMARY_INTERVAL); + if ended { + self.said.remove(&progress.phase); + eprintln!("{line}"); + } else if due { + // Not the first: a phase starting doesn't need a line of its own + if self.said.contains_key(&progress.phase) { + eprintln!("{line}"); + } + self.said.insert(progress.phase.clone(), Instant::now()); + } + return; + }; + + // Progress always starts on a line of its own. + bars.line_ended(true); + + let position = bars.running.iter().position(|(phase, _)| *phase == progress.phase); + 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(), + 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 + } + }; + // 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); + } + None => bar.unset_length(), + } + } + + /// Writes other output, keeping it clear of the bars. + pub fn write(&mut self, out: &mut impl Write, data: &[u8]) -> std::io::Result<()> { + let Some(bars) = &mut self.bars else { + out.write_all(data)?; + return out.flush(); + }; + if data.is_empty() { + return Ok(()); + } + + bars.multi.suspend(|| { + out.write_all(data)?; + out.flush() + })?; + bars.line_ended(data.ends_with(b"\n")); + Ok(()) + } + + /// Writes a line of `slop`'s own, above the bars. + pub fn say(&mut self, line: &str) { + match &mut self.bars { + Some(bars) => { + bars.line_ended(true); + let _ = bars.multi.println(line); + } + None => eprintln!("{line}"), + } + } + + /// 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(..) { + bar.finish_and_clear(); + } + let _ = bars.multi.clear(); + } + } +} + +impl Default for Board { + fn default() -> Board { + Board::new() + } +} + +impl Bars { + /// 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) { + if !ended { + if !self.mid_line { + self.multi.set_draw_target(ProgressDrawTarget::hidden()); + self.mid_line = true; + } + return; + } + if self.mid_line { + // The line other output left unfinished, for what comes next + eprintln!(); + self.multi.set_draw_target(ProgressDrawTarget::stderr()); + self.mid_line = false; + } + } +} + +/// A bar's layout, like `building ▕████▌ ▏ 37/120 · 3.0 MiB/3.0 GiB · firefox-147.0 · 1m 2s`. +fn style() -> ProgressStyle { + ProgressStyle::with_template("{prefix} ▕{bar:20}▏ {wide_msg}").unwrap().progress_chars("█▉▊▋▌▍▎▏ ") +} + +/// What follows a bar: the count, bytes, what's running now and the time. +fn details(progress: &Progress) -> String { + let mut parts = Vec::new(); + if let Some(count) = progress.bar() { + parts.push(format!("{}/{}", count.done, count.total)); + } + if let Some(bytes) = progress.counts.bytes.filter(|b| b.total > 0) { + parts.push(format!("{}/{}", Bytes(bytes.done), Bytes(bytes.total))); + } + if !progress.counts.current.is_empty() { + parts.push(progress.counts.current.join(", ")); + } + parts.push(elapsed(progress.elapsed)); + parts.join(" · ") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::progress::{Count, Counts}; + + fn running(done: u64) -> Progress { + Progress { + phase: Phase::Build, + state: State::Running, + elapsed: 62, + counts: Counts { + builds: Some(Count { done, total: 8 }), + bytes: Some(Count { done: 1024, total: 4096 }), + current: vec!["firefox-147.0".into()], + ..Counts::default() + }, + } + } + + #[test] + fn details_follow_the_bar() { + assert_eq!(details(&running(3)), "3/8 · 1.0 KiB/4.0 KiB · firefox-147.0 · 1m 2s"); + let starting = Progress { counts: Counts::default(), elapsed: 0, ..running(0) }; + assert_eq!(details(&starting), "0s"); + } + + #[test] + fn keeps_track_of_bars() { + let mut board = Board::with_terminal(true); + 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); + + // Output stopping mid-line hides the bars until the line ends. + board.write(&mut Vec::new(), b"partial").unwrap(); + assert!(board.bars.as_ref().unwrap().mid_line); + board.write(&mut Vec::new(), b" line\n").unwrap(); + 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()); + } + + #[test] + fn says_little_without_a_terminal() { + let mut board = Board::with_terminal(false); + 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()); + } +}