Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix(studio): keep a slow install alive and name what it is downloading (#8805)
Long Yixingb69bfe021616
diff --git a/install.ps1 b/install.ps1index 692a8ed1d76..1d4a91b6109 100644--- a/install.ps1+++ b/install.ps1@@ -200,6 +200,30 @@ function Install-UnslothStudio {}}+ # Mirrors _uv_download_markers in install.sh; only what was opened is closed.+ $script:UvDownloadMarkerMinBytes = 52428800+ if ($env:UNSLOTH_DL_MARKER_MIN_BYTES -match '^\d+$') {+ $script:UvDownloadMarkerMinBytes = [long]$env:UNSLOTH_DL_MARKER_MIN_BYTES+ }+ $script:UvAnnouncedDownloads = @{}+ function Write-UvDownloadMarker {+ param([string]$Line)+ if (-not $TauriMode) { return }+ if ($Line -match '(?:^|\s)Downloading (\S+) \(([0-9.]+)(KiB|MiB|GiB)\)\s*$') {+ $unit = @{ KiB = 1024L; MiB = 1048576L; GiB = 1073741824L }[$Matches[3]]+ if ([double]$Matches[2] * $unit -ge $script:UvDownloadMarkerMinBytes) {+ $script:UvAnnouncedDownloads[$Matches[1]] = $true+ Write-TauriLog "DL" "$($Matches[1]) $($Matches[2])$($Matches[3])"+ }+ } elseif ($Line -match '(?:^|\s)Downloaded (\S+)\s*$') {+ # ContainsKey, not Remove's return: Hashtable.Remove is void.+ if ($script:UvAnnouncedDownloads.ContainsKey($Matches[1])) {+ $script:UvAnnouncedDownloads.Remove($Matches[1])+ Write-TauriLog "DL_DONE" $Matches[1]+ }+ }+ }+function Clear-TauriInstallError {param([string]$Message)if ($TauriMode) {@@ -1047,9 +1071,19 @@ public static class UnslothStudioFinalPathV2# Redact per record: uv echoes index URLs (credentials and all) in# its errors, and verbose mode must not bypass the quiet path's# redaction. ForEach-Object/Out-Host leave $LASTEXITCODE untouched.- & $Command 2>&1 | ForEach-Object { Redact-InstallOutput "$_" } | Out-Host+ & $Command 2>&1 | ForEach-Object {+ Write-UvDownloadMarker "$_"+ Redact-InstallOutput "$_"+ } | Out-Host} else {- $output = & $Command 2>&1 | Out-String+ # Streamed, not collected, so a marker reaches the app mid-download.+ $collected = [System.Text.StringBuilder]::new()+ & $Command 2>&1 | ForEach-Object {+ $line = "$_"+ [void]$collected.AppendLine($line)+ Write-UvDownloadMarker $line+ }+ $output = $collected.ToString()if ($LASTEXITCODE -ne 0) {Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red}diff --git a/install.sh b/install.shindex d2a839d1cd8..6b6b29d14c2 100755--- a/install.sh+++ b/install.sh@@ -200,6 +200,48 @@ _redact_install_output() {"$@"}+# Large downloads become markers the app consumes and does not display; forwarding uv's+# own chatter would put dozens of lines in front of the user.+: "${UNSLOTH_DL_MARKER_MIN_BYTES:=52428800}"++# $1 is the child's output sink: a log file for the quiet path, empty to pass it along+# stdout for the verbose one. Markers go to stderr to stay clear of the verbose path's+# redactor -- sed block-buffers, so a marker queued behind it would arrive only once the+# download it announces had finished.+_uv_download_markers() {+ # Minimal images ship without awk, which the uv version probe below also allows for.+ # This pipe now carries every install command, so a missing awk must cost the markers+ # and nothing else: without this the pipeline closes and the child dies of SIGPIPE.+ if ! command -v awk >/dev/null 2>&1; then+ if [ -n "$1" ]; then cat >> "$1"; else cat; fi+ return+ fi+ awk -v logf="$1" -v minb="$2" -v tauri="${TAURI_MODE:-false}" -v err=/dev/stderr '+ { if (logf == "") print; else print >> logf }+ tauri != "true" { next }+ # Field-relative so a leading status glyph cannot shift the match.+ /(^| )Downloading [^ ]+ \([0-9.]+[KMG]iB\)$/ {+ size = $NF+ gsub(/[()]/, "", size)+ n = size; sub(/[KMG]iB$/, "", n)+ u = size; sub(/^[0-9.]+/, "", u)+ mult = (u == "GiB") ? 1073741824 : (u == "MiB") ? 1048576 : 1024+ if (n * mult >= minb) {+ announced[$(NF - 1)] = 1+ print "[TAURI:DL] " $(NF - 1) " " size > err+ fflush(err)+ }+ next+ }+ # Only close what was opened: uv also reports completion for unannounced packages.+ /(^| )Downloaded [^ ]+$/ && ($NF in announced) {+ delete announced[$NF]+ print "[TAURI:DL_DONE] " $NF > err+ fflush(err)+ }+ '+}+run_install_cmd() {_label="$1"shift@@ -225,7 +267,7 @@ run_install_cmd() {_cmd_rc=$?fiprintf '%s' "$_cmd_rc" > "$_rcf"- } | _redact_install_output+ } | _uv_download_markers "" "$UNSLOTH_DL_MARKER_MIN_BYTES" | _redact_install_output_rc=$(cat "$_rcf" 2>/dev/null || echo 1)rm -f "$_rcf"_rc=${_rc:-1}@@ -238,13 +280,25 @@ run_install_cmd() {return "$_rc"fi_log=$(mktemp)+ _rcf=$(mktemp)tauri_stream_log stderr "OUTPUT_CLEAR" "$_label"- "$@" >"$_log" 2>&1 && {+ # rc file because the marker filter is a pipe, and plain sh reports only its last stage.+ {+ if "$@" 2>&1; then+ _cmd_rc=0+ else+ _cmd_rc=$?+ fi+ printf '%s' "$_cmd_rc" > "$_rcf"+ } | _uv_download_markers "$_log" "$UNSLOTH_DL_MARKER_MIN_BYTES"+ _rc=$(cat "$_rcf" 2>/dev/null || echo 1)+ rm -f "$_rcf"+ _rc=${_rc:-1}+ if [ "$_rc" -eq 0 ] 2>/dev/null; thenrm -f "$_log"tauri_clear_install_error "$_label recovered"return 0- }- _rc=$?+ fistep "error" "$_label failed (exit code $_rc)" "$C_ERR" >&2_redact_install_output "$_log" >&2tauri_stream_log stderr "ERROR_OUTPUT" "$_label failed (exit code $_rc)"diff --git a/studio/src-tauri/src/install.rs b/studio/src-tauri/src/install.rsindex 6425b729035..1c77a2b9901 100644--- a/studio/src-tauri/src/install.rs+++ b/studio/src-tauri/src/install.rs@@ -1,4 +1,5 @@use crate::diagnostics::{self, AttemptLog, DiagnosticsState};+use crate::install_watchdog::{self, ProgressWatch, WatchState};use log::{error, info, warn};use process_wrap::std::*;use std::collections::{HashMap, VecDeque};@@ -626,6 +627,7 @@ fn spawn_script(fn stream_output(app: &AppHandle,state: &InstallState,+ watch: &WatchState,event_mode: InstallEventMode,diagnostics: DiagnosticsState,attempt: AttemptLog,@@ -641,6 +643,7 @@ fn stream_output(if let Some(out) = stdout {let app_clone = app.clone();let state_clone = Arc::clone(state);+ let watch_clone = Arc::clone(watch);let diagnostics_clone = diagnostics.clone();let attempt_clone = attempt.clone();let failure_context_clone = Arc::clone(&failure_context);@@ -654,6 +657,12 @@ fn stream_output(Ok(_) => {let text = String::from_utf8_lossy(trim_line_endings(&buf)).into_owned();diagnostics::append_phase_line(&attempt_clone.handle, "stdout", &text);+ // Not forwarded: a line per large dependency is noise. install.sh+ // sends them on stderr and install.ps1 on stdout, so both filter.+ if install_watchdog::note_progress(&watch_clone, &text) {+ info!("[install][stdout] {}", text);+ continue;+ }let is_failure_control = failure_context_clone.lock().map(|mut context| context.observe_stdout(&text))@@ -717,6 +726,7 @@ fn stream_output(if let Some(err) = stderr {let app_clone = app.clone();let attempt_clone = attempt.clone();+ let watch_clone = Arc::clone(watch);let failure_context_clone = Arc::clone(&failure_context);threads.push(std::thread::spawn(move || {let mut reader = std::io::BufReader::new(err);@@ -728,6 +738,10 @@ fn stream_output(Ok(_) => {let text = String::from_utf8_lossy(trim_line_endings(&buf)).into_owned();diagnostics::append_phase_line(&attempt_clone.handle, "stderr", &text);+ if install_watchdog::note_progress(&watch_clone, &text) {+ info!("[install][stderr] {}", text);+ continue;+ }let is_failure_control = failure_context_clone.lock().map(|mut context| context.observe_stderr(&text))@@ -754,35 +768,42 @@ fn stream_output(// ── Wait & Finalize ──/// Waits for the install process to exit. Returns (exit_status, was_intentional_stop).-/// Times out after 2 hours to prevent infinite loops if the child hangs.-fn wait_for_exit(state: &InstallState) -> Result<(ExitStatus, bool), String> {- const MAX_WAIT_ITERATIONS: u32 = 72_000; // 2h at 100ms intervals- for _ in 0..MAX_WAIT_ITERATIONS {- let mut install = state.lock().map_err(|e| e.to_string())?;- let intentional = install.intentional_stop;-- match install.child.as_mut() {- Some(child) => match child.try_wait() {- Ok(Some(status)) => {- install.child = None;- return Ok((status, intentional));- }- Ok(None) => {}- Err(e) => {- install.child = None;- return Err(format!("Error waiting for installer: {}", e));- }- },- None if intentional => return Err("Installation stopped.".to_string()),- None => return Err("Installer process disappeared unexpectedly.".to_string()),- }-- drop(install);- std::thread::sleep(std::time::Duration::from_millis(100));- }- // Timed out — kill and report- let _ = stop_install(state);- Err("Installation timed out after 2 hours".to_string())+/// The deadline is a backstop, not a patience limit; see install_watchdog.+fn wait_for_exit(+ state: &InstallState,+ watch: &WatchState,+ app: &AppHandle,+ event_mode: InstallEventMode,+) -> Result<(ExitStatus, bool), String> {+ install_watchdog::wait_with_watchdog(+ watch,+ || {+ let mut install = state.lock().map_err(|e| e.to_string())?;+ let intentional = install.intentional_stop;+ match install.child.as_mut() {+ Some(child) => match child.try_wait() {+ Ok(Some(status)) => {+ install.child = None;+ Ok(Some((status, intentional)))+ }+ Ok(None) => Ok(None),+ Err(e) => {+ install.child = None;+ Err(format!("Error waiting for installer: {}", e))+ }+ },+ None if intentional => Err("Installation stopped.".to_string()),+ None => Err("Installer process disappeared unexpectedly.".to_string()),+ }+ },+ |line| {+ info!("[install] {}", line);+ let _ = app.emit(event_mode.progress_event(), line);+ },+ || {+ let _ = stop_install(state);+ },+ )}// ── Public API ──@@ -869,9 +890,11 @@ fn run_install_with_event_mode(return Err(msg);}};+ let watch: WatchState = Arc::new(Mutex::new(ProgressWatch::new(std::time::Instant::now())));let (threads, failure_context) = stream_output(&app,&state,+ &watch,event_mode,diagnostics.clone(),attempt.clone(),@@ -880,7 +903,7 @@ fn run_install_with_event_mode();// Wait for exit, join reader threads- let result = wait_for_exit(&state);+ let result = wait_for_exit(&state, &watch, &app, event_mode);for handle in threads {let _ = handle.join();}diff --git a/studio/src-tauri/src/install_watchdog.rs b/studio/src-tauri/src/install_watchdog.rsnew file mode 100644index 00000000000..db489776a0f--- /dev/null+++ b/studio/src-tauri/src/install_watchdog.rs@@ -0,0 +1,322 @@+//! Keeps a slow install alive, and says what it is waiting on.+//!+//! Killing a download wastes every byte: uv restarts an interrupted one from zero+//! (astral-sh/uv#16934), so the budget marks pathology, not impatience.+//!+//! No silence-based stop: the markers miss the uv calls under `studio setup`, whose+//! output is captured rather than streamed, so quiet there does not mean stuck.++use std::time::{Duration, Instant};++/// Long enough that reaching it means something is wrong rather than slow.+pub const BACKSTOP_TIMEOUT: Duration = Duration::from_secs(12 * 60 * 60);+pub const REPORT_INTERVAL: Duration = Duration::from_secs(5 * 60);++#[derive(Debug, PartialEq, Eq)]+pub enum Marker<'a> {+ Start { package: &'a str, size: &'a str },+ Done { package: &'a str },+}++/// `[TAURI:DL] torch 2.4GiB` / `[TAURI:DL_DONE] torch`, from install.sh and install.ps1.+pub fn parse_marker(line: &str) -> Option<Marker<'_>> {+ if let Some(rest) = line.strip_prefix("[TAURI:DL] ") {+ let (package, size) = rest.trim().split_once(' ')?;+ return (!package.is_empty() && !size.is_empty())+ .then_some(Marker::Start { package, size });+ }+ let package = line.strip_prefix("[TAURI:DL_DONE] ")?.trim();+ (!package.is_empty()).then_some(Marker::Done { package })+}++fn human_duration(elapsed: Duration) -> String {+ let minutes = elapsed.as_secs() / 60;+ if minutes < 60 {+ return format!("{} min", minutes);+ }+ match minutes % 60 {+ 0 => format!("{} h", minutes / 60),+ rest => format!("{} h {} min", minutes / 60, rest),+ }+}++struct Download {+ package: String,+ size_text: String,+}++pub struct ProgressWatch {+ started: Instant,+ last_output: Instant,+ last_report: Instant,+ step: String,+ in_flight: Vec<Download>,+ backstop_timeout: Duration,+}++impl ProgressWatch {+ pub fn new(now: Instant) -> Self {+ Self {+ started: now,+ last_output: now,+ last_report: now,+ step: String::new(),+ in_flight: Vec::new(),+ backstop_timeout: BACKSTOP_TIMEOUT,+ }+ }++ #[cfg(test)]+ pub fn with_backstop(now: Instant, backstop: Duration) -> Self {+ Self { backstop_timeout: backstop, ..Self::new(now) }+ }++ pub fn note_output(&mut self, now: Instant) {+ self.last_output = now;+ }++ pub fn note_step(&mut self, step: &str) {+ self.step = step.to_string();+ }++ pub fn note_marker(&mut self, marker: &Marker<'_>, now: Instant) {+ match marker {+ Marker::Start { package, size } => {+ self.in_flight.retain(|d| d.package != *package);+ self.in_flight.push(Download {+ package: (*package).to_string(),+ size_text: (*size).to_string(),+ });+ }+ Marker::Done { package } => self.in_flight.retain(|d| d.package != *package),+ }+ self.note_output(now);+ }++ /// The message to fail with, once the run is long enough to be pathological.+ pub fn expired(&self, now: Instant) -> Option<String> {+ (now.duration_since(self.started) >= self.backstop_timeout).then(|| {+ let budget = human_duration(self.backstop_timeout);+ format!("Installation timed out after {budget}{}.", self.where_it_was())+ })+ }++ /// `None` until a full interval of silence, so a talkative install stays quiet.+ pub fn due_report(&mut self, now: Instant) -> Option<String> {+ if now.duration_since(self.last_output) < REPORT_INTERVAL+ || now.duration_since(self.last_report) < REPORT_INTERVAL+ {+ return None;+ }+ self.last_report = now;+ let elapsed = human_duration(now.duration_since(self.started));+ Some(match self.in_flight.first() {+ Some(download) => format!(+ "downloading {} ({}){} -- {} so far",+ download.package,+ download.size_text,+ self.where_it_was(),+ elapsed+ ),+ None => format!("still working{} -- {} so far", self.where_it_was(), elapsed),+ })+ }++ fn where_it_was(&self) -> String {+ match self.step.is_empty() {+ true => String::new(),+ false => format!(" during \"{}\"", self.step),+ }+ }+}++pub type WatchState = std::sync::Arc<std::sync::Mutex<ProgressWatch>>;++/// Returns true for a marker line, which the caller keeps off the UI.+pub fn note_progress(watch: &WatchState, text: &str) -> bool {+ let Ok(mut watch) = watch.lock() else {+ return false;+ };+ let now = Instant::now();+ if let Some(step) = text.strip_prefix("[TAURI:STEP] ") {+ watch.note_step(step);+ }+ match parse_marker(text) {+ Some(marker) => {+ watch.note_marker(&marker, now);+ true+ }+ None => {+ watch.note_output(now);+ false+ }+ }+}++/// `poll` yields the exit status and whether the stop was asked for, or None while running.+pub fn wait_with_watchdog(+ watch: &std::sync::Mutex<ProgressWatch>,+ mut poll: impl FnMut() -> Result<Option<(std::process::ExitStatus, bool)>, String>,+ mut report: impl FnMut(&str),+ mut stop: impl FnMut(),+) -> Result<(std::process::ExitStatus, bool), String> {+ loop {+ if let Some(exit) = poll()? {+ return Ok(exit);+ }++ let now = Instant::now();+ let (due, expired) = {+ let mut watch = watch.lock().map_err(|e| e.to_string())?;+ (watch.due_report(now), watch.expired(now))+ };+ if let Some(line) = due {+ report(&line);+ }+ if let Some(message) = expired {+ stop();+ return Err(message);+ }++ std::thread::sleep(Duration::from_millis(100));+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::{Arc, Mutex};++ const HOUR: Duration = Duration::from_secs(3600);++ fn watch(now: Instant) -> ProgressWatch {+ ProgressWatch::with_backstop(now, 12 * HOUR)+ }++ /// Built rather than spawned: `cargo test` also runs on Windows, which has no /bin/sh.+ fn exit_status(code: i32) -> std::process::ExitStatus {+ #[cfg(unix)]+ return std::os::unix::process::ExitStatusExt::from_raw(code << 8);+ #[cfg(windows)]+ return std::os::windows::process::ExitStatusExt::from_raw(code as u32);+ }++ #[test]+ fn markers_are_parsed_and_anything_else_is_left_alone() {+ assert_eq!(+ parse_marker("[TAURI:DL] torch 2.4GiB"),+ Some(Marker::Start { package: "torch", size: "2.4GiB" })+ );+ assert_eq!(+ parse_marker("[TAURI:DL_DONE] torch"),+ Some(Marker::Done { package: "torch" })+ );+ for not_ours in [+ "[TAURI:STEP] Installing PyTorch",+ "Downloading torch (2.4GiB)",+ "[TAURI:DL] torch",+ "[TAURI:DL_DONE] ",+ ] {+ assert_eq!(parse_marker(not_ours), None, "{not_ours}");+ }+ }++ #[test]+ fn only_the_backstop_stops_an_install() {+ assert_eq!(BACKSTOP_TIMEOUT, 12 * HOUR, "the shipped budget is what these assert");+ let t0 = Instant::now();+ let mut watch = watch(t0);+ watch.note_step("Installing unsloth");+ // The reporting host needed ~3.7 h for its torch download and was killed at 2 h.+ assert_eq!(watch.expired(t0 + 4 * HOUR), None);+ assert_eq!(watch.expired(t0 + 11 * HOUR + Duration::from_secs(3599)), None);+ let message = watch.expired(t0 + 12 * HOUR).expect("the backstop fires");+ assert!(message.contains("12 h"), "{message}");+ assert!(message.contains("Installing unsloth"), "{message}");+ }++ #[test]+ fn a_silent_stretch_reports_once_per_interval_and_names_the_download() {+ let t0 = Instant::now();+ let mut watch = watch(t0);+ watch.note_step("Installing PyTorch");+ watch.note_marker(&Marker::Start { package: "torch", size: "2.4GiB" }, t0);++ // Output resets the window, so an install that talks never reports.+ watch.note_output(t0 + Duration::from_secs(299));+ assert_eq!(watch.due_report(t0 + Duration::from_secs(300)), None);+ let first = watch.due_report(t0 + Duration::from_secs(600)).expect("a report is due");+ assert!(first.contains("torch") && first.contains("2.4GiB"), "{first}");+ assert!(first.contains("Installing PyTorch") && first.contains("10 min"), "{first}");+ assert_eq!(watch.due_report(t0 + Duration::from_secs(601)), None);+ let second = watch.due_report(t0 + Duration::from_secs(900)).expect("a second report");+ assert!(second.contains("15 min"), "{second}");+ }++ #[test]+ fn a_landed_download_stops_being_named() {+ let t0 = Instant::now();+ let mut watch = watch(t0);+ watch.note_marker(&Marker::Start { package: "torch", size: "2.4GiB" }, t0);+ watch.note_marker(&Marker::Done { package: "torch" }, t0);+ let report = watch.due_report(t0 + Duration::from_secs(600)).expect("a report is due");+ assert!(!report.contains("torch"), "{report}");+ assert!(report.contains("still working"), "{report}");+ }++ #[test]+ fn note_progress_records_markers_and_steps_and_reports_which_is_which() {+ let now = Instant::now();+ let watch: WatchState = Arc::new(Mutex::new(watch(now)));+ assert!(note_progress(&watch, "[TAURI:DL] torch 2.4GiB"));+ assert!(!note_progress(&watch, "[TAURI:STEP] Installing PyTorch"));+ assert!(!note_progress(&watch, " venv creating environment"));+ // A plain line is output: it postpones the report even though it changes no state.+ assert_eq!(watch.lock().unwrap().due_report(Instant::now()), None);++ let later = now + Duration::from_secs(600);+ let report = watch.lock().unwrap().due_report(later).expect("a report is due");+ assert!(report.contains("torch") && report.contains("Installing PyTorch"), "{report}");+ assert!(note_progress(&watch, "[TAURI:DL_DONE] torch"));+ let after = watch+ .lock()+ .unwrap()+ .due_report(later + Duration::from_secs(600))+ .expect("a later report");+ assert!(!after.contains("torch"), "{after}");+ }++ #[test]+ fn the_wait_loop_reports_a_silence_then_stops_the_child_at_the_backstop() {+ let watch = Mutex::new(ProgressWatch::with_backstop(Instant::now() - 13 * HOUR, 12 * HOUR));+ let (mut reports, mut stops) = (Vec::new(), 0);+ let error = wait_with_watchdog(+ &watch,+ || Ok(None),+ |line| reports.push(line.to_string()),+ || stops += 1,+ )+ .expect_err("the backstop must end the wait");+ assert!(error.contains("12 h"), "{error}");+ assert_eq!(stops, 1);+ assert_eq!(reports.len(), 1, "{reports:?}");+ assert!(reports[0].contains("still working"), "{reports:?}");+ }++ #[test]+ fn the_wait_loop_returns_the_childs_own_exit_without_stopping_it() {+ let watch = Mutex::new(watch(Instant::now()));+ let mut stops = 0;+ let status = exit_status(3);+ let (returned, intentional) = wait_with_watchdog(+ &watch,+ || Ok(Some((status, false))),+ |_| panic!("an install that exits at once must not report"),+ || stops += 1,+ )+ .expect("the child's exit is the result");+ assert_eq!(returned.code(), Some(3));+ assert!(!intentional);+ assert_eq!(stops, 0);+ }+}diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 128c0d53b36..6faea846fb0 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -8,6 +8,7 @@ mod desktop_update_policy;mod desktop_updater;mod diagnostics;mod install;+mod install_watchdog;#[cfg(target_os = "linux")]mod linux_webkit;mod loopback_http;diff --git a/unsloth_cli/tests/test_installer_download_markers.py b/unsloth_cli/tests/test_installer_download_markers.pynew file mode 100644index 00000000000..904bd98b1e8--- /dev/null+++ b/unsloth_cli/tests/test_installer_download_markers.py@@ -0,0 +1,289 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The installers turn uv's large-download announcements into markers the app reads.++These drive the real run_install_cmd out of install.sh and the real Invoke-InstallCommand+out of install.ps1, against recorded uv output, with only their collaborators stubbed.+"""++from __future__ import annotations++import os+import re+import select+import shutil+import signal+import subprocess+import tempfile+from pathlib import Path++import pytest++pytestmark = pytest.mark.skipif(os.name == "nt", reason = "drives install.sh under /bin/sh")++_REPO_ROOT = Path(__file__).resolve().parents[2]+_INSTALL_SH = _REPO_ROOT / "install.sh"+_INSTALL_PS1 = _REPO_ROOT / "install.ps1"++_THRESHOLD = 52428800 # 50 MiB, the shipped default in both installers.++# Shaped like real `uv pip install` output, but the two nvidia sizes are picked to bracket+# _THRESHOLD rather than to match those wheels (both are in fact far larger), so moving the+# default in either direction changes what is marked. transformers lands unannounced.+_UV_OUTPUT = """Resolved 38 packages in 2.60s+Downloading torch (2.4GiB)+Downloading nvidia-cudnn-cu12 (674.0MiB)+Downloading nvidia-cusparse-cu12 (51.0MiB)+Downloading nvidia-cublas-cu12 (49.0MiB)+Downloading transformers (11.2MiB)+Downloading idna (68.0KiB)+ Downloaded transformers+ Downloaded nvidia-cublas-cu12+ Downloaded nvidia-cusparse-cu12+ Downloaded nvidia-cudnn-cu12+ Downloaded torch+Installed 38 packages in 9.20s++ torch==2.10.0+cu126+"""++# uv does not repeat a completion, but a repeat must not close a download twice: the app+# would see an end for something it never saw start.+_UV_REPEATED_COMPLETION = """Downloading torch (2.4GiB)+ Downloaded torch+ Downloaded torch+"""++_MARKED = ["torch 2.4GiB", "nvidia-cudnn-cu12 674.0MiB", "nvidia-cusparse-cu12 51.0MiB"]+_LANDED = ["DONE nvidia-cusparse-cu12", "DONE nvidia-cudnn-cu12", "DONE torch"]++_ENV = {"PATH": "/usr/bin:/bin:/usr/local/bin"}+++def _expected(short: list[str]) -> list[str]:+ return [+ f"[TAURI:DL_DONE] {s.removeprefix('DONE ')}" if s.startswith("DONE ") else f"[TAURI:DL] {s}"+ for s in short+ ]+++def _extract(name: str) -> str:+ source = _INSTALL_SH.read_text(encoding = "utf-8")+ match = re.search(rf"^{name}\(\) \{{.*?^\}}", source, re.MULTILINE | re.DOTALL)+ assert match, f"install.sh no longer defines {name}"+ return match.group(0)+++# run_install_cmd's collaborators, stubbed so the real function can run here.+_STUBS = """+_is_verbose() { [ -n "${VERBOSE_MODE:-}" ]; }+step() { :; }; substep() { :; }; tauri_stream_log() { :; }; tauri_clear_install_error() { :; }+_redact_install_output() { cat "$@"; }+"""+++def _extract_default() -> str:+ """install.sh's own threshold default, so changing the shipped value changes the test."""+ source = _INSTALL_SH.read_text(encoding = "utf-8")+ match = re.search(r'^: "\$\{UNSLOTH_DL_MARKER_MIN_BYTES:=\d+\}"$', source, re.MULTILINE)+ assert match, "install.sh no longer defaults UNSLOTH_DL_MARKER_MIN_BYTES"+ return match.group(0)+++def _sh_harness(child: str) -> str:+ return f"""+{_STUBS}+{_extract_default()}+{_extract("_uv_download_markers")}+{_extract("run_install_cmd")}+run_install_cmd "install PyTorch" sh -c '{child}'+printf 'RC=%s\\n' "$?"+"""+++def _run(+ *,+ tauri: bool = True,+ exit_code: int = 0,+ min_bytes: str | None = None,+ verbose: bool = False,+ output: str = _UV_OUTPUT,+ path: str | None = None,+):+ """Drive the real run_install_cmd, with only its collaborators stubbed."""+ env = dict(_ENV, UV_OUTPUT = output)+ if path:+ env["PATH"] = path+ # Left unset by default so install.sh's own shipped threshold is what runs.+ if min_bytes:+ env["UNSLOTH_DL_MARKER_MIN_BYTES"] = min_bytes+ if tauri:+ env["TAURI_MODE"] = "true"+ if verbose:+ env["VERBOSE_MODE"] = "1"+ done = subprocess.run(+ ["/bin/sh", "-c", _sh_harness(f'printf "%s" "$UV_OUTPUT"; exit {exit_code}')],+ capture_output = True,+ text = True,+ env = env,+ timeout = 60,+ )+ assert done.returncode == 0, done.stderr+ # Markers ride stderr so the verbose path's block-buffering redactor cannot delay them.+ markers = [line for line in done.stderr.splitlines() if line.startswith("[TAURI:")]+ rc = next(line for line in done.stdout.splitlines() if line.startswith("RC="))+ # Both streams: the quiet arm prints the log to stderr, the verbose arm pipes to stdout.+ shown = "\n".join(+ [l for l in done.stdout.splitlines() if not l.startswith("RC=")]+ + [l for l in done.stderr.splitlines() if not l.startswith("[TAURI:")]+ )+ return markers, rc.removeprefix("RC="), shown+++ ("options", "expected"),+ [+ ({}, _MARKED + _LANDED),+ ({"min_bytes": "1000000000"}, ["torch 2.4GiB", "DONE torch"]),+ # The verbose arm pipes output instead of logging it, and marks just the same.+ ({"verbose": True}, _MARKED + _LANDED),+ ({"tauri": False}, []),+ ({"output": _UV_REPEATED_COMPLETION}, ["torch 2.4GiB", "DONE torch"]),+ ],+)+def test_only_downloads_worth_waiting_for_become_markers(options, expected):+ markers, _, _ = _run(**options)+ assert markers == _expected(expected)+++def test_a_failure_still_shows_the_childs_whole_output():+ # The added pipe must not cost the failure path the log it exists to print.+ _, rc, shown = _run(exit_code = 42)+ assert rc == "42"+ assert _UV_OUTPUT.strip() in shown++[email protected]("exit_code", [0, 42])+def test_the_exit_code_survives_the_added_pipe(exit_code):+ _, rc, _ = _run(exit_code = exit_code)+ assert rc == str(exit_code)++[email protected]("verbose", [False, True])+def test_a_host_without_awk_still_installs(verbose):+ # install.sh supports minimal images that ship no awk, and this pipe now carries every+ # install command, so losing awk must cost the markers and nothing else. Without the+ # fallback the pipeline closes and the child dies of SIGPIPE, reporting exit 141.+ with tempfile.TemporaryDirectory() as tmp:+ stub = Path(tmp) / "bin"+ stub.mkdir()+ for tool in ("sh", "cat", "mktemp", "rm", "sed", "printf"):+ found = shutil.which(tool)+ if found:+ (stub / tool).symlink_to(found)+ assert shutil.which("awk", path = str(stub)) is None, "the sandbox must still have no awk"+ ok_markers, ok_rc, ok_shown = _run(path = str(stub), verbose = verbose)+ markers, rc, shown = _run(exit_code = 42, path = str(stub), verbose = verbose)+ assert (ok_rc, rc) == ("0", "42"), "a missing awk turned into SIGPIPE"+ assert markers == [] and ok_markers == [], "markers cannot be produced without awk"+ assert _UV_OUTPUT.strip() in shown, "the failure path lost the child's output"+ # The sink still has to differ by arm: quiet holds output in the log until something+ # fails, verbose passes it straight through.+ assert (_UV_OUTPUT.strip() in ok_shown) is verbose+++def test_a_marker_arrives_while_its_download_is_still_running():+ # Every other test reads output after the child exits, so a buffered marker still+ # shows up -- just too late. Verbose is the arm with the block-buffering redactor.+ proc = subprocess.Popen(+ ["/bin/sh", "-c", _sh_harness('printf "Downloading torch (2.4GiB)\\n"; sleep 30')],+ stdout = subprocess.DEVNULL,+ stderr = subprocess.PIPE,+ text = True,+ env = dict(_ENV, TAURI_MODE = "true", VERBOSE_MODE = "1"),+ start_new_session = True,+ )+ try:+ assert select.select([proc.stderr], [], [], 15)[0], "no marker while the download ran"+ assert proc.stderr.readline().startswith("[TAURI:DL] torch"), "not the marker"+ assert proc.poll() is None, "the download must still be running when it arrives"+ finally:+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)+ proc.wait()+++_PWSH = shutil.which("pwsh") or shutil.which("powershell")+++def _ps1_block(first: str, last: str) -> str:+ """install.ps1 source, from the definition of `first` through the end of `last`."""+ ps1 = _INSTALL_PS1.read_text(encoding = "utf-8")+ start = ps1.find(f" function {first} {{")+ tail = ps1.find(f" function {last} {{")+ assert start >= 0 and tail >= start, f"install.ps1 no longer defines {first}..{last}"+ return ps1[start : ps1.index("\n }\n", tail) + len("\n }\n")]+++def _run_ps1(+ *,+ tauri: bool = True,+ min_bytes: str | None = None,+ verbose: bool = False,+ output: str = _UV_OUTPUT,+) -> list[str]:+ """Drive the real Invoke-InstallCommand, so both its arms are exercised as shipped."""+ markers = _ps1_block("Write-TauriLog", "Write-UvDownloadMarker")+ invoke = _ps1_block("Invoke-InstallCommand", "Invoke-InstallCommand")+ assert "Write-UvDownloadMarker" in invoke, "Invoke-InstallCommand no longer marks at all"+ lines = ", ".join("'{}'".format(line.replace("'", "''")) for line in output.splitlines())+ probe = (+ f"$TauriMode = ${str(tauri).lower()}\n"+ f"$script:UnslothVerbose = ${str(verbose).lower()}\n"+ "function Write-StudioLine { param([string]$Text, $ForegroundColor)"+ " [Console]::Out.WriteLine($Text) }\n"+ "function Redact-InstallOutput { param([string]$Text) $Text }\n"+ "function Clear-TauriInstallError { param([string]$Message) }\n"+ f"{markers}\n{invoke}\n"+ f"Invoke-InstallCommand -Command {{ @({lines}) | Write-Output }} -Label 'install PyTorch'\n"+ )+ # Not os.environ: an ambient UNSLOTH_DL_MARKER_MIN_BYTES would override the default.+ env = dict(_ENV)+ if min_bytes:+ env["UNSLOTH_DL_MARKER_MIN_BYTES"] = min_bytes+ with tempfile.TemporaryDirectory() as tmp:+ script = Path(tmp) / "probe.ps1"+ script.write_text(probe, encoding = "utf-8")+ done = subprocess.run(+ [_PWSH, "-NoProfile", "-File", str(script)],+ capture_output = True,+ text = True,+ env = env,+ timeout = 120,+ )+ assert done.returncode == 0, done.stderr+ return [line for line in done.stdout.splitlines() if line.startswith("[TAURI:DL")]++[email protected](_PWSH is None, reason = "needs PowerShell to run install.ps1")+ "options",+ [+ {},+ {"verbose": True},+ {"min_bytes": "1000000000"},+ {"tauri": False},+ {"output": _UV_REPEATED_COMPLETION},+ ],+)+def test_both_installers_emit_the_same_markers(options):+ # The sh expectations are pinned above, so agreeing with sh pins PowerShell too.+ expected, _, _ = _run(**options)+ assert _run_ps1(**options) == expected+++def test_both_installers_ship_the_same_threshold():+ # Execution only brackets the default between two fixture sizes; the literal pins it+ # exactly, and pins the two installers to each other so they cannot drift apart.+ assert _extract_default() == f': "${{UNSLOTH_DL_MARKER_MIN_BYTES:={_THRESHOLD}}}"'+ ps1 = _INSTALL_PS1.read_text(encoding = "utf-8")+ assert f"$script:UvDownloadMarkerMinBytes = {_THRESHOLD}" in ps1