From f6fe0ec825b479033071c3df123b3193628cee31 Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Thu, 3 Sep 2026 11:41:29 +0000 Subject: [PATCH 01/13] fix(dash): restore terminal on SIGTERM/SIGINT across the launcher hub (EAI-7194) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A signal delivered to `rocm dash` (or bare `rocm`) tore the process down while it still held the terminal in raw mode on the alternate screen, leaving the shell needing `reset`. `app::run` now installs a termination-signal watcher before entering raw mode that restores the terminal and exits `128 + signo` (SIGINT -> 130, SIGTERM -> 143) on Unix (Ctrl-C/Ctrl-Break on Windows). Bare `rocm` is a persistent hub: it outlives each session's Tokio runtime and returns to a synchronous, raw-mode launcher menu between flows. Tokio never unregisters the libc handler it installs, so once a session's runtime is dropped nothing drains the signal pipe and a per-session watcher goes deaf — leaving the menu holding the terminal in raw mode while SIGTERM/SIGINT are caught-and-discarded (an unkillable, worse form of the bug). `run_launcher` now keeps ONE runtime alive for the whole hub and spawns a single process-lifetime watcher on it, so every window — menu and session alike — stays killable. The teardown is factored into `restore_terminal`, split so the escape-sequence half (`write_restore_sequences`) takes an `impl Write` and a unit test asserts the emitted bytes against an in-memory sink instead of mutating the process's shared terminal state (which raced other tests in the single-process `cargo test` lane). `spawn_termination_watcher` documents the deliberate `process::exit` semantics: on a signal we stop promptly rather than racing an orderly teardown, so an in-flight focused-install child is left to the OS (matching the default disposition) and the embedded daemon's socket self-heals on the next bind. Tests: a Linux PTY scenario drives a full launcher round-trip (open the dashboard, quit back to the menu, then SIGTERM) and asserts 143 plus terminal restoration — red without the hub watcher, green with it. The dashboard SIGTERM/SIGINT scenarios (11/12) are unchanged. The ineffective startup-race scenario is dropped: a 20 ms-polled PTY cannot observe the microsecond register-before-raw-mode window, which is instead covered by construction (`spawn_termination_watcher` runs before `enable_raw_mode`). Signed-off-by: Roman Sirokov --- apps/rocm/src/dash.rs | 26 +++ crates/rocm-dash-tui/src/app/mod.rs | 205 ++++++++++++++++++++- tests/e2e-cucumber/features/dash.feature | 45 +++++ tests/e2e-cucumber/tests/e2e/dash_steps.rs | 81 +++++++- tests/e2e-cucumber/tests/e2e/tui_driver.rs | 154 ++++++++++++++++ 5 files changed, 499 insertions(+), 12 deletions(-) diff --git a/apps/rocm/src/dash.rs b/apps/rocm/src/dash.rs index 4f404b61dd..f4a403fe51 100644 --- a/apps/rocm/src/dash.rs +++ b/apps/rocm/src/dash.rs @@ -360,6 +360,32 @@ pub fn run_launcher(chat_mock: bool) -> Result<()> { let paths = AppPaths::discover()?; let config = RocmCliConfig::load(&paths).unwrap_or_default(); let theme = config.dashboard.tui.theme; + + // Bare `rocm` is a persistent hub: it outlives each session's Tokio runtime + // and returns to a synchronous, raw-mode launcher menu between flows. Each + // session builds and drops its own runtime, and Tokio never unregisters the + // libc signal handler it installs — so once a session's runtime is dropped + // nothing drains the signal pipe and a per-session watcher goes deaf. The + // menu would then hold the terminal in raw mode while SIGTERM/SIGINT are + // caught-and-discarded: an unkillable, worse form of the very bug this + // fixes. Keep ONE runtime alive for the whole hub and spawn a single + // process-lifetime watcher on it, so every window — the menu and each + // session alike — has a live reactor to restore the terminal and exit + // `128 + signo`. The watcher is registered before the first menu paint, so + // even the very first launcher screen is covered. + let signal_rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .enable_all() + .build() + .context("building the launcher signal runtime")?; + // Register + spawn inside the runtime context; the returned watcher handle is + // dropped on purpose (dropping a `JoinHandle` detaches the task, it does not + // abort it), so the hub keeps `signal_rt`'s worker draining the signal pipe + // for the whole loop below and the watcher lives for the process. + let _watcher = signal_rt + .block_on(async { rocm_dash_tui::app::spawn_termination_watcher() }) + .map_err(|e| anyhow::anyhow!("installing launcher termination-signal handlers: {e}"))?; + loop { // Re-read the managed-service registry on each pass so the front door // reflects models started (or stopped) during a prior flow. This is a diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index f046c0b80a..699bde6679 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -1608,6 +1608,16 @@ fn open_overlay_for_focus( } pub async fn run(args: ResolvedArgs) -> color_eyre::Result<()> { + // Install the termination-signal watcher BEFORE switching the terminal into + // raw/alternate-screen mode. A signal that arrives during startup must find + // the listeners already registered; otherwise it takes the default + // disposition and kills the process while the terminal is still in raw mode + // — the exact broken-terminal state this guards against. Registration + // failure is propagated here (via `?`), before any terminal state is + // mutated, so we never enter raw mode without a working restore path. See + // `spawn_termination_watcher` for the exit-code and no-unwind semantics. + let signal_task = spawn_termination_watcher()?; + enable_raw_mode()?; let mut stdout = io::stdout(); execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?; @@ -1616,20 +1626,159 @@ pub async fn run(args: ResolvedArgs) -> color_eyre::Result<()> { let res = event_loop(&mut terminal, &args).await; - // Best-effort terminal restoration: never let teardown failures override the - // session result. If the controlling terminal already went away (e.g. the - // PTY closed on quit), these writes can fail with a broken pipe — that must - // not turn a clean exit into a non-zero one. + // The session ended on its own — the signal watcher is no longer needed and + // must not linger to fire (and re-restore/exit) after a clean return. + signal_task.abort(); + + // Best-effort terminal restoration, reusing the exact teardown the signal + // path runs so the two cannot drift. Never let teardown failures override + // the session result: if the controlling terminal already went away (e.g. + // the PTY closed on quit), these writes can fail with a broken pipe — that + // must not turn a clean exit into a non-zero one (every step inside is + // best-effort). + restore_terminal(); + res +} + +/// Best-effort teardown of the terminal modes `run` set up. Disables raw mode +/// (process-global terminal state, so this can safely run from the signal +/// watcher even though the [`Terminal`] backend owns its own `stdout` clone), +/// then writes the alt-screen/mouse/cursor restore sequences to a fresh +/// `stdout`. Every step is best-effort: on a signal we are about to exit anyway, +/// and a vanished controlling terminal must not turn teardown into a panic. +fn restore_terminal() { + // `disable_raw_mode` mutates the real terminal (there is no in-memory + // equivalent), so it stays outside the testable sequence writer below. let _ = disable_raw_mode(); - let _ = execute!( - terminal.backend_mut(), + let _ = write_restore_sequences(&mut io::stdout()); +} + +/// Write the escape sequences that undo `run`'s terminal setup — leave the +/// alternate screen, disable mouse capture, show the cursor — to `out`. Split +/// from [`restore_terminal`] so a unit test can drive an in-memory sink and +/// assert the emitted bytes, rather than writing to the process's shared stdout +/// (which races every other test in the single-process `cargo test` lane). +fn write_restore_sequences(out: &mut W) -> io::Result<()> { + execute!( + out, LeaveAlternateScreen, - DisableMouseCapture - ); - let _ = terminal.show_cursor(); - res + DisableMouseCapture, + crossterm::cursor::Show + ) } +/// Register the termination-signal listeners on the current Tokio runtime and +/// spawn a detached watcher that restores the terminal and exits `128 + signo`. +/// +/// Returns the task handle so a caller whose process ends with the session +/// (`rocm dash`) can `abort()` it on a clean return; the persistent launcher hub +/// instead keeps its runtime alive and drops the handle, letting the watcher +/// live for the whole process so bare `rocm` stays killable across the sessions +/// it builds and drops (Tokio never unregisters its libc handler, so a +/// per-session watcher would go deaf the moment its runtime is dropped — see +/// `dash::run_launcher`). +/// +/// Registration happens here, synchronously, and is surfaced via `?`; callers +/// invoke this BEFORE entering raw/alternate-screen mode so a failure never +/// leaves the terminal switched with no restore path, and a signal arriving +/// during startup is latched by the already-installed OS handlers. +/// +/// The watcher ends the process with [`std::process::exit`], which does not +/// unwind — this is deliberate. SIGTERM/SIGINT means "stop now", so we restore +/// the terminal and leave promptly rather than racing an orderly teardown +/// against an imminent default-disposition kill. Two consequences are accepted +/// as the intended behavior: (1) an in-flight focused install/serve child is +/// left to the OS rather than reaped via `kill_on_drop`, matching the +/// pre-existing default disposition and avoiding truncating a mid-write child on +/// the way out; and (2) `run_async`'s embedded-daemon socket is not unlinked +/// here, but the daemon unlinks a stale socket on its next bind, so it self-heals. +pub fn spawn_termination_watcher() -> color_eyre::Result> { + let termination = TerminationSignals::register()?; + Ok(tokio::spawn(async move { + let code = termination.recv().await; + restore_terminal(); + std::process::exit(code); + })) +} + +/// Termination-signal listeners, registered up front so a signal that arrives +/// during terminal setup is latched by the OS/Tokio rather than taking the +/// default disposition. +/// +/// [`TerminationSignals::register`] installs the OS handlers and is called +/// BEFORE the terminal is switched into raw/alternate-screen mode, so a +/// registration failure is surfaced (via `?`) before any terminal state is +/// mutated. [`TerminationSignals::recv`] then parks the watcher task until a +/// signal fires, returning the conventional `128 + signo` exit code the process +/// should report (SIGINT → 130, SIGTERM → 143). +#[cfg(unix)] +struct TerminationSignals { + sigterm: tokio::signal::unix::Signal, + sigint: tokio::signal::unix::Signal, +} + +#[cfg(unix)] +impl TerminationSignals { + fn register() -> color_eyre::Result { + use tokio::signal::unix::{SignalKind, signal}; + + // Register both handlers before entering raw mode. `?` on each + // propagates a setup failure instead of parking forever; and if the + // second registration fails, the first is dropped (unregistered) as we + // return the error, so we never leave one signal silently swallowed. + Ok(Self { + sigterm: signal(SignalKind::terminate())?, + sigint: signal(SignalKind::interrupt())?, + }) + } + + async fn recv(mut self) -> i32 { + tokio::select! { + _ = self.sigterm.recv() => EXIT_CODE_SIGTERM, + _ = self.sigint.recv() => EXIT_CODE_SIGINT, + } + } +} + +/// Windows analog: Ctrl-C and Ctrl-Break arrive as console control events (not +/// key events) and would otherwise skip terminal restoration the same way. +/// Tokio exposes the two as separate streams, so BOTH are registered — +/// `ctrl_c()` subscribes only to `CTRL_C_EVENT` and would miss a Ctrl-Break. +/// Ctrl-Break is the harder "terminate" gesture and maps to the SIGTERM code; +/// Ctrl-C maps to the SIGINT code. +#[cfg(windows)] +struct TerminationSignals { + ctrl_c: tokio::signal::windows::CtrlC, + ctrl_break: tokio::signal::windows::CtrlBreak, +} + +#[cfg(windows)] +impl TerminationSignals { + fn register() -> color_eyre::Result { + use tokio::signal::windows::{ctrl_break, ctrl_c}; + + // `?` propagates a registration failure before raw mode is entered, + // rather than the old `let _ = ctrl_c().await` which treated a failed + // registration as a received Ctrl-C and exited immediately. + Ok(Self { + ctrl_c: ctrl_c()?, + ctrl_break: ctrl_break()?, + }) + } + + async fn recv(mut self) -> i32 { + tokio::select! { + _ = self.ctrl_c.recv() => EXIT_CODE_SIGINT, + _ = self.ctrl_break.recv() => EXIT_CODE_SIGTERM, + } + } +} + +/// Conventional shell exit code for a process terminated by SIGINT (128 + 2). +const EXIT_CODE_SIGINT: i32 = 130; +/// Conventional shell exit code for a process terminated by SIGTERM (128 + 15). +const EXIT_CODE_SIGTERM: i32 = 143; + async fn event_loop(terminal: &mut Tui, args: &ResolvedArgs) -> color_eyre::Result<()> { let (tx, mut rx) = mpsc::unbounded_channel::(); // Job-bridge channel (Phase 3 Wave 1): the async runtime streams @@ -3514,6 +3663,42 @@ mod tests { assert_eq!(hk(KeyCode::Esc, ActiveTab::Observe), KeyAction::OpenMenu); } + #[test] + fn signal_exit_codes_follow_shell_convention() { + // The signal-handler task exits with the conventional 128 + signo code so + // a supervisor sees the right termination reason. SIGINT is signal 2, + // SIGTERM is signal 15. + assert_eq!(EXIT_CODE_SIGINT, 128 + 2); + assert_eq!(EXIT_CODE_SIGTERM, 128 + 15); + } + + // Unix-only: crossterm emits ANSI escape sequences to a generic writer on + // Unix, so an in-memory sink captures the real bytes. On Windows crossterm + // drives the console via the WinAPI backend instead of writing ANSI, and + // `execute!` to a `Vec` errors with "Initial console modes not set" — there + // is no console to configure. Production `restore_terminal()` passes a real + // stdout handle, so the Windows path is exercised there, not by this sink. + #[cfg(unix)] + #[test] + fn write_restore_sequences_leaves_alt_screen_and_shows_cursor() { + // The restore path must leave the alternate screen and show the cursor. + // Driving an in-memory sink asserts the actual emitted bytes without + // touching the process's shared terminal state — the global + // `disable_raw_mode()` half is deliberately outside this function, so + // nothing here races other tests in the single-process `cargo test` lane. + let mut sink: Vec = Vec::new(); + write_restore_sequences(&mut sink).expect("writing to a Vec cannot fail"); + let emitted = String::from_utf8(sink).expect("restore sequences are ASCII escapes"); + assert!( + emitted.contains("\x1b[?1049l"), + "expected the leave-alt-screen sequence in {emitted:?}" + ); + assert!( + emitted.contains("\x1b[?25h"), + "expected the show-cursor sequence in {emitted:?}" + ); + } + #[test] fn tab_cycles_forward_and_wraps() { // 5-tab IA: Home → ROCm → Serving → Observe → Chat → Home. diff --git a/tests/e2e-cucumber/features/dash.feature b/tests/e2e-cucumber/features/dash.feature index 16ad1b2677..63caf8d142 100644 --- a/tests/e2e-cucumber/features/dash.feature +++ b/tests/e2e-cucumber/features/dash.feature @@ -123,3 +123,48 @@ Feature: Interactive dashboard Then the launcher shows the model serving When the user quits the launcher Then the launcher exits successfully + + @id:dash-sigterm-restores-terminal @requires-os:linux + Scenario: dash-11 - A SIGTERM restores the terminal and exits 143 + # Core regression for this PR: a SIGTERM to a running dashboard (e.g. a + # supervisor stopping it) must run the restore path — leave the alternate + # screen and show the cursor — and report the conventional 128+15 exit code, + # rather than dying on the default disposition and leaving a broken terminal. + When the user opens the dashboard with demo data + Then the dashboard home view is displayed + When the dashboard receives a SIGTERM + Then the dashboard exits from the signal with code 143 + And the terminal is restored to the normal screen + + @id:dash-sigint-restores-terminal @requires-os:linux + Scenario: dash-12 - A SIGINT restores the terminal and exits 130 + # The interactive Ctrl-C gesture (delivered as SIGINT) takes the same restore + # path and reports the conventional 128+2 exit code. + When the user opens the dashboard with demo data + Then the dashboard home view is displayed + When the dashboard receives a SIGINT + Then the dashboard exits from the signal with code 130 + And the terminal is restored to the normal screen + + @id:dash-launcher-sigterm-restores-terminal-across-a-session @requires-os:linux + Scenario: dash-13 - A SIGTERM to the launcher hub restores the terminal after a session + # rominf regression: bare `rocm` is a persistent hub whose process outlives + # each session's Tokio runtime. Tokio never unregisters the libc signal + # handler it installs, so a per-session watcher goes deaf the moment its + # runtime is dropped — leaving the synchronous launcher menu (itself in raw + # mode) unable to restore the terminal on a SIGTERM delivered after the + # user's first flow: an unkillable, worse form of the bug this PR fixes. A + # single process-lifetime watcher, installed once for the whole hub, must + # keep every window killable. This drives a full session round-trip — open + # the dashboard, quit back to the menu — before signalling, so it exercises + # the across-session path a single-session scenario cannot. (The startup + # ordering — listeners registered before raw mode — is covered by + # construction: `spawn_termination_watcher` is called before + # `enable_raw_mode`; a 20 ms-polled PTY scenario cannot observe that + # microsecond window, so none is claimed for it.) + When the user opens the launcher + And the user opens the dashboard from the launcher + And the user quits back to the launcher + And the launcher receives a SIGTERM + Then the dashboard exits from the signal with code 143 + And the terminal is restored to the normal screen diff --git a/tests/e2e-cucumber/tests/e2e/dash_steps.rs b/tests/e2e-cucumber/tests/e2e/dash_steps.rs index 49518724af..09e6749ba8 100644 --- a/tests/e2e-cucumber/tests/e2e/dash_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/dash_steps.rs @@ -12,8 +12,7 @@ use e2e_cucumber::mock_server::{MetricsMode, MockServer, ServiceRecordOptions}; use std::time::{Duration, Instant}; use crate::E2eWorld; -use crate::e2e::tui_driver::{TuiSession, default_timeout}; - +use crate::e2e::tui_driver::{TermSignal, TuiSession, default_timeout}; /// The exact prompt `send_managed_model_message` types, and the string the /// corresponding `Then` step (`managed_chat_request_carried_prompt`) asserts /// the mock actually received — so the two can never silently drift apart. @@ -240,6 +239,63 @@ async fn quit_launcher(world: &mut E2eWorld) { quit_tui(world, "the launcher").await; } +/// Deliver a termination signal to the running dashboard and wait for it to +/// exit, stashing the observed exit code for the `Then` steps. Shared by the +/// SIGTERM/SIGINT `When` steps so the two cannot drift. +async fn signal_dashboard(world: &mut E2eWorld, signal: TermSignal) { + session(world) + .deliver_signal_and_wait(signal, default_timeout()) + .await + .unwrap_or_else(|e| panic!("the dashboard did not exit after {signal:?}: {e}")); +} + +#[when("the user opens the dashboard from the launcher")] +async fn open_dashboard_from_launcher(world: &mut E2eWorld) { + let tui = session(world); + // Sync on the launcher front door before sending a key, so `d` is not + // swallowed before the launcher's synchronous event loop is reading input. + tui.wait_for_screen("Set up this system", default_timeout()) + .await + .unwrap_or_else(|e| panic!("the launcher front door never appeared: {e}")); + // `d` escalates straight into the full dashboard (LauncherChoice::OpenDashboard), + // which builds and then, on quit, drops its own Tokio runtime. + tui.send("d") + .unwrap_or_else(|e| panic!("failed to open the dashboard from the launcher: {e}")); + tui.wait_for_screen("Updates", default_timeout()) + .await + .unwrap_or_else(|e| panic!("the dashboard did not open from the launcher: {e}")); +} + +#[when("the user quits back to the launcher")] +async fn quit_back_to_launcher(world: &mut E2eWorld) { + let tui = session(world); + // `q` quits the dashboard; the hub loop drops the session runtime and + // redraws the launcher front door — the exact "back at the menu after a + // session" state where a per-session signal watcher would have gone deaf. + tui.send("q") + .unwrap_or_else(|e| panic!("failed to quit the dashboard: {e}")); + tui.wait_for_screen("Set up this system", default_timeout()) + .await + .unwrap_or_else(|e| { + panic!("the launcher front door did not return after the session: {e}") + }); +} + +#[when("the launcher receives a SIGTERM")] +async fn launcher_receives_sigterm(world: &mut E2eWorld) { + signal_dashboard(world, TermSignal::Term).await; +} + +#[when("the dashboard receives a SIGTERM")] +async fn dashboard_receives_sigterm(world: &mut E2eWorld) { + signal_dashboard(world, TermSignal::Term).await; +} + +#[when("the dashboard receives a SIGINT")] +async fn dashboard_receives_sigint(world: &mut E2eWorld) { + signal_dashboard(world, TermSignal::Int).await; +} + // ── Then ─────────────────────────────────────────────────────────── #[then("the dashboard home view is displayed")] @@ -422,6 +478,27 @@ async fn dashboard_exited(world: &mut E2eWorld) { assert_tui_opened(world); } +#[then(expr = "the dashboard exits from the signal with code {int}")] +async fn dashboard_exited_from_signal(world: &mut E2eWorld, expected: i32) { + let observed = session(world) + .observed_exit_code() + .expect("no signal exit code was recorded; deliver the signal first"); + assert_eq!( + observed, expected, + "dashboard exited with {observed} after the signal, expected {expected}" + ); +} + +#[then("the terminal is restored to the normal screen")] +async fn terminal_restored(world: &mut E2eWorld) { + // The dashboard's signal handler must leave the alternate screen and show + // the cursor before exiting; otherwise the shell is left in the broken + // raw/alt-screen state that needs a `reset`. + session(world) + .expect_terminal_restored() + .unwrap_or_else(|e| panic!("{e}")); +} + #[then("the launcher shows the model serving")] async fn launcher_shows_serving(world: &mut E2eWorld) { let model = world diff --git a/tests/e2e-cucumber/tests/e2e/tui_driver.rs b/tests/e2e-cucumber/tests/e2e/tui_driver.rs index 3ec8d0d855..26193aade5 100644 --- a/tests/e2e-cucumber/tests/e2e/tui_driver.rs +++ b/tests/e2e-cucumber/tests/e2e/tui_driver.rs @@ -82,6 +82,28 @@ pub fn default_timeout() -> Duration { ) } +/// A termination signal a scenario can deliver to the live TUI, paired with the +/// conventional `128 + signo` exit code the dashboard's signal handler reports +/// after restoring the terminal (SIGINT → 130, SIGTERM → 143). +#[derive(Debug, Clone, Copy)] +pub enum TermSignal { + /// SIGTERM — a supervisor stopping the dashboard (`kill `). + Term, + /// SIGINT — the interactive Ctrl-C gesture delivered as a signal. + Int, +} + +impl TermSignal { + /// The `kill(1)` name (`TERM`/`INT`), used to deliver the signal to the + /// child by pid. + const fn kill_name(self) -> &'static str { + match self { + Self::Term => "TERM", + Self::Int => "INT", + } + } +} + /// A running `rocm` TUI attached to a pseudo-terminal. pub struct TuiSession { child: Box, @@ -107,6 +129,9 @@ pub struct TuiSession { is_chat: bool, scenario: Option, argv: Vec, + /// Exit code observed by [`deliver_signal_and_wait`], read back by the + /// signal scenarios' `Then` steps once the child has been reaped. + observed_exit_code: Option, } impl std::fmt::Debug for TuiSession { @@ -224,6 +249,7 @@ impl TuiSession { is_chat: args.first() == Some(&"chat"), scenario: world.current_scenario.clone(), argv: args.iter().map(|s| (*s).to_string()).collect(), + observed_exit_code: None, }) } @@ -506,6 +532,134 @@ impl TuiSession { let argv: Vec<&str> = self.argv.iter().map(String::as_str).collect(); crate::record_command(self.scenario.as_deref(), &argv, rc, ""); } + + /// Deliver `signal` to the child, then wait for it to exit and stash the + /// observed exit code for the scenario's `Then` steps. Only harness faults + /// (no pid, a failed `kill`, a reader panic, or a timeout) are surfaced as + /// `Err`; asserting the exit *value* and terminal restoration is left to the + /// scenario's `Then` steps, which read the code back via + /// [`observed_exit_code`](Self::observed_exit_code) and call + /// [`expect_terminal_restored`](Self::expect_terminal_restored). + pub async fn deliver_signal_and_wait( + &mut self, + signal: TermSignal, + timeout: Duration, + ) -> Result<(), String> { + let pid = self + .child + .process_id() + .ok_or_else(|| "the TUI child has no pid; cannot deliver a signal".to_string())?; + // The signal scenarios are `@requires-os:linux`, so shelling out to + // `kill(1)` avoids pulling a `libc`/`nix` dependency into the harness + // just to reach `kill(2)`. + let status = std::process::Command::new("kill") + .arg(format!("-{}", signal.kill_name())) + .arg(pid.to_string()) + .status() + .map_err(|e| format!("failed to run `kill -{} {pid}`: {e}", signal.kill_name()))?; + if !status.success() { + return Err(format!( + "`kill -{} {pid}` exited unsuccessfully ({status})", + signal.kill_name() + )); + } + let code = self.wait_for_exit_code(timeout).await?; + self.observed_exit_code = Some(code); + Ok(()) + } + + /// The exit code recorded by the most recent + /// [`deliver_signal_and_wait`](Self::deliver_signal_and_wait), read back by + /// the scenario's `Then` step to assert the conventional `128 + signo` value. + #[must_use] + pub const fn observed_exit_code(&self) -> Option { + self.observed_exit_code + } + + /// Assert the terminal was restored on exit: the child left the alternate + /// screen and made the cursor visible again. A dashboard that dies on a + /// signal without running its restore path leaves both inverted (still on + /// the alt-screen, cursor hidden) — the broken state that needs a `reset`. + pub fn expect_terminal_restored(&self) -> Result<(), String> { + let on_alt = self.on_alternate_screen(); + let cursor_hidden = self.cursor_hidden(); + if on_alt || cursor_hidden { + return Err(format!( + "terminal was not restored on exit (alternate_screen={on_alt}, cursor_hidden={cursor_hidden}); expected the dashboard to leave the alt-screen and show the cursor.\n{}", + self.framed_screen() + )); + } + Ok(()) + } + + /// Whether the emulated screen is currently on the alternate screen. + fn on_alternate_screen(&self) -> bool { + self.parser + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .screen() + .alternate_screen() + } + + /// Whether the emulated cursor is currently hidden. + fn cursor_hidden(&self) -> bool { + self.parser + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .screen() + .hide_cursor() + } + + /// Poll until the child exits and return its exit code, giving the reader a + /// bounded window to consume the final frame — the terminal-restore + /// sequences the signal handler emits arrive immediately before the process + /// exits, so the parser must see them before restoration is asserted. + async fn wait_for_exit_code(&mut self, timeout: Duration) -> Result { + let deadline = Instant::now() + timeout; + loop { + match self.child.try_wait() { + Ok(Some(status)) => { + self.finished = true; + let code = i32::try_from(status.exit_code()).unwrap_or(-1); + self.record_once(code); + self.drain_final_frame().await; + return Ok(code); + } + Ok(None) => {} + Err(e) => return Err(format!("failed to poll TUI child: {e}")), + } + if let Some(panic_message) = self.take_reader_panic() { + return Err(format!( + "pty reader thread panicked while waiting for exit: {panic_message}\n{}", + self.framed_screen() + )); + } + if Instant::now() >= deadline { + return Err(format!( + "timed out after {timeout:?} waiting for the TUI to exit.\n{}", + self.framed_screen() + )); + } + tokio::time::sleep(POLL_INTERVAL).await; + } + } + + /// Let the reader thread consume any bytes still buffered after the child + /// exits (its final restore sequences) for a short bounded window, so the + /// emulated screen reflects the terminal's final state before it is read. + async fn drain_final_frame(&mut self) { + let drain_deadline = Instant::now() + DRAIN_TIMEOUT; + while Instant::now() < drain_deadline { + if self + .reader + .as_ref() + .is_some_and(std::thread::JoinHandle::is_finished) + { + break; + } + tokio::time::sleep(POLL_INTERVAL).await; + } + } } impl Drop for TuiSession { From f971ab63f4f763e2083ecf6eb2903bcf2118ae9f Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Thu, 10 Sep 2026 11:08:39 +0300 Subject: [PATCH 02/13] fix(dash): arbitrate concurrent termination watchers and test the wiring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two watchers can be live at once: bare `rocm` escalates from the launcher hub into a dashboard session, so the hub's process-lifetime watcher and `app::run`'s session watcher coexist. Tokio's signal registry is process-global, so a single `kill` wakes both — two threads then raced unsynchronised `write_restore_sequences` writes to stdout and both called `std::process::exit`. Add a process-global `SHUTTING_DOWN: AtomicBool` claimed inside the watcher body: only the first watcher through restores the terminal and exits, the rest stand down. The latch is process-global rather than a flag threaded through `ResolvedArgs` so it is path-independent — every call site inherits it without knowing whether an outer watcher exists. Replace the two non-discriminating unit tests with tests that exercise the real wiring in-process: - `termination_watcher_parks_until_aborted` — `spawn_termination_watcher` registers, the task stays parked while no signal has arrived, and `abort()` cancels it. - `termination_signals_yield_shell_exit_codes_and_only_one_watcher_shuts_down` (Unix) — registers two `TerminationSignals`, raises one real signal, and asserts the first maps it to 143/130 while the second stands down. Safe to self-signal because it drives `await_termination` directly, so the body that calls `process::exit` never runs; serialised against the test above because the Windows lane runs `cargo test` (threads in one process), not `cargo nextest`. - `only_the_first_caller_claims_the_shutdown_latch` — including under 16-thread contention. `await_termination` and `claim_shutdown` are split out of the watcher body purely so the above can be asserted without `process::exit`. Also, from review: restructure dash-13 into When/Then pairs and give the launcher hub its own outcome step (the process under test is not a dashboard), repair the corrupted scenario comment, and fold the duplicated PTY drain loop into one `drain_final_frame` helper. EAI-7194 Signed-off-by: Roman Sirokov --- Cargo.lock | 1 + apps/rocm/src/dash.rs | 8 + crates/rocm-dash-tui/Cargo.toml | 6 + crates/rocm-dash-tui/src/app/mod.rs | 194 ++++++++++++++++++++- tests/e2e-cucumber/features/dash.feature | 41 +++-- tests/e2e-cucumber/tests/e2e/dash_steps.rs | 33 +++- tests/e2e-cucumber/tests/e2e/tui_driver.rs | 82 +++++---- 7 files changed, 299 insertions(+), 66 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 473b8eb7bc..592bcd3bae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3676,6 +3676,7 @@ dependencies = [ "crossterm 0.28.1", "futures", "http", + "libc", "ratatui", "reqwest 0.13.4", "rig-core", diff --git a/apps/rocm/src/dash.rs b/apps/rocm/src/dash.rs index f4a403fe51..28cd75e563 100644 --- a/apps/rocm/src/dash.rs +++ b/apps/rocm/src/dash.rs @@ -382,6 +382,14 @@ pub fn run_launcher(chat_mock: bool) -> Result<()> { // dropped on purpose (dropping a `JoinHandle` detaches the task, it does not // abort it), so the hub keeps `signal_rt`'s worker draining the signal pipe // for the whole loop below and the watcher lives for the process. + // + // This watcher deliberately COEXISTS with the one `app::run` installs when a + // flow escalates into a full dashboard session. Tokio's signal registry is + // process-global, so a single `kill` wakes both. That is safe because the + // watcher body arbitrates on a process-global latch: only the first one + // through restores the terminal and exits, so the two never race + // unsynchronised stdout writes or concurrent `process::exit` calls. See + // `spawn_termination_watcher`. let _watcher = signal_rt .block_on(async { rocm_dash_tui::app::spawn_termination_watcher() }) .map_err(|e| anyhow::anyhow!("installing launcher termination-signal handlers: {e}"))?; diff --git a/crates/rocm-dash-tui/Cargo.toml b/crates/rocm-dash-tui/Cargo.toml index 772e8dbb7d..6e12e9af57 100644 --- a/crates/rocm-dash-tui/Cargo.toml +++ b/crates/rocm-dash-tui/Cargo.toml @@ -51,3 +51,9 @@ rig = { package = "rig-core", version = "=0.38.1", default-features = false, fea # same 0.13 line Rig already pulls in (TUI crate only) so the tree keeps one # reqwest version; `json` for response parsing, `rustls-tls` to match Rig's stack. reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"] } + +# Test-only, Unix-only: `raise(3)` lets the termination-watcher unit tests drive +# a real SIGTERM/SIGINT through Tokio's signal registry in-process. Not a runtime +# dependency — the production signal path goes through `tokio::signal`. +[target.'cfg(unix)'.dev-dependencies] +libc.workspace = true diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index 699bde6679..cd104ec989 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -6,6 +6,7 @@ use std::collections::VecDeque; use std::io; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use crossterm::event::{ @@ -1692,15 +1693,64 @@ fn write_restore_sequences(out: &mut W) -> io::Result<()> { /// pre-existing default disposition and avoiding truncating a mid-write child on /// the way out; and (2) `run_async`'s embedded-daemon socket is not unlinked /// here, but the daemon unlinks a stale socket on its next bind, so it self-heals. +/// +/// More than one watcher can be live at once — bare `rocm` escalates from the +/// hub into a dashboard session, so the hub's process-lifetime watcher and +/// `run`'s session watcher coexist — and Tokio's signal registry is +/// process-global: one `kill` notifies *every* subscriber regardless of which +/// runtime registered it. Both watchers therefore wake on the same signal. The +/// [`SHUTTING_DOWN`] latch arbitrates: only the first one through restores the +/// terminal and exits, so two threads never race unsynchronised writes to +/// stdout nor call `std::process::exit` concurrently. See [`await_termination`]. pub fn spawn_termination_watcher() -> color_eyre::Result> { let termination = TerminationSignals::register()?; Ok(tokio::spawn(async move { - let code = termination.recv().await; + let Some(code) = await_termination(termination, &SHUTTING_DOWN).await else { + // A sibling watcher already claimed the shutdown and is about to + // `exit`; this one must do nothing at all. + return; + }; restore_terminal(); std::process::exit(code); })) } +/// Process-global "some watcher has claimed the termination path" latch. +/// +/// Deliberately process-global rather than threaded through `ResolvedArgs`: the +/// hazard is two watchers on two *runtimes*, and a path-independent latch covers +/// every call site (present and future) without each one having to know whether +/// an outer watcher already exists. +static SHUTTING_DOWN: AtomicBool = AtomicBool::new(false); + +/// Claim the single-shot shutdown path on `latch`. Returns `true` exactly once — +/// for whichever caller wins the swap — and `false` for every caller after it. +/// +/// `SeqCst` because correctness here is "exactly one winner across threads", not +/// ordering of surrounding data; the stronger ordering costs nothing on a path +/// that runs at most once per process. +/// +/// Parameterised over the latch (rather than reading [`SHUTTING_DOWN`] directly) +/// so tests can drive a fresh latch and stay order-independent — the process +/// global cannot be reset once a test has set it. +fn claim_shutdown(latch: &AtomicBool) -> bool { + !latch.swap(true, Ordering::SeqCst) +} + +/// Park until a termination signal arrives, then arbitrate on `latch`. +/// +/// Returns `Some(128 + signo)` for the single watcher that wins the latch — that +/// caller must restore the terminal and exit with the code — and `None` for any +/// other watcher woken by the same process-global signal delivery. +/// +/// Split out of [`spawn_termination_watcher`]'s task body so a test can drive the +/// whole register → receive → arbitrate path in-process; the body itself ends in +/// `std::process::exit` and can never be unit-tested. +async fn await_termination(termination: TerminationSignals, latch: &AtomicBool) -> Option { + let code = termination.recv().await; + claim_shutdown(latch).then_some(code) +} + /// Termination-signal listeners, registered up front so a signal that arrives /// during terminal setup is latched by the OS/Tokio rather than taking the /// default disposition. @@ -3663,13 +3713,143 @@ mod tests { assert_eq!(hk(KeyCode::Esc, ActiveTab::Observe), KeyAction::OpenMenu); } + /// Serialises every test that touches the process-global signal machinery. + /// + /// The two lanes differ: Linux CI runs `cargo nextest` (one process per + /// test, so this lock is a no-op), while the required Windows lane runs + /// `cargo test`, which runs the whole binary's tests as THREADS IN ONE + /// PROCESS. There, `termination_watcher_parks_until_aborted` has a live + /// watcher whose body ends in `std::process::exit`; if the self-`kill` test + /// below ran concurrently, that watcher would wake on the other test's + /// signal and take the entire test binary down with exit 143. It would also + /// steal the signal the other test is asserting on. Holding this lock for + /// the whole of each test — including the runtime's `block_on` — makes the + /// two strictly sequential. + /// + /// The tests are written as plain `#[test]` + an explicit runtime (rather + /// than `#[tokio::test]`) precisely so the guard is held across `block_on` + /// without holding a `std` lock across an `.await`. + static SIGNAL_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + /// A current-thread runtime with the signal driver enabled, which + /// `TerminationSignals::register` needs. + fn signal_test_runtime() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("building a current-thread runtime for the signal tests") + } + + #[test] + fn only_the_first_caller_claims_the_shutdown_latch() { + // The guard that stops the hub's process-lifetime watcher and a + // session's watcher from both restoring the terminal and both calling + // `process::exit` on one signal. Driven on a local latch so the test + // never touches (or depends on the state of) the process global. + let latch = AtomicBool::new(false); + assert!(claim_shutdown(&latch), "the first claim must win"); + assert!(!claim_shutdown(&latch), "a second claim must lose"); + assert!(!claim_shutdown(&latch), "and so must every later one"); + + // Under contention there must still be exactly one winner: a + // non-atomic read-then-write would let several threads through. + let contended = AtomicBool::new(false); + let winners = std::sync::atomic::AtomicUsize::new(0); + std::thread::scope(|scope| { + for _ in 0..16 { + scope.spawn(|| { + if claim_shutdown(&contended) { + winners.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!( + winners.load(Ordering::SeqCst), + 1, + "exactly one of 16 racing watchers may claim the shutdown" + ); + } + + #[test] + fn termination_watcher_parks_until_aborted() { + let _guard = SIGNAL_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + signal_test_runtime().block_on(async { + // The real wiring `run` depends on: registration must succeed, and + // the spawned task must stay parked on `recv()` (never resolving on + // its own and exiting the process), until the clean-return path + // aborts it. + let handle = spawn_termination_watcher() + .expect("registering the termination-signal listeners must succeed"); + // Let the task actually start and park; on a current-thread runtime + // a freshly spawned task has not been polled yet, so without this + // `is_finished` would be trivially false. + tokio::task::yield_now().await; + assert!( + !handle.is_finished(), + "the watcher must stay parked while no signal has arrived" + ); + + handle.abort(); + let err = handle + .await + .expect_err("an aborted watcher must not report completion"); + assert!( + err.is_cancelled(), + "the watcher must end by cancellation, not by panicking: {err:?}" + ); + }); + } + + // Unix-only. This test sends real signals to its own process, which is safe + // ONLY because it drives `await_termination` directly: the watcher body that + // calls `std::process::exit` is never run here. `TerminationSignals::register` + // installs the handlers *before* the `kill`, so the signal is caught rather + // than taking its default (fatal) disposition. Both listeners are registered + // before the single `kill` on purpose — that is exactly the hub-watcher + + // session-watcher shape, and Tokio's process-global registry wakes both. + #[cfg(unix)] #[test] - fn signal_exit_codes_follow_shell_convention() { - // The signal-handler task exits with the conventional 128 + signo code so - // a supervisor sees the right termination reason. SIGINT is signal 2, - // SIGTERM is signal 15. - assert_eq!(EXIT_CODE_SIGINT, 128 + 2); - assert_eq!(EXIT_CODE_SIGTERM, 128 + 15); + fn termination_signals_yield_shell_exit_codes_and_only_one_watcher_shuts_down() { + let _guard = SIGNAL_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + signal_test_runtime().block_on(async { + for (signo, expected) in [ + (libc::SIGTERM, EXIT_CODE_SIGTERM), + (libc::SIGINT, EXIT_CODE_SIGINT), + ] { + // A fresh latch per kind keeps the test order-independent. + let latch = AtomicBool::new(false); + let hub_watcher = TerminationSignals::register() + .expect("registering the hub listeners must succeed"); + let session_watcher = TerminationSignals::register() + .expect("registering the session listeners must succeed"); + + // SAFETY: `raise` is an async-signal-safe libc call with no + // arguments to get wrong, and both listeners above are already + // installed, so the signal is delivered to Tokio's handler + // instead of terminating the test binary. + #[allow(unsafe_code)] // libc FFI + let rc = unsafe { libc::raise(signo) }; + assert_eq!(rc, 0, "raise({signo}) failed"); + + assert_eq!( + await_termination(hub_watcher, &latch).await, + Some(expected), + "the first watcher must receive signal {signo} and map it to \ + the conventional 128 + signo exit code" + ); + assert_eq!( + await_termination(session_watcher, &latch).await, + None, + "the second watcher woken by the same signal must stand down \ + rather than race a concurrent restore + exit" + ); + } + }); } // Unix-only: crossterm emits ANSI escape sequences to a generic writer on diff --git a/tests/e2e-cucumber/features/dash.feature b/tests/e2e-cucumber/features/dash.feature index 63caf8d142..21394baa9a 100644 --- a/tests/e2e-cucumber/features/dash.feature +++ b/tests/e2e-cucumber/features/dash.feature @@ -148,23 +148,28 @@ Feature: Interactive dashboard @id:dash-launcher-sigterm-restores-terminal-across-a-session @requires-os:linux Scenario: dash-13 - A SIGTERM to the launcher hub restores the terminal after a session - # rominf regression: bare `rocm` is a persistent hub whose process outlives - # each session's Tokio runtime. Tokio never unregisters the libc signal - # handler it installs, so a per-session watcher goes deaf the moment its - # runtime is dropped — leaving the synchronous launcher menu (itself in raw - # mode) unable to restore the terminal on a SIGTERM delivered after the - # user's first flow: an unkillable, worse form of the bug this PR fixes. A - # single process-lifetime watcher, installed once for the whole hub, must - # keep every window killable. This drives a full session round-trip — open - # the dashboard, quit back to the menu — before signalling, so it exercises - # the across-session path a single-session scenario cannot. (The startup - # ordering — listeners registered before raw mode — is covered by - # construction: `spawn_termination_watcher` is called before - # `enable_raw_mode`; a 20 ms-polled PTY scenario cannot observe that - # microsecond window, so none is claimed for it.) + # EAI-7194 launcher-hub regression: bare `rocm` is a persistent hub whose + # process outlives each session's Tokio runtime. Tokio never unregisters the + # libc signal handler it installs, so a per-session watcher goes deaf the + # moment its runtime is dropped — leaving the synchronous launcher menu + # (itself in raw mode) unable to restore the terminal on a SIGTERM delivered + # after the user's first flow: an unkillable, worse form of the bug this PR + # fixes. A single process-lifetime watcher, installed once for the whole hub, + # must keep every window killable. The process under test here is the + # launcher hub, not a dashboard, so the outcome steps are the launcher's. + # This drives a full session round-trip — open the dashboard, quit back to + # the menu — before signalling, so it exercises the across-session path a + # single-session scenario cannot. (The startup ordering — listeners + # registered before raw mode — is covered by construction: + # `spawn_termination_watcher` is called before `enable_raw_mode`; a 20 + # ms-polled PTY scenario cannot observe that microsecond window, so none is + # claimed for it.) When the user opens the launcher - And the user opens the dashboard from the launcher - And the user quits back to the launcher - And the launcher receives a SIGTERM - Then the dashboard exits from the signal with code 143 + Then the launcher front door is displayed + When the user opens the dashboard from the launcher + Then the dashboard home view is displayed + When the user quits back to the launcher + Then the launcher front door is displayed + When the launcher receives a SIGTERM + Then the launcher exits from the signal with code 143 And the terminal is restored to the normal screen diff --git a/tests/e2e-cucumber/tests/e2e/dash_steps.rs b/tests/e2e-cucumber/tests/e2e/dash_steps.rs index 09e6749ba8..f8b6f7215e 100644 --- a/tests/e2e-cucumber/tests/e2e/dash_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/dash_steps.rs @@ -478,17 +478,44 @@ async fn dashboard_exited(world: &mut E2eWorld) { assert_tui_opened(world); } -#[then(expr = "the dashboard exits from the signal with code {int}")] -async fn dashboard_exited_from_signal(world: &mut E2eWorld, expected: i32) { +/// Assert the exit code stashed by the signal `When` step. Shared by the +/// dashboard and launcher wordings — the assertion is identical, only the +/// process under test differs, and `subject` keeps the failure message honest +/// about which one it was. +fn assert_exited_from_signal(world: &mut E2eWorld, subject: &str, expected: i32) { let observed = session(world) .observed_exit_code() .expect("no signal exit code was recorded; deliver the signal first"); assert_eq!( observed, expected, - "dashboard exited with {observed} after the signal, expected {expected}" + "{subject} exited with {observed} after the signal, expected {expected}" ); } +#[then(expr = "the dashboard exits from the signal with code {int}")] +async fn dashboard_exited_from_signal(world: &mut E2eWorld, expected: i32) { + assert_exited_from_signal(world, "the dashboard", expected); +} + +// The launcher hub is a different process shape from a dashboard session (it +// outlives each session's runtime), so scenarios that signal the hub say so +// rather than borrowing the dashboard's wording. +#[then(expr = "the launcher exits from the signal with code {int}")] +async fn launcher_exited_from_signal(world: &mut E2eWorld, expected: i32) { + assert_exited_from_signal(world, "the launcher", expected); +} + +#[then("the launcher front door is displayed")] +async fn launcher_front_door_displayed(world: &mut E2eWorld) { + let tui = session(world); + // "Set up this system" is the front door's first menu entry, drawn at any + // size. Waiting (rather than reading the screen once) synchronises on the + // first paint after a launch or after a session hands control back. + tui.wait_for_screen("Set up this system", default_timeout()) + .await + .unwrap_or_else(|e| panic!("the launcher front door was not displayed: {e}")); +} + #[then("the terminal is restored to the normal screen")] async fn terminal_restored(world: &mut E2eWorld) { // The dashboard's signal handler must leave the alternate screen and show diff --git a/tests/e2e-cucumber/tests/e2e/tui_driver.rs b/tests/e2e-cucumber/tests/e2e/tui_driver.rs index 26193aade5..99eed5f36c 100644 --- a/tests/e2e-cucumber/tests/e2e/tui_driver.rs +++ b/tests/e2e-cucumber/tests/e2e/tui_driver.rs @@ -419,42 +419,9 @@ impl TuiSession { if let Ok(Some(status)) = self.child.try_wait() { self.finished = true; self.record_once(i32::try_from(status.exit_code()).unwrap_or(-1)); - let drain_deadline = Instant::now() + DRAIN_TIMEOUT; - while Instant::now() < drain_deadline { - if self.screen_text().contains(marker) { - return Ok(()); - } - if let Some(panic_message) = self.take_reader_panic() { - return Err(format!( - "pty reader thread panicked while draining the final frame for {marker:?}: {panic_message}\n{}", - self.framed_screen() - )); - } - if self - .reader - .as_ref() - .is_some_and(std::thread::JoinHandle::is_finished) - { - break; - } - tokio::time::sleep(POLL_INTERVAL).await; - } - // Final check after the drain window closes: the reader may have - // committed the last frame between the loop's screen check and the - // `is_finished`/deadline exit, so re-read before declaring failure. - if self.screen_text().contains(marker) { + if self.drain_final_frame(Some(marker)).await? { return Ok(()); } - // A reader panic landing exactly on the drain deadline would - // otherwise be masked by the generic "process exited" error below - // (and then swallowed entirely if `Drop` runs during another - // unwind). Surface it here so the real cause wins. - if let Some(panic_message) = self.take_reader_panic() { - return Err(format!( - "pty reader thread panicked while draining the final frame for {marker:?}: {panic_message}\n{}", - self.framed_screen() - )); - } return Err(format!( "process exited ({status:?}) before {marker:?} appeared.\n{}", self.framed_screen() @@ -622,7 +589,7 @@ impl TuiSession { self.finished = true; let code = i32::try_from(status.exit_code()).unwrap_or(-1); self.record_once(code); - self.drain_final_frame().await; + self.drain_final_frame(None).await?; return Ok(code); } Ok(None) => {} @@ -646,19 +613,58 @@ impl TuiSession { /// Let the reader thread consume any bytes still buffered after the child /// exits (its final restore sequences) for a short bounded window, so the - /// emulated screen reflects the terminal's final state before it is read. - async fn drain_final_frame(&mut self) { + /// emulated screen reflects the terminal's final state before it is read. A + /// single poll is not enough when a large frame is still buffered behind the + /// process exit notification. + /// + /// The one drain loop for both exit paths, so they cannot drift: pass + /// `stop_on: Some(marker)` to also return as soon as `marker` appears (that + /// caller is racing the drain against a screen assertion), or `None` to just + /// wait out the window. Returns whether `stop_on` was found; `Err` if the + /// reader thread panicked, which must win over the caller's generic timeout + /// or "process exited" message (and would otherwise be swallowed entirely + /// when `Drop` runs during another unwind). + async fn drain_final_frame(&mut self, stop_on: Option<&str>) -> Result { + let found = + |session: &Self| stop_on.is_some_and(|marker| session.screen_text().contains(marker)); let drain_deadline = Instant::now() + DRAIN_TIMEOUT; - while Instant::now() < drain_deadline { + loop { + if found(self) { + return Ok(true); + } + if let Some(panic_message) = self.take_reader_panic() { + return Err(self.drain_panic_message(stop_on, &panic_message)); + } if self .reader .as_ref() .is_some_and(std::thread::JoinHandle::is_finished) + || Instant::now() >= drain_deadline { break; } tokio::time::sleep(POLL_INTERVAL).await; } + // Final checks after the drain window closes: the reader may have + // committed the last frame — or panicked — between the loop's checks and + // the `is_finished`/deadline exit, so re-read before declaring failure. + if found(self) { + return Ok(true); + } + if let Some(panic_message) = self.take_reader_panic() { + return Err(self.drain_panic_message(stop_on, &panic_message)); + } + Ok(false) + } + + /// Reader-panic diagnostic for [`drain_final_frame`], naming the marker the + /// drain was racing when there was one. + fn drain_panic_message(&self, stop_on: Option<&str>, panic_message: &str) -> String { + let context = stop_on.map_or_else(String::new, |marker| format!(" for {marker:?}")); + format!( + "pty reader thread panicked while draining the final frame{context}: {panic_message}\n{}", + self.framed_screen() + ) } } From 4639efbf0cbf044f886d67b2150f13ecfca38113 Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Thu, 10 Sep 2026 14:08:52 +0300 Subject: [PATCH 03/13] fix(dash): handle a typed Ctrl-C as a key and stop late frames undoing the restore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Raw mode clears ISIG (Unix) and ENABLE_PROCESSED_INPUT (Windows), so while the TUI is up a typed Ctrl-C is never turned into a SIGINT or a CTRL_C_EVENT: the process receives 0x03 as an ordinary key event. Neither key loop handled it, so the first gesture a user reaches for did nothing at all and left them holding a raw-mode terminal. Measured through the PTY driver on Linux: the dashboard and the launcher both ignored 0x03 indefinitely — no exit, still on the alternate screen, cursor still hidden — and only a SIGTERM got them out. The same flag is why tokio's windows ctrl_c() stream cannot fire while the TUI is up, leaving Ctrl-Break as the only console arm that genuinely works there. Handle it as a key in both of the process's key loops — the dashboard event loop and the launcher's synchronous menu — routed through the same restore-and-exit path a real SIGINT takes, so the gesture cannot mean one thing inside a session and nothing at the front door. It sits above every overlay so no screen can trap it; a displayed job console keeps its established Ctrl+C meaning of cancelling the running job rather than killing the process mid-write. Also close the watcher-versus-renderer window instead of documenting it as a limitation. A draw can complete after restore_terminal() returns — the watcher runs on a Tokio worker thread while frames are drawn on the thread owning the loop, and nothing locks the terminal. It cannot re-enter the alternate screen, but every frame ends by hiding the cursor and repainting, so a late one would undo half the restore and paint a stale dashboard over the restored screen. In preference to a process-global terminal-write lock, both render loops now check the same SHUTTING_DOWN latch before drawing; the latch is claimed before the restore begins, so no frame can start after the claim. A frame already in flight can still interleave during the restore — cosmetic, and now stated as such. Narrow the signal doc comments and the SIGINT scenario to what they actually cover, and record on SIGNAL_TEST_LOCK that Tokio never unregisters the handler these tests install, so a single-process cargo test run is deaf to those signals from the first of them onward. dash-14 and dash-15 send a literal 0x03 through the existing PTY driver and assert terminal restore plus exit 130, for the dashboard and the launcher. EAI-7194 Signed-off-by: Roman Sirokov --- crates/rocm-dash-tui/src/app/mod.rs | 240 ++++++++++++++++++++- crates/rocm-dash-tui/src/ui/launcher.rs | 17 +- tests/e2e-cucumber/features/dash.feature | 35 ++- tests/e2e-cucumber/tests/e2e/dash_steps.rs | 49 ++++- tests/e2e-cucumber/tests/e2e/tui_driver.rs | 34 ++- 5 files changed, 352 insertions(+), 23 deletions(-) diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index cd104ec989..56980dcb95 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -1647,6 +1647,29 @@ pub async fn run(args: ResolvedArgs) -> color_eyre::Result<()> { /// then writes the alt-screen/mouse/cursor restore sequences to a fresh /// `stdout`. Every step is best-effort: on a signal we are about to exit anyway, /// and a vanished controlling terminal must not turn teardown into a panic. +/// +/// # Ordering against the renderer +/// +/// Nothing here locks the terminal, and this writer is genuinely concurrent with +/// the renderer: the watcher runs on a Tokio worker thread while frames are +/// drawn on the thread that owns the loop (`block_on`'s thread for a dashboard +/// session, the synchronous menu thread for the launcher hub). +/// +/// The consequence is not merely cosmetic, so it is closed rather than accepted. +/// A frame that *completes after* this function returns cannot re-enter the +/// alternate screen — `EnterAlternateScreen` is emitted exactly once at startup +/// and `Terminal::draw` never re-emits it — but every frame ends by hiding (or +/// repositioning) the cursor and repainting, so a late frame would undo the +/// show-cursor half of this restore and paint a stale dashboard over the +/// restored screen. The narrow serialization that closes that window, in +/// preference to a process-global lock on every terminal write: both render +/// loops consult [`shutdown_claimed`] before drawing, and the latch is claimed +/// *before* the restore begins, so no frame can start after the claim. +/// +/// What remains is a frame already in flight when the claim lands, which can +/// still interleave *during* the restore. That one is cosmetic — out-of-order +/// escapes on a terminal being reset in the same breath, with these restore +/// bytes written last — and is accepted. fn restore_terminal() { // `disable_raw_mode` mutates the real terminal (there is no in-memory // equivalent), so it stays outside the testable sequence writer below. @@ -1737,6 +1760,80 @@ fn claim_shutdown(latch: &AtomicBool) -> bool { !latch.swap(true, Ordering::SeqCst) } +/// Whether the shutdown path has already been claimed — by a signal watcher or +/// by a typed Ctrl-C — meaning the terminal is being restored and the process is +/// about to exit. +/// +/// Both render loops call this before every frame so a `draw` cannot land after +/// [`restore_terminal`] has run and undo it. See the ordering note on +/// [`restore_terminal`] for why that is the chosen fix rather than a lock on +/// every terminal write. +#[must_use] +pub fn shutdown_claimed() -> bool { + shutdown_claimed_on(&SHUTTING_DOWN) +} + +/// [`shutdown_claimed`] against an explicit latch, so a test can drive a fresh +/// one and stay order-independent — the process global cannot be reset once a +/// test has set it (same reason [`claim_shutdown`] is parameterised). +fn shutdown_claimed_on(latch: &AtomicBool) -> bool { + latch.load(Ordering::SeqCst) +} + +/// Whether `k` is a typed Ctrl-C. +/// +/// Raw mode is why this must be a key match at all. `enable_raw_mode` clears +/// `ISIG` on Unix and `ENABLE_PROCESSED_INPUT` on Windows; with those off the +/// terminal driver does NOT translate the keystroke into SIGINT (or raise +/// `CTRL_C_EVENT`) — it hands the application the byte `0x03` like any other +/// key. So while the TUI is up, [`TerminationSignals`] covers an *externally* +/// delivered `kill -INT` / `GenerateConsoleCtrlEvent` (and a Ctrl-C during the +/// startup window before raw mode is entered), but never the gesture a user +/// performs inside the dashboard. That one arrives here. +/// +/// Matches lowercase `c` only, mirroring +/// [`crate::ui::job_console::on_console_key`]: terminals commonly bind +/// Ctrl+Shift+C to copy, and claiming it would break a paste workflow. +pub(crate) const fn is_ctrl_c(k: KeyEvent) -> bool { + matches!(k.code, KeyCode::Char('c')) && k.modifiers.contains(KeyModifiers::CONTROL) +} + +/// Whether a key event must end the dashboard session: a typed Ctrl-C, unless a +/// job console is displayed. +/// +/// Split out of the event loop's match guard so the precedence is testable +/// without a terminal. The console exception is the whole reason this is not +/// simply [`is_ctrl_c`]: while a job console is up, Ctrl+C already means "cancel +/// this running job" (`ui::job_console::on_console_key`), which is the documented +/// way to stop a focused install/serve without truncating it — killing the +/// process instead would be a regression. +fn ctrl_c_should_exit(state: &AppState, k: KeyEvent) -> bool { + is_ctrl_c(k) && !state.has_active_console() +} + +/// End the process from a typed Ctrl-C, taking exactly the path an externally +/// delivered SIGINT takes: claim the shutdown latch, restore the terminal, exit +/// [`EXIT_CODE_SIGINT`]. Shared by the dashboard event loop and the launcher +/// menu — the two key loops are separate, and routing both here is what stops +/// the gesture from meaning different things in the two windows. +/// +/// Never returns, and (like the watcher) exits without unwinding; see +/// [`spawn_termination_watcher`] for the consequences that are accepted there +/// and apply identically here. +pub(crate) fn exit_on_ctrl_c() -> ! { + if claim_shutdown(&SHUTTING_DOWN) { + restore_terminal(); + std::process::exit(EXIT_CODE_SIGINT); + } + // Lost the race to a watcher that has already claimed the shutdown and is + // microseconds from `exit`. Park rather than racing a second + // `std::process::exit`; the winner ends the process. `park` is allowed to + // wake spuriously, hence the loop. + loop { + std::thread::park(); + } +} + /// Park until a termination signal arrives, then arbitrate on `latch`. /// /// Returns `Some(128 + signo)` for the single watcher that wins the latch — that @@ -1761,6 +1858,14 @@ async fn await_termination(termination: TerminationSignals, latch: &AtomicBool) /// mutated. [`TerminationSignals::recv`] then parks the watcher task until a /// signal fires, returning the conventional `128 + signo` exit code the process /// should report (SIGINT → 130, SIGTERM → 143). +/// +/// Scope, stated narrowly because it is easy to overclaim: this covers signals +/// that arrive as signals — `kill -TERM` / `kill -INT` from a supervisor or +/// another process, and anything delivered during the startup window before +/// `enable_raw_mode`. It does NOT cover a Ctrl-C typed at the running TUI: raw +/// mode clears `ISIG`, so the terminal driver never turns that keystroke into a +/// SIGINT and it arrives as a key event instead. See [`is_ctrl_c`], which both +/// key loops route to this same restore-and-exit path. #[cfg(unix)] struct TerminationSignals { sigterm: tokio::signal::unix::Signal, @@ -1790,12 +1895,24 @@ impl TerminationSignals { } } -/// Windows analog: Ctrl-C and Ctrl-Break arrive as console control events (not -/// key events) and would otherwise skip terminal restoration the same way. -/// Tokio exposes the two as separate streams, so BOTH are registered — -/// `ctrl_c()` subscribes only to `CTRL_C_EVENT` and would miss a Ctrl-Break. -/// Ctrl-Break is the harder "terminate" gesture and maps to the SIGTERM code; -/// Ctrl-C maps to the SIGINT code. +/// Windows analog: console control events, which would otherwise skip terminal +/// restoration the same way. Tokio exposes the two as separate streams, so BOTH +/// are registered — `ctrl_c()` subscribes only to `CTRL_C_EVENT` and would miss +/// a Ctrl-Break. Ctrl-Break is the harder "terminate" gesture and maps to the +/// SIGTERM code; Ctrl-C maps to the SIGINT code. +/// +/// Scope, narrowly, because the two arms differ and the difference matters: +/// +/// - Ctrl-Break: `ENABLE_PROCESSED_INPUT` does not affect `CTRL_BREAK_EVENT`, so +/// this arm is live for the whole session and is what actually terminates a +/// running TUI through the signal path. +/// - Ctrl-C: crossterm's raw mode clears `ENABLE_PROCESSED_INPUT`, and with that +/// flag off the console delivers a typed Ctrl+C into the input buffer as a KEY +/// EVENT and never raises `CTRL_C_EVENT`. This stream therefore cannot fire +/// while the TUI is up; it is kept for the startup window before +/// `enable_raw_mode` and for a `GenerateConsoleCtrlEvent` sent by another +/// process. The typed gesture is handled as a key instead — see [`is_ctrl_c`], +/// which routes it to the same restore path. #[cfg(windows)] struct TerminationSignals { ctrl_c: tokio::signal::windows::CtrlC, @@ -2046,12 +2163,19 @@ async fn event_loop(terminal: &mut Tui, args: &ResolvedArgs) -> color_eyre::Resu let mut local_agent = agent.clone(); loop { + // A termination is in flight on another thread (the signal watcher, or a + // typed Ctrl-C handled below): the terminal is being restored, so stop + // painting rather than have this frame land after the restore and undo + // it. See the ordering note on `restore_terminal`. + // // Focused host renders overlay-only (no header / tabs / dock / footer // chrome); the dashboard renders the full shell. - if should_skip_daemon(args.focus) { - terminal.draw(|f| ui::draw_focused(f, &mut state))?; - } else { - terminal.draw(|f| ui::draw(f, &mut state))?; + if !shutdown_claimed() { + if should_skip_daemon(args.focus) { + terminal.draw(|f| ui::draw_focused(f, &mut state))?; + } else { + terminal.draw(|f| ui::draw(f, &mut state))?; + } } tokio::select! { _ = tick.tick() => { @@ -2118,6 +2242,22 @@ async fn event_loop(terminal: &mut Tui, args: &ResolvedArgs) -> color_eyre::Resu Some(Ok(CtEvent::Key(k))) if !is_actionable_key(k.kind) => { let _ = k; } + // A typed Ctrl-C. Raw mode means this reaches the app as a + // key event and never as SIGINT / `CTRL_C_EVENT` (see + // `is_ctrl_c`), so the signal watcher cannot see it: without + // this arm the first gesture a user reaches for does nothing + // at all and leaves them in a raw-mode terminal. Handled + // above every overlay so no screen can trap it, and routed + // through the same restore-and-exit path a real SIGINT takes. + // + // The one exception is a displayed job console, where Ctrl+C + // already means "cancel this running job" + // (`ui::job_console::on_console_key`, dispatched by the + // overlay arms below). Exiting the process there would be a + // regression, so that established meaning wins. + Some(Ok(CtEvent::Key(k))) if ctrl_c_should_exit(&state, k) => { + exit_on_ctrl_c(); + } // The approval modal, when open, owns ALL keys with the // highest priority (above every operational overlay and the // general handler) so the operator's decision can't be @@ -3729,6 +3869,18 @@ mod tests { /// The tests are written as plain `#[test]` + an explicit runtime (rather /// than `#[tokio::test]`) precisely so the guard is held across `block_on` /// without holding a `std` lock across an `.await`. + /// + /// One residue this lock cannot undo, recorded so it is not rediscovered as + /// a mystery: `TerminationSignals::register` installs Tokio's libc handler + /// for SIGINT/SIGTERM process-wide, and Tokio never unregisters it — not on + /// drop of the `Signal`, not on drop of the runtime. So from the first of + /// these tests onward, the rest of a single-process `cargo test` run (the + /// required Windows lane) is deaf to those signals: they are caught and + /// discarded instead of terminating the binary. Harmless for the suite as it + /// stands — nothing signals the test process except the test that does so + /// deliberately, under this lock — but any future test that expects a signal + /// to actually kill the test binary, or a CI step that relies on cancelling + /// it with SIGINT, must not assume the default disposition is still in place. static SIGNAL_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// A current-thread runtime with the signal driver enabled, which @@ -3771,6 +3923,74 @@ mod tests { ); } + #[test] + fn claiming_the_shutdown_latch_suspends_rendering() { + // The narrow serialization that stops a frame landing after + // `restore_terminal()` has run and undoing it: both render loops gate on + // the SAME latch the shutdown path claims, and the claim happens before + // the restore begins. Driven on a local latch so the test never touches + // the process global. + let latch = AtomicBool::new(false); + assert!( + !shutdown_claimed_on(&latch), + "rendering must be allowed while no shutdown has been claimed" + ); + assert!(claim_shutdown(&latch), "the first claim must win"); + assert!( + shutdown_claimed_on(&latch), + "claiming the shutdown must suspend rendering, or a late frame can \ + repaint over the restored terminal" + ); + } + + #[test] + fn ctrl_c_is_recognised_as_a_key_because_raw_mode_suppresses_the_signal() { + // Raw mode clears ISIG (and ENABLE_PROCESSED_INPUT on Windows), so a + // typed Ctrl-C never becomes a signal — it arrives here as a key event. + let ctrl = |c: char| KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL); + assert!(is_ctrl_c(ctrl('c')), "Ctrl+C must be recognised"); + assert!( + !is_ctrl_c(press(KeyCode::Char('c'))), + "a bare `c` must not terminate the session" + ); + assert!(!is_ctrl_c(ctrl('d')), "Ctrl+D is a different key"); + // Terminals commonly bind Ctrl+Shift+C to copy; claiming it would kill + // the session on a copy. + assert!( + !is_ctrl_c(KeyEvent::new( + KeyCode::Char('C'), + KeyModifiers::CONTROL | KeyModifiers::SHIFT + )), + "Ctrl+Shift+C is copy, not terminate" + ); + } + + #[test] + fn ctrl_c_exits_the_session_but_a_job_console_keeps_cancelling_the_job() { + // Precedence for the event loop's Ctrl-C arm. With no console up, the + // gesture ends the session; with one up it must fall through to + // `job_console::on_console_key`, whose Ctrl+C cancels the running job — + // the documented way to stop a focused install/serve without killing the + // process mid-write. + let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL); + let mut s = st(); + assert!( + ctrl_c_should_exit(&s, ctrl_c), + "Ctrl+C with no job console must end the session" + ); + assert!( + !ctrl_c_should_exit(&s, press(KeyCode::Char('q'))), + "an unrelated key must not take the terminate path" + ); + + let _ = open_overlay_for_focus(&mut s, Focus::Examine); // auto-runs a job + assert!(s.has_active_console(), "examine console is live"); + assert!( + !ctrl_c_should_exit(&s, ctrl_c), + "Ctrl+C over a live job console must cancel the job, not the process" + ); + } + #[test] fn termination_watcher_parks_until_aborted() { let _guard = SIGNAL_TEST_LOCK diff --git a/crates/rocm-dash-tui/src/ui/launcher.rs b/crates/rocm-dash-tui/src/ui/launcher.rs index 144f532538..2f461d6fde 100644 --- a/crates/rocm-dash-tui/src/ui/launcher.rs +++ b/crates/rocm-dash-tui/src/ui/launcher.rs @@ -290,13 +290,28 @@ pub fn run_launcher( let mut sel = 0usize; let result = loop { - terminal.draw(|f| draw(f, f.area(), &state, sel, &theme))?; + // A termination is in flight on another thread (the hub's signal watcher + // runs on its own runtime while this menu loop owns the main thread): + // the terminal is being restored, so stop painting rather than let this + // frame land after the restore and undo it. See the ordering note on + // `crate::app::restore_terminal`. + if !crate::app::shutdown_claimed() { + terminal.draw(|f| draw(f, f.area(), &state, sel, &theme))?; + } let Event::Key(k) = event::read()? else { continue; }; if k.kind != KeyEventKind::Press { continue; } + // Raw mode delivers a typed Ctrl-C as a key event, not a signal, so the + // hub's termination watcher never sees it. This menu is the second of + // the process's two key loops; route it through the same + // restore-and-exit path a real SIGINT takes, so the gesture cannot mean + // one thing inside a session and nothing at all at the front door. + if crate::app::is_ctrl_c(k) { + crate::app::exit_on_ctrl_c(); + } match k.code { KeyCode::Char('q') | KeyCode::Esc => break None, KeyCode::Char('d') => break Some(LauncherChoice::OpenDashboard), diff --git a/tests/e2e-cucumber/features/dash.feature b/tests/e2e-cucumber/features/dash.feature index 21394baa9a..1ae4436131 100644 --- a/tests/e2e-cucumber/features/dash.feature +++ b/tests/e2e-cucumber/features/dash.feature @@ -138,8 +138,10 @@ Feature: Interactive dashboard @id:dash-sigint-restores-terminal @requires-os:linux Scenario: dash-12 - A SIGINT restores the terminal and exits 130 - # The interactive Ctrl-C gesture (delivered as SIGINT) takes the same restore - # path and reports the conventional 128+2 exit code. + # An externally delivered SIGINT (`kill -INT` from another process) takes the + # same restore path and reports the conventional 128+2 exit code. This is NOT + # the typed Ctrl-C gesture: raw mode clears ISIG, so that keystroke never + # becomes a signal — dash-14 covers it as the key event it actually is. When the user opens the dashboard with demo data Then the dashboard home view is displayed When the dashboard receives a SIGINT @@ -173,3 +175,32 @@ Feature: Interactive dashboard When the launcher receives a SIGTERM Then the launcher exits from the signal with code 143 And the terminal is restored to the normal screen + + @id:dash-ctrl-c-restores-terminal @requires-os:linux + Scenario: dash-14 - Typing Ctrl-C in the dashboard restores the terminal and exits 130 + # The gesture a user actually performs, and the one nothing covered. While + # the TUI holds the terminal in raw mode the driver's ISIG translation is off + # (ENABLE_PROCESSED_INPUT on Windows), so this keystroke is delivered to the + # process as the byte 0x03 — an ordinary key event — and never becomes a + # SIGINT. The signal watcher therefore cannot see it: before this was handled + # as a key, pressing Ctrl-C in the dashboard did nothing at all and left the + # user in a raw-mode terminal. The step sends the literal byte, not a signal, + # so it fails if the handling regresses to relying on the signal path. + When the user opens the dashboard with demo data + Then the dashboard home view is displayed + When the user presses Ctrl-C in the dashboard + Then the dashboard exits from the keystroke with code 130 + And the terminal is restored to the normal screen + + @id:dash-launcher-ctrl-c-restores-terminal @requires-os:linux + Scenario: dash-15 - Typing Ctrl-C at the launcher front door restores the terminal and exits 130 + # The same keystroke at the hub's synchronous menu. That loop is a separate + # key loop from the dashboard's and had no Ctrl-C handling at all, so the + # gesture left bare `rocm` sitting at the front door in raw mode. Both loops + # must route it through the one restore path, or the key means different + # things in the two windows of the same process. + When the user opens the launcher + Then the launcher front door is displayed + When the user presses Ctrl-C in the launcher + Then the launcher exits from the keystroke with code 130 + And the terminal is restored to the normal screen diff --git a/tests/e2e-cucumber/tests/e2e/dash_steps.rs b/tests/e2e-cucumber/tests/e2e/dash_steps.rs index f8b6f7215e..24a7d0d438 100644 --- a/tests/e2e-cucumber/tests/e2e/dash_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/dash_steps.rs @@ -296,6 +296,26 @@ async fn dashboard_receives_sigint(world: &mut E2eWorld) { signal_dashboard(world, TermSignal::Int).await; } +/// Type a literal Ctrl-C at the running TUI and wait for it to exit. Shared by +/// the dashboard and launcher wordings, which press the same key at the two +/// separate key loops the process runs. +async fn press_ctrl_c(world: &mut E2eWorld, subject: &str) { + session(world) + .press_ctrl_c_and_wait(default_timeout()) + .await + .unwrap_or_else(|e| panic!("{subject} did not exit after Ctrl-C: {e}")); +} + +#[when("the user presses Ctrl-C in the dashboard")] +async fn dashboard_ctrl_c(world: &mut E2eWorld) { + press_ctrl_c(world, "the dashboard").await; +} + +#[when("the user presses Ctrl-C in the launcher")] +async fn launcher_ctrl_c(world: &mut E2eWorld) { + press_ctrl_c(world, "the launcher").await; +} + // ── Then ─────────────────────────────────────────────────────────── #[then("the dashboard home view is displayed")] @@ -478,23 +498,24 @@ async fn dashboard_exited(world: &mut E2eWorld) { assert_tui_opened(world); } -/// Assert the exit code stashed by the signal `When` step. Shared by the +/// Assert the exit code stashed by the terminating `When` step. Shared by the /// dashboard and launcher wordings — the assertion is identical, only the /// process under test differs, and `subject` keeps the failure message honest -/// about which one it was. -fn assert_exited_from_signal(world: &mut E2eWorld, subject: &str, expected: i32) { +/// about which one it was. `gesture` names how the exit was requested, so a +/// failure says whether the signal path or the keystroke path is broken. +fn assert_exited_with(world: &mut E2eWorld, subject: &str, gesture: &str, expected: i32) { let observed = session(world) .observed_exit_code() - .expect("no signal exit code was recorded; deliver the signal first"); + .expect("no exit code was recorded; terminate the session first"); assert_eq!( observed, expected, - "{subject} exited with {observed} after the signal, expected {expected}" + "{subject} exited with {observed} after {gesture}, expected {expected}" ); } #[then(expr = "the dashboard exits from the signal with code {int}")] async fn dashboard_exited_from_signal(world: &mut E2eWorld, expected: i32) { - assert_exited_from_signal(world, "the dashboard", expected); + assert_exited_with(world, "the dashboard", "the signal", expected); } // The launcher hub is a different process shape from a dashboard session (it @@ -502,7 +523,21 @@ async fn dashboard_exited_from_signal(world: &mut E2eWorld, expected: i32) { // rather than borrowing the dashboard's wording. #[then(expr = "the launcher exits from the signal with code {int}")] async fn launcher_exited_from_signal(world: &mut E2eWorld, expected: i32) { - assert_exited_from_signal(world, "the launcher", expected); + assert_exited_with(world, "the launcher", "the signal", expected); +} + +// Separate wording from the signal steps on purpose: a typed Ctrl-C never +// becomes a signal while the terminal is in raw mode, so a scenario that says +// "from the signal" here would assert the wrong thing about how the exit +// happened, even though the code it lands on is the same 130. +#[then(expr = "the dashboard exits from the keystroke with code {int}")] +async fn dashboard_exited_from_keystroke(world: &mut E2eWorld, expected: i32) { + assert_exited_with(world, "the dashboard", "the keystroke", expected); +} + +#[then(expr = "the launcher exits from the keystroke with code {int}")] +async fn launcher_exited_from_keystroke(world: &mut E2eWorld, expected: i32) { + assert_exited_with(world, "the launcher", "the keystroke", expected); } #[then("the launcher front door is displayed")] diff --git a/tests/e2e-cucumber/tests/e2e/tui_driver.rs b/tests/e2e-cucumber/tests/e2e/tui_driver.rs index 99eed5f36c..2f5d1cc086 100644 --- a/tests/e2e-cucumber/tests/e2e/tui_driver.rs +++ b/tests/e2e-cucumber/tests/e2e/tui_driver.rs @@ -89,7 +89,12 @@ pub fn default_timeout() -> Duration { pub enum TermSignal { /// SIGTERM — a supervisor stopping the dashboard (`kill `). Term, - /// SIGINT — the interactive Ctrl-C gesture delivered as a signal. + /// SIGINT — an externally delivered `kill -INT` from another process. + /// + /// Deliberately NOT described as "the Ctrl-C gesture": while the TUI holds + /// the terminal in raw mode the driver's `ISIG` translation is off, so a + /// typed Ctrl-C never becomes a SIGINT. That gesture is a different code + /// path and is covered by [`TuiSession::press_ctrl_c_and_wait`]. Int, } @@ -535,9 +540,32 @@ impl TuiSession { Ok(()) } + /// Type a literal Ctrl-C at the TUI and wait for it to exit, stashing the + /// observed code for the scenario's `Then` steps. + /// + /// Sends the raw byte `0x03` — what a terminal actually transmits for the + /// keystroke — rather than a signal, and that distinction is the point. + /// While the TUI holds the terminal in raw mode, `ISIG` is off (and + /// `ENABLE_PROCESSED_INPUT` on Windows), so the driver does not turn the + /// keystroke into SIGINT: nothing in the process ever sees a signal, and the + /// byte arrives as an ordinary key event. Only sending it covers the gesture + /// a user performs; [`deliver_signal_and_wait`](Self::deliver_signal_and_wait) + /// covers the externally delivered signal, which is a genuinely different + /// path. + /// + /// As there, only harness faults are `Err`; the exit *value* and terminal + /// restoration are asserted by the scenario's `Then` steps. + pub async fn press_ctrl_c_and_wait(&mut self, timeout: Duration) -> Result<(), String> { + self.send("\u{3}")?; + let code = self.wait_for_exit_code(timeout).await?; + self.observed_exit_code = Some(code); + Ok(()) + } + /// The exit code recorded by the most recent - /// [`deliver_signal_and_wait`](Self::deliver_signal_and_wait), read back by - /// the scenario's `Then` step to assert the conventional `128 + signo` value. + /// [`deliver_signal_and_wait`](Self::deliver_signal_and_wait) or + /// [`press_ctrl_c_and_wait`](Self::press_ctrl_c_and_wait), read back by the + /// scenario's `Then` step to assert the expected `128 + signo` value. #[must_use] pub const fn observed_exit_code(&self) -> Option { self.observed_exit_code From 2e1ebb6424c090677d9227e944a431e11770478e Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Tue, 15 Sep 2026 12:10:08 +0300 Subject: [PATCH 04/13] fix(e2e): collapse the duplicate wait_for_exit_code from the merge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both sides added the helper at different offsets, so git merged them into one impl block with no conflict marker and the e2e target failed to compile (E0592). Kept this branch's draining copy — the signal scenarios need the reader to consume the restore sequences before restoration is asserted — and promoted it to pub for main's callers. Signed-off-by: Roman Sirokov --- tests/e2e-cucumber/tests/e2e/tui_driver.rs | 64 ++++------------------ 1 file changed, 10 insertions(+), 54 deletions(-) diff --git a/tests/e2e-cucumber/tests/e2e/tui_driver.rs b/tests/e2e-cucumber/tests/e2e/tui_driver.rs index 6bb6ac10d3..65404c1620 100644 --- a/tests/e2e-cucumber/tests/e2e/tui_driver.rs +++ b/tests/e2e-cucumber/tests/e2e/tui_driver.rs @@ -497,55 +497,6 @@ impl TuiSession { } } - /// Poll until the child exits, returning its raw exit code regardless of - /// whether it is zero. Used by journeys (e.g. a declined confirmation - /// prompt) whose success case is a specific *nonzero* code, where - /// [`wait_for_exit`](Self::wait_for_exit)'s built-in zero-only assertion - /// would reject the very outcome under test. - pub async fn wait_for_exit_code(&mut self, timeout: Duration) -> Result { - let deadline = Instant::now() + timeout; - loop { - match self.child.try_wait() { - Ok(Some(status)) => { - let code = i32::try_from(status.exit_code()).unwrap_or(-1); - self.finished = true; - self.record_once(code); - return Ok(code); - } - Ok(None) => {} - Err(e) => return Err(format!("failed to poll TUI child: {e}")), - } - // A reader panic doesn't affect whether the child itself has exited, - // but it does mean the screen in any resulting error/diagnostic is - // stale, so surface it rather than let this poll silently continue. - if let Some(panic_message) = self.take_reader_panic() { - return Err(format!( - "pty reader thread panicked while waiting for exit: {panic_message}\n{}", - self.framed_screen() - )); - } - if Instant::now() >= deadline { - return Err(format!( - "timed out after {timeout:?} waiting for the TUI to exit.\n{}", - self.framed_screen() - )); - } - tokio::time::sleep(POLL_INTERVAL).await; - } - } - - /// Whether the emulated terminal is currently in the alternate screen — the - /// full-screen buffer a TUI switches to with `ESC[?1049h`. For a fail-fast - /// refusal that never takes over the terminal this must stay `false`. - #[must_use] - pub fn in_alternate_screen(&self) -> bool { - self.parser - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .screen() - .alternate_screen() - } - /// Poll until the child exits, asserting a *non-zero* exit code — the fail- /// fast refusal contract. Unlike [`wait_for_exit`](Self::wait_for_exit) (which /// requires success), this fails if the child exits 0, and — crucially — if it @@ -720,11 +671,16 @@ impl TuiSession { .hide_cursor() } - /// Poll until the child exits and return its exit code, giving the reader a - /// bounded window to consume the final frame — the terminal-restore - /// sequences the signal handler emits arrive immediately before the process - /// exits, so the parser must see them before restoration is asserted. - async fn wait_for_exit_code(&mut self, timeout: Duration) -> Result { + /// Poll until the child exits, returning its raw exit code regardless of + /// whether it is zero — journeys whose success case is a specific *nonzero* + /// code (a declined confirmation, a signal exit) need the code rather than + /// [`wait_for_exit`](Self::wait_for_exit)'s zero-only assertion. + /// + /// The reader gets a bounded window to consume the final frame first: the + /// terminal-restore sequences a signal handler emits arrive immediately + /// before the process exits, so the parser must see them before restoration + /// is asserted. + pub async fn wait_for_exit_code(&mut self, timeout: Duration) -> Result { let deadline = Instant::now() + timeout; loop { match self.child.try_wait() { From 7a82ef8d2ff24abd0348ef40eca2b3a5440f752d Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Tue, 15 Sep 2026 12:12:44 +0300 Subject: [PATCH 05/13] fix(e2e): restore in_alternate_screen dropped while deduping the merge The dedup deleted from the duplicate helper up to the next `pub async fn`, which swallowed the non-async `in_alternate_screen` sitting between them. Signed-off-by: Roman Sirokov --- tests/e2e-cucumber/tests/e2e/tui_driver.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/e2e-cucumber/tests/e2e/tui_driver.rs b/tests/e2e-cucumber/tests/e2e/tui_driver.rs index 65404c1620..b1f9166e9c 100644 --- a/tests/e2e-cucumber/tests/e2e/tui_driver.rs +++ b/tests/e2e-cucumber/tests/e2e/tui_driver.rs @@ -671,6 +671,18 @@ impl TuiSession { .hide_cursor() } + /// Whether the emulated terminal is currently in the alternate screen — the + /// full-screen buffer a TUI switches to with `ESC[?1049h`. For a fail-fast + /// refusal that never takes over the terminal this must stay `false`. + #[must_use] + pub fn in_alternate_screen(&self) -> bool { + self.parser + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .screen() + .alternate_screen() + } + /// Poll until the child exits, returning its raw exit code regardless of /// whether it is zero — journeys whose success case is a specific *nonzero* /// code (a declined confirmation, a signal exit) need the code rather than From e3e36cc03daacde9819e812d94ae96c89ec4926f Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Tue, 15 Sep 2026 13:59:51 +0300 Subject: [PATCH 06/13] fix(dash): quit on Ctrl-C over a finished job console, and cover the render gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Ctrl-C exemption keyed on "a job console is displayed" rather than "a job is running". Nothing clears a manager's `active_job` when its job completes — only an Esc/Enter dismissal does — so the console stays on screen indefinitely, and Ctrl-C there fell through to `on_console_key` -> `CancelJob`, which the reducer drops on a terminal job. The keystroke did nothing at all, in exactly the gesture this PR exists to fix. Gate on the job being non-terminal instead. The render gate had no coverage and the PR body's falsification claim for it was false: with the gate inlined in the two loop bodies, deleting it left the suite green. Extract it into `draw_frame_unless_shutting_down` and `draw_menu_unless_shutting_down`, parameterised over the backend and the latch, and assert painted cells against a `TestBackend` in both key loops. The body is corrected rather than quietly re-worded. Also: - Claim the shutdown latch on `run`'s clean-quit teardown. `abort()` cannot stop a watcher already past its `.await` and inside its own synchronous restore + exit, so a SIGTERM racing a typed `q` could put two unsynchronised restore writes on one stdout. This was the only restore path not claiming the latch. - Bound both `await_termination` awaits in the signal test with a 10s timeout. A regression breaking registration of one signal kind parked the await forever; measured, the un-timed test ran 119.76s reporting nothing, the bounded one fails in 10.00s with a named message. A hanging test is worse than a failing one. - Route `run_launcher`'s teardown through `restore_terminal` instead of its own inline `disable_raw_mode` + `LeaveAlternateScreen` + `show_cursor`, so the crate carries one restore implementation. Its `?`s also turned a vanished controlling terminal into a spurious `Err` on a clean exit. - Drop the duplicate `on_alternate_screen` re-added by the merge fix-up; `expect_terminal_restored` uses the existing public `in_alternate_screen`. - Document Ctrl-C on both `?` help modals, the launcher hint line and the README. - Rename `signal_dashboard` to `signal_tui` and generalise the driver's "expected the dashboard" text; the launcher is also a process under test. - `shutdown_claimed` was in-crate only and is now folded into `shutdown_claimed_on`. Falsified: reverting `ctrl_c_should_exit` to `!has_active_console()` reds `ctrl_c_exits_once_the_console_job_has_finished`; deleting the `shutdown_claimed_on` early-return reds both new render-gate tests; breaking a signal listener reds the bounded signal test in 10.00s. Reported-by: rominf Signed-off-by: Roman Sirokov --- README.md | 7 +- crates/rocm-dash-tui/src/app/mod.rs | 269 +++++++++++++++++---- crates/rocm-dash-tui/src/ui/launcher.rs | 102 ++++++-- crates/rocm-dash-tui/src/ui/modal.rs | 11 +- tests/e2e-cucumber/tests/e2e/dash_steps.rs | 18 +- tests/e2e-cucumber/tests/e2e/tui_driver.rs | 22 +- 6 files changed, 348 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index b7bbb539d6..1b1eed3793 100644 --- a/README.md +++ b/README.md @@ -155,9 +155,10 @@ small front-door menu that gets you to the common tasks: - **Chat** — talk to a local or API-backed model - **Open full dashboard →** — escalate into the live dashboard (`rocm dash`) -Pick a row with the arrow keys and `Enter`; press `q` to quit. On a -non-interactive terminal (or piped output), `rocm` prints a one-shot status -summary instead of opening the launcher. +Pick a row with the arrow keys and `Enter`; press `q` — or `Ctrl-C`, which works +in the launcher and the dashboard alike and always restores your terminal — to +quit. On a non-interactive terminal (or piped output), `rocm` prints a one-shot +status summary instead of opening the launcher. ## Interactive interfaces diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index 9bed7675d7..4b98d45209 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -1793,7 +1793,22 @@ pub async fn run(args: ResolvedArgs) -> color_eyre::Result<()> { // the PTY closed on quit), these writes can fail with a broken pipe — that // must not turn a clean exit into a non-zero one (every step inside is // best-effort). - restore_terminal(); + // + // Gated on the same latch every other restore path claims, because + // `abort()` above is not sufficient on its own: it cannot stop a watcher + // that has already resumed past its `.await` and is inside its own + // synchronous `restore_terminal(); process::exit(code)`. A SIGTERM landing + // in the same instant the user presses `q` would otherwise have two threads + // writing `write_restore_sequences` to the same stdout, unsynchronised. If + // we lose the claim, the watcher owns the teardown and is microseconds from + // ending the process; leaving it to do both is what keeps the restore + // single-writer. (We still return `res` in that case rather than parking, so + // the reported exit code is whichever of the two lands first — the process + // is terminating either way, and parking a `block_on` thread to tighten that + // is not worth the hang risk if the winner's write ever blocks.) + if claim_shutdown(&SHUTTING_DOWN) { + restore_terminal(); + } res } @@ -1819,14 +1834,14 @@ pub async fn run(args: ResolvedArgs) -> color_eyre::Result<()> { /// show-cursor half of this restore and paint a stale dashboard over the /// restored screen. The narrow serialization that closes that window, in /// preference to a process-global lock on every terminal write: both render -/// loops consult [`shutdown_claimed`] before drawing, and the latch is claimed -/// *before* the restore begins, so no frame can start after the claim. +/// loops consult [`shutdown_claimed_on`] before drawing, and the latch is +/// claimed *before* the restore begins, so no frame can start after the claim. /// /// What remains is a frame already in flight when the claim lands, which can /// still interleave *during* the restore. That one is cosmetic — out-of-order /// escapes on a terminal being reset in the same breath, with these restore /// bytes written last — and is accepted. -fn restore_terminal() { +pub(crate) fn restore_terminal() { // `disable_raw_mode` mutates the real terminal (there is no in-memory // equivalent), so it stays outside the testable sequence writer below. let _ = disable_raw_mode(); @@ -1900,7 +1915,7 @@ pub fn spawn_termination_watcher() -> color_eyre::Result bool { !latch.swap(true, Ordering::SeqCst) } -/// Whether the shutdown path has already been claimed — by a signal watcher or -/// by a typed Ctrl-C — meaning the terminal is being restored and the process is -/// about to exit. +/// Whether the shutdown path has already been claimed on `latch` — by a signal +/// watcher or by a typed Ctrl-C — meaning the terminal is being restored and the +/// process is about to exit. /// -/// Both render loops call this before every frame so a `draw` cannot land after -/// [`restore_terminal`] has run and undo it. See the ordering note on -/// [`restore_terminal`] for why that is the chosen fix rather than a lock on -/// every terminal write. -#[must_use] -pub fn shutdown_claimed() -> bool { - shutdown_claimed_on(&SHUTTING_DOWN) -} - -/// [`shutdown_claimed`] against an explicit latch, so a test can drive a fresh -/// one and stay order-independent — the process global cannot be reset once a -/// test has set it (same reason [`claim_shutdown`] is parameterised). -fn shutdown_claimed_on(latch: &AtomicBool) -> bool { +/// Both render gates ([`draw_frame_unless_shutting_down`] and the launcher's +/// `draw_menu_unless_shutting_down`) consult this before every frame so a `draw` +/// cannot land after [`restore_terminal`] has run and undo it. See the ordering +/// note on [`restore_terminal`] for why that is the chosen fix rather than a lock +/// on every terminal write. +/// +/// Takes the latch explicitly rather than reading [`SHUTTING_DOWN`] directly so +/// a test can drive a fresh one and stay order-independent — the process global +/// cannot be reset once a test has set it (same reason [`claim_shutdown`] is +/// parameterised). Production callers pass [`SHUTTING_DOWN`]. +pub(crate) fn shutdown_claimed_on(latch: &AtomicBool) -> bool { latch.load(Ordering::SeqCst) } @@ -1955,16 +1968,31 @@ pub(crate) const fn is_ctrl_c(k: KeyEvent) -> bool { } /// Whether a key event must end the dashboard session: a typed Ctrl-C, unless a -/// job console is displayed. +/// console for a *still-running* job is displayed. /// /// Split out of the event loop's match guard so the precedence is testable /// without a terminal. The console exception is the whole reason this is not -/// simply [`is_ctrl_c`]: while a job console is up, Ctrl+C already means "cancel +/// simply [`is_ctrl_c`]: while a job is running, Ctrl+C already means "cancel /// this running job" (`ui::job_console::on_console_key`), which is the documented /// way to stop a focused install/serve without truncating it — killing the /// process instead would be a regression. +/// +/// That justification stops the moment the job reaches a terminal state, and the +/// exception has to stop with it. No manager clears its `active_job` on +/// completion — it is cleared only when the user dismisses the console with +/// Esc/Enter — so a finished console stays on screen indefinitely. Exempting it +/// unconditionally made Ctrl-C fall through to `on_console_key`, which emits +/// `CancelJob`, which the reducer ignores on a terminal job: the keystroke was a +/// **silent no-op**, leaving the user in raw mode on the alternate screen. Gating +/// on the job being non-terminal keeps "cancel the job" winning only while there +/// is a job left to cancel. fn ctrl_c_should_exit(state: &AppState, k: KeyEvent) -> bool { - is_ctrl_c(k) && !state.has_active_console() + // Reads as: no job console is up, or the one that is has already finished. + is_ctrl_c(k) + && state + .active_job_id() + .and_then(|id| state.jobs.job(id)) + .is_none_or(rocm_dash_core::state::JobState::is_terminal) } /// End the process from a typed Ctrl-C, taking exactly the path an externally @@ -2102,6 +2130,39 @@ const EXIT_CODE_SIGINT: i32 = 130; /// Conventional shell exit code for a process terminated by SIGTERM (128 + 15). const EXIT_CODE_SIGTERM: i32 = 143; +/// Draw one dashboard frame, unless a shutdown has already been claimed on +/// `latch`. +/// +/// This is the render gate. A termination may be in flight on another thread +/// (the signal watcher, or a typed Ctrl-C): the terminal is being restored, so +/// the frame must not land after the restore and undo it. See the ordering note +/// on [`restore_terminal`]. +/// +/// Extracted from the event loop's body — and parameterised over the backend and +/// the latch — purely so the gate is *testable*: a test can drive a +/// `TestBackend`, claim a local latch, and assert no cells were painted. Inlined +/// in the loop it was unreachable from any test, and deleting it turned nothing +/// red. +/// +/// Focused host renders overlay-only (no header / tabs / dock / footer chrome); +/// the dashboard renders the full shell. +fn draw_frame_unless_shutting_down( + terminal: &mut Terminal, + state: &mut AppState, + focus: Option, + latch: &AtomicBool, +) -> Result<(), ::Error> { + if shutdown_claimed_on(latch) { + return Ok(()); + } + if should_skip_daemon(focus) { + terminal.draw(|f| ui::draw_focused(f, state))?; + } else { + terminal.draw(|f| ui::draw(f, state))?; + } + Ok(()) +} + async fn event_loop(terminal: &mut Tui, args: &ResolvedArgs) -> color_eyre::Result<()> { let (tx, mut rx) = mpsc::unbounded_channel::(); // Job-bridge channel (Phase 3 Wave 1): the async runtime streams @@ -2321,20 +2382,7 @@ async fn event_loop(terminal: &mut Tui, args: &ResolvedArgs) -> color_eyre::Resu let mut local_agent = agent.clone(); loop { - // A termination is in flight on another thread (the signal watcher, or a - // typed Ctrl-C handled below): the terminal is being restored, so stop - // painting rather than have this frame land after the restore and undo - // it. See the ordering note on `restore_terminal`. - // - // Focused host renders overlay-only (no header / tabs / dock / footer - // chrome); the dashboard renders the full shell. - if !shutdown_claimed() { - if should_skip_daemon(args.focus) { - terminal.draw(|f| ui::draw_focused(f, &mut state))?; - } else { - terminal.draw(|f| ui::draw(f, &mut state))?; - } - } + draw_frame_unless_shutting_down(terminal, &mut state, args.focus, &SHUTTING_DOWN)?; tokio::select! { _ = tick.tick() => { // Advance the animation clock so spinners cycle even while a @@ -4049,6 +4097,13 @@ mod tests { /// it with SIGINT, must not assume the default disposition is still in place. static SIGNAL_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// Upper bound on any `await_termination` in a test. The signal it waits for + /// is already queued before the await starts, so the real latency is + /// microseconds; this only exists so a broken registration fails the test + /// instead of parking the `.await` forever and burning the lane's job + /// timeout. A hanging test is worse than a failing one — it reports nothing. + const SIGNAL_AWAIT_TIMEOUT: Duration = Duration::from_secs(10); + /// A current-thread runtime with the signal driver enabled, which /// `TerminationSignals::register` needs. fn signal_test_runtime() -> tokio::runtime::Runtime { @@ -4157,6 +4212,106 @@ mod tests { ); } + #[test] + fn a_claimed_shutdown_stops_the_dashboard_painting_another_frame() { + // The render gate itself, not just the latch predicate underneath it. + // `restore_terminal()` runs on a Tokio worker while frames are drawn on + // the `block_on` thread, and nothing locks the terminal — so a frame that + // *starts* after the restore would hide the cursor again and repaint a + // stale dashboard over the restored screen. The claim happens before the + // restore begins, so gating on it is what makes that impossible. + // + // Driven against a `TestBackend` and a local latch: no process-global + // state, no real terminal, and the assertion is on painted cells rather + // than on the predicate the gate happens to call. + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + let painted = |term: &Terminal| -> String { + term.backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect::() + .trim() + .to_string() + }; + + // Control: with nothing claimed the gate must let the frame through, + // otherwise the assertion below would pass on a helper that never draws. + let mut s = st(); + let open = AtomicBool::new(false); + let mut term = Terminal::new(TestBackend::new(120, 32)).unwrap(); + draw_frame_unless_shutting_down(&mut term, &mut s, None, &open) + .expect("drawing to a TestBackend cannot fail"); + assert!( + !painted(&term).is_empty(), + "with no shutdown claimed the dashboard must paint a frame" + ); + + // The real case: a watcher (or a typed Ctrl-C) has claimed the shutdown + // and the restore is under way. + let mut s = st(); + let claimed = AtomicBool::new(false); + assert!(claim_shutdown(&claimed), "the test must win its own latch"); + let mut term = Terminal::new(TestBackend::new(120, 32)).unwrap(); + draw_frame_unless_shutting_down(&mut term, &mut s, None, &claimed) + .expect("the gate must not turn a suppressed frame into an error"); + assert_eq!( + painted(&term), + "", + "once the shutdown is claimed no further frame may be painted — a \ + late frame lands after `restore_terminal()` and undoes it" + ); + } + + #[test] + fn ctrl_c_exits_once_the_console_job_has_finished() { + // The gesture the PR exists to fix, in the state that used to swallow it. + // Nothing clears `active_job` when a job completes (only an Esc/Enter + // dismissal does), so the console stays on screen after the job is done. + // While the exemption keyed on "a console is displayed" rather than "a + // job is running", Ctrl-C there fell through to `on_console_key` → + // `CancelJob`, which the reducer drops on a terminal job: nothing + // happened at all, and the user stayed in raw mode on the alt-screen. + let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL); + let mut s = st(); + let _ = open_overlay_for_focus(&mut s, Focus::Examine); // auto-runs a job + let job_id = s + .active_job_id() + .expect("opening Examine must start a job and show its console") + .to_string(); + assert!( + !ctrl_c_should_exit(&s, ctrl_c), + "while the job is still running, Ctrl+C must cancel the job" + ); + + // The job finishes. The console is NOT dismissed — this is the review + // state the user is left sitting in. + s.jobs.apply(rocm_dash_core::state::StateEvent::JobDone { + id: job_id.clone(), + code: 0, + }); + assert!( + s.jobs + .job(&job_id) + .is_some_and(rocm_dash_core::state::JobState::is_terminal), + "the job must have reached a terminal state" + ); + assert!( + s.has_active_console(), + "the finished console must still be displayed — that is the whole \ + point of this case" + ); + assert!( + ctrl_c_should_exit(&s, ctrl_c), + "Ctrl+C over a FINISHED job console must end the session; there is no \ + job left to cancel, so exempting it makes the keystroke a silent \ + no-op and traps the user in raw mode" + ); + } + #[test] fn termination_watcher_parks_until_aborted() { let _guard = SIGNAL_TEST_LOCK @@ -4222,15 +4377,47 @@ mod tests { let rc = unsafe { libc::raise(signo) }; assert_eq!(rc, 0, "raise({signo}) failed"); + // Both `await_termination`s are bounded. A regression that breaks + // *registration* of one signal kind (rather than mis-mapping its + // exit code) leaves the `.await` parked forever, and an unbounded + // await would burn the required lane's job timeout instead of + // reporting a failure. The bound is generous — the signal is + // already queued by the `raise` above, so the await resolves in + // microseconds; anything near 10 s is a genuine hang. + let received = tokio::time::timeout( + SIGNAL_AWAIT_TIMEOUT, + await_termination(hub_watcher, &latch), + ) + .await + .unwrap_or_else(|_| { + panic!( + "the first watcher never received signal {signo} within \ + {SIGNAL_AWAIT_TIMEOUT:?} — the listener for it is not \ + registered, so the watcher would park forever instead of \ + restoring the terminal" + ) + }); assert_eq!( - await_termination(hub_watcher, &latch).await, + received, Some(expected), "the first watcher must receive signal {signo} and map it to \ the conventional 128 + signo exit code" ); + + let stood_down = tokio::time::timeout( + SIGNAL_AWAIT_TIMEOUT, + await_termination(session_watcher, &latch), + ) + .await + .unwrap_or_else(|_| { + panic!( + "the second watcher never woke for signal {signo} within \ + {SIGNAL_AWAIT_TIMEOUT:?} — Tokio's registry must wake \ + every listener registered for a kind, not just the first" + ) + }); assert_eq!( - await_termination(session_watcher, &latch).await, - None, + stood_down, None, "the second watcher woken by the same signal must stand down \ rather than race a concurrent restore + exit" ); diff --git a/crates/rocm-dash-tui/src/ui/launcher.rs b/crates/rocm-dash-tui/src/ui/launcher.rs index bcd62814d9..119d846449 100644 --- a/crates/rocm-dash-tui/src/ui/launcher.rs +++ b/crates/rocm-dash-tui/src/ui/launcher.rs @@ -248,7 +248,7 @@ fn draw_menu(f: &mut Frame, area: Rect, state: &AppState, sel: usize, theme: &Th ])); lines.push(Line::raw("")); lines.push(Line::from(Span::styled( - "↑↓←→ move Enter select d dashboard q quit", + "↑↓←→ move Enter select d dashboard q / Ctrl-C quit", Style::default().fg(theme.muted), ))); f.render_widget(Paragraph::new(lines), area); @@ -287,9 +287,7 @@ pub fn run_launcher( serving: Vec, ) -> std::io::Result> { use crossterm::event::{self, Event, KeyCode, KeyEventKind}; - use crossterm::terminal::{ - EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode, - }; + use crossterm::terminal::{EnterAlternateScreen, enable_raw_mode}; use ratatui::Terminal; use ratatui::backend::CrosstermBackend; @@ -304,14 +302,13 @@ pub fn run_launcher( let mut sel = 0usize; let result = loop { - // A termination is in flight on another thread (the hub's signal watcher - // runs on its own runtime while this menu loop owns the main thread): - // the terminal is being restored, so stop painting rather than let this - // frame land after the restore and undo it. See the ordering note on - // `crate::app::restore_terminal`. - if !crate::app::shutdown_claimed() { - terminal.draw(|f| draw(f, f.area(), &state, sel, &theme))?; - } + draw_menu_unless_shutting_down( + &mut terminal, + &state, + sel, + &theme, + &crate::app::SHUTTING_DOWN, + )?; let Event::Key(k) = event::read()? else { continue; }; @@ -340,12 +337,41 @@ pub fn run_launcher( } }; - disable_raw_mode()?; - crossterm::execute!(terminal.backend_mut(), LeaveAlternateScreen)?; - terminal.show_cursor()?; + // One shared teardown for the whole crate. This used to be an open-coded + // `disable_raw_mode` + `LeaveAlternateScreen` + `show_cursor` — a second + // restore implementation that could (and would) drift from the one the + // signal watcher and the typed-Ctrl-C path run. `restore_terminal` is + // best-effort by design: a vanished controlling terminal must not turn a + // clean launcher exit into an `Err`, which the `?`s here previously did. + crate::app::restore_terminal(); Ok(result) } +/// Draw one launcher frame, unless a shutdown has already been claimed on +/// `latch`. +/// +/// The hub's signal watcher runs on its own runtime while this menu loop owns +/// the main thread, so a termination can be in flight concurrently: the terminal +/// is being restored, and this frame must not land after the restore and undo +/// it. See the ordering note on `crate::app::restore_terminal`. +/// +/// Parameterised over the backend and the latch so the gate is testable against +/// a `TestBackend` — inlined in the loop it was reachable only from a real +/// terminal, and deleting it turned no test red. +fn draw_menu_unless_shutting_down( + terminal: &mut ratatui::Terminal, + state: &AppState, + sel: usize, + theme: &Theme, + latch: &std::sync::atomic::AtomicBool, +) -> Result<(), ::Error> { + if crate::app::shutdown_claimed_on(latch) { + return Ok(()); + } + terminal.draw(|f| draw(f, f.area(), state, sel, theme))?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -367,6 +393,52 @@ mod tests { .collect() } + #[test] + fn a_claimed_shutdown_stops_the_launcher_painting_another_frame() { + // Same gate as the dashboard's, on the crate's *other* key loop. The hub + // menu runs on the main thread while the hub's signal watcher runs on its + // own runtime, so a frame started after `restore_terminal()` would hide + // the cursor again and repaint the menu over the restored screen. + // Local latch, `TestBackend`: asserts painted cells, not the predicate. + use std::sync::atomic::AtomicBool; + + let painted = |term: &Terminal| -> String { + term.backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect::() + .trim() + .to_string() + }; + + let state = base(); + let theme = state.theme; + + // Control: an unclaimed latch must let the frame through, or the + // assertion below would hold for a helper that simply never draws. + let open = AtomicBool::new(false); + let mut term = Terminal::new(TestBackend::new(100, 30)).unwrap(); + draw_menu_unless_shutting_down(&mut term, &state, 0, &theme, &open) + .expect("drawing to a TestBackend cannot fail"); + assert!( + !painted(&term).is_empty(), + "with no shutdown claimed the launcher must paint its menu" + ); + + let claimed = AtomicBool::new(true); + let mut term = Terminal::new(TestBackend::new(100, 30)).unwrap(); + draw_menu_unless_shutting_down(&mut term, &state, 0, &theme, &claimed) + .expect("the gate must not turn a suppressed frame into an error"); + assert_eq!( + painted(&term), + "", + "once the shutdown is claimed the launcher must stop painting — a \ + late frame lands after `restore_terminal()` and undoes it" + ); + } + fn base() -> AppState { let mut s = AppState::new("t".into(), "default-dark".into()); s.latest = Some(Snapshot { diff --git a/crates/rocm-dash-tui/src/ui/modal.rs b/crates/rocm-dash-tui/src/ui/modal.rs index c305875893..dfe02fa811 100644 --- a/crates/rocm-dash-tui/src/ui/modal.rs +++ b/crates/rocm-dash-tui/src/ui/modal.rs @@ -86,6 +86,11 @@ pub fn draw_help(f: &mut Frame, area: Rect, tab: ActiveTab, theme: &Theme) { let mut lines: Vec = vec![ key_line("q", "quit", theme), + // Ctrl-C is a first-class quit gesture in both key loops (it restores the + // terminal and exits 130), so it belongs on the help surface next to `q`. + // The exception is worth stating: over a *running* job console it still + // means "cancel this job". + key_line("Ctrl-C", "quit (cancels a running job console)", theme), key_line("?", "toggle this help", theme), key_line("Tab / Shift-Tab", "next / previous tab", theme), key_line("1 .. 5", "jump to tab", theme), @@ -601,7 +606,11 @@ pub fn draw_global_help(f: &mut Frame, area: Rect, theme: &Theme) { ), ( "CHAT / GLOBAL", - &[("i / Enter", "focus chat input"), ("q", "quit")], + &[ + ("i / Enter", "focus chat input"), + ("q", "quit"), + ("Ctrl-C", "quit (cancels a running job)"), + ], ), ]; render_help_groups(f, cols[0], left, theme); diff --git a/tests/e2e-cucumber/tests/e2e/dash_steps.rs b/tests/e2e-cucumber/tests/e2e/dash_steps.rs index 2c789bf7be..5801e8fe46 100644 --- a/tests/e2e-cucumber/tests/e2e/dash_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/dash_steps.rs @@ -260,14 +260,18 @@ async fn quit_launcher(world: &mut E2eWorld) { quit_tui(world, "the launcher").await; } -/// Deliver a termination signal to the running dashboard and wait for it to -/// exit, stashing the observed exit code for the `Then` steps. Shared by the +/// Deliver a termination signal to the TUI under test and wait for it to exit, +/// stashing the observed exit code for the `Then` steps. Shared by the /// SIGTERM/SIGINT `When` steps so the two cannot drift. -async fn signal_dashboard(world: &mut E2eWorld, signal: TermSignal) { +/// +/// Deliberately not named for the dashboard: the process under test is the +/// launcher in the hub round-trip scenario, and the signal handling being +/// asserted is process-wide, not dashboard-specific. +async fn signal_tui(world: &mut E2eWorld, signal: TermSignal) { session(world) .deliver_signal_and_wait(signal, default_timeout()) .await - .unwrap_or_else(|e| panic!("the dashboard did not exit after {signal:?}: {e}")); + .unwrap_or_else(|e| panic!("the process under test did not exit after {signal:?}: {e}")); } #[when("the user opens the dashboard from the launcher")] @@ -304,17 +308,17 @@ async fn quit_back_to_launcher(world: &mut E2eWorld) { #[when("the launcher receives a SIGTERM")] async fn launcher_receives_sigterm(world: &mut E2eWorld) { - signal_dashboard(world, TermSignal::Term).await; + signal_tui(world, TermSignal::Term).await; } #[when("the dashboard receives a SIGTERM")] async fn dashboard_receives_sigterm(world: &mut E2eWorld) { - signal_dashboard(world, TermSignal::Term).await; + signal_tui(world, TermSignal::Term).await; } #[when("the dashboard receives a SIGINT")] async fn dashboard_receives_sigint(world: &mut E2eWorld) { - signal_dashboard(world, TermSignal::Int).await; + signal_tui(world, TermSignal::Int).await; } /// Type a literal Ctrl-C at the running TUI and wait for it to exit. Shared by diff --git a/tests/e2e-cucumber/tests/e2e/tui_driver.rs b/tests/e2e-cucumber/tests/e2e/tui_driver.rs index b1f9166e9c..af4bfc70a0 100644 --- a/tests/e2e-cucumber/tests/e2e/tui_driver.rs +++ b/tests/e2e-cucumber/tests/e2e/tui_driver.rs @@ -638,30 +638,24 @@ impl TuiSession { } /// Assert the terminal was restored on exit: the child left the alternate - /// screen and made the cursor visible again. A dashboard that dies on a - /// signal without running its restore path leaves both inverted (still on - /// the alt-screen, cursor hidden) — the broken state that needs a `reset`. + /// screen and made the cursor visible again. A TUI that dies on a signal + /// without running its restore path leaves both inverted (still on the + /// alt-screen, cursor hidden) — the broken state that needs a `reset`. + /// + /// Reuses the public [`in_alternate_screen`](Self::in_alternate_screen) + /// rather than carrying a second, byte-identical alt-screen probe. pub fn expect_terminal_restored(&self) -> Result<(), String> { - let on_alt = self.on_alternate_screen(); + let on_alt = self.in_alternate_screen(); let cursor_hidden = self.cursor_hidden(); if on_alt || cursor_hidden { return Err(format!( - "terminal was not restored on exit (alternate_screen={on_alt}, cursor_hidden={cursor_hidden}); expected the dashboard to leave the alt-screen and show the cursor.\n{}", + "terminal was not restored on exit (alternate_screen={on_alt}, cursor_hidden={cursor_hidden}); expected the process under test to leave the alt-screen and show the cursor.\n{}", self.framed_screen() )); } Ok(()) } - /// Whether the emulated screen is currently on the alternate screen. - fn on_alternate_screen(&self) -> bool { - self.parser - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .screen() - .alternate_screen() - } - /// Whether the emulated cursor is currently hidden. fn cursor_hidden(&self) -> bool { self.parser From f46ca9aa8969191fa7a0ca951c6969d911e976d2 Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Tue, 15 Sep 2026 14:10:12 +0300 Subject: [PATCH 07/13] fix(dash): gate the test signal timeout to unix so the Windows lane builds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `windows-build-and-test` failed on e3e36cc0: error: constant `SIGNAL_AWAIT_TIMEOUT` is never used --> crates\rocm-dash-tui\src\app\mod.rs:4105:11 = note: `-D dead-code` implied by `-D warnings` The constant bounds the two `await_termination` calls in `termination_signals_yield_shell_exit_codes_and_only_one_watcher_shuts_down`, which is `#[cfg(unix)]` — all four references sit inside it. The constant itself was ungated, so on Windows it compiled with no callers. Gate it the same way. `Duration` stays imported for `UPDATE_CHECK_INTERVAL` and the tick interval, so nothing is orphaned. The sibling `SIGNAL_TEST_LOCK` and `signal_test_runtime` are deliberately left ungated: both are also used by `termination_watcher_parks_until_aborted`, which runs on every platform. Worth noting for the next one: `cargo clippy --workspace --all-targets` on Linux cannot see this class of failure at all — a `cfg(unix)` body keeps its helpers live there, and only the Windows lane compiles the configuration that makes them dead. Signed-off-by: Roman Sirokov --- crates/rocm-dash-tui/src/app/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index 4b98d45209..5fca52fc73 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -4102,6 +4102,10 @@ mod tests { /// microseconds; this only exists so a broken registration fails the test /// instead of parking the `.await` forever and burning the lane's job /// timeout. A hanging test is worse than a failing one — it reports nothing. + /// + /// Gated because its only callers are: ungated, it is dead code on Windows + /// and `-D warnings` fails that lane. + #[cfg(unix)] const SIGNAL_AWAIT_TIMEOUT: Duration = Duration::from_secs(10); /// A current-thread runtime with the signal driver enabled, which From f3e29d6e6c599fae239cf176743e5d8173487af9 Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Tue, 15 Sep 2026 14:30:08 +0300 Subject: [PATCH 08/13] test(dash): assert the restore path disables mouse capture MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The restore-sequences test only checked leave-alt-screen and show-cursor, so deleting `DisableMouseCapture` from `write_restore_sequences` left it green while leaving the terminal reporting mouse events after exit. Assert crossterm's five-mode expansion too (verified by falsification: dropping the command turns the test red). Also correct two comments that no longer describe the code: the approval modal is no longer an absolute key priority now that the Ctrl-C arm sits above it, and `signal_task.abort()` cannot pre-empt a watcher that has already resumed past its await — that narrow window is accepted. Signed-off-by: Roman Sirokov --- crates/rocm-dash-tui/src/app/mod.rs | 44 ++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index 5fca52fc73..cb80288210 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -1785,6 +1785,14 @@ pub async fn run(args: ResolvedArgs) -> color_eyre::Result<()> { // The session ended on its own — the signal watcher is no longer needed and // must not linger to fire (and re-restore/exit) after a clean return. + // What `abort()` buys is cancelling a watcher still parked on its `.await`: + // `spawn_termination_watcher`'s body runs straight from `await_termination` + // into `process::exit` with no await point in between, so once the signal + // has resolved there is nowhere for the cancellation to land. A signal + // arriving in the instant before this call therefore still ends the process + // with `128 + signo` instead of returning `res`. Narrow window, accepted: + // the process is exiting either way, and the terminal is restored on both + // paths. signal_task.abort(); // Best-effort terminal restoration, reusing the exact teardown the signal @@ -2471,10 +2479,11 @@ async fn event_loop(terminal: &mut Tui, args: &ResolvedArgs) -> color_eyre::Resu Some(Ok(CtEvent::Key(k))) if ctrl_c_should_exit(&state, k) => { exit_on_ctrl_c(); } - // The approval modal, when open, owns ALL keys with the - // highest priority (above every operational overlay and the - // general handler) so the operator's decision can't be - // pre-empted. On Approve: replay the approved action off the + // The approval modal, when open, owns every remaining key + // (above every operational overlay and the general handler) + // so the operator's decision can't be pre-empted by a screen + // behind it. Only the Ctrl-C arm above outranks it. + // On Approve: replay the approved action off the // event loop (spawn_blocking) and post ChatApprovalResult. // On Deny/Cancel: a declined turn, no execution. Some(Ok(CtEvent::Key(k))) if state.approval.is_some() => { @@ -4437,12 +4446,13 @@ mod tests { // stdout handle, so the Windows path is exercised there, not by this sink. #[cfg(unix)] #[test] - fn write_restore_sequences_leaves_alt_screen_and_shows_cursor() { - // The restore path must leave the alternate screen and show the cursor. - // Driving an in-memory sink asserts the actual emitted bytes without - // touching the process's shared terminal state — the global - // `disable_raw_mode()` half is deliberately outside this function, so - // nothing here races other tests in the single-process `cargo test` lane. + fn write_restore_sequences_leaves_alt_screen_disables_mouse_and_shows_cursor() { + // The restore path must undo all three things `run` set up: leave the + // alternate screen, disable mouse capture, show the cursor. Driving an + // in-memory sink asserts the actual emitted bytes without touching the + // process's shared terminal state — the global `disable_raw_mode()` half + // is deliberately outside this function, so nothing here races other + // tests in the single-process `cargo test` lane. let mut sink: Vec = Vec::new(); write_restore_sequences(&mut sink).expect("writing to a Vec cannot fail"); let emitted = String::from_utf8(sink).expect("restore sequences are ASCII escapes"); @@ -4450,6 +4460,20 @@ mod tests { emitted.contains("\x1b[?1049l"), "expected the leave-alt-screen sequence in {emitted:?}" ); + // `DisableMouseCapture` is one command but five terminal modes: + // crossterm 0.28 expands it to SGR-encoding, urxvt-encoding, any-motion, + // button-event and normal tracking, turned off in that order. Assert + // the whole block rather than a single mode so dropping the command from + // `write_restore_sequences` cannot leave this test green — a terminal + // left reporting mouse events after `rocm dash` exits is exactly the + // broken-terminal state this restore path exists to prevent. If a + // crossterm bump changes the expansion, re-derive it from a sink run + // rather than weakening the assertion. + let disable_mouse = "\x1b[?1006l\x1b[?1015l\x1b[?1003l\x1b[?1002l\x1b[?1000l"; + assert!( + emitted.contains(disable_mouse), + "expected the disable-mouse-capture sequences {disable_mouse:?} in {emitted:?}" + ); assert!( emitted.contains("\x1b[?25h"), "expected the show-cursor sequence in {emitted:?}" From 94702d1b1e3b4fc3d3e76a512d2f960f748a57e8 Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Tue, 15 Sep 2026 15:12:08 +0300 Subject: [PATCH 09/13] fix(dash): unwedge the launcher hub, and stop the help modal truncating MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two regressions from e3e36cc0, both surfaced by the E2E lane. `run`'s clean-quit teardown claimed `SHUTTING_DOWN`. That latch is a one-shot *process-exit* arbiter — nothing releases it, because every other claimer goes straight on to `process::exit`. `run` returning is the one teardown with an "after": bare `rocm` is a persistent hub, so control goes back to a live launcher menu. Claiming there wedged the hub three ways at once — the render gate refused every subsequent frame (`dash-14` timed out on a blank front door), `exit_on_ctrl_c` parked forever, and every later `await_termination` lost the claim and returned without exiting, so the hub silently swallowed SIGTERM: the unkillable-terminal failure this PR exists to fix, reintroduced one layer up. So the exit latch is read, not claimed, by `restore_after_session`: if a watcher or a typed Ctrl-C already owns the exit it is microseconds from ending the process and a second restore is redundant; otherwise the session restores and leaves the latch for the windows that follow. rominf's finding stands — the single-writer guarantee moves to `RESTORE_LOCK`, a mutex held across `restore_terminal`'s escape bytes, which is strictly stronger than the latch was: it covers the two-watchers-on-two-runtimes case too, and it holds even though the check above is racy on its own. The render gate keeps its meaning, now an exact one — "the process is exiting". Second, the help modal was sized to a fixed 70% of the body. At the 80x24 the e2e lane pins that is 14 rows; the new Ctrl-C hint wraps to two lines at that width, which pushed the per-tab guidance off the bottom with no scrollbar or indicator — `dash-05` failed on "Home tab", text unrelated to the hint that was added. The hint is documented deliberately and stays; the modal is now sized to the height `Paragraph::line_count` says its wrapped content needs, clamped to the area, so a new hint can no longer silently evict an unrelated one. `centered_width` is split out of `centered_rect` so the pre-layout width cannot drift from the real geometry. Falsified: restoring `centered_rect(70, 70, 80, 22, area)` reds `help_modal_shows_every_hint_at_the_minimum_supported_geometry`, printing the same modal-ends-at-`{ / }` render the failing CI job captured; restoring `claim_shutdown` in `restore_after_session` reds both `a_clean_session_teardown_restores_without_claiming_the_exit_latch` and `the_front_door_comes_back_after_a_session_ends_cleanly`, the latter on a blank buffer — the e2e symptom, at unit cost. `RESTORE_LOCK`'s mutual exclusion has no deterministic single-threaded observable and is not separately tested. All 16 `dash` e2e scenarios pass on the mock lane. Reported-by: rominf Signed-off-by: Roman Sirokov --- crates/rocm-dash-tui/src/app/mod.rs | 140 ++++++++++++++++++++---- crates/rocm-dash-tui/src/ui/launcher.rs | 37 +++++++ crates/rocm-dash-tui/src/ui/modal.rs | 98 ++++++++++++++++- 3 files changed, 249 insertions(+), 26 deletions(-) diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index cb80288210..1fe9b80235 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -1795,31 +1795,56 @@ pub async fn run(args: ResolvedArgs) -> color_eyre::Result<()> { // paths. signal_task.abort(); - // Best-effort terminal restoration, reusing the exact teardown the signal - // path runs so the two cannot drift. Never let teardown failures override - // the session result: if the controlling terminal already went away (e.g. - // the PTY closed on quit), these writes can fail with a broken pipe — that - // must not turn a clean exit into a non-zero one (every step inside is - // best-effort). - // - // Gated on the same latch every other restore path claims, because - // `abort()` above is not sufficient on its own: it cannot stop a watcher - // that has already resumed past its `.await` and is inside its own - // synchronous `restore_terminal(); process::exit(code)`. A SIGTERM landing - // in the same instant the user presses `q` would otherwise have two threads - // writing `write_restore_sequences` to the same stdout, unsynchronised. If - // we lose the claim, the watcher owns the teardown and is microseconds from - // ending the process; leaving it to do both is what keeps the restore - // single-writer. (We still return `res` in that case rather than parking, so - // the reported exit code is whichever of the two lands first — the process - // is terminating either way, and parking a `block_on` thread to tighten that - // is not worth the hang risk if the winner's write ever blocks.) - if claim_shutdown(&SHUTTING_DOWN) { - restore_terminal(); - } + restore_after_session(&SHUTTING_DOWN, restore_terminal); res } +/// Teardown for a dash *session* that has ended — the counterpart to the +/// watcher's and [`exit_on_ctrl_c`]'s teardown, for the one restore path that +/// does **not** end the process. +/// +/// Best-effort, reusing the exact teardown the signal path runs so the two +/// cannot drift, and never letting teardown failures override the session +/// result: if the controlling terminal already went away (e.g. the PTY closed on +/// quit), these writes can fail with a broken pipe — that must not turn a clean +/// exit into a non-zero one (every step inside `restore` is best-effort). +/// +/// # Why this reads the latch instead of claiming it +/// +/// [`SHUTTING_DOWN`] is a one-shot *process-exit* arbiter: whoever claims it +/// restores the terminal and calls `process::exit`, and nothing ever releases +/// it because there is no "after" to release into. `run` returning is the one +/// teardown with an after — bare `rocm` is a persistent hub, so `run` hands +/// control back to a live launcher menu that must keep painting, keep honouring +/// Ctrl-C, and keep being killable. Claiming the latch here wedged all three at +/// once: the render gate refused every subsequent launcher frame (a blank front +/// door), [`exit_on_ctrl_c`] parked forever, and every later `await_termination` +/// lost the claim and returned without exiting — a signal-swallowing, blank, +/// unkillable hub after the user's first flow. +/// +/// So the latch is *read*: if a watcher (or a typed Ctrl-C) has already claimed +/// the exit, it owns the teardown and is microseconds from ending the process, +/// and a second restore here would be pure redundancy. Otherwise this session +/// restores the terminal and leaves the latch untouched for the windows that +/// come after it. +/// +/// Single-writer is preserved by [`RESTORE_LOCK`] inside [`restore_terminal`] +/// rather than by this read, which is deliberately racy on its own: `abort()` +/// above cannot stop a watcher already resumed past its `.await` and inside its +/// own synchronous `restore_terminal(); process::exit(code)`, so a SIGTERM +/// landing in the same instant the user presses `q` can still put two threads on +/// this path. They serialise on the lock; they no longer contend for the latch. +/// +/// `restore` is a parameter so a unit test can assert both halves of the +/// contract — that the teardown runs, and that it leaves the latch unclaimed — +/// without writing escape sequences to the stdout every other test shares. +pub(crate) fn restore_after_session(latch: &AtomicBool, restore: impl FnOnce()) { + if shutdown_claimed_on(latch) { + return; + } + restore(); +} + /// Best-effort teardown of the terminal modes `run` set up. Disables raw mode /// (process-global terminal state, so this can safely run from the signal /// watcher even though the [`Terminal`] backend owns its own `stdout` clone), @@ -1849,13 +1874,41 @@ pub async fn run(args: ResolvedArgs) -> color_eyre::Result<()> { /// still interleave *during* the restore. That one is cosmetic — out-of-order /// escapes on a terminal being reset in the same breath, with these restore /// bytes written last — and is accepted. +/// +/// # Ordering against another restore +/// +/// Separate hazard, separate mechanism. Two teardowns can run at once: a signal +/// watcher resumed past its `.await` races [`run`]'s clean-quit teardown (which +/// deliberately does not claim the exit latch — see [`restore_after_session`]), +/// and two watchers on two runtimes both wake on one process-global signal. +/// [`RESTORE_LOCK`] makes this function the single writer for the duration of +/// one teardown, so two threads can never interleave `write_restore_sequences` +/// on the same stdout. It is held only across a handful of escape bytes, so it +/// adds no hang profile beyond the internal lock `io::stdout()` already takes on +/// every write. pub(crate) fn restore_terminal() { + // Poisoning is irrelevant here: nothing inside can panic (every step is + // best-effort), and a teardown skipped because some *other* thread panicked + // mid-restore is strictly worse than running it again. + let _guard = RESTORE_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); // `disable_raw_mode` mutates the real terminal (there is no in-memory // equivalent), so it stays outside the testable sequence writer below. let _ = disable_raw_mode(); let _ = write_restore_sequences(&mut io::stdout()); } +/// Serialises [`restore_terminal`] so concurrent teardowns cannot interleave +/// their escape sequences on one stdout. +/// +/// Distinct from [`SHUTTING_DOWN`], and deliberately so: the latch answers "is +/// the process exiting" (one-shot, never released, gates rendering), this +/// answers "is someone writing the restore right now" (re-armable, held for the +/// length of one teardown). Conflating them is what made a clean session exit +/// permanently wedge the launcher hub. +static RESTORE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// Write the escape sequences that undo `run`'s terminal setup — leave the /// alternate screen, disable mouse capture, show the cursor — to `out`. Split /// from [`restore_terminal`] so a unit test can drive an in-memory sink and @@ -1923,6 +1976,15 @@ pub fn spawn_termination_watcher() -> color_eyre::Result AppState { let mut s = AppState::new("t".into(), "default-dark".into()); s.latest = Some(Snapshot { diff --git a/crates/rocm-dash-tui/src/ui/modal.rs b/crates/rocm-dash-tui/src/ui/modal.rs index dfe02fa811..12fb130b43 100644 --- a/crates/rocm-dash-tui/src/ui/modal.rs +++ b/crates/rocm-dash-tui/src/ui/modal.rs @@ -25,6 +25,7 @@ use crate::ui::theme::{self, Theme}; pub fn centered_rect(pct_x: u16, pct_y: u16, max_w: u16, max_h: u16, area: Rect) -> Rect { let h_pct = (area.height * pct_y / 100).min(max_h).max(5); let v_pad = (area.height.saturating_sub(h_pct)) / 2; + let w_pct = centered_width(pct_x, max_w, area); let vert = Layout::default() .direction(Direction::Vertical) .constraints([ @@ -34,7 +35,6 @@ pub fn centered_rect(pct_x: u16, pct_y: u16, max_w: u16, max_h: u16, area: Rect) ]) .split(area); - let w_pct = (area.width * pct_x / 100).min(max_w).max(20); let h_pad = (area.width.saturating_sub(w_pct)) / 2; let horiz = Layout::default() .direction(Direction::Horizontal) @@ -48,6 +48,13 @@ pub fn centered_rect(pct_x: u16, pct_y: u16, max_w: u16, max_h: u16, area: Rect) horiz[1] } +/// Width [`centered_rect`] will give a popup, split out so a caller that needs +/// to lay its content out *before* the popup exists (to size the popup to that +/// content) cannot drift from the real geometry. +pub fn centered_width(pct_x: u16, max_w: u16, area: Rect) -> u16 { + (area.width * pct_x / 100).min(max_w).max(20) +} + /// Render a bordered block with `title` over `area` after clearing it, /// returning the inner area so the caller can render content into it. pub fn draw_popup_frame(f: &mut Frame, area: Rect, title: &str, theme: &Theme) -> Rect { @@ -80,10 +87,16 @@ pub fn draw_scrollable_lines( } /// Render the Help modal for the active tab. +/// +/// The popup is sized to the height its *wrapped* content actually needs, +/// clamped to `area`, rather than to a fixed share of the screen. A fixed share +/// silently truncated: at the 80x24 the e2e lane pins, the body is 20 rows, 70% +/// of that is 14, and two of the key hints wrap to a second line — so the modal +/// ended mid-list at `{ / }` and the per-tab guidance below it was never drawn, +/// with no scrollbar or indicator to say so. Content-sizing keeps every hint on +/// screen wherever the room exists, and adding a hint can no longer push an +/// unrelated one off the bottom. pub fn draw_help(f: &mut Frame, area: Rect, tab: ActiveTab, theme: &Theme) { - let popup = centered_rect(70, 70, 80, 22, area); - let inner = draw_popup_frame(f, popup, "Help", theme); - let mut lines: Vec = vec![ key_line("q", "quit", theme), // Ctrl-C is a first-class quit gesture in both key loops (it restores the @@ -146,6 +159,19 @@ pub fn draw_help(f: &mut Frame, area: Rect, tab: ActiveTab, theme: &Theme) { } let p = Paragraph::new(lines).wrap(Wrap { trim: false }); + + // Width first — it does not depend on the height — then ask the paragraph + // how many rows it wraps to at that width. `line_count` is the renderer's + // own wrap, not an estimate of it, so this cannot drift from what lands on + // screen. `pct_y = 100` with `max_h = needed` means "exactly the content, + // or the whole area when the content is taller than it". + let width = centered_width(70, 80, area); + let needed = u16::try_from(p.line_count(width.saturating_sub(2))) + .unwrap_or(u16::MAX) + .saturating_add(2); + let popup = centered_rect(70, 100, 80, needed, area); + let inner = draw_popup_frame(f, popup, "Help", theme); + f.render_widget(p, inner); } @@ -878,4 +904,68 @@ mod ported_chrome_tests { assert!(out.contains("tokyo"), "value missing: {out:?}"); assert!(out.contains('▸'), "focus/control marker missing: {out:?}"); } + + /// The help modal must show ALL of its content at the smallest geometry the + /// product supports, not as much of it as a fixed share of the screen + /// happens to fit. + /// + /// Regression: adding the Ctrl-C hint pushed the per-tab guidance off the + /// bottom at 80x24 and nothing said so — the modal just ended mid-list at + /// `{ / }`. That reached CI as an e2e failure on an assertion about + /// unrelated text ("Home tab"), because no unit test asserted the modal's + /// last row was reachable. + /// + /// 80x20 is the *body* rect `ui::draw` hands `draw_help` on the 80x24 the + /// e2e lane pins (3-row header, 1-row footer), so this is the real + /// worst-case geometry rather than an invented one. + #[test] + fn help_modal_shows_every_hint_at_the_minimum_supported_geometry() { + use crate::app::ActiveTab; + let theme = Theme::from_name("default-dark"); + let area = Rect::new(0, 0, 80, 20); + let backend = TestBackend::new(80, 20); + let mut term = Terminal::new(backend).unwrap(); + term.draw(|f| super::draw_help(f, area, ActiveTab::Home, &theme)) + .unwrap(); + let out = flat(&term); + + // First hint, the hint that wraps, the last global hint, and the per-tab + // section that used to fall off the bottom. The last two are the ones + // that regress when the modal is sized to anything but its content. + for needle in [ + "quit", + "Ctrl-C", + "toggle this help", + "next / previous tab", + "jump ±60s", + "Home tab", + "no tab-specific keys", + ] { + assert!( + out.contains(needle), + "help modal truncated before {needle:?} at 80x20:\n{out}" + ); + } + } + + /// A modal taller than the space available must be clamped to the area, not + /// allowed to run off it. Content-sizing the popup is only safe if this + /// holds. + #[test] + fn help_modal_is_clamped_when_the_content_cannot_fit() { + use crate::app::ActiveTab; + let theme = Theme::from_name("default-dark"); + let area = Rect::new(0, 0, 80, 10); + let backend = TestBackend::new(80, 10); + let mut term = Terminal::new(backend).unwrap(); + // The assertion is that this does not panic on an out-of-bounds rect and + // still paints the top of the list. + term.draw(|f| super::draw_help(f, area, ActiveTab::Chat, &theme)) + .unwrap(); + let out = flat(&term); + assert!( + out.contains("Ctrl-C"), + "clamped modal painted nothing:\n{out}" + ); + } } From ba6d16105488a25753a2f9917239476142f414a9 Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Tue, 15 Sep 2026 17:42:25 +0300 Subject: [PATCH 10/13] test(dash): replace a help-modal test that could not fail, and content-size the global help MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `help_modal_is_clamped_when_the_content_cannot_fit` claimed to verify that a modal taller than its area is clamped to it. It could not fail: that property is ratatui's, not this crate's — `Layout::split` structurally cannot emit a segment larger than its input area, so the popup is bounded no matter what `centered_rect` computes. Confirmed by re-running the mutation that motivated the finding — replacing the whole area-relative clamp with `max_h.max(5)` still leaves the suite green (743 passed, 0 failed). Replace it with assertions on properties this crate does own: - `help_modal_is_sized_to_exactly_its_content_on_every_tab` — on all five tabs at a roomy geometry, the last hint lands on the row directly above the bottom border: nothing evicted before it, no filler row after it. This generalises the single-geometry, single-tab sibling test into the arithmetic itself. - `help_modal_fills_every_available_row_when_the_content_cannot_fit` — the honest half of "clamped": when the content cannot fit, the modal takes every row of the area rather than a fixed share, which is what `pct_y = 100` buys. - `global_help_is_sized_to_its_content_and_evicts_nothing` - `centered_rect_does_not_overflow_on_a_very_tall_or_wide_area` `draw_global_help` still had the fixed-percentage, no-scrollbar shape that had just truncated `draw_help`, and this PR adds a hint to it. At the 80x24 the e2e lane pins it had zero rows of margin (14 available, 14 needed); on a 120x30 terminal it drew ten blank rows. Content-size it the same way, measuring each column at the width the 50/50 split actually hands it, and move the blank group separator between groups so there is no trailing filler row. `area.height * pct_y / 100` in `centered_rect` overflows a u16 above 655 rows now that `draw_help` passes `pct_y = 100` — a debug-build panic on a tall terminal. Widen the product to u32 in a shared `scale_pct` rather than leaving each caller to know where the ceiling is. Also, from the same review: - README overstated Ctrl-C as *always* quitting; state the running-job-console exception the code and both help modals already document. - `debug_assert` the invariant `ctrl_c_should_exit` leans on — that an `active_job` id resolves in the jobs map — so a manager that breaks the pairing trips the suite instead of silently making Ctrl-C quit out from under a running job. - Note at the signal test that its expectation is built from the same `EXIT_CODE_*` constants it checks, so it pins the mapping but not the literal 130/143, which the e2e scenarios pin. - Note that `Paragraph::line_count` (ratatui's `unstable-rendered-line-info`) is now load-bearing for layout, not just scroll bounds. Falsification: `+2` -> `+1` on the popup height, `+2` -> `+3`, measuring at the popup width instead of the inner width, `pct_y` 100 -> 70, reverting `scale_pct` to u16, and reverting `draw_global_help` to the fixed 26-row shape each turn the covering test(s) red; restoring gives 743 passed, 0 failed. The `+2` -> `+3` filler mutation is caught only by the new tests — the pre-existing `help_modal_shows_every_hint_at_the_minimum_supported_geometry` stays green — so this is added coverage, not a rename. Signed-off-by: Roman Sirokov --- README.md | 11 +- crates/rocm-dash-tui/src/app/mod.rs | 29 ++- crates/rocm-dash-tui/src/ui/modal.rs | 294 +++++++++++++++++++++++---- 3 files changed, 286 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 1b1eed3793..bf5c05e454 100644 --- a/README.md +++ b/README.md @@ -155,10 +155,13 @@ small front-door menu that gets you to the common tasks: - **Chat** — talk to a local or API-backed model - **Open full dashboard →** — escalate into the live dashboard (`rocm dash`) -Pick a row with the arrow keys and `Enter`; press `q` — or `Ctrl-C`, which works -in the launcher and the dashboard alike and always restores your terminal — to -quit. On a non-interactive terminal (or piped output), `rocm` prints a one-shot -status summary instead of opening the launcher. +Pick a row with the arrow keys and `Enter`; press `q` — or `Ctrl-C`, which quits +from the launcher and the dashboard alike and restores your terminal — to quit. +The one exception is the dashboard's console for a **running** job, where +`Ctrl-C` keeps its existing meaning of "cancel this job" and does not quit; once +that job finishes, `Ctrl-C` quits there too. On a non-interactive terminal (or +piped output), `rocm` prints a one-shot status summary instead of opening the +launcher. ## Interactive interfaces diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index 1fe9b80235..a1fe064a4b 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -2057,12 +2057,23 @@ pub(crate) const fn is_ctrl_c(k: KeyEvent) -> bool { /// on the job being non-terminal keeps "cancel the job" winning only while there /// is a job left to cancel. fn ctrl_c_should_exit(state: &AppState, k: KeyEvent) -> bool { + let job = state.active_job_id().and_then(|id| state.jobs.job(id)); + // The uncodified invariant this predicate leans on: a manager's `active_job` + // is the id of a job it just spawned into `state.jobs`, so the lookup above + // resolves. Thirteen manager modules set `active_job`; nothing enforces the + // pairing at a type level. If it ever breaks, `is_none_or` below silently + // reads "no job console is up" and Ctrl-C would quit out from under a + // *running* job — the one case this function exists to prevent. Assert it in + // debug builds so a manager that sets an id without a matching job trips the + // suite rather than shipping the wrong precedence. + debug_assert!( + state.active_job_id().is_none() || job.is_some(), + "active_job id {:?} is not in the jobs map; ctrl_c_should_exit would \ + treat a live job console as absent", + state.active_job_id() + ); // Reads as: no job console is up, or the one that is has already finished. - is_ctrl_c(k) - && state - .active_job_id() - .and_then(|id| state.jobs.job(id)) - .is_none_or(rocm_dash_core::state::JobState::is_terminal) + is_ctrl_c(k) && job.is_none_or(rocm_dash_core::state::JobState::is_terminal) } /// End the process from a typed Ctrl-C, taking exactly the path an externally @@ -4467,6 +4478,14 @@ mod tests { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); signal_test_runtime().block_on(async { + // Scope, so nobody reads more into this than it proves: the + // expectation is built from the same `EXIT_CODE_*` constants the + // code under test returns, so this pins the SIGTERM→sigterm-code / + // SIGINT→sigint-code *mapping* (swapping the two arms turns it red) + // but not the literal values. Editing `EXIT_CODE_SIGINT` to 7 leaves + // this green. The literals 130/143 are pinned by the e2e scenarios + // `dash-12` … `dash-16` in `tests/e2e-cucumber/features/dash.feature`, + // which assert the shell-visible exit status of a real process. for (signo, expected) in [ (libc::SIGTERM, EXIT_CODE_SIGTERM), (libc::SIGINT, EXIT_CODE_SIGINT), diff --git a/crates/rocm-dash-tui/src/ui/modal.rs b/crates/rocm-dash-tui/src/ui/modal.rs index 12fb130b43..91a277ae8b 100644 --- a/crates/rocm-dash-tui/src/ui/modal.rs +++ b/crates/rocm-dash-tui/src/ui/modal.rs @@ -20,10 +20,23 @@ use crate::ui::panel::{self, BoxRole}; use crate::ui::sparkline::BrailleSparkline; use crate::ui::theme::{self, Theme}; +/// `extent * pct / 100`, computed in `u32` so the intermediate product cannot +/// overflow a `u16`. +/// +/// `area.height * pct_y` overflows above 655 rows once `pct_y` is 100 — which +/// [`draw_help`] now passes, to mean "the whole area when the content is taller +/// than it". That is a debug-build panic on a terminal tall enough (tmux panes +/// and some GUI terminals report large synthetic sizes), and a wrap-around in +/// release. Widening here removes the ceiling for every caller rather than +/// leaving each one to know where it is. +fn scale_pct(extent: u16, pct: u16) -> u16 { + u16::try_from(u32::from(extent) * u32::from(pct) / 100).unwrap_or(u16::MAX) +} + /// Centered rectangle taking `pct_x`% width and `pct_y`% height of `area`, /// clamped to a maximum so it doesn't drown the screen on big terminals. pub fn centered_rect(pct_x: u16, pct_y: u16, max_w: u16, max_h: u16, area: Rect) -> Rect { - let h_pct = (area.height * pct_y / 100).min(max_h).max(5); + let h_pct = scale_pct(area.height, pct_y).min(max_h).max(5); let v_pad = (area.height.saturating_sub(h_pct)) / 2; let w_pct = centered_width(pct_x, max_w, area); let vert = Layout::default() @@ -52,7 +65,7 @@ pub fn centered_rect(pct_x: u16, pct_y: u16, max_w: u16, max_h: u16, area: Rect) /// to lay its content out *before* the popup exists (to size the popup to that /// content) cannot drift from the real geometry. pub fn centered_width(pct_x: u16, max_w: u16, area: Rect) -> u16 { - (area.width * pct_x / 100).min(max_w).max(20) + scale_pct(area.width, pct_x).min(max_w).max(20) } /// Render a bordered block with `title` over `area` after clearing it, @@ -164,17 +177,34 @@ pub fn draw_help(f: &mut Frame, area: Rect, tab: ActiveTab, theme: &Theme) { // how many rows it wraps to at that width. `line_count` is the renderer's // own wrap, not an estimate of it, so this cannot drift from what lands on // screen. `pct_y = 100` with `max_h = needed` means "exactly the content, - // or the whole area when the content is taller than it". + // or the whole area when the content is taller than it". `+ 2` is the + // popup's top and bottom border rows; `- 2` on the width is the left and + // right ones. + // + // `line_count` sits behind ratatui's `unstable-rendered-line-info` feature + // (already enabled in this crate's Cargo.toml for the scroll bounds). It is + // now load-bearing for *layout*, not just for how far a scrollbar may + // travel: if a ratatui release changes or withdraws it, this modal silently + // mis-sizes rather than merely mis-scrolling. + // `help_modal_is_sized_to_exactly_its_content_on_every_tab` (in this + // module's `ported_chrome_tests`) is the tripwire for that. let width = centered_width(70, 80, area); - let needed = u16::try_from(p.line_count(width.saturating_sub(2))) - .unwrap_or(u16::MAX) - .saturating_add(2); + let needed = popup_height_for(p.line_count(width.saturating_sub(2))); let popup = centered_rect(70, 100, 80, needed, area); let inner = draw_popup_frame(f, popup, "Help", theme); f.render_widget(p, inner); } +/// Popup height that shows `content_rows` rows of wrapped content: the content +/// plus the popup's top and bottom border rows. Shared by [`draw_help`] and +/// [`draw_global_help`] so the two content-sized modals cannot drift apart. +fn popup_height_for(content_rows: usize) -> u16 { + u16::try_from(content_rows) + .unwrap_or(u16::MAX) + .saturating_add(2) +} + fn key_line<'a>(key: &'a str, desc: &'a str, theme: &Theme) -> Line<'a> { Line::from(vec![ Span::styled( @@ -590,18 +620,16 @@ pub fn draw_options(f: &mut Frame, area: Rect, state: &AppState, theme: &Theme) /// Global 2-column keyboard reference (NAVIGATE / OVERLAYS / ACTIONS / CHAT / /// GLOBAL). Distinct from the contextual per-tab `?` help (`draw_help`). +/// +/// Content-sized exactly like [`draw_help`], and for the same reason. The old +/// fixed `centered_rect(80, 80, 100, 26, area)` shape truncated silently, with +/// no scrollbar and no indicator: at the 80x24 the e2e lane pins it had *zero* +/// rows of margin (14 available, 14 needed), so the Ctrl-C hint this PR adds to +/// the right-hand column landed on the last usable row and one more hint — or +/// one more wrap, from a wording change — would have pushed it off. On a roomy +/// terminal the same fixed shape drew ten blank rows below the content. pub fn draw_global_help(f: &mut Frame, area: Rect, theme: &Theme) { grey_overlay(f); - let modal = centered_rect(80, 80, 100, 26, area); - let inner = draw_popup_frame(f, modal, "Keyboard", theme); - if inner.height == 0 { - return; - } - f.render_widget(Clear, inner); - let cols = Layout::default() - .direction(Direction::Horizontal) - .constraints([Constraint::Percentage(50), Constraint::Percentage(50)]) - .split(inner); let left: &[(&str, &[(&str, &str)])] = &[ ( "NAVIGATE", @@ -639,18 +667,56 @@ pub fn draw_global_help(f: &mut Frame, area: Rect, theme: &Theme) { ], ), ]; - render_help_groups(f, cols[0], left, theme); - render_help_groups(f, cols[1], right, theme); + let left_p = Paragraph::new(help_group_lines(left, theme)).wrap(Wrap { trim: false }); + let right_p = Paragraph::new(help_group_lines(right, theme)).wrap(Wrap { trim: false }); + + // Width first, then the height the *taller* column wraps to at the width + // the 50/50 split will actually hand it. The split is run here on a stand-in + // rect rather than the ratio being re-derived by hand, so the measurement + // cannot drift from the render below. + let width = centered_width(80, 100, area); + let measure = help_columns(Rect::new(0, 0, width.saturating_sub(2), 1)); + let needed = popup_height_for( + left_p + .line_count(measure[0].width) + .max(right_p.line_count(measure[1].width)), + ); + + let modal = centered_rect(80, 100, 100, needed, area); + let inner = draw_popup_frame(f, modal, "Keyboard", theme); + if inner.height == 0 { + return; + } + f.render_widget(Clear, inner); + let cols = help_columns(inner); + f.render_widget(left_p, cols[0]); + f.render_widget(right_p, cols[1]); } -fn render_help_groups( - f: &mut Frame, - area: Rect, - groups: &[(&str, &[(&str, &str)])], +/// The two equal columns [`draw_global_help`] lays its groups out in. Returned +/// as an array so the same split serves both the measure and the render. +fn help_columns(area: Rect) -> [Rect; 2] { + let cols = Layout::default() + .direction(Direction::Horizontal) + .constraints([Constraint::Percentage(50), Constraint::Percentage(50)]) + .split(area); + [cols[0], cols[1]] +} + +/// Titled key/description groups as renderable lines. +/// +/// The blank separator sits *between* groups, not after each one: a trailing +/// blank would make the content-sized popup one row taller than its content and +/// show as a gap above the bottom border. +fn help_group_lines<'a>( + groups: &'a [(&'a str, &'a [(&'a str, &'a str)])], theme: &Theme, -) { +) -> Vec> { let mut lines: Vec = Vec::new(); - for (title, rows) in groups { + for (i, (title, rows)) in groups.iter().enumerate() { + if i > 0 { + lines.push(Line::raw("")); + } lines.push(Line::from(Span::styled( *title, Style::default() @@ -660,9 +726,8 @@ fn render_help_groups( for (k, desc) in *rows { lines.push(key_line(k, desc, theme)); } - lines.push(Line::raw("")); } - f.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), area); + lines } // =========================================================================== @@ -948,24 +1013,175 @@ mod ported_chrome_tests { } } - /// A modal taller than the space available must be clamped to the area, not - /// allowed to run off it. Content-sizing the popup is only safe if this - /// holds. + /// Render `draw` onto a fresh `w`x`h` backend and return it row by row, + /// trailing blanks trimmed. Row structure is what the sizing tests below + /// assert on — `flat` throws it away. + fn rows(w: u16, h: u16, draw: impl Fn(&mut ratatui::Frame)) -> Vec { + let backend = TestBackend::new(w, h); + let mut term = Terminal::new(backend).unwrap(); + term.draw(|f| draw(f)).unwrap(); + let buf = term.backend().buffer(); + (0..h) + .map(|y| { + (0..w) + .map(|x| buf[(x, y)].symbol()) + .collect::() + .trim_end() + .to_string() + }) + .collect() + } + + /// Index of the popup's bottom border row (the rounded bottom-left corner). + fn bottom_border_row(rows: &[String]) -> usize { + rows.iter() + .position(|r| r.contains('╰')) + .unwrap_or_else(|| panic!("no popup bottom border was painted:\n{}", rows.join("\n"))) + } + + /// The popup is sized to *exactly* its wrapped content whenever the area has + /// room: the last hint lands on the row directly above the bottom border, + /// with no filler row after it and nothing evicted before it. + /// + /// This is the property the crate actually owns — `needed` is computed here + /// from `Paragraph::line_count` and handed to `centered_rect` as `max_h`. + /// (That a popup cannot overrun its area is ratatui's own guarantee: + /// `Layout::split` structurally cannot emit a segment larger than its input, + /// so asserting it here would constrain no branch of this module.) + /// + /// Checked on every tab, because each has a different hint list and a + /// different set of lines that wrap; the sibling test above pins a single + /// geometry on a single tab. #[test] - fn help_modal_is_clamped_when_the_content_cannot_fit() { + fn help_modal_is_sized_to_exactly_its_content_on_every_tab() { use crate::app::ActiveTab; let theme = Theme::from_name("default-dark"); + // (tab, the tail of that tab's LAST hint — the text that must land on + // the row immediately above the bottom border). Several of these are + // wrap continuations, which is the point: the sizing has to account for + // the renderer's own wrapping, not the unwrapped line count. + let cases = [ + (ActiveTab::Home, "Serving tabs)"), + (ActiveTab::Rocm, "Actions)"), + (ActiveTab::Serving, "Actions)"), + (ActiveTab::Observe, "update / install / logs"), + (ActiveTab::Chat, "focused)"), + ]; + for (tab, tail) in cases { + // Tall enough that every tab's help fits with room to spare, so any + // mismatch is the sizing arithmetic and not the clamp. + let area = Rect::new(0, 0, 80, 44); + let painted = rows(80, 44, |f| super::draw_help(f, area, tab, &theme)); + let bottom = bottom_border_row(&painted); + let last = &painted[bottom - 1]; + assert!( + last.contains(tail), + "{tab:?}: the last hint must sit directly above the bottom \ + border, but row {} is {last:?} (expected it to contain \ + {tail:?}) — the popup is over- or under-sized for its \ + content:\n{}", + bottom - 1, + painted.join("\n") + ); + } + } + + /// When the content genuinely cannot fit, the modal takes **every** row of + /// the area rather than a fixed share of it, so the most hints the terminal + /// can hold are shown. This is what `pct_y = 100` buys over the old 70%. + #[test] + fn help_modal_fills_every_available_row_when_the_content_cannot_fit() { + use crate::app::ActiveTab; + let theme = Theme::from_name("default-dark"); + // Chat has the longest hint list; at 10 rows it cannot fit by a wide + // margin, so the popup is clamp-bound rather than content-bound. let area = Rect::new(0, 0, 80, 10); - let backend = TestBackend::new(80, 10); - let mut term = Terminal::new(backend).unwrap(); - // The assertion is that this does not panic on an out-of-bounds rect and - // still paints the top of the list. - term.draw(|f| super::draw_help(f, area, ActiveTab::Chat, &theme)) - .unwrap(); - let out = flat(&term); + let painted = rows(80, 10, |f| { + super::draw_help(f, area, ActiveTab::Chat, &theme); + }); + assert!( + painted[0].contains('╭'), + "the modal must start on the first row of the area:\n{}", + painted.join("\n") + ); + assert_eq!( + bottom_border_row(&painted), + 9, + "the modal must end on the last row of the area, using all 10 rows \ + rather than a fixed share of them:\n{}", + painted.join("\n") + ); + // Eight inner rows, so eight wrapped hint rows: `q`, the two the Ctrl-C + // hint wraps to, `?`, Tab, `1 .. 5`, `t`, Space. A 70% share would stop + // five rows in, at `next / previous tab`. assert!( - out.contains("Ctrl-C"), - "clamped modal painted nothing:\n{out}" + painted[8].contains("pause / resume"), + "a full-height modal must paint every row it has:\n{}", + painted.join("\n") ); } + + /// The global keyboard reference is content-sized the same way `draw_help` + /// is: no filler rows on a roomy terminal, and — the regression that + /// matters — nothing silently evicted at the smallest geometry the product + /// supports, where the fixed 80%-of-area shape had zero rows of margin and + /// this PR added a hint to it. + #[test] + fn global_help_is_sized_to_its_content_and_evicts_nothing() { + let theme = Theme::from_name("default-dark"); + // 80x20 is the body rect on the 80x24 the e2e lane pins; 120x30 is a + // roomy terminal, where a fixed 26-row modal left ten blank rows. + for (w, h) in [(80u16, 20u16), (120, 30)] { + let area = Rect::new(0, 0, w, h); + let painted = rows(w, h, |f| super::draw_global_help(f, area, &theme)); + let bottom = bottom_border_row(&painted); + let last = painted[bottom - 1].trim_end(); + assert!( + last.ends_with('│'), + "{w}x{h}: the modal's last row must be content, not filler, but \ + row {} is {last:?}:\n{}", + bottom - 1, + painted.join("\n") + ); + assert!( + last.trim_matches(['│', ' ']).chars().count() > 0, + "{w}x{h}: the row above the bottom border is blank — the popup \ + is taller than its content:\n{}", + painted.join("\n") + ); + let flat = painted.join(""); + for needle in [ + "NAVIGATE", + "OVERLAYS", + "ACTIONS", + "CHAT / GLOBAL", + "main menu", + "cancels a running", + ] { + assert!( + flat.contains(needle), + "{w}x{h}: the keyboard reference is truncated before \ + {needle:?}:\n{}", + painted.join("\n") + ); + } + } + } + + /// `centered_rect` scales a percentage of the area, and `area.height` is a + /// `u16`. Since `draw_help` passes `pct_y = 100`, a `u16` product overflows + /// above 655 rows — a debug-build panic on a tall terminal. The arithmetic + /// widens to `u32` so no caller has to know where the ceiling is. + #[test] + fn centered_rect_does_not_overflow_on_a_very_tall_or_wide_area() { + for (w, h) in [(2000u16, 2000u16), (u16::MAX, u16::MAX)] { + let area = Rect::new(0, 0, w, h); + let r = super::centered_rect(100, 100, u16::MAX, u16::MAX, area); + assert!( + r.height <= h && r.width <= w, + "centered_rect({w}x{h}) escaped its area: {r:?}" + ); + assert_eq!(super::centered_width(100, u16::MAX, area), w); + } + } } From 52cb544003c048142b2e92582f6febcc209329e8 Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Tue, 15 Sep 2026 19:11:24 +0300 Subject: [PATCH 11/13] fix(dash): clamp the popup width floor, and mark a help modal that still truncates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up on this PR's content-sizing change. Two behavioural fixes and three documentation corrections; no change to key precedence. `centered_width`'s 20-column minimum could exceed `area.width`, returning a width the popup can never have — `centered_rect`'s `Layout::split` truncates the segment to the area. That was harmless while the number was only used to render, but both help modals now *measure* their wrapped content against it before the popup exists, so on a terminal under 20 columns they counted rows at 20 and rendered at 12: an under-count that cuts the tail off, which is exactly the silent truncation content-sizing was added to remove. The floor is now clamped to the area, so the measured width is the rendered width everywhere. When the content still cannot fit at full height the modal used every row and truncated with no scrollbar and no indicator — the same shape the new doc comment calls the original defect. These modals are sized, not scrolled, so there is nothing to scroll and nothing to press: the honest option is to say so. `help_title` marks the border title in that case, chosen over a body marker because a body marker would evict a hint to announce that hints were evicted. The marker is dropped (falling back to the plain title) on a popup too narrow for it, since `stamp_title` drops an oversized title rather than overflowing the border; that residual is documented rather than claimed away. `panel::title_fits` exposes that arithmetic so the caller asks instead of re-deriving it, and `stamp_title` now uses the same predicate. Documentation only, no behaviour change: - `press_ctrl_c_and_wait` claimed the keystroke/signal distinction was "the point", but the outcome assertions (130 + terminal restored) are identical either way. The doc now states what actually discriminates — deleting the key-event arm raises no signal, so the process never exits and the step fails on its timeout — and admits what it cannot prove: a build that failed to enter raw mode would let the tty synthesise SIGINT and still pass. - `wait_for_exit_code` now drains the final frame on every path, including `wait_for_exit`/`quit_and_wait` callers this PR never intended to touch. The cost is recorded next to the code (normally one poll interval; `DRAIN_TIMEOUT` is the ceiling). - The Ctrl-C-over-approval precedence is unchanged and correct — `approval_key` ignores Ctrl-C, so without the arm above it the gesture would be a silent no-op on exactly the screen where a user most wants out. The comment now spells the consequence out for someone who meets it by surprise, notes that the pending action has not run so quitting and declining leave identical state, and names the modal's own decline keys. Tests, both falsified against the code they cover: - `popup_width_is_never_wider_than_a_narrow_area` sweeps 0..=24 columns for both live `(pct_x, max_w)` pairs, asserting the measured width is <= the area and equal to the width `centered_rect` hands back. Restoring the unclamped floor fails it at 12 columns as well as at 0. - `help_modals_mark_the_title_when_the_content_still_cannot_fit` asserts the marker appears at 80x10 for both modals and does not appear at 80x44 / 80x20 / 120x30. It fails in both directions: never marking, and always marking. Verified on Linux: `cargo test -p rocm-dash-tui --all-targets`, `cargo test --workspace --all-targets`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo clippy -p e2e-cucumber --test e2e -- -D warnings`, and the 16 `dash-*` e2e scenarios (100 steps, all passing). Signed-off-by: Roman Sirokov --- crates/rocm-dash-tui/src/app/mod.rs | 21 ++++ crates/rocm-dash-tui/src/ui/modal.rs | 137 ++++++++++++++++++++- crates/rocm-dash-tui/src/ui/panel.rs | 26 +++- tests/e2e-cucumber/tests/e2e/tui_driver.rs | 45 +++++-- 4 files changed, 210 insertions(+), 19 deletions(-) diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index a1fe064a4b..eaf8e0d729 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -2556,6 +2556,27 @@ async fn event_loop(terminal: &mut Tui, args: &ResolvedArgs) -> color_eyre::Resu // (above every operational overlay and the general handler) // so the operator's decision can't be pre-empted by a screen // behind it. Only the Ctrl-C arm above outranks it. + // + // Spelling out the consequence, because it is the one that + // surprises: a typed Ctrl-C while an approval is pending + // QUITS the dashboard. It is not consumed by the modal and + // it is not a decline. That is deliberate — Ctrl-C is the + // gesture a user reaches for to get out of a program, and a + // modal that swallowed it would recreate the wedge this PR + // fixes (the pre-fix dashboard ignored Ctrl-C entirely and + // left the user in a raw-mode terminal), which is worse here + // than anywhere: the approval modal is exactly where someone + // wants out in a hurry. Nothing is lost by quitting — the + // pending action has NOT run (approval is what would run + // it), so declining and quitting leave identical state on + // disk; only the chat turn differs. The help surfaces say + // "quit" for Ctrl-C without exception for this modal, which + // is therefore accurate. + // + // To decline without quitting there are `n` (deny) and + // `Esc` / `q` (cancel) — `ui::approval::approval_key`, which + // ignores Ctrl-C, so without the arm above the gesture would + // be a silent no-op on this screen. // On Approve: replay the approved action off the // event loop (spawn_blocking) and post ChatApprovalResult. // On Deny/Cancel: a declined turn, no execution. diff --git a/crates/rocm-dash-tui/src/ui/modal.rs b/crates/rocm-dash-tui/src/ui/modal.rs index 91a277ae8b..29f2af185b 100644 --- a/crates/rocm-dash-tui/src/ui/modal.rs +++ b/crates/rocm-dash-tui/src/ui/modal.rs @@ -61,11 +61,26 @@ pub fn centered_rect(pct_x: u16, pct_y: u16, max_w: u16, max_h: u16, area: Rect) horiz[1] } +/// Narrowest a popup is allowed to be shrunk to by the percentage, so a modal +/// on a merely small terminal is still wide enough to read. +const MIN_POPUP_WIDTH: u16 = 20; + /// Width [`centered_rect`] will give a popup, split out so a caller that needs /// to lay its content out *before* the popup exists (to size the popup to that /// content) cannot drift from the real geometry. +/// +/// The [`MIN_POPUP_WIDTH`] floor is itself clamped to `area.width`, which is the +/// difference between a number the popup might get and the number it *will* +/// get. An unclamped floor returns 20 on a terminal narrower than 20 — a width +/// the popup can never have, because [`centered_rect`]'s `Layout::split` +/// truncates the segment to the area. That is harmless for a caller that only +/// renders, but both help modals now *measure* their wrapped content against +/// this width before the popup exists: measuring the wrap at 20 columns and +/// rendering it into 12 under-counts the rows the content needs and cuts the +/// tail off — the precise silent truncation content-sizing was added to remove. pub fn centered_width(pct_x: u16, max_w: u16, area: Rect) -> u16 { - scale_pct(area.width, pct_x).min(max_w).max(20) + let floor = MIN_POPUP_WIDTH.min(area.width); + scale_pct(area.width, pct_x).min(max_w).max(floor) } /// Render a bordered block with `title` over `area` after clearing it, @@ -109,6 +124,12 @@ pub fn draw_scrollable_lines( /// with no scrollbar or indicator to say so. Content-sizing keeps every hint on /// screen wherever the room exists, and adding a hint can no longer push an /// unrelated one off the bottom. +/// +/// Where the room does *not* exist — a terminal too short for the hint list even +/// at full height — the content is still cut, and the modal does not scroll. +/// [`help_title`] marks the title in that case rather than leaving the user to +/// guess, which is the whole of what is claimed here: an honest indicator, not a +/// guarantee that everything is visible. pub fn draw_help(f: &mut Frame, area: Rect, tab: ActiveTab, theme: &Theme) { let mut lines: Vec = vec![ key_line("q", "quit", theme), @@ -191,11 +212,39 @@ pub fn draw_help(f: &mut Frame, area: Rect, tab: ActiveTab, theme: &Theme) { let width = centered_width(70, 80, area); let needed = popup_height_for(p.line_count(width.saturating_sub(2))); let popup = centered_rect(70, 100, 80, needed, area); - let inner = draw_popup_frame(f, popup, "Help", theme); + let inner = draw_popup_frame(f, popup, &help_title("Help", needed, popup), theme); f.render_widget(p, inner); } +/// Title for a content-sized help popup, marked when the content did not fit. +/// +/// `needed` is the height the wrapped content asked for; `popup` is what the +/// area could actually give it. When the popup is shorter, the tail of the +/// content is off-screen — and these modals are *sized*, not scrolled, so there +/// is no scrollbar, no scroll position, and nothing the user can press to see +/// the rest. Saying so is the only honest option left; the alternative is the +/// silent truncation this module's doc comments call the original defect. +/// +/// The marker goes in the border title rather than the body because a body +/// marker would cost a content row on precisely the terminal that has none to +/// spare — it would evict a hint to announce that hints were evicted. +/// +/// Residual, stated rather than papered over: [`panel::title_fits`] is false on +/// a popup too narrow for the marked form, and a title that does not fit is +/// dropped rather than overflowing the border. Rather than lose the plain +/// "Help" as well, the bare title is used there and the truncation goes +/// unmarked. That is a popup under ~30 columns, i.e. a terminal well below +/// anything the dashboard lays out usefully. +fn help_title(base: &str, needed: u16, popup: Rect) -> String { + let marked = format!("{base} (truncated — resize)"); + if needed > popup.height && panel::title_fits(popup.width, &marked) { + marked + } else { + base.to_string() + } +} + /// Popup height that shows `content_rows` rows of wrapped content: the content /// plus the popup's top and bottom border rows. Shared by [`draw_help`] and /// [`draw_global_help`] so the two content-sized modals cannot drift apart. @@ -628,6 +677,10 @@ pub fn draw_options(f: &mut Frame, area: Rect, state: &AppState, theme: &Theme) /// the right-hand column landed on the last usable row and one more hint — or /// one more wrap, from a wording change — would have pushed it off. On a roomy /// terminal the same fixed shape drew ten blank rows below the content. +/// +/// Shares [`help_title`] with [`draw_help`], so the residual case — a terminal +/// too short even for the content-sized modal — is marked here the same way and +/// under the same caveat. pub fn draw_global_help(f: &mut Frame, area: Rect, theme: &Theme) { grey_overlay(f); let left: &[(&str, &[(&str, &str)])] = &[ @@ -683,7 +736,7 @@ pub fn draw_global_help(f: &mut Frame, area: Rect, theme: &Theme) { ); let modal = centered_rect(80, 100, 100, needed, area); - let inner = draw_popup_frame(f, modal, "Keyboard", theme); + let inner = draw_popup_frame(f, modal, &help_title("Keyboard", needed, modal), theme); if inner.height == 0 { return; } @@ -1168,6 +1221,84 @@ mod ported_chrome_tests { } } + /// The width the content-sized modals *measure* their wrapped content + /// against must be the width the popup actually gets. + /// + /// `centered_width`'s minimum-width floor is what can break that. On a + /// terminal narrower than the floor, an unclamped floor hands back a number + /// `centered_rect` then truncates (`Layout::split` cannot emit a segment + /// wider than its input), so `draw_help` / `draw_global_help` count the rows + /// their content wraps to at one width and render it at a narrower one — + /// under-counting the rows needed and cutting the tail off. That is the + /// silent truncation content-sizing exists to remove, re-introduced at a + /// geometry nothing else in this module exercises. + /// + /// Both live `(pct_x, max_w)` pairs are checked: `draw_help`'s 70/80 and + /// `draw_global_help`'s 80/100. + #[test] + fn popup_width_is_never_wider_than_a_narrow_area() { + for w in 0..=24u16 { + let area = Rect::new(0, 0, w, 40); + for (pct_x, max_w) in [(70u16, 80u16), (80, 100)] { + let measured = super::centered_width(pct_x, max_w, area); + assert!( + measured <= w, + "centered_width({pct_x}, {max_w}) returned {measured} on a \ + {w}-column area: the modals would measure their content at \ + a width the popup cannot have" + ); + assert_eq!( + super::centered_rect(pct_x, 100, max_w, 10, area).width, + measured, + "the popup's rendered width must equal the width its \ + content was measured against ({w}-column area)" + ); + } + } + } + + /// When the content still cannot fit at full height, the modal says so. + /// + /// It is sized, not scrolled: there is no scrollbar and nothing to press, so + /// an unmarked short modal is indistinguishable from a complete one. The + /// marker lives in the border title, which costs no content row. + #[test] + fn help_modals_mark_the_title_when_the_content_still_cannot_fit() { + use crate::app::ActiveTab; + let theme = Theme::from_name("default-dark"); + let painted = |w: u16, h: u16, global: bool| -> String { + let area = Rect::new(0, 0, w, h); + rows(w, h, |f| { + if global { + super::draw_global_help(f, area, &theme); + } else { + super::draw_help(f, area, ActiveTab::Chat, &theme); + } + }) + .join("\n") + }; + + // Ten rows holds neither hint list — the sibling test above pins that + // `draw_help` is clamp-bound here — so both must be marked. + for global in [false, true] { + let out = painted(80, 10, global); + assert!( + out.contains("truncated"), + "a modal that cut its content must say so (global={global}):\n{out}" + ); + } + // Roomy: every hint fits, so the marker must NOT appear — it would be a + // false alarm on the geometry the product is normally used at. + for (w, h, global) in [(80u16, 44u16, false), (80, 20, true), (120, 30, true)] { + let out = painted(w, h, global); + assert!( + !out.contains("truncated"), + "{w}x{h}: a modal that fits must not claim it was truncated \ + (global={global}):\n{out}" + ); + } + } + /// `centered_rect` scales a percentage of the area, and `area.height` is a /// `u16`. Since `draw_help` passes `pct_y = 100`, a `u16` product overflows /// above 655 rows — a debug-build panic on a tall terminal. The arithmetic diff --git a/crates/rocm-dash-tui/src/ui/panel.rs b/crates/rocm-dash-tui/src/ui/panel.rs index 90c4052625..ddb1b850ff 100644 --- a/crates/rocm-dash-tui/src/ui/panel.rs +++ b/crates/rocm-dash-tui/src/ui/panel.rs @@ -114,6 +114,24 @@ fn put(f: &mut Frame, x: u16, y: u16, text: &str, style: Style) { } } +/// Whether [`stamp_title`] has room to draw `title` on a box `area_width` +/// columns wide. +/// +/// The top row spends one column on each rounded corner, one on the dash before +/// the label, and one on each label bracket, so the label itself needs +/// `area_width - 4` columns. A title that does not fit is dropped rather than +/// overflowing the border. +/// +/// Public so a caller choosing between a long and a short title — the help +/// modals, which append a truncation marker only when they have to — can *ask* +/// instead of re-deriving this arithmetic and drifting from it. Without it the +/// longer form would silently erase the title it was meant to annotate. +#[must_use] +pub fn title_fits(area_width: u16, title: &str) -> bool { + let label_w = title.trim().chars().count(); + label_w > 0 && label_w.saturating_add(4) < usize::from(area_width) +} + /// Overlay the btop-style title onto the already-drawn rounded top border. /// /// Layout on the top row: `╭─╮ Title ╭───────╮` — the inner `╮`/`╭` are the label @@ -123,17 +141,13 @@ fn put(f: &mut Frame, x: u16, y: u16, text: &str, style: Style) { /// tint on every theme. fn stamp_title(f: &mut Frame, area: Rect, title: &str, border: Color, bg: Color, text_fg: Color) { let title = title.trim(); - if title.is_empty() { - return; + if !title_fits(area.width, title) { + return; // empty, or not enough room — leave the plain rounded top edge } let label_w = title.chars().count() as u16; // corner(x0) + at least one dash, then the left bracket. let lb = area.x + 2; let rb = lb + 1 + label_w; // right bracket column - let x1 = area.x + area.width - 1; - if rb >= x1 { - return; // not enough room — leave the plain rounded top edge - } let y0 = area.y; let bracket = Style::default().fg(border).bg(bg); let text = Style::default() diff --git a/tests/e2e-cucumber/tests/e2e/tui_driver.rs b/tests/e2e-cucumber/tests/e2e/tui_driver.rs index af4bfc70a0..be684846b3 100644 --- a/tests/e2e-cucumber/tests/e2e/tui_driver.rs +++ b/tests/e2e-cucumber/tests/e2e/tui_driver.rs @@ -610,17 +610,34 @@ impl TuiSession { /// observed code for the scenario's `Then` steps. /// /// Sends the raw byte `0x03` — what a terminal actually transmits for the - /// keystroke — rather than a signal, and that distinction is the point. - /// While the TUI holds the terminal in raw mode, `ISIG` is off (and - /// `ENABLE_PROCESSED_INPUT` on Windows), so the driver does not turn the - /// keystroke into SIGINT: nothing in the process ever sees a signal, and the - /// byte arrives as an ordinary key event. Only sending it covers the gesture - /// a user performs; [`deliver_signal_and_wait`](Self::deliver_signal_and_wait) - /// covers the externally delivered signal, which is a genuinely different - /// path. + /// keystroke — rather than a signal. While the TUI holds the terminal in raw + /// mode, `ISIG` is off (and `ENABLE_PROCESSED_INPUT` on Windows), so the + /// driver does not translate the keystroke into SIGINT and the byte arrives + /// as an ordinary key event. That is the gesture a user performs; + /// [`deliver_signal_and_wait`](Self::deliver_signal_and_wait) covers the + /// externally delivered signal. /// - /// As there, only harness faults are `Err`; the exit *value* and terminal - /// restoration are asserted by the scenario's `Then` steps. + /// What the scenario's assertions do and do not distinguish, stated plainly + /// because the two paths converge: + /// + /// - The *outcome* assertions (exit code 130, terminal restored) are + /// byte-identical to the SIGINT scenario's, and cannot tell the paths + /// apart on their own. + /// - The discrimination comes from the input plus the fact that the process + /// exits **at all**. Delete the key-event arm and no signal is ever + /// raised, so nothing ends the process and this call fails on its timeout. + /// That is the regression the step is here to catch, and it catches it. + /// - It does **not** independently prove no signal was involved. That rests + /// on the product's own raw mode: a build that failed to enter raw mode + /// would leave `ISIG` on, the tty would turn `0x03` into a SIGINT, and + /// these same assertions would still pass via the signal handler. Probing + /// the pty's termios from the master side would need `libc`/`nix` in the + /// harness, which this module deliberately avoids (see + /// [`deliver_signal_and_wait`](Self::deliver_signal_and_wait), which shells + /// out to `kill(1)` for the same reason). + /// + /// As with the signal path, only harness faults are `Err`; the exit *value* + /// and terminal restoration are asserted by the scenario's `Then` steps. pub async fn press_ctrl_c_and_wait(&mut self, timeout: Duration) -> Result<(), String> { self.send("\u{3}")?; let code = self.wait_for_exit_code(timeout).await?; @@ -686,6 +703,14 @@ impl TuiSession { /// terminal-restore sequences a signal handler emits arrive immediately /// before the process exits, so the parser must see them before restoration /// is asserted. + /// + /// That drain runs on *every* path through here, including callers that + /// predate the signal scenarios ([`wait_for_exit`](Self::wait_for_exit), and + /// through it [`quit_and_wait`](Self::quit_and_wait)). It is not gated on the + /// caller needing it, because the frame is just as buffered after a `q` as + /// after a signal. It ends the moment the reader thread sees EOF — the usual + /// case, costing about one [`POLL_INTERVAL`] — with [`DRAIN_TIMEOUT`] as the + /// ceiling a wedged PTY can impose. pub async fn wait_for_exit_code(&mut self, timeout: Duration) -> Result { let deadline = Instant::now() + timeout; loop { From 68db54f2f97550db41246a785644d2f68ac803dc Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Tue, 15 Sep 2026 19:40:14 +0300 Subject: [PATCH 12/13] fix(dash): stop an in-flight frame undoing the restore it raced MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `dash-sigint-restores-terminal` failed on the WSL2 E2E lane with `alternate_screen=false, cursor_hidden=true` — a *partial* restore, which is not what a missing `write_restore_sequences` looks like. It is the frame the render gate could not stop. The gate reads `SHUTTING_DOWN` before drawing, so no frame can *start* after a watcher claims the exit. It says nothing about the frame already in flight when the claim lands, and `restore_terminal` runs concurrently on a Tokio worker while that frame is written from the loop's own thread to the same `io::stdout()`. `Terminal::draw` ends by emitting `Hide` unconditionally when the frame sets no cursor position, so the frame's tail lands after the restore's `Show`: the alternate screen stays left (`EnterAlternateScreen` is emitted once, at startup, and never re-emitted) while the cursor stays invisible. The doc comment called that residue cosmetic; it is the user-visible half of the defect this PR exists to fix. Measured rather than argued. A standalone pty probe (no test harness: raw `openpty`, `kill -INT`, replay the 1049/25 toggles off the byte stream) caught it on a loaded Linux box, with the restore spliced into the middle of a frame — an SGR sequence cut in half by `ESC[?1049l … ESC[?25h`, then the frame's remainder and `ESC[?25l` last. The same probe reproduces it 6 times in 300 on `7a82ef8d`, the last head the WSL2 lane passed on, so this is not a regression from any of `e3e36cc0`/`94702d1b`/`ba6d1610`: the lane runs once per head and simply got lucky. The harness was not at fault either — `wait_for_exit_code`'s unconditional final-frame drain predates that green run and is unchanged since. So the window is closed. `RESTORE_LOCK` becomes `TERMINAL_WRITE_LOCK`, held across one whole frame as well as one whole teardown, and both render gates read the latch *under* it. Neither half suffices alone: the lock alone would merely order a late frame after the restore, and the latch alone cannot stop a frame that already passed the gate. No new hang profile — a renderer blocked mid-frame on a full terminal already blocks the restore's own writes to that same terminal. With the fix the probe is 0 in 300 under the same load. Falsified: deleting `lock_terminal_writer()` from the two gates reds `a_frame_cannot_paint_while_a_teardown_owns_the_terminal` and `a_menu_frame_cannot_paint_while_a_teardown_owns_the_terminal` (the existing latch-only gate tests stay green, which is the point — they cannot see this). Both new tests hold the teardown's half of the lock on another thread, claim the latch under it, and assert the racing frame paints nothing. Verified on Linux: `cargo test -p rocm-dash-tui --all-targets`, `cargo test --workspace --all-targets`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo clippy -p e2e-cucumber --test e2e -- -D warnings`, and all 16 `dash-*` e2e scenarios (100 steps). The WSL2 lane itself cannot be run locally. Signed-off-by: Roman Sirokov --- crates/rocm-dash-tui/src/app/mod.rs | 201 ++++++++++++++++++------ crates/rocm-dash-tui/src/ui/launcher.rs | 68 ++++++++ 2 files changed, 222 insertions(+), 47 deletions(-) diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index eaf8e0d729..0a13853ae8 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -1854,60 +1854,86 @@ pub(crate) fn restore_after_session(latch: &AtomicBool, restore: impl FnOnce()) /// /// # Ordering against the renderer /// -/// Nothing here locks the terminal, and this writer is genuinely concurrent with -/// the renderer: the watcher runs on a Tokio worker thread while frames are -/// drawn on the thread that owns the loop (`block_on`'s thread for a dashboard -/// session, the synchronous menu thread for the launcher hub). +/// This writer is genuinely concurrent with the renderer: the watcher runs on a +/// Tokio worker thread while frames are drawn on the thread that owns the loop +/// (`block_on`'s thread for a dashboard session, the synchronous menu thread for +/// the launcher hub). A frame that lands *after* this function's bytes cannot +/// re-enter the alternate screen — `EnterAlternateScreen` is emitted exactly +/// once at startup and `Terminal::draw` never re-emits it — but every frame ends +/// by hiding the cursor (`Terminal::draw` emits `Hide` unconditionally when the +/// frame sets no cursor position), so a late frame undoes the show-cursor half of +/// this restore and leaves the user with an invisible cursor. /// -/// The consequence is not merely cosmetic, so it is closed rather than accepted. -/// A frame that *completes after* this function returns cannot re-enter the -/// alternate screen — `EnterAlternateScreen` is emitted exactly once at startup -/// and `Terminal::draw` never re-emits it — but every frame ends by hiding (or -/// repositioning) the cursor and repainting, so a late frame would undo the -/// show-cursor half of this restore and paint a stale dashboard over the -/// restored screen. The narrow serialization that closes that window, in -/// preference to a process-global lock on every terminal write: both render -/// loops consult [`shutdown_claimed_on`] before drawing, and the latch is -/// claimed *before* the restore begins, so no frame can start after the claim. +/// Gating the loops on [`shutdown_claimed_on`] is necessary but *not* sufficient, +/// and the gap is not cosmetic: the claim cannot stop a frame that already passed +/// the gate, and that frame's tail is written after these bytes. Measured, rather +/// than argued — SIGINT delivered to a real `rocm dash --demo` under a pty, 300 +/// runs on a loaded Linux box: 6 of them ended with this restore spliced into the +/// middle of a frame (`…;48;` `ESC[?1049l … ESC[?25h` `2;19;20;22m qui…ESC[?25l`), +/// leaving the alternate screen with the cursor still hidden. That is exactly +/// what the E2E scenario `dash-sigint-restores-terminal` reported from the WSL2 +/// lane, and it reproduces identically on the commits before this PR, so it is +/// the long-standing shape of the race and not a new one. /// -/// What remains is a frame already in flight when the claim lands, which can -/// still interleave *during* the restore. That one is cosmetic — out-of-order -/// escapes on a terminal being reset in the same breath, with these restore -/// bytes written last — and is accepted. +/// So the window is closed rather than accepted: [`TERMINAL_WRITE_LOCK`] is held +/// across one whole frame and across one whole restore, and both render loops +/// re-check the latch *while holding it*. Every interleaving then ends with these +/// bytes last — either the frame completes first and this restore follows it, or +/// this restore goes first and the gate suppresses the frame behind it. +/// +/// This adds no new hang: a renderer blocked mid-frame on a full terminal blocks +/// this restore's own writes to that same terminal just as surely, so the lock +/// can only make us wait where we were already waiting. /// /// # Ordering against another restore /// -/// Separate hazard, separate mechanism. Two teardowns can run at once: a signal -/// watcher resumed past its `.await` races [`run`]'s clean-quit teardown (which -/// deliberately does not claim the exit latch — see [`restore_after_session`]), -/// and two watchers on two runtimes both wake on one process-global signal. -/// [`RESTORE_LOCK`] makes this function the single writer for the duration of -/// one teardown, so two threads can never interleave `write_restore_sequences` -/// on the same stdout. It is held only across a handful of escape bytes, so it -/// adds no hang profile beyond the internal lock `io::stdout()` already takes on -/// every write. +/// The same lock covers the second hazard. Two teardowns can run at once: a +/// signal watcher resumed past its `.await` races [`run`]'s clean-quit teardown +/// (which deliberately does not claim the exit latch — see +/// [`restore_after_session`]), and two watchers on two runtimes both wake on one +/// process-global signal. Holding [`TERMINAL_WRITE_LOCK`] makes this function the +/// single writer for the duration of one teardown, so two threads can never +/// interleave `write_restore_sequences` on the same stdout. pub(crate) fn restore_terminal() { // Poisoning is irrelevant here: nothing inside can panic (every step is // best-effort), and a teardown skipped because some *other* thread panicked // mid-restore is strictly worse than running it again. - let _guard = RESTORE_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let _guard = lock_terminal_writer(); // `disable_raw_mode` mutates the real terminal (there is no in-memory // equivalent), so it stays outside the testable sequence writer below. let _ = disable_raw_mode(); let _ = write_restore_sequences(&mut io::stdout()); } -/// Serialises [`restore_terminal`] so concurrent teardowns cannot interleave -/// their escape sequences on one stdout. +/// Serialises everything that writes to the process's one stdout while the TUI +/// owns it: one whole frame from either render loop, and one whole teardown in +/// [`restore_terminal`]. /// /// Distinct from [`SHUTTING_DOWN`], and deliberately so: the latch answers "is -/// the process exiting" (one-shot, never released, gates rendering), this -/// answers "is someone writing the restore right now" (re-armable, held for the -/// length of one teardown). Conflating them is what made a clean session exit +/// the process exiting" (one-shot, never released), this answers "is someone +/// writing the terminal right now" (re-armable, held for the length of one frame +/// or one teardown). Conflating them is what made a clean session exit /// permanently wedge the launcher hub. -static RESTORE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); +/// +/// The two are used *together* in the render gates — the latch is re-read under +/// this lock — because neither alone is enough: the lock without the latch would +/// merely order a late frame after the restore, and the latch without the lock +/// cannot stop a frame that has already passed the gate. See the ordering notes +/// on [`restore_terminal`]. +static TERMINAL_WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Take exclusive ownership of the terminal for the length of one frame or one +/// teardown. Poisoning is recovered from rather than propagated: a teardown or a +/// frame skipped because some *other* thread panicked while holding the lock is +/// strictly worse than doing it anyway. +/// +/// `pub(crate)` so the launcher's menu loop — the crate's other render loop — +/// can take the same lock around its own frame. +pub(crate) fn lock_terminal_writer() -> std::sync::MutexGuard<'static, ()> { + TERMINAL_WRITE_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} /// Write the escape sequences that undo `run`'s terminal setup — leave the /// alternate screen, disable mouse capture, show the cursor — to `out`. Split @@ -2219,6 +2245,12 @@ const EXIT_CODE_SIGTERM: i32 = 143; /// the frame must not land after the restore and undo it. See the ordering note /// on [`restore_terminal`]. /// +/// The gate is the latch read **plus** [`lock_terminal_writer`], and needs both. +/// The lock is taken first and held across the whole frame, so the restore can +/// neither splice its bytes into the middle of this frame nor be overtaken by its +/// tail; the latch is then read *under* that lock, so a restore that got there +/// first suppresses this frame entirely instead of merely preceding it. +/// /// Extracted from the event loop's body — and parameterised over the backend and /// the latch — purely so the gate is *testable*: a test can drive a /// `TestBackend`, claim a local latch, and assert no cells were painted. Inlined @@ -2233,6 +2265,7 @@ fn draw_frame_unless_shutting_down( focus: Option, latch: &AtomicBool, ) -> Result<(), ::Error> { + let _writer = lock_terminal_writer(); if shutdown_claimed_on(latch) { return Ok(()); } @@ -4353,6 +4386,20 @@ mod tests { ); } + /// Every cell a `TestBackend` frame painted, trimmed — `""` for a frame the + /// render gate suppressed. Shared by the two gate tests below so they assert + /// on the same thing. + fn painted(term: &ratatui::Terminal) -> String { + term.backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect::() + .trim() + .to_string() + } + #[test] fn a_claimed_shutdown_stops_the_dashboard_painting_another_frame() { // The render gate itself, not just the latch predicate underneath it. @@ -4368,17 +4415,6 @@ mod tests { use ratatui::Terminal; use ratatui::backend::TestBackend; - let painted = |term: &Terminal| -> String { - term.backend() - .buffer() - .content() - .iter() - .map(ratatui::buffer::Cell::symbol) - .collect::() - .trim() - .to_string() - }; - // Control: with nothing claimed the gate must let the frame through, // otherwise the assertion below would pass on a helper that never draws. let mut s = st(); @@ -4407,6 +4443,77 @@ mod tests { ); } + #[test] + fn a_frame_cannot_paint_while_a_teardown_owns_the_terminal() { + // The half of the gate the latch cannot provide on its own, and the + // defect the WSL2 E2E lane caught as `dash-sigint-restores-terminal`: + // "alternate_screen=false, cursor_hidden=true" — the alt-screen left, but + // the cursor still invisible. + // + // Reading the latch before drawing stops a frame that *starts* after the + // claim. It cannot stop the frame already in flight when the claim lands, + // and that frame is the problem: `Terminal::draw` ends by emitting `Hide` + // unconditionally, so its tail undoes the restore's `Show` while the + // alt-screen stays left (`EnterAlternateScreen` is never re-emitted) — + // exactly the half-restored terminal the lane reported. Reproduced + // outside the harness by signalling a real `rocm dash --demo` under a + // pty: the restore landed *inside* a frame's bytes, with `ESC[?25l` last. + // + // So the gate must take `lock_terminal_writer()` FIRST and read the latch + // under it. Modelled with the teardown's half of that lock held by another + // thread: this thread asks to draw while the teardown owns the terminal, + // and must paint nothing, because the claim happens-before the unlock it + // is waiting on. Delete the lock from the gate and the frame paints + // immediately instead, which is the bug. + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + let latch = AtomicBool::new(false); + let mut s = st(); + let mut term = Terminal::new(TestBackend::new(120, 32)).unwrap(); + let (held_tx, held_rx) = std::sync::mpsc::channel::<()>(); + let (drawing_tx, drawing_rx) = std::sync::mpsc::channel::<()>(); + + std::thread::scope(|scope| { + // `mpsc::Receiver` is `Send` but not `Sync`, so the halves the + // teardown thread uses are moved into it; the latch is shared as a + // plain reference (the whole point is that both threads see it). + let latch = &latch; + scope.spawn(move || { + // Stands in for `restore_terminal()`. It writes nothing: the + // claim is what this test is about, not the escape bytes (those + // are covered by `write_restore_sequences_leaves_alt_screen_…`). + let guard = lock_terminal_writer(); + held_tx.send(()).expect("the drawing thread is alive"); + drawing_rx.recv().expect("the drawing thread is alive"); + // Only to make the unfixed code reliably red: an ungated draw + // paints in microseconds, so it would certainly have painted + // within this window. The fixed path does not depend on the + // duration — the claim below happens-before the unlock either + // way, so the assertion holds even if this were zero. + std::thread::sleep(std::time::Duration::from_millis(200)); + assert!( + claim_shutdown(latch), + "the teardown must win a latch nothing else can see" + ); + drop(guard); + }); + + held_rx.recv().expect("the teardown thread is alive"); + drawing_tx.send(()).expect("the teardown thread is alive"); + draw_frame_unless_shutting_down(&mut term, &mut s, None, latch) + .expect("the gate must not turn a suppressed frame into an error"); + }); + + assert_eq!( + painted(&term), + "", + "a frame asked for while a teardown owned the terminal must not paint \ + — its trailing `Hide` would land after the restore's `Show` and leave \ + the user on the normal screen with an invisible cursor" + ); + } + #[test] fn ctrl_c_exits_once_the_console_job_has_finished() { // The gesture the PR exists to fix, in the state that used to swallow it. diff --git a/crates/rocm-dash-tui/src/ui/launcher.rs b/crates/rocm-dash-tui/src/ui/launcher.rs index 97a12891a8..c0cb529023 100644 --- a/crates/rocm-dash-tui/src/ui/launcher.rs +++ b/crates/rocm-dash-tui/src/ui/launcher.rs @@ -355,6 +355,12 @@ pub fn run_launcher( /// is being restored, and this frame must not land after the restore and undo /// it. See the ordering note on `crate::app::restore_terminal`. /// +/// As in the dashboard's gate, the latch read is done *under* +/// `crate::app::lock_terminal_writer`, which is then held for the whole frame: +/// the lock stops a restore splicing into (or being overtaken by) this frame, and +/// the latch read under it stops a frame that a restore already beat to the lock. +/// Neither half is sufficient alone. +/// /// Parameterised over the backend and the latch so the gate is testable against /// a `TestBackend` — inlined in the loop it was reachable only from a real /// terminal, and deleting it turned no test red. @@ -365,6 +371,7 @@ fn draw_menu_unless_shutting_down( theme: &Theme, latch: &std::sync::atomic::AtomicBool, ) -> Result<(), ::Error> { + let _writer = crate::app::lock_terminal_writer(); if crate::app::shutdown_claimed_on(latch) { return Ok(()); } @@ -439,6 +446,67 @@ mod tests { ); } + #[test] + fn a_menu_frame_cannot_paint_while_a_teardown_owns_the_terminal() { + // The launcher's half of the fix for the partial restore the WSL2 E2E + // lane caught (`alternate_screen=false, cursor_hidden=true`): reading the + // latch cannot stop a frame that already passed the gate, and that + // frame's trailing `Hide` undoes the restore's `Show`. The menu loop must + // therefore take `lock_terminal_writer()` first and read the latch under + // it. See the twin test in `app::tests`, which carries the full analysis. + use std::sync::atomic::AtomicBool; + + let painted = |term: &Terminal| -> String { + term.backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect::() + .trim() + .to_string() + }; + + let state = base(); + let theme = state.theme; + let latch = AtomicBool::new(false); + let mut term = Terminal::new(TestBackend::new(100, 30)).unwrap(); + let (held_tx, held_rx) = std::sync::mpsc::channel::<()>(); + let (drawing_tx, drawing_rx) = std::sync::mpsc::channel::<()>(); + + std::thread::scope(|scope| { + // `mpsc::Receiver` is `Send` but not `Sync`, so the halves the + // teardown thread uses are moved into it; the latch is shared as a + // plain reference (the whole point is that both threads see it). + let latch = &latch; + scope.spawn(move || { + // Stands in for `crate::app::restore_terminal()`, which takes this + // same lock around its escape bytes. + let guard = crate::app::lock_terminal_writer(); + held_tx.send(()).expect("the drawing thread is alive"); + drawing_rx.recv().expect("the drawing thread is alive"); + // Only to make the unfixed code reliably red; the fixed path is + // correct for any duration, including zero. + std::thread::sleep(std::time::Duration::from_millis(200)); + latch.store(true, std::sync::atomic::Ordering::SeqCst); + drop(guard); + }); + + held_rx.recv().expect("the teardown thread is alive"); + drawing_tx.send(()).expect("the teardown thread is alive"); + draw_menu_unless_shutting_down(&mut term, &state, 0, &theme, latch) + .expect("the gate must not turn a suppressed frame into an error"); + }); + + assert_eq!( + painted(&term), + "", + "a menu frame asked for while a teardown owned the terminal must not \ + paint — its trailing `Hide` would land after the restore's `Show` and \ + leave the user on the normal screen with an invisible cursor" + ); + } + #[test] fn the_front_door_comes_back_after_a_session_ends_cleanly() { // The launcher-hub regression, at the seam the e2e scenario From cbe5af6884745f7b533031270aafd1624e118ee0 Mon Sep 17 00:00:00 2001 From: Roman Sirokov Date: Tue, 15 Sep 2026 20:35:32 +0300 Subject: [PATCH 13/13] fix(dash): clamp the popup height floor, the twin of the width floor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up. One latent geometry fix and one test-prose correction; no behaviour change on any geometry the product is used at. `centered_rect`'s 5-row minimum had the bare `.max(5)` form that `centered_width` carried until the previous round: on an area shorter than five rows it asks the vertical `Layout::split` for a segment taller than the area. The number is split out into `centered_height` and clamped to `area.height`, the exact counterpart of `centered_width`, so the height the popup is laid out to is the height it gets. This one is latent, and the commit says so rather than overselling it. Nothing measures against the height yet — both help modals measure their content and pass the answer in as `max_h` — so the divergence is confined to a local that `Layout::split` truncates before it reaches a caller. What made the width defect live was a caller that needed the number *before* the popup existed; keeping the two sides identical is what stops the same thing happening here. `popup_height_is_never_taller_than_a_short_area` sweeps 0..=8 rows for both live `(pct_y, max_h)` shapes, asserting the laid-out height is `<= area.height` and equal to `centered_rect(..).height`. It asserts on `centered_height`, not on the returned rect, deliberately: a rect-only test could not fail, because the rect has already been truncated by ratatui — that is the mistake the deleted `help_modal_is_clamped_when_the_content_cannot_fit` made, and it was confirmed here by probe before the test was written. Falsified by restoring the unclamped floor: panicked at crates/rocm-dash-tui/src/ui/modal.rs:1308: centered_height(100, 12) returned 5 on a 0-row area: the popup would be laid out to a height it cannot have with the other 12 modal tests still green. Test prose only, no assertion removed: in `global_help_is_sized_to_its_content_and_evicts_nothing`, the `ends_with('│')` assertion's message claimed the last row "must be content, not filler". It cannot establish that — a blank row inside a bordered popup paints as `│ │` and ends with the right border too. Confirmed by forcing a trailing blank row: `ends_with` passed and the *next* assertion (`trim_matches(['│', ' ']).count() > 0`) is what reds. Both checks are kept, because `ends_with` does establish something real — the row above the bottom border is an interior body row rather than the popup's own top border, which ends with '╮' — and the message now says that instead. Signed-off-by: Roman Sirokov --- crates/rocm-dash-tui/src/ui/modal.rs | 71 ++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/crates/rocm-dash-tui/src/ui/modal.rs b/crates/rocm-dash-tui/src/ui/modal.rs index 29f2af185b..6a6edbdf21 100644 --- a/crates/rocm-dash-tui/src/ui/modal.rs +++ b/crates/rocm-dash-tui/src/ui/modal.rs @@ -36,7 +36,7 @@ fn scale_pct(extent: u16, pct: u16) -> u16 { /// Centered rectangle taking `pct_x`% width and `pct_y`% height of `area`, /// clamped to a maximum so it doesn't drown the screen on big terminals. pub fn centered_rect(pct_x: u16, pct_y: u16, max_w: u16, max_h: u16, area: Rect) -> Rect { - let h_pct = scale_pct(area.height, pct_y).min(max_h).max(5); + let h_pct = centered_height(pct_y, max_h, area); let v_pad = (area.height.saturating_sub(h_pct)) / 2; let w_pct = centered_width(pct_x, max_w, area); let vert = Layout::default() @@ -83,6 +83,27 @@ pub fn centered_width(pct_x: u16, max_w: u16, area: Rect) -> u16 { scale_pct(area.width, pct_x).min(max_w).max(floor) } +/// Shortest a popup is allowed to be shrunk to by the percentage: a border pair +/// plus enough body rows to be worth opening. +const MIN_POPUP_HEIGHT: u16 = 5; + +/// Height [`centered_rect`] will give a popup — the exact counterpart of +/// [`centered_width`], and split out for the same reason: the number this +/// computes has to be the number the popup gets. +/// +/// The [`MIN_POPUP_HEIGHT`] floor is clamped to `area.height` for the reason +/// spelled out on [`centered_width`]. An unclamped floor asks for 5 rows on an +/// area shorter than 5, which the `Layout::split` below then truncates, so the +/// requested geometry and the rendered geometry disagree. Nothing measures +/// against the height *today* — the callers measure their content and pass the +/// answer in as `max_h` — so this is a latent form of the defect that had gone +/// live on the width. Keeping the two sides identical is what stops it going +/// live here the first time a caller needs the height before the popup exists. +fn centered_height(pct_y: u16, max_h: u16, area: Rect) -> u16 { + let floor = MIN_POPUP_HEIGHT.min(area.height); + scale_pct(area.height, pct_y).min(max_h).max(floor) +} + /// Render a bordered block with `title` over `area` after clearing it, /// returning the inner area so the caller can render content into it. pub fn draw_popup_frame(f: &mut Frame, area: Rect, title: &str, theme: &Theme) -> Rect { @@ -1189,10 +1210,18 @@ mod ported_chrome_tests { let painted = rows(w, h, |f| super::draw_global_help(f, area, &theme)); let bottom = bottom_border_row(&painted); let last = painted[bottom - 1].trim_end(); + // Two separate properties, in order. The first is *not* a + // no-filler check: a blank row inside a bordered popup paints as + // `│ │` and ends with '│' too, so `ends_with` can never tell + // filler from content. What it does establish is that the row above + // the bottom border is an interior row — a body row between the two + // side borders, rather than the popup's own top border (`╭───╮`, + // which ends with '╮') as it would be on a two-row popup. The + // second assertion is the one that rules out filler. assert!( last.ends_with('│'), - "{w}x{h}: the modal's last row must be content, not filler, but \ - row {} is {last:?}:\n{}", + "{w}x{h}: the row above the bottom border must be a body row \ + between the side borders, but row {} is {last:?}:\n{}", bottom - 1, painted.join("\n") ); @@ -1257,6 +1286,42 @@ mod ported_chrome_tests { } } + /// The height counterpart of the sweep above, pinned for the same reason. + /// + /// Unlike the width, nothing measures its content against this number yet, + /// so the defect is latent rather than live: `centered_rect` returns a rect + /// `Layout::split` has already truncated to the area, and *that* is why this + /// test asserts on `centered_height` rather than on `centered_rect(..). + /// height`. A test written against the returned rect could not fail — it + /// would be re-asserting ratatui's own invariant, which is precisely the + /// mistake `help_modal_is_clamped_when_the_content_cannot_fit` made before + /// it was deleted. The property this crate owns is that the height it *asks* + /// for is the height it gets. + /// + /// Both live `(pct_y, max_h)` shapes are swept: the content-sized help + /// modals' `pct_y = 100`, and a fixed-height overlay's 80/30. + #[test] + fn popup_height_is_never_taller_than_a_short_area() { + for h in 0..=8u16 { + let area = Rect::new(0, 0, 80, h); + for (pct_y, max_h) in [(100u16, 12u16), (80, 30)] { + let asked = super::centered_height(pct_y, max_h, area); + assert!( + asked <= h, + "centered_height({pct_y}, {max_h}) returned {asked} on a \ + {h}-row area: the popup would be laid out to a height it \ + cannot have" + ); + assert_eq!( + super::centered_rect(100, pct_y, 80, max_h, area).height, + asked, + "the popup's rendered height must equal the height it was \ + laid out to ({h}-row area)" + ); + } + } + } + /// When the content still cannot fit at full height, the modal says so. /// /// It is sized, not scrolled: there is no scrollbar and nothing to press, so