From e9b210e20ada6bc3859ae891c452e73acb05ce36 Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Tue, 17 Nov 2026 13:57:29 +0100 Subject: [PATCH] ui: park the live widget while a prompt owns the terminal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The widget's steady-tick redraws fight the prompt for the cursor, so a raw-mode question never stayed on screen: pkh put showed the warning, then appeared to hang, with the upload running blind behind the spinner. Every prompt now releases the widget first (its full teardown, through a hook the view registers; prompts stay view-agnostic). The release is one-way — after a prompt the view narrates in plain lines instead of through the gone spinner — and hooks are generation-tokened so a view's drop never clears the registration of a view created after it (pkh new runs two builds in a row). --- src/ui/deb.rs | 71 +++++++++++++++++++++++---------- src/ui/prompt.rs | 101 +++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 149 insertions(+), 23 deletions(-) diff --git a/src/ui/deb.rs b/src/ui/deb.rs index 6a7a6c9..85a0599 100644 --- a/src/ui/deb.rs +++ b/src/ui/deb.rs @@ -76,6 +76,9 @@ struct Shared { /// Subprocess output reaches it through [`crate::report::BuildView::sink`]. pub struct DebUi { shared: Arc, + /// This view's hook slot in [`crate::ui::prompt`], cleared on drop. + /// `None` when the widget is disabled: nothing to park then. + park_generation: Option, } impl DebUi { @@ -111,26 +114,40 @@ impl DebUi { let timestamp = chrono::Utc::now().format("%Y%m%dT%H%M%S").to_string(); let log_path = default_log_path(×tamp); - let ui = Self { - shared: Arc::new(Shared { - multi: multi.clone(), - top, - pane, - state: Mutex::new(Pipeline { - classifier: Box::new(GenericClassifier::new()), - lines: VecDeque::new(), - errors: Vec::new(), - last_draw: Instant::now(), - bar_total: 0, - bar_bytes: false, - }), - tee: Mutex::new(None), - log_path: Mutex::new(log_path), - timestamp, - enabled, - suspended: AtomicBool::new(false), - started: Instant::now(), + // Prompts release this widget from the terminal (a steady-tick + // redraw would clobber a raw-mode question), and after the release + // the view narrates in plain lines. Registered only for enabled + // views: headless runs have no widget to park. + let shared = Arc::new(Shared { + multi: multi.clone(), + top, + pane, + state: Mutex::new(Pipeline { + classifier: Box::new(GenericClassifier::new()), + lines: VecDeque::new(), + errors: Vec::new(), + last_draw: Instant::now(), + bar_total: 0, + bar_bytes: false, }), + tee: Mutex::new(None), + log_path: Mutex::new(log_path), + timestamp, + enabled, + suspended: AtomicBool::new(false), + started: Instant::now(), + }); + let park_generation = if enabled { + Some(crate::ui::prompt::set_park_hook(Arc::new({ + let shared = shared.clone(); + move || suspend_shared(&shared) + }))) + } else { + None + }; + let ui = Self { + shared, + park_generation, }; // Ctrl+C: the signal wiring lives in the CLI; this view only @@ -275,6 +292,10 @@ impl crate::report::BuildView for DebUi { fn target(&self, target: BuildTarget<'_>) { if self.active() { self.shared.top.set_prefix(target.display.clone()); + } else if self.shared.enabled { + // Released from the terminal (parked for a prompt, or torn + // down): narrate plainly + eprintln!("{}", target.display); } if target.tee_log { let kind = match target.kind { @@ -296,7 +317,14 @@ impl crate::report::BuildView for DebUi { } fn message(&self, text: &str) { - if self.active() { + if !self.shared.enabled { + return; + } + if self.shared.suspended.load(Ordering::SeqCst) { + // Released from the terminal (parked for a prompt, or torn + // down): narrate plainly, the spinner no longer redraws + eprintln!("{text}"); + } else { self.shared.top.set_message(text.to_string()); } } @@ -352,6 +380,9 @@ impl crate::report::BuildView for DebUi { impl Drop for DebUi { fn drop(&mut self) { + if let Some(generation) = self.park_generation { + crate::ui::prompt::clear_park_hook(generation); + } // Safety net: clear the widget on early returns/unwinds self.suspend(); } diff --git a/src/ui/prompt.rs b/src/ui/prompt.rs index 9d15e5e..2209a22 100644 --- a/src/ui/prompt.rs +++ b/src/ui/prompt.rs @@ -2,8 +2,10 @@ //! input with an optional validator, one-line option selection and yes/no //! confirmation. //! -//! Every public prompt enables raw mode itself and always restores it. When -//! no interactive terminal is attached, [`select`] fails with +//! Every public prompt enables raw mode itself and always restores it, and +//! first releases the live build widget from the terminal (see [`PARK`]): +//! a steady-tick redraw would clobber the raw-mode question. When no +//! interactive terminal is attached, [`select`] fails with //! [`PromptError::NotATty`] so callers decide on a fallback, while [`text`] //! and [`confirm`] answer with their default. @@ -13,6 +15,8 @@ use crossterm::{ terminal, }; use std::io::{self, IsTerminal, Write}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Duration; /// Why a prompt could not run interactively @@ -162,7 +166,9 @@ impl crate::report::Prompter for TerminalPrompter { fn accept_host_key(&self, host: &str, key_type: &str, fingerprint: &str) -> bool { // The banner is plain output: the confirmation prompt itself must - // stay a single line for its redraw logic + // stay a single line for its redraw logic. Released from the live + // widget first, so banner and question both stay on screen + park_widget(); println!("The authenticity of host '{host}' can't be established."); println!("{key_type} key fingerprint is {fingerprint}."); confirm("Accept and store this host key?", false).unwrap_or(false) @@ -173,12 +179,59 @@ impl crate::report::Prompter for TerminalPrompter { } } +/// The live widget's parking hook: any prompt releases the widget from the +/// terminal before drawing its raw-mode line. Without this, the widget's +/// steady-tick redraws fight the prompt for the cursor — the question +/// never stays on screen, and the flow reads as a hang. Parking is the +/// widget's full teardown, so after the first prompt the view stays +/// released and its later messages print as plain lines (see +/// [`super::deb`]). +/// A registered hook: its generation token plus the teardown closure. +type ParkHook = (u64, Arc); + +static PARK: Mutex> = Mutex::new(None); + +/// Monotonic hook identity, so a view's drop never clears the +/// registration of a view created after it (`pkh new` runs two builds in +/// a row, each with its own view) +static PARK_GENERATION: AtomicU64 = AtomicU64::new(0); + +/// Register the widget-parking hook, returning the generation token for +/// [`clear_park_hook`]. +pub fn set_park_hook(hook: Arc) -> u64 { + let generation = PARK_GENERATION.fetch_add(1, Ordering::SeqCst); + *PARK.lock().unwrap() = Some((generation, hook)); + generation +} + +/// Clear the hook if `generation` is still the registered one. +pub fn clear_park_hook(generation: u64) { + let mut park = PARK.lock().unwrap(); + if park + .as_ref() + .is_some_and(|(registered, _)| *registered == generation) + { + *park = None; + } +} + +/// Release the live widget from the terminal, if one is registered. +/// Idempotent: the hook is the widget's teardown. +fn park_widget() { + if let Some((_, hook)) = PARK.lock().unwrap().as_ref() { + hook(); + } +} + /// Run `prompt` with the terminal in raw mode, always restoring it /// afterwards. Fails with [`PromptError::NotATty`] when raw mode cannot be /// enabled. fn with_raw_mode( prompt: impl FnOnce() -> Result>, ) -> Result> { + // The question must own the terminal: release the live widget first + park_widget(); + // Try to enter raw mode — if not possible (e.g. piped input), the caller // falls back to a non-interactive answer if terminal::enable_raw_mode().is_err() { @@ -492,6 +545,48 @@ fn confirm_inner( #[cfg(test)] mod tests { + /// A parked hook runs, and a stale generation never clears a newer + /// registration: `pkh new` runs two builds in a row, each registering + /// its own view. + #[test] + fn park_hook_registration_and_stale_clear() { + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let first = { + let calls = calls.clone(); + set_park_hook(Arc::new(move || { + calls.fetch_add(1, Ordering::SeqCst); + })) + }; + + park_widget(); + assert_eq!(calls.load(Ordering::SeqCst), 1, "the hook parked once"); + + // A second view registers; the first view's drop clears by its + // stale token and must not remove the newer hook + let second_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let second = { + let second_calls = second_calls.clone(); + set_park_hook(Arc::new(move || { + second_calls.fetch_add(1, Ordering::SeqCst); + })) + }; + clear_park_hook(first); + park_widget(); + assert_eq!( + calls.load(Ordering::SeqCst), + 1, + "the stale clear left the newer hook" + ); + assert_eq!(second_calls.load(Ordering::SeqCst), 1); + + clear_park_hook(second); + park_widget(); + assert_eq!( + second_calls.load(Ordering::SeqCst), + 1, + "the current clear removed the hook" + ); + } use super::*; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};