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
Studio setup: reuse the uv a previous run installed instead of downloading it again (#10659)
Daniel Han768d644036a9
diff --git a/install.sh b/install.shindex e9d3978e93e..783ffbfef97 100755--- a/install.sh+++ b/install.sh@@ -1213,6 +1213,15 @@ _cleanup_install_temporaries() {[ -n "${_UIP_STAGE:-}" ] && rm -f "$_UIP_STAGE" 2>/dev/null || true[ -n "${_UIP_STAGE2:-}" ] && rm -f "$_UIP_STAGE2" 2>/dev/null || true[ -n "${_ROCM_TAG_MEMO_DIR:-}" ] && rm -rf "$_ROCM_TAG_MEMO_DIR" 2>/dev/null || true+ # The probe's ceiling is held by this shell, so a cancel during one would otherwise leave the+ # candidate (and, under monitor mode, its whole group) running with nobody left to stop it.+ if [ -n "${_UV_PROBE_TARGET:-}" ] && [ -n "${_UV_PROBE_PID:-}" ]; then+ # Two seconds, not the ceiling's five: a cancel that waited that long on a binary+ # ignoring TERM would read as an installer ignoring the cancel.+ _uv_probe_terminate "$_UV_PROBE_TARGET" "$_UV_PROBE_PID" 2+ _UV_PROBE_TARGET=""+ _UV_PROBE_PID=""+ fi}_on_install_exit() {@@ -1246,6 +1255,8 @@ _UIP_STAGE=""_UIP_STAGE2=""_ROCM_TAG_MEMO_DIR=""_ROCM_TAG_MEMO=""+_UV_PROBE_TARGET=""+_UV_PROBE_PID=""trap _on_install_exit EXITtrap '_on_install_signal 129' HUPtrap '_on_install_signal 130' INT@@ -3233,13 +3244,83 @@ _uv_sha256() {fi}-# Can a freshly downloaded binary run at all? Both ways it could hang are closed off: no stdin, so a build that prompts reads EOF, and a ceiling where `timeout` exists (stock macOS has none). A healthy uv answers in milliseconds, so only a binary we would refuse reaches the ceiling.+# Liveness probe for a fresh binary, hang-proof: no stdin (a prompting build reads EOF) and a+# ceiling, held by `timeout -k` where it exists and by a watchdog on stock macOS, which has none.+_uv_signal_target() {+ # bash reads a bare negative pid as a signal spec, dash refuses the `--` that fixes bash, and+ # only a shell that made a process group produces a negative target: the sign picks the form.+ case "$2" in+ -*) kill "-$1" -- "$2" 2>/dev/null || : ;;+ *) kill "-$1" "$2" 2>/dev/null || : ;;+ esac+}++# TERM, then KILL what ignored it, as `timeout -k` does where it exists.+# $1 target (a group when one was made, else the pid), $2 pid to watch, $3 seconds of grace.+_uv_probe_terminate() {+ _upt_grace=0+ _uv_signal_target TERM "$1"+ while [ "$_upt_grace" -lt "$3" ] && kill -0 "$2" 2>/dev/null; do+ sleep 1+ _upt_grace=$((_upt_grace + 1))+ done+ # Only if it is still there: the loop also ends when TERM worked, and the KILL would go out+ # anyway, to a number this shell no longer owns.+ if kill -0 "$2" 2>/dev/null; then _uv_signal_target KILL "$1"; fi+ unset _upt_grace+}+_uv_probe_exec() {- if command -v timeout >/dev/null 2>&1; then- timeout 20 "$1" --version >/dev/null 2>&1 </dev/null- else- "$1" --version >/dev/null 2>&1 </dev/null+ _upe_secs="${_UV_PROBE_SECONDS:-20}"+ # KILL after TERM (TERM can be ignored): `timeout -k` where supported, else the watchdog below.+ if command -v timeout >/dev/null 2>&1 && timeout -k 1 5 true >/dev/null 2>&1; then+ timeout -k 5 "$_upe_secs" "$1" --version >/dev/null 2>&1 </dev/null+ return $?+ fi+ # Monitor mode gives the probe a process group of its own, so the signals below reach what IT+ # started, as `timeout`'s do. Off again at once.+ _upe_monitor=off+ case "$-" in *m*) _upe_monitor=on ;; esac+ [ "$_upe_monitor" = on ] || set -m 2>/dev/null || :+ "$1" --version >/dev/null 2>&1 </dev/null &+ _upe_pid=$!+ [ "$_upe_monitor" = on ] || set +m 2>/dev/null || :+ # The group only where it is provably not this shell's own, else the single pid as before.+ # Parameter expansion, not `tr`: this branch has to hold on a bare PATH.+ _upe_target="$_upe_pid"+ if command -v ps >/dev/null 2>&1; then+ _upe_pgid=$(ps -o pgid= -p "$_upe_pid" 2>/dev/null)+ _upe_self=$(ps -o pgid= -p $$ 2>/dev/null)+ _upe_pgid=${_upe_pgid##* }+ _upe_self=${_upe_self##* }+ case "$_upe_pgid$_upe_self" in+ ''|*[!0-9]*) : ;;+ *) [ "$_upe_pgid" = "$_upe_self" ] || _upe_target="-$_upe_pgid" ;;+ esacfi+ # Published for _cleanup_install_temporaries: the installer's HUP/INT/TERM handlers run it,+ # so a cancel during the wait kills the probe instead of orphaning it.+ _UV_PROBE_TARGET="$_upe_target"+ _UV_PROBE_PID="$_upe_pid"+ _upe_waited=0+ while kill -0 "$_upe_pid" 2>/dev/null; do+ if [ "$_upe_waited" -ge "$_upe_secs" ]; then+ _uv_probe_terminate "$_upe_target" "$_upe_pid" 5+ wait "$_upe_pid" 2>/dev/null+ _UV_PROBE_TARGET=""+ _UV_PROBE_PID=""+ unset _upe_pid _upe_waited _upe_target _upe_pgid _upe_self+ return 124+ fi+ sleep 1+ _upe_waited=$((_upe_waited + 1))+ done+ wait "$_upe_pid"+ _upe_rc=$?+ _UV_PROBE_TARGET=""+ _UV_PROBE_PID=""+ unset _upe_pid _upe_waited _upe_target _upe_pgid _upe_self+ return $_upe_rc}_uv_install_pinned() {diff --git a/studio/setup.ps1 b/studio/setup.ps1index 4163b952336..99044e7deba 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -6433,14 +6433,17 @@ function Get-UvHostArch {return "unknown"}-# Writes to the pipeline, not the console: under Invoke-SetupCommand a quiet run swallows this-# exactly as it swallowed astral's output, and a verbose run shows it. The console lines around-# the call site are unchanged.function Get-SetupUvExecutableVerdict {# Mirrors Get-UvExecutableVerdict in install.ps1: "ok", "failed" or "unknown". Only the# binary answering non-zero is "failed"; a launch that throws or a wait that times out got# no verdict, and the digest already proved the bytes are astral's pinned release.+ # Returns the verdict ONLY: a reason on the pipeline made the caller read [reason, verdict]+ # and take the last element, so substep carries them instead. A cached exit code decides;+ # with none (the timed wait can return first), a printed version is "ok".param([string]$Path)+ # What the binary printed, for the caller that has to know WHICH uv answered. A second+ # pipeline value would undo the paragraph above; re-running it would be a chance to hang.+ $script:SetupUvVersionLine = ""if (-not $Path -or -not (Test-Path -LiteralPath $Path)) { return "failed" }$outFile = [System.IO.Path]::GetTempFileName()$errFile = [System.IO.Path]::GetTempFileName()@@ -6449,30 +6452,34 @@ function Get-SetupUvExecutableVerdict {-RedirectStandardOutput $outFile -RedirectStandardError $errFile -ErrorAction Stopif (-not $proc.WaitForExit(20000)) {try { $proc.Kill() } catch {}- Write-Output "uv did not answer --version within 20s; installing it unprobed."+ substep "uv did not answer --version within 20s; installing it unprobed."return "unknown"}- # The timed overload can return before the exit code is cached, which is how- # arm64 and the Windows containers reported an EMPTY code and had a working uv- # read as broken. The parameterless wait settles it and returns at once, since- # the process has already exited. No code at all is still no verdict.+ # The timed overload can return before the exit code is cached (arm64 and the Windows+ # containers read a working uv as broken); the parameterless wait settles it at once.try { $proc.WaitForExit() } catch {}+ $answer = ""+ try { $answer = Get-Content -LiteralPath $outFile -Raw -ErrorAction SilentlyContinue } catch {}+ if ($answer) { $script:SetupUvVersionLine = $answer.Trim() }$code = $nulltry { $code = $proc.ExitCode } catch {}if ($null -eq $code -or "$code" -eq "") {- Write-Output "uv --version gave no exit code; installing it unprobed."+ # No exit code: a printed version is "ok"; nothing printed gets no verdict.+ if ($answer -and ($answer.Trim() -match '^uv \d+\.\d+')) { return "ok" }+ substep "uv --version gave no exit code; installing it unprobed."return "unknown"}+ # A code decides: a printed version with a non-zero exit is the binary's own failure.if ($code -eq 0) { return "ok" }$detail = ""try {$detail = Get-Content -LiteralPath $errFile -Raw -ErrorAction SilentlyContinue} catch {}if ($detail) { $detail = " " + (($detail.Trim()) -replace '\s+', ' ') }- Write-Output "uv --version exited $code.$detail"+ substep "uv --version exited $code.$detail"return "failed"} catch {- Write-Output "could not probe uv: $($_.Exception.Message); installing it unprobed."+ substep "could not probe uv: $($_.Exception.Message); installing it unprobed."return "unknown"} finally {Remove-Item -LiteralPath $outFile -Force -ErrorAction SilentlyContinue@@ -6634,16 +6641,112 @@ function Enter-StudioVenv {Enter-StudioVenvAssert-VenvActivated -VenvDir $VenvDir+function Find-InstalledUv {+ # The uv a previous run installed but this process's PATH lacks (a desktop shell launched+ # before the install, a CI step): the miss re-downloaded the pinned archive every update,+ # 42 of a 53 s Windows no-op. Install-UvFromPinnedRelease's own priority list plus+ # install.ps1's winget alias directory; it has to run, not merely exist.+ # .NET Combine, not the path cmdlet: under ErrorActionPreference Stop, before the+ # installation branch's try, the cmdlet terminates on a missing drive (XDG_DATA_HOME=Z:\xdg).+ # Get-UvInstallDir first, so the installer's own destination leads however that helper+ # changes. It joins with the cmdlet, hence the try: here that is outside the branch's own.+ $installerDest = $null+ try { $installerDest = Get-UvInstallDir } catch { $installerDest = $null }+ $candidates = @($installerDest, $env:UV_INSTALL_DIR, $env:UV_UNMANAGED_INSTALL, $env:XDG_BIN_HOME)+ if ($env:XDG_DATA_HOME) { $candidates += [System.IO.Path]::Combine($env:XDG_DATA_HOME, "..", "bin") }+ $userHome = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME }+ if ($userHome) { $candidates += [System.IO.Path]::Combine($userHome, ".local", "bin") }+ # winget's alias directory reaches PATH only via the registry, so a process started before+ # install.ps1's winget route never saw it and downloaded the pinned release over it.+ if ($env:LOCALAPPDATA) { $candidates += [System.IO.Path]::Combine($env:LOCALAPPDATA, "Microsoft", "WinGet", "Links") }+ $script:InstalledUvLooked = @()+ # Assigned even when no uv.exe exists: unassigned, it terminates under a caller's Set-StrictMode.+ $script:InstalledUvProbeMiss = $null+ $script:InstalledUvTooOld = $null+ # Two variables commonly name one directory, which would then be launched and reported twice.+ # Ordinal, since a path differing only in case is the same directory here.+ $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)+ foreach ($dir in $candidates) {+ if (-not $dir) { continue }+ if (-not $seen.Add([string]$dir)) { continue }+ $exe = [System.IO.Path]::Combine($dir, "uv.exe")+ $script:InstalledUvLooked += $exe+ if (-not (Test-Path -LiteralPath $exe -PathType Leaf -ErrorAction SilentlyContinue)) { continue }+ # "ok" only: no digest vouches for a found binary, and a launch that threw or timed out+ # would reach an unbounded uv pip. Asked twice: one miss (a scanner holding a fresh+ # binary) sent setup to the pinned download, which put an OLDER uv over this one.+ if ((Get-InstalledUvVerdict -Path $exe) -ne "ok") { continue }+ # install.ps1's UvMinVersion: reuse accepts what the Windows installer accepts, no more.+ # Unreadable leaves the candidate alone.+ if (-not (Test-SetupUvVersionAtLeast -VersionLine $script:SetupUvVersionLine -Minimum $SetupUvMinVersion)) {+ $script:InstalledUvTooOld = $exe+ continue+ }+ return $dir+ }+ return $null+}++# The floor a found uv has to clear: install.ps1's UvMinVersion, so reuse accepts exactly what+# the Windows installer accepts. It is not install.sh's 0.9.3, and deliberately: that number is+# about uv's managed-Python manifest topping out at a CPython that cannot import torch, and+# nothing here asks uv for an interpreter -- the one uv command this file runs is+# `uv pip install --python <the venv's python>`. install.ps1 keeps 3.13.8 out with its own+# $PythonSkip instead.+$SetupUvMinVersion = "0.8.16"++function Test-SetupUvVersionAtLeast {+ # "uv 0.12.1 (abcdef0 2026-01-01)" -> $true when 0.12.1 is at least $Minimum. Unparseable is+ # $false: the download that follows is what ran before the reuse existed.+ param([string]$VersionLine, [string]$Minimum)+ if (-not $VersionLine) { return $false }+ if ($VersionLine -notmatch '(?m)^\s*uv\s+(\d+(?:\.\d+){0,2})([-+]\S*)?') { return $false }+ $found = $Matches[1]+ # A group that did not participate is absent from $Matches, and reading it would throw under+ # a caller's Set-StrictMode rather than read as "no suffix".+ $pre = if ($Matches.ContainsKey(2)) { $Matches[2] } else { "" }+ try {+ if ([version]$found -gt [version]$Minimum) { return $true }+ # A prerelease of the floor itself is the floor minus something, so it does not clear it.+ # install.sh's _uv_version_ok refuses the same shape.+ if ([version]$found -eq [version]$Minimum) { return (-not $pre) }+ return $false+ } catch { return $false }+}++function Get-InstalledUvVerdict {+ # The verdict alone, asked twice. The last element, not the value itself: the verdict+ # function is shared with the staged-uv check, and this keeps reading it correctly if a+ # reason is ever written to the pipeline again.+ param([string]$Path)+ $verdict = @(Get-SetupUvExecutableVerdict -Path $Path)[-1]+ if ($verdict -eq "ok") { return "ok" }+ Start-Sleep -Seconds 2+ $verdict = @(Get-SetupUvExecutableVerdict -Path $Path)[-1]+ if ($verdict -ne "ok") { $script:InstalledUvProbeMiss = "$Path ($verdict)" }+ return $verdict+}+# Try to use uv (much faster than pip), fall back to pip if unavailable$UseUv = $false+$installedUvDir = $nullif (Get-Command uv -ErrorAction SilentlyContinue) {$UseUv = $true-} elseif ((Get-UvInstallDir) -and (Test-Path -LiteralPath (Join-Path (Get-UvInstallDir) "uv.exe"))) {- # Already installed, just not on this process's PATH. The install prepends the user registry- # PATH, which an update inheriting its parent's PATH never sees, so every update re-downloaded it.- $env:PATH = (Get-UvInstallDir) + ";" + $env:PATH+} elseif (($installedUvDir = Find-InstalledUv)) {+ # Read-only reuse, fine under a stage root. Appended: a python.exe beside uv must not+ # step in front of the staged interpreter.+ $env:PATH = "$env:PATH;$installedUvDir"+ substep "reusing the uv installed at $installedUvDir (it was not on PATH)"$UseUv = $true} elseif (-not $StageRoot) {+ if ($script:InstalledUvTooOld) {+ substep "the uv at $($script:InstalledUvTooOld) is older than $SetupUvMinVersion; installing the pinned release"+ } elseif ($script:InstalledUvProbeMiss) {+ substep "the uv at $($script:InstalledUvProbeMiss) did not answer --version twice; installing the pinned release"+ } elseif ($script:InstalledUvLooked) {+ # Names the destinations searched, so a re-download can be read.+ substep "no installed uv at $($script:InstalledUvLooked -join ', '); installing the pinned release"+ }substep "installing uv package manager..."try {$script:UvPinnedInstalled = $falsediff --git a/studio/setup.sh b/studio/setup.shindex 1a0105ed36d..2747c9565ff 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -2035,14 +2035,121 @@ _setup_uv_sha256() {fi}-# Bounded liveness probe: no stdin, so a build that prompts reads EOF, and a ceiling where-# `timeout` exists (stock macOS has none).-_setup_uv_probe_exec() {- if command -v timeout >/dev/null 2>&1; then- timeout 20 "$1" --version >/dev/null 2>&1 </dev/null+_SETUP_UV_PROBE_TARGET=""+_SETUP_UV_PROBE_PID=""+_SETUP_UV_PROBE_PREV_TRAP=""++# A process group is signalled as a negative pid, and the two shells that get here disagree about+# how to write one: bash reads a bare `-123` as a signal spec and refuses it, dash refuses the+# `--` that fixes bash. Only a shell that made a group can produce a negative target, so the sign+# picks the spelling. Measured both ways: the wrong one fails silently under 2>/dev/null and the+# group survives the ceiling.+_setup_uv_signal_target() {+ case "$2" in+ -*) kill "-$1" -- "$2" 2>/dev/null || : ;;+ *) kill "-$1" "$2" 2>/dev/null || : ;;+ esac+}++# TERM, then KILL what ignored it, exactly as `timeout -k` does on the hosts that have it.+# $1 target (a group when one was made, else the pid), $2 pid to watch, $3 seconds of grace.+_setup_uv_probe_terminate() {+ _supt_grace=0+ _setup_uv_signal_target TERM "$1"+ while [ "$_supt_grace" -lt "$3" ] && kill -0 "$2" 2>/dev/null; do+ sleep 1+ _supt_grace=$((_supt_grace + 1))+ done+ # Only if it is still there: the loop also ends when TERM worked, and an unconditional KILL+ # then goes to a number this shell no longer owns. Narrows the window, not closes it.+ if kill -0 "$2" 2>/dev/null; then _setup_uv_signal_target KILL "$1"; fi+ unset _supt_grace+}++# The watchdog's ceiling lives in the calling shell, so a cancel during the wait would leave the+# candidate, and under monitor mode its whole group, running with nobody left to stop it. These+# two chain rather than replace: the pinned installer's own handlers still have to run.+_setup_uv_probe_restore_trap() {+ _SETUP_UV_PROBE_TARGET=""+ _SETUP_UV_PROBE_PID=""+ if [ -n "${_SETUP_UV_PROBE_PREV_TRAP:-}" ]; then+ eval "$_SETUP_UV_PROBE_PREV_TRAP"else- "$1" --version >/dev/null 2>&1 </dev/null+ trap - HUP INT TERM+ fi+ _SETUP_UV_PROBE_PREV_TRAP=""+}++_setup_uv_probe_on_signal() {+ # The same TERM/KILL the ceiling uses, on a shorter leash: a cancel that waited the full five+ # seconds for a binary ignoring TERM would read as a setup that ignored the cancel.+ if [ -n "${_SETUP_UV_PROBE_TARGET:-}" ] && [ -n "${_SETUP_UV_PROBE_PID:-}" ]; then+ _setup_uv_probe_terminate "$_SETUP_UV_PROBE_TARGET" "$_SETUP_UV_PROBE_PID" 2+ wait "$_SETUP_UV_PROBE_PID" 2>/dev/null || :+ fi+ _setup_uv_probe_restore_trap+ # Hand the signal back to whoever had it: the installer's handler, or the default action.+ kill -s "$1" "$$" 2>/dev/null || :+}++# Bounded liveness probe: no stdin (a prompting build reads EOF), 20 s ceiling held by GNU+# timeout or, without it (stock macOS), a background job killed when the ceiling passes.+# $2 takes the binary's stdout, /dev/null by default: reuse needs the version line, and running+# the binary again to read it would be a second chance to hang.+_setup_uv_probe_exec() {+ _supe_secs="${_SETUP_UV_PROBE_SECONDS:-20}"+ _supe_out="${2:-/dev/null}"+ # KILL after TERM (TERM can be ignored): `timeout -k` where supported, else the watchdog below.+ if command -v timeout >/dev/null 2>&1 && timeout -k 1 5 true >/dev/null 2>&1; then+ timeout -k 5 "$_supe_secs" "$1" --version >"$_supe_out" 2>/dev/null </dev/null+ return $?+ fi+ # Monitor mode gives the probe a process group of its own, so the signals below reach what IT+ # started, as `timeout`'s setpgid does. Off again at once: it changes how later jobs report.+ _supe_monitor=off+ case "$-" in *m*) _supe_monitor=on ;; esac+ [ "$_supe_monitor" = on ] || set -m 2>/dev/null || :+ "$1" --version >"$_supe_out" 2>/dev/null </dev/null &+ _supe_pid=$!+ [ "$_supe_monitor" = on ] || set +m 2>/dev/null || :+ # The group only where it is provably not this shell's own (zsh shares them, and a group TERM+ # there kills setup); otherwise the single pid, as before. Parameter expansion, not `tr`: this+ # branch has to hold on a PATH as bare as the shell and sleep.+ _supe_target="$_supe_pid"+ if command -v ps >/dev/null 2>&1; then+ _supe_pgid=$(ps -o pgid= -p "$_supe_pid" 2>/dev/null)+ _supe_self=$(ps -o pgid= -p $$ 2>/dev/null)+ _supe_pgid=${_supe_pgid##* }+ _supe_self=${_supe_self##* }+ case "$_supe_pgid$_supe_self" in+ ''|*[!0-9]*) : ;;+ *) [ "$_supe_pgid" = "$_supe_self" ] || _supe_target="-$_supe_pgid" ;;+ esacfi+ _SETUP_UV_PROBE_TARGET="$_supe_target"+ _SETUP_UV_PROBE_PID="$_supe_pid"+ _SETUP_UV_PROBE_PREV_TRAP=$(trap -p HUP INT TERM 2>/dev/null) || _SETUP_UV_PROBE_PREV_TRAP=""+ trap '_setup_uv_probe_on_signal HUP' HUP+ trap '_setup_uv_probe_on_signal INT' INT+ trap '_setup_uv_probe_on_signal TERM' TERM+ _supe_waited=0+ while kill -0 "$_supe_pid" 2>/dev/null; do+ if [ "$_supe_waited" -ge "$_supe_secs" ]; then+ # Escalate as timeout -k does: a binary ignoring TERM would hold the wait.+ _setup_uv_probe_terminate "$_supe_target" "$_supe_pid" 5+ wait "$_supe_pid" 2>/dev/null+ _setup_uv_probe_restore_trap+ unset _supe_pid _supe_waited _supe_target _supe_pgid _supe_self+ return 124+ fi+ sleep 1+ _supe_waited=$((_supe_waited + 1))+ done+ wait "$_supe_pid"+ _supe_rc=$?+ _setup_uv_probe_restore_trap+ unset _supe_pid _supe_waited _supe_target _supe_pgid _supe_self+ return $_supe_rc}# The function's own cleanup only runs when it returns, so an interrupt left the unpacked@@ -2367,12 +2474,124 @@ _setup_persist_uv_path() {done}+_SETUP_UV_PROBE_MISS=""+_SETUP_UV_LOOKED=""+_SETUP_UV_DIR=""+_SETUP_UV_TOO_OLD=""+# install.sh's UV_MIN_VERSION, for its reason: below it uv's managed-Python manifest tops out at+# a CPython that cannot import torch, which the installer refuses to build on.+_SETUP_UV_MIN_VERSION="0.9.3"++# True when uv's --version line names a release at least as new as $2. Unreadable is false: the+# candidate is left alone and the download runs, as it did before this search existed.+_setup_uv_version_at_least() {+ [ -n "$1" ] || return 1+ printf '%s\n' "$1" | awk -v floor="$2" '+ NR == 1 {+ # It has to be uv saying it. Another binary that runs and prints a version of its+ # own ("curl 8.9.1") would otherwise clear a floor of 0.9.3 on the strength of+ # being curl 8.+ if ($1 != "uv") { exit 1 }+ # A prerelease is the version it precedes minus something, so it is compared as that+ # version and refused when that lands exactly on the floor, as install.sh does.+ core = $2+ pre = (sub(/[-+].*$/, "", core) > 0)+ split(core, have, ".")+ if (have[1] !~ /^[0-9]+$/) { exit 1 }+ split(floor, want, ".")+ for (i = 1; i <= 3; i++) {+ h = (have[i] ~ /^[0-9]+$/) ? have[i] + 0 : 0+ w = (want[i] ~ /^[0-9]+$/) ? want[i] + 0 : 0+ if (h > w) { exit 0 }+ if (h < w) { exit 1 }+ }+ if (pre) { exit 1 }+ # Braced, like every other exit in this program: setup.sh is allowed exactly two+ # exits of its own (tests/sh/test_tauri_retry_failure_context.sh counts the lines),+ # and an awk exit indented on a line of its own reads as a third.+ { exit 0 }+ }+ { exit 1 }+ '+}++# Answers in _SETUP_UV_DIR: under command substitution the miss diagnostics above would die+# with the subshell.+_setup_find_installed_uv() {+ # The uv a previous run installed but this process's PATH lacks (a desktop shell launched+ # before the install, a CI step, an unread profile line): the miss re-downloaded the pinned+ # archive on every update, 42 of a 53 s Windows no-op. Same priority list+ # _setup_install_uv_pinned writes to; it has to run, not merely exist.+ # Cleared on entry: a second search would otherwise report the first one's destinations.+ _SETUP_UV_PROBE_MISS=""+ _SETUP_UV_LOOKED=""+ _SETUP_UV_DIR=""+ _SETUP_UV_TOO_OLD=""+ _sfu_seen=""+ # A file, not a command substitution: whatever the candidate starts inherits the probe's+ # stdout, so a pipe holds this open until the last descendant lets go, which is the hang the+ # ceiling exists to prevent. No file means no version, so no reuse: the old download path.+ _sfu_ver_file=""+ if command -v mktemp >/dev/null 2>&1; then+ _sfu_ver_file=$(mktemp 2>/dev/null) || _sfu_ver_file=""+ fi+ for _sfu_dir in "${UV_INSTALL_DIR:-}" "${UV_UNMANAGED_INSTALL:-}" "${XDG_BIN_HOME:-}" \+ "${XDG_DATA_HOME:+$XDG_DATA_HOME/../bin}" "${HOME:+$HOME/.local/bin}"; do+ [ -n "$_sfu_dir" ] || continue+ # Once per directory however many variables name it, as the PowerShell finder does: a+ # hanging candidate costs the ceiling once per name (126 s over four tiers, 42 s for one).+ case "$_sfu_seen" in *"|$_sfu_dir|"*) continue ;; esac+ _sfu_seen="$_sfu_seen|$_sfu_dir|"+ _SETUP_UV_LOOKED="${_SETUP_UV_LOOKED:+$_SETUP_UV_LOOKED, }$_sfu_dir/uv"+ [ -x "$_sfu_dir/uv" ] || continue+ # Bounded, like the pinned installer's probe. Asked twice: one miss (an antivirus scan+ # holding a fresh binary) sent setup to the pinned download, which put an OLDER uv+ # over this one and moved the manifest's uv_version on the next pass.+ if _setup_uv_probe_exec "$_sfu_dir/uv" "${_sfu_ver_file:-/dev/null}" ||+ { sleep 2; _setup_uv_probe_exec "$_sfu_dir/uv" "${_sfu_ver_file:-/dev/null}"; }; then+ # `read`, not `cat`: this branch has to hold on a bare PATH, and an empty file+ # returning non-zero is not a reason for `set -e` to end setup.+ _sfu_ver=""+ if [ -n "$_sfu_ver_file" ]; then+ read -r _sfu_ver < "$_sfu_ver_file" 2>/dev/null || _sfu_ver=""+ fi+ if _setup_uv_version_at_least "$_sfu_ver" "$_SETUP_UV_MIN_VERSION"; then+ _SETUP_UV_DIR="$_sfu_dir"+ if [ -n "$_sfu_ver_file" ]; then rm -f "$_sfu_ver_file" 2>/dev/null || :; fi+ unset _sfu_dir _sfu_ver _sfu_seen _sfu_ver_file+ return 0+ fi+ _SETUP_UV_TOO_OLD="$_sfu_dir/uv"+ continue+ fi+ _SETUP_UV_PROBE_MISS="$_sfu_dir/uv"+ done+ if [ -n "$_sfu_ver_file" ]; then rm -f "$_sfu_ver_file" 2>/dev/null || :; fi+ unset _sfu_dir _sfu_ver _sfu_seen _sfu_ver_file+ return 1+}+USE_UV=falseif command -v uv &>/dev/null; thenUSE_UV=true+elif _setup_find_installed_uv; then+ _setup_uv_dir="$_SETUP_UV_DIR"+ # Read-only reuse, fine under a stage root. Appended: a python beside uv (~/.local/bin+ # often has one) must not step in front of the staged $VENV_DIR/bin/python.+ export PATH="$PATH:$_setup_uv_dir"+ step "uv" "reusing the uv installed at $_setup_uv_dir (it was not on PATH)"+ USE_UV=true+ unset _setup_uv_direlif [ -n "$STAGE_ROOT" ]; thenstep "uv" "using pip inside the staged environment"elif {+ if [ -n "${_SETUP_UV_TOO_OLD:-}" ]; then+ step "uv" "the uv at $_SETUP_UV_TOO_OLD is older than $_SETUP_UV_MIN_VERSION; installing the pinned release"+ elif [ -n "${_SETUP_UV_PROBE_MISS:-}" ]; then+ step "uv" "the uv at $_SETUP_UV_PROBE_MISS did not answer --version twice; installing the pinned release"+ elif [ -n "${_SETUP_UV_LOOKED:-}" ]; then+ step "uv" "no installed uv at $_SETUP_UV_LOOKED; installing the pinned release"+ fi_SETUP_UV_PINNED_OK=falseif _setup_install_uv_pinned; then_SETUP_UV_PINNED_OK=truediff --git a/tests/sh/test_setup_reuse_installed_uv.sh b/tests/sh/test_setup_reuse_installed_uv.shnew file mode 100755index 00000000000..d8263d14106--- /dev/null+++ b/tests/sh/test_setup_reuse_installed_uv.sh@@ -0,0 +1,394 @@+#!/bin/sh+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+#+# A uv installed but off THIS process's PATH made setup.sh re-download the pinned archive every+# update, 42 of a 53 s Windows no-op. It now searches astral's destinations first, and only a uv+# that runs, and answers as uv at or above install.sh's floor, counts.+set -e++SCRIPT_DIR=$(CDPATH= cd -- "$(dirname "$0")" && pwd)+. "$SCRIPT_DIR/_harness.sh"+SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"+SETUP_PS1="$SCRIPT_DIR/../../studio/setup.ps1"++WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT INT TERM++HELPER=$(awk '+ /^_setup_uv_signal_target\(\) \{/ { grab = 1 }+ /^_setup_uv_probe_terminate\(\) \{/ { grab = 1 }+ /^_setup_uv_probe_restore_trap\(\) \{/ { grab = 1 }+ /^_setup_uv_probe_on_signal\(\) \{/ { grab = 1 }+ /^_setup_uv_probe_exec\(\) \{/ { grab = 1 }+ /^_setup_uv_version_at_least\(\) \{/ { grab = 1 }+ /^_setup_find_installed_uv\(\) \{/ { grab = 1 }+ grab { print }+ grab && /^}/ { grab = 0 }+' "$SETUP_SH")+# The floor the finder compares against lives beside the function, not inside it.+HELPER="$(grep '^_SETUP_UV_MIN_VERSION=' "$SETUP_SH")+$HELPER"+for _fn in _setup_uv_signal_target _setup_uv_probe_terminate _setup_uv_probe_restore_trap _setup_uv_probe_on_signal _setup_uv_probe_exec \+ _setup_uv_version_at_least _setup_find_installed_uv; do+ printf '%s\n' "$HELPER" | grep -q "^$_fn() {" || {+ echo "FATAL: could not extract $_fn from setup.sh" >&2; exit 1; }+done+printf '%s\n' "$HELPER" | grep -q '^_SETUP_UV_MIN_VERSION=' || {+ echo "FATAL: could not extract _SETUP_UV_MIN_VERSION from setup.sh" >&2; exit 1; }++PROBE="$WORK/probe.sh"+{+ printf '%s\n' "$HELPER"+ cat <<'BODY'+if _setup_find_installed_uv; then printf 'found=%s' "$_SETUP_UV_DIR"; else printf 'none'; fi+BODY+} > "$PROBE"+# The miss diagnostics survive only when the finder runs in the caller's shell, not a substitution.+DIAG="$WORK/diag.sh"+{+ printf '%s\n' "$HELPER"+ cat <<'BODY'+if _setup_find_installed_uv; then printf 'found'; else printf 'looked=%s miss=%s old=%s' "$_SETUP_UV_LOOKED" "$_SETUP_UV_PROBE_MISS" "$_SETUP_UV_TOO_OLD"; fi+BODY+} > "$DIAG"+# setup.ps1's finder, whole, so the checks below do not depend on its line count.+PS_FINDER=$(awk '+ /^function Find-InstalledUv \{/ { grab = 1 }+ grab { print }+ grab && /^\}/ { grab = 0 }+' "$SETUP_PS1")+printf '%s\n' "$PS_FINDER" | grep -q '^function Find-InstalledUv {' || {+ echo "FATAL: could not extract Find-InstalledUv from setup.ps1" >&2; exit 1; }++fake_uv() { # fake_uv <dir> [exit code] [version]+ # It prints a version because the finder reads one: a silent stand-in would be refused for+ # that reason and every reuse case would go green for the wrong one.+ mkdir -p "$1"+ printf '#!/bin/sh\necho "uv %s (0123456 2026-01-01)"\nexit %s\n' "${3:-0.12.12}" "${2:-0}" > "$1/uv"+ chmod +x "$1/uv"+}++echo "=== test_setup_reuse_installed_uv ==="+for shell in sh bash; do+ command -v "$shell" >/dev/null 2>&1 || continue+ CASE="$WORK/$shell case"+ HOME_DIR="$CASE/home with spaces"+ mkdir -p "$HOME_DIR"+ # A PATH with no uv on it at all, as the miss requires.+ BARE_PATH="/usr/bin:/bin"++ assert_eq "$shell: nothing installed anywhere is a miss" \+ "none" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" "$shell" "$PROBE")"+ case "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" "$shell" "$DIAG")" in+ "looked=$HOME_DIR/.local/bin/uv miss= old=") ok "$shell: a miss names the destinations it looked at" ;;+ *) bad "$shell: a miss names the destinations it looked at ($(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" "$shell" "$DIAG"))" ;;+ esac++ fake_uv "$HOME_DIR/.local/bin"+ assert_eq "$shell: astral's default destination is found" \+ "found=$HOME_DIR/.local/bin" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" "$shell" "$PROBE")"++ XDG="$CASE/xdg data"+ fake_uv "$XDG/../bin"+ assert_eq "$shell: XDG_DATA_HOME/../bin outranks the home default" \+ "found=$XDG/../bin" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" XDG_DATA_HOME="$XDG" "$shell" "$PROBE")"++ CUSTOM="$CASE/custom install dir"+ fake_uv "$CUSTOM"+ assert_eq "$shell: UV_INSTALL_DIR outranks every default" \+ "found=$CUSTOM" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" XDG_DATA_HOME="$XDG" UV_INSTALL_DIR="$CUSTOM" "$shell" "$PROBE")"++ # Present but broken (another architecture, a half-written download): never reused.+ BROKEN="$CASE/broken"+ fake_uv "$BROKEN" 1+ assert_eq "$shell: a uv that cannot run is not reused" \+ "found=$HOME_DIR/.local/bin" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$BROKEN" "$shell" "$PROBE")"+ rm -f "$HOME_DIR/.local/bin/uv"+ assert_eq "$shell: ...and with nothing else installed that is a miss" \+ "none" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$BROKEN" "$shell" "$PROBE")"++ # Runs, but below install.sh's floor: its managed-Python manifest tops out at a CPython that+ # cannot import torch, and a bare "does it run" check reused it over the pinned release.+ OLD="$CASE/old uv"+ fake_uv "$OLD" 0 0.4.0+ assert_eq "$shell: a uv below the minimum version is not reused" \+ "none" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$OLD" "$shell" "$PROBE")"+ case "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$OLD" "$shell" "$DIAG")" in+ *"old=$OLD/uv"*) ok "$shell: ...and the diagnostic names the version it refused" ;;+ *) bad "$shell: ...and the diagnostic names the version it refused ($(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$OLD" "$shell" "$DIAG"))" ;;+ esac+ # The floor itself is reused, and a newer one over it.+ fake_uv "$OLD" 0 0.9.3+ assert_eq "$shell: a uv exactly at the minimum version is reused" \+ "found=$OLD" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$OLD" "$shell" "$PROBE")"+ # A prerelease of the floor is the floor minus something, and install.sh's _uv_version_ok+ # refuses it, so reuse has to as well. One above the floor is a normal release to both.+ fake_uv "$OLD" 0 "0.9.3-rc.1"+ assert_eq "$shell: a prerelease of the minimum version is not reused" \+ "none" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$OLD" "$shell" "$PROBE")"+ fake_uv "$OLD" 0 "0.9.4-rc1"+ assert_eq "$shell: a prerelease above the minimum version is reused" \+ "found=$OLD" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$OLD" "$shell" "$PROBE")"+ # Runs, answers as something else: a miss, and the case a Windows stand-in cannot express.+ NOTUV="$CASE/not uv"+ mkdir -p "$NOTUV"+ printf '#!/bin/sh\necho "curl 8.9.1 (x86_64-pc-linux-gnu)"\nexit 0\n' > "$NOTUV/uv"+ chmod +x "$NOTUV/uv"+ assert_eq "$shell: a binary that runs but does not answer as uv is not reused" \+ "none" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$NOTUV" "$shell" "$PROBE")"++ # One directory, however many variables name it: launched once, named once.+ DUP="$CASE/one dir"+ fake_uv "$DUP"+ case "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$DUP" UV_UNMANAGED_INSTALL="$DUP" XDG_BIN_HOME="$DUP" "$shell" "$DIAG")" in+ found) ok "$shell: duplicate destinations are searched once" ;;+ *) bad "$shell: duplicate destinations are searched once" ;;+ esac+ rm -f "$DUP/uv"+ case "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$DUP" UV_UNMANAGED_INSTALL="$DUP" XDG_BIN_HOME="$DUP" "$shell" "$DIAG")" in+ "looked=$DUP/uv, $HOME_DIR/.local/bin/uv miss= old=") ok "$shell: ...and named once in the miss diagnostic" ;;+ *) bad "$shell: ...and named once in the miss diagnostic ($(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$DUP" UV_UNMANAGED_INSTALL="$DUP" XDG_BIN_HOME="$DUP" "$shell" "$DIAG"))" ;;+ esac++ # A second search in one process reports its own destinations, not the first search's.+ TWICE="$WORK/$shell twice.sh"+ {+ printf '%s\n' "$HELPER"+ cat <<'BODY'+_setup_find_installed_uv || :+_setup_find_installed_uv || :+printf 'looked=%s' "$_SETUP_UV_LOOKED"+BODY+ } > "$TWICE"+ assert_eq "$shell: a second search does not inherit the first one's destinations" \+ "looked=$HOME_DIR/.local/bin/uv" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" "$shell" "$TWICE")"++ # A uv that never answers: the probe is bounded, so a miss is reported, not a hang.+ # NOT gated on `command -v timeout`: it was, and stock macOS has none, so the one platform+ # that takes the watchdog branch skipped the whole block (27 assertions against 43 on Linux).+ if true; then+ HANG="$CASE/hangs"+ mkdir -p "$HANG"+ printf '#!/bin/sh\nsleep 60\n' > "$HANG/uv"+ chmod +x "$HANG/uv"+ HANG_PROBE="$WORK/$shell hang probe.sh"+ # The 20 s ceiling is the helper's; the test only needs it finite.+ { echo '_SETUP_UV_PROBE_SECONDS=2'; cat "$PROBE"; } > "$HANG_PROBE"+ _hang_started=$(date +%s)+ assert_eq "$shell: a uv that never answers is not reused" \+ "none" "$(env -i PATH="$BARE_PATH" HOME="$HOME_DIR" UV_INSTALL_DIR="$HANG" "$shell" "$HANG_PROBE")"+ if [ $(( $(date +%s) - _hang_started )) -lt 30 ]; then+ ok "$shell: ...and the probe returned within its bound"+ else+ bad "$shell: ...and the probe returned within its bound"+ fi+ # Stock macOS has no GNU timeout: a PATH with only the shell and sleep must still return.+ NOTO="$CASE/no timeout bin"+ mkdir -p "$NOTO"+ ln -s "$(command -v sleep)" "$NOTO/sleep"+ ln -s "$(command -v "$shell")" "$NOTO/$shell"+ # Stock macOS ships no GNU timeout and DOES ship ps, which is how the probe learns whether+ # its child got a process group. Leaving ps out made the fixture prove the weaker path.+ [ -n "$(command -v ps)" ] && ln -s "$(command -v ps)" "$NOTO/ps"+ _hang_started=$(date +%s)+ assert_eq "$shell: without GNU timeout a uv that never answers is still not reused" \+ "none" "$(env -i PATH="$NOTO" HOME="$HOME_DIR" UV_INSTALL_DIR="$HANG" "$shell" "$HANG_PROBE")"+ if [ $(( $(date +%s) - _hang_started )) -lt 30 ]; then+ ok "$shell: ...and the fallback bound held"+ else+ bad "$shell: ...and the fallback bound held"+ fi+ # Cancelling setup mid-probe must take the candidate with it. Only the watchdog branch+ # needs this: `timeout` is its own process and enforces the ceiling whatever happens to+ # the shell, while the watchdog's ceiling IS the shell being cancelled.+ CANCEL="$WORK/$shell cancel probe.sh"+ {+ printf '%s\n' "$HELPER"+ printf '_setup_uv_probe_exec "%s/uv"\n' "$HANG"+ } > "$CANCEL"+ env -i PATH="$NOTO" HOME="$HOME_DIR" _SETUP_UV_PROBE_SECONDS=30 \+ "$shell" "$CANCEL" >/dev/null 2>&1 &+ _cancel_sup=$!+ sleep 3+ kill -TERM "$_cancel_sup" 2>/dev/null || :+ # The supervisor dies of the signal, so `wait` reports 143: not a test failure.+ wait "$_cancel_sup" 2>/dev/null || :+ sleep 2+ # Snapshot first and match in the shell: piping into grep puts the pattern on grep's own+ # command line, so `ps | grep` matches itself and the check can never go green.+ _cancel_snap=$(ps -A -o args= 2>/dev/null) || _cancel_snap=""+ case "$_cancel_snap" in+ *"$HANG/uv"*) bad "$shell: cancelling setup kills the probe with it" ;;+ *) ok "$shell: cancelling setup kills the probe with it" ;;+ esac++ # A uv that ignores TERM: both branches must end in KILL.+ DEAF="$CASE/ignores term"+ mkdir -p "$DEAF"+ # A loop, not one long sleep: `sleep` does not ignore TERM, so a group TERM would end the+ # sleep, the script would fall off the end, and a stand-in meant to survive TERM would not.+ printf '#!/bin/sh\ntrap "" TERM\n_i=0\nwhile [ "$_i" -lt 60 ]; do sleep 1; _i=$((_i + 1)); done\n' > "$DEAF/uv"+ chmod +x "$DEAF/uv"+ # The cancel path shares one routine with the ceiling, so what a cancel does to a binary+ # that ignores TERM is decided here: TERM, a bounded grace, then KILL. Tested on the+ # routine rather than by cancelling a setup, because the lifetime of an orphan after its+ # shell dies is the host's business, not this code's, and the assertion would be measuring+ # the host.+ TERMINATE="$WORK/$shell terminate.sh"+ DEAF_READY="$CASE/deaf is deaf"+ # It announces itself only once TERM is ignored: signalling before that line runs would+ # kill it by default action and the case would pass without the escalation existing.+ printf '#!/bin/sh\ntrap "" TERM\n: > "%s"\n_i=0\nwhile [ "$_i" -lt 20 ]; do sleep 1; _i=$((_i + 1)); done\n' \+ "$DEAF_READY" > "$DEAF/ready uv"+ chmod +x "$DEAF/ready uv"+ rm -f "$DEAF_READY"+ {+ printf '%s\n' "$HELPER"+ printf '"%s/ready uv" --version >/dev/null 2>&1 </dev/null &\n' "$DEAF"+ printf '_t_ready="%s"\n' "$DEAF_READY"+ cat <<'BODY'+_t_pid=$!+_t_waited=0+while [ ! -f "$_t_ready" ] && [ "$_t_waited" -lt 10 ]; do+ sleep 1+ _t_waited=$((_t_waited + 1))+done+[ -f "$_t_ready" ] || { printf 'never armed'; exit 0; }+_setup_uv_probe_terminate "$_t_pid" "$_t_pid" 1+# How it ended, not whether it is still listed: a killed child sits as a zombie until it is+# waited for, and `kill -0` answers yes for one of those.+wait "$_t_pid" 2>/dev/null+printf '%s' "$?"+BODY+ } > "$TERMINATE"+ # 137 is 128 + SIGKILL: TERM alone leaves this stand-in running to its own end, rc 0.+ assert_eq "$shell: a probe that ignores TERM is escalated to KILL" \+ "137" "$(env -i PATH="$NOTO" HOME="$HOME_DIR" "$shell" "$TERMINATE")"+ for _deaf_path in "$BARE_PATH" "$NOTO"; do+ _hang_started=$(date +%s)+ assert_eq "$shell: a uv that ignores TERM is not reused (PATH=$_deaf_path)" \+ "none" "$(env -i PATH="$_deaf_path" HOME="$HOME_DIR" UV_INSTALL_DIR="$DEAF" "$shell" "$HANG_PROBE")"+ if [ $(( $(date +%s) - _hang_started )) -lt 30 ]; then+ ok "$shell: ...and the KILL escalation held the bound"+ else+ bad "$shell: ...and the KILL escalation held the bound"+ fi+ done+ fi+done++# Source contract: the reuse sits between the PATH probe and the download, in both shells.+_probe_at=$(grep -n '^if command -v uv &>/dev/null; then$' "$SETUP_SH" | head -1 | cut -d: -f1)+_reuse_at=$(grep -n '^elif _setup_find_installed_uv; then$' "$SETUP_SH" | head -1 | cut -d: -f1)+_install_at=$(grep -n 'if _setup_install_uv_pinned; then' "$SETUP_SH" | head -1 | cut -d: -f1)+if [ -n "$_probe_at" ] && [ -n "$_reuse_at" ] && [ -n "$_install_at" ] \+ && [ "$_probe_at" -lt "$_reuse_at" ] && [ "$_reuse_at" -lt "$_install_at" ]; then+ ok "setup.sh reuses an installed uv before it downloads one"+else+ bad "setup.sh reuses an installed uv before it downloads one (probe=$_probe_at reuse=$_reuse_at install=$_install_at)"+fi+_ps_probe_at=$(grep -n '^if (Get-Command uv -ErrorAction SilentlyContinue) {$' "$SETUP_PS1" | head -1 | cut -d: -f1)+_ps_reuse_at=$(grep -n '} elseif ((\$installedUvDir = Find-InstalledUv)) {' "$SETUP_PS1" | head -1 | cut -d: -f1)+_ps_install_at=$(grep -n 'Invoke-SetupCommand { Install-UvFromPinnedRelease }' "$SETUP_PS1" | head -1 | cut -d: -f1)+if [ -n "$_ps_probe_at" ] && [ -n "$_ps_reuse_at" ] && [ -n "$_ps_install_at" ] \+ && [ "$_ps_probe_at" -lt "$_ps_reuse_at" ] && [ "$_ps_reuse_at" -lt "$_ps_install_at" ]; then+ ok "setup.ps1 reuses an installed uv before it downloads one"+else+ bad "setup.ps1 reuses an installed uv before it downloads one (probe=$_ps_probe_at reuse=$_ps_reuse_at install=$_ps_install_at)"+fi+# The same destinations, in the same order, on both sides.+for _name in UV_INSTALL_DIR UV_UNMANAGED_INSTALL XDG_BIN_HOME XDG_DATA_HOME; do+ if printf '%s\n' "$HELPER" | grep -q "$_name" && printf '%s\n' "$PS_FINDER" | grep -q "env:$_name"; then+ ok "both shells consult $_name"+ else+ bad "both shells consult $_name"+ fi+done++# The reused directory goes to the END of PATH in both shells: a python beside uv must not+# step in front of the staged interpreter.+if grep -q '^ export PATH="\$PATH:\$_setup_uv_dir"$' "$SETUP_SH"; then+ ok "setup.sh appends the reused uv directory to PATH"+else+ bad "setup.sh appends the reused uv directory to PATH"+fi+if grep -qF '$env:PATH = "$env:PATH;$installedUvDir"' "$SETUP_PS1"; then+ ok "setup.ps1 appends the reused uv directory to PATH"+else+ bad "setup.ps1 appends the reused uv directory to PATH"+fi++# Only a uv that answered counts on both sides: the bounded probe here, an "ok" verdict in setup.ps1.+if printf '%s\n' "$HELPER" | grep -q '_setup_uv_probe_exec "\$_sfu_dir/uv"'; then+ ok "setup.sh probes the candidate through the bounded helper"+else+ bad "setup.sh probes the candidate through the bounded helper"+fi+if printf '%s\n' "$PS_FINDER" | grep -q -- '-ne "ok") { continue }'; then+ ok "setup.ps1 reuses only a uv with an ok verdict"+else+ bad "setup.ps1 reuses only a uv with an ok verdict"+fi++# ...and on each side it clears that platform's installer floor, so reuse accepts exactly what+# the installer would have accepted. The two numbers differ on purpose: install.sh refuses a uv+# whose managed-Python manifest tops out at a CPython that cannot import torch, install.ps1 keeps+# that patch out with $PythonSkip instead and stays at 0.8.16.+_sh_floor=$(grep '^_SETUP_UV_MIN_VERSION="' "$SETUP_SH" | head -1 | sed 's/.*"\(.*\)"/\1/')+_ps_floor=$(grep '^\$SetupUvMinVersion = "' "$SETUP_PS1" | head -1 | sed 's/.*"\(.*\)"/\1/')+_install_floor=$(grep '^UV_MIN_VERSION="' "$SCRIPT_DIR/../../install.sh" | head -1 | sed 's/.*"\(.*\)"/\1/')+_install_ps_floor=$(grep '^ \$UvMinVersion = "' "$SCRIPT_DIR/../../install.ps1" | head -1 | sed 's/.*"\(.*\)"/\1/')+if printf '%s\n' "$HELPER" | grep -q '_setup_uv_version_at_least "\$_sfu_ver"'; then+ ok "setup.sh gates the reused uv on a minimum version"+else+ bad "setup.sh gates the reused uv on a minimum version"+fi+if printf '%s\n' "$PS_FINDER" | grep -q 'Test-SetupUvVersionAtLeast'; then+ ok "setup.ps1 gates the reused uv on a minimum version"+else+ bad "setup.ps1 gates the reused uv on a minimum version"+fi+if [ -n "$_sh_floor" ] && [ "$_sh_floor" = "$_install_floor" ]; then+ ok "setup.sh keeps install.sh's floor ($_sh_floor)"+else+ bad "setup.sh keeps install.sh's floor (setup.sh=$_sh_floor install.sh=$_install_floor)"+fi+if [ -n "$_ps_floor" ] && [ "$_ps_floor" = "$_install_ps_floor" ]; then+ ok "setup.ps1 keeps install.ps1's floor ($_ps_floor)"+else+ bad "setup.ps1 keeps install.ps1's floor (setup.ps1=$_ps_floor install.ps1=$_install_ps_floor)"+fi++# Get-SetupUvExecutableVerdict returns the verdict only: a Write-Output in it rode along in+# the return value, `-ne "ok"` on that array was true for every probe, and uv was re-downloaded+# on every update. With no cached exit code a printed version is "ok"; a code that is there decides.+_verdict=$(awk '/^function Get-SetupUvExecutableVerdict \{/ { grab = 1 } grab { print } grab && /^\}/ { exit }' "$SETUP_PS1")+if [ -n "$_verdict" ] && ! printf '%s\n' "$_verdict" | grep -q 'Write-Output'; then+ ok "setup.ps1 uv verdict returns only the verdict"+else+ bad "setup.ps1 uv verdict returns only the verdict"+fi+if printf '%s\n' "$_verdict" | grep -q "match '\^uv \\\\d+"; then+ ok "setup.ps1 uv verdict accepts a printed version"+else+ bad "setup.ps1 uv verdict accepts a printed version"+fi++# Candidates use .NET Combine: Join-Path terminates on a missing drive under+# ErrorActionPreference Stop, before the installation branch's try, so one bad XDG_DATA_HOME ended setup.+_finder=$(awk '/^function Find-InstalledUv \{/ { grab = 1 } grab { print } grab && /^\}/ { exit }' "$SETUP_PS1")+if [ -n "$_finder" ] && ! printf '%s\n' "$_finder" | grep -q 'Join-Path' && printf '%s\n' "$_finder" | grep -q 'System.IO.Path\]::Combine'; then+ ok "setup.ps1 builds uv candidates without Join-Path"+else+ bad "setup.ps1 builds uv candidates without Join-Path"+fi++echo ""+echo " PASS: $PASS"+echo " FAIL: $FAIL"+if [ "$FAIL" -gt 0 ]; then+ echo "FAILED"+ exit 1+fi+echo "ALL PASSED"diff --git a/tests/studio/install/test_setup_fast_path_guard.py b/tests/studio/install/test_setup_fast_path_guard.pyindex 3da5ab03d8c..28e75223b7e 100644--- a/tests/studio/install/test_setup_fast_path_guard.py+++ b/tests/studio/install/test_setup_fast_path_guard.py@@ -422,9 +422,24 @@ def test_the_windows_uv_probe_looks_where_the_pinned_installer_put_uv():start = text.index("$UseUv = $false")probe = text[start : start + 700]assert (- "Get-UvInstallDir" in probe+ "Find-InstalledUv" in probe), "the uv probe checks PATH only again; on Windows that reinstalls uv every update"- assert 'Join-Path (Get-UvInstallDir) "uv.exe"' in probe+ # The finder replaced the inline `Test-Path (Join-Path (Get-UvInstallDir) "uv.exe")`, which+ # saw one destination and never ran what it found: a uv.exe that could not run was put on+ # PATH anyway. It must still start from the installer's destination, or the two can disagree.+ finder = text[text.index("function Find-InstalledUv {") :]+ finder = finder[: finder.index("\n}\n") + 3]+ assert "Get-UvInstallDir" in finder, (+ "the uv probe no longer starts from the installer's destination helper; the probe and "+ "the installer can now disagree about where uv lives"+ )+ assert 'Combine($dir, "uv.exe")' in finder, "the probe stopped looking for uv.exe itself"+ # Join-Path terminates on a missing drive under ErrorActionPreference Stop, and this runs+ # outside the installation branch's try, so XDG_DATA_HOME=Z:\xdg ended setup.+ body = finder[finder.index("$candidates") :]+ assert (+ "Join-Path" not in body+ ), "the candidate paths are built with Join-Path again; one missing drive ends setup"# And the run that installs uv has to use it, or it records a manifest with no uv_version and# the next run rewrites it: a no-op update that is not one.install_arm = text[text.index('substep "installing uv package manager..."') :][:2000]diff --git a/tests/studio_setup_ps1/Studio.Setup.FindInstalledUv.Tests.ps1 b/tests/studio_setup_ps1/Studio.Setup.FindInstalledUv.Tests.ps1new file mode 100644index 00000000000..88076663787--- /dev/null+++ b/tests/studio_setup_ps1/Studio.Setup.FindInstalledUv.Tests.ps1@@ -0,0 +1,287 @@+<#+ Find-InstalledUv, executed rather than read.++ tests/sh/test_setup_reuse_installed_uv.sh runs the shell finder for real, but checks the+ PowerShell one only by grepping setup.ps1. Mutation-tested: deleting the winget alias+ directory from the candidates, and making the finder skip every candidate so it can never+ reuse anything, both left that suite green at 43 of 43. Windows is where the re-download+ cost 42 of a 53 s no-op update, so it is the side that most needs running.++ Fixtures are a real executable copied into a candidate directory, and a text file for the+ one that cannot run, so both the Test-Path gate and the launch are exercised.+#>++BeforeAll {+ . (Join-Path $PSScriptRoot 'Get-FunctionSource.ps1')+ $setup = Join-Path $PSScriptRoot '../../studio/setup.ps1'+ foreach ($fn in @('Get-UvInstallDir', 'Get-SetupUvExecutableVerdict', 'Get-InstalledUvVerdict',+ 'Test-SetupUvVersionAtLeast', 'Find-InstalledUv')) {+ $src = Get-FunctionSource -Path $setup -Name $fn+ if (-not $src) { throw "could not extract $fn from setup.ps1" }+ . ([scriptblock]::Create($src))+ }+ # Read from setup.ps1, not repeated here, so a change to the number cannot leave these cases+ # testing the old one.+ $script:SetupUvMinVersionSource = (Select-String -Path $setup -Pattern '^\$SetupUvMinVersion = "([^"]+)"' |+ Select-Object -First 1).Matches[0].Groups[1].Value+ if (-not $script:SetupUvMinVersionSource) { throw "could not read `$SetupUvMinVersion from setup.ps1" }+ $SetupUvMinVersion = $script:SetupUvMinVersionSource+ # setup.ps1 reports through substep; the finder must not depend on its formatting.+ function substep { param([string]$Message, [string]$Color = 'DarkGray') }++ $script:UvCandidateVars = @(+ 'UV_INSTALL_DIR', 'UV_UNMANAGED_INSTALL', 'XDG_BIN_HOME', 'XDG_DATA_HOME', 'LOCALAPPDATA'+ )++ function New-Sandbox {+ $dir = Join-Path ([System.IO.Path]::GetTempPath()) ('finduv_' + [guid]::NewGuid().ToString('N').Substring(0, 10))+ New-Item -ItemType Directory -Force -Path $dir | Out-Null+ New-Item -ItemType Directory -Force -Path (Join-Path $dir 'home') | Out-Null+ foreach ($v in $script:UvCandidateVars) { Remove-Item -Path ("env:" + $v) -ErrorAction SilentlyContinue }+ # A home with no uv in it, so the default tier is a miss unless a test populates it.+ $env:USERPROFILE = Join-Path $dir 'home'+ if (-not $IsWindows) { $env:HOME = Join-Path $dir 'home' }+ return $dir+ }++ function Copy-RunnableExe {+ # Copied ALONE into a candidate directory, it still has to launch and exit 0 for+ # `--version`. pwsh.exe does NOT qualify: on Windows it cannot start without its runtime+ # files beside it. curl.exe and tar.exe link only against System32 and take --version.+ param([Parameter(Mandatory)][string]$Destination)+ foreach ($src in $script:RunnableExeCandidates) {+ if (-not (Test-Path -LiteralPath $src -PathType Leaf)) { continue }+ try { Copy-Item -LiteralPath $src -Destination $Destination -Force -ErrorAction Stop } catch { continue }+ if (Test-ExeAnswers -Path $Destination) { return $src }+ }+ throw ("no stand-in executable on this host answers --version with exit 0; tried: " ++ ($script:RunnableExeCandidates -join ', '))+ }++ function Test-ExeAnswers {+ param([Parameter(Mandatory)][string]$Path)+ $out = [System.IO.Path]::GetTempFileName()+ $err = [System.IO.Path]::GetTempFileName()+ try {+ $p = Start-Process -FilePath $Path -ArgumentList "--version" -NoNewWindow -PassThru `+ -RedirectStandardOutput $out -RedirectStandardError $err -ErrorAction Stop+ if (-not $p.WaitForExit(15000)) { try { $p.Kill() } catch {}; return $false }+ $p.WaitForExit()+ return ($p.ExitCode -eq 0)+ } catch {+ return $false+ } finally {+ Remove-Item -LiteralPath $out, $err -Force -ErrorAction SilentlyContinue+ }+ }++ $sys = if ($env:SystemRoot) { Join-Path $env:SystemRoot 'System32' } else { '' }+ $script:RunnableExeCandidates = if ($IsWindows) {+ @((Join-Path $sys 'curl.exe'), (Join-Path $sys 'tar.exe'))+ } else {+ @()+ }++ function New-FakeUv {+ # ok: runs and exits 0. broken: exists, cannot launch. folder: a directory named uv.exe.+ # old: runs, answers below the floor (POSIX only, where the stand-in is a script).+ param([Parameter(Mandatory)][string]$Dir, [string]$Kind = 'ok')+ New-Item -ItemType Directory -Force -Path $Dir | Out-Null+ $exe = Join-Path $Dir 'uv.exe'+ if ($Kind -eq 'folder') {+ New-Item -ItemType Directory -Force -Path $exe | Out-Null+ return $exe+ }+ if ($Kind -eq 'broken') {+ Set-Content -LiteralPath $exe -Value 'this is not an executable'+ return $exe+ }+ if ($IsWindows) {+ if ($Kind -eq 'old') { throw "the Windows stand-in cannot choose what it prints" }+ Copy-RunnableExe -Destination $exe | Out-Null+ } else {+ $version = if ($Kind -eq 'old') { '0.4.0' } else { '0.12.1' }+ Set-Content -LiteralPath $exe -Value "#!/bin/sh`nprintf 'uv $version\n'`nexit 0`n"+ & chmod +x $exe+ }+ return $exe+ }+}++Describe "the fixtures themselves" {+ It "has a stand-in that really runs, so a finder miss cannot be blamed on the fixture" {+ $dir = Join-Path ([System.IO.Path]::GetTempPath()) ('fixtureprobe_' + [guid]::NewGuid().ToString('N').Substring(0, 8))+ try {+ $exe = New-FakeUv -Dir $dir+ Test-ExeAnswers -Path $exe | Should -BeTrue+ } finally {+ Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue+ }+ }++ It "has a broken stand-in that really cannot run" {+ $dir = Join-Path ([System.IO.Path]::GetTempPath()) ('fixtureprobe_' + [guid]::NewGuid().ToString('N').Substring(0, 8))+ try {+ $exe = New-FakeUv -Dir $dir -Kind broken+ Test-ExeAnswers -Path $exe | Should -BeFalse+ } finally {+ Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue+ }+ }+}++Describe "Find-InstalledUv" {+ BeforeAll {+ # The Windows stand-in is a real console binary that is NOT uv, so its --version line+ # cannot clear the floor and every discovery case would miss for an unrelated reason.+ # The floor is answered here and tested on its own in "the uv version floor" below.+ if ($IsWindows) {+ function Test-SetupUvVersionAtLeast { param([string]$VersionLine, [string]$Minimum) return $true }+ }+ }+ BeforeEach { $script:Sandbox = New-Sandbox }+ AfterEach {+ foreach ($v in $script:UvCandidateVars) { Remove-Item -Path ("env:" + $v) -ErrorAction SilentlyContinue }+ if ($script:Sandbox) { Remove-Item -LiteralPath $script:Sandbox -Recurse -Force -ErrorAction SilentlyContinue }+ }++ It "is a miss when no destination holds a uv, and names what it looked at" {+ Find-InstalledUv | Should -BeNullOrEmpty+ $script:InstalledUvLooked | Should -Not -BeNullOrEmpty+ $script:InstalledUvProbeMiss | Should -BeNullOrEmpty+ }++ It "reuses a uv that runs, at the destination the installer writes to" {+ $dest = Join-Path $script:Sandbox 'custom dir'+ $env:UV_INSTALL_DIR = $dest+ New-FakeUv -Dir $dest | Out-Null+ (Get-UvInstallDir) | Should -Be $dest+ Find-InstalledUv | Should -Be $dest+ }++ It "skips a uv that cannot run and keeps looking" {+ $broken = Join-Path $script:Sandbox 'broken dir'+ $env:UV_INSTALL_DIR = $broken+ New-FakeUv -Dir $broken -Kind broken | Out-Null+ $good = Join-Path $env:USERPROFILE '.local/bin'+ New-FakeUv -Dir $good | Out-Null+ Find-InstalledUv | Should -Be ([System.IO.Path]::Combine($env:USERPROFILE, '.local', 'bin'))+ $script:InstalledUvProbeMiss | Should -Not -BeNullOrEmpty+ }++ It "does not reuse a directory that happens to be named uv.exe" {+ $dest = Join-Path $script:Sandbox 'folder dir'+ $env:UV_INSTALL_DIR = $dest+ New-FakeUv -Dir $dest -Kind folder | Out-Null+ Find-InstalledUv | Should -BeNullOrEmpty+ }++ It "finds the uv install.ps1 put in winget's alias directory" {+ # winget's alias directory reaches PATH only through the registry, so a process started+ # before that install never saw it: this is the tier that made the Windows no-op update+ # download uv again even though install.ps1 had just installed it.+ $local = Join-Path $script:Sandbox 'localappdata'+ $env:LOCALAPPDATA = $local+ $links = [System.IO.Path]::Combine($local, 'Microsoft', 'WinGet', 'Links')+ New-FakeUv -Dir $links | Out-Null+ Find-InstalledUv | Should -Be $links+ }++ It "searches the installer's destination before any other tier" {+ $dest = Join-Path $script:Sandbox 'install dest'+ $env:UV_INSTALL_DIR = $dest+ Find-InstalledUv | Out-Null+ $script:InstalledUvLooked[0] | Should -Be ([System.IO.Path]::Combine($dest, 'uv.exe'))+ }++ It "looks at one directory once, however many variables point at it" {+ $dest = Join-Path $script:Sandbox 'shared dest'+ $env:UV_INSTALL_DIR = $dest+ $env:UV_UNMANAGED_INSTALL = $dest+ $env:XDG_BIN_HOME = $dest+ Find-InstalledUv | Out-Null+ @($script:InstalledUvLooked | Where-Object { $_ -like (Join-Path $dest '*') }).Count |+ Should -Be 1+ }++ It "honours the documented priority order" {+ $first = Join-Path $script:Sandbox 'tier one'+ $second = Join-Path $script:Sandbox 'tier two'+ $env:UV_INSTALL_DIR = $first+ $env:UV_UNMANAGED_INSTALL = $second+ New-FakeUv -Dir $first | Out-Null+ New-FakeUv -Dir $second | Out-Null+ Find-InstalledUv | Should -Be $first+ }++ It "refuses a uv that runs but does not clear the floor, and says which one" {+ # The refusal itself, on every platform: the gate answers no for this case only, so+ # what is under test is the finder's handling of it, not the version parsing.+ function Test-SetupUvVersionAtLeast { param([string]$VersionLine, [string]$Minimum) return $false }+ $dest = Join-Path $script:Sandbox 'old uv'+ $env:UV_INSTALL_DIR = $dest+ $exe = New-FakeUv -Dir $dest+ Find-InstalledUv | Should -BeNullOrEmpty+ $script:InstalledUvTooOld | Should -Be $exe+ $script:InstalledUvProbeMiss | Should -BeNullOrEmpty+ }++ It "reuses a uv whose version clears the floor" -Skip:$IsWindows {+ $dest = Join-Path $script:Sandbox 'new uv'+ $env:UV_INSTALL_DIR = $dest+ New-FakeUv -Dir $dest | Out-Null+ Find-InstalledUv | Should -Be $dest+ $script:InstalledUvTooOld | Should -BeNullOrEmpty+ }++ It "does not reuse a real uv older than the floor" -Skip:$IsWindows {+ $dest = Join-Path $script:Sandbox 'ancient uv'+ $env:UV_INSTALL_DIR = $dest+ $exe = New-FakeUv -Dir $dest -Kind old+ Find-InstalledUv | Should -BeNullOrEmpty+ $script:InstalledUvTooOld | Should -Be $exe+ }+}++Describe "the uv version floor" {+ # The parsing on its own, so the discovery cases above do not have to carry it. install.ps1+ # refuses a uv below the same number outright; reusing one instead of downloading the pinned+ # release would hand the dependency pass the interpreter that refusal exists to avoid.+ It "reads <line> as clearing <floor>: <expected>" -ForEach @(+ @{ line = 'uv 0.12.1 (0123456 2026-01-01)'; floor = '0.9.3'; expected = $true }+ @{ line = 'uv 0.9.3'; floor = '0.9.3'; expected = $true }+ @{ line = 'uv 1.0.0'; floor = '0.9.3'; expected = $true }+ @{ line = 'uv 0.9.2'; floor = '0.9.3'; expected = $false }+ @{ line = 'uv 0.4.0'; floor = '0.9.3'; expected = $false }+ @{ line = 'curl 8.9.1 (x86_64-pc-linux-gnu)'; floor = '0.9.3'; expected = $false }+ # A prerelease of the floor is the floor minus something. install.sh's _uv_version_ok+ # refuses exactly this shape, and one above the floor is a normal release to both.+ @{ line = 'uv 0.9.3-rc.1'; floor = '0.9.3'; expected = $false }+ @{ line = 'uv 0.9.3+build5'; floor = '0.9.3'; expected = $false }+ @{ line = 'uv 0.9.4-rc1'; floor = '0.9.3'; expected = $true }+ @{ line = 'uv 1.0.0-beta'; floor = '0.9.3'; expected = $true }+ # The floor this file actually ships is install.ps1's, which is lower than install.sh's:+ # nothing here asks uv for an interpreter, so the manifest reason that raised the POSIX+ # number does not apply, and refusing 0.8.16-0.9.2 would decline to reuse a uv the+ # Windows installer installs and keeps.+ @{ line = 'uv 0.8.16'; floor = '0.8.16'; expected = $true }+ @{ line = 'uv 0.9.2'; floor = '0.8.16'; expected = $true }+ @{ line = 'uv 0.8.15'; floor = '0.8.16'; expected = $false }+ @{ line = 'uv 0.8.16-rc1'; floor = '0.8.16'; expected = $false }+ @{ line = 'not a version at all'; floor = '0.9.3'; expected = $false }+ @{ line = ''; floor = '0.9.3'; expected = $false }+ ) {+ (Test-SetupUvVersionAtLeast -VersionLine $line -Minimum $floor) | Should -Be $expected+ }++ It "compares numerically, not as text" {+ # 0.12.1 sorts below 0.9.3 as a string; that is the comparison this must not be.+ Test-SetupUvVersionAtLeast -VersionLine 'uv 0.12.1' -Minimum '0.9.3' | Should -BeTrue+ }++ It "reads the floor setup.ps1 actually ships" {+ $script:SetupUvMinVersionSource | Should -Not -BeNullOrEmpty+ Test-SetupUvVersionAtLeast -VersionLine 'uv 0.12.1' -Minimum $script:SetupUvMinVersionSource |+ Should -BeTrue+ }+}