Skip to main content

ados_term/progress/
mod.rs

1//! Live step-progress UI.
2//!
3//! A step engine emits [`ProgressEvent`]s through a [`ProgressSink`] (cheap to
4//! clone, a no-op when no renderer is attached). A renderer thread consumes them
5//! and draws one of: a full-screen split dashboard ([`RenderMode::Fullscreen`]),
6//! an inline sticky block on stderr ([`RenderMode::Rich`]), or clean line
7//! transitions ([`RenderMode::Plain`]). The durable log keeps flowing to the
8//! tool's own subscriber; this UI is purely additive operator feedback.
9//!
10//! Mode is chosen from **stderr** (where the inline UI renders) plus the
11//! environment, so it behaves correctly under `curl … | sudo bash` (stdin is a
12//! pipe, stderr is the operator's terminal) and degrades to plain text in CI /
13//! piped / `TERM=dumb` contexts.
14
15pub mod events;
16pub mod export;
17pub mod fullscreen;
18pub mod model;
19pub mod plain;
20pub mod rich;
21
22use std::io::{IsTerminal, Write};
23use std::sync::mpsc::{self, Sender};
24use std::sync::OnceLock;
25use std::thread::JoinHandle;
26
27use tracing::field::{Field, Visit};
28use tracing::{Event, Subscriber};
29use tracing_subscriber::layer::{Context, Layer};
30
31pub use events::{group_index_for_step, GroupMap, ProgressEvent, ProgressSpec, SummaryView};
32
33use crate::outcome::StepOutcome;
34use crate::theme::Theme;
35use crate::tty::Tty;
36
37/// The renderer thread name.
38const THREAD_NAME: &str = "ados-term-ui";
39
40/// Set once a log-forwarding renderer is running. The tracing [`ChannelLayer`]
41/// forwards log lines here; until it is set, forwarding is a no-op.
42static LOG_TX: OnceLock<Sender<ProgressEvent>> = OnceLock::new();
43
44/// Which renderer to drive, decided once at startup.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum RenderMode {
47    /// Full-screen split dashboard on an open [`Tty`].
48    Fullscreen,
49    /// Inline sticky-block dashboard on stderr (stderr is a terminal but no
50    /// full-screen terminal could be opened).
51    Rich,
52    /// Clean escape-free line transitions (non-tty / CI / `--plain`).
53    Plain,
54    /// Only the final summary (and errors).
55    Quiet,
56    /// No UI; the tool writes machine output itself.
57    Json,
58}
59
60/// The output flags a tool's command line carries.
61#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
62pub struct ModeFlags {
63    /// Machine output; no UI.
64    pub json: bool,
65    /// Only the final summary.
66    pub quiet: bool,
67    /// Force the plain line renderer.
68    pub plain: bool,
69}
70
71/// Decide the render mode from the flags + environment. Gates on **stderr**
72/// because that is where the inline UI draws.
73pub fn detect_mode(flags: ModeFlags) -> RenderMode {
74    if flags.json {
75        return RenderMode::Json;
76    }
77    if flags.quiet {
78        return RenderMode::Quiet;
79    }
80    let is_tty = std::io::stderr().is_terminal();
81    let ci = std::env::var_os("CI").is_some();
82    let dumb = std::env::var("TERM").map(|t| t == "dumb").unwrap_or(false);
83    if flags.plain || !is_tty || ci || dumb {
84        return RenderMode::Plain;
85    }
86    RenderMode::Rich
87}
88
89/// Resolve the live render mode + terminal, upgrading `Rich` to `Fullscreen`
90/// when a terminal can be opened. `carried` is a still-open [`Tty`] (a wizard →
91/// progress handoff keeps one alternate-screen session); when it is `None` but
92/// the base mode is `Rich`, `open` is tried (pass [`Tty::open_controlling`] or
93/// [`Tty::open_stdio`]). Plain / Quiet / Json drop any carried `Tty` (leaving
94/// the alternate screen) and keep the base renderer.
95pub fn resolve_live_mode(
96    base: RenderMode,
97    carried: Option<Tty>,
98    open: fn() -> std::io::Result<Option<Tty>>,
99) -> (RenderMode, Option<Tty>) {
100    match base {
101        RenderMode::Rich => {
102            if let Some(t) = carried {
103                (RenderMode::Fullscreen, Some(t))
104            } else if let Ok(Some(t)) = open() {
105                (RenderMode::Fullscreen, Some(t))
106            } else {
107                (RenderMode::Rich, None)
108            }
109        }
110        other => {
111            drop(carried);
112            (other, None)
113        }
114    }
115}
116
117/// A cheap, clonable handle the step engine emits events through. A sink with
118/// no channel (the default, or [`RenderMode::Json`]) silently drops events.
119#[derive(Debug, Clone, Default)]
120pub struct ProgressSink {
121    tx: Option<Sender<ProgressEvent>>,
122}
123
124impl ProgressSink {
125    fn send(&self, ev: ProgressEvent) {
126        if let Some(tx) = &self.tx {
127            let _ = tx.send(ev);
128        }
129    }
130
131    /// A step's `run()` is about to execute.
132    pub fn step_started(&self, id: &str) {
133        self.send(ProgressEvent::StepStarted { id: id.to_string() });
134    }
135
136    /// A step finished (ran or skipped) with this outcome.
137    pub fn step_result(&self, id: &str, outcome: &StepOutcome) {
138        self.send(ProgressEvent::StepResult {
139            id: id.to_string(),
140            outcome: outcome.clone(),
141        });
142    }
143
144    /// Incremental sub-progress for a step that reports a fraction.
145    pub fn sub_progress(&self, id: &str, done: u64, total: u64) {
146        self.send(ProgressEvent::SubProgress {
147            id: id.to_string(),
148            done,
149            total,
150        });
151    }
152
153    /// Set the curated headline for the running step's live-detail pane.
154    pub fn activity(&self, id: &str, message: String) {
155        self.send(ProgressEvent::Activity {
156            id: id.to_string(),
157            message,
158        });
159    }
160
161    /// Emit one raw subprocess line into the running step's log tail.
162    pub fn sub_log(&self, id: &str, line: &str) {
163        self.send(ProgressEvent::SubLog {
164            id: id.to_string(),
165            line: line.to_string(),
166        });
167    }
168
169    /// Byte-level download progress for the running step's current file.
170    pub fn byte_progress(&self, id: &str, done: u64, total: u64, label: &str) {
171        self.send(ProgressEvent::ByteProgress {
172            id: id.to_string(),
173            done,
174            total,
175            label: label.to_string(),
176        });
177    }
178
179    /// The closing summary (success card / failure panel).
180    pub fn summary(&self, s: Box<dyn SummaryView>) {
181        self.send(ProgressEvent::Summary(s));
182    }
183
184    /// Stop the renderer and restore the terminal.
185    pub fn finish(&self) {
186        self.send(ProgressEvent::Finished);
187    }
188}
189
190/// Owns the renderer thread; [`RenderHandle::finish`] joins it (call after
191/// sending [`ProgressSink::summary`] + [`ProgressSink::finish`]).
192pub struct RenderHandle {
193    join: Option<JoinHandle<()>>,
194}
195
196impl RenderHandle {
197    /// Wait for the renderer to draw the final summary and restore the terminal.
198    pub fn finish(self) {
199        if let Some(j) = self.join {
200            let _ = j.join();
201        }
202    }
203}
204
205/// Create the progress sink + spawn the renderer thread for `mode`. `header` is
206/// the one-line banner the renderer prints first. `tty` is the terminal for
207/// `Fullscreen` (from [`resolve_live_mode`]); the other modes ignore it (it is
208/// dropped, leaving the alternate screen if one was carried). `interactive`
209/// holds a non-failed closing card full-screen until a key press.
210pub fn start(
211    mode: RenderMode,
212    header: String,
213    theme: Theme,
214    tty: Option<Tty>,
215    spec: ProgressSpec,
216    interactive: bool,
217) -> (ProgressSink, RenderHandle) {
218    if mode == RenderMode::Json {
219        return (ProgressSink::default(), RenderHandle { join: None });
220    }
221    let (tx, rx) = mpsc::channel::<ProgressEvent>();
222    let sink = ProgressSink {
223        tx: Some(tx.clone()),
224    };
225    let join = match (mode, tty) {
226        (RenderMode::Fullscreen, Some(tty)) => {
227            // The `Tty`'s own panic-reset hook leaves the alternate screen and
228            // un-raws on a panic, so no stderr cursor hook here.
229            let _ = LOG_TX.set(tx);
230            spawn(move || fullscreen::run(tty, rx, theme, header, spec, interactive))
231        }
232        (RenderMode::Fullscreen | RenderMode::Rich, _) => {
233            // The renderer hides the cursor; a panic (release builds abort) must
234            // still restore it, so install the hook before drawing.
235            install_panic_hook();
236            // Forward log lines into the live block.
237            let _ = LOG_TX.set(tx);
238            spawn(move || rich::run(rx, theme, header, spec))
239        }
240        (RenderMode::Quiet, _) => spawn(move || plain::run(rx, true, header, spec)),
241        (_, _) => spawn(move || plain::run(rx, false, header, spec)),
242    };
243    (sink, RenderHandle { join })
244}
245
246/// Spawn the renderer thread.
247fn spawn(body: impl FnOnce() + Send + 'static) -> Option<JoinHandle<()>> {
248    std::thread::Builder::new()
249        .name(THREAD_NAME.to_string())
250        .spawn(body)
251        .ok()
252}
253
254/// Restore the cursor on panic. Release builds abort on panic, so the hook is
255/// the only chance to undo `cursor::Hide`. Installed at most once.
256fn install_panic_hook() {
257    static ONCE: OnceLock<()> = OnceLock::new();
258    if ONCE.set(()).is_err() {
259        return;
260    }
261    let prev = std::panic::take_hook();
262    std::panic::set_hook(Box::new(move |info| {
263        let mut err = std::io::stderr();
264        let _ = ratatui::crossterm::execute!(err, ratatui::crossterm::cursor::Show);
265        let _ = writeln!(err);
266        prev(info);
267    }));
268}
269
270/// A tracing layer that forwards each log line to the renderer (when a
271/// log-forwarding renderer is attached). Add it alongside the tool's durable
272/// log layer so that log keeps the full record regardless.
273pub struct ChannelLayer;
274
275#[derive(Default)]
276struct MsgVisitor {
277    message: Option<String>,
278}
279
280impl Visit for MsgVisitor {
281    fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
282        if field.name() == "message" {
283            self.message = Some(format!("{value:?}"));
284        }
285    }
286}
287
288impl<S: Subscriber> Layer<S> for ChannelLayer {
289    fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
290        let Some(tx) = LOG_TX.get() else {
291            return;
292        };
293        let mut v = MsgVisitor::default();
294        event.record(&mut v);
295        if let Some(msg) = v.message {
296            let _ = tx.send(ProgressEvent::Log {
297                level: *event.metadata().level(),
298                line: msg,
299            });
300        }
301    }
302}
303
304/// A small flow shared by the renderer tests: a three-member group, a
305/// one-member group, a two-member group.
306#[cfg(test)]
307pub(crate) const TEST_SPEC: ProgressSpec = ProgressSpec {
308    groups: &[
309        ("Configuring", &["identity", "mac_pin", "regulatory"]),
310        ("Installing dependencies", &["deps"]),
311        ("Registering services", &["watchdog", "units"]),
312    ],
313    footer: "Safe to leave running.",
314    rich_title: "Example · installing",
315    skipped: "cached",
316    plain_skipped: "already done",
317    interrupted: "Example interrupted.",
318};
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323
324    #[test]
325    fn json_and_quiet_flags_win() {
326        let mut f = ModeFlags {
327            json: true,
328            ..ModeFlags::default()
329        };
330        assert_eq!(detect_mode(f), RenderMode::Json);
331        f.json = false;
332        f.quiet = true;
333        assert_eq!(detect_mode(f), RenderMode::Quiet);
334    }
335
336    #[test]
337    fn plain_flag_forces_plain() {
338        let f = ModeFlags {
339            plain: true,
340            ..ModeFlags::default()
341        };
342        assert_eq!(detect_mode(f), RenderMode::Plain);
343    }
344
345    #[test]
346    fn rich_without_a_terminal_stays_rich() {
347        fn none() -> std::io::Result<Option<Tty>> {
348            Ok(None)
349        }
350        let (mode, tty) = resolve_live_mode(RenderMode::Rich, None, none);
351        assert_eq!(mode, RenderMode::Rich);
352        assert!(tty.is_none());
353        let (mode, _) = resolve_live_mode(RenderMode::Plain, None, none);
354        assert_eq!(mode, RenderMode::Plain);
355    }
356
357    #[test]
358    fn noop_sink_does_not_panic() {
359        let sink = ProgressSink::default();
360        sink.step_started("deps");
361        sink.step_result("deps", &StepOutcome::Ok);
362        sink.finish();
363    }
364}