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
Reduce antivirus false positives in the desktop installers (#8586)
Daniel Han5a5bf64130d7
diff --git a/.github/workflows/desktop-app-clean-machine-ci.yml b/.github/workflows/desktop-app-clean-machine-ci.ymlindex a2d95c9b9ce..9d046a2cb53 100644--- a/.github/workflows/desktop-app-clean-machine-ci.yml+++ b/.github/workflows/desktop-app-clean-machine-ci.yml@@ -438,10 +438,13 @@ jobs:# The launch step below only proves the process stayed alive: on a fresh home# preflight reports not_installed and the app waits for a click on the install# screen (use-tauri-backend.ts:252-254, startup-screen.tsx:388-389), so a bundle- # with a missing or broken install.sh passed both Linux rows. tauri.conf.json:56-59+ # with a missing or broken install.sh passed both Linux rows. tauri.linux.conf.json# ships it as a bundle resource, so find it there and run it as install.rs does.if [ "${{ matrix.kind }}" = "deb" ]; then- SH="$(dpkg -L "$(dpkg-deb -f dl/*.deb Package)" | grep -E '/install\.sh$' | head -1)"+ # `|| true`: grep exits 1 when it selects nothing, and under the `set -o pipefail`+ # above plus this step's `bash -e` that aborts the assignment outright, swallowing+ # the explicit annotation below in favour of a bare exit 1.+ SH="$(dpkg -L "$(dpkg-deb -f dl/*.deb Package)" | grep -E '/install\.sh$' | head -1 || true)"else# ls returns a bare filename here, and a command word with no slash resolves# through PATH, not the cwd, so this needs the ./ prefix.diff --git a/install.ps1 b/install.ps1index 6bf22983e1b..a05242eea71 100644--- a/install.ps1+++ b/install.ps1@@ -1,16 +1,12 @@# Unsloth Studio Installer for Windows PowerShell#-# Usage: irm https://unsloth.ai/install.ps1 | iex-# Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass; .\install.ps1 --local+# Usage, options and the web one-liner: see "Unsloth Studio (web UI)" in the README+# (https://github.com/unslothai/unsloth#unsloth-studio-web-ui). Not repeated here, because+# AMSI scans this file in full before a line of it runs and nothing reads the header from inside.#-# irm | iex cannot forward arguments, so web installs take options as env vars set-# before the pipe (flags still work via .\install.ps1):-# $env:UNSLOTH_NO_TORCH=1; irm https://unsloth.ai/install.ps1 | iex # skip PyTorch (GGUF-only)-# $env:UNSLOTH_SKIP_AUTOSTART=1; irm https://unsloth.ai/install.ps1 | iex # do not prompt to launch-# $env:UNSLOTH_PYTHON='3.12'; irm https://unsloth.ai/install.ps1 | iex # pin Python version-# $env:UNSLOTH_STUDIO_HOME='C:\path'; irm https://unsloth.ai/install.ps1 | iex-# .\install.ps1 --no-torch # equivalent flag-# Or pass flags to a scriptblock: & ([scriptblock]::Create((irm https://unsloth.ai/install.ps1))) --no-torch+# The web entry point cannot forward arguments, so it takes options as environment variables set+# beforehand (UNSLOTH_NO_TORCH, UNSLOTH_SKIP_AUTOSTART, UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME); a+# local run takes the equivalent flags (--no-torch, --skip-autostart, --python, --local).## Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME (alias) > $USERPROFILE\.unsloth\studio#@@ -20,7 +16,7 @@ function Install-UnslothStudio {$ErrorActionPreference = "Stop"# The user's PowerShell profile has already run by the time this does, and the documented- # "irm https://unsloth.ai/install.ps1 | iex" entry point has no script file to re-launch+ # piped web entry point documented in the README has no script file to re-launch# with -NoProfile, so each way a profile can reach in here is cut individually below.## Off, not Latest: this script predates strict mode, testing environment variables that are@@ -60,7 +56,7 @@ function Install-UnslothStudio {# (27.8 MB) took 41.34s with the bar on against 0.08s with it off, and the uv archive the# same. That is the multi-minute "slow download" users report. -UseBasicParsing does NOT# avoid it and PowerShell 7 never had the cost; only this preference does. Same scoping rule- # as the table above: no qualifier, so the caller's own preference survives "irm ... | iex".+ # as the table above: no qualifier, so the caller's own preference survives a piped web run.$ProgressPreference = 'SilentlyContinue'# The kept proxies travel to studio/setup.ps1 (launched -NoProfile by unsloth_cli, and it@@ -90,7 +86,7 @@ function Install-UnslothStudio {} catch { }}}- # A FUNCTION-local, not $script: or an environment variable: under "irm ... | iex" this runs+ # A FUNCTION-local, not $script: or an environment variable: under a piped web run this runs# in the caller's own session, and the value can carry credentials (http://user:secret@proxy# is the ordinary corporate form) that must not outlive the install on any of the dozens of# return paths. Module-qualified serializer, as in the probe: a profile alias or function@@ -108,7 +104,7 @@ function Install-UnslothStudio {$PSNativeCommandUseErrorActionPreference = $false# Reset per invocation, for the reason at $script:IsIntelXpu further down: under- # "irm ... | iex" $script: is the caller's session scope, so a second run in the same+ # a piped web run, $script: is the caller's session scope, so a second run in the same# console would start on the first run's state. These two are the only ones no later# statement re-assigns unconditionally.$script:UvExe = 'uv'@@ -1361,11 +1357,14 @@ try {# Single-quote the path in the child -Command so `$` / backtick in custom# roots don't get reparsed; double any apostrophes so 'O''Brien' survives.`$studioCommand = "& '" + (`$studioExe -replace "'", "''") + "' studio -p " + `$launchPort+ # RemoteSigned, not Bypass: the child runs an inline -Command against an executable, so no+ # script file is loaded and the two behave identically here. No reason to spend a scored+ # token on a launch that needs no policy relief.`$launchArgs = @('-NoExit','-NoProfile','-ExecutionPolicy',- 'Bypass',+ 'RemoteSigned','-Command',`$studioCommand)@@ -1419,6 +1418,15 @@ exit 0# even when install.ps1 is executed from PowerShell 7.$utf8Bom = New-Object System.Text.UTF8Encoding($true)[System.IO.File]::WriteAllText($launcherPs1, $launcherContent, $utf8Bom)+ # WriteAllText replaces the unnamed data stream and leaves any other NTFS stream on+ # an existing file alone, so a launcher that somehow acquired a mark of the web keeps+ # it across the rewrite. The shortcut loads this under RemoteSigned, which refuses a+ # marked unsigned script, so clear the mark on the file we just authored. A no-op on+ # every ordinary install, where the stream was never there.+ # -Confirm:$false: Unblock-File is SupportsShouldProcess at Medium impact, so a+ # profile lowering $ConfirmPreference would prompt here, and ErrorAction does not+ # suppress a ShouldProcess prompt. On a noninteractive host that skips shortcut setup.+ Unblock-File -LiteralPath $launcherPs1 -Confirm:$false -ErrorAction SilentlyContinue# No .vbs launcher is written. A WScript.Shell .vbs that spawns a hidden# ExecutionPolicy-Bypass PowerShell is exactly the shape VBS-dropper# heuristics score (e.g. Kaspersky HEUR:Trojan.VBS.Agent.gen). The .lnk@@ -1516,9 +1524,28 @@ exit 0# launch-studio.ps1 with a hidden window. We deliberately avoid a# .vbs/WScript.Shell wrapper -- that script-engine shape is what AV# VBS-dropper heuristics score (Kaspersky HEUR:Trojan.VBS.Agent.gen).+ #+ # RemoteSigned, not Bypass: a hidden window beside a bypassed policy is the pair+ # Microsoft's detections key on, and install.rs makes the same call for the app's own+ # launch. This launcher is written locally, so RemoteSigned loads it either way.$powershellForLnk = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe"$shortcutTarget = $powershellForLnk- $shortcutArgs = "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$launcherPs1`""+ $shortcutArgs = "-NoProfile -WindowStyle Hidden -ExecutionPolicy RemoteSigned -File `"$launcherPs1`""+ # A launcher on a share is a REMOTE script to PowerShell and RemoteSigned refuses an+ # unsigned one, so a roaming profile would get a shortcut that exits without starting+ # Studio. Bypass for that case only, and without the hidden window: a console beats+ # nothing launching. A mapped drive (H:, Z:) is the same share and the same zone, and+ # DriveInfo on the root reports Network for both.+ $launcherIsRemote = $launcherPs1 -like "\\*"+ if (-not $launcherIsRemote) {+ try {+ $launcherIsRemote = ([System.IO.DriveInfo]::new(+ [System.IO.Path]::GetPathRoot($launcherPs1))).DriveType -eq 'Network'+ } catch {}+ }+ if ($launcherIsRemote) {+ $shortcutArgs = "-NoProfile -ExecutionPolicy Bypass -File `"$launcherPs1`""+ }try {$wshell = New-Object -ComObject WScript.Shell@@ -1612,7 +1639,7 @@ exit 0}# ── Leave Windows system directories before installing ──- # "Run as administrator" starts in C:\Windows\System32, so `irm ... | iex` installs+ # "Run as administrator" starts in C:\Windows\System32, so a piped web run installs# from there and `unsloth studio setup` refuses only after PyTorch has downloaded,# then rolls back. Relocating is safe: nothing here reads the caller's directory# ($RepoRoot from $PSCommandPath, $StudioHome from the environment), so only@@ -2501,6 +2528,55 @@ exit 0}}+ function Get-UvExecutableVerdict {+ # "ok", "failed" or "unknown". Only the binary itself answering non-zero is "failed".+ # A launch that throws or a wait that times out is "unknown", because the probe got no+ # verdict: Start-Process -NoNewWindow with redirected streams does not behave in a+ # Windows container or on the arm64 image the way it does in a desktop session, and+ # treating that as a broken binary turned three clean-machine CI legs into hard install+ # failures. The digest already proved these bytes are astral's pinned release, so no+ # verdict publishes, as the pre-pin code did. Every path says why.+ param([string]$Path)+ if (-not $Path -or -not (Test-Path -LiteralPath $Path)) { return "failed" }+ # Redirected: uv's version line is not part of this installer's output.+ $outFile = [System.IO.Path]::GetTempFileName()+ $errFile = [System.IO.Path]::GetTempFileName()+ try {+ $proc = Start-Process -FilePath $Path -ArgumentList "--version" -NoNewWindow -PassThru `+ -RedirectStandardOutput $outFile -RedirectStandardError $errFile -ErrorAction Stop+ if (-not $proc.WaitForExit(20000)) {+ try { $proc.Kill() } catch {}+ substep "uv did not answer --version within 20s; installing it unprobed." "Yellow"+ 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.+ try { $proc.WaitForExit() } catch {}+ $code = $null+ try { $code = $proc.ExitCode } catch {}+ if ($null -eq $code -or "$code" -eq "") {+ substep "uv --version gave no exit code; installing it unprobed." "Yellow"+ return "unknown"+ }+ if ($code -eq 0) { return "ok" }+ $detail = ""+ try {+ $detail = Get-Content -LiteralPath $errFile -Raw -ErrorAction SilentlyContinue+ } catch {}+ if ($detail) { $detail = " " + (($detail.Trim()) -replace '\s+', ' ') }+ substep "uv --version exited $code.$detail" "Yellow"+ return "failed"+ } catch {+ substep "could not probe uv: $($_.Exception.Message); installing it unprobed." "Yellow"+ return "unknown"+ } finally {+ Remove-Item -LiteralPath $outFile -Force -ErrorAction SilentlyContinue+ Remove-Item -LiteralPath $errFile -Force -ErrorAction SilentlyContinue+ }+ }+# Fallback for hosts without winget. Same archive, destination and user-PATH# prepend as astral's install.ps1, but it fetches a data file with a pinned# SHA-256 instead of script text run in-process, which is what AMSI and cloud@@ -2538,10 +2614,14 @@ exit 0$destDir = Join-Path $userHome ".local\bin"}- # Same mirrors and precedence as astral's installer; each serves the- # identical asset, so the pin holds across all of them. UV_DOWNLOAD_URL is- # not honoured: it points at an arbitrary version the pin would reject.- $uvBase = if ($env:UV_INSTALLER_GHE_BASE_URL) {+ # astral's sources in astral's order, each exclusive when set: a host that sets one+ # usually cannot reach the public endpoints at all, so trying those first would stall.+ # The pin still applies, so a source serving a different build fails the digest.+ $uvBase = if ($env:UV_DOWNLOAD_URL) {+ @("$($env:UV_DOWNLOAD_URL.TrimEnd('/'))")+ } elseif ($env:INSTALLER_DOWNLOAD_URL) {+ @("$($env:INSTALLER_DOWNLOAD_URL.TrimEnd('/'))")+ } elseif ($env:UV_INSTALLER_GHE_BASE_URL) {@("$($env:UV_INSTALLER_GHE_BASE_URL.TrimEnd('/'))/astral-sh/uv/releases/download/$UvPinnedVersion")} elseif ($env:UV_INSTALLER_GITHUB_BASE_URL) {@("$($env:UV_INSTALLER_GITHUB_BASE_URL.TrimEnd('/'))/astral-sh/uv/releases/download/$UvPinnedVersion")@@ -2554,39 +2634,77 @@ exit 0$zip = Join-Path $work $assettry {[System.IO.Directory]::CreateDirectory($work) | Out-Null+ # Digest per mirror, not once after the loop: a proxy answering 200 with its own+ # body is a successful download by every measure Invoke-WebRequest has, and checking+ # afterwards spends the only attempt on it.$downloaded = $falseforeach ($base in $uvBase) {substep "downloading uv $UvPinnedVersion ($arch) from $base..." "Yellow"try {Invoke-WebRequest -UseBasicParsing -OutFile $zip -Uri "$base/$asset"- $downloaded = $true- break} catch {substep "uv download failed: $($_.Exception.Message)" "Yellow"+ continue+ }+ $actual = ""+ try { $actual = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash } catch {}+ if ($actual -eq $wanted) {+ $downloaded = $true+ break}- }- if (-not $downloaded) { return $false }-- $actual = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash- if ($actual -ne $wanted) {substep "uv download failed checksum verification -- discarding it." "Red"substep "expected $wanted, got $actual" "Red"- return $false+ Remove-Item -LiteralPath $zip -Force -ErrorAction SilentlyContinue}+ if (-not $downloaded) { return $false }# The Windows archives are flat: uv.exe, uvx.exe, uvw.exe at the root.Expand-Archive -LiteralPath $zip -DestinationPath $work -Force[System.IO.Directory]::CreateDirectory($destDir) | Out-Null- $haveUv = $false++ $stagedUv = Join-Path $work "uv.exe"+ if (-not (Test-Path -LiteralPath $stagedUv)) {+ substep "uv.exe was not present in $asset." "Yellow"+ return $false+ }+ # Run it where it landed, before the destination is touched. A host can have a+ # working older uv while AppLocker, WDAC or endpoint protection refuses this one, and+ # copying first would leave the user with neither. A policy scoped to the destination+ # path is not covered here: the caller's fallback handles it.+ if ((Get-UvExecutableVerdict -Path $stagedUv) -eq "failed") {+ substep "the downloaded uv $UvPinnedVersion could not run on this machine." "Yellow"+ return $false+ }++ # uvw.exe is the windowless launcher and has no console to answer a probe on, so+ # the staged uv.exe above stands for the set: it came from the same verified+ # archive. Copy-Item under Stop so a locked or ACL-denied destination fails the+ # install rather than leaving half a set behind quietly.+ $ok = $trueforeach ($exe in @("uv.exe", "uvx.exe", "uvw.exe")) {$src = Join-Path $work $exe- if (Test-Path -LiteralPath $src) {- Copy-Item -LiteralPath $src -Destination (Join-Path $destDir $exe) -Force- if ($exe -eq "uv.exe") { $haveUv = $true }+ if (-not (Test-Path -LiteralPath $src)) { continue }+ $dst = Join-Path $destDir $exe+ try {+ Copy-Item -LiteralPath $src -Destination $dst -Force -ErrorAction Stop+ } catch {+ $ok = $false+ break+ }+ if ($exe -eq "uv.exe") {+ # Copy-Item is non-terminating under some callers preference, so compare+ # against the archive we verified: a stale uv.exe must not pass for ours.+ $copied = $false+ try {+ $copied = (Test-Path -LiteralPath $dst) -and+ (Get-FileHash -LiteralPath $dst -Algorithm SHA256).Hash -eq+ (Get-FileHash -LiteralPath $src -Algorithm SHA256).Hash+ } catch { $copied = $false }+ if (-not $copied) { $ok = $false; break }}}- if (-not $haveUv) {- substep "uv.exe was not present in $asset." "Yellow"+ if (-not $ok) {+ substep "the downloaded uv $UvPinnedVersion could not run on this machine." "Yellow"return $false}} finally {@@ -3642,7 +3760,7 @@ exit 0# qualify, UHD / HD / Iris Xe do not.$HasIntelGpu = $false$IntelGpuLabel = $null- # Reset every invocation: under "irm ... | iex" $script: is the caller's session scope, so a+ # Reset every invocation: under a piped web run $script: is the caller's session scope, so a# second run would inherit a stale $true and reroute a now-NVIDIA host to the xpu index.$script:IsIntelXpu = $false# $AmdHasGpuWheels keeps a wheel-served AMD host out of the XPU reroute below; an AMD hostdiff --git a/install.sh b/install.shindex a35328b778d..ef70a2f3bbd 100755--- a/install.sh+++ b/install.sh@@ -2,17 +2,16 @@## Unsloth Studio Installer#-# Usage: curl -fsSL https://unsloth.ai/install.sh | sh-# wget -qO- https://unsloth.ai/install.sh | sh-# ./install.sh --local (install from a cloned repo instead of PyPI)+# Usage, supported options and the web one-liner are documented in the repository README under+# "Unsloth Studio (web UI)": https://github.com/unslothai/unsloth#unsloth-studio-web-ui.+# They are not repeated here: this file ships inside the Linux desktop bundle, where a header+# rehearsing download-and-run command lines is the first thing a generic script classifier reads,+# and nothing in the script consults it.#-# Piped installs take options as env vars after the pipe (a bare `| sh --no-torch`-# makes sh reject --no-torch as its own option). Flags still work via ./install.sh:-# curl -fsSL https://unsloth.ai/install.sh | UNSLOTH_NO_TORCH=1 sh # skip PyTorch (GGUF-only)-# curl -fsSL https://unsloth.ai/install.sh | UNSLOTH_SKIP_AUTOSTART=1 sh # do not prompt to launch-# curl -fsSL https://unsloth.ai/install.sh | UNSLOTH_PYTHON=3.12 sh # pin Python version-# curl -fsSL https://unsloth.ai/install.sh | UNSLOTH_STUDIO_HOME=/abs/path sh-# Equivalent flags: ./install.sh --no-torch --python 3.12 (or pipe them: sh -s -- --no-torch)+# A piped install takes options as environment variables after the pipe (UNSLOTH_NO_TORCH,+# UNSLOTH_SKIP_AUTOSTART, UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME) because a bare `--no-torch` after+# the pipe would be read as an option to sh itself; a local run takes the equivalent flags+# (--no-torch, --python, --local).## Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME (alias) > $HOME/.unsloth/studio#@@ -20,7 +19,7 @@# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0set -e# ── Why the installer lives in a function ──-# Under `curl ... | sh`, sh is the pipe READER. This file is ~150KB, so a top-level+# Under a piped web install, sh is the pipe READER. This file is ~150KB, so a top-level# `exit` left most of it unread, the write end failed, and curl tacked# "(56) Failure writing output to destination" onto our own error message. Wrapping# the body forces sh to parse to the closing brace first, so the pipe always drains@@ -595,6 +594,12 @@ _resolve_studio_destinations() {_STUDIO_HOME_REDIRECT=default}_resolve_studio_destinations+# The PATH we inherited, before anything below prepends to it. The shim setup at the end asks+# whether a NEW login shell will find _LOCAL_BIN, and by then this process has prepended it+# several times (uv bootstrap, venv), so testing $PATH there answers yes for a shell that would+# answer no and the profile entry never gets written. astral's installer used to write that line+# for us; the pinned path does not.+_UNSLOTH_LOGIN_PATH="$PATH"VENV_DIR="$STUDIO_HOME/unsloth_studio"_VENV_ROLLBACK_DIR=""_VENV_ROLLBACK_TARGET="$VENV_DIR"@@ -719,6 +724,11 @@ _cleanup_install_temporaries() {[ -n "${_UV_OVERRIDE_TMPDIR:-}" ] && rm -rf "$_UV_OVERRIDE_TMPDIR" 2>/dev/null || true[ -n "${_UV_INSTALL_NAME_TOOL_SHIM_DIR:-}" ] && rm -rf "$_UV_INSTALL_NAME_TOOL_SHIM_DIR" 2>/dev/null || true[ -n "${_UNSLOTH_TORCH_OVERRIDES:-}" ] && rm -f "$_UNSLOTH_TORCH_OVERRIDES" 2>/dev/null || true+ # The pinned uv path's own cleanup only runs when that function returns, so a Ctrl-C left+ # the unpacked archive behind plus a staging file inside a directory that is on PATH.+ [ -n "${_UIP_WORK:-}" ] && rm -rf "$_UIP_WORK" 2>/dev/null || true+ [ -n "${_UIP_STAGE:-}" ] && rm -f "$_UIP_STAGE" 2>/dev/null || true+ [ -n "${_UIP_STAGE2:-}" ] && rm -f "$_UIP_STAGE2" 2>/dev/null || true}_on_install_exit() {@@ -746,6 +756,9 @@ _on_install_signal() {_UV_OVERRIDE_TMPDIR=""_UV_INSTALL_NAME_TOOL_SHIM_DIR=""_UNSLOTH_TORCH_OVERRIDES=""+_UIP_WORK=""+_UIP_STAGE=""+_UIP_STAGE2=""trap _on_install_exit EXITtrap '_on_install_signal 129' HUPtrap '_on_install_signal 130' INT@@ -2048,7 +2061,7 @@ _maybe_reroute_strixhalo_to_2404() {echo ""substep "ROCm-on-WSL (GPU) needs Ubuntu 24.04; this distro is Ubuntu ${_rr_ver:-unknown}." "$C_WARN"substep "Found an existing $_rr_target distro -- continuing the GPU install there." "$C_OK"- # A --local checkout can't be replayed via curl|sh (the repo isn't in the target+ # A --local checkout can't be replayed by a piped web install (the repo isn't in the target# distro), so tell the user to re-run there rather than silently run a different install.if [ "$STUDIO_LOCAL_INSTALL" = true ]; thensubstep "This is a --local install; re-run it from $_rr_target instead:" "$C_WARN"@@ -2083,7 +2096,7 @@ _maybe_reroute_strixhalo_to_2404() {else_rr_cmd="curl -fsSL https://unsloth.ai/install.sh | sh"fi- # pipefail so a failed curl in `curl | sh` isn't masked by sh exiting 0 on empty+ # pipefail so a failed download in a piped web install isn't masked by sh exiting 0 on empty# input (which would wrongly report success and exit 0 the parent installer)._rr_rc=0wsl.exe -d "$_rr_target" -- bash -lc "$_rr_exports; $_rr_cmd" || _rr_rc=$?@@ -2407,6 +2420,213 @@ _uv_version_ok() { # uv command, floor (defaults to UV_MIN_VERSION)return 0}+# ── uv from a pinned release ──+# Same archive, destination and PATH treatment as astral's installer, but it fetches a+# data file with a pinned SHA-256 instead of a script it runs and deletes. Mirrors+# Install-UvFromRelease in install.ps1. Bumping the version means bumping every hash:+# curl -sL https://github.com/astral-sh/uv/releases/download/<ver>/<asset>.sha256+#+# Only the four mainstream targets are pinned. musl, armv7 and the rest fall through to+# the caller's existing path rather than risk a wrong triple.+UV_PINNED_VERSION="0.12.1"++# Echoes the glibc minor version (the N in 2.N), or nothing when this is not a glibc host or+# the version cannot be read. "not musl" is not the same as "a glibc new enough to run the GNU+# build": astral's installer checks a minimum and drops to its musl-static archive below it, so+# a host we cannot positively confirm has to reach the fallback rather than take a binary that+# will not exec.+_uv_glibc_minor() {+ _ugm_line=$( (ldd --version 2>/dev/null || true) | head -1 )+ case "$_ugm_line" in *[Mm]usl*) return 1 ;; esac+ _ugm_ver=$(printf '%s\n' "$_ugm_line" | awk '{print $NF}')+ # getconf is the fallback for an ldd that prints no version, and for hosts with no ldd.+ case "$_ugm_ver" in+ 2.[0-9]*) : ;;+ *) _ugm_ver=$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{print $NF}') ;;+ esac+ case "$_ugm_ver" in 2.[0-9]*) : ;; *) return 1 ;; esac+ _ugm_minor=${_ugm_ver#2.}+ _ugm_minor=${_ugm_minor%%.*}+ case "$_ugm_minor" in "" | *[!0-9]*) return 1 ;; esac+ echo "$_ugm_minor"+ return 0+}++# Prints "<asset> <sha256>" for this host, or nothing when the host is not pinned.+_uv_pinned_asset() {+ _upa_os=$(uname -s 2>/dev/null || echo unknown)+ _upa_arch=$(uname -m 2>/dev/null || echo unknown)+ case "$_upa_os" in+ Linux)+ # A 64-bit kernel under a 32-bit userland reports x86_64 from uname but cannot load+ # a 64-bit binary, so ask the userland, not the kernel.+ [ "$(getconf LONG_BIT 2>/dev/null || echo 0)" = "64" ] || return 1+ # Rejects musl, an unreadable libc, and a glibc below astral's floor for the triple.+ _upa_glibc=$(_uv_glibc_minor) || return 1+ case "$_upa_arch" in+ x86_64|amd64)+ [ "$_upa_glibc" -ge 17 ] 2>/dev/null || return 1+ echo "uv-x86_64-unknown-linux-gnu.tar.gz 90b2f223fb69d19db49e117da601f64978593417988530aa733d456141b4bcbb" ;;+ aarch64|arm64)+ [ "$_upa_glibc" -ge 28 ] 2>/dev/null || return 1+ echo "uv-aarch64-unknown-linux-gnu.tar.gz 769d373e146692c639b5fbaae33b331c297a32e03d30448772051902df52bbf4" ;;+ *) return 1 ;;+ esac+ ;;+ Darwin)+ # Under Rosetta 2 a translated shell reports x86_64 on an Apple Silicon Mac. astral+ # reads the same sysctl and ships the native build; matching it keeps the uv the user+ # ends up with identical to the one they had before.+ if [ "$_upa_arch" = "x86_64" ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null)" = "1" ]; then+ _upa_arch=arm64+ fi+ case "$_upa_arch" in+ x86_64)+ echo "uv-x86_64-apple-darwin.tar.gz 69d9f9a00337f25a50dcb13882052da08b8469bac11091c98c5694c3c6721467" ;;+ arm64|aarch64)+ echo "uv-aarch64-apple-darwin.tar.gz 77d2906988e8074fd43f2f329ec452ebbf9b0c257ba1c66451c71de70a6baf42" ;;+ *) return 1 ;;+ esac+ ;;+ *) return 1 ;;+ esac+ return 0+}++# Echoes the SHA-256 of "$1", or nothing when the host has no digest tool.+_uv_sha256() {+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$1" 2>/dev/null | awk '{print $1}'+ elif command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$1" 2>/dev/null | awk '{print $1}'+ 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.+_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+ fi+}++_uv_install_pinned() {+ _uip_spec=$(_uv_pinned_asset) || return 1+ [ -n "$_uip_spec" ] || return 1+ _uip_asset=${_uip_spec%% *}+ _uip_want=${_uip_spec##* }+ # Unverified is worth less than astral's own release flow, so decline instead.+ command -v tar >/dev/null 2>&1 || return 1+ if [ -z "$(_uv_sha256 /dev/null)" ]; then return 1; fi++ # astral's destination priority, so an existing uv is replaced in place and the+ # PATH lines below still find it.+ _uip_dest=""+ for _uip_candidate in "${UV_INSTALL_DIR:-}" "${UV_UNMANAGED_INSTALL:-}" "${XDG_BIN_HOME:-}"; do+ if [ -n "$_uip_candidate" ]; then _uip_dest="$_uip_candidate"; break; fi+ done+ if [ -z "$_uip_dest" ] && [ -n "${XDG_DATA_HOME:-}" ]; then _uip_dest="$XDG_DATA_HOME/../bin"; fi+ if [ -z "$_uip_dest" ]; then+ [ -n "${HOME:-}" ] || return 1+ _uip_dest="$HOME/.local/bin"+ fi++ # 2>/dev/null: this is a speculative attempt whose failure falls back to astral's+ # installer, so an unusable $TMPDIR must not print a line the user cannot act on.+ _uip_work=$(mktemp -d 2>/dev/null) || return 1+ _UIP_WORK="$_uip_work"+ _uip_rc=1+ # astral's mirrors and precedence; each serves the identical asset, so one pin holds. A+ # configured mirror is EXCLUSIVE, as it is for astral: a restricted network sets one because+ # the public hosts are unreachable, and download() has no timeout, so trying them first+ # would hang rather than fall through.+ if [ -n "${UV_DOWNLOAD_URL:-}" ]; then+ _uip_bases="${UV_DOWNLOAD_URL%/}"+ elif [ -n "${INSTALLER_DOWNLOAD_URL:-}" ]; then+ _uip_bases="${INSTALLER_DOWNLOAD_URL%/}"+ elif [ -n "${UV_INSTALLER_GHE_BASE_URL:-}" ]; then+ _uip_bases="${UV_INSTALLER_GHE_BASE_URL%/}/astral-sh/uv/releases/download/$UV_PINNED_VERSION"+ elif [ -n "${UV_INSTALLER_GITHUB_BASE_URL:-}" ]; then+ _uip_bases="${UV_INSTALLER_GITHUB_BASE_URL%/}/astral-sh/uv/releases/download/$UV_PINNED_VERSION"+ else+ _uip_bases="https://releases.astral.sh/github/uv/releases/download/$UV_PINNED_VERSION+https://github.com/astral-sh/uv/releases/download/$UV_PINNED_VERSION"+ fi+ for _uip_base in $_uip_bases; do+ # 2>/dev/null: curl -sS prints its own errors and these attempts are speculative, so an+ # unreachable mirror stays off the console when the install still succeeds.+ if ! download "$_uip_base/$_uip_asset" "$_uip_work/$_uip_asset" 2>/dev/null; then continue; fi+ _uip_got=$(_uv_sha256 "$_uip_work/$_uip_asset")+ if [ "$_uip_got" != "$_uip_want" ]; then+ # Not tauri_log: [TAURI:WARN] is a marker install.sh has never emitted, and the app+ # forwards unknown markers to its progress UI verbatim. Verbose only, since the next+ # mirror or the fallback still runs.+ if _is_verbose; then+ echo "uv archive digest mismatch from $_uip_base, trying the next source" >&2+ fi+ continue+ fi+ # The POSIX archives hold uv and uvx under a uv-<triple>/ directory.+ if ! tar -xzf "$_uip_work/$_uip_asset" -C "$_uip_work" 2>/dev/null; then continue; fi+ mkdir -p "$_uip_dest" 2>/dev/null || break+ _uip_placed=0+ # uv first, and either half failing aborts the placement: the two ship as a set, and a+ # pinned uvx beside the host's older uv is a pairing we never built or tested.+ # Stage both, then publish both: the renames sit next to each other so the pair is+ # replaced as one, and a failure anywhere before them leaves the destination untouched.+ _uip_ready=1+ for _uip_exe in uv uvx; do+ # `mv f d` moves f INTO d and reports success, and a searchable directory passes -x+ # too, so a directory called uv at the destination would look like a published+ # binary and skip the fallback. The installer already refuses one for its own shim.+ if [ -d "$_uip_dest/$_uip_exe" ]; then _uip_ready=0; break; fi+ _uip_src=$(find "$_uip_work" -type f -name "$_uip_exe" 2>/dev/null | head -1)+ if [ -z "$_uip_src" ] || [ ! -f "$_uip_src" ]; then _uip_ready=0; break; fi+ # cp onto a symlinked destination writes through it and would rewrite, say, the+ # Homebrew binary `~/.local/bin/uv` points at; rename replaces the link. mktemp, not+ # a fixed name, so two installers racing here cannot publish each other's file.+ _uip_stage=$(mktemp "$_uip_dest/.$_uip_exe.XXXXXX" 2>/dev/null) || { _uip_ready=0; break; }+ if [ "$_uip_exe" = "uv" ]; then _UIP_STAGE="$_uip_stage"; else _UIP_STAGE2="$_uip_stage"; fi+ if ! cp -f "$_uip_src" "$_uip_stage" 2>/dev/null; then _uip_ready=0; break; fi+ # 0755, not +x: the staging file carries the umask default and +x only adds execute+ # where read was allowed, so umask 077 would leave uv unusable for every other+ # account. astral ships these 0755.+ chmod 0755 "$_uip_stage" 2>/dev/null || true+ # Validate BEFORE publishing: the rename destroys the incumbent, and a missing loader+ # or a noexec mount would leave the host with neither. The staging file is on the+ # destination filesystem, so this answers noexec too.+ if [ "$_uip_exe" = "uv" ] && ! _uv_probe_exec "$_uip_stage"; then _uip_ready=0; break; fi+ done+ if [ "$_uip_ready" = "1" ] &&+ mv -f "$_UIP_STAGE" "$_uip_dest/uv" 2>/dev/null &&+ mv -f "$_UIP_STAGE2" "$_uip_dest/uvx" 2>/dev/null; then+ _uip_placed=1+ fi+ rm -f "$_UIP_STAGE" "$_UIP_STAGE2" 2>/dev/null || true+ _UIP_STAGE=""+ _UIP_STAGE2=""+ # The staged binary already answered --version above, before it replaced anything.+ if [ "$_uip_placed" = "1" ] && [ -x "$_uip_dest/uv" ]; then+ export PATH="$_uip_dest:$PATH"+ # Where uv landed, for the profile write below: UV_INSTALL_DIR and friends can put+ # it outside ~/.local/bin, and that directory has to reach a new shell too.+ _UNSLOTH_UV_BIN_DIR="$_uip_dest"+ _uip_rc=0+ fi+ break+ done+ rm -rf "$_uip_work"+ _UIP_WORK=""+ _UIP_STAGE=""+ _UIP_STAGE2=""+ # Nothing is unwound on the failure path on purpose: the fallback installs over whatever is+ # at the destination, and deleting there would take out a working uv the host already had.+ return "$_uip_rc"+}+if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv; then# Raising the floor pulled every 0.8.16-0.9.2 host into this block, and those# installs used to succeed without touching the network, so a download@@ -2429,13 +2649,21 @@ if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv; then# which an `if` cannot catch, so probe first: a minimal image with uv copied# in but no downloader must keep the install it had before the floor moved.if command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1; then- _uv_tmp=$(mktemp)- if download "https://astral.sh/uv/install.sh" "$_uv_tmp"; then- run_maybe_quiet sh "$_uv_tmp" </dev/null || _uv_refreshed=false+ # Pinned release first: a digest-checked data file scores far lower than+ # download-run-delete, which is the literal shape of a dropper.+ if _uv_install_pinned; then+ :else- _uv_refreshed=false+ # Unpinned hosts keep the path they have always had: a wrong triple+ # breaks the install outright, which costs more than the fallback's score.+ _uv_tmp=$(mktemp)+ if download "https://astral.sh/uv/install.sh" "$_uv_tmp"; then+ run_maybe_quiet sh "$_uv_tmp" </dev/null || _uv_refreshed=false+ else+ _uv_refreshed=false+ fi+ rm -f "$_uv_tmp"fi- rm -f "$_uv_tmp"else_uv_refreshed=falsefi@@ -2449,6 +2677,12 @@ if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv; then. "$HOME/.local/bin/env"fiexport PATH="$HOME/.local/bin:$PATH"+ # ...and put the pinned destination back in front. UV_INSTALL_DIR and friends can put uv+ # somewhere other than ~/.local/bin, and both the line above and astral's env file prepend+ # ~/.local/bin, so a stale uv there would shadow the 0.12.1 we just verified.+ if [ -n "${_UNSLOTH_UV_BIN_DIR:-}" ] && [ "$_UNSLOTH_UV_BIN_DIR" != "$HOME/.local/bin" ]; then+ export PATH="$_UNSLOTH_UV_BIN_DIR:$PATH"+ fifi# ── Create venv (migrate old layout if possible, otherwise fresh) ──@@ -2761,7 +2995,7 @@ TORCHAUDIO_CONSTRAINT="torchaudio>=2.4,<2.11.0"# ── Resolve repo root (for --local installs) ──_REPO_ROOT="$(cd "$(dirname "$0" 2>/dev/null || echo ".")" && pwd)"-# Whether the scripts next to install.sh may be trusted. A piped install (curl ... | sh)+# Whether the scripts next to install.sh may be trusted. A piped web install# has $0 = "sh", so _REPO_ROOT is just the caller's cwd and a file planted there would run.# Marker files cannot decide this (whoever can plant a helper can plant those), so require# the explicit --local intent AND a run from the file itself; else fetch the official copy.@@ -3965,7 +4199,7 @@ _maybe_bootstrap_rocm_wsl() {# Consent: the narrow guarded case is exactly the GPU setup the user ran the# installer for, so it proceeds AUTOMATICALLY by default (works with no TTY,- # e.g. `curl ... | sh`). Opt out via UNSLOTH_SKIP_ROCM_WSL_SETUP=1 (top of+ # e.g. a piped web install). Opt out via UNSLOTH_SKIP_ROCM_WSL_SETUP=1 (top of# function). The Tauri app drives its own consent UI, so under TAURI_MODE it# only runs when the app passes UNSLOTH_ROCM_WSL_AUTO=1; else surface and wait._rw_go=1@@ -5166,33 +5400,144 @@ fi# the shim path (the directory guard above already rejects a real directory).ln -sfn "$VENV_DIR/bin/unsloth" "$_shim_path"-case ":$PATH:" in- *":$_LOCAL_BIN:"*) ;; # already on PATH- *)+# Is $2 one of the colon-separated entries of $1? Field splitting also globs, so pathname+# expansion is off for the walk and restored afterwards: a directory holding *, ? or [ would+# otherwise match an unrelated entry and the persistence would be skipped.+_path_has_dir() {+ _phd_glob=on+ case $- in *f*) _phd_glob=off ;; esac+ set -f+ _phd_found=1+ _phd_old_ifs="$IFS"+ IFS=:+ for _phd_entry in $1; do+ if [ "$_phd_entry" = "$2" ]; then _phd_found=0; break; fi+ done+ IFS="$_phd_old_ifs"+ [ "$_phd_glob" = on ] && set +f+ return "$_phd_found"+}++# fish reads none of the POSIX rc files, so an `export` line is a no-op for a fish user: the+# next session resolves neither uv nor the shim. conf.d is fish's own drop-in directory and+# fish_add_path is idempotent by design. ~/.config, not XDG_CONFIG_HOME, because that is where+# astral's installer put its own fish file.+_persist_fish_path_dir() {+ _pfp_dir="$1"; _pfp_label="${2:-$1}"+ [ -n "${HOME:-}" ] || return 0+ _pfp_dir_conf="$HOME/.config/fish/conf.d"+ mkdir -p "$_pfp_dir_conf" 2>/dev/null || return 0+ _pfp_file="$_pfp_dir_conf/unsloth.fish"+ # Single-quoted: an unquoted path with a space is two arguments to fish_add_path and+ # neither exists. Inside fish single quotes only \\ and \' carry meaning.+ _pfp_quoted=$(printf '%s' "$_pfp_dir" | sed "s/\\\\/\\\\\\\\/g; s/'/\\\\'/g")+ # The exact line we would write, not any occurrence of the directory: /opt/uv-old must not+ # pass for /opt/uv, and fish reads none of the POSIX files that would otherwise cover it.+ if ! grep -v '^[[:space:]]*#' "$_pfp_file" 2>/dev/null | grep -qxF "fish_add_path '$_pfp_quoted'"; then+ echo "# Added by Unsloth installer" >> "$_pfp_file"+ echo "fish_add_path '$_pfp_quoted'" >> "$_pfp_file"+ step "path" "added $_pfp_label to PATH in $_pfp_file"+ fi+}++# A line that SETS PATH, as opposed to one that merely names the directory. The name boundary+# keeps PYTHONPATH and friends out; the three helpers are the common non-assignment spellings.+_PATH_LINE_RE='(^|[^[:alnum:]_])(PATH[[:space:]]*=|fish_add_path|pathmunge|path_helper)'++# Put a directory on the PATH of the NEXT shell, not just this process.+# $1 the directory $2 the rc-file literal (~/.local/bin keeps $HOME unexpanded, as it always+# has) $3 how to name it in the line we print $4 the grep that says it is already there+# $5 an explicit profile file, or empty to pick one the way this installer always has+_persist_login_path_dir() {+ _plp_dir="$1"; _plp_literal="$2"; _plp_label="$3"; _plp_pattern="$4"; _plp_file="${5:-}"+ [ -n "${HOME:-}" ] || return 0+ # fish reads none of the POSIX rc files, so an `export` line there is a no-op for a fish+ # user: the next session resolves neither uv nor the shim. conf.d is fish's own drop-in+ # directory and fish_add_path is idempotent by design.+ if [ -z "$_plp_file" ] && [ "$(basename "${SHELL:-}")" = "fish" ]; then+ _persist_fish_path_dir "$_plp_dir" "$_plp_label"+ return 0+ fi+ _SHELL_PROFILE="$_plp_file"+ if [ -n "$_SHELL_PROFILE" ]; then+ :+ elif [ -n "${ZSH_VERSION:-}" ] || [ "$(basename "${SHELL:-}")" = "zsh" ]; then+ _SHELL_PROFILE="${ZDOTDIR:-$HOME}/.zshrc"+ elif [ -f "$HOME/.bashrc" ]; then+ _SHELL_PROFILE="$HOME/.bashrc"+ elif [ -f "$HOME/.profile" ]; then+ _SHELL_PROFILE="$HOME/.profile"+ elif [ -w "$HOME" ]; then+ # A fresh account can have no rc file at all: astral's installer used to create one,+ # the pinned path does not. The append creates it, and every POSIX login shell reads+ # ~/.profile.+ _SHELL_PROFILE="$HOME/.profile"+ fi+ [ -n "$_SHELL_PROFILE" ] || return 0+ # Comments stripped first, then only lines that actually set PATH: a commented-out old export+ # is not an active entry, and neither is `UV_CACHE=/opt/uv` or `PYTHONPATH=/opt/uv`. The name+ # boundary is what keeps PYTHONPATH out. Taking any of them for a PATH entry leaves the next+ # shell with no uv at all.+ if ! grep -v '^[[:space:]]*#' "$_SHELL_PROFILE" 2>/dev/null \+ | grep -E "$_PATH_LINE_RE" | grep -qE "$_plp_pattern"; then+ echo '' >> "$_SHELL_PROFILE"+ echo '# Added by Unsloth installer' >> "$_SHELL_PROFILE"+ echo "export PATH=\"$_plp_literal:\$PATH\"" >> "$_SHELL_PROFILE"+ step "path" "added $_plp_label to PATH in $_SHELL_PROFILE"+ fi+}++if ! _path_has_dir "$_UNSLOTH_LOGIN_PATH" "$_LOCAL_BIN"; then # not on a new shell's PATHif [ "$_STUDIO_HOME_REDIRECT" = "env" ]; thenexport PATH="$_LOCAL_BIN:$PATH"step "path" "exported $_LOCAL_BIN for this session (no rc-file append in env-override mode)"else- _SHELL_PROFILE=""- if [ -n "${ZSH_VERSION:-}" ] || [ "$(basename "${SHELL:-}")" = "zsh" ]; then- _SHELL_PROFILE="$HOME/.zshrc"- elif [ -f "$HOME/.bashrc" ]; then- _SHELL_PROFILE="$HOME/.bashrc"- elif [ -f "$HOME/.profile" ]; then- _SHELL_PROFILE="$HOME/.profile"- fi- if [ -n "$_SHELL_PROFILE" ]; then- if ! grep -q '\.local/bin' "$_SHELL_PROFILE" 2>/dev/null; then- echo '' >> "$_SHELL_PROFILE"- echo '# Added by Unsloth installer' >> "$_SHELL_PROFILE"- echo 'export PATH="$HOME/.local/bin:$PATH"' >> "$_SHELL_PROFILE"- step "path" "added ~/.local/bin to PATH in $_SHELL_PROFILE"- fi- fi+ _persist_login_path_dir "$_LOCAL_BIN" '$HOME/.local/bin' "~/.local/bin" '\.local/bin'export PATH="$_LOCAL_BIN:$PATH"fi- ;;-esac+fi++# UV_INSTALL_DIR, UV_UNMANAGED_INSTALL, XDG_BIN_HOME and XDG_DATA_HOME all outrank ~/.local/bin,+# and astral's installer wrote a PATH line for whichever it picked, so replacing that installer+# means persisting its destination too. Both of astral's opt-outs are honoured. Not gated on the+# destination differing from ~/.local/bin: that IS the default, so gating there left every+# ordinary machine with the single-file write.+if [ -n "${_UNSLOTH_UV_BIN_DIR:-}" ] \+ && [ -z "${UV_NO_MODIFY_PATH:-}" ] && [ -z "${UV_UNMANAGED_INSTALL:-}" ] \+ && [ "$_STUDIO_HOME_REDIRECT" != "env" ]; then+ if ! _path_has_dir "$_UNSLOTH_LOGIN_PATH" "$_UNSLOTH_UV_BIN_DIR"; then+ # The rc line is double-quoted, so a path holding $, ` or " would be expanded or+ # terminated by the shell that reads it. The ~/.local/bin literal is exempt: its+ # $HOME is meant to stay unexpanded.+ _uv_rc_literal=$(printf '%s' "$_UNSLOTH_UV_BIN_DIR" | sed 's/[\\"$`]/\\&/g')+ # Anchored on both sides, so /opt/uv is not satisfied by /opt/uv-old and the match has+ # to be a whole PATH entry rather than any occurrence of the text.+ _uv_grep_esc=$(printf '%s' "$_UNSLOTH_UV_BIN_DIR" | sed 's/[].[\\()*+?{}|^$\/]/\\&/g')+ # ...and the $HOME-relative spelling as well, because the shim block above writes+ # `export PATH="$HOME/.local/bin:$PATH"` unexpanded. Without this the default install+ # would add a second line for the same directory in the same file.+ case "$_UNSLOTH_UV_BIN_DIR" in+ "$HOME"/*)+ _uv_grep_esc="$_uv_grep_esc|\\\$HOME$(printf '%s' "${_UNSLOTH_UV_BIN_DIR#$HOME}" | sed 's/[].[\\()*+?{}|^$\/]/\\&/g')"+ ;;+ esac+ _uv_pattern="(^|[^[:alnum:]_.~/-])($_uv_grep_esc)([^[:alnum:]_.~/-]|\$)"+ # Every startup file astral's installer wired, because it is the installer we replaced.+ # Writing only the file for the shell that happens to be running leaves a bash user whose+ # .bash_profile does not source .bashrc, or anyone who later switches shells, without uv.+ for _uv_prof in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.bash_profile" \+ "$HOME/.bash_login" "${ZDOTDIR:-$HOME}/.zshrc" "${ZDOTDIR:-$HOME}/.zshenv"; do+ # ~/.profile is created when absent, as astral does; the rest are only touched when+ # the user already has them.+ if [ "$_uv_prof" = "$HOME/.profile" ] || [ -f "$_uv_prof" ]; then+ _persist_login_path_dir "$_UNSLOTH_UV_BIN_DIR" "$_uv_rc_literal" \+ "$_UNSLOTH_UV_BIN_DIR" "$_uv_pattern" "$_uv_prof"+ fi+ done+ _persist_fish_path_dir "$_UNSLOTH_UV_BIN_DIR"+ fi+fi+# end of the PATH persistence block# Non-Tauri installs keep shortcuts even if setup reports failure.# create_studio_shortcuts gates persistent menu shortcuts on env-mode;@@ -5276,7 +5621,7 @@ if [ "$_SKIP_AUTOSTART" != true ] && [ -t 1 ]; thencase "${_reply:-y}" in[Yy]*|"")step "launch" "starting Unsloth Studio..."- # Detach stdin from the `curl | sh` pipe: as a foreground server the+ # Detach stdin from the piped web install's pipe: as a foreground server the# studio would otherwise drain the rest of this piped script, leaving# the shell to die parsing the now-truncated tail (`unexpected fi`).# trap '' INT: wait for studio's shutdown instead of racing the prompt.diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1index a6c87b006b2..57d5d7328c9 100644--- a/scripts/uninstall.ps1+++ b/scripts/uninstall.ps1@@ -4,13 +4,13 @@# Unsloth Studio uninstaller for Windows PowerShell. Run -Help for details.# Custom roots (UNSLOTH_STUDIO_HOME / STUDIO_HOME) come from share\studio.conf.#-# Usage: irm https://raw.githubusercontent.com/unslothai/unsloth/main/scripts/uninstall.ps1 | iex-# Local: Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass; .\scripts\uninstall.ps1+# Usage: run -Help. The web one-liner is in that help text and is not repeated here, since+# AMSI scans this file in full before any of it runs and nothing reads the header.function Uninstall-UnslothStudio {$ErrorActionPreference = "Continue"- # Reset at entry: `irm ... | iex` defines this function in the caller's session, so a+ # Reset at entry: a piped web run defines this function in the caller's session, so a# second run in the same window would otherwise inherit the first run's flags.$script:RemoveFailed = $false$script:StudioDbRemoved = $falsediff --git a/scripts/virustotal_scan.py b/scripts/virustotal_scan.pyindex 57a86107f15..af302c6a03a 100644--- a/scripts/virustotal_scan.py+++ b/scripts/virustotal_scan.py@@ -198,6 +198,43 @@ def _md_text(text: str) -> str:SUMMARY_HEADING = "### VirusTotal release asset scan"+def submission_packet_lines(detected: Sequence[FileReport]) -> list[str]:+ """Pre-fill a false-positive submission for every flagged asset.++ The build job assembles one too, but only for the Windows `-setup.exe`, so the detection+ that actually arrived -- `Trojan:Script/Wacatac.B!ml` on the 0.1.701-beta Linux AppImage --+ produced nothing to submit. Anything flagged here gets a packet, whatever built it.++ Engine names are not repeated: third-party text, already escaped under "Flagging engines".+ """+ lines = [+ "",+ "#### False-positive submission packet",+ "",+ "Submit each flagged asset before announcing this release.",+ "",+ "- Microsoft: <https://www.microsoft.com/en-us/wdsi/filesubmission>, "+ "**Software developer** -> **Incorrectly detected as malware/malicious** "+ "(50 MB cap; use <https://security.microsoft.com/reportsubmission> for larger bundles).",+ "- Any other flagging vendor: use that vendor's own false-positive form. "+ "Microsoft clearance does not carry across engines.",+ "",+ "| Asset | SHA-256 | Size |",+ "| --- | --- | ---: |",+ ]+ for report in detected:+ lines.append(+ f"| `{_md_code(report.name)}` | `{_md_code(report.sha256 or 'n/a')}` | "+ f"{report.size} bytes |"+ )+ lines += [+ "",+ "> Clearance is per hash. It fixes the release you submit and nothing after it, so this",+ "> is a complement to signing, not a substitute.",+ ]+ return lines++def render_markdown(reports: Sequence[FileReport], threshold: int) -> str:"""Render the job-summary table. Kept pure so it is unit testable."""lines = [@@ -231,6 +268,13 @@ def render_markdown(reports: Sequence[FileReport], threshold: int) -> str:for report in notes:lines.append(f"- `{_md_code(report.name)}`: {_md_text(report.note)}")+ # Keyed on the counts, not the engine list: stats and results are separate fields of the+ # same response, so an asset can carry a flagged count with no readable results map. The+ # table would report it and the packet would skip it, which is the one asset that needs one.+ flagged = [report for report in reports if report.stats is not None and report.stats.flagged]+ if flagged:+ lines += submission_packet_lines(flagged)+lines += ["", "<details><summary>SHA-256</summary>", ""]for report in reports:lines.append(f"- `{_md_code(report.name)}`: `{_md_code(report.sha256 or 'n/a')}`")diff --git a/studio/setup.ps1 b/studio/setup.ps1index f5609816a8e..7604f253a97 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -39,9 +39,10 @@ $PackageDir = Split-Path -Parent $ScriptDir# The 'Get-ExecutionPolicy' command was found in the module# 'Microsoft.PowerShell.Security', but the module could not be loaded.#-# astral's uv installer calls Get-ExecutionPolicy, and the run ends there with-# exit 1 and no further output. The try/catch around that call does not help,-# because Invoke-Expression runs the installer in this process.+# Any Security cmdlet reached during the run ends it there with exit 1 and no+# further output -- Get-AuthenticodeSignature, which verifies the VC++ runtime+# download, sits on this path. A try/catch does not help, because the failure is+# module loading in this process rather than an error the caller can catch.## Prepended, not appended: the problem is precedence, not absence. Clearing the# variable so 5.1 rebuilds its default does not help either, because the@@ -4336,6 +4337,217 @@ function Assert-VenvActivated {Exit-SetupFailure "Activating $VenvDir did not put its interpreter on PATH (python resolves to $_where)"}+# Mirrors install.ps1's Install-UvFromRelease: same archive, destination priority and user-PATH+# prepend as astral's installer, but it fetches a data file with a pinned SHA-256 instead of+# running remote script text in-process, which is what AMSI scores hardest. Bumping the version+# means bumping all 3 hashes:+# curl -sL https://github.com/astral-sh/uv/releases/download/<ver>/uv-<arch>-pc-windows-msvc.zip.sha256+$UvPinnedVersion = "0.12.1"+$UvPinnedAssets = @{+ "x86_64" = @{ Asset = "uv-x86_64-pc-windows-msvc.zip"; Sha256 = "8FCB0CB46E1229065E344758980924E569BEF5882EF45F46FADA8FB24E06B74A" }+ "arm64" = @{ Asset = "uv-aarch64-pc-windows-msvc.zip"; Sha256 = "9BC7C18E616230FA2DC6FB24BC3AFDE18A95C2B5C9433DE747E9502C66041568" }+ "x86" = @{ Asset = "uv-i686-pc-windows-msvc.zip"; Sha256 = "9B51C33D307A8AB9E9DFD88D4AE1491761F63DE0BFFA3CEC96BEC536491C9B97" }+}++# Not Get-HostMachineArch: it answers arm64/other for the VC++ and prebuilt probes, and "other"+# cannot pick between the x86_64 and i686 archives. install.ps1's resolution order.+function Get-UvHostArch {+ $osArch = ""+ try { $osArch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() } catch { $osArch = "" }+ $signals = @([string]$env:PROCESSOR_ARCHITEW6432, [string]$env:PROCESSOR_ARCHITECTURE, $osArch)+ foreach ($s in $signals) {+ if ($s.ToLowerInvariant() -eq "arm64") { return "arm64" }+ }+ foreach ($s in $signals) {+ if ([string]::IsNullOrWhiteSpace($s)) { continue }+ switch ($s.ToLowerInvariant()) {+ "amd64" { return "x86_64" }+ "x64" { return "x86_64" }+ "x86" { return "x86" }+ }+ }+ 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.+ param([string]$Path)+ if (-not $Path -or -not (Test-Path -LiteralPath $Path)) { return "failed" }+ $outFile = [System.IO.Path]::GetTempFileName()+ $errFile = [System.IO.Path]::GetTempFileName()+ try {+ $proc = Start-Process -FilePath $Path -ArgumentList "--version" -NoNewWindow -PassThru `+ -RedirectStandardOutput $outFile -RedirectStandardError $errFile -ErrorAction Stop+ if (-not $proc.WaitForExit(20000)) {+ try { $proc.Kill() } catch {}+ Write-Output "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.+ try { $proc.WaitForExit() } catch {}+ $code = $null+ try { $code = $proc.ExitCode } catch {}+ if ($null -eq $code -or "$code" -eq "") {+ Write-Output "uv --version gave no exit code; installing it unprobed."+ return "unknown"+ }+ 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"+ return "failed"+ } catch {+ Write-Output "could not probe uv: $($_.Exception.Message); installing it unprobed."+ return "unknown"+ } finally {+ Remove-Item -LiteralPath $outFile -Force -ErrorAction SilentlyContinue+ Remove-Item -LiteralPath $errFile -Force -ErrorAction SilentlyContinue+ }+}++function Install-UvFromPinnedRelease {+ $arch = Get-UvHostArch+ if (-not $UvPinnedAssets.ContainsKey($arch)) {+ Write-Output "No uv build is published for this architecture ($arch)."+ return $false+ }+ $asset = $UvPinnedAssets[$arch].Asset+ $wanted = $UvPinnedAssets[$arch].Sha256++ # astral's destination priority, so an existing uv is replaced in place and the Get-Command+ # probe after Refresh-Environment still finds it.+ $destDir = $null+ foreach ($candidate in @($env:UV_INSTALL_DIR, $env:UV_UNMANAGED_INSTALL, $env:XDG_BIN_HOME)) {+ if ($candidate) { $destDir = $candidate; break }+ }+ if (-not $destDir -and $env:XDG_DATA_HOME) { $destDir = Join-Path $env:XDG_DATA_HOME "../bin" }+ if (-not $destDir) {+ $userHome = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME }+ if (-not $userHome) {+ Write-Output "Could not determine a home directory to install uv into."+ return $false+ }+ $destDir = Join-Path $userHome ".local\bin"+ }++ # astral's sources in astral's order, each exclusive when set. UV_DOWNLOAD_URL (and its older+ # alias INSTALLER_DOWNLOAD_URL) outrank the mirror variables there, and a host that sets one+ # usually cannot reach the public endpoints at all, so trying those first would stall. The pin+ # still applies: a source serving a different build fails the digest and the caller falls back.+ $uvBase = if ($env:UV_DOWNLOAD_URL) {+ @("$($env:UV_DOWNLOAD_URL.TrimEnd('/'))")+ } elseif ($env:INSTALLER_DOWNLOAD_URL) {+ @("$($env:INSTALLER_DOWNLOAD_URL.TrimEnd('/'))")+ } elseif ($env:UV_INSTALLER_GHE_BASE_URL) {+ @("$($env:UV_INSTALLER_GHE_BASE_URL.TrimEnd('/'))/astral-sh/uv/releases/download/$UvPinnedVersion")+ } elseif ($env:UV_INSTALLER_GITHUB_BASE_URL) {+ @("$($env:UV_INSTALLER_GITHUB_BASE_URL.TrimEnd('/'))/astral-sh/uv/releases/download/$UvPinnedVersion")+ } else {+ @("https://releases.astral.sh/github/uv/releases/download/$UvPinnedVersion",+ "https://github.com/astral-sh/uv/releases/download/$UvPinnedVersion")+ }++ $work = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-uv-" + [guid]::NewGuid().ToString('N').Substring(0, 8))+ $zip = Join-Path $work $asset+ try {+ [System.IO.Directory]::CreateDirectory($work) | Out-Null+ # Digest per mirror, as install.ps1 does: a proxy answering 200 with its own body is a+ # successful download by every measure Invoke-WebRequest has.+ $downloaded = $false+ foreach ($base in $uvBase) {+ Write-Output "downloading uv $UvPinnedVersion ($arch) from $base..."+ try {+ Invoke-WebRequest -UseBasicParsing -OutFile $zip -Uri "$base/$asset"+ } catch {+ Write-Output "uv download failed: $($_.Exception.Message)"+ continue+ }+ $actual = ""+ try { $actual = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash } catch {}+ if ($actual -eq $wanted) {+ $downloaded = $true+ break+ }+ Write-Output "uv download failed checksum verification -- discarding it."+ Write-Output "expected $wanted, got $actual"+ Remove-Item -LiteralPath $zip -Force -ErrorAction SilentlyContinue+ }+ if (-not $downloaded) { return $false }++ # The Windows archives are flat: uv.exe, uvx.exe, uvw.exe at the root.+ Expand-Archive -LiteralPath $zip -DestinationPath $work -Force+ [System.IO.Directory]::CreateDirectory($destDir) | Out-Null+ $stagedUv = Join-Path $work "uv.exe"+ if (-not (Test-Path -LiteralPath $stagedUv)) {+ Write-Output "uv.exe was not present in $asset."+ return $false+ }+ # Run it where it landed, before the destination is touched: a host can have a working+ # older uv while a policy refuses this one, and copying first leaves it with neither.+ if ((Get-SetupUvExecutableVerdict -Path $stagedUv) -eq "failed") {+ Write-Output "the downloaded uv $UvPinnedVersion could not run on this machine."+ return $false+ }++ # uvw.exe is the windowless launcher and has no console to answer a probe on, so the+ # staged uv.exe above stands for the set: it came from the same verified archive.+ # Copy-Item under Stop so a locked or ACL-denied destination fails the install rather+ # than leaving half a set behind quietly.+ $haveUv = $true+ foreach ($exe in @("uv.exe", "uvx.exe", "uvw.exe")) {+ $src = Join-Path $work $exe+ if (-not (Test-Path -LiteralPath $src)) { continue }+ $dst = Join-Path $destDir $exe+ try {+ Copy-Item -LiteralPath $src -Destination $dst -Force -ErrorAction Stop+ } catch {+ $haveUv = $false+ break+ }+ if ($exe -eq "uv.exe") {+ # Invoke-SetupCommand sets ErrorActionPreference to Continue, so compare+ # against the archive we verified: a stale uv.exe must not pass for ours.+ $copied = $false+ try {+ $copied = (Test-Path -LiteralPath $dst) -and+ (Get-FileHash -LiteralPath $dst -Algorithm SHA256).Hash -eq+ (Get-FileHash -LiteralPath $src -Algorithm SHA256).Hash+ } catch { $copied = $false }+ if (-not $copied) { $haveUv = $false; break }+ }+ }+ if (-not $haveUv) {+ Write-Output "uv.exe was not present in $asset."+ return $false+ }+ } finally {+ Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue+ }++ # astral's PATH treatment and opt-outs: an unmanaged install forces no-modify-path there, so+ # it must here too. The user-PATH prepend is what survives the Refresh-Environment below.+ if (-not $env:UV_NO_MODIFY_PATH -and -not $env:UV_UNMANAGED_INSTALL) {+ Add-ToUserPath -Directory $destDir -Position Prepend | Out-Null+ }+ $env:PATH = "$destDir;$env:PATH"+ # Recorded on the script scope as well as returned: the caller runs this through+ # Invoke-SetupCommand, which hands back [int]$LASTEXITCODE rather than the pipeline value,+ # so the return alone cannot tell the fallback whether to run.+ $script:UvPinnedInstalled = $true+ return $true+}+$ActivateScript = Join-Path $VenvDir "Scripts\Activate.ps1". $ActivateScriptAssert-VenvActivated -VenvDir $VenvDir@@ -4347,7 +4559,18 @@ if (Get-Command uv -ErrorAction SilentlyContinue) {} else {substep "installing uv package manager..."try {- Invoke-SetupCommand { Invoke-Expression (Invoke-RestMethod -Uri "https://astral.sh/uv/install.ps1") } | Out-Null+ $script:UvPinnedInstalled = $false+ Invoke-SetupCommand { Install-UvFromPinnedRelease } | Out-Null+ # The merge base ran astral's installer here, so a failed pinned install needs somewhere+ # to go: with no fallback the setup drops to pip for torch, bitsandbytes and Triton, which+ # is a different resolver rather than a different download. winget, not the remote script,+ # which is the shape this branch removes and is what install.ps1 already tries first.+ if (-not $script:UvPinnedInstalled -and (Get-Command winget -ErrorAction SilentlyContinue)) {+ Invoke-SetupCommand {+ winget install --id astral-sh.uv --source winget --accept-source-agreements `+ --accept-package-agreements --silent+ } | Out-Null+ }Refresh-Environment# Re-activate venv since Refresh-Environment rebuilds PATH from# registry and drops the venv's Scripts directorydiff --git a/studio/setup.sh b/studio/setup.shindex fde43767916..5f3271c595a 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -1477,17 +1477,287 @@ _setup_http_get_timed() {fi}+# ── uv from a pinned release ──+# Same archive and destination as astral's installer, but it fetches a data file with a+# pinned SHA-256 instead of piping remote script text into a shell. Mirrors install.sh.+# Bumping the version means bumping every hash:+# curl -sL https://github.com/astral-sh/uv/releases/download/<ver>/<asset>.sha256+#+# Only the four mainstream targets are pinned; the rest fall through to the existing path+# rather than risk a binary for the wrong triple.+_SETUP_UV_PINNED_VERSION="0.12.1"++# Mirrors _uv_glibc_minor in install.sh: "not musl" is not the same as "a glibc new enough to+# run the GNU build", and astral drops to its musl-static archive below its floor.+_setup_uv_glibc_minor() {+ _sugm_line=$( (ldd --version 2>/dev/null || true) | head -1 )+ case "$_sugm_line" in *[Mm]usl*) return 1 ;; esac+ _sugm_ver=$(printf '%s\n' "$_sugm_line" | awk '{print $NF}')+ case "$_sugm_ver" in+ 2.[0-9]*) : ;;+ *) _sugm_ver=$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{print $NF}') ;;+ esac+ case "$_sugm_ver" in 2.[0-9]*) : ;; *) return 1 ;; esac+ _sugm_minor=${_sugm_ver#2.}+ _sugm_minor=${_sugm_minor%%.*}+ case "$_sugm_minor" in "" | *[!0-9]*) return 1 ;; esac+ echo "$_sugm_minor"+ return 0+}++_setup_uv_pinned_asset() {+ _supa_os=$(uname -s 2>/dev/null || echo unknown)+ _supa_arch=$(uname -m 2>/dev/null || echo unknown)+ case "$_supa_os" in+ Linux)+ # A 32-bit userland on a 64-bit kernel still reports x86_64 from uname.+ [ "$(getconf LONG_BIT 2>/dev/null || echo 0)" = "64" ] || return 1+ _supa_glibc=$(_setup_uv_glibc_minor) || return 1+ case "$_supa_arch" in+ x86_64|amd64)+ [ "$_supa_glibc" -ge 17 ] 2>/dev/null || return 1+ echo "uv-x86_64-unknown-linux-gnu.tar.gz 90b2f223fb69d19db49e117da601f64978593417988530aa733d456141b4bcbb" ;;+ aarch64|arm64)+ [ "$_supa_glibc" -ge 28 ] 2>/dev/null || return 1+ echo "uv-aarch64-unknown-linux-gnu.tar.gz 769d373e146692c639b5fbaae33b331c297a32e03d30448772051902df52bbf4" ;;+ *) return 1 ;;+ esac+ ;;+ Darwin)+ # Rosetta 2 reports x86_64 from a translated shell; astral reads the same sysctl.+ if [ "$_supa_arch" = "x86_64" ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null)" = "1" ]; then+ _supa_arch=arm64+ fi+ case "$_supa_arch" in+ x86_64)+ echo "uv-x86_64-apple-darwin.tar.gz 69d9f9a00337f25a50dcb13882052da08b8469bac11091c98c5694c3c6721467" ;;+ arm64|aarch64)+ echo "uv-aarch64-apple-darwin.tar.gz 77d2906988e8074fd43f2f329ec452ebbf9b0c257ba1c66451c71de70a6baf42" ;;+ *) return 1 ;;+ esac+ ;;+ *) return 1 ;;+ esac+ return 0+}++_setup_uv_sha256() {+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$1" 2>/dev/null | awk '{print $1}'+ elif command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$1" 2>/dev/null | awk '{print $1}'+ 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+ else+ "$1" --version >/dev/null 2>&1 </dev/null+ fi+}++# The function's own cleanup only runs when it returns, so an interrupt left the unpacked+# archive behind plus a staging file inside a directory on PATH. No trap is active here (the+# gitignore EXIT trap is cleared well above), so the pinned install owns these four for its+# duration and hands them back on the way out.+_setup_uv_cleanup_temporaries() {+ [ -n "${_SIUP_WORK:-}" ] && rm -rf "$_SIUP_WORK" 2>/dev/null || true+ [ -n "${_SIUP_STAGE:-}" ] && rm -f "$_SIUP_STAGE" 2>/dev/null || true+ [ -n "${_SIUP_STAGE2:-}" ] && rm -f "$_SIUP_STAGE2" 2>/dev/null || true+}++_setup_uv_on_signal() {+ trap - EXIT HUP INT TERM+ _setup_uv_cleanup_temporaries+ exit "$1"+}++# The PATH a new shell inherits, captured before the uv destination can be prepended to it.+_SETUP_LOGIN_PATH="$PATH"+_SIUP_WORK=""+_SIUP_STAGE=""+_SIUP_STAGE2=""++_setup_install_uv_pinned() {+ _siup_spec=$(_setup_uv_pinned_asset) || return 1+ [ -n "$_siup_spec" ] || return 1+ _siup_asset=${_siup_spec%% *}+ _siup_want=${_siup_spec##* }+ command -v tar >/dev/null 2>&1 || return 1+ [ -n "$(_setup_uv_sha256 /dev/null)" ] || return 1+ [ -n "${HOME:-}" ] || return 1++ # astral's full destination priority, including the XDG_DATA_HOME tier that sits between+ # XDG_BIN_HOME and the home default. Dropping it would leave uv under ~/.local/bin on a+ # host that configured an XDG location, where no later shell looks for it.+ _siup_dest="${UV_INSTALL_DIR:-${UV_UNMANAGED_INSTALL:-${XDG_BIN_HOME:-}}}"+ if [ -z "$_siup_dest" ] && [ -n "${XDG_DATA_HOME:-}" ]; then _siup_dest="$XDG_DATA_HOME/../bin"; fi+ [ -n "$_siup_dest" ] || _siup_dest="$HOME/.local/bin"+ # 2>/dev/null, as install.sh does: a speculative attempt whose failure falls back.+ _siup_work=$(mktemp -d 2>/dev/null) || return 1+ _SIUP_WORK="$_siup_work"+ trap _setup_uv_cleanup_temporaries EXIT+ trap '_setup_uv_on_signal 129' HUP+ trap '_setup_uv_on_signal 130' INT+ trap '_setup_uv_on_signal 143' TERM+ _siup_rc=1+ # A configured mirror is EXCLUSIVE, matching astral's installer and the PowerShell side: a+ # restricted network sets one because the public hosts are unreachable, so trying those first+ # would stall instead of falling through.+ if [ -n "${UV_DOWNLOAD_URL:-}" ]; then+ _siup_bases="${UV_DOWNLOAD_URL%/}"+ elif [ -n "${INSTALLER_DOWNLOAD_URL:-}" ]; then+ _siup_bases="${INSTALLER_DOWNLOAD_URL%/}"+ elif [ -n "${UV_INSTALLER_GHE_BASE_URL:-}" ]; then+ _siup_bases="${UV_INSTALLER_GHE_BASE_URL%/}/astral-sh/uv/releases/download/$_SETUP_UV_PINNED_VERSION"+ elif [ -n "${UV_INSTALLER_GITHUB_BASE_URL:-}" ]; then+ _siup_bases="${UV_INSTALLER_GITHUB_BASE_URL%/}/astral-sh/uv/releases/download/$_SETUP_UV_PINNED_VERSION"+ else+ _siup_bases="https://releases.astral.sh/github/uv/releases/download/$_SETUP_UV_PINNED_VERSION+https://github.com/astral-sh/uv/releases/download/$_SETUP_UV_PINNED_VERSION"+ fi+ for _siup_base in $_siup_bases; do+ _setup_http_get "$_siup_base/$_siup_asset" > "$_siup_work/$_siup_asset" 2>/dev/null || continue+ [ -s "$_siup_work/$_siup_asset" ] || continue+ [ "$(_setup_uv_sha256 "$_siup_work/$_siup_asset")" = "$_siup_want" ] || continue+ tar -xzf "$_siup_work/$_siup_asset" -C "$_siup_work" 2>/dev/null || continue+ mkdir -p "$_siup_dest" 2>/dev/null || break+ # Stage both, then publish both, as install.sh does: the renames sit next to each+ # other so the pair is replaced as one.+ _siup_ready=1+ for _siup_exe in uv uvx; do+ # `mv f d` moves f INTO d and reports success, and a searchable directory passes -x+ # too, so a directory called uv at the destination would look like a published+ # binary and skip the fallback. The installer already refuses one for its own shim.+ if [ -d "$_siup_dest/$_siup_exe" ]; then _siup_ready=0; break; fi+ _siup_src=$(find "$_siup_work" -type f -name "$_siup_exe" 2>/dev/null | head -1)+ if [ -z "$_siup_src" ]; then _siup_ready=0; break; fi+ # cp writes through a symlinked destination, and a per-process staging name keeps+ # two racing installers from publishing each other's half-written file.+ _siup_stage=$(mktemp "$_siup_dest/.$_siup_exe.XXXXXX" 2>/dev/null) || { _siup_ready=0; break; }+ if [ "$_siup_exe" = "uv" ]; then _SIUP_STAGE="$_siup_stage"; else _SIUP_STAGE2="$_siup_stage"; fi+ if ! cp -f "$_siup_src" "$_siup_stage" 2>/dev/null; then _siup_ready=0; break; fi+ # 0755, not +x: the staging file carries the umask default and +x only adds execute+ # where read was allowed, so umask 077 would leave uv unusable for every other+ # account. astral ships these 0755.+ chmod 0755 "$_siup_stage" 2>/dev/null || true+ # Validate before publishing: the rename destroys the incumbent, so a binary that+ # cannot run here must never replace one that could.+ if [ "$_siup_exe" = "uv" ] && ! _setup_uv_probe_exec "$_siup_stage"; then _siup_ready=0; break; fi+ done+ if [ "$_siup_ready" = "1" ] &&+ mv -f "$_SIUP_STAGE" "$_siup_dest/uv" 2>/dev/null &&+ mv -f "$_SIUP_STAGE2" "$_siup_dest/uvx" 2>/dev/null; then+ _siup_rc=0+ fi+ rm -f "$_SIUP_STAGE" "$_SIUP_STAGE2" 2>/dev/null || true+ _SIUP_STAGE=""+ _SIUP_STAGE2=""+ break+ done+ rm -rf "$_siup_work"+ _SIUP_WORK=""+ _SIUP_STAGE=""+ _SIUP_STAGE2=""+ trap - EXIT HUP INT TERM+ # The staged binary already answered --version above, before it replaced anything.+ [ -x "$_siup_dest/uv" ] || _siup_rc=1+ if [ "$_siup_rc" = "0" ]; then+ export PATH="$_siup_dest:$PATH"+ _setup_persist_uv_path "$_siup_dest"+ fi+ return "$_siup_rc"+}++# astral's installer wrote a profile line for whichever destination it chose. This replaces that+# installer, so setup.sh run directly (local or Colab) has to do the same or the export above+# dies with this shell and every later run reinstalls uv. Both of astral's opt-outs apply, and+# fish is handled on its own terms since it reads none of the POSIX rc files.+# Is $2 one of the colon-separated entries of $1? Field splitting also globs, so pathname+# expansion is off for the walk and restored afterwards.+_setup_path_has_dir() {+ _sphd_glob=on+ case $- in *f*) _sphd_glob=off ;; esac+ set -f+ _sphd_found=1+ _sphd_old_ifs="$IFS"+ IFS=:+ for _sphd_entry in $1; do+ if [ "$_sphd_entry" = "$2" ]; then _sphd_found=0; break; fi+ done+ IFS="$_sphd_old_ifs"+ [ "$_sphd_glob" = on ] && set +f+ return "$_sphd_found"+}++_setup_persist_uv_path() {+ _supp_dir="$1"+ [ -n "$_supp_dir" ] || return 0+ [ -n "${HOME:-}" ] || return 0+ [ -z "${UV_NO_MODIFY_PATH:-}" ] || return 0+ [ -z "${UV_UNMANAGED_INSTALL:-}" ] || return 0+ # The PATH a new shell inherits, not the one this process has already prepended to, and+ # compared entry by entry: a directory holding *, ? or [ is a glob inside a case pattern.+ _setup_path_has_dir "${_SETUP_LOGIN_PATH:-$PATH}" "$_supp_dir" && return 0+ # ~/.config, not XDG_CONFIG_HOME, because that is where astral's installer put its own fish+ # file, and it is written regardless of the current shell for the same reason.+ _supp_fish_dir="$HOME/.config/fish/conf.d"+ if mkdir -p "$_supp_fish_dir" 2>/dev/null; then+ _supp_fish="$_supp_fish_dir/unsloth.fish"+ # Single-quoted: an unquoted path with a space is two arguments to fish_add_path.+ _supp_quoted=$(printf '%s' "$_supp_dir" | sed "s/\\\\/\\\\\\\\/g; s/'/\\\\'/g")+ # The exact line, not any occurrence: /opt/uv-old must not pass for /opt/uv.+ if ! grep -v '^[[:space:]]*#' "$_supp_fish" 2>/dev/null | grep -qxF "fish_add_path '$_supp_quoted'"; then+ echo "# Added by Unsloth setup" >> "$_supp_fish"+ echo "fish_add_path '$_supp_quoted'" >> "$_supp_fish"+ fi+ fi+ # An entry has to be active, whole and on a line that SETS PATH: a commented-out export,+ # /opt/uv-old when we want /opt/uv, and PYTHONPATH=/opt/uv are none of them, and taking any+ # for an entry leaves the next shell unable to resolve uv.+ _supp_path_line='(^|[^[:alnum:]_])(PATH[[:space:]]*=|fish_add_path|pathmunge|path_helper)'+ _supp_grep=$(printf '%s' "$_supp_dir" | sed 's/[].[\\()*+?{}|^$\/]/\\&/g')+ # Escaped: the line is double-quoted, so a path holding $, ` or " would be expanded or+ # terminated by the shell that reads it.+ _supp_literal=$(printf '%s' "$_supp_dir" | sed 's/[\\"$`]/\\&/g')+ # Every startup file astral's installer wired, because it is the installer this replaced:+ # ~/.profile always, each bash file that exists, and zsh under ZDOTDIR. Writing only the+ # file for the shell that happens to be running would leave a bash user whose .bash_profile+ # does not source .bashrc, or anyone who later switches shells, without uv on PATH.+ for _supp_profile in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.bash_profile" \+ "$HOME/.bash_login" "${ZDOTDIR:-$HOME}/.zshrc" "${ZDOTDIR:-$HOME}/.zshenv"; do+ if [ "$_supp_profile" != "$HOME/.profile" ] && [ ! -f "$_supp_profile" ]; then continue; fi+ # Only lines that actually set PATH count: `UV_CACHE=/opt/uv` and `PYTHONPATH=/opt/uv`+ # are not PATH entries, and taking one for an entry leaves the next shell without uv.+ if grep -v '^[[:space:]]*#' "$_supp_profile" 2>/dev/null \+ | grep -E "$_supp_path_line" \+ | grep -qE "(^|[^[:alnum:]_.~/-])$_supp_grep([^[:alnum:]_.~/-]|\$)"; then continue; fi+ echo '' >> "$_supp_profile"+ echo '# Added by Unsloth setup' >> "$_supp_profile"+ echo "export PATH=\"$_supp_literal:\$PATH\"" >> "$_supp_profile"+ done+}+USE_UV=falseif command -v uv &>/dev/null; thenUSE_UV=trueelif {- if _is_verbose; then+ _SETUP_UV_PINNED_OK=false+ if _setup_install_uv_pinned; then+ _SETUP_UV_PINNED_OK=true+ elif _is_verbose; then_setup_http_get https://astral.sh/uv/install.sh | shelse_setup_http_get https://astral.sh/uv/install.sh | sh > /dev/null 2>&1fi}; then- export PATH="$HOME/.local/bin:$PATH"+ # Only for astral's installer, which writes to ~/.local/bin. The pinned path already put its+ # own destination first, and prepending here would let a stale ~/.local/bin/uv shadow the+ # 0.12.1 we just verified, so the rest of setup would run the wrong one.+ [ "$_SETUP_UV_PINNED_OK" = true ] || export PATH="$HOME/.local/bin:$PATH"command -v uv &>/dev/null && USE_UV=truefidiff --git a/studio/src-tauri/src/install.rs b/studio/src-tauri/src/install.rsindex d451c96c4e2..6425b729035 100644--- a/studio/src-tauri/src/install.rs+++ b/studio/src-tauri/src/install.rs@@ -1,7 +1,7 @@use crate::diagnostics::{self, AttemptLog, DiagnosticsState};use log::{error, info, warn};use process_wrap::std::*;-use std::collections::VecDeque;+use std::collections::{HashMap, VecDeque};use std::io::BufRead;use std::path::{Path, PathBuf};use std::process::{Command, ExitStatus, Stdio};@@ -31,6 +31,8 @@ use crate::process::trim_line_endings;const FAILURE_CONTEXT_LINES: usize = 8;const FAILURE_CONTEXT_LINE_BYTES: usize = 1_000;+/// Clear labels are a small fixed set; this only bounds a pathological producer.+const MAX_UNPAIRED_CLEARS: usize = 64;fn generic_failure_message(code: i32) -> String {format!(@@ -39,12 +41,111 @@ fn generic_failure_message(code: i32) -> String {)}-#[derive(Clone, Copy, PartialEq, Eq)]+/// PowerShell hands the whole top-level script block to AMSI while compiling it, so a security+/// product's verdict arrives as a parse error over the entire file before the installer's first+/// line runs: no `[TAURI:ERROR]` marker, no phase log, just an unexplained stderr tail. Match the+/// stable error id, never the localized message text.+const AMSI_MALWARE_ERROR_ID: &str = "ScriptContainedMaliciousContent";+const AMSI_ADMIN_BLOCK_ERROR_ID: &str = "ScriptHasAdminBlockedContent";++/// The id only means a verdict when it is the VALUE of a `FullyQualifiedErrorId` field, which is+/// how the parse error prints it. Otherwise a scanner log or a diagnostic that merely names the id+/// would attach antivirus guidance to an unrelated failure. A record split across writes loses the+/// guidance rather than inventing one, which is the safe direction.+const POWERSHELL_ERROR_ID_FIELD: &str = "FullyQualifiedErrorId";++/// "Nothing was changed" only holds for a block on install.ps1 itself, which AMSI rejects before+/// its first statement. It also runs `unsloth studio setup`, whose child spawns studio/setup.ps1+/// through the same pipes: a block there arrives with the venv, PyTorch and the packages already+/// on disk. A `[TAURI:STEP]` marker is the dividing line, since a pre-start block produces none.+/// Not "nothing was changed": a diagnostics attempt and its phase log are written before+/// PowerShell is spawned, so the honest claim is that no installation step ran. And not "this is a+/// false positive": classification proves only that the output carries an error id, and install.ps1+/// can sit in a user-writable directory.+const AMSI_MALWARE_GUIDANCE_PRE_START: &str = "Security software blocked the installer before it \+ started, so no installation steps ran; only diagnostic logs may have been written. This is \+ usually a false positive: reinstall from an official Unsloth package, and if an unmodified \+ copy is still blocked, update your security product's definitions or report it to your \+ vendor. Do not disable endpoint protection.";+const AMSI_MALWARE_GUIDANCE_IN_PROGRESS: &str = "Security software blocked part of the installer, \+ so setup did not finish and some components may already be installed. This is usually a \+ false positive: reinstall from an official Unsloth package, and if an unmodified copy is \+ still blocked, update your security product's definitions or report it to your vendor. Do \+ not disable endpoint protection.";+const AMSI_ADMIN_BLOCK_GUIDANCE_PRE_START: &str = "This machine's security policy blocked the \+ installer before it started, so no installation steps ran. Ask whoever manages the device \+ to allow it.";+const AMSI_ADMIN_BLOCK_GUIDANCE_IN_PROGRESS: &str = "This machine's security policy blocked part \+ of the installer, so setup did not finish and some components may already be installed. Ask \+ whoever manages the device to allow it.";++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+enum SecurityBlockKind {+ Malware,+ AdminPolicy,+}++impl SecurityBlockKind {+ /// Resolved at message time, not observation time: the two streams are read by independent+ /// threads, so a `[TAURI:STEP]` written before the block can be observed after it.+ fn guidance(self, started: bool) -> &'static str {+ match (self, started) {+ (Self::Malware, false) => AMSI_MALWARE_GUIDANCE_PRE_START,+ (Self::Malware, true) => AMSI_MALWARE_GUIDANCE_IN_PROGRESS,+ (Self::AdminPolicy, false) => AMSI_ADMIN_BLOCK_GUIDANCE_PRE_START,+ (Self::AdminPolicy, true) => AMSI_ADMIN_BLOCK_GUIDANCE_IN_PROGRESS,+ }+ }+}++/// True when `id` is the value of the `FullyQualifiedErrorId` field rather than merely present on+/// the line. PowerShell prints `+ FullyQualifiedErrorId : <id>[,<cmdlet>]`, so it follows the+/// colon; prose naming both does not qualify.+fn is_error_id_value(text: &str, id: &str) -> bool {+ let mut rest = text;+ while let Some(at) = rest.find(POWERSHELL_ERROR_ID_FIELD) {+ let after = &rest[at + POWERSHELL_ERROR_ID_FIELD.len()..];+ let after = after.trim_start();+ if let Some(value) = after.strip_prefix(':') {+ let value = value.trim_start();+ if let Some(tail) = value.strip_prefix(id) {+ // The id can carry a cmdlet suffix, but nothing else may extend the token.+ if tail.is_empty() || tail.starts_with(',') || tail.starts_with(char::is_whitespace)+ {+ return true;+ }+ }+ }+ rest = &rest[at + POWERSHELL_ERROR_ID_FIELD.len()..];+ }+ false+}++fn security_block_kind(text: &str) -> Option<SecurityBlockKind> {+ if is_error_id_value(text, AMSI_MALWARE_ERROR_ID) {+ return Some(SecurityBlockKind::Malware);+ }+ if is_error_id_value(text, AMSI_ADMIN_BLOCK_ERROR_ID) {+ return Some(SecurityBlockKind::AdminPolicy);+ }+ None+}++#[derive(Clone, Copy, PartialEq, Eq, Hash)]enum InstallOutputStream {Stdout,Stderr,}+impl InstallOutputStream {+ fn other(self) -> Self {+ match self {+ Self::Stdout => Self::Stderr,+ Self::Stderr => Self::Stdout,+ }+ }+}+struct InstallOutputLine {stream: InstallOutputStream,text: String,@@ -55,13 +156,20 @@ struct InstallFailureContext {explicit_error: Option<String>,explicit_error_stream: Option<InstallOutputStream>,default_error: Option<String>,+ security_block: Option<SecurityBlockKind>,+ unpaired_clears: HashMap<(String, InstallOutputStream), usize>,+ started: bool,output_tail: VecDeque<InstallOutputLine>,}impl InstallFailureContext {fn observe_stdout(&mut self, text: &str) -> bool {- if text.starts_with("[TAURI:ERROR_CLEAR] ") {- self.clear_failure(InstallOutputStream::Stdout);+ if text.starts_with("[TAURI:STEP] ") {+ self.started = true;+ }+ self.note_security_block(text);+ if let Some(message) = text.strip_prefix("[TAURI:ERROR_CLEAR] ") {+ self.clear_failure(InstallOutputStream::Stdout, message);return true;}if text.starts_with("[TAURI:OUTPUT_CLEAR] ") {@@ -94,8 +202,9 @@ impl InstallFailureContext {}fn observe_stderr(&mut self, text: &str) -> bool {- if text.starts_with("[TAURI:ERROR_CLEAR] ") {- self.clear_failure(InstallOutputStream::Stderr);+ self.note_security_block(text);+ if let Some(message) = text.strip_prefix("[TAURI:ERROR_CLEAR] ") {+ self.clear_failure(InstallOutputStream::Stderr, message);return true;}if text.starts_with("[TAURI:OUTPUT_CLEAR] ") {@@ -130,7 +239,53 @@ impl InstallFailureContext {}}- fn clear_failure(&mut self, stream: InstallOutputStream) {+ /// Both streams, before marker handling: PowerShell writes the parse error to stderr, but a+ /// wrapper that folded the streams together would otherwise lose it.+ fn note_security_block(&mut self, text: &str) {+ if self.security_block.is_none() {+ self.security_block = security_block_kind(text);+ }+ }++ fn clear_failure(&mut self, stream: InstallOutputStream, message: &str) {+ // Clear-TauriInstallError writes ONE logical clear to BOTH streams (install.ps1:198),+ // read by independent threads, so a verdict can land between a clear and its own twin and+ // treating the twin as a second clear would discard a real block.+ //+ // Pair by message, not against the previous clear alone: a reader can lag several clears+ // behind, so "is this the message I just saw" answers no and throws the verdict away. Each+ // logical clear emits exactly two markers, so the first sighting is the clear and the next+ // pairs with it.+ //+ // Keyed by stream as well as message: the same label can be cleared twice for real (an+ // install and then a repair both emit "install PyTorch recovered"), and a reader that got+ // ahead would otherwise pair those two same-stream clears with each other. Only the+ // opposite stream's copy can consume a pending marker.+ let other = stream.other();+ let twin = match self.unpaired_clears.get_mut(&(message.to_owned(), other)) {+ Some(count) if *count > 0 => {+ *count -= 1;+ true+ }+ _ => {+ *self+ .unpaired_clears+ .entry((message.to_owned(), stream))+ .or_insert(0) += 1;+ false+ }+ };+ self.unpaired_clears.retain(|_, count| *count > 0);+ // Producers clear with a small fixed set of labels, and an unbounded map fed by child+ // output is a memory sink. Dropping the oldest entries only costs a twin match.+ if self.unpaired_clears.len() > MAX_UNPAIRED_CLEARS {+ self.unpaired_clears.clear();+ }+ if !twin {+ // A run that cleared its own failure state was never blocked at parse time, so a+ // verdict here is stale.+ self.security_block = None;+ }if self.explicit_error_stream == Some(stream) {self.explicit_error = None;self.explicit_error_stream = None;@@ -172,9 +327,15 @@ impl InstallFailureContext {.as_deref().or(self.default_error.as_deref()).or_else(|| self.output_tail.back().map(|line| line.text.as_str()));- match detail {+ let base = match detail {Some(detail) => format!("Installation failed: {}", detail),None => generic_failure_message(code),+ };+ // Appended, not substituted: the raw id is what a diagnostics report and a vendor+ // submission need, the guidance is what the user needs.+ match self.security_block {+ Some(kind) => format!("{} {}", base, kind.guidance(self.started)),+ None => base,}}}@@ -1316,6 +1477,241 @@ mod tests {assert!(!is_elevation_request(1, &["cmake".to_string()]));}+ /// The exact stderr an AMSI provider produced in #8523. The scan covers the whole script+ /// block, so the parse error points at line 1 char 1 and no statement ever runs.+ const AMSI_BLOCK_STDERR: [&str; 6] = [+ r"At C:\Program Files\Unsloth\install.ps1:1 char:1",+ "+ # Unsloth Studio Installer for Windows PowerShell",+ "+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~",+ "This script contains malicious content and has been blocked by your antivirus software.",+ " + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException",+ " + FullyQualifiedErrorId : ScriptContainedMaliciousContent",+ ];++ #[test]+ fn amsi_block_explains_itself_without_losing_the_error_id() {+ let mut context = InstallFailureContext::default();+ for line in AMSI_BLOCK_STDERR {+ context.observe_stderr(line);+ }+ let message = context.message(1);+ // The raw id survives: diagnostics and vendor submissions need it.+ assert!(message.contains("ScriptContainedMaliciousContent"), "{message}");+ assert!(message.starts_with("Installation failed: "), "{message}");+ assert!(message.contains("blocked the installer before it started"), "{message}");+ assert!(message.contains("only diagnostic logs may have been written"), "{message}");+ // We cannot know a verdict is wrong, so the text must not assert it.+ assert!(!message.contains("This is a false positive"), "{message}");+ }++ #[test]+ fn a_block_after_the_install_started_does_not_claim_nothing_changed() {+ // install.ps1 runs `unsloth studio setup` near the end, and that child spawns+ // studio/setup.ps1 on the same inherited pipes. A block there lands after the venv and+ // PyTorch are on disk, so the pre-start reassurance would be false.+ let mut context = InstallFailureContext::default();+ context.observe_stdout("[TAURI:STEP] running unsloth studio setup...");+ for line in AMSI_BLOCK_STDERR {+ context.observe_stderr(line);+ }+ let message = context.message(1);+ assert!(message.contains("ScriptContainedMaliciousContent"), "{message}");+ assert!(message.contains("blocked part of the installer"), "{message}");+ assert!(!message.contains("no installation steps ran"), "{message}");+ assert!(message.contains("some components may already be installed"), "{message}");+ }++ #[test]+ fn the_wording_follows_the_final_started_state_not_the_arrival_order() {+ // stdout and stderr are read by independent threads, so the STEP a child wrote before+ // the block can be observed after it. Deciding the wording when the token arrives would+ // tell the user nothing was changed on a run that had already installed PyTorch.+ let mut context = InstallFailureContext::default();+ for line in AMSI_BLOCK_STDERR {+ context.observe_stderr(line);+ }+ context.observe_stdout("[TAURI:STEP] running unsloth studio setup...");+ let message = context.message(1);+ assert!(message.contains("blocked part of the installer"), "{message}");+ assert!(!message.contains("no installation steps ran"), "{message}");+ }++ #[test]+ fn the_twin_of_an_earlier_clear_does_not_erase_a_later_verdict() {+ // Clear-TauriInstallError writes one clear to BOTH streams, and independent readers can+ // interleave them around a block that happened afterwards. install.ps1 clears after each+ // recovered step, so this is the ordinary shape of a setup.ps1 block late in a run.+ let mut context = InstallFailureContext::default();+ context.observe_stdout("[TAURI:STEP] installing PyTorch");+ context.observe_stderr("[TAURI:ERROR_CLEAR] PyTorch recovered");+ for line in AMSI_BLOCK_STDERR {+ context.observe_stderr(line);+ }+ // the twin of the same clear, arriving late on the other stream+ context.observe_stdout("[TAURI:ERROR_CLEAR] PyTorch recovered");+ let message = context.message(1);+ assert!(message.contains("blocked part of the installer"), "{message}");+ }++ #[test]+ fn two_real_clears_of_one_label_on_one_stream_are_not_twins() {+ // The same label can be cleared twice for real: _install_torch_default_index emits its+ // recovery during the install and again during the ROCm repair. Pairing by message alone+ // treated the second as the twin of the first, so the block that landed between them was+ // then erased by the genuinely later clear arriving on the other stream.+ let mut context = InstallFailureContext::default();+ context.observe_stdout("[TAURI:STEP] installing PyTorch");+ context.observe_stderr("[TAURI:ERROR_CLEAR] install PyTorch recovered");+ context.observe_stderr("[TAURI:ERROR_CLEAR] install PyTorch recovered");+ for line in AMSI_BLOCK_STDERR {+ context.observe_stderr(line);+ }+ // Both twins arrive late on the other stream and consume the two pending clears.+ context.observe_stdout("[TAURI:ERROR_CLEAR] install PyTorch recovered");+ context.observe_stdout("[TAURI:ERROR_CLEAR] install PyTorch recovered");+ let message = context.message(1);+ assert!(message.contains("blocked part of the installer"), "{message}");+ }++ #[test]+ fn a_twin_lagging_several_clears_behind_still_pairs() {+ // install.ps1 clears after every recovered step, so a slower reader can be several clears+ // behind when a block lands. Pairing only against the previous message would treat this+ // delayed twin of A as a fresh recovery and drop the verdict.+ let mut context = InstallFailureContext::default();+ context.observe_stdout("[TAURI:STEP] installing PyTorch");+ context.observe_stderr("[TAURI:ERROR_CLEAR] step A recovered");+ context.observe_stderr("[TAURI:ERROR_CLEAR] step B recovered");+ for line in AMSI_BLOCK_STDERR {+ context.observe_stderr(line);+ }+ context.observe_stdout("[TAURI:ERROR_CLEAR] step A recovered");+ context.observe_stdout("[TAURI:ERROR_CLEAR] step B recovered");+ let message = context.message(1);+ assert!(message.contains("blocked part of the installer"), "{message}");+ }++ #[test]+ fn a_genuinely_later_recovery_still_clears_the_verdict() {+ // Distinct text means a real subsequent recovery, not a twin, and the guidance must go.+ let mut context = InstallFailureContext::default();+ context.observe_stderr("[TAURI:ERROR_CLEAR] PyTorch recovered");+ for line in AMSI_BLOCK_STDERR {+ context.observe_stderr(line);+ }+ context.observe_stdout("[TAURI:ERROR_CLEAR] studio setup completed");+ context.observe_stdout("[TAURI:ERROR] Failed to install PyTorch");+ assert_eq!(+ context.message(7),+ "Installation failed: Failed to install PyTorch"+ );+ }++ #[test]+ fn the_id_has_to_be_the_field_value_not_just_on_the_line() {+ // Prose that names both the field and the id is not an error record.+ let mut context = InstallFailureContext::default();+ context.observe_stderr(+ "checking FullyQualifiedErrorId handling for ScriptContainedMaliciousContent",+ );+ context.observe_stdout("[TAURI:ERROR] Failed to install PyTorch");+ assert_eq!(+ context.message(7),+ "Installation failed: Failed to install PyTorch"+ );+ // A longer token that merely starts with the id is a different id.+ assert!(!is_error_id_value(+ "+ FullyQualifiedErrorId : ScriptContainedMaliciousContentX",+ AMSI_MALWARE_ERROR_ID+ ));+ // The real record, with and without the cmdlet suffix.+ assert!(is_error_id_value(+ " + FullyQualifiedErrorId : ScriptContainedMaliciousContent",+ AMSI_MALWARE_ERROR_ID+ ));+ assert!(is_error_id_value(+ " + FullyQualifiedErrorId : ScriptContainedMaliciousContent,Microsoft.PowerShell",+ AMSI_MALWARE_ERROR_ID+ ));+ }++ #[test]+ fn a_flood_of_distinct_clears_cannot_grow_the_pairing_map() {+ let mut context = InstallFailureContext::default();+ for i in 0..(MAX_UNPAIRED_CLEARS * 4) {+ context.observe_stdout(&format!("[TAURI:ERROR_CLEAR] step {i} recovered"));+ }+ assert!(context.unpaired_clears.len() <= MAX_UNPAIRED_CLEARS, "{}", context.unpaired_clears.len());+ }++ #[test]+ fn merely_naming_the_error_id_is_not_a_verdict() {+ // The id is only a verdict as the value of a PowerShell error record's field. A scanner+ // log or a test fixture that prints the bare string must not attach antivirus guidance+ // to whatever fails next.+ let mut context = InstallFailureContext::default();+ context.observe_stderr("scanning fixture ScriptContainedMaliciousContent");+ context.observe_stdout("[TAURI:ERROR] Failed to install PyTorch");+ assert_eq!(+ context.message(7),+ "Installation failed: Failed to install PyTorch"+ );+ }++ #[test]+ fn an_admin_policy_block_after_the_install_started_is_also_neutral() {+ let mut context = InstallFailureContext::default();+ context.observe_stdout("[TAURI:STEP] installing PyTorch");+ context.observe_stderr(" + FullyQualifiedErrorId : ScriptHasAdminBlockedContent");+ let message = context.message(1);+ assert!(message.contains("blocked part of the installer"), "{message}");+ assert!(!message.contains("no installation steps ran"), "{message}");+ }++ #[test]+ fn amsi_block_is_recognised_on_stdout_and_when_the_id_carries_a_cmdlet_suffix() {+ // A wrapper folding stderr into stdout, plus the Invoke-Expression form of the id.+ let mut context = InstallFailureContext::default();+ context.observe_stdout(+ " + FullyQualifiedErrorId : ScriptContainedMaliciousContent,\+ Microsoft.PowerShell.Commands.InvokeExpressionCommand",+ );+ assert!(context+ .message(1)+ .contains("blocked the installer before it started"));+ }++ #[test]+ fn admin_policy_block_gets_its_own_guidance() {+ let mut context = InstallFailureContext::default();+ context.observe_stderr(" + FullyQualifiedErrorId : ScriptHasAdminBlockedContent");+ let message = context.message(1);+ assert!(message.contains("security policy blocked the installer"), "{message}");+ assert!(!message.contains("report it to your vendor"), "{message}");+ }++ #[test]+ fn an_ordinary_failure_gains_no_security_guidance() {+ let mut context = InstallFailureContext::default();+ context.observe_stdout("[TAURI:ERROR] Failed to install PyTorch");+ assert_eq!(+ context.message(7),+ "Installation failed: Failed to install PyTorch"+ );+ }++ #[test]+ fn a_run_that_clears_its_failure_state_drops_a_stale_verdict() {+ let mut context = InstallFailureContext::default();+ context.observe_stderr(" + FullyQualifiedErrorId : ScriptContainedMaliciousContent");+ context.observe_stdout("[TAURI:ERROR_CLEAR] retrying");+ context.observe_stdout("[TAURI:ERROR] Failed to install PyTorch");+ assert_eq!(+ context.message(7),+ "Installation failed: Failed to install PyTorch"+ );+ }+#[test]fn explicit_installer_error_beats_stderr_noise() {let mut context = InstallFailureContext::default();diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.jsonindex 5dde75d1b73..c8cc4b334d4 100644--- a/studio/src-tauri/tauri.conf.json+++ b/studio/src-tauri/tauri.conf.json@@ -58,10 +58,6 @@"copyright": "© 2026 Unsloth AI. All rights reserved.","license": "AGPL-3.0-only","targets": ["app", "deb", "dmg", "nsis"],- "resources": {- "../../install.sh": "install.sh",- "../../install.ps1": "install.ps1"- },"icon": ["icons/32x32.png","icons/128x128.png",diff --git a/studio/src-tauri/tauri.linux.conf.json b/studio/src-tauri/tauri.linux.conf.jsonnew file mode 100644index 00000000000..a60898ea8c3--- /dev/null+++ b/studio/src-tauri/tauri.linux.conf.json@@ -0,0 +1,7 @@+{+ "bundle": {+ "resources": {+ "../../install.sh": "install.sh"+ }+ }+}diff --git a/studio/src-tauri/tauri.macos.conf.json b/studio/src-tauri/tauri.macos.conf.jsonindex dc9fdaadc3b..bc7b5005e30 100644--- a/studio/src-tauri/tauri.macos.conf.json+++ b/studio/src-tauri/tauri.macos.conf.json@@ -1,5 +1,8 @@{"bundle": {+ "resources": {+ "../../install.sh": "install.sh"+ },"macOS": {"entitlements": "./Entitlements.plist","infoPlist": "./Info.plist",diff --git a/studio/src-tauri/tauri.windows.conf.json b/studio/src-tauri/tauri.windows.conf.jsonindex 1619edd923f..49faf19aa60 100644--- a/studio/src-tauri/tauri.windows.conf.json+++ b/studio/src-tauri/tauri.windows.conf.json@@ -1,5 +1,8 @@{"bundle": {+ "resources": {+ "../../install.ps1": "install.ps1"+ },"windows": {"signCommand": {"cmd": "powershell",diff --git a/studio/src-tauri/windows/hooks.nsh b/studio/src-tauri/windows/hooks.nshindex e5b6699d24e..9ebc4d1a998 100644--- a/studio/src-tauri/windows/hooks.nsh+++ b/studio/src-tauri/windows/hooks.nsh@@ -1,5 +1,24 @@; Unsloth NSIS installer hooks+!macro NSIS_HOOK_PREINSTALL+ ; Windows bundles carry only install.ps1 now. NSIS writes the current resource manifest+ ; and deletes nothing, so an in-place upgrade from a release that shipped both would keep+ ; install.sh forever and make the non-recursive RMDir "$INSTDIR" fail at uninstall.+ ; Gated on our own executable being there: this hook runs before the user can still cancel,+ ; and the directory can be one they picked themselves, so only a directory that already+ ; holds an Unsloth install is ours to tidy.+ ${If} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe"+ Delete "$INSTDIR\install.sh"+ ${EndIf}+!macroend++!macro NSIS_HOOK_PREUNINSTALL+ ; Same file, for anyone uninstalling a version that never ran the hook above.+ ${If} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe"+ Delete "$INSTDIR\install.sh"+ ${EndIf}+!macroend+!macro NSIS_HOOK_POSTUNINSTALL; Desktop uninstall must not remove $PROFILE\.unsloth. The CLI/web; installers also use that tree for environments, models, outputs, anddiff --git a/tests/python/test_cross_platform_parity.py b/tests/python/test_cross_platform_parity.pyindex 83382060a59..053bb1229d7 100644--- a/tests/python/test_cross_platform_parity.py+++ b/tests/python/test_cross_platform_parity.py@@ -688,6 +688,56 @@ class TestPinnedIndexClearsUvEnvParity:"finally"), "pip fallback must run before the scrub is restored"+ def test_windows_installers_probe_uv_before_replacing_an_incumbent(self):+ """A host can have a working older uv while AppLocker, WDAC or endpoint+ protection refuses the one we just downloaded. Both PowerShell installers must+ run the extracted uv.exe where it landed BEFORE anything at the destination is+ touched, and must restore the incumbent if the published copy will not run."""+ for path, probe in (+ (INSTALL_PS1, "Get-UvExecutableVerdict"),+ (SETUP_PS1, "Get-SetupUvExecutableVerdict"),+ ):+ text = path.read_text(encoding = "utf-8")+ assert f"function {probe}" in text, f"{path.name} must define {probe}"+ # WaitForExit takes a timeout: an unbounded wait on a freshly downloaded+ # binary is exactly how an unattended install hangs.+ assert "WaitForExit(20000)" in text, f"{path.name}'s uv probe must bound its wait"+ probe_at = text.index(f"({probe} -Path $stagedUv)")+ # Tri-state, not a boolean. A launch that throws or a wait that times out got no+ # verdict, and treating that as a broken binary turned three clean-machine CI legs+ # into hard install failures: Start-Process -NoNewWindow with redirected streams+ # does not behave in a Windows container or on arm64 as it does on a desktop. Only+ # the binary answering non-zero may block the install.+ body = text.split(f"function {probe}", 1)[1].split("\n }\n", 1)[0]+ # An EMPTY exit code is no verdict either. WaitForExit(ms) can return before the+ # code is cached, which is how arm64 and the Windows containers reported "exited ."+ # and had a working uv read as broken.+ assert (+ "try { $proc.WaitForExit() } catch {}" in body+ ), f"{path.name} must settle the exit code before reading it"+ assert (+ '$null -eq $code -or "$code" -eq ""' in body+ ), f"{path.name} must treat a missing exit code as inconclusive"+ assert (+ body.count('return "unknown"') == 3+ ), f"{path.name}: a launch failure and a timeout must both be inconclusive"+ assert (+ 'return "failed"' in body and 'return "ok"' in body+ ), f"{path.name}'s probe must report a real answer as well"+ assert (+ f'({probe} -Path $stagedUv) -eq "failed"' in text+ ), f"{path.name} must gate only on a failed verdict"+ copy_at = text.index("Copy-Item -LiteralPath $src -Destination $dst -Force")+ assert probe_at < copy_at, (+ f"{path.name} must probe the extracted uv.exe before copying over the "+ "destination"+ )+ # The publish is not a transaction: a locked or ACL-denied destination fails the+ # install rather than being skipped, which is what the caller's fallback is for.+ assert (+ "Copy-Item -LiteralPath $src -Destination $dst -Force -ErrorAction Stop" in text+ ), f"{path.name} must copy each executable under -ErrorAction Stop"+def test_all_installers_disable_uv_config_for_pinned_installs(self):"""A DISCOVERED uv.toml / pyproject [tool.uv] outranks the CLI pin(verified with uv 0.10: [pip] torch-backend = "cpu" and a non-defaultdiff --git a/tests/python/test_virustotal_scan.py b/tests/python/test_virustotal_scan.pyindex fb39d7fb3c5..26487044aec 100644--- a/tests/python/test_virustotal_scan.py+++ b/tests/python/test_virustotal_scan.py@@ -478,6 +478,53 @@ class TestRenderMarkdown:assert "Flagging engines" in textassert "AlphaAV (Trojan)" in text+ def test_a_flagged_asset_gets_a_submission_packet(self):+ # The build job only ever assembled a packet for the Windows -setup.exe, so the one+ # detection that actually arrived -- Trojan:Script/Wacatac.B!ml on the Linux AppImage --+ # produced nothing to submit.+ text = vt.render_markdown(+ [+ vt.FileReport(+ name = "Unsloth-Desktop-Linux.AppImage",+ sha256 = "e3aa9b36",+ size = 46193144,+ stats = vt.ScanStats(malicious = 1, undetected = 62),+ detections = ["Microsoft (Trojan:Script/Wacatac.B!ml)"],+ )+ ],+ 0,+ )+ assert "False-positive submission packet" in text+ assert "Unsloth-Desktop-Linux.AppImage" in text+ assert "e3aa9b36" in text+ assert "46193144 bytes" in text+ assert "wdsi/filesubmission" in text++ def test_a_flagged_asset_with_no_readable_engine_list_still_gets_a_packet(self):+ # stats and results are separate fields of the same response. The table reports the+ # count, so the packet has to key on the same thing or it skips the one asset that+ # needs one.+ text = vt.render_markdown(+ [+ vt.FileReport(+ name = "a.exe",+ sha256 = "ab",+ size = 10,+ stats = vt.ScanStats(malicious = 1, undetected = 60),+ detections = [],+ )+ ],+ 0,+ )+ assert "False-positive submission packet" in text+ assert "Flagging engines" not in text++ def test_a_clean_run_gets_no_submission_packet(self):+ text = vt.render_markdown(+ [vt.FileReport(name = "a.exe", sha256 = "ab", stats = vt.ScanStats(undetected = 60))], 0+ )+ assert "False-positive submission packet" not in text+class TestFailClosedOnMalformedLookup:"""A 200 whose body does not parse must not be read as 'never seen'.diff --git a/tests/sh/test_uv_pinned_release.sh b/tests/sh/test_uv_pinned_release.shnew file mode 100755index 00000000000..db2b60b7bc8--- /dev/null+++ b/tests/sh/test_uv_pinned_release.sh@@ -0,0 +1,1120 @@+#!/bin/bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+#+# Guards install.sh's uv bootstrap.+#+# It used to download astral's install.sh to a temp file, run it and delete the file, which+# is shape for shape what a dropper does. It now fetches the pinned release archive and+# verifies a hardcoded SHA-256 first, the move install.ps1 already made.+#+# The fallback must stay: musl, armv7 and hosts without a digest tool keep the old path+# rather than risk a wrong triple. These tests pin the digest check (a mismatched archive+# installs nothing), the extraction, and the fallback being reachable but not primary.+set -e++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+INSTALL_SH="$SCRIPT_DIR/../../install.sh"+PASS=0+FAIL=0++ok() { echo " PASS: $1"; PASS=$((PASS + 1)); }+bad() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }++WORK="$(mktemp -d)"+trap 'rm -rf "$WORK"' EXIT++# ── source contract ──+echo "=== source contract ==="++if grep -q '_uv_install_pinned' "$INSTALL_SH"; then+ ok "install.sh has a pinned-release uv path"+else+ bad "install.sh has a pinned-release uv path"+fi++# The pinned attempt must precede the fallback, or the fallback is what actually runs.+_pinned_at=$(grep -n 'if _uv_install_pinned; then' "$INSTALL_SH" | head -1 | cut -d: -f1)+_fallback_at=$(grep -n 'download "https://astral.sh/uv/install.sh"' "$INSTALL_SH" | head -1 | cut -d: -f1)+if [ -n "$_pinned_at" ] && [ -n "$_fallback_at" ] && [ "$_pinned_at" -lt "$_fallback_at" ]; then+ ok "the pinned path is tried before the astral fallback"+else+ bad "the pinned path is tried before the astral fallback (pinned=$_pinned_at fallback=$_fallback_at)"+fi++# A truncated digest would silently never match and route every host to the fallback.+_bad_digests=$(grep -oE 'uv-[a-z0-9_]+-[a-z0-9.-]+\.tar\.gz [0-9a-f]*' "$INSTALL_SH" \+ | awk '{ if (length($2) != 64) print }' | wc -l | tr -d ' ')+if [ "$_bad_digests" = "0" ]; then+ ok "every pinned archive digest is a full sha256"+else+ bad "every pinned archive digest is a full sha256 ($_bad_digests malformed)"+fi++# One version constant, quoted into every URL.+if grep -q '^UV_PINNED_VERSION="' "$INSTALL_SH"; then+ ok "the pinned uv version is a single constant"+else+ bad "the pinned uv version is a single constant"+fi++# All four installers must pin the same uv, or which one a user ends up with depends on which+# script reached the machine first.+_pinned_versions=$(+ grep -hoE '(UV_PINNED_VERSION|_SETUP_UV_PINNED_VERSION)="[0-9.]+"' \+ "$INSTALL_SH" "$SCRIPT_DIR/../../studio/setup.sh"+ grep -hoE '\$UvPinnedVersion += +"[0-9.]+"' \+ "$SCRIPT_DIR/../../install.ps1" "$SCRIPT_DIR/../../studio/setup.ps1"+)+_pinned_distinct=$(printf '%s\n' "$_pinned_versions" | grep -oE '[0-9]+\.[0-9]+(\.[0-9]+)?' | sort -u)+_pinned_count=$(printf '%s\n' "$_pinned_distinct" | grep -c .)+if [ "$(printf '%s\n' "$_pinned_versions" | grep -c .)" = "4" ] && [ "$_pinned_count" = "1" ]; then+ ok "all four installers pin the same uv ($_pinned_distinct)"+else+ bad "the pinned uv version disagrees across installers: $(printf '%s' "$_pinned_distinct" | tr '\n' ' ')"+fi++# The pin has to clear every version floor in the tree. Before the pin, astral's endpoint always+# delivered the newest uv, so raising a floor was safe on its own; now a floor above the pin would+# install a uv the same script immediately judges too old. This is the check that catches it.+_floors=$(+ grep -hoE '^UV_MIN_VERSION="[0-9.]+"|^UV_OFFLINE_MIN_VERSION="[0-9.]+"' "$INSTALL_SH"+ grep -hoE '\$UvMinVersion += +"[0-9.]+"' "$SCRIPT_DIR/../../install.ps1"+)+_floor_bad=0+for _floor in $(printf '%s\n' "$_floors" | grep -oE '[0-9]+\.[0-9]+(\.[0-9]+)?'); do+ # sort -V: the lower of the two sorts first, so the pin must not be it unless they are equal.+ _lowest=$(printf '%s\n%s\n' "$_floor" "$_pinned_distinct" | sort -V | head -1)+ if [ "$_lowest" != "$_floor" ] && [ "$_floor" != "$_pinned_distinct" ]; then+ echo " floor $_floor is above the pin $_pinned_distinct"+ _floor_bad=$((_floor_bad + 1))+ fi+done+if [ "$_floor_bad" = 0 ]; then+ ok "the pinned uv clears every version floor in the tree"+else+ bad "$_floor_bad version floor(s) sit above the pinned uv"+fi++# astral's installer wrote its own shell-profile line; the pinned path does not, so install.sh's+# own profile write is now the only thing that puts _LOCAL_BIN on a NEW shell's PATH. That guard+# has to read the PATH we inherited: by the time it runs, this process has prepended the directory+# for the uv bootstrap and the venv, so testing the live $PATH answers yes for a login shell that+# would answer no, the profile line never gets written, and `unsloth` is missing from the next+# terminal.+_snapshot_at=$(grep -n '^_UNSLOTH_LOGIN_PATH="\$PATH"' "$INSTALL_SH" | head -1 | cut -d: -f1)+_first_mutation=$(grep -n 'export PATH=' "$INSTALL_SH" | head -1 | cut -d: -f1)+if [ -n "$_snapshot_at" ] && [ -n "$_first_mutation" ] && [ "$_snapshot_at" -lt "$_first_mutation" ]; then+ ok "the login PATH is snapshotted before anything prepends to PATH"+else+ bad "the login PATH snapshot is missing or too late (snapshot=$_snapshot_at first mutation=$_first_mutation)"+fi+if grep -q '_path_has_dir "\$_UNSLOTH_LOGIN_PATH"' "$INSTALL_SH"; then+ ok "the shell-profile guard tests the inherited PATH, not the one we prepended to"+else+ bad "the shell-profile guard tests the inherited PATH, not the one we prepended to"+fi++# ...and having found that a new shell would NOT see the directory, it has to actually persist it.+# A fresh account can have no rc file at all; astral's installer used to create one, the pinned+# path does not, so an empty _SHELL_PROFILE means the next terminal resolves neither unsloth nor+# uv. Run the real block from install.sh rather than grepping it.+# The guard now calls _persist_login_path_dir, so the extract has to carry the function too.+_fn_start=$(grep -n '^_path_has_dir() {' "$INSTALL_SH" | head -1 | cut -d: -f1)+# Through the sentinel that closes the block: the two persistence decisions are one contract+# and the test drives both.+_guard_end=$(grep -n '^# end of the PATH persistence block$' "$INSTALL_SH" | head -1 | cut -d: -f1)+sed -n "${_fn_start},${_guard_end}p" "$INSTALL_SH" > "$WORK/path_guard.sh"+mkdir -p "$WORK/fresh_home/.local/bin"+(+ set +e+ step() { :; }+ HOME="$WORK/fresh_home"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+if grep -q '\.local/bin' "$WORK/fresh_home/.profile" 2>/dev/null; then+ ok "an account with no rc file still gets ~/.local/bin persisted"+else+ bad "an account with no rc file still gets ~/.local/bin persisted"+fi+# And it must stay idempotent: a second run over the file it just wrote adds nothing.+(+ set +e+ step() { :; }+ HOME="$WORK/fresh_home"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+if [ "$(grep -c 'Added by Unsloth installer' "$WORK/fresh_home/.profile")" = "1" ]; then+ ok "the created profile is written once, not once per run"+else+ bad "the created profile is written once, not once per run"+fi++# The digest belongs inside the mirror loop. A proxy answering 200 with its own body is a+# successful download by every measure Invoke-WebRequest has, and checking once afterwards spends+# the only attempt on it and never reaches the mirror that would have served the real archive.+for _ps in "$SCRIPT_DIR/../../install.ps1" "$SCRIPT_DIR/../../studio/setup.ps1"; do+ _dl_line=$(grep -n 'if (-not \$downloaded) { return \$false }' "$_ps" | head -1 | cut -d: -f1)+ _hash_line=$(grep -n 'Get-FileHash -LiteralPath \$zip' "$_ps" | head -1 | cut -d: -f1)+ if [ -n "$_dl_line" ] && [ -n "$_hash_line" ] && [ "$_hash_line" -lt "$_dl_line" ]; then+ ok "${_ps##*/} verifies each uv mirror before it stops trying them"+ else+ bad "${_ps##*/} verifies each uv mirror before it stops trying them"+ fi+done++# A configured uv mirror is exclusive: a restricted network sets one because the public hosts are+# unreachable, and download() has no timeout, so trying them first stalls instead of falling back.+for _impl in "$INSTALL_SH" "$SCRIPT_DIR/../../studio/setup.sh"; do+ if grep -q 'UV_INSTALLER_GHE_BASE_URL' "$_impl" && grep -q 'UV_INSTALLER_GITHUB_BASE_URL' "$_impl"; then+ ok "${_impl##*/} honours a configured uv mirror"+ else+ bad "${_impl##*/} honours a configured uv mirror"+ fi+done++# The staging name must be unique per process. Two installers sharing one fixed staging path let+# the loser keep writing through its open descriptor after the winner renamed that inode into+# place, publishing a truncated uv. mktemp in the destination directory is what makes the rename+# a swap of a file nobody else can still be writing.+for _impl in "$INSTALL_SH" "$SCRIPT_DIR/../../studio/setup.sh"; do+ if grep -qE 'mktemp "\$_[a-z]+_dest/\.\$_[a-z]+_exe\.XXXXXX"' "$_impl" \+ && ! grep -q 'unsloth-new' "$_impl"; then+ ok "${_impl##*/} stages the uv copy under a per-process name"+ else+ bad "${_impl##*/} stages the uv copy under a per-process name"+ fi+done++# astral honours UV_DOWNLOAD_URL and its alias INSTALLER_DOWNLOAD_URL ahead of the mirror+# variables, and a host that sets one usually cannot reach the public endpoints, so trying those+# first stalls instead of falling back. All four implementations have to agree on that order.+for _impl in "$INSTALL_SH" "$SCRIPT_DIR/../../studio/setup.sh" \+ "$SCRIPT_DIR/../../install.ps1" "$SCRIPT_DIR/../../studio/setup.ps1"; do+ if grep -q 'UV_DOWNLOAD_URL' "$_impl" && grep -q 'INSTALLER_DOWNLOAD_URL' "$_impl"; then+ ok "${_impl##*/} honours astral's primary download override"+ else+ bad "${_impl##*/} honours astral's primary download override"+ fi+done++# 0755, not the umask default: astral ships these executable for everyone, and a umask of 077+# would otherwise leave uv unusable for other accounts on a shared machine.+for _impl in "$INSTALL_SH" "$SCRIPT_DIR/../../studio/setup.sh"; do+ if grep -q 'chmod 0755' "$_impl" && ! grep -qE 'chmod \+x "\$_[a-z]+_stage"' "$_impl"; then+ ok "${_impl##*/} stages uv with an explicit 0755"+ else+ bad "${_impl##*/} stages uv with an explicit 0755"+ fi+done++# astral's destination priority puts XDG_DATA_HOME/../bin between XDG_BIN_HOME and the home+# default. An implementation that skips that tier drops uv under ~/.local/bin on a host that+# configured an XDG location, where no later shell looks for it.+for _impl in "$INSTALL_SH" "$SCRIPT_DIR/../../studio/setup.sh" \+ "$SCRIPT_DIR/../../install.ps1" "$SCRIPT_DIR/../../studio/setup.ps1"; do+ if grep -q 'XDG_DATA_HOME' "$_impl"; then+ ok "${_impl##*/} honours the XDG_DATA_HOME destination tier"+ else+ bad "${_impl##*/} honours the XDG_DATA_HOME destination tier"+ fi+done++# ── behaviour ──+echo "=== behaviour ==="++# Drive the helper block from install.sh with a stubbed downloader: offline, sandboxed.+awk '/^# ── uv from a pinned release ──$/,/^if ! command -v uv /' "$INSTALL_SH" \+ | sed '$d' > "$WORK/uvfns.sh"++# Stand-in for the real archive: same uv-<triple>/{uv,uvx} layout.+mkdir -p "$WORK/src/uv-fake-triple"+printf '#!/bin/sh\necho "uv 0.12.1 (fake)"\n' > "$WORK/src/uv-fake-triple/uv"+printf '#!/bin/sh\necho "uvx"\n' > "$WORK/src/uv-fake-triple/uvx"+tar -czf "$WORK/uv-fake.tar.gz" -C "$WORK/src" uv-fake-triple+if command -v sha256sum >/dev/null 2>&1; then+ FIXTURE_SHA=$(sha256sum "$WORK/uv-fake.tar.gz" | awk '{print $1}')+else+ FIXTURE_SHA=$(shasum -a 256 "$WORK/uv-fake.tar.gz" | awk '{print $1}')+fi++run_case() {+ # $ADVERTISED = the digest the pin claims, $1 = HOME for the run+ _rc_home="$1"+ mkdir -p "$_rc_home"+ (+ set +e+ tauri_log() { :; }+ # shellcheck disable=SC1090+ . "$WORK/uvfns.sh"+ # Stub the host lookup and the transport, not the installer: the point under test+ # is the verify/extract/place path.+ _uv_pinned_asset() { echo "uv-fake.tar.gz $ADVERTISED"; }+ download() { cp -f "$WORK/uv-fake.tar.gz" "$2"; }+ HOME="$_rc_home"+ unset UV_INSTALL_DIR UV_UNMANAGED_INSTALL XDG_BIN_HOME+ if [ -n "${CASE_XDG_DATA_HOME:-}" ]; then+ export XDG_DATA_HOME="$CASE_XDG_DATA_HOME"+ else+ unset XDG_DATA_HOME+ fi+ _uv_install_pinned+ echo "rc=$?"+ )+}++ADVERTISED="$FIXTURE_SHA" run_case "$WORK/home_ok" > "$WORK/out_ok" 2>&1 || true+if grep -q '^rc=0$' "$WORK/out_ok" && [ -x "$WORK/home_ok/.local/bin/uv" ]; then+ ok "a matching digest installs uv into the default destination"+else+ bad "a matching digest installs uv into the default destination"+ sed 's/^/ /' "$WORK/out_ok"+fi++if [ -x "$WORK/home_ok/.local/bin/uvx" ]; then+ ok "uvx is installed alongside uv"+else+ bad "uvx is installed alongside uv"+fi++# XDG_DATA_HOME/../bin wins over the home default, as it does for astral's installer.+ADVERTISED="$FIXTURE_SHA" CASE_XDG_DATA_HOME="$WORK/home_xdg/share" \+ run_case "$WORK/home_xdg" > "$WORK/out_xdg" 2>&1 || true+if [ -x "$WORK/home_xdg/bin/uv" ] && [ ! -e "$WORK/home_xdg/.local/bin/uv" ]; then+ ok "XDG_DATA_HOME redirects the install away from the home default"+else+ bad "XDG_DATA_HOME redirects the install away from the home default"+ sed 's/^/ /' "$WORK/out_xdg"+fi++ADVERTISED="0000000000000000000000000000000000000000000000000000000000000000" \+ run_case "$WORK/home_bad" > "$WORK/out_bad" 2>&1 || true+if grep -q '^rc=0$' "$WORK/out_bad"; then+ bad "a mismatched digest is rejected"+else+ ok "a mismatched digest is rejected"+fi+if [ -e "$WORK/home_bad/.local/bin/uv" ]; then+ bad "a rejected archive installs nothing"+else+ ok "a rejected archive installs nothing"+fi++# Repeat application. The installer is re-run on every upgrade and every repair, so the second+# and third pass over the same HOME must land on the same tree, not accumulate or half-replace.+_sig() { printf '%s|%s' "$(cd "$1" && find . -type f | LC_ALL=C sort | tr '\n' ' ')" \+ "$(cat "$1/.local/bin/uv" 2>/dev/null)"; }+_idem_ok=1+_idem_sig=""+for _i in 1 2 3; do+ ADVERTISED="$FIXTURE_SHA" run_case "$WORK/home_idem" > "$WORK/out_idem_$_i" 2>&1 || true+ grep -q '^rc=0$' "$WORK/out_idem_$_i" || _idem_ok=0+ _s=$(_sig "$WORK/home_idem")+ [ -z "$_idem_sig" ] && _idem_sig="$_s"+ [ "$_s" = "$_idem_sig" ] || _idem_ok=0+done+if [ "$_idem_ok" = 1 ]; then+ ok "runs 1..3 over the same HOME leave an identical tree"+else+ bad "repeat application is not idempotent"+ sed 's/^/ /' "$WORK/out_idem_3"+fi++# A stale uv from an older install is replaced in place. Two copies under one destination would+# leave PATH order deciding which one runs.+printf 'stale binary' > "$WORK/home_idem/.local/bin/uv"+ADVERTISED="$FIXTURE_SHA" run_case "$WORK/home_idem" > "$WORK/out_replace" 2>&1 || true+if grep -q 'fake' "$WORK/home_idem/.local/bin/uv" 2>/dev/null \+ && [ "$(cd "$WORK/home_idem" && find . -name uv -type f | wc -l | tr -d ' ')" = 1 ]; then+ ok "an existing uv at the destination is replaced in place"+else+ bad "an existing uv at the destination is replaced in place"+fi++# A destination that is a symlink must be replaced, not written through. `~/.local/bin/uv ->+# /opt/homebrew/bin/uv` is an ordinary layout, and a plain cp there rewrites Homebrew's binary.+mkdir -p "$WORK/home_link/.local/bin" "$WORK/elsewhere"+printf 'other package manager owns this' > "$WORK/elsewhere/uv"+_link_before=$(sha256sum "$WORK/elsewhere/uv" 2>/dev/null || shasum -a 256 "$WORK/elsewhere/uv")+ln -sf "$WORK/elsewhere/uv" "$WORK/home_link/.local/bin/uv"+ADVERTISED="$FIXTURE_SHA" run_case "$WORK/home_link" > "$WORK/out_link" 2>&1 || true+_link_after=$(sha256sum "$WORK/elsewhere/uv" 2>/dev/null || shasum -a 256 "$WORK/elsewhere/uv")+if [ "$_link_before" = "$_link_after" ]; then+ ok "a symlinked destination is not written through"+else+ bad "the install rewrote the file the destination symlink pointed at"+fi+if [ ! -L "$WORK/home_link/.local/bin/uv" ] && grep -q 'fake' "$WORK/home_link/.local/bin/uv" 2>/dev/null; then+ ok "the symlink itself is replaced by the installed uv"+else+ bad "the symlink itself is replaced by the installed uv"+fi+# The staging file must not survive a run, or the destination collects debris on every upgrade.+if [ -z "$(find "$WORK/home_link/.local/bin" -name '.uv.*' 2>/dev/null)" ]; then+ ok "no staging file is left behind"+else+ bad "no staging file is left behind"+fi++# A binary that cannot execute must decline, not report success. The executable bit says nothing+# about whether the loader a GNU binary asks for exists: a stripped NixOS-derived image reads a+# glibc version from getconf, passes every static check, and then fails on first use with the+# fallback already skipped. Stand in for that with an archive whose uv cannot run.+mkdir -p "$WORK/src_bad/uv-fake-triple"+printf '\177ELF not a real loader target\n' > "$WORK/src_bad/uv-fake-triple/uv"+printf '#!/bin/sh\necho uvx\n' > "$WORK/src_bad/uv-fake-triple/uvx"+tar -czf "$WORK/uv-bad.tar.gz" -C "$WORK/src_bad" uv-fake-triple+if command -v sha256sum >/dev/null 2>&1; then+ BAD_EXEC_SHA=$(sha256sum "$WORK/uv-bad.tar.gz" | awk '{print $1}')+else+ BAD_EXEC_SHA=$(shasum -a 256 "$WORK/uv-bad.tar.gz" | awk '{print $1}')+fi+mkdir -p "$WORK/home_noexec"+(+ set +e+ tauri_log() { :; }+ # shellcheck disable=SC1090+ . "$WORK/uvfns.sh"+ _uv_pinned_asset() { echo "uv-bad.tar.gz $BAD_EXEC_SHA"; }+ download() { cp -f "$WORK/uv-bad.tar.gz" "$2"; }+ HOME="$WORK/home_noexec"; export HOME+ unset UV_INSTALL_DIR UV_UNMANAGED_INSTALL XDG_BIN_HOME XDG_DATA_HOME+ _uv_install_pinned+ echo "rc=$?"+) > "$WORK/out_noexec" 2>&1 || true+if grep -q '^rc=0$' "$WORK/out_noexec"; then+ bad "a uv that cannot execute declines to the fallback"+else+ ok "a uv that cannot execute declines to the fallback"+fi++# And it must not have destroyed the uv the host was already using. The rename publishes over the+# destination, so validating the new binary only after that point would leave a host whose loader+# is missing with neither its old working uv nor a usable new one, while _uv_present_before still+# says one is installed.+mkdir -p "$WORK/home_keep/.local/bin"+printf '#!/bin/sh\necho "uv 0.9.9 (incumbent)"\n' > "$WORK/home_keep/.local/bin/uv"+chmod +x "$WORK/home_keep/.local/bin/uv"+(+ set +e+ tauri_log() { :; }+ # shellcheck disable=SC1090+ . "$WORK/uvfns.sh"+ _uv_pinned_asset() { echo "uv-bad.tar.gz $BAD_EXEC_SHA"; }+ download() { cp -f "$WORK/uv-bad.tar.gz" "$2"; }+ HOME="$WORK/home_keep"; export HOME+ unset UV_INSTALL_DIR UV_UNMANAGED_INSTALL XDG_BIN_HOME XDG_DATA_HOME+ _uv_install_pinned+) >/dev/null 2>&1 || true+if "$WORK/home_keep/.local/bin/uv" 2>/dev/null | grep -q incumbent; then+ ok "a uv that cannot execute never replaces the working one"+else+ bad "a uv that cannot execute replaced the working one"+fi+if [ -z "$(find "$WORK/home_keep/.local/bin" -name '.uv.*' 2>/dev/null)" ]; then+ ok "the rejected staging file is cleaned up"+else+ bad "the rejected staging file is cleaned up"+fi+# uv and uvx ship as a set. When uv is rejected the loop must abandon the whole placement, not+# carry on and publish the pinned uvx beside whatever older uv the host already had, which is a+# pairing we never build or test.+if [ -f "$WORK/home_keep/.local/bin/uvx" ]; then+ bad "a rejected uv must not publish its uvx"+else+ ok "a rejected uv must not publish its uvx"+fi++# The probe runs a binary that was just downloaded, so it has to be bounded on both of the ways+# such a binary can fail to return: reading stdin, and never exiting. Neither may hold an+# unattended install open.+mkdir -p "$WORK/src_hang/uv-fake-triple"+# Reads a line from stdin, so with the installer's console attached it would block forever;+# with </dev/null the read hits EOF at once. Then sleeps past the ceiling, so an unbounded+# wait would hang here instead.+printf '#!/bin/sh\nread _line\nsleep 120\n' > "$WORK/src_hang/uv-fake-triple/uv"+chmod +x "$WORK/src_hang/uv-fake-triple/uv"+printf '#!/bin/sh\necho uvx\n' > "$WORK/src_hang/uv-fake-triple/uvx"+tar -czf "$WORK/uv-hang.tar.gz" -C "$WORK/src_hang" uv-fake-triple+if command -v sha256sum >/dev/null 2>&1; then+ HANG_SHA=$(sha256sum "$WORK/uv-hang.tar.gz" | awk '{print $1}')+else+ HANG_SHA=$(shasum -a 256 "$WORK/uv-hang.tar.gz" | awk '{print $1}')+fi+mkdir -p "$WORK/home_hang"+_HANG_START=$(date +%s)+(+ set +e+ tauri_log() { :; }+ # shellcheck disable=SC1090+ . "$WORK/uvfns.sh"+ _uv_pinned_asset() { echo "uv-hang.tar.gz $HANG_SHA"; }+ download() { cp -f "$WORK/uv-hang.tar.gz" "$2"; }+ HOME="$WORK/home_hang"; export HOME+ unset UV_INSTALL_DIR UV_UNMANAGED_INSTALL XDG_BIN_HOME XDG_DATA_HOME+ _uv_install_pinned+ echo "rc=$?"+) > "$WORK/out_hang" 2>&1 || true+_HANG_ELAPSED=$(( $(date +%s) - _HANG_START ))+# 40s, not 20: the ceiling only applies where `timeout` exists, and a host without it still has+# to come back because stdin is closed. Either way this must not run for two minutes.+if [ "$_HANG_ELAPSED" -lt 40 ] && grep -q '^rc=1$' "$WORK/out_hang"; then+ ok "the executable probe is bounded and declines (${_HANG_ELAPSED}s)"+else+ bad "the executable probe is bounded and declines (${_HANG_ELAPSED}s, $(cat "$WORK/out_hang"))"+fi++# Host matrix. A wrong triple installs a binary that cannot execute, which is worse than not+# installing at all, so every host must either get its own triple or decline to the fallback.+# $4 libc: musl | none (no ldd and no getconf) | a glibc version | rosetta (Darwin only)+# $5 bits: what getconf LONG_BIT reports, so a 32-bit userland on a 64-bit kernel is covered.+_probe_asset() { # $1 fn, $2 os, $3 arch, $4 libc, $5 bits+ (+ set +e+ # Bind before the stubs: inside a function body $2..$5 are the stub's own arguments.+ _pa_os="$2"; _pa_arch="$3"; _pa_libc="$4"; _pa_bits="$5"+ tauri_log() { :; }+ # shellcheck disable=SC1090+ . "$WORK/uvfns.sh"+ uname() { case "${1:-}" in -m) echo "$_pa_arch" ;; *) echo "$_pa_os" ;; esac; }+ ldd() {+ case "$_pa_libc" in+ musl) echo "musl libc (x86_64)" ;;+ none) return 127 ;;+ *) echo "ldd (Ubuntu GLIBC $_pa_libc-0ubuntu1) $_pa_libc" ;;+ esac+ }+ getconf() {+ case "${1:-}" in+ LONG_BIT) echo "$_pa_bits" ;;+ GNU_LIBC_VERSION) [ "$_pa_libc" = none ] && return 1; echo "glibc $_pa_libc" ;;+ esac+ }+ sysctl() { [ "$_pa_libc" = rosetta ] && echo 1; }+ "$1" 2>/dev/null+ )+}+_matrix_bad=0+# "<os> <arch> <libc> <bits> <expected triple, or - to decline>"+while read -r _m_os _m_arch _m_libc _m_bits _m_want; do+ [ -n "$_m_os" ] || continue+ # `|| _m_got=`: a declining host exits non-zero, and set -e would end the run here.+ _m_got=$(_probe_asset _uv_pinned_asset "$_m_os" "$_m_arch" "$_m_libc" "$_m_bits") || _m_got=""+ _m_label="$_m_os/$_m_arch/$_m_libc/$_m_bits"+ if [ "$_m_want" = "-" ]; then+ [ -z "$_m_got" ] || { echo " $_m_label should decline, got '$_m_got'"; _matrix_bad=$((_matrix_bad + 1)); }+ else+ case "$_m_got" in+ "uv-$_m_want.tar.gz "*) : ;;+ *) echo " $_m_label expected $_m_want, got '$_m_got'"; _matrix_bad=$((_matrix_bad + 1)) ;;+ esac+ fi+done <<'MATRIX'+Linux x86_64 2.35 64 x86_64-unknown-linux-gnu+Linux amd64 2.35 64 x86_64-unknown-linux-gnu+Linux aarch64 2.35 64 aarch64-unknown-linux-gnu+Linux arm64 2.28 64 aarch64-unknown-linux-gnu+Linux x86_64 2.17 64 x86_64-unknown-linux-gnu+Darwin x86_64 2.35 64 x86_64-apple-darwin+Darwin arm64 2.35 64 aarch64-apple-darwin+Darwin aarch64 2.35 64 aarch64-apple-darwin+Darwin x86_64 rosetta 64 aarch64-apple-darwin+Linux x86_64 musl 64 -+Linux aarch64 musl 64 -+Linux x86_64 none 64 -+Linux aarch64 none 64 -+Linux x86_64 2.12 64 -+Linux aarch64 2.27 64 -+Linux x86_64 2.35 32 -+Linux aarch64 2.35 32 -+Linux armv7l 2.35 64 -+Linux i686 2.35 64 -+Linux ppc64le 2.35 64 -+Linux riscv64 2.35 64 -+Linux s390x 2.35 64 -+Darwin i386 2.35 64 -+FreeBSD x86_64 2.35 64 -+SunOS x86_64 2.35 64 -+MINGW64_NT-10.0 x86_64 2.35 64 -+CYGWIN_NT-10.0 x86_64 2.35 64 -+unknown unknown 2.35 64 -+MATRIX+if [ "$_matrix_bad" = 0 ]; then+ ok "every host either gets its own triple or declines to the fallback"+else+ bad "the host matrix has $_matrix_bad wrong outcomes"+fi++# An unpinned host must decline, so the caller falls back instead of installing nothing.+(+ set +e+ tauri_log() { :; }+ # shellcheck disable=SC1090+ . "$WORK/uvfns.sh"+ uname() { if [ "$1" = "-s" ]; then echo Linux; else echo sparc64; fi; }+ _uv_pinned_asset >/dev/null 2>&1+ echo "rc=$?"+) > "$WORK/out_arch" 2>&1 || true+if grep -q '^rc=0$' "$WORK/out_arch"; then+ bad "an unpinned architecture declines so the fallback runs"+else+ ok "an unpinned architecture declines so the fallback runs"+fi+++# An interrupted install must not leave the pinned path's temporaries behind: the work+# directory holds a ~40 MB unpacked archive, and the staging file sits inside a directory that+# is on PATH. The helper's own cleanup only runs when it returns normally, so both have to be+# reachable from the signal and exit traps.+_cleanup_body=$(awk '/^_cleanup_install_temporaries\(\) \{/,/^\}/' "$INSTALL_SH")+if printf '%s' "$_cleanup_body" | grep -q '_UIP_WORK' && printf '%s' "$_cleanup_body" | grep -q '_UIP_STAGE'; then+ ok "the pinned uv temporaries are removed by the interrupt cleanup"+else+ bad "the pinned uv temporaries are removed by the interrupt cleanup"+fi+if grep -q '^_UIP_WORK=""' "$INSTALL_SH" && grep -q '_UIP_WORK="\$_uip_work"' "$INSTALL_SH" \+ && grep -q '_UIP_STAGE="\$_uip_stage"' "$INSTALL_SH"; then+ ok "the pinned uv temporaries are published to the trap as they are created"+else+ bad "the pinned uv temporaries are published to the trap as they are created"+fi+# fish sources none of the POSIX rc files, so an `export` line in ~/.profile is a no-op for a+# fish user: the install works in this process and the next session resolves neither uv nor the+# unsloth shim.+mkdir -p "$WORK/fish_home/.local/bin"+(+ set +e+ step() { :; }+ HOME="$WORK/fish_home"; export HOME+ SHELL="/usr/bin/fish"; export SHELL+ unset ZSH_VERSION XDG_CONFIG_HOME+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+if grep -q 'fish_add_path' "$WORK/fish_home/.config/fish/conf.d/unsloth.fish" 2>/dev/null \+ && [ ! -f "$WORK/fish_home/.profile" ]; then+ ok "a fish login shell gets a fish drop-in, not an ignored ~/.profile"+else+ bad "a fish login shell gets a fish drop-in, not an ignored ~/.profile"+fi++# uv can land somewhere other than ~/.local/bin (UV_INSTALL_DIR and friends outrank it), and+# astral's installer wrote a PATH line for whichever directory it picked. The pinned path+# replaces that installer, so it has to persist its own destination too.+mkdir -p "$WORK/uvdir_home/.local/bin" "$WORK/uvdir_home/opt/uvbin"+: > "$WORK/uvdir_home/.bashrc"+(+ set +e+ step() { :; }+ HOME="$WORK/uvdir_home"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION UV_NO_MODIFY_PATH+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ _UNSLOTH_UV_BIN_DIR="$HOME/opt/uvbin"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+if grep -qF "$WORK/uvdir_home/opt/uvbin" "$WORK/uvdir_home/.bashrc" 2>/dev/null; then+ ok "a custom uv install directory reaches the next shell"+else+ bad "a custom uv install directory reaches the next shell"+fi+# ...and UV_NO_MODIFY_PATH is astral's opt-out, so it has to be honoured here for the same+# reason it is honoured there.+mkdir -p "$WORK/uvopt_home/.local/bin" "$WORK/uvopt_home/opt/uvbin"+: > "$WORK/uvopt_home/.bashrc"+(+ set +e+ step() { :; }+ HOME="$WORK/uvopt_home"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION+ UV_NO_MODIFY_PATH=1; export UV_NO_MODIFY_PATH+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ _UNSLOTH_UV_BIN_DIR="$HOME/opt/uvbin"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+if grep -qF "$WORK/uvopt_home/opt/uvbin" "$WORK/uvopt_home/.bashrc" 2>/dev/null; then+ bad "UV_NO_MODIFY_PATH still suppresses the uv directory write"+else+ ok "UV_NO_MODIFY_PATH still suppresses the uv directory write"+fi++# A path with a space is two arguments to fish_add_path and neither of them exists, so the+# drop-in has to quote. The home directory alone is enough to hit this.+mkdir -p "$WORK/fish sp home/.local/bin"+(+ set +e+ step() { :; }+ HOME="$WORK/fish sp home"; export HOME+ SHELL="/usr/bin/fish"; export SHELL+ unset ZSH_VERSION XDG_CONFIG_HOME+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+_fish_line=$(grep 'fish_add_path' "$WORK/fish sp home/.config/fish/conf.d/unsloth.fish" 2>/dev/null)+if [ "$_fish_line" = "fish_add_path '$WORK/fish sp home/.local/bin'" ]; then+ ok "a fish path with a space is written as one quoted argument"+else+ bad "a fish path with a space is written as one quoted argument ($_fish_line)"+fi++# The rc line is written inside double quotes, so a custom uv directory holding $ or a backtick+# would be expanded by the shell that reads it rather than treated as a path.+mkdir -p "$WORK/uvmeta_home/.local/bin" "$WORK/uvmeta_home/opt/a\$b/bin"+: > "$WORK/uvmeta_home/.bashrc"+(+ set +e+ step() { :; }+ HOME="$WORK/uvmeta_home"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION UV_NO_MODIFY_PATH+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ _UNSLOTH_UV_BIN_DIR="$HOME/opt/a\$b/bin"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+# Read it back the way a login shell would: source the file and ask what PATH holds.+_uvmeta_path=$(HOME="$WORK/uvmeta_home"; PATH="/usr/bin:/bin"; . "$WORK/uvmeta_home/.bashrc" 2>/dev/null; printf '%s' "$PATH")+case ":$_uvmeta_path:" in+ *":$WORK/uvmeta_home/opt/a\$b/bin:"*)+ ok "a uv directory holding shell metacharacters survives the rc round trip" ;;+ *)+ bad "a uv directory holding shell metacharacters survives the rc round trip" ;;+esac++# Publishing uv and then failing to publish uvx must put the incumbent uv back. The caller+# treats a non-zero return as "fall back to astral's installer", but that installer can be+# unreachable, and a host that had a working pair must not be left with a new uv beside its old+# uvx. Made to fail by pointing uvx's destination at a directory, which no rename can replace.+mkdir -p "$WORK/home_half/.local/bin"+printf '#!/bin/sh\necho "uv 0.9.9 (incumbent)"\n' > "$WORK/home_half/.local/bin/uv"+printf '#!/bin/sh\necho "uvx 0.9.9 (incumbent)"\n' > "$WORK/home_half/.local/bin/uvx"+chmod +x "$WORK/home_half/.local/bin/uv" "$WORK/home_half/.local/bin/uvx"+(+ set +e+ tauri_log() { :; }+ # Fail the second rename only. A directory at the destination would not do it: `mv f d`+ # moves f INTO d and reports success, which is itself worth knowing.+ mv() {+ case "$*" in+ *"/uvx") return 1 ;;+ esac+ command mv "$@"+ }+ # shellcheck disable=SC1090+ . "$WORK/uvfns.sh"+ _uv_pinned_asset() { echo "uv-fake.tar.gz $FIXTURE_SHA"; }+ download() { cp -f "$WORK/uv-fake.tar.gz" "$2"; }+ HOME="$WORK/home_half"; export HOME+ unset UV_INSTALL_DIR UV_UNMANAGED_INSTALL XDG_BIN_HOME XDG_DATA_HOME+ _uv_install_pinned+ echo "rc=$?"+) > "$WORK/out_half" 2>&1 || true+if grep -q '^rc=0$' "$WORK/out_half"; then+ bad "a half-published pair declines to the fallback"+else+ ok "a half-published pair declines to the fallback"+fi+if [ -z "$(find "$WORK/home_half/.local/bin" -maxdepth 1 -name '.uv*' 2>/dev/null)" ]; then+ ok "the half-published staging and undo files are cleaned up"+else+ bad "the half-published staging and undo files are cleaned up"+fi++# studio/setup.sh is run directly for local and Colab setup, and astral's installer used to+# write a profile line for whichever destination it chose. Without one the export dies with that+# shell and every later run reinstalls uv.+SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"+SETUP_PS1="$SCRIPT_DIR/../../studio/setup.ps1"+_sp_start=$(grep -n '^_setup_persist_uv_path() {' "$SETUP_SH" | head -1 | cut -d: -f1)+_sp_end=$(awk -v s="$_sp_start" 'NR>s && /^\}$/ {print NR; exit}' "$SETUP_SH")+sed -n "${_sp_start},${_sp_end}p" "$SETUP_SH" > "$WORK/setup_path.sh"+mkdir -p "$WORK/setup_home" "$WORK/setup_home/opt/bin"+: > "$WORK/setup_home/.bashrc"+(+ set +e+ HOME="$WORK/setup_home"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION UV_NO_MODIFY_PATH UV_UNMANAGED_INSTALL+ _SETUP_LOGIN_PATH="/usr/bin:/bin"+ # shellcheck disable=SC1090+ . "$WORK/setup_path.sh"+ _setup_persist_uv_path "$HOME/opt/bin"+) >/dev/null 2>&1 || true+if grep -qF "$WORK/setup_home/opt/bin" "$WORK/setup_home/.bashrc" 2>/dev/null; then+ ok "a direct setup.sh run persists the uv destination"+else+ bad "a direct setup.sh run persists the uv destination"+fi+# ...and the same mention-only trap as install.sh: PYTHONPATH holds the text PATH, so only a+# name boundary keeps it from passing for an entry.+mkdir -p "$WORK/setup_mention" "$WORK/setup_mention/opt/bin"+printf 'export PYTHONPATH="%s/opt/bin"\n' "$WORK/setup_mention" > "$WORK/setup_mention/.bashrc"+(+ set +e+ HOME="$WORK/setup_mention"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION UV_NO_MODIFY_PATH UV_UNMANAGED_INSTALL+ _SETUP_LOGIN_PATH="/usr/bin:/bin"+ # shellcheck disable=SC1090+ . "$WORK/setup_path.sh"+ _setup_persist_uv_path "$HOME/opt/bin"+) >/dev/null 2>&1 || true+if grep -q 'export PATH=' "$WORK/setup_mention/.bashrc" 2>/dev/null; then+ ok "setup.sh writes past a non-PATH mention of the destination"+else+ bad "setup.sh writes past a non-PATH mention of the destination"+fi++mkdir -p "$WORK/setup_unmanaged" "$WORK/setup_unmanaged/opt/bin"+: > "$WORK/setup_unmanaged/.bashrc"+(+ set +e+ HOME="$WORK/setup_unmanaged"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION UV_NO_MODIFY_PATH+ UV_UNMANAGED_INSTALL=1; export UV_UNMANAGED_INSTALL+ _SETUP_LOGIN_PATH="/usr/bin:/bin"+ # shellcheck disable=SC1090+ . "$WORK/setup_path.sh"+ _setup_persist_uv_path "$HOME/opt/bin"+) >/dev/null 2>&1 || true+if grep -qF "$WORK/setup_unmanaged/opt/bin" "$WORK/setup_unmanaged/.bashrc" 2>/dev/null; then+ bad "UV_UNMANAGED_INSTALL suppresses the setup.sh profile write"+else+ ok "UV_UNMANAGED_INSTALL suppresses the setup.sh profile write"+fi++# A destination holding a glob character is a pattern inside a case arm, so `/opt/*` counted as+# present whenever the inherited PATH held any /opt entry and the persistence was skipped.+mkdir -p "$WORK/glob_home/.local/bin" "$WORK/glob_home/opt/star"+: > "$WORK/glob_home/.bashrc"+(+ set +e+ step() { :; }+ HOME="$WORK/glob_home"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION UV_NO_MODIFY_PATH UV_UNMANAGED_INSTALL+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="$HOME/opt/star:/usr/bin"+ _UNSLOTH_UV_BIN_DIR="$HOME/opt/*"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+if grep -qF 'opt/*' "$WORK/glob_home/.bashrc" 2>/dev/null; then+ ok "a uv directory holding a glob character is compared literally"+else+ bad "a uv directory holding a glob character is compared literally"+fi++# The fish escapers have to be valid sed. Run them rather than reading them: the setup.sh copy+# reached sed as `s/\/\\/g` and would have killed setup under set -e after uv was published.+for _impl in "$INSTALL_SH" "$SETUP_SH"; do+ _esc_line=$(grep -h 'sed "s/' "$_impl" | grep 'fish\|_quoted=' | head -1)+ _esc_expr=${_esc_line#*| }+ if [ -n "$_esc_expr" ] && printf '%s' "/opt/a b" | eval "${_esc_expr%\)}" >/dev/null 2>&1; then+ ok "${_impl##*/} escapes fish paths with a valid sed expression"+ else+ bad "${_impl##*/} escapes fish paths with a valid sed expression"+ fi+done++# A commented-out old export is not an active PATH entry, and neither is a directory that merely+# starts with ours. Taking either for one leaves the next shell unable to resolve uv.+for _case in comment prefix; do+ _ch="$WORK/entry_$_case"+ mkdir -p "$_ch/.local/bin" "$_ch/opt/uv"+ if [ "$_case" = comment ]; then+ printf '# export PATH="%s/opt/uv:$PATH"\n' "$_ch" > "$_ch/.bashrc"+ else+ printf 'export PATH="%s/opt/uv-old:$PATH"\n' "$_ch" > "$_ch/.bashrc"+ fi+ (+ set +e+ step() { :; }+ HOME="$_ch"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION UV_NO_MODIFY_PATH UV_UNMANAGED_INSTALL+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ _UNSLOTH_UV_BIN_DIR="$HOME/opt/uv"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+ ) >/dev/null 2>&1 || true+ # Count only ACTIVE lines naming the uv directory exactly: the ~/.local/bin line is written+ # too and would mask the answer.+ # `|| _n=0`: grep -c exits non-zero on no match and set -e would take the suite down.+ _n=$(grep -v '^[[:space:]]*#' "$_ch/.bashrc" | grep -cE "(^|[^[:alnum:]_.~/-])$_ch/opt/uv([^[:alnum:]_.~/-]|$)") || _n=0+ if [ "$_n" = "1" ]; then+ ok "an inactive entry ($_case) does not suppress the uv PATH write"+ else+ bad "an inactive entry ($_case) does not suppress the uv PATH write (active lines: $_n)"+ fi+done+# ...and a genuinely active entry still suppresses it, so the write stays idempotent.+_ch="$WORK/entry_active"+mkdir -p "$_ch/.local/bin" "$_ch/opt/uv"+printf 'export PATH="%s/opt/uv:$PATH"\n' "$_ch" > "$_ch/.bashrc"+(+ set +e+ step() { :; }+ HOME="$_ch"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION UV_NO_MODIFY_PATH UV_UNMANAGED_INSTALL+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ _UNSLOTH_UV_BIN_DIR="$HOME/opt/uv"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+_n=$(grep -v '^[[:space:]]*#' "$_ch/.bashrc" | grep -cE "(^|[^[:alnum:]_.~/-])$_ch/opt/uv([^[:alnum:]_.~/-]|$)") || _n=0+if [ "$_n" = "1" ]; then+ ok "an active entry still suppresses the uv PATH write"+else+ bad "an active entry still suppresses the uv PATH write (active lines: $_n)"+fi++# Both installers put the pinned destination back in front of PATH after the ~/.local/bin+# prepend that follows them, or a stale uv there shadows the one that was just verified.+if grep -q 'export PATH="\$_UNSLOTH_UV_BIN_DIR:\$PATH"' "$INSTALL_SH"; then+ ok "install.sh keeps the pinned uv destination ahead of ~/.local/bin"+else+ bad "install.sh keeps the pinned uv destination ahead of ~/.local/bin"+fi+if grep -q '\[ "\$_SETUP_UV_PINNED_OK" = true \] || export PATH="\$HOME/.local/bin:\$PATH"' "$SETUP_SH"; then+ ok "setup.sh does not prepend ~/.local/bin over a pinned destination"+else+ bad "setup.sh does not prepend ~/.local/bin over a pinned destination"+fi++# The NSIS hooks run before the user can cancel and $INSTDIR can be a directory they chose, so+# the tidy-up only applies where our own executable already is.+_hooks="$SCRIPT_DIR/../../studio/src-tauri/windows/hooks.nsh"+_h_gates=$(grep -c 'FileExists} "$INSTDIR\\${MAINBINARYNAME}.exe"' "$_hooks") || _h_gates=0+_h_deletes=$(grep -c 'Delete "$INSTDIR\\install.sh"' "$_hooks") || _h_deletes=0+if [ "$_h_gates" = "2" ] && [ "$_h_deletes" = "2" ]; then+ ok "the NSIS hooks only tidy a directory that already holds an Unsloth install"+else+ bad "the NSIS hooks only tidy a directory that already holds an Unsloth install"+fi++# astral's installer wired EVERY startup file it knew: ~/.profile, each bash file that exists,+# zsh under ZDOTDIR, and a fish drop-in. Writing only the one for the current shell would leave+# a bash user whose .bash_profile does not source .bashrc without uv on PATH, so the replacement+# has to cover the same set, once each.+_ph="$WORK/parity_home"+mkdir -p "$_ph/.local/bin" "$_ph/opt/uv"+: > "$_ph/.bashrc"; : > "$_ph/.bash_profile"; : > "$_ph/.zshrc"+for _pass in 1 2; do+ (+ set +e+ step() { :; }+ HOME="$_ph"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION ZDOTDIR UV_NO_MODIFY_PATH UV_UNMANAGED_INSTALL+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ _UNSLOTH_UV_BIN_DIR="$HOME/opt/uv"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+ ) >/dev/null 2>&1 || true+done+_missing=""+for _f in .profile .bashrc .bash_profile .zshrc .config/fish/conf.d/unsloth.fish; do+ _n=$(grep -c "opt/uv" "$_ph/$_f" 2>/dev/null) || _n=0+ [ "$_n" = "1" ] || _missing="$_missing $_f=$_n"+done+# .bash_login and .zshenv did not exist, so they must not have been created.+[ -f "$_ph/.bash_login" ] && _missing="$_missing .bash_login=created"+[ -f "$_ph/.zshenv" ] && _missing="$_missing .zshenv=created"+if [ -z "$_missing" ]; then+ ok "the uv PATH entry reaches every startup file astral wired, once each"+else+ bad "the uv PATH entry reaches every startup file astral wired, once each ($_missing)"+fi++# fish reads none of the POSIX files, so its drop-in is the only thing that puts uv on a fish+# user's PATH. A different directory already in that file must not pass for this one.+_fh="$WORK/fish_entry_home"+mkdir -p "$_fh/.config/fish/conf.d" "$_fh/.local/bin" "$_fh/opt/uv"+printf "# Added by Unsloth installer\nfish_add_path '%s/opt/uv-old'\n" "$_fh" > "$_fh/.config/fish/conf.d/unsloth.fish"+(+ set +e+ step() { :; }+ HOME="$_fh"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION ZDOTDIR UV_NO_MODIFY_PATH UV_UNMANAGED_INSTALL+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ _UNSLOTH_UV_BIN_DIR="$HOME/opt/uv"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+if grep -qxF "fish_add_path '$_fh/opt/uv'" "$_fh/.config/fish/conf.d/unsloth.fish"; then+ ok "a different fish entry does not suppress this one"+else+ bad "a different fish entry does not suppress this one"+fi++# A profile that merely NAMES the directory is not a profile that puts it on PATH:+# `UV_CACHE=$HOME/.local/bin` must not suppress the export, or the next shell finds no uv.+_mh="$WORK/mention_home"+mkdir -p "$_mh/.local/bin"+# PYTHONPATH is the trap for a naive "does the line mention a path" filter: it holds the text+# PATH, so only a name boundary keeps it out.+printf 'UV_CACHE="$HOME/.local/bin"\nexport PYTHONPATH="$HOME/.local/bin"\n' > "$_mh/.profile"+(+ set +e+ step() { :; }+ HOME="$_mh"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+) >/dev/null 2>&1 || true+if grep -q 'export PATH=' "$_mh/.profile"; then+ ok "a non-PATH mention of the directory does not suppress the export"+else+ bad "a non-PATH mention of the directory does not suppress the export"+fi++# A launcher on a UNC share is a remote script to PowerShell, and RemoteSigned refuses an+# unsigned one, so a roaming profile would get a shortcut that exits without starting Studio.+# A mapped drive is the same share and the same zone, so it must take the same branch.+_ps1="$SCRIPT_DIR/../../install.ps1"+if grep -q '\$launcherIsRemote = \$launcherPs1 -like "\\\\\*"' "$_ps1" \+ && grep -q "DriveType -eq 'Network'" "$_ps1" \+ && grep -q '"-NoProfile -ExecutionPolicy Bypass -File `"$launcherPs1`""' "$_ps1"; then+ ok "a UNC or mapped-drive launcher gets a policy that can actually load it"+else+ bad "a UNC or mapped-drive launcher gets a policy that can actually load it"+fi++# The DEFAULT install puts uv in ~/.local/bin, so the all-profile write must not be gated on the+# destination differing from it: gating there left every ordinary machine with the single-file+# write, which is the case that matters most.+_dh="$WORK/default_home"+mkdir -p "$_dh/.local/bin"+: > "$_dh/.bashrc"; : > "$_dh/.bash_profile"+for _pass in 1 2; do+ (+ set +e+ step() { :; }+ HOME="$_dh"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION ZDOTDIR UV_NO_MODIFY_PATH UV_UNMANAGED_INSTALL+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ _UNSLOTH_UV_BIN_DIR="$HOME/.local/bin"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+ ) >/dev/null 2>&1 || true+done+_dmiss=""+for _f in .profile .bashrc .bash_profile .config/fish/conf.d/unsloth.fish; do+ _n=$(grep -c "local/bin" "$_dh/$_f" 2>/dev/null) || _n=0+ [ "$_n" = "1" ] || _dmiss="$_dmiss $_f=$_n"+done+if [ -z "$_dmiss" ]; then+ ok "a default install wires every startup file, once each"+else+ bad "a default install wires every startup file, once each ($_dmiss)"+fi++# studio/setup.ps1 replaced astral's installer, so a failed pinned install needs somewhere to go+# or the whole setup silently drops to pip for torch and everything after it.+# The flag, not the return value: Invoke-SetupCommand hands back $LASTEXITCODE, so reading the+# function's $true through it always said "failed" and ran the fallback every time.+if grep -q 'if (-not $script:UvPinnedInstalled -and (Get-Command winget' "$SETUP_PS1" \+ && grep -q '$script:UvPinnedInstalled = $true' "$SETUP_PS1"; then+ ok "setup.ps1 still has a uv fallback when the pinned install fails"+else+ bad "setup.ps1 still has a uv fallback when the pinned install fails"+fi++# A directory named uv at the destination must not look like a published binary: `mv f d` moves+# into it and reports success, and a searchable directory passes -x.+mkdir -p "$WORK/home_dir_target/.local/bin/uv"+(+ set +e+ tauri_log() { :; }+ # shellcheck disable=SC1090+ . "$WORK/uvfns.sh"+ _uv_pinned_asset() { echo "uv-fake.tar.gz $FIXTURE_SHA"; }+ download() { cp -f "$WORK/uv-fake.tar.gz" "$2"; }+ HOME="$WORK/home_dir_target"; export HOME+ unset UV_INSTALL_DIR UV_UNMANAGED_INSTALL XDG_BIN_HOME XDG_DATA_HOME+ _uv_install_pinned+ echo "rc=$?"+) > "$WORK/out_dir_target" 2>&1 || true+if grep -q '^rc=0$' "$WORK/out_dir_target"; then+ bad "a directory at the destination declines to the fallback"+else+ ok "a directory at the destination declines to the fallback"+fi++# A destination holding an ERE metacharacter must still match itself on the next run, or every+# reinstall appends another PATH block to every profile.+_mh="$WORK/meta_home"+mkdir -p "$_mh/.local/bin" "$_mh/opt/a+b(c)"+: > "$_mh/.bashrc"+for _pass in 1 2; do+ (+ set +e+ step() { :; }+ HOME="$_mh"; export HOME+ SHELL="/bin/bash"; export SHELL+ unset ZSH_VERSION ZDOTDIR UV_NO_MODIFY_PATH UV_UNMANAGED_INSTALL+ _LOCAL_BIN="$HOME/.local/bin"+ _STUDIO_HOME_REDIRECT="none"+ _UNSLOTH_LOGIN_PATH="/usr/bin:/bin"+ _UNSLOTH_UV_BIN_DIR="$HOME/opt/a+b(c)"+ # shellcheck disable=SC1090+ . "$WORK/path_guard.sh"+ ) >/dev/null 2>&1 || true+done+_n=$(grep -cF 'a+b(c)' "$_mh/.bashrc") || _n=0+if [ "$_n" = "1" ]; then+ ok "a destination holding regex metacharacters is written once, not once per run"+else+ bad "a destination holding regex metacharacters is written once, not once per run ($_n)"+fi++echo+echo "passed: $PASS failed: $FAIL"+[ "$FAIL" -eq 0 ]diff --git a/tests/studio/install/test_launch_studio_launcher.py b/tests/studio/install/test_launch_studio_launcher.pyindex 1c12024f6d0..fd95f9c923f 100644--- a/tests/studio/install/test_launch_studio_launcher.py+++ b/tests/studio/install/test_launch_studio_launcher.py@@ -58,5 +58,21 @@ def test_launcher_is_windowless_powershell():assert "launch-studio.ps1" in text+def test_hidden_window_never_pairs_with_execution_policy_bypass():+ # The pair AV detections key on; install.rs already refuses it for the app's own launch.+ # launch-studio.ps1 is written locally, so it has no mark-of-the-web and RemoteSigned loads+ # it. The hidden window costs nothing to keep, the Bypass costs a detection.+ text = _text()+ for line in text.splitlines():+ if re.search(r"-WindowStyle\s+Hidden", line):+ assert not re.search(r"-ExecutionPolicy\s+Bypass", line), (+ "a hidden-window PowerShell launch must not also pass -ExecutionPolicy Bypass: "+ f"{line.strip()}"+ )+ assert re.search(+ r"-WindowStyle\s+Hidden\s+-ExecutionPolicy\s+RemoteSigned", text+ ), "the shortcut must launch launch-studio.ps1 under RemoteSigned, not Bypass."++if __name__ == "__main__":raise SystemExit(pytest.main([__file__, "-v"]))diff --git a/tests/studio/test_installer_av_shapes.py b/tests/studio/test_installer_av_shapes.pynew file mode 100644index 00000000000..c428882eea7--- /dev/null+++ b/tests/studio/test_installer_av_shapes.py@@ -0,0 +1,184 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Keep the shipped installers off the shapes antivirus heuristics score.++An AMSI provider blocked install.ps1 at parse time (#8523) and Microsoft flagged the Linux+AppImage `Trojan:Script/Wacatac.B!ml`. PowerShell hands the whole script block to AMSI before+running a line, so every byte counts, comments included.++Nothing here reproduces either verdict; it pins the constructs that were removed. The output+lock at the bottom is the other half: hardening must not change what a user sees.+"""++import re+from pathlib import Path++import pytest+++REPO = Path(__file__).resolve().parents[2]++PS_SCRIPTS = ("install.ps1", "studio/setup.ps1", "scripts/uninstall.ps1")+SH_SCRIPTS = ("install.sh", "studio/setup.sh")+ALL_SCRIPTS = PS_SCRIPTS + SH_SCRIPTS+++def _text(name: str) -> str:+ return (REPO / name).read_text(encoding = "utf-8")+++_QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"")+++def _code_lines(name: str):+ """Lines reduced to what the script executes: no comments, here-strings or quoted literals.++ Most checks here scan the whole file, since AMSI does too. The ones about what the script+ *does* use this, so the printed remediation text does not read as an execution.+ """+ in_here_string = False+ for number, line in enumerate(_text(name).splitlines(), start = 1):+ stripped = line.strip()+ if in_here_string:+ if stripped in ("'@", '"@'):+ in_here_string = False+ continue+ if re.search(r"@[\"']$", stripped):+ in_here_string = True+ continue+ if stripped.startswith("#"):+ continue+ yield number, _QUOTED.sub('""', line)++[email protected]("name", ALL_SCRIPTS)+def test_script_exists(name: str) -> None:+ assert (REPO / name).is_file(), f"missing {name}"++[email protected]("name", PS_SCRIPTS)+def test_no_remote_script_is_executed_in_process(name: str) -> None:+ # The construct AMSI and cloud ML scanners score hardest. Both files fetch a pinned+ # archive instead.+ for number, line in _code_lines(name):+ assert not re.search(+ r"Invoke-Expression\s*\(\s*Invoke-(RestMethod|WebRequest)", line+ ), f"{name}:{number} runs downloaded script text in-process: {line.strip()}"+ assert not re.search(+ r"\|\s*(iex|Invoke-Expression)\b", line+ ), f"{name}:{number} pipes into the engine: {line.strip()}"+ assert "scriptblock]::Create" not in line.lower().replace(+ " ", ""+ ), f"{name}:{number} builds a script block from a string: {line.strip()}"++[email protected]("name", SH_SCRIPTS)+def test_no_remote_script_is_piped_into_a_shell_first(name: str) -> None:+ # The astral fallback stays reachable for unpinned hosts, but must never be tried first.+ text = _text(name)+ if "astral.sh/uv/install.sh" not in text:+ return+ pinned = min(+ (m.start() for m in re.finditer(r"_(setup_install_uv_pinned|uv_install_pinned)\b", text)),+ default = None,+ )+ fallback = text.index("astral.sh/uv/install.sh")+ assert pinned is not None, f"{name} has no pinned uv path"+ assert pinned < fallback, f"{name} reaches the piped fallback before the pinned release"++[email protected]("name", ALL_SCRIPTS)+def test_no_encoded_or_base64_command_payloads(name: str) -> None:+ text = _text(name)+ for banned in ("-EncodedCommand", "FromBase64String", "base64 -d", "base64 --decode"):+ assert banned not in text, f"{name} contains {banned}"++[email protected]("name", ALL_SCRIPTS)+def test_a_hidden_window_never_pairs_with_a_bypassed_policy(name: str) -> None:+ # Microsoft's detections key on this pair; install.rs already refuses it for the app's+ # own launch.+ for number, line in enumerate(_text(name).splitlines(), start = 1):+ if re.search(r"-WindowStyle\s+Hidden", line, re.IGNORECASE):+ assert not re.search(+ r"-ExecutionPolicy\s+Bypass", line, re.IGNORECASE+ ), f"{name}:{number} pairs a hidden window with a bypassed policy: {line.strip()}"+++# Every runtime-compiled P/Invoke left in the installers. Each costs a csc.exe compile and is+# scored, so a new entry needs a reason; a PowerShell equivalent usually exists.+ALLOWED_PINVOKES = {+ # Canonicalising linked ancestors of security-relevant paths. No PS 5.1 equivalent:+ # ResolveLinkTarget is .NET 6+, and .Target misses a linked ancestor of a non-link leaf.+ "CreateFileW",+ "GetFinalPathNameByHandleW",+ # ANSI colour on legacy conhost.+ "GetStdHandle",+ "GetConsoleMode",+ "SetConsoleMode",+ # Per-item Explorer icon refresh; the global broadcast alone does not recover a stale .lnk.+ "SHChangeNotify",+ # PID -> image path for the venv-holder check. Win32_Process answers the same question,+ # but test_windows_installer_concurrency_guard.py bans it and $process.Path there: the+ # races #7764 closed came from inferring "in use" from anything but a confirmed executable+ # identity. A wrongly blocked install costs more than these imports.+ "OpenProcess",+ "QueryFullProcessImageNameW",+ "CloseHandle",+}++[email protected]("name", ALL_SCRIPTS)+def test_no_new_native_imports(name: str) -> None:+ text = _text(name)+ imported = set()+ for match in re.finditer(+ r"DllImport\(\"[^\"]+\"[^)]*\)\][^;{]*?extern\s+[\w.\[\]]+\s+(\w+)", text+ ):+ imported.add(match.group(1))+ # install.ps1's multi-line declarations put the parameter list on later lines.+ for match in re.finditer(r"extern\s+[\w.<>\[\]]+\s+(\w+)\s*\(", text):+ imported.add(match.group(1))+ unexpected = imported - ALLOWED_PINVOKES+ assert not unexpected, (+ f"{name} imports {sorted(unexpected)} from native code. Prefer a PowerShell or .NET "+ f"equivalent; if there genuinely is none, add it to ALLOWED_PINVOKES with the reason."+ )++[email protected]("name", ALL_SCRIPTS)+def test_no_process_memory_apis(name: str) -> None:+ # The installer reads image paths, nothing more. Reaching into another process's memory+ # has no use here and is what the injection heuristics look for.+ for banned in (+ "VirtualAllocEx",+ "WriteProcessMemory",+ "ReadProcessMemory",+ "CreateRemoteThread",+ "SetWindowsHookEx",+ ):+ assert banned not in _text(name), f"{name} references {banned}"+++# What the installers print when they need the user to reinstall. Hardening must not touch+# user-visible output, and a search-and-replace would take exactly these out.+REQUIRED_OUTPUT = {+ "install.ps1": ['Write-StudioLine " irm https://unsloth.ai/install.ps1 | iex"'],+ "studio/setup.ps1": ['Write-StudioLine " irm https://unsloth.ai/install.ps1 | iex"'],+ "install.sh": ["curl -fsSL https://unsloth.ai/install.sh | sh"],+}++[email protected]("name", sorted(REQUIRED_OUTPUT))+def test_printed_remediation_survives_the_hardening(name: str) -> None:+ text = _text(name)+ for snippet in REQUIRED_OUTPUT[name]:+ assert snippet in text, (+ f"{name} no longer prints {snippet!r}. Removing the one-liner from comments is the "+ f"point; removing it from what the user is told to run is a regression."+ )+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-v"]))diff --git a/tests/studio/test_tauri_installer_resource_contract.py b/tests/studio/test_tauri_installer_resource_contract.pyindex 5b1fbe9bebd..f58ec3d653c 100644--- a/tests/studio/test_tauri_installer_resource_contract.py+++ b/tests/studio/test_tauri_installer_resource_contract.py@@ -1,19 +1,35 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Keep Tauri repair helpers from mixing package versions."""+"""Keep Tauri repair helpers from mixing package versions, and keep each desktop bundle carrying+only the installer it can actually run."""import jsonfrom pathlib import PathREPO = Path(__file__).resolve().parents[2]+TAURI = REPO / "studio/src-tauri"+++def _resources(config_name: str) -> dict:+ config = json.loads((TAURI / config_name).read_text(encoding = "utf-8"))+ return config.get("bundle", {}).get("resources", {})+++def _bundled_resources(platform: str) -> dict:+ # Tauri merges tauri.<platform>.conf.json over tauri.conf.json for the target being built.+ merged = dict(_resources("tauri.conf.json"))+ merged.update(_resources(f"tauri.{platform}.conf.json"))+ return mergeddef test_tauri_never_overlays_install_python_stack() -> None:- config = json.loads((REPO / "studio/src-tauri/tauri.conf.json").read_text(encoding = "utf-8"))- resources = config["bundle"]["resources"]- assert not any("install_python_stack.py" in path for item in resources.items() for path in item)+ for platform in ("windows", "linux", "macos"):+ resources = _bundled_resources(platform)+ assert not any(+ "install_python_stack.py" in path for item in resources.items() for path in item+ ), platforminstaller = (REPO / "install.ps1").read_text(encoding = "utf-8")assert "Overlay Tauri-bundled studio fixes" not in installer@@ -21,3 +37,31 @@ def test_tauri_never_overlays_install_python_stack() -> None:'"install_python_stack.py" = "Lib\\site-packages\\studio\\install_python_stack.py"'not in installer)+++def test_each_bundle_ships_only_the_installer_it_runs() -> None:+ # resolve_install_script picks install.sh on unix and install.ps1 elsewhere, so the other+ # was dead weight in every bundle -- and the largest script body a classifier walking the+ # AppImage finds, which is where Trojan:Script/Wacatac.B!ml landed.+ assert _bundled_resources("windows") == {"../../install.ps1": "install.ps1"}+ assert _bundled_resources("linux") == {"../../install.sh": "install.sh"}+ assert _bundled_resources("macos") == {"../../install.sh": "install.sh"}+++def test_no_installer_resource_leaks_through_the_shared_config() -> None:+ # A resource in the shared config lands in every bundle, which is how the split regresses.+ assert _resources("tauri.conf.json") == {}+++def test_windows_upgrade_removes_the_installer_it_no_longer_ships() -> None:+ # NSIS writes the current resource manifest and deletes nothing, and the uninstaller+ # deletes only what is in that manifest. An in-place upgrade from a release that+ # bundled both installers would therefore keep install.sh on a Windows machine+ # forever, and the non-recursive RMDir "$INSTDIR" would fail at uninstall.+ hooks = (REPO / "studio/src-tauri/windows/hooks.nsh").read_text(encoding = "utf-8")+ for macro in ("NSIS_HOOK_PREINSTALL", "NSIS_HOOK_PREUNINSTALL"):+ assert f"!macro {macro}" in hooks, f"hooks.nsh must define {macro}"+ body = hooks.split(f"!macro {macro}", 1)[1].split("!macroend", 1)[0]+ assert (+ 'Delete "$INSTDIR\\install.sh"' in body+ ), f"{macro} must remove the install.sh a pre-split release left behind"