diff --git a/src-tauri/src/files.rs b/src-tauri/src/files.rs index 60c6a74..8d20b20 100644 --- a/src-tauri/src/files.rs +++ b/src-tauri/src/files.rs @@ -596,11 +596,16 @@ fn find_winget_package_tool(name: &str, file_names: &[String]) -> Option>> = + OnceLock::new(); + #[cfg(target_os = "windows")] fn find_windows_tool(name: &str) -> Option { - static FOUND: OnceLock>> = - OnceLock::new(); - let cache = FOUND.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new())); + let cache = WINDOWS_TOOL_CACHE.get_or_init(Default::default); if let Some(path) = cache.lock().ok().and_then(|tools| tools.get(name).cloned()) { return Some(path); } @@ -613,6 +618,114 @@ fn find_windows_tool(name: &str) -> Option { found } +/// Forget every resolved tool path. A package manager has just installed something, and +/// a path found before that install is no longer a safe answer. +#[cfg(target_os = "windows")] +pub(crate) fn reset_tool_cache() { + if let Some(cache) = WINDOWS_TOOL_CACHE.get() { + if let Ok(mut tools) = cache.lock() { + tools.clear(); + } + } +} + +/// Pick up a PATH that changed while Shift was running. +/// +/// An install writes the new directory into the registry, and a fresh shell or Explorer +/// window picks it up from there; a running process keeps the environment block it was +/// launched with. Without this, a component Shift has *just* installed stays invisible to +/// its own resolver, and the panel reports an install that succeeded as a failure. +/// Reading the two registry PATHs into the live environment also means every child +/// process Shift starts from now on inherits it. +#[cfg(target_os = "windows")] +pub(crate) fn refresh_process_path() { + let current = std::env::var_os("PATH").unwrap_or_default(); + let mut directories: Vec = std::env::split_paths(¤t) + .filter(|directory| !directory.as_os_str().is_empty()) + .collect(); + let before = directories.len(); + for key in [ + ( + windows_sys::Win32::System::Registry::HKEY_CURRENT_USER, + r"Environment", + ), + ( + windows_sys::Win32::System::Registry::HKEY_LOCAL_MACHINE, + r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", + ), + ] { + let Some(path) = windows_registry_path(key.0, key.1) else { + continue; + }; + for directory in std::env::split_paths(&path) { + if !directory.as_os_str().is_empty() && !directories.contains(&directory) { + directories.push(directory); + } + } + } + if directories.len() == before { + return; + } + if let Ok(path) = std::env::join_paths(directories) { + std::env::set_var("PATH", path); + } +} + +/// `Path` from a registry environment key: `HKCU\Environment` for the per-user PATH +/// and the Session Manager key for the machine PATH. +/// +/// `RegGetValueW` is asked without `RRF_NOEXPAND`, so a value stored as +/// `REG_EXPAND_SZ` arrives with `%SystemRoot%`-style references already resolved, which +/// is how the system builds a process environment from the same key. +#[cfg(target_os = "windows")] +fn windows_registry_path( + root: windows_sys::Win32::System::Registry::HKEY, + subkey: &str, +) -> Option { + use std::os::windows::ffi::OsStringExt; + use windows_sys::Win32::System::Registry::{RegGetValueW, RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ}; + + let subkey: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); + let name: Vec = "Path".encode_utf16().chain(std::iter::once(0)).collect(); + let filter = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ; + let mut size = 0_u32; + let queried = unsafe { + RegGetValueW( + root, + subkey.as_ptr(), + name.as_ptr(), + filter, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut size, + ) + }; + if queried != 0 || size == 0 { + return None; + } + let mut buffer = vec![0_u16; size as usize / std::mem::size_of::()]; + let read = unsafe { + RegGetValueW( + root, + subkey.as_ptr(), + name.as_ptr(), + filter, + std::ptr::null_mut(), + buffer.as_mut_ptr().cast(), + &mut size, + ) + }; + if read != 0 { + return None; + } + let end = buffer + .iter() + .position(|value| *value == 0) + .unwrap_or(buffer.len()); + let raw = std::ffi::OsString::from_wide(&buffer[..end]); + Some(raw) +} + #[cfg(target_os = "windows")] fn find_windows_tool_uncached(name: &str) -> Option { let file_names = windows_tool_file_names(name); diff --git a/src-tauri/src/process.rs b/src-tauri/src/process.rs index a1b9714..2e607bc 100644 --- a/src-tauri/src/process.rs +++ b/src-tauri/src/process.rs @@ -23,6 +23,11 @@ const BELOW_NORMAL_PRIORITY_CLASS: u32 = 0x0000_4000; /// would let a verbose child fill the pipe and block until the deadline. const MAX_CAPTURED_OUTPUT: usize = 4 * 1024 * 1024; +/// Present in every message this module returns for a child that outlived its deadline. +/// A caller that must treat "never answered" differently from "answered no" matches on +/// this rather than on the whole sentence, whose seconds count varies. +pub const TIMEOUT_MARKER: &str = "did not finish within"; + fn drain_output(mut reader: impl Read) -> Vec { let mut captured = Vec::new(); let mut buffer = [0_u8; 8192]; @@ -127,7 +132,7 @@ pub fn output_with_timeout( let _ = child.kill(); let _ = child.wait(); break Err(format!( - "The command did not finish within {} seconds.", + "The command {TIMEOUT_MARKER} {} seconds.", timeout.as_secs() )); } @@ -166,6 +171,64 @@ pub fn status_with_timeout( .ok_or_else(|| "The converter exited without a status.".to_string()) } +/// `output_with_timeout` for a long-running install. The installer's exit code is only +/// half the answer - `winget` says the things that matter ("already installed", "needs +/// administrator") in its output - so this captures both, keeps the console hidden, and +/// runs the child below the UI's priority the way `status_with_timeout` does. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub fn output_hidden_with_timeout( + program: impl AsRef, + args: &[&str], + timeout: Duration, +) -> Result { + let mut command = command(program); + background(&mut command); + command + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let deadline = Instant::now() + timeout; + let mut child = command + .spawn() + .map_err(|error| format!("Could not start the command: {error}"))?; + let stdout = child + .stdout + .take() + .map(|pipe| std::thread::spawn(move || drain_output(pipe))); + let stderr = child + .stderr + .take() + .map(|pipe| std::thread::spawn(move || drain_output(pipe))); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if Instant::now() >= deadline => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!( + "The command {TIMEOUT_MARKER} {} seconds.", + timeout.as_secs() + )); + } + Ok(None) => std::thread::sleep(Duration::from_millis(50)), + Err(error) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("Could not monitor the command: {error}")); + } + } + }; + Ok(Output { + status, + stdout: stdout + .and_then(|reader| reader.join().ok()) + .unwrap_or_default(), + stderr: stderr + .and_then(|reader| reader.join().ok()) + .unwrap_or_default(), + }) +} + fn status_with_args_and_timeout( program: impl AsRef, args: &[&str], @@ -190,7 +253,7 @@ fn status_with_args_and_timeout( let _ = child.kill(); let _ = child.wait(); return Err(format!( - "The conversion did not finish within {} seconds.", + "The conversion {TIMEOUT_MARKER} {} seconds.", started.elapsed().as_secs() )); } diff --git a/src-tauri/src/runtime.rs b/src-tauri/src/runtime.rs index 109dfd0..8d9f2c6 100644 --- a/src-tauri/src/runtime.rs +++ b/src-tauri/src/runtime.rs @@ -40,6 +40,176 @@ struct InstallTarget { executable: &'static str, } +/// One argument set handed to `winget install`, tried in the order the installer uses +/// them. A single command line is not enough because two of its flags depend on the +/// package rather than on the caller: without `--source winget` a machine that also +/// carries the msstore source can stop on an agreement that `--silent` never answers, +/// and `--scope user` is refused outright by a package that only installs machine-wide. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum WingetAttempt { + /// Pin the community source and ask for a per-user install explicitly. This is the + /// rung that can succeed where an unscoped install was refused for want of + /// administrator rights, and it still needs no elevation. + UserScope, + /// The same command without a scope, which is what this app has always sent: WinGet + /// picks the scope the package itself prefers. + Unscoped, + /// Force the machine-wide scope, where Poppler, FFmpeg, ImageMagick and Typst + /// live. Reaching it means elevating, so it is attempted last. + MachineScope, +} + +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +impl WingetAttempt { + /// The order a package is offered to `winget`, unelevated. The unscoped shape leads + /// because it is the command line that has always been sent, so a package that + /// installs per-user by default is served on the first attempt exactly as before. The + /// explicit user scope follows as the no-prompt escape hatch for a package whose + /// default is machine-wide: WinGet rejects an unsupported scope while it is still + /// choosing an installer, so that rung costs a handshake rather than a download. + const LADDER: [WingetAttempt; 2] = [WingetAttempt::Unscoped, WingetAttempt::UserScope]; + + fn args(self, package_id: &str) -> Vec { + let scope = match self { + WingetAttempt::UserScope => Some("user"), + WingetAttempt::Unscoped => None, + WingetAttempt::MachineScope => Some("machine"), + }; + let mut args = vec![ + "install".to_string(), + "--id".to_string(), + package_id.to_string(), + "--exact".to_string(), + // `winget` and not `msstore`: a store package needs an agreement these + // flags cannot settle, and none of the components Shift installs live there. + "--source".to_string(), + "winget".to_string(), + "--silent".to_string(), + "--accept-package-agreements".to_string(), + "--accept-source-agreements".to_string(), + ]; + if let Some(scope) = scope { + args.push("--scope".to_string()); + args.push(scope.to_string()); + } + args + } +} + +/// What one `winget` run means. WinGet reports several outcomes that are not failures +/// as a non-zero exit code, so `ExitStatus::success()` alone cannot decide: reading +/// "this package is already installed" as an error is exactly what makes the one-click +/// install report failure on a machine where the component is fine. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum WingetOutcome { + /// Installed, or already there. Either way the row's re-detection has the last word. + Succeeded, + /// WinGet itself cannot serve the request - disabled app execution alias, no + /// working source, no network. No package-shaped retry can fix that, so the batch + /// stops and says which. + Unrecoverable, + /// The package needs elevation, which an unelevated attempt cannot supply. + NeedsElevation, + /// A real failure of this attempt, worth retrying in another shape. + Failed, +} + +/// WinGet raises its own `APPINSTALLER_CLI_ERROR_*` codes under facility `0x8A15`, and +/// the two elevation outcomes arrive as plain Win32 errors under `0x8007`. Matching the +/// whole code rather than its low 16 bits keeps a Win32 error that happens to share a +/// tail with a WinGet code from being read as the wrong thing. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +mod winget_codes { + /// APPINSTALLER_CLI_ERROR_PACKAGE_ALREADY_INSTALLED + pub const ALREADY_INSTALLED: u32 = 0x8A15_002B; + /// APPINSTALLER_CLI_ERROR_UPDATE_NOT_APPLICABLE: the package is there and current. + pub const NO_UPGRADE_APPLICABLE: u32 = 0x8A15_0016; + /// APPINSTALLER_CLI_ERROR_NO_APPLICABLE_INSTALLER + pub const NO_APPLICABLE_INSTALLER: u32 = 0x8A15_0061; + /// APPINSTALLER_CLI_ERROR_INSTALLER_BLOCKED_BY_POLICY + pub const BLOCKED_BY_POLICY: u32 = 0x8A15_002D; + /// APPINSTALLER_CLI_ERROR_NO_APPLICATIONS_FOUND + pub const PACKAGE_NOT_FOUND: u32 = 0x8A15_0018; + /// APPINSTALLER_CLI_ERROR_SOURCE_NOT_CONFIGURED + pub const SOURCE_NOT_CONFIGURED: u32 = 0x8A15_00A5; + /// APPINSTALLER_CLI_ERROR_CLIREPAIR_FAILED: the alias exists but WinGet cannot run. + pub const CLI_REPAIR_FAILED: u32 = 0x8A15_0003; + /// APPINSTALLER_CLI_ERROR_PACKAGE_IN_USE: something holds the install target open. + pub const PACKAGE_IN_USE: u32 = 0x8A15_0064; + /// ERROR_INSTALL_USEREXIT: the user said no to the elevation prompt. + pub const ELEVATION_DECLINED: u32 = 0x8007_012C; + /// ERROR_ELEVATION_REQUIRED + pub const ELEVATION_REQUIRED: u32 = 0x8007_04C7; +} + +/// Classify a `winget` exit code. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +fn classify_winget_status(code: u32) -> WingetOutcome { + use winget_codes::*; + match code { + 0 | ALREADY_INSTALLED | NO_UPGRADE_APPLICABLE => WingetOutcome::Succeeded, + NO_APPLICABLE_INSTALLER + | BLOCKED_BY_POLICY + | PACKAGE_NOT_FOUND + | SOURCE_NOT_CONFIGURED + | CLI_REPAIR_FAILED => WingetOutcome::Unrecoverable, + ELEVATION_DECLINED | ELEVATION_REQUIRED | PACKAGE_IN_USE => WingetOutcome::NeedsElevation, + _ => WingetOutcome::Failed, + } +} + +/// Second opinion from what `winget` printed, used when the exit code is not one of the +/// codes above. WinGet's own wording is the only place the two outcomes that matter +/// most are distinguishable: an elevation the user refused and a source that was never +/// agreed to both arrive as generic failures. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +fn classify_winget_output(output: &str) -> Option { + let text = output.to_ascii_lowercase(); + // "No applicable upgrade was found", "already installed", "Package is already + // installed" - the component is on the machine whatever the exit code said. + if text.contains("already installed") || text.contains("no applicable upgrade") { + return Some(WingetOutcome::Succeeded); + } + if text.contains("administrator") + || text.contains("elevated") + || text.contains("elevation") + || text.contains("run as admin") + { + return Some(WingetOutcome::NeedsElevation); + } + if text.contains("no official windows package manager source") + || text.contains("found no source") + || text.contains("source agreement") + || text.contains("the term 'winget'") + || text.contains("is not recognized") + || text.contains("server is unavailable") + // Reaching for the machine scope cannot fix a machine that cannot download, and + // an elevation prompt on top of a network failure reads as one more thing broken. + || text.contains("internet") + || text.contains("download") + || text.contains("unable to connect") + || text.contains("the server returned") + { + return Some(WingetOutcome::Unrecoverable); + } + None +} + +/// Decide from the exit code first, since it is exact, and fall back to the installer's +/// words for everything it leaves ambiguous. A code that is not in the table is a +/// failure of *this* command line, so it stays `Failed` and the next shape is tried; +/// matching the wording only for the phrases above is what keeps a genuine download +/// error from being read as an elevation problem. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +fn classify_winget_with_output(code: u32, output: &str) -> WingetOutcome { + match classify_winget_status(code) { + WingetOutcome::Failed => classify_winget_output(output).unwrap_or(WingetOutcome::Failed), + outcome => outcome, + } +} + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] fn macos_install_target(id: &str) -> Option { match id { @@ -415,28 +585,56 @@ pub async fn install_runtime_components(component_ids: Vec) -> Result<() /// Install a group of components as one request. The package managers hold one lock /// per tool, so the batch runs one install after another instead of racing itself, /// and a package that serves several rows (Poppler answers both PDF rows on Windows) -/// is installed once. The first failure stops the batch: it is nearly always the -/// package manager itself, so repeating the same failure per row would only add waits. -/// Callers refresh afterwards, which is what reports the rows that did land. +/// is installed once. +/// +/// A row that fails does not abandon the rows after it: on Windows the usual reasons are +/// per-package (a declined elevation prompt, one installer that refused), and dropping the +/// rest would punish components that had nothing to do with the failure. Only an answer +/// about WinGet itself - missing, no source, no answer - stops the batch, because every +/// remaining row would spend its full timeout discovering the same thing. Callers refresh +/// afterwards, which is what reports the rows that did land. fn install_runtime_components_sync(component_ids: &[String]) -> Result<(), String> { let mut installed: Vec<&'static str> = Vec::new(); + let mut first_failure: Option = None; for component_id in component_ids { let target = install_target(component_id) .ok_or_else(|| "unsupported-runtime-component".to_string())?; if installed.contains(&target.package_id) { continue; } - install_target_package(target)?; + if let Err(error) = install_target_package(target) { + if ends_the_batch(&error) { + return Err(error); + } + first_failure.get_or_insert(error); + continue; + } installed.push(target.package_id); } - Ok(()) + match first_failure { + Some(error) => Err(error), + None => Ok(()), + } +} + +/// Whether an install failure is a verdict on the package manager rather than on one +/// package, and therefore worth stopping a batch over. +fn ends_the_batch(error: &str) -> bool { + matches!( + error, + "homebrew-missing" + | "winget-missing" + | "winget-unavailable" + | "winget-install-timeout" + | "winget-launch-failed" + | "unsupported-runtime-component" + ) } fn install_target_package(target: InstallTarget) -> Result<(), String> { - let timeout = Duration::from_secs(15 * 60); - #[cfg(target_os = "macos")] { + let timeout = Duration::from_secs(15 * 60); let brew = files::resolve_tool("brew").ok_or_else(|| "homebrew-missing".to_string())?; let status = crate::process::status_with_timeout(brew, &["install", target.package_id], timeout) @@ -452,28 +650,7 @@ fn install_target_package(target: InstallTarget) -> Result<(), String> { #[cfg(target_os = "windows")] { - let winget = files::resolve_tool("winget").ok_or_else(|| "winget-missing".to_string())?; - let status = crate::process::status_with_timeout( - winget, - &[ - "install", - "--id", - target.package_id, - "--exact", - "--silent", - "--accept-package-agreements", - "--accept-source-agreements", - ], - timeout, - ) - .map_err(|error| format!("winget-install-failed: {error}"))?; - if !status.success() { - return Err(format!("winget-install-failed: {status}")); - } - if files::resolve_tool(target.executable).is_none() { - return Err("winget-install-missing-binary".to_string()); - } - Ok(()) + install_windows_package(target) } #[cfg(not(any(target_os = "macos", target_os = "windows")))] @@ -483,6 +660,196 @@ fn install_target_package(target: InstallTarget) -> Result<(), String> { } } +/// How long one unelevated `winget` run may take. A package manager that is going to +/// answer at all answers in well under this; the ceiling exists so a run that stops on a +/// prompt it can never be answered cannot spend the whole panel's patience twice. +#[cfg(target_os = "windows")] +const WINGET_TIMEOUT: Duration = Duration::from_secs(8 * 60); + +/// Longer for the elevated attempt, whose clock includes the time a person spends +/// reading the UAC prompt. +#[cfg(target_os = "windows")] +const WINGET_ELEVATED_TIMEOUT: Duration = Duration::from_secs(20 * 60); + +/// Run `winget install` once and say what it meant. +#[cfg(target_os = "windows")] +fn run_winget( + winget: &Path, + attempt: WingetAttempt, + package_id: &str, +) -> Result { + let args = attempt.args(package_id); + let references: Vec<&str> = args.iter().map(String::as_str).collect(); + // A run that never answered would not answer on the next shape either, so the + // timeout leaves here as its own code rather than being retried. + let output = crate::process::output_hidden_with_timeout(winget, &references, WINGET_TIMEOUT) + .map_err(|error| { + if error.contains(crate::process::TIMEOUT_MARKER) { + "winget-install-timeout".to_string() + } else { + "winget-launch-failed".to_string() + } + })?; + let code = output.status.code().unwrap_or(-1) as u32; + let report = format!( + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let outcome = classify_winget_with_output(code, &report); + if outcome != WingetOutcome::Succeeded { + // The exit code and the installer's own words are worth having in a log, and + // too long for a sentence: the panel shows a dictionary entry instead. + eprintln!("winget {code:#010x}: {}", report.trim()); + } + Ok(outcome) +} + +/// Whether the hosting shell said the elevation prompt was refused. PowerShell raises +/// `OperationCanceledException` / "The operation was canceled by the user" for a dismissed +/// UAC dialog, which is the only place that decision appears in words. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +fn elevation_was_declined(report: &str) -> bool { + let text = report.to_ascii_lowercase(); + text.contains("canceled by the user") + || text.contains("cancelled by the user") + || text.contains("operationwas_canceled") + || text.contains("this operation requires elevation") +} + +/// Install one WinGet package: several command lines, because the flags that decide +/// success are properties of the package rather than of the caller, and one final check +/// of what actually reached disk. +#[cfg(target_os = "windows")] +fn install_windows_package(target: InstallTarget) -> Result<(), String> { + let winget = files::resolve_tool("winget").ok_or_else(|| "winget-missing".to_string())?; + for attempt in WingetAttempt::LADDER { + match run_winget(&winget, attempt, target.package_id)? { + // Whatever the exit code said, the tool is either on this machine now or it + // is not, and that is the only question the panel answers. + WingetOutcome::Succeeded => return verify_windows_install(target), + WingetOutcome::Unrecoverable => return Err("winget-unavailable".to_string()), + WingetOutcome::Failed => continue, + // Keep working down the ladder: a package that answers "needs administrator" + // to an unscoped install may still install per-user, which is what the next + // rung asks for. A prompt is only raised once every unelevated shape has been + // refused, because the prompt itself is what makes an install feel broken to a + // user who expected a settings switch to just work. + WingetOutcome::NeedsElevation => continue, + } + } + match elevate_windows_install(target.package_id) { + // The only outcome the user can act on by pressing the button again. + Err(ElevationError::Declined) => Err("winget-elevation-declined".to_string()), + Err(ElevationError::Unavailable) => Err("winget-launch-failed".to_string()), + Ok(WingetOutcome::Unrecoverable) => Err("winget-unavailable".to_string()), + // A failure is a failure even when the disk check would also say "not there": + // the two have different advice, and "restart Shift" is only honest about an + // install that *reported* success. + Ok(WingetOutcome::Failed) => Err("winget-install-failed".to_string()), + // Asking a second time after the machine scope itself was refused would only + // repeat the refusal, and "restart Shift" would be the wrong advice: the blocker + // is administrator rights, which is exactly what that message tells the user. + Ok(WingetOutcome::NeedsElevation) => Err("winget-elevation-declined".to_string()), + // A machine-scope success lands in a directory the installer itself adds to the + // machine PATH, which is exactly what `verify_windows_install` re-reads. + Ok(WingetOutcome::Succeeded) => verify_windows_install(target), + } +} + +/// The panel's answer is only as good as the last check: WinGet reporting success and +/// the executable not existing are both reasons to say "missing", and neither is a +/// reason to claim the install failed when the PATH simply has not been read again. +#[cfg(target_os = "windows")] +fn verify_windows_install(target: InstallTarget) -> Result<(), String> { + files::refresh_process_path(); + files::reset_tool_cache(); + if files::resolve_tool(target.executable).is_some() { + return Ok(()); + } + // An installer that has just finished can still hold the new directory until its + // own cleanup writes the registry, so look once more after a short pause. + std::thread::sleep(Duration::from_secs(2)); + files::refresh_process_path(); + files::reset_tool_cache(); + if files::resolve_tool(target.executable).is_some() { + return Ok(()); + } + Err("winget-install-missing-binary".to_string()) +} + +/// What stopped the machine-wide attempt from running at all. +#[cfg(target_os = "windows")] +enum ElevationError { + /// Windows asked, and the answer was no: a decision the user made, not a malfunction, + /// and the only one that is fixed by pressing the same button again. + Declined, + /// The elevated install could not be started, so nothing was ever refused. + Unavailable, +} + +/// Ask WinGet for the machine-wide install through a shell that can elevate, since a +/// process started without a console cannot raise a UAC prompt of its own. +/// +/// `Start-Process -Verb RunAs -Wait -PassThru` is the shape that works from a GUI app: +/// PowerShell shows the prompt, waits for the installer, and hands back its exit code. +/// The elevated `winget` prints into its own console, so its prose never reaches us, but +/// the *hosting* shell's does - and that is where a dismissed prompt announces itself, +/// which no exit code reports reliably. +#[cfg(target_os = "windows")] +fn elevate_windows_install(package_id: &str) -> Result { + let script = format!( + "$p = Start-Process -FilePath winget.exe -ArgumentList '{}' -Verb RunAs -WindowStyle Hidden -Wait -PassThru; exit $p.ExitCode", + WingetAttempt::MachineScope + .args(package_id) + .iter() + .map(|argument| format!("'{argument}'")) + .collect::>() + .join(",") + ); + let output = crate::process::output_hidden_with_timeout( + powershell(), + &[ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-Command", + &script, + ], + WINGET_ELEVATED_TIMEOUT, + ) + // Either the shell is not there or the prompt was never answered; neither is a + // refusal, so neither is reported as one. + .map_err(|_| ElevationError::Unavailable)?; + let code = output.status.code().unwrap_or(-1) as u32; + let report = format!( + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + // PowerShell reports a dismissed prompt as an exception rather than an exit code, and + // `Start-Process` answers 1223 (ERROR_CANCELLED) when the elevated child reports it. + if code == 1223 || elevation_was_declined(&report) { + return Err(ElevationError::Declined); + } + // The re-detection is the authority on whether the tool ended up usable, so a success + // here means "go and look", and a failure is classified for the caller. + if output.status.success() { + return Ok(WingetOutcome::Succeeded); + } + Ok(classify_winget_with_output(code, &report)) +} + +#[cfg(target_os = "windows")] +fn powershell() -> PathBuf { + // The 64-bit path, so a 32-bit host cannot be handed the 32-bit shell whose WinGet + // view of the machine differs on a few packages. + let system = + env::var_os("SystemRoot").unwrap_or_else(|| std::ffi::OsString::from("C:\\Windows")); + PathBuf::from(system).join(r"System32\WindowsPowerShell\v1.0\powershell.exe") +} + fn machine_info_sync() -> RuntimeInfo { let os_version = os_version(); let mut components = vec![ @@ -726,4 +1093,189 @@ mod tests { ); } } + + /// Regression for the Windows one-click install: every command line pinned the + /// community source, because an unpinned `winget` on a machine that also carries + /// msstore can stop on an agreement that `--silent` never answers, and the run then + /// looks identical to a slow install until the deadline kills it. + #[test] + fn every_winget_attempt_pins_the_community_source() { + for attempt in [ + WingetAttempt::UserScope, + WingetAttempt::Unscoped, + WingetAttempt::MachineScope, + ] { + let args = attempt.args("Gyan.FFmpeg"); + let joined = args.join(" "); + assert!(joined.contains("--source winget"), "{joined}"); + assert!(joined.contains("--exact"), "{joined}"); + assert!(joined.contains("--accept-source-agreements"), "{joined}"); + } + } + + /// Elevation is the last resort, so no unelevated rung may ask for the machine scope, + /// and the rung that goes first has to be the plain command line that this app has + /// always sent: a package that installs per-user by default must behave exactly as it + /// did before. The explicit user scope is the escape hatch tried second, for a package + /// whose default is machine-wide. + #[test] + fn the_ladder_escalates_scope_only_when_it_must() { + let scope = |attempt: WingetAttempt| -> Option { + let args = attempt.args("pandoc"); + let at = args.iter().position(|arg| arg == "--scope")?; + args.get(at + 1).cloned() + }; + assert_eq!(scope(WingetAttempt::Unscoped), None); + assert_eq!(scope(WingetAttempt::UserScope), Some("user".into())); + assert_eq!( + scope(WingetAttempt::MachineScope), + Some("machine".into()), + "the escalated attempt must be explicit about the machine scope" + ); + assert_eq!( + WingetAttempt::LADDER, + [WingetAttempt::Unscoped, WingetAttempt::UserScope], + "neither unelevated rung may request the machine scope" + ); + } + + /// The heart of the bug: WinGet reports "already installed" as a non-zero exit code. + /// Reading that as a failure is what made the panel say the one-click install failed + /// on a machine where the component was already present and working. + #[test] + fn an_already_installed_package_is_not_a_failure() { + use winget_codes::*; + assert_eq!(classify_winget_status(0), WingetOutcome::Succeeded); + assert_eq!( + classify_winget_status(ALREADY_INSTALLED), + WingetOutcome::Succeeded + ); + assert_eq!( + classify_winget_status(NO_UPGRADE_APPLICABLE), + WingetOutcome::Succeeded + ); + } + + /// Only elevation-shaped codes may send the installer down the UAC path, and only + /// package-manager-shaped codes may stop a whole batch. A Win32 error that happens to + /// share the low 16 bits of a WinGet code must not be confused for one: that is why + /// the whole code is matched. + #[test] + fn exit_codes_are_separated_by_who_can_fix_them() { + use winget_codes::*; + assert_eq!( + classify_winget_status(ELEVATION_REQUIRED), + WingetOutcome::NeedsElevation + ); + assert_eq!( + classify_winget_status(ELEVATION_DECLINED), + WingetOutcome::NeedsElevation + ); + assert_eq!( + classify_winget_status(PACKAGE_IN_USE), + WingetOutcome::NeedsElevation + ); + assert_eq!( + classify_winget_status(CLI_REPAIR_FAILED), + WingetOutcome::Unrecoverable + ); + assert_eq!( + classify_winget_status(SOURCE_NOT_CONFIGURED), + WingetOutcome::Unrecoverable + ); + assert_eq!( + classify_winget_status(BLOCKED_BY_POLICY), + WingetOutcome::Unrecoverable + ); + // A plain Win32 code sharing a tail with a WinGet one stays an ordinary failure. + assert_eq!(classify_winget_status(0x8007_002B), WingetOutcome::Failed); + assert_eq!(classify_winget_status(0x8007_0005), WingetOutcome::Failed); + } + + /// Two outcomes that arrive as generic failures are only separable from the + /// installer's wording, and both change what the user should do next. + #[test] + fn the_installer_own_words_break_a_tie() { + assert_eq!( + classify_winget_with_output( + 0x8007_0005, + "Package installation failed: this package requires administrator privileges." + ), + WingetOutcome::NeedsElevation + ); + assert_eq!( + classify_winget_with_output(0x8007_0005, "No applicable upgrade was found."), + WingetOutcome::Succeeded + ); + assert_eq!( + classify_winget_with_output(0x8007_0005, "Found no source; agreements not accepted."), + WingetOutcome::Unrecoverable + ); + // An exact code outranks the prose: an unhelpful log line cannot turn a real + // success into a retry. + assert_eq!( + classify_winget_with_output(0x8A15_002B, "installation failed"), + WingetOutcome::Succeeded + ); + assert_eq!( + classify_winget_with_output(0x8007_0057, "something nobody has read yet"), + WingetOutcome::Failed + ); + // A machine that cannot download must stop here. Left to fall through as an + // ordinary failure it would reach the elevated attempt and raise a UAC prompt + // that cannot possibly help, which is how a network outage gets reported as + // "installation failed" on a machine where the answer was "check your Wi-Fi". + for report in [ + "Internet connection failed. Check your network.", + "Download of installer failed.", + "Unable to connect to the server.", + ] { + assert_eq!( + classify_winget_with_output(0x8A15_0101, report), + WingetOutcome::Unrecoverable, + "{report} should not escalate to an elevation prompt" + ); + } + } + + /// A declined elevation prompt is reported by the hosting shell in prose rather than + /// by a reliable exit code, and it is the one failure the panel answers with "press + /// Install again and choose Yes". + #[test] + fn a_closed_prompt_reads_as_a_refusal() { + assert!(elevation_was_declined( + "Start-Process : The operation was canceled by the user" + )); + assert!(elevation_was_declined( + "This operation requires elevation. Run as administrator." + )); + assert!( + !elevation_was_declined("Internet connection failed. Check your network."), + "a dead network is not a user saying no" + ); + } + + /// Only a verdict about the package manager may abandon the rest of a batch. Per-package + /// outcomes - a declined prompt, one installer that refused - must leave the other rows + /// free to install, because "一键安装" is asking for all of them. + #[test] + fn only_a_broken_package_manager_ends_the_batch() { + for code in [ + "homebrew-missing", + "winget-missing", + "winget-unavailable", + "winget-install-timeout", + "winget-launch-failed", + ] { + assert!(ends_the_batch(code), "{code} should stop the batch"); + } + for code in [ + "winget-elevation-declined", + "winget-install-failed", + "winget-install-missing-binary", + "homebrew-install-missing-binary", + ] { + assert!(!ends_the_batch(code), "{code} should not stop the batch"); + } + } } diff --git a/src/components/MainWindow.tsx b/src/components/MainWindow.tsx index 0ecf862..04a3c7b 100644 --- a/src/components/MainWindow.tsx +++ b/src/components/MainWindow.tsx @@ -519,7 +519,7 @@ export function MainWindow() { setRuntimeInstallHelp( message === "homebrew-missing" ? "homebrew" - : message === "winget-missing" + : message === "winget-missing" || message === "winget-unavailable" ? "winget" : null, ); @@ -541,14 +541,23 @@ export function MainWindow() { console.error(message); return t("runtimeInstallFailed"); } - if (message.startsWith("winget-install-failed:")) { - console.error(message); - return t("runtimeInstallFailed"); - } if ( message === "homebrew-install-missing-binary" || message === "winget-install-missing-binary" ) { + // The installer reported success and Shift still cannot see the tool. On Windows + // that is nearly always a PATH the running process has not re-read, and it is + // fixed by restarting Shift rather than by pressing Install again. + if (message === "winget-install-missing-binary") return t("runtimeInstallNotOnPath"); + return t("runtimeInstallFailed"); + } + // Windows names each shape of failure it can distinguish, because "installation + // failed" cannot tell a closed UAC prompt from a dead network - and only one of + // those is fixed by pressing the same button again. + if (message === "winget-elevation-declined") return t("runtimeInstallNeedsAdmin"); + if (message === "winget-unavailable") return t("runtimeInstallNoPackageManager"); + if (message === "winget-install-timeout") return t("runtimeInstallTimedOut"); + if (message === "winget-install-failed" || message === "winget-launch-failed") { return t("runtimeInstallFailed"); } // Every failure the installer raises is a code it names here, so anything diff --git a/src/i18n.ts b/src/i18n.ts index f24abd2..5ca9624 100644 --- a/src/i18n.ts +++ b/src/i18n.ts @@ -202,6 +202,14 @@ const messages: Record> = { "Automatic installation requires Microsoft App Installer (WinGet). Install or update it, then try again.", runtimeInstallUnsupported: "Automatic installation is not available for this component.", runtimeInstallFailed: "Installation failed.", + runtimeInstallNeedsAdmin: + "This component installs machine-wide, so Windows asks for permission. The prompt was closed, so nothing was installed — press Install again and choose Yes.", + runtimeInstallNotOnPath: + "The installer finished, but Shift cannot find the tool yet. Restart Shift and press Refresh.", + runtimeInstallNoPackageManager: + "WinGet could not reach its package source. Check the network, or install the component yourself and press Refresh.", + runtimeInstallTimedOut: + "WinGet did not answer, usually because a Windows Update is holding the installer. Try again once it finishes.", runtimeOpenHomebrew: "Open brew.sh", runtimeOpenWinget: "WinGet setup guide", runtimeBundledInApp: "Included in Shift", @@ -460,6 +468,14 @@ const messages: Record> = { "Windows 自动安装需要“应用安装程序”(WinGet)。安装或更新后请重试。", runtimeInstallUnsupported: "此组件暂不支持自动安装。", runtimeInstallFailed: "安装失败。", + runtimeInstallNeedsAdmin: + "该组件需要为整机安装,Windows 会请求管理员权限。授权窗口被关闭了,因此没有安装:请再次点击“安装”并选择“是”。", + runtimeInstallNotOnPath: + "安装程序已完成,但 Shift 暂时找不到该工具。请重启 Shift 后点击“重新检测”。", + runtimeInstallNoPackageManager: + "WinGet 无法连接组件源。请检查网络,或自行安装该组件后点击“重新检测”。", + runtimeInstallTimedOut: + "WinGet 没有响应,通常是被 Windows 更新占住了安装程序。等它结束后再试。", runtimeOpenHomebrew: "打开 brew.sh", runtimeOpenWinget: "打开 WinGet 安装说明", runtimeBundledInApp: "随 Shift 内置",