Skip to content

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.

Keep uv, its cache and the uv-managed Python inside a custom UNSLOTH_STUDIO_HOME (#13373)

Daniel Han04f362f3b5e4
diff --git a/.github/scripts/clean-machine-assert.sh b/.github/scripts/clean-machine-assert.sh
index 5626250e0d6..81b7c9b6aac 100755
--- a/.github/scripts/clean-machine-assert.sh
+++ b/.github/scripts/clean-machine-assert.sh
@@ -445,7 +445,8 @@ for check in "$@"; do
if [ ! -d "$root" ]; then
fail "macho requested but $root does not exist"
else
- # SCOPE, part 2: the two payloads the install RUNS ON live outside $root. `uv
+ # SCOPE, part 2: the two payloads the install RUNS ON can live outside $root (a custom
+ # UNSLOTH_STUDIO_HOME keeps both under it, #11327). `uv
# venv` links <venv>/bin/python at its base interpreter and the find below has no
# -L, so the interpreter that ran every step is invisible to it; the uv that
# fetched it lands in $HOME/.local/bin. Both are what Rosetta 2 hides: an x86_64
@@ -453,7 +454,7 @@ for check in "$@"; do
# -L follows that symlink; -maxdepth keeps this a bin/ lookup, not a second walk
# of site-packages through the venv's lib64 link -- depth 4 covers
# <root>/unsloth_studio, the .venv_t5_* sidecars and <root>/studio/unsloth_studio.
- # In a variable so it can be counted separately: uv alone would satisfy $nout.
+ # In a variable so it can be counted separately from uv.
base_py="$(find -L "$root" -maxdepth 4 -type f -path '*/bin/python' 2>/dev/null)"
_macho_targets() {
find "$root" -type f \( -perm -u+x -o -name '*.dylib' -o -name '*.so' -o -name '*.node' \) 2>/dev/null
@@ -462,7 +463,7 @@ for check in "$@"; do
[ -n "$_uv" ] && [ -f "$_uv" ] && printf '%s\n' "$_uv"
done
}
- n=0 nexe=0 nout=0 nbase=0 bad_arch="" unsigned="" broken=""
+ n=0 nexe=0 nuv=0 nbase=0 bad_arch="" unsigned="" broken=""
while IFS= read -r f; do
# -L: find printed the SYMLINK path for <venv>/bin/python, and plain `file` does
# not dereference, so it answered "symbolic link to ..." and the Mach-O test
@@ -470,7 +471,7 @@ for check in "$@"; do
desc="$(file -Lb "$f" 2>/dev/null || true)"
case "$desc" in *Mach-O*) ;; *) continue ;; esac
n=$((n + 1))
- case "$f" in "$root"/*) ;; *) nout=$((nout + 1)) ;; esac
+ case "${f##*/}" in uv) nuv=$((nuv + 1)) ;; esac
# Classified, not merely found: an entry `file` could not read is invisible here.
case "
$base_py
@@ -521,10 +522,10 @@ $f
fail "no Mach-O found under $root; the arch/signature assertion proved nothing"
elif [ "$nbase" = "0" ]; then
fail "no */bin/python under $root was classified as Mach-O, so the venv's base interpreter went unchecked (found: ${base_py:-none})"
- elif [ "$nout" = "0" ]; then
- # install.sh always bootstraps uv into $HOME/.local/bin, so zero hits outside
- # $root means the extra scan matched nothing and uv's arch went unproven.
- fail "no Mach-O outside $root was scanned, so uv and the venv's base interpreter escaped the check"
+ elif [ "$nuv" = "0" ]; then
+ # uv is in $HOME/.local/bin, on PATH, or under $root for a custom home: none
+ # classified means uv's arch went unproven.
+ fail "no uv was classified as Mach-O, so uv's arch went unproven"
elif [ -n "$bad_arch" ]; then
fail "Mach-O is not $want, so it runs here only under Rosetta 2, which a fresh Mac does not have:$bad_arch"
elif [ -n "$unsigned" ]; then
diff --git a/install.ps1 b/install.ps1
index 94ee55e9ab6..a867a5179b7 100644
--- a/install.ps1
+++ b/install.ps1
@@ -143,6 +143,7 @@ function Install-UnslothStudio {
# statement re-assigns unconditionally.
$script:UvExe = 'uv'
$script:UvInstallDestDir = $null
+ $script:StudioPrivateUvDir = $null
# Same reason, and this one caches a decision about the machine: a policy added or
# removed between two runs in one console, or a replaced launcher under a hash rule,
# would otherwise be answered from the first run's probe.
@@ -6551,6 +6552,8 @@ exit 0
$studioAutoStartProcess = $null
$hadPreviousUvCacheDir = [Environment]::GetEnvironmentVariables().ContainsKey("UV_CACHE_DIR")
$previousUvCacheDir = [Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
+ $hadPreviousUvPythonInstallDir = [Environment]::GetEnvironmentVariables().ContainsKey("UV_PYTHON_INSTALL_DIR")
+ $previousUvPythonInstallDir = [Environment]::GetEnvironmentVariable("UV_PYTHON_INSTALL_DIR", "Process")
try {
if ($studioNeedsRuntimeLock) {
try {
@@ -6910,8 +6913,10 @@ exit 0
# Same destination priority as astral's installer, so an existing uv is
# replaced in place and the PATH probe further below still finds it.
- $destDir = $null
- foreach ($candidate in @($env:UV_INSTALL_DIR, $env:UV_UNMANAGED_INSTALL, $env:XDG_BIN_HOME)) {
+ # Read safely: extracted, this runs under a caller's strict mode.
+ $privateDir = Get-Variable -Name StudioPrivateUvDir -Scope Script -ValueOnly -ErrorAction SilentlyContinue
+ $destDir = $privateDir
+ foreach ($candidate in @($destDir, $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" }
@@ -7030,7 +7035,7 @@ exit 0
# Same PATH treatment and opt-outs astral's installer uses: an unmanaged
# install forces no-modify-path there, so it must here too.
- if (-not $env:UV_NO_MODIFY_PATH -and -not $env:UV_UNMANAGED_INSTALL) {
+ if (-not $env:UV_NO_MODIFY_PATH -and -not $env:UV_UNMANAGED_INSTALL -and -not $privateDir) {
Add-ToUserPath -Directory $destDir -Position Prepend | Out-Null
}
$env:PATH = "$destDir;$env:PATH"
@@ -7040,7 +7045,31 @@ exit 0
return $true
}
- if (-not (Test-UvVersionOk)) {
+ # A custom home gets its own uv in <home>\uv: winget and the default edit the profile and user PATH.
+ $script:StudioKeepsTools = (-not $studioUsesLegacyLayout) -and (Test-StudioHomeIsCustom)
+ if ($script:StudioKeepsTools) {
+ # Claimed before uv or python\ lands in it: the claim needs an empty root. A no-op once claimed.
+ Write-StudioRootOwnerMarker -Root $StudioHome
+ # Created even when unused: Studio reads it as this choice at runtime.
+ try { [System.IO.Directory]::CreateDirectory((Join-Path $StudioHome "python")) | Out-Null } catch {}
+ }
+ $script:StudioPrivateUvDir = $null
+ $script:StudioPrivateUvStale = $false
+ if ($script:StudioKeepsTools -and
+ -not ($env:UV_INSTALL_DIR -or $env:UV_UNMANAGED_INSTALL -or $env:XDG_BIN_HOME)) {
+ $script:StudioPrivateUvDir = Join-Path $StudioHome "uv"
+ $privateUv = Join-Path $script:StudioPrivateUvDir "uv.exe"
+ if (Test-Path -LiteralPath $privateUv -PathType Leaf) {
+ # Studio puts this one first at runtime, so a stale copy is replaced even when PATH has a good uv.
+ if (Test-UvCandidateVersion $privateUv) {
+ $env:PATH = "$($script:StudioPrivateUvDir);$env:PATH"
+ } else {
+ $script:StudioPrivateUvStale = $true
+ }
+ }
+ }
+
+ if ($script:StudioPrivateUvStale -or -not (Test-UvVersionOk)) {
# Resolve-UvExecutable, not a bare Get-Command: a profile alias named uv would
# otherwise report "updating" on what is in fact a first install.
if (Resolve-UvExecutable) {
@@ -7048,7 +7077,7 @@ exit 0
} else {
substep "installing uv package manager..."
}
- if ($script:WingetAvailable) {
+ if ($script:WingetAvailable -and -not $script:StudioPrivateUvDir) {
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = "Continue"
try { & $script:WingetExe upgrade --id=astral-sh.uv -e --source winget --accept-package-agreements --accept-source-agreements } catch {}
@@ -7059,8 +7088,9 @@ exit 0
Refresh-SessionPath
}
# winget unavailable or it didn't put uv on PATH: install the pinned
- # release directly (ARM64 runners, machines without the Store).
- if (-not (Test-UvVersionOk)) {
+ # release directly (ARM64 runners, machines without the Store). A stale private uv is
+ # replaced even when PATH has a good one: Studio puts the private one first.
+ if ($script:StudioPrivateUvStale -or -not (Test-UvVersionOk)) {
if (@(Install-UvFromRelease)[-1] -ne $true -and $script:UvReleaseUnfetched -and (Use-MirrorSpare uvbin)) { Install-UvFromRelease | Out-Null }
Refresh-SessionPath
}
@@ -7092,6 +7122,11 @@ exit 0
# tests/python/test_windows_python_venv_hardening.py, where a call into the rest of the
# installer is a command-not-found.
Write-StudioRootOwnerMarker -Root $StudioHome
+ # Never the shared cache: new wheels would land on the profile drive.
+ if ($script:StudioKeepsTools -and
+ (Test-StudioUvCacheUsable -Cache (Join-Path (Join-Path $StudioHome "cache") "uv"))) {
+ $IsolateUvCache = $true
+ }
Set-StudioUvCacheEnvironment -StudioRoot $StudioHome -Isolated $IsolateUvCache -UvExecutable $script:UvExe
# Bytecode compilation can exceed uv's 60s default on slow machines ("0" disables).
if (-not $env:UV_COMPILE_BYTECODE_TIMEOUT) {
@@ -7185,6 +7220,10 @@ exit 0
return $venvHome.StartsWith($store, [System.StringComparison]::OrdinalIgnoreCase)
}
+ # The venv is built on this interpreter, so a custom home keeps it too.
+ if ($script:StudioKeepsTools -and [string]::IsNullOrWhiteSpace($env:UV_PYTHON_INSTALL_DIR)) {
+ $env:UV_PYTHON_INSTALL_DIR = Join-Path $StudioHome "python"
+ }
$DetectedPython = Resolve-UvManagedPython -Minor $PythonVersion -Patch $PythonPatchRequest -Arch $PythonArch
if (-not $DetectedPython -and $PythonArch -eq "arm64" -and -not (Test-Arm64PythonOptOut)) {
substep "could not get a native ARM64 Python; falling back to the x64 stack." "Yellow"
@@ -11871,6 +11910,11 @@ sys.exit(2 if conflict else (0 if installed else 1))
}
} finally {
Restore-StudioUvCacheEnvironment -WasPresent $hadPreviousUvCacheDir -PreviousValue $previousUvCacheDir
+ if ($hadPreviousUvPythonInstallDir) {
+ Set-Item -LiteralPath Env:UV_PYTHON_INSTALL_DIR -Value $previousUvPythonInstallDir
+ } elseif (Test-Path -LiteralPath Env:UV_PYTHON_INSTALL_DIR) {
+ Remove-Item -LiteralPath Env:UV_PYTHON_INSTALL_DIR
+ }
for ($i = $studioRuntimeMutexes.Count - 1; $i -ge 0; $i--) {
Exit-StudioInstallMutex -Mutex $studioRuntimeMutexes[$i]
}
diff --git a/install.sh b/install.sh
index f427d4d061a..97527d82b66 100755
--- a/install.sh
+++ b/install.sh
@@ -845,7 +845,7 @@ _configure_uv_cache() {
esac
fi
- if [ "$_ISOLATE_UV_CACHE" = true ]; then
+ if [ "$_ISOLATE_UV_CACHE" = true ] || { [ "$_STUDIO_KEEPS_TOOLS" = true ] && _uv_cache_is_writable "$_uv_studio_cache"; }; then
UV_CACHE_DIR="$_uv_studio_cache"
_UV_CACHE_MODE=isolated
export UV_CACHE_DIR
@@ -1062,6 +1062,12 @@ _prepare_studio_uv_cache_for_launch() {
export UV_CACHE_DIR
}
_resolve_studio_destinations
+# A custom home keeps uv, its cache and the uv-managed Python inside it (#11327); the legacy root keeps the default layout.
+_STUDIO_KEEPS_TOOLS=false
+if [ "$_STUDIO_HOME_REDIRECT" = "env" ] && [ "$STUDIO_HOME" != "$(CDPATH= cd -P -- "$HOME/.unsloth/studio" 2>/dev/null && pwd -P)" ]; then
+ _STUDIO_KEEPS_TOOLS=true
+ [ -n "${UV_PYTHON_INSTALL_DIR:-}" ] || export UV_PYTHON_INSTALL_DIR="$STUDIO_HOME/python"
+fi
# 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"
@@ -1118,6 +1124,8 @@ _claim_studio_root() {
printf '' > "$_claim_marker" 2>/dev/null || true
}
_claim_studio_root
+# After the claim, which needs an empty root. Created even when unused: Studio reads it as this choice at runtime.
+if [ "$_STUDIO_KEEPS_TOOLS" = true ]; then mkdir -p "$STUDIO_HOME/python" 2>/dev/null || true; fi
# Keep uv's cache on the same filesystem as the venv it fills.
# uv hardlinks wheels within one filesystem and copies across a boundary, so a moved STUDIO_HOME paid double the disk and stranded the cache. An explicit UV_CACHE_DIR wins. The fallback is required, since uv aborts on a cache it cannot create; mkdir -p exits 0 for an existing unwritable directory and -w reads the mode rather than the filesystem, so probe with a real create.
@@ -4030,7 +4038,7 @@ _uv_install_pinned() {
# 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
+ for _uip_candidate in "${_STUDIO_UV_DIR:-}" "${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
@@ -4124,7 +4132,17 @@ https://github.com/astral-sh/uv/releases/download/$UV_PINNED_VERSION"
return "$_uip_rc"
}
-if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv; then
+# Only installed when no usable uv is on PATH; never written to a shell profile.
+_STUDIO_UV_DIR=""
+_STUDIO_UV_STALE=false
+if [ "$_STUDIO_KEEPS_TOOLS" = true ] && [ -z "${UV_INSTALL_DIR:-}${UV_UNMANAGED_INSTALL:-}${XDG_BIN_HOME:-}" ]; then
+ _STUDIO_UV_DIR="$STUDIO_HOME/uv"
+ if [ -x "$_STUDIO_UV_DIR/uv" ]; then
+ # Studio puts this one first at runtime, so a stale copy is replaced even when PATH has a good uv.
+ if _uv_version_ok "$_STUDIO_UV_DIR/uv"; then export PATH="$_STUDIO_UV_DIR:$PATH"; else _STUDIO_UV_STALE=true; fi
+ fi
+fi
+if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv || [ "$_STUDIO_UV_STALE" = true ]; 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 failure must not be fatal for them. An unreadable version counts as present: that is a minimal image without awk, not an old uv.
_uv_present_before=false
if command -v uv >/dev/null 2>&1; then
@@ -4153,6 +4171,13 @@ if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv; then
if [ -n "$_uv_inst_sum" ] && [ "$_uv_inst_sum" != "$UV_INSTALLER_SH_SHA256" ]; then
substep "uv installer script failed its sha256 check; not running it"
_uv_refreshed=false
+ elif [ -n "$_STUDIO_UV_DIR" ]; then
+ # astral's unmanaged mode: that directory only, no profile edits, no receipt.
+ if (export UV_UNMANAGED_INSTALL="$_STUDIO_UV_DIR"; run_maybe_quiet sh "$_uv_tmp" </dev/null); then
+ _UNSLOTH_UV_BIN_DIR="$_STUDIO_UV_DIR"
+ else
+ _uv_refreshed=false
+ fi
else
run_maybe_quiet sh "$_uv_tmp" </dev/null || _uv_refreshed=false
fi
diff --git a/studio/backend/core/inference/engine_install.py b/studio/backend/core/inference/engine_install.py
index 28616867075..61c64978cfa 100644
--- a/studio/backend/core/inference/engine_install.py
+++ b/studio/backend/core/inference/engine_install.py
@@ -1139,6 +1139,8 @@ def install_environment() -> dict[str, str]:
"https_proxy",
"http_proxy",
"no_proxy",
+ # Where uv puts a managed Python; a custom Studio home keeps it inside the home.
+ "UV_PYTHON_INSTALL_DIR",
}
}
from utils.paths.storage_roots import cache_root
diff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.py
index 532a86470b7..b84e8e5151a 100644
--- a/studio/backend/utils/paths/storage_roots.py
+++ b/studio/backend/utils/paths/storage_roots.py
@@ -1285,6 +1285,29 @@ def parseable_cache_fallback(key: str, intended: str) -> str | None:
return candidate
+def _use_studio_uv_tools() -> None:
+ """An install with a custom UNSLOTH_STUDIO_HOME keeps its own uv in <studio>/uv, off the user
+ PATH, and its uv-managed Python in <studio>/python. Keyed on those directories, which only
+ that installer creates, so nothing else opts in. Its uv goes first: the installer only places
+ one there when PATH had none or one below its minimum."""
+ root = studio_root()
+ try:
+ if root.resolve() == (Path.home() / ".unsloth" / "studio").resolve():
+ return
+ except (OSError, RuntimeError, ValueError):
+ return
+ if (root / "python").is_dir() and not (os.environ.get("UV_PYTHON_INSTALL_DIR") or "").strip():
+ os.environ["UV_PYTHON_INSTALL_DIR"] = str(root / "python")
+ uv_dir = root / "uv"
+ if (uv_dir / ("uv.exe" if os.name == "nt" else "uv")).is_file():
+ os.environ["PATH"] = _path_with_first(os.environ.get("PATH", ""), str(uv_dir))
+
+
+def _path_with_first(path: str, first: str) -> str:
+ rest = [entry for entry in path.split(os.pathsep) if entry and entry != first]
+ return os.pathsep.join([first, *rest])
+
+
def _setup_cache_env() -> None:
"""Set cache env vars for HuggingFace, uv, and vLLM.
@@ -1292,6 +1315,7 @@ def _setup_cache_env() -> None:
stored location. Unsloth seeds import-time variables once, while each later
worker receives its own captured cache location.
"""
+ _use_studio_uv_tools()
root = cache_root()
from utils.hf_cache_settings import initialize_hf_cache_environment
diff --git a/tests/python/test_custom_studio_home_keeps_uv.py b/tests/python/test_custom_studio_home_keeps_uv.py
new file mode 100644
index 00000000000..4733b5c1375
--- /dev/null
+++ b/tests/python/test_custom_studio_home_keeps_uv.py
@@ -0,0 +1,351 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""A custom UNSLOTH_STUDIO_HOME keeps uv, its cache and the uv-managed Python inside the home
+(#11327), so a home on another drive leaves nothing large on the profile drive."""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+from unsloth_pwsh_runner import run_pwsh
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+INSTALL_PS1 = (REPO_ROOT / "install.ps1").read_text(encoding = "utf-8")
+INSTALL_SH = (REPO_ROOT / "install.sh").read_text(encoding = "utf-8")
+POWERSHELLS = [shell for shell in ("pwsh", "powershell") if shutil.which(shell)]
+needs_pwsh = pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")
+needs_sh = pytest.mark.skipif(
+ sys.platform == "win32" or not shutil.which("sh"), reason = "POSIX sh is unavailable"
+)
+
+
+def _between(source: str, start: str, end: str) -> str:
+ begin = source.index(start)
+ return source[begin : source.index(end, begin)]
+
+
+def _uv_stub(directory: Path) -> None:
+ name = "uv.exe" if os.name == "nt" else "uv"
+ directory.mkdir(parents = True, exist_ok = True)
+ (directory / name).write_text("#!/bin/sh\n")
+ (directory / name).chmod(0o755)
+
+
+# ── install.ps1 ──
+
+
+def _ps1_private_uv(
+ shell,
+ home: Path,
+ *,
+ legacy = False,
+ profile_default = False,
+ private_ok = True,
+ env = None,
+):
+ block = _between(
+ INSTALL_PS1,
+ " $script:StudioKeepsTools = ",
+ " if ($script:StudioPrivateUvStale -or -not (Test-UvVersionOk)) {",
+ )
+ script = f"""
+$ErrorActionPreference = "Stop"
+$StudioHome = '{home}'
+$studioUsesLegacyLayout = ${str(legacy).lower()}
+function Test-StudioHomeIsCustom {{ return ${str(not profile_default).lower()} }}
+function Write-StudioRootOwnerMarker {{ param($Root) $script:claimedBeforePython = -not (Test-Path (Join-Path $Root "python")) }}
+function Test-UvCandidateVersion {{ param($exe) return ${str(private_ok).lower()} }}
+$script:claimedBeforePython = $null
+{block}
+"claimed=$($script:claimedBeforePython)"
+"stale=$($script:StudioPrivateUvStale)"
+"keeps=$($script:StudioKeepsTools)"
+"dir=$($script:StudioPrivateUvDir)"
+"path=$env:PATH"
+"""
+ child_env = {
+ k: v
+ for k, v in os.environ.items()
+ if k not in ("UV_INSTALL_DIR", "UV_UNMANAGED_INSTALL", "XDG_BIN_HOME")
+ }
+ child_env.update(env or {})
+ out = run_pwsh(
+ [shell, "-NoProfile", "-NonInteractive", "-Command", script],
+ check = True,
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ env = child_env,
+ timeout = 60,
+ ).stdout
+ return dict(line.split("=", 1) for line in out.splitlines() if "=" in line)
+
+
+@needs_pwsh
[email protected]("shell", POWERSHELLS)
+def test_ps1_custom_home_installs_uv_into_its_own_dir(shell, tmp_path):
+ bin_dir = str(tmp_path / "uv")
+ found = _ps1_private_uv(shell, tmp_path)
+ assert found["keeps"] == "True"
+ assert Path(found["dir"]) == Path(bin_dir)
+ # Nothing there yet, so PATH is untouched until a uv lands in it.
+ assert bin_dir not in found["path"]
+
+ # The root is claimed before python\ is created in it.
+ assert found["claimed"] == "True"
+ assert (tmp_path / "python").is_dir()
+
+ (tmp_path / "uv").mkdir()
+ (tmp_path / "uv" / "uv.exe").write_bytes(b"")
+ found = _ps1_private_uv(shell, tmp_path)
+ assert (found["stale"], found["path"].startswith(bin_dir)) == ("False", True)
+ # A stale private uv is not put first; the installer replaces it instead.
+ found = _ps1_private_uv(shell, tmp_path, private_ok = False)
+ assert (found["stale"], found["path"].startswith(bin_dir)) == ("True", False)
+
+
+@needs_pwsh
[email protected]("shell", POWERSHELLS)
+def test_ps1_default_root_and_explicit_uv_dir_keep_the_old_layout(shell, tmp_path):
+ for found in (
+ _ps1_private_uv(shell, tmp_path, legacy = True),
+ # UNSLOTH_STUDIO_HOME naming the current USERPROFILE default is still the default.
+ _ps1_private_uv(shell, tmp_path, profile_default = True),
+ ):
+ assert (found["keeps"], found["dir"]) == ("False", "")
+ explicit = _ps1_private_uv(shell, tmp_path, env = {"UV_INSTALL_DIR": str(tmp_path / "mine")})
+ assert (explicit["keeps"], explicit["dir"]) == ("True", "")
+
+
+def test_ps1_private_uv_skips_winget_and_the_user_path():
+ install = _between(INSTALL_PS1, " function Install-UvFromRelease {", "\n }\n")
+ assert "Get-Variable -Name StudioPrivateUvDir -Scope Script" in install
+ assert "$destDir = $privateDir" in install
+ assert (
+ "-not $env:UV_UNMANAGED_INSTALL -and -not $privateDir) {\n"
+ " Add-ToUserPath" in install
+ )
+ assert "if ($script:WingetAvailable -and -not $script:StudioPrivateUvDir) {" in INSTALL_PS1
+ # Both guards on the way to Install-UvFromRelease honour the stale flag, not only the outer one.
+ block = _between(
+ INSTALL_PS1,
+ " if ($script:StudioPrivateUvStale -or -not (Test-UvVersionOk)) {",
+ " # A freshly installed uv can sit behind an older one on PATH",
+ )
+ assert block.count("$script:StudioPrivateUvStale -or -not (Test-UvVersionOk)") == 2
+
+
+def test_ps1_custom_home_isolates_a_usable_cache_and_the_python_store():
+ configured = INSTALL_PS1.index(
+ "Set-StudioUvCacheEnvironment -StudioRoot $StudioHome -Isolated $IsolateUvCache"
+ )
+ isolate = INSTALL_PS1.rindex("if ($script:StudioKeepsTools -and", 0, configured)
+ # An unusable Studio cache falls through to the selector, as it does without the override.
+ assert "Test-StudioUvCacheUsable -Cache" in INSTALL_PS1[isolate:configured]
+ python = _between(
+ INSTALL_PS1,
+ " # The venv is built on this interpreter, so a custom home keeps it too.\n",
+ " $DetectedPython = Resolve-UvManagedPython -Minor",
+ )
+ assert "$script:StudioKeepsTools" in python
+ assert '$env:UV_PYTHON_INSTALL_DIR = Join-Path $StudioHome "python"' in python
+ # Restored for `irm | iex`, where the session is the user's own.
+ restore = _between(
+ INSTALL_PS1,
+ " } finally {\n Restore-StudioUvCacheEnvironment",
+ "Restore-StudioTempEnvironment",
+ )
+ assert "Env:UV_PYTHON_INSTALL_DIR" in restore
+
+
+# ── install.sh ──
+
+
+def _sh(
+ home: Path,
+ studio_home: Path,
+ *,
+ redirect = "env",
+ env = None,
+):
+ keeps = _between(INSTALL_SH, "_STUDIO_KEEPS_TOOLS=false\n", "# The PATH we inherited")
+ private = _between(
+ INSTALL_SH,
+ '_STUDIO_UV_DIR=""\n',
+ 'if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv || [ "$_STUDIO_UV_STALE"',
+ )
+ script = f"""
+set -e
+_uv_version_ok() {{ "$1" --version >/dev/null 2>&1; }}
+_STUDIO_HOME_REDIRECT={redirect}
+STUDIO_HOME='{studio_home}'
+{keeps}
+{private}
+echo "keeps=$_STUDIO_KEEPS_TOOLS"
+echo "uvdir=$_STUDIO_UV_DIR"
+echo "stale=$_STUDIO_UV_STALE"
+echo "pydir=${{UV_PYTHON_INSTALL_DIR:-}}"
+echo "path=$PATH"
+"""
+ child_env = {"HOME": str(home), "PATH": os.environ.get("PATH", "/usr/bin:/bin")}
+ child_env.update(env or {})
+ out = subprocess.run(
+ ["sh", "-c", script], check = True, capture_output = True, text = True, env = child_env
+ ).stdout
+ return dict(line.split("=", 1) for line in out.splitlines() if "=" in line)
+
+
+@needs_sh
+def test_sh_custom_home_keeps_uv_and_python(tmp_path):
+ studio = tmp_path / "drive" / "studio"
+ studio.mkdir(parents = True)
+ found = _sh(tmp_path / "home", studio)
+ assert (found["keeps"], found["uvdir"]) == ("true", f"{studio}/uv")
+ assert found["pydir"] == f"{studio}/python"
+ assert not found["path"].startswith(f"{studio}/uv")
+
+ _uv_stub(studio / "uv")
+ found = _sh(tmp_path / "home", studio)
+ assert (found["stale"], found["path"].startswith(f"{studio}/uv:")) == ("false", True)
+ # A stale private uv is not put first; the installer replaces it instead.
+ (studio / "uv" / "uv").write_text("#!/bin/sh\nexit 1\n")
+ found = _sh(tmp_path / "home", studio)
+ assert (found["stale"], found["path"].startswith(f"{studio}/uv:")) == ("true", False)
+
+
+def test_sh_python_marker_is_created_only_after_the_root_claim():
+ claim = INSTALL_SH.index("\n_claim_studio_root\n")
+ marker = INSTALL_SH.index('then mkdir -p "$STUDIO_HOME/python"')
+ assert claim < marker
+ assert INSTALL_SH.count('mkdir -p "$STUDIO_HOME/python"') == 1
+
+
+@needs_sh
+def test_sh_explicit_settings_and_the_default_root_win(tmp_path):
+ home = tmp_path / "home"
+ legacy = home / ".unsloth" / "studio"
+ legacy.mkdir(parents = True)
+ for found in (_sh(home, legacy), _sh(home, legacy, redirect = "default")):
+ assert (found["keeps"], found["uvdir"], found["pydir"]) == ("false", "", "")
+
+ studio = tmp_path / "studio"
+ studio.mkdir()
+ found = _sh(
+ home,
+ studio,
+ env = {"UV_PYTHON_INSTALL_DIR": "/mine/python", "UV_INSTALL_DIR": "/mine/bin"},
+ )
+ assert (found["keeps"], found["uvdir"], found["pydir"]) == ("true", "", "/mine/python")
+
+
+def test_sh_custom_home_isolates_a_usable_cache_and_unmanaged_fallback():
+ cache = _between(INSTALL_SH, "_configure_uv_cache() {", "\n}\n")
+ assert (
+ 'if [ "$_ISOLATE_UV_CACHE" = true ] || { [ "$_STUDIO_KEEPS_TOOLS" = true ] '
+ '&& _uv_cache_is_writable "$_uv_studio_cache"; }; then' in cache
+ )
+ pinned = _between(INSTALL_SH, "_uv_install_pinned() {", "\n}\n")
+ assert 'for _uip_candidate in "${_STUDIO_UV_DIR:-}" "${UV_INSTALL_DIR:-}"' in pinned
+ assert (
+ '(export UV_UNMANAGED_INSTALL="$_STUDIO_UV_DIR"; run_maybe_quiet sh "$_uv_tmp"'
+ in INSTALL_SH
+ )
+
+
+# ── backend and CLI ──
+
+
+def test_backend_points_on_demand_installs_at_the_home(tmp_path, monkeypatch):
+ sys.path.insert(0, str(REPO_ROOT / "studio" / "backend"))
+ try:
+ from utils.paths import storage_roots
+ finally:
+ sys.path.pop(0)
+
+ home = tmp_path / "home"
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))
+ mine = tmp_path / "mine"
+ _uv_stub(mine)
+ monkeypatch.setenv("PATH", str(mine))
+ monkeypatch.delenv("UV_PYTHON_INSTALL_DIR", raising = False)
+
+ legacy = home / ".unsloth" / "studio"
+ _uv_stub(legacy / "uv")
+ monkeypatch.setattr(storage_roots, "studio_root", lambda: legacy)
+ storage_roots._use_studio_uv_tools()
+ assert os.environ["PATH"] == str(mine)
+ assert "UV_PYTHON_INSTALL_DIR" not in os.environ
+
+ # A custom root the opt-in installer never touched (UNSLOTH_HOME alone, say) is left alone.
+ studio = tmp_path / "drive" / "studio"
+ studio.mkdir(parents = True)
+ monkeypatch.setattr(storage_roots, "studio_root", lambda: studio)
+ storage_roots._use_studio_uv_tools()
+ assert os.environ["PATH"] == str(mine)
+ assert "UV_PYTHON_INSTALL_DIR" not in os.environ
+
+ (studio / "python").mkdir()
+ storage_roots._use_studio_uv_tools()
+ assert os.environ["PATH"] == str(mine)
+ assert os.environ["UV_PYTHON_INSTALL_DIR"] == str(studio / "python")
+
+ # The installer only places a uv here when PATH had none or an old one, so it goes first,
+ # also when it is already further down PATH, and only once.
+ _uv_stub(studio / "uv")
+ monkeypatch.setenv("PATH", os.pathsep.join([str(mine), str(studio / "uv")]))
+ storage_roots._use_studio_uv_tools()
+ storage_roots._use_studio_uv_tools()
+ assert os.environ["PATH"] == str(studio / "uv") + os.pathsep + str(mine)
+
+ # The engine installer's child keeps the Python store.
+ sys.path.insert(0, str(REPO_ROOT / "studio" / "backend"))
+ try:
+ from core.inference import engine_install
+ finally:
+ sys.path.pop(0)
+
+ assert engine_install.install_environment()["UV_PYTHON_INSTALL_DIR"] == str(studio / "python")
+
+ monkeypatch.setenv("UV_PYTHON_INSTALL_DIR", "/mine/python")
+ storage_roots._use_studio_uv_tools()
+ assert os.environ["UV_PYTHON_INSTALL_DIR"] == "/mine/python"
+
+
+def test_cli_update_points_setup_at_the_home(tmp_path, monkeypatch):
+ # `unsloth studio update` runs setup directly. setup uses a uv on PATH as is, and otherwise
+ # version-checks UV_UNMANAGED_INSTALL and installs the pinned uv there, with no profile edit.
+ sys.path.insert(0, str(REPO_ROOT))
+ try:
+ from unsloth_cli.commands import studio as studio_cli
+ finally:
+ sys.path.pop(0)
+
+ home = tmp_path / "studio"
+ home.mkdir()
+ monkeypatch.setattr(studio_cli, "STUDIO_HOME", home)
+ monkeypatch.setattr(studio_cli, "_STUDIO_HOME_IS_CUSTOM", True)
+ env = {"PATH": str(tmp_path / "mine")}
+
+ # Not opted in: a custom root the opt-in installer never touched.
+ assert studio_cli._with_studio_uv(env) is env
+
+ (home / "python").mkdir()
+ assert studio_cli._with_studio_uv(env) == {
+ "PATH": str(tmp_path / "mine"),
+ "UV_PYTHON_INSTALL_DIR": str(home / "python"),
+ "UV_UNMANAGED_INSTALL": str(home / "uv"),
+ }
+ assert env == {"PATH": str(tmp_path / "mine")}
+ # The caller's own choices win.
+ mine = {"PATH": "p", "UV_INSTALL_DIR": "/mine/bin", "UV_PYTHON_INSTALL_DIR": "/mine/py"}
+ assert studio_cli._with_studio_uv(mine) == mine
+
+ monkeypatch.setattr(studio_cli, "_STUDIO_HOME_IS_CUSTOM", False)
+ assert studio_cli._with_studio_uv(env) is env
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 5b595e525a3..f98e2fe1404 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -3799,6 +3799,33 @@ def _with_studio_uv_cache(env: Optional[dict], cwd: Optional[Path] = None) -> Op
return {**(env or os.environ), "UV_CACHE_DIR": str(studio_cache)}
+def _with_studio_uv(env: Optional[dict]) -> Optional[dict]:
+ """An install with a custom UNSLOTH_STUDIO_HOME keeps its uv-managed Python in <home>/python
+ and its own uv in <home>/uv; only that installer creates <home>/python. Without this, setup
+ would put a missing or stale uv, and any managed Python, in the profile. setup version-checks
+ the uv it finds there and replaces it in place; a uv already on PATH is used as before."""
+ try:
+ if (
+ not _STUDIO_HOME_IS_CUSTOM
+ or STUDIO_HOME.resolve() == (Path.home() / ".unsloth" / "studio").resolve()
+ ):
+ return env
+ except (OSError, RuntimeError, ValueError):
+ return env
+ if not (STUDIO_HOME / "python").is_dir():
+ return env
+ out = {**(env if env is not None else os.environ)}
+ if not (out.get("UV_PYTHON_INSTALL_DIR") or "").strip():
+ out["UV_PYTHON_INSTALL_DIR"] = str(STUDIO_HOME / "python")
+ # astral's unmanaged mode: that directory, no profile or user PATH edit (setup.sh, setup.ps1).
+ if not any(
+ (out.get(k) or "").strip()
+ for k in ("UV_INSTALL_DIR", "UV_UNMANAGED_INSTALL", "XDG_BIN_HOME")
+ ):
+ out["UV_UNMANAGED_INSTALL"] = str(STUDIO_HOME / "uv")
+ return out
+
+
def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None) -> None:
script = _find_setup_script(repo_root)
if not script:
@@ -3815,6 +3842,7 @@ def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None
# Where setup runs uv from: setup.sh cds into its own directory, setup.ps1 keeps this cwd.
setup_cwd = None if platform.system() == "Windows" else script.parent
env = _with_studio_uv_cache(env, cwd = setup_cwd)
+ env = _with_studio_uv(env)
# Saves setup.ps1 the process walk. A HINT, not a promise: only the desktop spawn guarantees
# the managed venv's python, while a pip install, a checkout or a staged run puts an
# interpreter here that is nowhere near $VenvDir. Get-SetupHostInterpreterInVenv tests