diff --git a/AGENTS.md b/AGENTS.md index 155b474510..5bbbafdb12 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -250,7 +250,7 @@ Shared UI components — reuse rather than hand-rolling new ones. The CLI (`apps Shared (`crates/rocm-core`): -- [`confirm.rs`](crates/rocm-core/src/confirm.rs)'s **`print_prompt`**/**`read_answer`** — the shared `[y/N]` confirmation prompt: `print_prompt` writes and flushes a prompt (callers include their own trailing `[y/N]: `), `read_answer` reads a line and parses it as yes/no. Two fallible calls rather than one, so a caller can choose whether a failed write is fatal: [`fix/consent.rs`](crates/rocm-core/src/fix/consent.rs)'s `confirm()` attempts the read anyway, while [`uninstall_plan.rs`](apps/rocm/src/uninstall_plan.rs)'s `confirm_uninstall` and [`consent.rs`](apps/rocm/src/therock/consent.rs)'s `prompt_yes_no` treat it as fatal. [`uninstall.rs`](apps/rocm/src/uninstall.rs), [`storage.rs`](apps/rocm/src/storage.rs) and [`runtimes_cmd.rs`](apps/rocm/src/runtimes_cmd.rs) reach the prompt only through `confirm_uninstall`, each behind `require_yes_or_interactive` (below); [`fix/consent.rs`](crates/rocm-core/src/fix/consent.rs)'s `confirm()` additionally layers its own non-interactive short-circuit and refusal wording on top +- [`confirm.rs`](crates/rocm-core/src/confirm.rs)'s **`print_prompt`**/**`read_answer`** — the shared `[y/N]` confirmation prompt: `print_prompt` writes and flushes a prompt (callers include their own trailing `[y/N]: `), `read_answer` reads a line and parses it as yes/no, and writes to the stream it is given a newline when the input ended without one and a line saying so when the answer was neither yes nor no (declined either way). Two fallible calls rather than one, so a caller can choose whether a failed write is fatal: [`fix/consent.rs`](crates/rocm-core/src/fix/consent.rs)'s `confirm()` attempts the read anyway, while [`uninstall_plan.rs`](apps/rocm/src/uninstall_plan.rs)'s `confirm_uninstall` and [`consent.rs`](apps/rocm/src/therock/consent.rs)'s `prompt_yes_no` treat it as fatal. [`uninstall.rs`](apps/rocm/src/uninstall.rs), [`storage.rs`](apps/rocm/src/storage.rs) and [`runtimes_cmd.rs`](apps/rocm/src/runtimes_cmd.rs) reach the prompt only through `confirm_uninstall`, each behind `require_yes_or_interactive` (below); [`fix/consent.rs`](crates/rocm-core/src/fix/consent.rs)'s `confirm()` additionally layers its own non-interactive short-circuit and refusal wording on top - [`confirm.rs`](crates/rocm-core/src/confirm.rs)'s **`require_yes_or_interactive(yes, action)`** — the guard in front of a mutating command that confirms with that `[y/N]` prompt. `Ok(true)` means `--yes` already approved it (skip the prompt), `Ok(false)` means there is no `--yes` but a terminal, so the caller still asks, and otherwise it bails with `"{action} requires --yes outside an interactive terminal"`. A new `--yes`-gated command reuses it instead of re-deriving the `yes` / `interactive_terminal()` / `bail!` sequence. Not for a refusal that deliberately differs: [`therock/consent.rs`](apps/rocm/src/therock/consent.rs)'s `sdk_install_approval` names two consents that are not interchangeable, and [`fix/consent.rs`](crates/rocm-core/src/fix/consent.rs)'s `confirm()` has its own exit code and checks stdin only CLI: diff --git a/README.md b/README.md index bd0d887420..313a7f4ee1 100644 --- a/README.md +++ b/README.md @@ -1613,8 +1613,11 @@ non-zero too, after printing its log. `rocm uninstall` removes four categories of files that ROCm CLI manages on this computer: its binaries, configuration, data, and caches. It lists what it will -do and asks `[y/N]` (default: no) before doing it. Use `--dry-run` to only list, -and `--yes` to skip the confirmation. There is no `--force`; `--force-dev-binaries` +do and asks `[y/N]` (default: no) before doing it. Only `y` or `yes` proceeds. +Enter, `n` and `no` cancel: it prints `uninstall cancelled`, removes nothing and +exits with code 0. Any other answer cancels the same way, after a line saying +that the answer was not understood and is treated as no. Use `--dry-run` to only +list, and `--yes` to skip the confirmation. There is no `--force`; `--force-dev-binaries` is a separate opt-in for development builds. At a terminal, a dry run that finds something to remove ends by saying to run the same command again without `--dry-run`; with nothing to remove, or when stdin or stdout is not a terminal diff --git a/apps/rocm/src/therock/consent.rs b/apps/rocm/src/therock/consent.rs index 60ef0f9c9b..165bddca9b 100644 --- a/apps/rocm/src/therock/consent.rs +++ b/apps/rocm/src/therock/consent.rs @@ -440,7 +440,7 @@ pub(super) fn confirm_overwrite_existing_sdk( fn prompt_yes_no(prompt: &str) -> Result { rocm_core::confirm::print_prompt(&mut std::io::stdout(), prompt) .context("failed to write confirmation prompt")?; - rocm_core::confirm::read_answer(&mut std::io::stdin().lock()) + rocm_core::confirm::read_answer(&mut std::io::stdin().lock(), &mut std::io::stdout()) .context("failed to read confirmation response") } diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index e553dc9e47..1ad1f979a4 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -438,7 +438,7 @@ fn env_path(name: &str) -> Option { pub(crate) fn confirm_uninstall() -> Result { rocm_core::confirm::print_prompt(&mut io::stdout(), "Proceed with uninstall? [y/N]: ") .context("failed to write uninstall prompt")?; - rocm_core::confirm::read_answer(&mut io::stdin().lock()) + rocm_core::confirm::read_answer(&mut io::stdin().lock(), &mut io::stdout()) .context("failed to read uninstall confirmation") } diff --git a/crates/rocm-core/src/confirm.rs b/crates/rocm-core/src/confirm.rs index 20ee2587cc..e5fa9f9a03 100644 --- a/crates/rocm-core/src/confirm.rs +++ b/crates/rocm-core/src/confirm.rs @@ -23,6 +23,13 @@ //! without a controlled terminal. Real callers pass `std::io::stdout()` and //! `std::io::stdin().lock()`. //! +//! [`read_answer`] also tells the user when their answer was not understood, and +//! ends the prompt line when the input ended without a newline. Both go to the +//! `out` stream the caller passes, so every caller gets them and none can forget. +//! `y`/`yes` approve; `n`/`no`/an empty line decline silently (an empty line is +//! the documented default); anything else declines with a line saying so, rather +//! than being mistaken for a deliberate "no". +//! //! [`interactive_terminal`] answers the question callers ask before prompting at //! all: whether this process has a terminal on both streams. //! [`require_yes_or_interactive`] is the guard built on it for a mutating @@ -32,9 +39,24 @@ use anyhow::{Result, bail}; use std::io::{BufRead, IsTerminal, Write, stdin, stdout}; -/// Parse a user's typed response to a `[y/N]` prompt. -pub fn is_affirmative_answer(line: &str) -> bool { - matches!(line.trim().to_lowercase().as_str(), "y" | "yes") +/// How a typed response to a `[y/N]` prompt reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Answer { + /// `y` or `yes`, in any case. + Yes, + /// `n` or `no`, or an empty line: the prompt's default. + No, + /// Anything else. Declined like [`Answer::No`], but worth saying so. + Unrecognized, +} + +/// Classify a user's typed response to a `[y/N]` prompt. +pub fn parse_answer(line: &str) -> Answer { + match line.trim().to_lowercase().as_str() { + "y" | "yes" => Answer::Yes, + "" | "n" | "no" => Answer::No, + _ => Answer::Unrecognized, + } } /// Write `prompt` to `out` and flush it, so it's visible before a blocking @@ -54,10 +76,48 @@ pub fn print_prompt(out: &mut impl Write, prompt: &str) -> std::io::Result<()> { /// Read one line from `input` and parse it as yes/no. Only errors if the /// line can't be read; a declined answer — including an empty read at EOF — /// is `Ok(false)`, not an error. -pub fn read_answer(input: &mut impl BufRead) -> std::io::Result { +/// +/// Two things are written to `out` so the caller's own message lands where the +/// user can read it: +/// - when the line did not end in a newline (EOF, as from Ctrl-D, or piped input +/// with no final newline such as `printf no |`), a newline, ending the prompt +/// line: either way nothing echoed a line end, so the cursor is still on the +/// prompt line and the caller's next line would run into it; +/// - when the answer is [`Answer::Unrecognized`], a line saying it is being +/// treated as no, with the answer shown back quoted and escaped and cut to +/// [`MAX_ECHOED_ANSWER_CHARS`] characters, so a long pasted line does not fill +/// the screen. +/// +/// Both writes are best effort: a failure to explain a decline must not turn +/// into an error that replaces the decline, which `fix`'s `confirm()` relies on. +pub fn read_answer(input: &mut impl BufRead, out: &mut impl Write) -> std::io::Result { let mut line = String::new(); input.read_line(&mut line)?; - Ok(is_affirmative_answer(&line)) + if !line.ends_with('\n') { + let _ = writeln!(out); + } + let answer = parse_answer(&line); + if answer == Answer::Unrecognized { + let _ = writeln!( + out, + "{} is not yes or no; treating it as no.", + echoed_answer(line.trim()) + ); + } + Ok(answer == Answer::Yes) +} + +/// The most characters of a typed answer that the "not understood" line shows. +const MAX_ECHOED_ANSWER_CHARS: usize = 40; + +/// `answer` as shown back to the user: quoted with control characters escaped, and +/// cut to [`MAX_ECHOED_ANSWER_CHARS`] characters (never in the middle of one), with +/// `...` after the closing quote when there was more. +fn echoed_answer(answer: &str) -> String { + let mut chars = answer.chars(); + let shown: String = chars.by_ref().take(MAX_ECHOED_ANSWER_CHARS).collect(); + let more = if chars.next().is_some() { "..." } else { "" }; + format!("{shown:?}{more}") } /// Whether this process can hold an interactive exchange with a user. @@ -112,21 +172,34 @@ mod tests { use std::io::{Error, Result}; #[test] - fn is_affirmative_answer_accepts_only_y_and_yes() { + fn parse_answer_accepts_only_y_and_yes() { for accepted in ["y", "Y", "yes", "YES", "Yes", " y ", " yes\n"] { - assert!( - is_affirmative_answer(accepted), + assert_eq!( + parse_answer(accepted), + Answer::Yes, "expected {accepted:?} to be treated as a yes" ); } } #[test] - fn is_affirmative_answer_rejects_everything_else() { - for declined in ["n", "no", "", "\n", "yep", "ye"] { - assert!( - !is_affirmative_answer(declined), - "expected {declined:?} to be treated as a decline" + fn parse_answer_reads_n_no_and_an_empty_line_as_the_default_no() { + for declined in ["n", "N", "no", "NO", " no ", "", "\n", " \n"] { + assert_eq!( + parse_answer(declined), + Answer::No, + "expected {declined:?} to be the default no" + ); + } + } + + #[test] + fn parse_answer_flags_everything_else_as_unrecognized() { + for odd in ["maybe", "yep", "ye", "yes please", "nope", "1", "y n"] { + assert_eq!( + parse_answer(odd), + Answer::Unrecognized, + "expected {odd:?} to be unrecognized" ); } } @@ -189,19 +262,170 @@ mod tests { ); } + /// Run `read_answer` over `typed` and return the verdict and everything it + /// wrote to the output stream. + fn answer_and_output(typed: &[u8]) -> (bool, String) { + let mut input = typed; + let mut out = Vec::new(); + let verdict = + read_answer(&mut input, &mut out).expect("read from a byte slice cannot fail"); + ( + verdict, + String::from_utf8(out).expect("the helper writes UTF-8"), + ) + } + + #[test] + fn read_answer_approves_y_and_yes_without_writing_anything() { + for typed in [&b"y\n"[..], b"yes\n", b"YES\n"] { + let (verdict, written) = answer_and_output(typed); + assert!(verdict, "{typed:?} must approve"); + assert_eq!(written, "", "an approval needs no comment"); + } + } + + #[test] + fn read_answer_declines_n_no_and_enter_without_writing_anything() { + for typed in [&b"n\n"[..], b"no\n", b"\n"] { + let (verdict, written) = answer_and_output(typed); + assert!(!verdict, "{typed:?} must decline"); + assert_eq!( + written, "", + "a deliberate no (or the default) must not be commented on" + ); + } + } + + #[test] + fn read_answer_declines_an_unrecognized_answer_and_says_so() { + let (verdict, written) = answer_and_output(b"maybe\n"); + assert!(!verdict, "an unrecognized answer must decline"); + assert_eq!(written, "\"maybe\" is not yes or no; treating it as no.\n"); + } + + #[test] + fn read_answer_at_eof_declines_and_ends_the_prompt_line() { + let (verdict, written) = answer_and_output(b""); + assert!(!verdict, "EOF is Ok(false), not an error"); + assert_eq!(written, "\n", "EOF leaves the cursor on the prompt line"); + } + + #[test] + fn read_answer_for_a_partial_line_ends_the_prompt_line_then_says_so() { + // Typed text and then EOF, with no newline: the terminal echoed the text + // but no newline, so the line must be ended before the feedback line. + let (verdict, written) = answer_and_output(b"maybe"); + assert!(!verdict); + assert_eq!( + written, + "\n\"maybe\" is not yes or no; treating it as no.\n" + ); + } + + #[test] + fn read_answer_for_a_yes_without_a_newline_still_approves() { + let (verdict, written) = answer_and_output(b"yes"); + assert!(verdict, "a yes is a yes with or without the final newline"); + assert_eq!(written, "\n", "the unfinished prompt line is still ended"); + } + + #[test] + fn read_answer_cuts_a_long_answer_short_and_marks_the_cut() { + let typed = format!("{}\n", "a".repeat(100)); + let (verdict, written) = answer_and_output(typed.as_bytes()); + assert!(!verdict); + assert_eq!( + written, + format!( + "\"{}\"... is not yes or no; treating it as no.\n", + "a".repeat(MAX_ECHOED_ANSWER_CHARS) + ) + ); + } + + #[test] + fn read_answer_shows_an_answer_of_exactly_the_limit_whole() { + let answer = "b".repeat(MAX_ECHOED_ANSWER_CHARS); + let (_, written) = answer_and_output(format!("{answer}\n").as_bytes()); + assert_eq!( + written, + format!("\"{answer}\" is not yes or no; treating it as no.\n"), + "an answer that fits is not marked as cut" + ); + let (_, written) = answer_and_output(format!("{answer}c\n").as_bytes()); + assert_eq!( + written, + format!("\"{answer}\"... is not yes or no; treating it as no.\n"), + "one character over the limit is cut" + ); + } + + #[test] + fn read_answer_cuts_between_characters_not_inside_one() { + // 2-byte and 4-byte characters: a cut by bytes would split one and panic + // or write invalid UTF-8; the limit counts characters. + for ch in ['é', '🦀'] { + let typed = format!("{}\n", ch.to_string().repeat(MAX_ECHOED_ANSWER_CHARS + 5)); + let (_, written) = answer_and_output(typed.as_bytes()); + assert_eq!( + written, + format!( + "\"{}\"... is not yes or no; treating it as no.\n", + ch.to_string().repeat(MAX_ECHOED_ANSWER_CHARS) + ), + "answer of {ch:?}" + ); + } + } + + #[test] + fn read_answer_bounds_the_line_even_when_every_character_is_escaped() { + // An escaped control character is longer than itself, so the limit is on + // the typed characters and the line stays bounded by it. + let typed = format!("{}\n", "\x1b".repeat(100)); + let (_, written) = answer_and_output(typed.as_bytes()); + assert_eq!( + written, + format!( + "\"{}\"... is not yes or no; treating it as no.\n", + "\\u{1b}".repeat(MAX_ECHOED_ANSWER_CHARS) + ) + ); + assert!( + !written.contains('\x1b'), + "no raw escape reaches the terminal" + ); + } + #[test] - fn read_answer_parses_a_typed_line() { - let mut input: &[u8] = b"yes\n"; - assert!(read_answer(&mut input).expect("read from a byte slice cannot fail")); + fn read_answer_for_a_no_without_a_newline_declines_and_only_ends_the_prompt_line() { + // Piped input such as `printf no |` has no final newline either. The + // verdict is the decline `no\n` gives and nothing explains it, but the + // prompt line is still ended: no newline was echoed after the prompt. + let (verdict, written) = answer_and_output(b"no"); + assert!(!verdict, "a no is a no with or without the final newline"); + assert_eq!(written, "\n", "only the unfinished prompt line is ended"); + } - let mut input: &[u8] = b"n\n"; - assert!(!read_answer(&mut input).expect("read from a byte slice cannot fail")); + #[test] + fn read_answer_quotes_an_answer_that_holds_control_characters() { + // The answer is echoed back, so it is escaped rather than written raw. + let (_, written) = answer_and_output(b"\x1b[31mred\n"); + assert_eq!( + written, + "\"\\u{1b}[31mred\" is not yes or no; treating it as no.\n" + ); } #[test] - fn read_answer_at_eof_declines_without_erroring() { - let mut input: &[u8] = b""; - assert!(!read_answer(&mut input).expect("EOF is Ok(false), not an error")); + fn read_answer_keeps_the_verdict_when_the_feedback_cannot_be_written() { + // The explanation is best effort: a closed stdout must not turn a + // decline into an error, which `fix`'s `confirm()` relies on. + let mut input: &[u8] = b"maybe\n"; + let mut out = FailingWriter; + let verdict = read_answer(&mut input, &mut out) + .expect("a failed feedback write must not replace the verdict"); + assert!(!verdict); } /// A reader whose `read_line` always fails, so a real I/O failure on the @@ -224,7 +448,9 @@ mod tests { #[test] fn read_answer_surfaces_a_read_failure_as_an_error() { let mut input = FailingReader; - read_answer(&mut input).expect_err("a failing reader must return Err"); + let mut out = Vec::new(); + read_answer(&mut input, &mut out).expect_err("a failing reader must return Err"); + assert!(out.is_empty(), "nothing is written for a failed read"); } #[test] diff --git a/crates/rocm-core/src/fix/consent.rs b/crates/rocm-core/src/fix/consent.rs index ee3b0afbc3..95b9d8931f 100644 --- a/crates/rocm-core/src/fix/consent.rs +++ b/crates/rocm-core/src/fix/consent.rs @@ -75,7 +75,9 @@ pub(super) fn confirm(prompt: &str, assume_yes: bool) -> bool { return verdict; } let _ = crate::confirm::print_prompt(&mut std::io::stdout(), &format!("{prompt} [y/N]: ")); - let confirmed = crate::confirm::read_answer(&mut std::io::stdin().lock()).unwrap_or(false); + let confirmed = + crate::confirm::read_answer(&mut std::io::stdin().lock(), &mut std::io::stdout()) + .unwrap_or(false); if !confirmed { fail!("Not confirmed; refusing to apply."); } diff --git a/docs/architecture.md b/docs/architecture.md index 15aa2820ee..a659605192 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -183,7 +183,7 @@ Already-extracted subsystem modules, following the same full-domain-extraction p - [`codex_bridge.rs`](../crates/rocm-core/src/codex_bridge.rs) — (ROCMAI-662) the `CodexBridgeSnapshot`/`CodexBridgeGpuSnapshot`/`CodexBridgeEngine` host-snapshot DTOs. Plain serde data: `rocm` and `rocmd` each build their own snapshot of this shape, so the types live here rather than in either binary. - [`command_capture.rs`](../crates/rocm-core/src/command_capture.rs) — (ROCMAI-720) running the `rocm` binary as a captured child: `CommandCapture`, `run_rocm_capture_with_env` and the `command_capture_text` formatter, shared by `rocmd`'s sandbox/MCP clusters and `rocm`'s chat tool bridge. Each caller passes the environment the child should get rather than this module choosing it; the bounded-execution half is [`process.rs`](../crates/rocm-core/src/process.rs)'s `run_with_timeout`. - [`config.rs`](../crates/rocm-core/src/config.rs) — (ROCMAI-151) the unified `RocmCliConfig` and its nested sections, including the persisted `WatcherMode` enum, the built-in watcher catalog (`BuiltinWatcherSpec`, `builtin_watchers`, `builtin_watcher`) and the rocm-dash dashboard sub-config — see the module's own doc comment for what it owns. -- [`confirm.rs`](../crates/rocm-core/src/confirm.rs) — (issue #769) the shared `[y/N]` prompt primitives: `is_affirmative_answer`, plus `print_prompt` and `read_answer` (each generic over the `Write`/`BufRead` stream so the sequence is unit-testable without a controlled terminal). Deduplicates the print-prompt/read-line/parse sequence that [`fix/consent.rs`](../crates/rocm-core/src/fix/consent.rs)'s `confirm()`, [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs)'s `confirm_uninstall` and [`therock/consent.rs`](../apps/rocm/src/therock/consent.rs)'s `prompt_yes_no` each used to hand-roll. [`uninstall.rs`](../apps/rocm/src/uninstall.rs), [`storage.rs`](../apps/rocm/src/storage.rs) and [`runtimes_cmd.rs`](../apps/rocm/src/runtimes_cmd.rs) reach the prompt only through `confirm_uninstall`. `print_prompt` and `read_answer` stay separate rather than one bundled call because [`fix/consent.rs`](../crates/rocm-core/src/fix/consent.rs)'s `confirm()` attempts the read even when the prompt couldn't be written, while the other callers treat a failed write as fatal; [`fix/consent.rs`](../crates/rocm-core/src/fix/consent.rs)'s `confirm()` also keeps its own `--yes`/non-interactive short-circuit and refusal wording on top of these, since those are specific to the `fix` recipe flow. The module also holds `interactive_terminal`, whether stdin and stdout are both terminals, which callers check before they prompt, and `require_yes_or_interactive`, the `--yes`/terminal guard that [`uninstall.rs`](../apps/rocm/src/uninstall.rs), [`storage.rs`](../apps/rocm/src/storage.rs) and [`runtimes_cmd.rs`](../apps/rocm/src/runtimes_cmd.rs) put in front of that prompt; `interactive_terminal` is re-exported from `lib.rs` as `rocm_core::interactive_terminal` and from `host_gpu.rs` as `rocm_core::host_gpu::interactive_terminal`, the path it had before it moved here. +- [`confirm.rs`](../crates/rocm-core/src/confirm.rs) — (issue #769) the shared `[y/N]` prompt primitives: `parse_answer`, which sorts a typed line into `Answer::Yes`, `Answer::No` (`n`, `no` or an empty line) or `Answer::Unrecognized`, plus `print_prompt` and `read_answer` (each generic over the `Write`/`BufRead` stream so the sequence is unit-testable without a controlled terminal). `read_answer` takes the output stream as well: it ends the prompt line when the input ended without a newline (Ctrl-D, or piped input with no final newline) and says so when an answer is unrecognized and treated as no, showing at most the first 40 characters of the answer, best effort, so a failed write never replaces the verdict. Deduplicates the print-prompt/read-line/parse sequence that [`fix/consent.rs`](../crates/rocm-core/src/fix/consent.rs)'s `confirm()`, [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs)'s `confirm_uninstall` and [`therock/consent.rs`](../apps/rocm/src/therock/consent.rs)'s `prompt_yes_no` each used to hand-roll. [`uninstall.rs`](../apps/rocm/src/uninstall.rs), [`storage.rs`](../apps/rocm/src/storage.rs) and [`runtimes_cmd.rs`](../apps/rocm/src/runtimes_cmd.rs) reach the prompt only through `confirm_uninstall`. `print_prompt` and `read_answer` stay separate rather than one bundled call because [`fix/consent.rs`](../crates/rocm-core/src/fix/consent.rs)'s `confirm()` attempts the read even when the prompt couldn't be written, while the other callers treat a failed write as fatal; [`fix/consent.rs`](../crates/rocm-core/src/fix/consent.rs)'s `confirm()` also keeps its own `--yes`/non-interactive short-circuit and refusal wording on top of these, since those are specific to the `fix` recipe flow. The module also holds `interactive_terminal`, whether stdin and stdout are both terminals, which callers check before they prompt, and `require_yes_or_interactive`, the `--yes`/terminal guard that [`uninstall.rs`](../apps/rocm/src/uninstall.rs), [`storage.rs`](../apps/rocm/src/storage.rs) and [`runtimes_cmd.rs`](../apps/rocm/src/runtimes_cmd.rs) put in front of that prompt; `interactive_terminal` is re-exported from `lib.rs` as `rocm_core::interactive_terminal` and from `host_gpu.rs` as `rocm_core::host_gpu::interactive_terminal`, the path it had before it moved here. - [`crypto.rs`](../crates/rocm-core/src/crypto.rs) — (ROCMAI-152, Phase 7c) RSASSA-PKCS#1 v1.5/SHA-256 sign/verify, generic — not model-catalog-specific. - [`diagnose.rs`](../crates/rocm-core/src/diagnose.rs) — `rocm diagnose`: matches an `Examination` and optional symptom text against the closed failure catalog and returns ranked findings. The module root keeps the public types (`Fix`, `Diagnosis`, `Route`, `DiagnoseReport`), the two score thresholds, `diagnose` itself, the two `vllm_*_symptom_is_diagnosable` classifiers the vLLM engine calls (they run the whole catalog, so they cannot live below it) and the re-exports that keep every `rocm_core::diagnose::` path resolving; everything else lives in child modules under `diagnose/`, with `diagnose.rs` kept as the module root so those paths and the links to it stay valid. The platform children do not import each other, and `catalog.rs` is the only module that names every checker. [`catalog.rs`](../crates/rocm-core/src/diagnose/catalog.rs) (the `CHECKERS` table that tags each check with the platform families it applies to, in catalog order, plus the platform-family resolution, applicability and the out-of-scope message), [`scoring.rs`](../crates/rocm-core/src/diagnose/scoring.rs) (every keyword table, the scoring helpers over them, and the small helpers that read an `Examination` or build a `Diagnosis`), [`report.rs`](../crates/rocm-core/src/diagnose/report.rs) (where an unmatched report is routed upstream, `upstream_route`, `route_when_no_match` and the tracker table behind them, and `render_report_text`, the human-facing view), [`linux.rs`](../crates/rocm-core/src/diagnose/linux.rs) (the checks that apply on Linux only: kernel and module, device-node access, package repositories and the repo-native install, plus the package-manager helpers and `dkms_driver_plan_is_supported`, which the driver planner calls), [`windows.rs`](../crates/rocm-core/src/diagnose/windows.rs) (the checks that apply on Windows only: the HIP SDK, the Adrenalin driver, the Visual C++ runtime and the display driver date, with the version comparison and scores only they use), [`wsl.rs`](../crates/rocm-core/src/diagnose/wsl.rs) (the checks that apply on WSL2 only: the DXCore handoff, the ROCDXG userspace, the distro floor, the Windows host driver and WSL 1), [`host.rs`](../crates/rocm-core/src/diagnose/host.rs) (the checks on the host's configuration that run on more than one platform: wheel architecture, the HSA override, `PATH`, the wheel's ROCm against the system's, an integrated GPU beside a discrete one, and GPUs ROCm does not support), [`engine.rs`](../crates/rocm-core/src/diagnose/engine.rs) (the checks on the engine runtime that run on Linux and WSL2: the vLLM out-of-memory and import failures, a second copy of the code object manager, and a `/dev/shm` too small for a serving workload, plus the two canonical symptom strings the vLLM engine falls back to) and [`test_support.rs`](../crates/rocm-core/src/diagnose/test_support.rs) (test-only: the `Examination` builders that the tests of more than one `diagnose` module share). - [`download.rs`](../crates/rocm-core/src/download.rs) — streaming file downloads with resume and retry: `DownloadRequest`/`DownloadOutcome`, `download_file_streaming(_with_progress)` and the simpler `download_file_to_path(_with_progress)`, `Backoff`, and the retry policy (`DOWNLOAD_MAX_ATTEMPTS`). A download streams to a per-process `.part-` sibling, resumes with a `Range` request, and enforces the caller's size limit, expected length and SHA-256 digest before publishing the file. It uses `ureq`, not the loopback client in [`net.rs`](../crates/rocm-core/src/net.rs), and depends only on [`disk_space.rs`](../crates/rocm-core/src/disk_space.rs). The module is private and [`lib.rs`](../crates/rocm-core/src/lib.rs) re-exports its public names. diff --git a/docs/manual-testing.md b/docs/manual-testing.md index 062ec8d8cc..cbadbcba38 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -1200,7 +1200,13 @@ Expected result: HOME=$(mktemp -d) rocm uninstall --keep-binaries < /dev/null # expect the refusal; exit 1 ``` - At a terminal, the same command asks `[y/N]` and treats Enter as no. + At a terminal, the same command asks `[y/N]` and treats Enter as no. Type + `maybe` and it cancels after printing `"maybe" is not yes or no; treating it + as no.`; an answer longer than 40 characters is shown cut to its first 40, + with `...` after the closing quote. Press Ctrl-D and `uninstall cancelled` + appears on a line of its own, not after the prompt. Nothing is removed in + either case. The same prompt is shared by `rocm fix` and the SDK-overwrite + prompt, so the same answers behave the same way there. ## 11. AIM (Docker) Engine Verification diff --git a/docs/testing.md b/docs/testing.md index 010bb8efb6..edf0c10e6d 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1499,6 +1499,13 @@ is not answered with `--force-dev-binaries` (`uninstall-10`); the help starts its examples with a dry run (`uninstall-11`). The assistant's uninstall preview ends differently, since it has no flag to offer: it says removal needs approval, which `lifecycle_read_mutate_split_is_honest` in [tool_policy.rs](../apps/rocm/src/tool_policy.rs) backs. +`uninstall-13` to `uninstall-15` drive the confirmation prompt under a +pseudo-terminal, which is the only way to reach it, and pin the shared `[y/N]` +helper's behaviour for an answer that is neither yes nor no, for ending the input +with Ctrl-D, and for a plain no, each together with the config folder being left +in place. They run on the default mock lane; the helper's other callers (`rocm fix`, +the SDK-overwrite prompt) share it and are covered by its unit tests in +[confirm.rs](../crates/rocm-core/src/confirm.rs). The `uninstall` command does not start the file logger, which would otherwise create the data folder's `logs` folder before the plan is built: diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index 63e2568f33..147f0455e3 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -156,3 +156,34 @@ Feature: Uninstall And the preview lists the config folder And the preview says removal needs approval And the config folder still holds the user's files + + # The `[y/N]` prompt is shared with `rocm fix` and the SDK-overwrite prompt; + # `rocm uninstall` is the one that is cheap to isolate, so the shared helper's + # behaviour is pinned here. A prompt is only reached on a real terminal (without + # one the command is refused, see uninstall-04), so these run under a + # pseudo-terminal. An answer that is neither yes nor no used to be declined with + # no sign it was not understood, and ending the input (Ctrl-D) left the + # cancellation on the prompt line because no newline had been echoed. + @id:uninstall-unrecognized-answer-is-declined-and-said-so @requires-os:linux + Scenario: uninstall-13 - An answer that is neither yes nor no is declined, and the user is told so + Given the config folder holds the user's files + When the user is asked to confirm an uninstall on a real terminal and types an answer that is neither yes nor no + Then the user is told the answer was not understood and is treated as no + And the uninstall is reported as cancelled + And the config folder still holds the user's files + + @id:uninstall-end-of-input-cancels-on-a-fresh-line @requires-os:linux + Scenario: uninstall-14 - Ending the input at the confirmation prompt cancels on a fresh line + Given the config folder holds the user's files + When the user is asked to confirm an uninstall on a real terminal and ends the input instead of answering + Then the cancellation is reported on its own line, not on the prompt line + And the config folder still holds the user's files + + # The other side of uninstall-13: a deliberate no is not an error to explain. + @id:uninstall-plain-no-is-declined-without-complaint @requires-os:linux + Scenario: uninstall-15 - Answering no is declined without any complaint + Given the config folder holds the user's files + When the user is asked to confirm an uninstall on a real terminal and types no + Then the uninstall is reported as cancelled + And the user is not told the answer was misunderstood + And the config folder still holds the user's files diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index 0dbf34f51c..49a16b9436 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -172,6 +172,145 @@ async fn uninstall_config_unconfirmed(world: &mut E2eWorld) { ); } +/// Run `rocm uninstall` of the config folder only, without `--yes`, under a real +/// terminal, wait for the confirmation prompt and send `keys` as the answer. +/// +/// The piped harness can never reach the prompt (no terminal, so the command is +/// refused first); a pseudo-terminal is the only way to answer it. The screen +/// the user would be looking at is kept as the scenario's output. +async fn answer_uninstall_prompt(world: &mut E2eWorld, keys: &str) { + let root = root(world).to_path_buf(); + let home = root.join("home"); + std::fs::create_dir_all(&home).expect("failed to create isolated HOME"); + let home = home.display().to_string(); + let uv = root.join("uv-cache").display().to_string(); + let hf = root.join("hf-home").display().to_string(); + let config = config_dir(world).display().to_string(); + let mut session = TuiSession::spawn_with_env( + world, + &[ + "uninstall", + "--keep-binaries", + "--keep-data", + "--keep-cache", + ], + &[ + ("HOME", home.as_str()), + ("UV_CACHE_DIR", uv.as_str()), + ("HF_HOME", hf.as_str()), + ("ROCM_CLI_CONFIG_DIR", config.as_str()), + ], + ) + .unwrap_or_else(|e| panic!("failed to open the uninstall prompt: {e}")); + session + .wait_for_screen("Proceed with uninstall? [y/N]:", default_timeout()) + .await + .unwrap_or_else(|e| panic!("the confirmation prompt never appeared: {e}")); + session + .send(keys) + .unwrap_or_else(|e| panic!("failed to answer the prompt: {e}")); + let rc = session + .wait_for_exit_code(default_timeout()) + .await + .unwrap_or_else(|e| panic!("the CLI never exited after the answer: {e}")); + world.cli_output = Some(session.screen_text()); + world.cli_rc = Some(rc); + world.tui = Some(session); +} + +#[when( + "the user is asked to confirm an uninstall on a real terminal and types an answer that is neither yes nor no" +)] +async fn uninstall_prompt_unrecognized(world: &mut E2eWorld) { + answer_uninstall_prompt(world, "maybe\r").await; +} + +#[when( + "the user is asked to confirm an uninstall on a real terminal and ends the input instead of answering" +)] +async fn uninstall_prompt_end_of_input(world: &mut E2eWorld) { + // Ctrl-D on an empty line: the terminal reports end of input and echoes + // nothing, which is what left the cursor on the prompt line. + answer_uninstall_prompt(world, "\x04").await; +} + +#[when("the user is asked to confirm an uninstall on a real terminal and types no")] +async fn uninstall_prompt_no(world: &mut E2eWorld) { + answer_uninstall_prompt(world, "no\r").await; +} + +/// The screen's lines with trailing padding removed. +fn screen_lines(world: &E2eWorld) -> Vec { + output(world) + .lines() + .map(|l| l.trim_end().to_owned()) + .collect() +} + +#[then("the user is told the answer was not understood and is treated as no")] +async fn told_answer_not_understood(world: &mut E2eWorld) { + let lines = screen_lines(world); + let expected = "\"maybe\" is not yes or no; treating it as no."; + assert!( + lines.iter().any(|l| l == expected), + "expected a `{expected}` line on the terminal:\n{}", + output(world) + ); +} + +#[then("the user is not told the answer was misunderstood")] +async fn not_told_answer_misunderstood(world: &mut E2eWorld) { + assert!( + !output(world).contains("is not yes or no"), + "a plain no must not be commented on:\n{}", + output(world) + ); +} + +#[then("the uninstall is reported as cancelled")] +async fn uninstall_reported_cancelled(world: &mut E2eWorld) { + let rc = world.cli_rc.expect("no exit code captured"); + assert_eq!( + rc, + 0, + "declining is not a failure, got exit {rc}:\n{}", + output(world) + ); + assert!( + screen_lines(world) + .iter() + .any(|l| l == "uninstall cancelled"), + "expected an `uninstall cancelled` line on its own:\n{}", + output(world) + ); +} + +#[then("the cancellation is reported on its own line, not on the prompt line")] +async fn cancellation_on_its_own_line(world: &mut E2eWorld) { + let lines = screen_lines(world); + let prompt = lines + .iter() + .find(|l| l.starts_with("Proceed with uninstall? [y/N]:")) + .unwrap_or_else(|| panic!("no prompt line on the terminal:\n{}", output(world))); + assert_eq!( + prompt, + "Proceed with uninstall? [y/N]:", + "nothing may follow the prompt after the input ended:\n{}", + output(world) + ); + assert!( + lines.iter().any(|l| l == "uninstall cancelled"), + "expected an `uninstall cancelled` line on its own:\n{}", + output(world) + ); + assert_eq!( + world.cli_rc, + Some(0), + "ending the input declines, it does not fail:\n{}", + output(world) + ); +} + /// The scenario's own home folder, standing in for the user's. fn home_dir(world: &E2eWorld) -> PathBuf { root(world).join("home")