From 6fc584f9fb24a5947d3b4a2987d04b2659216a1c Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Thu, 3 Dec 2026 08:33:48 +0800 Subject: [PATCH 1/3] install: keep following the device while the account is typed The account's questions open as soon as the device is in DFU mode, while the install system boots. They were read blocking, so a stalled start ("Reconnect the cable at your iPad") or a failed one stayed unseen until the typing was done. The questions are now read key by key on a thread of their own, in raw mode, and the run keeps following the flow: what it says goes above the question, which is drawn again below with what was typed (dots for the password and PIN); a stall also rings the bell once. A start that fails meanwhile closes the question and the DFU-again step runs; the account is asked again when the flow is back at it. Without a terminal, or with --password-file or --pin-file, nothing changes. The terminal is put back on every way out (Ctrl-C through the signal handler, errors through Drop). Assisted-by: LLM --- CHANGELOG.md | 3 + crates/cli/src/commands/install.rs | 210 +++++++++++++++++++--- crates/cli/src/commands/term.rs | 277 +++++++++++++++++++++++++++-- 3 files changed, 456 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bff7de9..fc657b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ is on main, the release is published with that section as its notes (AGENTS.md, ### Installer and launcher +- The terminal installer shows 'Reconnect the cable' while you type your + password, instead of waiting silently. + - On Linux, a start through palera1n or checkra1n begins only once the computer has given your account access to the device, so the tool is no longer refused it in its first moment. When a tool is refused the device diff --git a/crates/cli/src/commands/install.rs b/crates/cli/src/commands/install.rs index 66bac74..e508bb4 100644 --- a/crates/cli/src/commands/install.rs +++ b/crates/cli/src/commands/install.rs @@ -6,7 +6,7 @@ //! (exit 5) naming the flag. With --json each step is one JSON object per line //! on stdout; the words for people go to the terminal. use crate::args::Global; -use super::term::{bar, gradient, s, Span, Term, BLUE, FG, GREEN, MUTED, RED, SUB, TITLE, TRACK, YELLOW}; +use super::term::{bar, gradient, s, KeyReader, Span, Term, Typed, BLUE, FG, GREEN, MUTED, RED, SUB, TITLE, TRACK, YELLOW}; use orchard_flow::recovery::{self, Phase, Run}; use orchard_flow::{Again, App, Event, Flow, Layout, Link, Sequence, State, UsbMode, MIN_OMARCHY_GB}; use orchard_runtime::disk_file::{Clash, DiskFile}; @@ -17,7 +17,7 @@ use std::io::BufRead; use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, TryRecvError}; use std::time::{Duration, Instant}; /// Outcomes, as the exit status. @@ -1491,16 +1491,21 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { let mut disk_said = false; // After the end block, while the started system may still say it is ready. let mut ready_wait: Option = None; + // The newest flow the account's questions saw, not yet gone through here. + let mut followed: Option = None; loop { out.term.tick(); shared.tick(&mut out); for event in shared.keys(&mut out) { send(event); } - let flow = match rx.recv_timeout(Duration::from_millis(100)) { - Ok(flow) => Some(flow), - Err(RecvTimeoutError::Timeout) => None, - Err(RecvTimeoutError::Disconnected) => return finish(&mut out, Exit::Failed, "driver", "the installer stopped"), + let flow = match followed.take() { + Some(flow) => Some(flow), + None => match rx.recv_timeout(Duration::from_millis(100)) { + Ok(flow) => Some(flow), + Err(RecvTimeoutError::Timeout) => None, + Err(RecvTimeoutError::Disconnected) => return finish(&mut out, Exit::Failed, "driver", "the installer stopped"), + }, }; let interrupts = INTERRUPTS.load(Ordering::SeqCst); let busy = shared.last == "splitting" || shared.last == "installing"; @@ -1906,16 +1911,51 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { } // The name this device gets for plain ssh, where it is certain already. let ssh_name = flow.state.device().and_then(|d| orchard_runtime::ssh_config::coming_for(&handle.executor, d)); - let Some(account) = make_account(&mut out, &user, password.clone(), pin.clone().filter(|_| wants_pin), wants_pin, ssh_name.as_deref(), args) else { - send(Event::Quit); - std::thread::sleep(Duration::from_secs(1)); - return finish(&mut out, Exit::NeedsInput, "needs-input", if wants_pin { "--password-file/--pin-file" } else { "--password-file" }); + // The device starts meanwhile: in a terminal, without the + // files' answers, what it says shows above the questions. + let mut follow = |out: &mut Out| loop { + match rx.try_recv() { + Ok(next) => { + let said = follow_flow(out, &mut shared, &next); + followed = Some(next); + if !matches!(said, Follow::Go) { + return said; + } + } + Err(TryRecvError::Empty) => return Follow::Go, + Err(TryRecvError::Disconnected) => return Follow::Exit(finish(out, Exit::Failed, "driver", "the installer stopped")), + } + }; + let following = out.term.tty && args.password_file.is_none() && args.pin_file.is_none(); + let asked = make_account(&mut out, &user, password.clone(), pin.clone().filter(|_| wants_pin), wants_pin, ssh_name.as_deref(), args, following.then_some(&mut follow as &mut dyn FnMut(&mut Out) -> Follow)); + let account = match asked { + Ok(account) => account, + Err(Stop::NeedsInput) => { + send(Event::Quit); + std::thread::sleep(Duration::from_secs(1)); + return finish(&mut out, Exit::NeedsInput, "needs-input", if wants_pin { "--password-file/--pin-file" } else { "--password-file" }); + } + // Starting it didn't work: DFU mode again, and the + // questions again when the flow is back here. + Err(Stop::Left) => { + account_sent = false; + continue; + } + Err(Stop::Exit(code)) => return code, }; ssh_chosen = account.ssh; send(Event::EditAccount(account)); - if env.is_none() { + let booting = match &followed { + Some(newer) => matches!(newer.state, State::CreateAccount { env: None, .. }), + None => env.is_none(), + }; + if booting { out.term.live_restart(vec![s(orchard_flow::for_device("Your iPad is getting ready"), SUB)]); } + // What came meanwhile goes on from the newest flow. + if followed.is_some() { + continue; + } } // The device is ready; the install goes on once the // system's files are there too. @@ -2079,9 +2119,73 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { } } +/// Why the account's questions ended without an account. +enum Stop { + /// Without a terminal, an answer no flag gave. + NeedsInput, + /// The flow left the account's step (starting the device didn't work). + Left, + /// The run ends (the flow said so meanwhile). + Exit(ExitCode), +} + +/// What following the flow says while a question is open. +enum Follow { + Go, + Left, + Exit(ExitCode), +} + +/// A flow that came while the account is typed: what the run says for it +/// goes above the question (a stalled start rings the bell too), and once +/// the flow has left the account's step the question gives way. +fn follow_flow(out: &mut Out, shared: &mut Shared, flow: &Flow) -> Follow { + if !matches!(flow.state, State::CreateAccount { .. }) { + return Follow::Left; + } + let stalled = shared.stalled; + if let Next::Exit(code) = shared.see(out, flow) { + return Follow::Exit(code); + } + if shared.stalled && !stalled { + out.term.bell(); + } + Follow::Go +} + +/// A question's answer, read key by key while FOLLOW keeps up with the +/// flow; as `Term::ask` without FOLLOW. None without a terminal. +fn ask(out: &mut Out, prompt: Vec, secret: bool, follow: &mut Option<&mut dyn FnMut(&mut Out) -> Follow>) -> Result, Stop> { + let Some(follow) = follow.as_mut().filter(|_| out.term.tty) else { + return Ok(out.term.ask(prompt, secret)); + }; + let Some(keys) = KeyReader::start() else { + return Ok(out.term.ask(prompt, secret)); + }; + out.term.open_prompt(prompt, secret); + let ended = loop { + match keys.next(Duration::from_millis(100)) { + Typed::Byte(byte) if out.term.prompt_key(byte) => break Ok(()), + // The terminal gone: what was typed, as a line read to its end. + Typed::Gone => break Ok(()), + Typed::Byte(_) | Typed::Nothing => {} + } + match follow(out) { + Follow::Go => {} + Follow::Left => break Err(Stop::Left), + Follow::Exit(code) => break Err(Stop::Exit(code)), + } + }; + let typed = out.term.close_prompt(ended.is_ok()); + drop(keys); + ended.map(|()| Some(typed)) +} + /// The account from the flags or the prompts (T.6), checked as the window checks it; -/// the PIN only where the release asks for one (WANTS_PIN). -fn make_account(out: &mut Out, user: &str, password: Option, pin: Option, wants_pin: bool, ssh_name: Option<&str>, args: &InstallArgs) -> Option { +/// the PIN only where the release asks for one (WANTS_PIN). FOLLOW keeps up +/// with the flow while a question is open. +#[allow(clippy::too_many_arguments)] +fn make_account(out: &mut Out, user: &str, password: Option, pin: Option, wants_pin: bool, ssh_name: Option<&str>, args: &InstallArgs, mut follow: Option<&mut dyn FnMut(&mut Out) -> Follow>) -> Result { out.term.blank(); out.heading("Create your account", Some(orchard_flow::for_device("Your iPad is getting ready in the meantime.").into())); if cfg!(target_os = "macos") { @@ -2089,9 +2193,9 @@ fn make_account(out: &mut Out, user: &str, password: Option, pin: Option } out.term.blank(); out.term.line(vec![s(format!(" {:<19}", "Username"), SUB), s(user, FG)]); - let password = secret_pair(out, "Password", "Repeat password", "--password-file", password, "password", |p| (p.chars().count() >= 8).then_some(()).ok_or("The password needs 8 or more characters"))?; + let password = secret_pair(out, "Password", "Repeat password", "--password-file", password, "password", |p| (p.chars().count() >= 8).then_some(()).ok_or("The password needs 8 or more characters"), &mut follow)?; let pin = if wants_pin { - secret_pair(out, "Lock screen PIN", "Repeat PIN", "--pin-file", pin, "PIN", |p| (p.len() == 6 && p.bytes().all(|b| b.is_ascii_digit())).then_some(()).ok_or("The PIN needs exactly 6 digits"))? + secret_pair(out, "Lock screen PIN", "Repeat PIN", "--pin-file", pin, "PIN", |p| (p.len() == 6 && p.bytes().all(|b| b.is_ascii_digit())).then_some(()).ok_or("The PIN needs exactly 6 digits"), &mut follow)? } else { String::new() }; @@ -2101,35 +2205,39 @@ fn make_account(out: &mut Out, user: &str, password: Option, pin: Option false } else { out.term.blank(); - let answer = out.term.ask(vec![s(" Allow SSH from this computer? ", FG), s("[y/N] ", MUTED)], false); + let answer = ask(out, vec![s(" Allow SSH from this computer? ", FG), s("[y/N] ", MUTED)], false, &mut follow)?; let yes = matches!(answer.as_deref().map(str::trim), Some("y" | "Y" | "yes")); if yes { out.muted(format!("Adds this computer's keys: {} over the USB cable, no password.", orchard_flow::ssh_command(user, ssh_name))); } yes }; - Some(orchard_flow::Account { username: user.to_owned(), password: password.clone(), password_again: password, pin: pin.clone(), pin_again: pin, ssh, pin_asked: wants_pin }) + Ok(orchard_flow::Account { username: user.to_owned(), password: password.clone(), password_again: password, pin: pin.clone(), pin_again: pin, ssh, pin_asked: wants_pin }) } /// A password or PIN from its flag, or asked twice until both match and CHECK passes. -fn secret_pair(out: &mut Out, label: &str, again: &str, flag: &str, given: Option, what: &str, check: impl Fn(&str) -> Result<(), &'static str>) -> Option { +#[allow(clippy::too_many_arguments)] +fn secret_pair(out: &mut Out, label: &str, again: &str, flag: &str, given: Option, what: &str, check: impl Fn(&str) -> Result<(), &'static str>, follow: &mut Option<&mut dyn FnMut(&mut Out) -> Follow>) -> Result { if let Some(v) = given { out.term.line(vec![s(format!(" {label:<19}"), SUB), s(format!("from {flag}"), MUTED)]); - return Some(v); + return Ok(v); } loop { - let a = out.term.ask(vec![s(format!(" {label:<19}"), SUB)], true); - let b = a.as_ref().and_then(|_| out.term.ask(vec![s(format!(" {again:<19}"), SUB)], true)); + let a = ask(out, vec![s(format!(" {label:<19}"), SUB)], true, follow)?; + let b = match a { + Some(_) => ask(out, vec![s(format!(" {again:<19}"), SUB)], true, follow)?, + None => None, + }; match (a, b) { (Some(a), Some(b)) if a != b => out.warn(format!("The {what}s don't match. Once more:")), (Some(a), Some(_)) => match check(&a) { - Ok(()) => return Some(a), + Ok(()) => return Ok(a), Err(why) => out.warn(format!("{why}. Once more:")), }, _ => { out.event(json!({"event": "needs", "action": "input", "flag": flag})); out.fail(format!("Run again with {flag} FILE (or - for stdin)")); - return None; + return Err(Stop::NeedsInput); } } } @@ -2400,6 +2508,62 @@ mod tests { assert!(install_args(&["omarchy-a", "--kernel", "linux", "--demo"]).is_none()); } + /// What the terminal was given, shared with the test. + #[derive(Clone, Default)] + struct Screen(std::sync::Arc>>); + + impl std::io::Write for Screen { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl Screen { + fn take(&self) -> String { + String::from_utf8(std::mem::take(&mut *self.0.lock().unwrap())).unwrap() + } + } + + #[test] + fn a_stalled_start_while_typing_shows_above_the_question_and_keeps_what_was_typed() { + use orchard_flow::{Account, Device, DeviceId, Model, OsVersion, Routes, Support}; + let screen = Screen::default(); + let mut out = Out { term: Term::to(Box::new(screen.clone())), json: false }; + let cli = ::try_parse_from(["orchard", "install", "omarchy-a"]).unwrap(); + let mut shared = Shared::new(App::Installer, 0, &cli.global); + let device = Device { id: DeviceId("e".into()), board: "j71b".into(), name: "iPad".into(), model: Model::IpadHome, sequence: Sequence::HomePower, support: Support::Supported, os: OsVersion::Unknown, routes: Routes::default() }; + let account = Flow { state: State::CreateAccount { device: device.clone(), account: Account::default(), env: None, erase_approved: false, slow: false }, ..Flow::new() }; + shared.see(&mut out, &account); + out.term.open_prompt(vec![s(" Password ", SUB)], true); + for &b in b"abc" { + assert!(!out.term.prompt_key(b)); + } + screen.take(); + // palera1n stalls: the hint above, the bell, the question again with its dots. + let stalled = Flow { boot_stalled: true, ..account.clone() }; + assert!(matches!(follow_flow(&mut out, &mut shared, &stalled), Follow::Go)); + let shown = screen.take(); + let hint = shown.find("! Reconnect the cable at your iPad").expect(&shown); + let bell = shown.find('\x07').expect(&shown); + assert!(shown.starts_with("\r\x1b[2K"), "{shown:?}"); + assert!(hint < bell && shown.replace('\x07', "").ends_with("\n Password •••"), "{shown:?}"); + // Once: the same stall again says nothing. + assert!(matches!(follow_flow(&mut out, &mut shared, &stalled), Follow::Go)); + assert_eq!(screen.take(), ""); + assert!(out.term.prompt_key(b'\r')); + assert_eq!(out.term.close_prompt(true), "abc"); + // Starting it didn't work: the question gives way to DFU mode again. + out.term.open_prompt(vec![s(" Password ", SUB)], true); + let failed = orchard_flow::step(App::Installer, account, Event::ChainFailed("palera1n: Unable to perform checkm8".into())).0; + assert!(matches!(follow_flow(&mut out, &mut shared, &failed), Follow::Left)); + assert_eq!(out.term.close_prompt(false), ""); + assert!(screen.take().ends_with("\r\x1b[2K")); + } + #[test] fn a_layer_built_here_is_installed_from_its_file() { let layer = orchard_build::layer::Layer { diff --git a/crates/cli/src/commands/term.rs b/crates/cli/src/commands/term.rs index 5ef2a19..736205f 100644 --- a/crates/cli/src/commands/term.rs +++ b/crates/cli/src/commands/term.rs @@ -7,7 +7,9 @@ use std::fs::File; use std::io::{Read, Write}; use std::os::fd::FromRawFd; use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; -use std::time::Instant; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; +use std::sync::Arc; +use std::time::{Duration, Instant}; /// A question is waiting for its line (Ctrl-C then quits at once). pub static ASKING: AtomicBool = AtomicBool::new(false); @@ -68,7 +70,9 @@ const FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", " pub struct Term { /// The terminal, kept aside before stderr went to the log. - out: File, + out: Box, + /// Its fd, for its size. + fd: i32, pub tty: bool, color: bool, live: Option<(Vec, Instant)>, @@ -81,6 +85,9 @@ pub struct Term { counting: Option, /// Rows of the last block, while nothing was printed after it. block: Option, + /// The question being typed into while the run goes on (see + /// `open_prompt`): lines print above it, and it is drawn again below. + prompt: Option, } impl Term { @@ -105,10 +112,11 @@ impl Term { } } let log_file = log_path.is_some(); - { + let fd = { use std::os::fd::AsRawFd; - TTY_FD.store(out.as_raw_fd(), Ordering::SeqCst); - } + out.as_raw_fd() + }; + TTY_FD.store(fd, Ordering::SeqCst); if tty { // SAFETY: once, before any signal handler reads it. unsafe { @@ -118,7 +126,13 @@ impl Term { } } } - Term { out, tty, color, live: None, log: log_file, log_path, raw: None, counting: None, block: None } + Term { out: Box::new(out), fd, tty, color, live: None, log: log_file, log_path, raw: None, counting: None, block: None, prompt: None } + } + + /// A terminal that writes to OUT, plain, as a terminal (tests). + #[cfg(test)] + pub fn to(out: Box) -> Term { + Term { out, fd: -1, tty: true, color: false, live: None, log: false, log_path: None, raw: None, counting: None, block: None, prompt: None } } fn paint(&self, spans: &[Span]) -> String { @@ -137,7 +151,7 @@ impl Term { } fn clear_live(&mut self) { - if self.tty && self.live.is_some() { + if self.tty && self.live.is_some() && self.prompt.is_none() { let _ = write!(self.out, "\r\x1b[2K"); } } @@ -150,7 +164,13 @@ impl Term { } self.clear_live(); let text = self.paint(&spans); - let _ = writeln!(self.out, "{text}"); + match &self.prompt { + // Above the question, which is drawn again below it as it was. + Some(prompt) if self.tty => prompt.above(&mut self.out, &text), + _ => { + let _ = writeln!(self.out, "{text}"); + } + } if self.log { let plain: String = spans.iter().map(|(t, _)| t.as_str()).collect(); orchard_cache::runlog::line("shown", &plain); @@ -184,9 +204,8 @@ impl Term { fn rows(&self, spans: &[Span]) -> usize { let width: usize = spans.iter().map(|(text, _)| text.chars().count()).sum(); let mut size: libc::winsize = unsafe { std::mem::zeroed() }; - use std::os::fd::AsRawFd; // SAFETY: asks the terminal for its size into a struct this owns. - let columns = match unsafe { libc::ioctl(self.out.as_raw_fd(), libc::TIOCGWINSZ, &mut size) } { + let columns = match unsafe { libc::ioctl(self.fd, libc::TIOCGWINSZ, &mut size) } { 0 if size.ws_col > 0 => usize::from(size.ws_col), _ => 80, }; @@ -224,7 +243,7 @@ impl Term { } fn draw_live(&mut self) { - if !self.tty { + if !self.tty || self.prompt.is_some() { return; } if let Some((spans, started)) = &self.live { @@ -266,6 +285,56 @@ impl Term { Some(line.trim_end_matches(['\r', '\n']).to_owned()) } + /// Opens a question that is typed into key by key (`prompt_key`) while + /// the run goes on: what prints meanwhile goes above it. SECRET shows a + /// dot per character. + pub fn open_prompt(&mut self, prompt: Vec, secret: bool) { + self.keys(false); + self.clear_live(); + self.block = None; + let live = self.live.take(); + let open = Prompt::new(self.paint(&prompt), prompt.iter().map(|(t, _)| t.as_str()).collect(), secret, self.paint(&[s("•", BLUE)]), live); + open.draw(&mut self.out); + self.prompt = Some(open); + ASKING.store(true, Ordering::SeqCst); + } + + /// A key typed into the open question; true when it is answered (Enter). + pub fn prompt_key(&mut self, byte: u8) -> bool { + match &mut self.prompt { + Some(prompt) => prompt.key(byte, &mut self.out), + None => false, + } + } + + /// Closes the open question: ANSWERED leaves it standing, otherwise it + /// goes. What was typed. + pub fn close_prompt(&mut self, answered: bool) -> String { + ASKING.store(false, Ordering::SeqCst); + let Some(prompt) = self.prompt.take() else { + return String::new(); + }; + let _ = if answered { writeln!(self.out) } else { write!(self.out, "\r\x1b[2K") }; + let _ = self.out.flush(); + if self.log && answered { + orchard_cache::runlog::line("shown", &format!("{}{}", prompt.plain, if prompt.secret { "(hidden)".into() } else { prompt.typed() })); + } + // A live line set meanwhile is the newer one. + if self.live.is_none() { + self.live = prompt.live.clone(); + } + self.draw_live(); + prompt.typed() + } + + /// The terminal bell, once. + pub fn bell(&mut self) { + if self.tty { + let _ = write!(self.out, "\x07"); + let _ = self.out.flush(); + } + } + /// Lets the person choose one of ROWS with the arrow keys (or j and k, or /// its number) and Enter, starting at SELECTED; None when they leave /// (Esc, q) or without a terminal. The rows stay, the chosen one marked. @@ -511,6 +580,7 @@ fn waiting_byte() -> bool { impl Drop for Term { fn drop(&mut self) { + self.close_prompt(false); self.keys(false); self.clear_live(); } @@ -595,6 +665,191 @@ impl Escape { } } +/// A question typed into key by key, which the terminal holds: its line +/// can be drawn again below what prints while it is open, with what was +/// typed (dots for a secret). +pub struct Prompt { + /// The question, painted and plain (the log). + text: String, + plain: String, + secret: bool, + dot: String, + bytes: Vec, + escape: Escape, + /// The live line it took the place of. + live: Option<(Vec, Instant)>, +} + +impl Prompt { + fn new(text: String, plain: String, secret: bool, dot: String, live: Option<(Vec, Instant)>) -> Prompt { + Prompt { text, plain, secret, dot, bytes: Vec::new(), escape: Escape::None, live } + } + + /// What was typed so far. + pub fn typed(&self) -> String { + String::from_utf8_lossy(&self.bytes).into_owned() + } + + /// What its line shows of it. + fn shown(&self) -> String { + let typed = self.typed(); + if self.secret { + self.dot.repeat(typed.chars().count()) + } else { + typed + } + } + + fn draw(&self, out: &mut dyn Write) { + let _ = write!(out, "{}{}", self.text, self.shown()); + let _ = out.flush(); + } + + /// LINE above the question: its line cleared, LINE, the question again. + fn above(&self, out: &mut dyn Write, line: &str) { + let _ = writeln!(out, "\r\x1b[2K{line}"); + self.draw(out); + } + + /// A key: Backspace takes a character back, Ctrl-U all; an escape + /// sequence (arrow keys, Delete) is never part of it. True on Enter. + fn key(&mut self, b: u8, out: &mut dyn Write) -> bool { + if self.escape.consumes(b) { + return false; + } + match b { + b'\r' | b'\n' => return true, + 0x7f | 0x08 => { + if let Some(ch) = self.typed().chars().last() { + self.bytes.truncate(self.bytes.len().saturating_sub(ch.len_utf8())); + let _ = write!(out, "\x08 \x08"); + } + } + 0x15 => { + let _ = write!(out, "{}", "\x08 \x08".repeat(self.typed().chars().count())); + self.bytes.clear(); + } + 0x1b => self.escape = Escape::Start, + c if c < 0x20 => {} + c => { + self.bytes.push(c); + // Shown when a character is complete (UTF-8 lead or ASCII). + if let Ok(text) = std::str::from_utf8(&self.bytes) { + let shown = if self.secret { self.dot.clone() } else { text.chars().last().map(String::from).unwrap_or_default() }; + let _ = write!(out, "{shown}"); + } + } + } + let _ = out.flush(); + false + } +} + +/// What the key reader gives. +pub enum Typed { + Byte(u8), + /// Nothing within the wait. + Nothing, + /// The terminal is gone. + Gone, +} + +/// The terminal's keys one at a time, without echo, read on a thread of +/// their own so the run goes on meanwhile. Dropping it stops the thread and +/// puts the terminal back as it was (Ctrl-C: the signal handler does). +pub struct KeyReader { + keys: Receiver>, + stop: Arc, + thread: Option>, + saved: libc::termios, +} + +impl KeyReader { + pub fn start() -> Option { + let saved = cbreak()?; + let (send, keys) = mpsc::channel(); + let stop = Arc::new(AtomicBool::new(false)); + let stopped = stop.clone(); + // It looks for a key every 50 ms, so it is never left waiting in a + // read that takes the next question's first key. + let thread = std::thread::spawn(move || { + while !stopped.load(Ordering::SeqCst) { + let mut fd = libc::pollfd { fd: 0, events: libc::POLLIN, revents: 0 }; + // SAFETY: poll on stdin with one descriptor. + match unsafe { libc::poll(&mut fd, 1, 50) } { + 0 => continue, + n if n < 0 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted => continue, + n if n < 0 => { + let _ = send.send(None); + return; + } + _ => {} + } + let byte = terminal_byte(); + if send.send(byte).is_err() || byte.is_none() { + return; + } + } + }); + Some(KeyReader { keys, stop, thread: Some(thread), saved }) + } + + /// The next key, waited for up to WAIT. + pub fn next(&self, wait: Duration) -> Typed { + match self.keys.recv_timeout(wait) { + Ok(Some(byte)) => Typed::Byte(byte), + Ok(None) | Err(RecvTimeoutError::Disconnected) => Typed::Gone, + Err(RecvTimeoutError::Timeout) => Typed::Nothing, + } + } +} + +impl Drop for KeyReader { + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + restore(self.saved); + } +} + +#[cfg(test)] +mod prompt_tests { + use super::*; + + /// The question "Password: ", secret (dots as *), with BYTES typed. + fn typed(secret: bool, bytes: &[u8]) -> (Prompt, String) { + let mut prompt = Prompt::new("Password: ".into(), "Password: ".into(), secret, "*".into(), None); + let mut out = Vec::new(); + for &b in bytes { + assert!(!prompt.key(b, &mut out)); + } + (prompt, String::from_utf8(out).unwrap()) + } + + #[test] + fn typing_keeps_the_buffer_and_shows_dots_for_a_secret() { + let (prompt, shown) = typed(true, b"pa\x1b[Dss\x7fs"); + assert_eq!(prompt.typed(), "pass"); + assert_eq!(shown, "****\x08 \x08*"); + let (prompt, _) = typed(true, b"abc\x15xy"); + assert_eq!(prompt.typed(), "xy"); + let (mut prompt, shown) = typed(false, "yé".as_bytes()); + assert_eq!((prompt.typed().as_str(), shown.as_str()), ("yé", "yé")); + assert!(prompt.key(b'\r', &mut Vec::new())); + } + + #[test] + fn a_line_goes_above_the_question_which_is_drawn_again_as_it_was() { + let (prompt, _) = typed(true, b"secret"); + let mut out = Vec::new(); + prompt.above(&mut out, "! Reconnect"); + assert_eq!(String::from_utf8(out).unwrap(), "\r\x1b[2K! Reconnect\nPassword: ******"); + assert_eq!(prompt.typed(), "secret"); + } +} + #[cfg(test)] mod escape_tests { use super::Escape; From f6e769371353bfa8cb22db1f0d4adad3cfe5c57a Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Thu, 3 Dec 2026 08:36:38 +0800 Subject: [PATCH 2/3] install: the stall test holds whatever device the words name Assisted-by: LLM --- crates/cli/src/commands/install.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/cli/src/commands/install.rs b/crates/cli/src/commands/install.rs index e508bb4..3bce344 100644 --- a/crates/cli/src/commands/install.rs +++ b/crates/cli/src/commands/install.rs @@ -2547,7 +2547,7 @@ mod tests { let stalled = Flow { boot_stalled: true, ..account.clone() }; assert!(matches!(follow_flow(&mut out, &mut shared, &stalled), Follow::Go)); let shown = screen.take(); - let hint = shown.find("! Reconnect the cable at your iPad").expect(&shown); + let hint = shown.find("! Reconnect the cable at your ").expect(&shown); let bell = shown.find('\x07').expect(&shown); assert!(shown.starts_with("\r\x1b[2K"), "{shown:?}"); assert!(hint < bell && shown.replace('\x07', "").ends_with("\n Password •••"), "{shown:?}"); From ee59d0d3c58d9d24da869335248aebe4efecb746 Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Thu, 3 Dec 2026 08:52:23 +0800 Subject: [PATCH 3/3] install: every question still asked follows the device A password or PIN a file answers isn't asked; the questions that are still asked (the PIN after --password-file, the SSH question) now show a stalled or failed start like the rest. Assisted-by: LLM --- crates/cli/src/commands/install.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/cli/src/commands/install.rs b/crates/cli/src/commands/install.rs index 3bce344..fe5488e 100644 --- a/crates/cli/src/commands/install.rs +++ b/crates/cli/src/commands/install.rs @@ -1911,8 +1911,9 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { } // The name this device gets for plain ssh, where it is certain already. let ssh_name = flow.state.device().and_then(|d| orchard_runtime::ssh_config::coming_for(&handle.executor, d)); - // The device starts meanwhile: in a terminal, without the - // files' answers, what it says shows above the questions. + // The device starts meanwhile: in a terminal, what it says + // shows above every question still asked (one a file + // answered isn't asked). let mut follow = |out: &mut Out| loop { match rx.try_recv() { Ok(next) => { @@ -1926,7 +1927,7 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { Err(TryRecvError::Disconnected) => return Follow::Exit(finish(out, Exit::Failed, "driver", "the installer stopped")), } }; - let following = out.term.tty && args.password_file.is_none() && args.pin_file.is_none(); + let following = out.term.tty; let asked = make_account(&mut out, &user, password.clone(), pin.clone().filter(|_| wants_pin), wants_pin, ssh_name.as_deref(), args, following.then_some(&mut follow as &mut dyn FnMut(&mut Out) -> Follow)); let account = match asked { Ok(account) => account,