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.

Studio: honor UNSLOTH_HOME in installers (#14293)

oobaboogae72a79fb510a
diff --git a/install.ps1 b/install.ps1
index 56e4c3820a2..3fb4c319c11 100644
--- a/install.ps1
+++ b/install.ps1
@@ -11,7 +11,7 @@
# equivalent flags (--no-torch, --skip-autostart, --isolated-uv-cache, --no-rollback,
# --python, --local).
#
-# Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME (alias) > $USERPROFILE\.unsloth\studio
+# Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME (alias) > UNSLOTH_HOME/studio > $USERPROFILE\.unsloth\studio
#
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
@@ -2159,6 +2159,8 @@ function Install-UnslothStudio {
$env:UNSLOTH_STUDIO_HOME.Trim()
} elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) {
$env:STUDIO_HOME.Trim()
+ } elseif (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_HOME)) {
+ $env:UNSLOTH_HOME.Trim()
} else {
$UnslothRoot
}
@@ -2179,6 +2181,9 @@ function Install-UnslothStudio {
} elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) {
$envOverrideVar = "STUDIO_HOME"
$envOverride = $env:STUDIO_HOME.Trim()
+ } elseif (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_HOME)) {
+ $envOverrideVar = "UNSLOTH_HOME (studio child)"
+ $envOverride = Join-Path $env:UNSLOTH_HOME.Trim() "studio"
}
$defaultProfile = $null
try { $defaultProfile = [Environment]::GetFolderPath("UserProfile") } catch {}
@@ -3156,13 +3161,16 @@ function Install-UnslothStudio {
# Custom Unsloth roots are not supported with --tauri (the desktop app uses
# the Windows profile folder). Pass through if the override is that same root,
# or the one the desktop chose (UNSLOTH_DESKTOP_CHOSEN_STUDIO_HOME=1).
+ if ($envOverride) {
+ if ($envOverride -eq "~" -or $envOverride -like "~/*" -or $envOverride -like "~\*") {
+ $envOverride = (Join-Path $env:USERPROFILE $envOverride.Substring(1).TrimStart('/','\'))
+ }
+ $envOverride = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($envOverride)
+ }
$tauriChosenRoot = ($TauriMode -and $envOverrideVar -eq "UNSLOTH_STUDIO_HOME" -and
$env:UNSLOTH_DESKTOP_CHOSEN_STUDIO_HOME -eq "1")
if ($TauriMode -and $envOverride -and -not $tauriChosenRoot) {
$_tauriOverride = $envOverride
- if ($_tauriOverride -eq "~" -or $_tauriOverride -like "~/*" -or $_tauriOverride -like "~\*") {
- $_tauriOverride = (Join-Path $env:USERPROFILE $_tauriOverride.Substring(1).TrimStart('/','\'))
- }
try {
$_tauriOverride = Get-StudioFinalPath -Path $_tauriOverride
} catch {}
@@ -3218,10 +3226,6 @@ function Install-UnslothStudio {
$script:StudioEnvRootExisted = $false
if ($envOverride) {
- # Tilde expansion: env vars aren't subject to it when quoted on assignment.
- if ($envOverride -eq "~" -or $envOverride -like "~/*" -or $envOverride -like "~\*") {
- $envOverride = (Join-Path $env:USERPROFILE $envOverride.Substring(1).TrimStart('/','\'))
- }
try {
# BEFORE the create: this is the only moment anyone can still tell. The lock runs
# thousands of lines below and asks whether the root existed, which by then is yes for
@@ -4436,6 +4440,10 @@ function Install-UnslothStudio {
return (Get-CanonicalDir -Path $value)
}
+ # Anchor the master root before the System32 escape changes the working directory.
+ $_installMasterRoot = Get-MasterRootOverride
+ if ($_installMasterRoot) { $env:UNSLOTH_HOME = $_installMasterRoot }
+
# Explicit staging root, the master root, the shared default cache, or the custom Unsloth
# home's tree.
function Get-ManagedLlamaCppDir {
diff --git a/install.sh b/install.sh
index a604717b5ff..22b270fe711 100755
--- a/install.sh
+++ b/install.sh
@@ -1,5 +1,5 @@
#!/bin/sh
-# Unsloth Studio Installer. Usage, supported options and the web one-liner live in the README under "Unsloth Studio (web UI)" and are deliberately 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. A piped install takes options as environment variables after the pipe (UNSLOTH_NO_TORCH, UNSLOTH_SKIP_AUTOSTART, UNSLOTH_INSTALL_SYSTEMD, UNSLOTH_SYSTEMD_HOST, UNSLOTH_SYSTEMD_PORT, UNSLOTH_ISOLATE_UV_CACHE, UNSLOTH_INSTALL_NO_ROLLBACK, 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, --isolated-uv-cache, --no-rollback, --python, --local). Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME > $HOME/.unsloth/studio
+# Unsloth Studio Installer. Usage, supported options and the web one-liner live in the README under "Unsloth Studio (web UI)" and are deliberately 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. A piped install takes options as environment variables after the pipe (UNSLOTH_NO_TORCH, UNSLOTH_SKIP_AUTOSTART, UNSLOTH_INSTALL_SYSTEMD, UNSLOTH_SYSTEMD_HOST, UNSLOTH_SYSTEMD_PORT, UNSLOTH_ISOLATE_UV_CACHE, UNSLOTH_INSTALL_NO_ROLLBACK, 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, --isolated-uv-cache, --no-rollback, --python, --local). Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME > UNSLOTH_HOME/studio > $HOME/.unsloth/studio
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
set -e
@@ -95,42 +95,52 @@ fi
# Custom Unsloth roots are unsupported with --tauri unless override == legacy default.
if [ "$TAURI_MODE" = true ]; then
+ _tauri_canonical_root() (
+ _tcr_path=$1
+ case "$_tcr_path" in /*) ;; *) _tcr_path="$PWD/$_tcr_path" ;; esac
+ _tcr_tail=""
+ # Resolve the existing ancestor without creating a fresh install root.
+ while [ ! -d "$_tcr_path" ]; do
+ _tcr_tail="/${_tcr_path##*/}$_tcr_tail"
+ _tcr_path=${_tcr_path%/*}
+ [ -n "$_tcr_path" ] || _tcr_path=/
+ done
+ _tcr_path=$(CDPATH= cd -P -- "$_tcr_path" 2>/dev/null && pwd -P) || return 1
+ printf '%s\n' "$_tcr_path$_tcr_tail" | awk -F/ '{
+ for (i = 1; i <= NF; i++) {
+ if ($i == "" || $i == ".") continue
+ if ($i == "..") { if (n > 0) n-- }
+ else parts[++n] = $i
+ }
+ for (i = 1; i <= n; i++) printf "/%s", parts[i]
+ if (n == 0) printf "/"
+ printf "\n"
+ }'
+ )
_tauri_override_var=""
- _tauri_override="${UNSLOTH_STUDIO_HOME:-}"
+ _tauri_override=$(printf '%s' "${UNSLOTH_STUDIO_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
if [ -n "$_tauri_override" ]; then
_tauri_override_var="UNSLOTH_STUDIO_HOME"
else
- _tauri_override="${STUDIO_HOME:-}"
+ _tauri_override=$(printf '%s' "${STUDIO_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
[ -n "$_tauri_override" ] && _tauri_override_var="STUDIO_HOME"
fi
- # Strip whitespace so " " is treated as unset (matches Python .strip()).
- _tauri_override=$(printf '%s' "$_tauri_override" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
+ if [ -z "$_tauri_override" ]; then
+ _tauri_override=$(printf '%s' "${UNSLOTH_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
+ if [ -n "$_tauri_override" ]; then
+ _tauri_override_var="UNSLOTH_HOME (studio child)"
+ _tauri_override="${_tauri_override%/}/studio"
+ fi
+ fi
if [ -n "$_tauri_override" ]; then
case "$_tauri_override" in
"~") _tauri_override="$HOME" ;;
"~/"*) _tauri_override="$HOME/${_tauri_override#'~/'}" ;;
esac
- # Canonicalize both sides so CDPATH / a symlinked $HOME cannot break equality.
- if [ -d "$_tauri_override" ]; then
- _tauri_override_abs=$(CDPATH= cd -P -- "$_tauri_override" 2>/dev/null && pwd -P) \
- || _tauri_override_abs="$_tauri_override"
- else
- _tauri_override_abs="$_tauri_override"
- fi
- # Strip trailing separators so ".../studio/" matches ".../studio".
- while [ "$_tauri_override_abs" != "/" ] \
- && [ "${_tauri_override_abs%/}" != "$_tauri_override_abs" ]; do
- _tauri_override_abs=${_tauri_override_abs%/}
- done
- _tauri_legacy_root="$HOME/.unsloth/studio"
- if [ -d "$_tauri_legacy_root" ]; then
- _tauri_legacy_root=$(CDPATH= cd -P -- "$_tauri_legacy_root" 2>/dev/null && pwd -P) \
- || _tauri_legacy_root="$HOME/.unsloth/studio"
- fi
- while [ "$_tauri_legacy_root" != "/" ] \
- && [ "${_tauri_legacy_root%/}" != "$_tauri_legacy_root" ]; do
- _tauri_legacy_root=${_tauri_legacy_root%/}
- done
+ _tauri_override_abs=$(_tauri_canonical_root "$_tauri_override") \
+ || _tauri_override_abs="$_tauri_override"
+ _tauri_legacy_root=$(_tauri_canonical_root "$HOME/.unsloth/studio") \
+ || _tauri_legacy_root="$HOME/.unsloth/studio"
if [ "$_tauri_override_abs" != "$_tauri_legacy_root" ]; then
echo "ERROR: $_tauri_override_var is not supported with --tauri." >&2
echo " The desktop app still uses the legacy ~/.unsloth/studio root." >&2
@@ -596,15 +606,20 @@ PYTHON_VERSION="" # resolved after platform detection
_resolve_studio_destinations() {
_override_var=""
- _override="${UNSLOTH_STUDIO_HOME:-}"
+ _override=$(printf '%s' "${UNSLOTH_STUDIO_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
if [ -n "$_override" ]; then
_override_var="UNSLOTH_STUDIO_HOME"
else
- _override="${STUDIO_HOME:-}"
+ _override=$(printf '%s' "${STUDIO_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
[ -n "$_override" ] && _override_var="STUDIO_HOME"
fi
- # Strip surrounding whitespace so " " is treated as unset (matches Python .strip()).
- _override=$(printf '%s' "$_override" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
+ if [ -z "$_override" ]; then
+ _override=$(printf '%s' "${UNSLOTH_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
+ if [ -n "$_override" ]; then
+ _override_var="UNSLOTH_HOME (studio child)"
+ _override="${_override%/}/studio"
+ fi
+ fi
# Tilde expansion: quoted env vars aren't subject to it on assignment.
case "$_override" in
"~") _override="$HOME" ;;
@@ -2146,7 +2161,17 @@ LAUNCHER_EOF
_css_legacy_studio=$(CDPATH= cd -P -- "$_css_legacy_studio" 2>/dev/null && pwd -P) \
|| _css_legacy_studio="$HOME/.unsloth/studio"
fi
- if [ "$STUDIO_HOME" = "$_css_legacy_studio" ]; then
+ _css_master_root=$(printf '%s' "${UNSLOTH_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
+ if [ -n "$_css_master_root" ]; then
+ case "$_css_master_root" in
+ "~") _css_master_root="$HOME" ;;
+ "~/"*) _css_master_root="$HOME/${_css_master_root#'~/'}" ;;
+ esac
+ case "$_css_master_root" in /*) ;; *) _css_master_root="$PWD/$_css_master_root" ;; esac
+ _css_master_canon=$(CDPATH= cd -P -- "$_css_master_root" 2>/dev/null && pwd -P) || _css_master_canon=""
+ [ -z "$_css_master_canon" ] || _css_master_root="$_css_master_canon"
+ _css_llama_path="${_css_master_root%/}/llama.cpp"
+ elif [ "$STUDIO_HOME" = "$_css_legacy_studio" ]; then
_css_llama_path="$HOME/.unsloth/llama.cpp"
else
_css_llama_path="$STUDIO_HOME/llama.cpp"
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 80000eaa111..7a5194784b9 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -2627,6 +2627,7 @@ function Get-IntelRegistryAdapterNames {
function Get-ProbableStudioVenvDir {
$root = if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) { $env:UNSLOTH_STUDIO_HOME.Trim() }
elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) { $env:STUDIO_HOME.Trim() }
+ elseif (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_HOME)) { Join-Path $env:UNSLOTH_HOME.Trim() "studio" }
else { $null }
# Expand a leading ~ like the canonical resolver; without it the path stays cwd-relative.
if ($root -and ($root -eq "~" -or $root -like "~/*" -or $root -like "~\*")) {
@@ -3521,6 +3522,8 @@ if ($env:SKIP_STUDIO_BASE -ne "1") {
$env:UNSLOTH_STUDIO_HOME.Trim()
} elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) {
$env:STUDIO_HOME.Trim()
+ } elseif (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_HOME)) {
+ $env:UNSLOTH_HOME.Trim()
} else {
$_unslothRoot
}
@@ -3555,6 +3558,9 @@ if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) {
} elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) {
$_studioOverrideVar = "STUDIO_HOME"
$_studioOverride = $env:STUDIO_HOME.Trim()
+} elseif (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_HOME)) {
+ $_studioOverrideVar = "UNSLOTH_HOME (studio child)"
+ $_studioOverride = Join-Path $env:UNSLOTH_HOME.Trim() "studio"
}
if ($_studioOverride) {
if ($_studioOverride -eq "~" -or $_studioOverride -like "~/*" -or $_studioOverride -like "~\*") {
@@ -3651,11 +3657,7 @@ function Test-MasterRootNoteIsHonoured {
Write-StudioLine " UNSLOTH_HOME whenever you run Unsloth." -ForegroundColor Yellow
return $false
}
- # A note must describe the tree it is written into: every reader requires the Studio
- # directory to lie INSIDE the root it names, so a tree copied between master roots cannot aim
- # a removal at the original install. install.ps1 does not read UNSLOTH_HOME yet, so a master
- # root on an ordinary install leaves Studio at the legacy path with the runtimes elsewhere,
- # which is that shape: say so, rather than leave a file that behaves as no note at all.
+ # Reject split layouts: readers require Studio inside the recorded root to prevent deleting another install.
$sep = [System.IO.Path]::DirectorySeparatorChar
if (($here -ieq $norm) -or $here.StartsWith($norm + $sep, [System.StringComparison]::OrdinalIgnoreCase)) {
return $true
@@ -5745,16 +5747,8 @@ function Resolve-ReusedSetupPython {
(Test-Path -LiteralPath $env:UNSLOTH_SETUP_PYTHON)) {
return $env:UNSLOTH_SETUP_PYTHON
}
- $root = if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) { $env:UNSLOTH_STUDIO_HOME.Trim() }
- elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) { $env:STUDIO_HOME.Trim() }
- else { Join-Path $env:USERPROFILE ".unsloth\studio" }
- if ($root -eq "~") {
- # Join-Path with an empty child throws on Windows PowerShell 5.1.
- $root = $env:USERPROFILE
- } elseif ($root -like "~/*" -or $root -like "~\*") {
- $root = Join-Path $env:USERPROFILE $root.Substring(1).TrimStart('/', '\')
- }
- $venvPy = Join-Path $root "unsloth_studio\Scripts\python.exe"
+ # Root preflight already applied the overrides, including any staged update.
+ $venvPy = Join-Path $VenvDir "Scripts\python.exe"
if (Test-Path -LiteralPath $venvPy) { return $venvPy }
return $null
}
diff --git a/studio/setup.sh b/studio/setup.sh
index 7b42d50288e..36cd2ec576c 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -1722,17 +1722,22 @@ fi
# llama.cpp section needs STUDIO_HOME / _STUDIO_HOME_IS_CUSTOM, but
# UNSLOTH_STUDIO_LLAMA_ONLY=1 ('unsloth studio update') skips the base install.
# UNSLOTH_STUDIO_HOME (or STUDIO_HOME alias) overrides the install root
-# (mirrors install.sh). UNSLOTH_STUDIO_HOME wins when both are set.
+# (mirrors install.sh), followed by the studio/ child of UNSLOTH_HOME.
_studio_override_var=""
-_studio_override="${UNSLOTH_STUDIO_HOME:-}"
+_studio_override=$(printf '%s' "${UNSLOTH_STUDIO_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
if [ -n "$_studio_override" ]; then
_studio_override_var="UNSLOTH_STUDIO_HOME"
else
- _studio_override="${STUDIO_HOME:-}"
+ _studio_override=$(printf '%s' "${STUDIO_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
[ -n "$_studio_override" ] && _studio_override_var="STUDIO_HOME"
fi
-# Strip whitespace so " " is treated as unset (matches Python .strip()).
-_studio_override=$(printf '%s' "$_studio_override" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
+if [ -z "$_studio_override" ]; then
+ _studio_override=$(printf '%s' "${UNSLOTH_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
+ if [ -n "$_studio_override" ]; then
+ _studio_override_var="UNSLOTH_HOME (studio child)"
+ _studio_override="${_studio_override%/}/studio"
+ fi
+fi
case "$_studio_override" in
"~") _studio_override="$HOME" ;;
"~/"*) _studio_override="$HOME/${_studio_override#'~/'}" ;;
@@ -4735,12 +4740,7 @@ _master_root_note_is_honoured() {
echo " you run Unsloth." >&2
return 1
fi
- # A note must describe the tree it is written into: all four readers require the Studio
- # directory to lie INSIDE the root it names, so a tree copied between master roots cannot
- # aim a removal at the original install. install.sh and install.ps1 do not read UNSLOTH_HOME
- # yet, so `UNSLOTH_HOME=/mnt/portable unsloth studio update` leaves Studio at
- # ~/.unsloth/studio with the runtimes at /mnt/portable, which is exactly that shape: warn,
- # rather than leave a file that reads as a recorded root and behaves as none.
+ # Reject split layouts: readers require Studio inside the recorded root to prevent deleting another install.
case "$STUDIO_HOME" in
"$_mrn_root"|"$_mrn_root"/*) return 0 ;;
esac
diff --git a/tests/python/test_installer_master_root.py b/tests/python/test_installer_master_root.py
new file mode 100644
index 00000000000..f66e7db2e94
--- /dev/null
+++ b/tests/python/test_installer_master_root.py
@@ -0,0 +1,314 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+from unsloth_pwsh_runner import PWSH, run_pwsh
+
+REPO = Path(__file__).resolve().parents[2]
+POSIX = pytest.mark.skipif(os.name == "nt", reason = "POSIX")
+WINDOWS = pytest.mark.skipif(not PWSH, reason = "PowerShell")
+PS_PRELUDE = """$ErrorActionPreference = 'Stop'
+function Write-StudioLine { param($Message, $ForegroundColor) }
+function substep { param($Message) }
+function Restore-StudioTempEnvironment {}
+function Exit-SetupFailure { param($Message) throw $Message }
+"""
+
+
+def _part(filename, start, end):
+ source = (REPO / filename).read_text(encoding = "utf-8")
+ begin = source.index(start)
+ return source[begin : source.index(end, begin)]
+
+
+def env(tmp_path):
+ result = dict(os.environ, HOME = str(tmp_path), USERPROFILE = str(tmp_path))
+ for key in (
+ "UNSLOTH_HOME",
+ "UNSLOTH_STUDIO_HOME",
+ "STUDIO_HOME",
+ "UNSLOTH_LLAMA_CPP_PATH",
+ "UNSLOTH_SETUP_PYTHON",
+ "UNSLOTH_STUDIO_STAGE_ROOT",
+ ):
+ result.pop(key, None)
+ return result
+
+
+def _run(
+ script,
+ env,
+ cwd,
+ powershell = False,
+ expected_exit = 0,
+):
+ if (powershell and not PWSH) or (not powershell and os.name == "nt"):
+ pytest.skip("shell unavailable")
+ argv = [PWSH, "-NoProfile", "-NonInteractive", "-Command"] if powershell else ["sh", "-c"]
+ run = run_pwsh if powershell else subprocess.run
+ result = run(argv + [script], env = env, cwd = cwd, capture_output = True, text = True, timeout = 60)
+ assert result.returncode == expected_exit, result.stdout + result.stderr
+ return result
+
+
+def _root_script(filename):
+ if filename == "install.sh":
+ body = _part(filename, "_resolve_studio_destinations() {", "\n}\n")
+ return (
+ "set -eu\nsubstep() { :; }\n"
+ + body
+ + '\n}\n_resolve_studio_destinations\necho "$STUDIO_HOME|$_STUDIO_HOME_REDIRECT"'
+ )
+ if filename == "studio/setup.sh":
+ return (
+ 'set -eu\nsetup_fail() { exit "$1"; }\n'
+ + _part(filename, '_studio_override_var=""', "\nSTAGE_ROOT=")
+ + '\necho "$STUDIO_HOME"'
+ )
+ if filename == "install.ps1":
+ body = "$defaultProfile = $null\n$defaultDataDir = 'unused'\n$tauriChosenRoot = $false\n"
+ body += "$tauriProfile = $env:USERPROFILE\n"
+ body += _part(filename, " $envOverrideVar = $null", " $defaultProfile = $null")
+ for name in (
+ "Resolve-StudioLinkTarget",
+ "Get-StudioSubstTarget",
+ "Get-StudioLexicalPath",
+ "Resolve-StudioFinalPathInfo",
+ "Get-StudioFinalPath",
+ "Test-StudioSameDirectoryByProbe",
+ "Split-StudioExistingAncestor",
+ ):
+ body += _part(filename, f" function {name} {{", "\n }\n") + "\n }\n"
+ body += "function Get-StudioPythonFinalPath { param($Path) return $null }\n"
+ body += "function Write-StudioFinalPathDegraded { param($Reason) }\n"
+ body += _part(
+ filename,
+ " # Custom Unsloth roots are not supported with --tauri",
+ " # LOCALAPPDATA may be unset",
+ )
+ body += _part(
+ filename, " # Cleared per invocation:", " $VenvDir = Join-Path $StudioHome"
+ )
+ return PS_PRELUDE + body + '\n"$StudioHome|$StudioRedirectMode"'
+ return (
+ PS_PRELUDE
+ + _part(filename, "$_studioOverrideVar = $null", "$StudioOwnedMarker = ")
+ + '\n"$StudioHome"\n'
+ )
+
+
+ "filename", ["install.sh", "studio/setup.sh", "install.ps1", "studio/setup.ps1", "cli"]
+)
+ "studio, alias, master, expected",
+ [
+ ("", "", "", ".unsloth/studio"),
+ ("chosen", "", "", "chosen"),
+ ("", "alias", "", "alias"),
+ ("chosen", "alias", "", "chosen"),
+ ("chosen", "", "portable", "chosen"),
+ ("", "alias", "portable", "alias"),
+ ("", "", "{home}/portable [1]", "portable [1]/studio"),
+ (" \t ", " ", " portable [1] ", "portable [1]/studio"),
+ ("chosen", "ignored", "portable", "chosen"),
+ (" \t ", "alias", "portable", "alias"),
+ ("", "", "~/portable", "portable/studio"),
+ ("", "", "~", "studio"),
+ ("~/chosen space [1]", "", "", "chosen space [1]"),
+ ("", "~/alias space [1]", "", "alias space [1]"),
+ ("", "", " \t ", ".unsloth/studio"),
+ ],
+)
+def test_install_and_setup_root_precedence(
+ tmp_path, env, filename, studio, alias, master, expected
+):
+ for key, value in zip(
+ ("UNSLOTH_STUDIO_HOME", "STUDIO_HOME", "UNSLOTH_HOME"), (studio, alias, master)
+ ):
+ env[key] = value.format(home = tmp_path)
+ root = tmp_path / expected
+ if filename.startswith("studio/"):
+ root.mkdir(parents = True)
+ if filename == "cli":
+ env["PYTHONPATH"] = str(REPO)
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ "from unsloth_cli.commands.studio import STUDIO_HOME; print(STUDIO_HOME)",
+ ],
+ env = env,
+ cwd = tmp_path,
+ capture_output = True,
+ text = True,
+ timeout = 60,
+ )
+ assert result.returncode == 0, result.stderr
+ assert Path(result.stdout.strip()).resolve() == root.resolve()
+ return
+ output = _run(
+ _root_script(filename), env, tmp_path, powershell = filename.endswith(".ps1")
+ ).stdout.strip()
+ chosen, *mode = output.split("|")
+ assert Path(chosen).resolve() == root.resolve()
+ if mode and master.strip():
+ assert mode == ["env"]
+
+
+@POSIX
+ "master, studio, alias, accepted",
+ [
+ (" portable [1] ", "", "", False),
+ ("portable", " \t ", " ", False),
+ ("", " \t ", "custom", False),
+ ("portable", "{home}/.unsloth/studio", "ignored", True),
+ ("~/.unsloth/", "", "", True),
+ (".unsloth", "", "", True),
+ ("./.unsloth", "", "", True),
+ ("missing/../.unsloth", "", "", True),
+ ("", ".unsloth/studio", "", True),
+ ("", "", "./.unsloth/studio", True),
+ ],
+)
+def test_desktop_guard_uses_selected_root(tmp_path, env, master, studio, alias, accepted):
+ for key, value in zip(
+ ("UNSLOTH_HOME", "UNSLOTH_STUDIO_HOME", "STUDIO_HOME"), (master, studio, alias)
+ ):
+ env[key] = value.format(home = tmp_path)
+ # Run argument parsing and the guard, stopping before any install work.
+ script = (
+ _part("install.sh", "#!/bin/sh", "\n_is_verbose() {")
+ + "\necho accepted\n}\n_unsloth_main --tauri"
+ )
+ result = _run(script, env, tmp_path, expected_exit = 0 if accepted else 1)
+ assert (
+ "accepted" in result.stdout if accepted else "not supported with --tauri" in result.stderr
+ )
+ assert not any(tmp_path.iterdir())
+
+
+@WINDOWS
[email protected]("handoff", [None, "UNSLOTH_STUDIO_STAGE_ROOT", "UNSLOTH_SETUP_PYTHON"])
+def test_setup_reuses_python_without_system_python(tmp_path, env, handoff):
+ studio = tmp_path / "portable" / "studio"
+ studio.mkdir(parents = True)
+ env["UNSLOTH_HOME"] = str(studio.parent)
+ runtime = tmp_path / "handoff [1]" if handoff else studio
+ venv = runtime / "unsloth_studio"
+ subprocess.run(
+ [sys.executable, "-m", "venv", "--without-pip", str(venv)], check = True, timeout = 60
+ )
+ python = venv / "Scripts" / "python.exe"
+ if os.name != "nt":
+ python.parent.mkdir()
+ python.symlink_to(venv / "bin" / "python")
+ if handoff:
+ env[handoff] = str(python if handoff == "UNSLOTH_SETUP_PYTHON" else runtime)
+ script = (
+ _root_script("studio/setup.ps1")
+ + """
+$env:PATH = ''
+function winget { throw 'Unexpected system Python installation' }
+"""
+ )
+ script += _part(
+ "studio/setup.ps1", "$CondaSkipPattern = ", "# Add user-scheme Python Scripts dir"
+ )
+ script += (
+ '\nif (-not $PythonOk) { throw "Python prerequisite failed" }\n"$ValidatedSetupPython"'
+ )
+ output = _run(script, env, tmp_path, powershell = True).stdout.splitlines()
+ assert output[-1] == str(python)
+
+
+@WINDOWS
+def test_windows_relative_master_survives_directory_change(tmp_path, env):
+ env["UNSLOTH_HOME"] = "portable"
+ (tmp_path / "elsewhere").mkdir()
+ script = PS_PRELUDE + "function Get-PathState { param($Path, $PathType) return 'Missing' }\n"
+ script += _part("install.ps1", " function Get-CanonicalDir {", "\n }\n") + "\n }\n"
+ script += _part(
+ "install.ps1", " function Get-MasterRootOverride {", " # Explicit staging root,"
+ )
+ script += "\nSet-Location -LiteralPath 'elsewhere'\nGet-MasterRootOverride"
+ assert (
+ Path(_run(script, env, tmp_path, powershell = True).stdout.strip()) == tmp_path / "portable"
+ )
+
+
+@WINDOWS
+def test_windows_install_root_uses_powershell_working_directory(tmp_path, env):
+ caller = tmp_path / "caller space [1]"
+ caller.mkdir()
+ env["UNSLOTH_HOME"] = "portable"
+ script = "Set-Location -LiteralPath 'caller space [1]'\n" + _root_script("install.ps1")
+ output = _run(script, env, tmp_path, powershell = True).stdout.strip()
+ assert Path(output.split("|")[0]) == caller / "portable" / "studio"
+ assert not (tmp_path / "portable").exists()
+
+
+@WINDOWS
[email protected]("variable", ["UNSLOTH_HOME", "UNSLOTH_STUDIO_HOME", "STUDIO_HOME"])
[email protected]("accepted", [False, True])
+def test_windows_tauri_root_uses_powershell_working_directory(tmp_path, env, variable, accepted):
+ caller = tmp_path / "caller space [1]"
+ caller.mkdir()
+ env["USERPROFILE"] = str(caller)
+ env.pop("UNSLOTH_DESKTOP_CHOSEN_STUDIO_HOME", None)
+ root = ".unsloth" if accepted else "custom"
+ env[variable] = root if variable == "UNSLOTH_HOME" else root + "/studio"
+ script = "$TauriMode = $true\nSet-Location -LiteralPath 'caller space [1]'\n"
+ result = _run(
+ script + _root_script("install.ps1"),
+ env,
+ tmp_path,
+ powershell = True,
+ expected_exit = 0 if accepted else 1,
+ )
+ if accepted:
+ assert Path(result.stdout.strip().split("|")[0]) == caller / ".unsloth" / "studio"
+ else:
+ assert "not supported with --tauri" in result.stderr
+ assert not any(caller.iterdir())
+ assert not (tmp_path / root).exists()
+
+
+@POSIX
[email protected]("prefix", ["", "~/"])
+def test_saved_launcher_keeps_runtime_path_without_master_env(tmp_path, env, prefix):
+ master = tmp_path / "portable space's [1]"
+ studio = master / "studio"
+ (studio / "share").mkdir(parents = True)
+ (master / "llama.cpp").mkdir()
+ config = studio / "share" / "studio.conf"
+ saved_env = dict(
+ env,
+ UNSLOTH_HOME = f" {prefix}{master.name} ",
+ STUDIO_HOME = str(studio),
+ _STUDIO_HOME_REDIRECT = "env",
+ _css_data_dir = str(config.parent),
+ _css_quoted_exe = "unused",
+ _css_id_file = "unused",
+ )
+ block = _part(
+ "install.sh",
+ " {\n printf '%s\\n' \"UNSLOTH_EXE=",
+ ' > "$_css_data_dir/studio.conf"',
+ )
+ _run(block + ' > "$_css_data_dir/studio.conf"', saved_env, tmp_path)
+ env["TEST_CONFIG"] = str(config)
+ for override in ("", str(tmp_path / "external llama")):
+ env["UNSLOTH_LLAMA_CPP_PATH"] = override
+ script = (
+ '. "$TEST_CONFIG"\nprintf "%s\\n%s\\n" "$UNSLOTH_STUDIO_HOME" "$UNSLOTH_LLAMA_CPP_PATH"'
+ )
+ output = _run(script, env, tmp_path).stdout.splitlines()
+ assert output == [str(studio), override or str(master / "llama.cpp")]
diff --git a/tests/test_unsloth_home_root_agreement.py b/tests/test_unsloth_home_root_agreement.py
index f74dca10f9f..e5c782ce14f 100644
--- a/tests/test_unsloth_home_root_agreement.py
+++ b/tests/test_unsloth_home_root_agreement.py
@@ -24,8 +24,17 @@ import subprocess
import sys
from pathlib import Path
+import pytest
+
REPO_ROOT = Path(__file__).resolve().parents[1]
+
[email protected](autouse = True)
+def isolated_home(tmp_path, monkeypatch):
+ for key in ("HOME", "USERPROFILE"):
+ monkeypatch.setenv(key, str(tmp_path / "home"))
+
+
_PROBE = """
import json, sys
sys.path.insert(0, {backend!r})
@@ -46,7 +55,7 @@ print(json.dumps({{
"""
-def _probe(env_overrides: dict) -> dict:
+def _probe(env_overrides: dict, prefix: Path | None = None) -> dict:
env = dict(os.environ)
# Clear UNSLOTH_LLAMA_CPP_PATH too, as _main_probe does: an inherited value measures the runner.
for key in ("UNSLOTH_HOME", "UNSLOTH_STUDIO_HOME", "STUDIO_HOME", "UNSLOTH_LLAMA_CPP_PATH"):
@@ -54,6 +63,8 @@ def _probe(env_overrides: dict) -> dict:
env.update(env_overrides)
env["PYTHONPATH"] = str(REPO_ROOT)
source = _PROBE.format(backend = str(REPO_ROOT / "studio" / "backend"))
+ if prefix is not None:
+ source = f"import sys\nsys.prefix = {str(prefix)!r}\n" + source
out = subprocess.run(
[sys.executable, "-c", source],
capture_output = True,
@@ -65,6 +76,32 @@ def _probe(env_overrides: dict) -> dict:
return json.loads(out.stdout.strip().splitlines()[-1])
[email protected]("installed", [False, True])
+def test_cli_infers_only_a_managed_interpreter_root(tmp_path, installed):
+ root = tmp_path / "custom"
+ if installed:
+ (root / "share").mkdir(parents = True)
+ (root / "share" / "studio.conf").write_text("installed\n", encoding = "utf-8")
+ result = _probe({}, prefix = root / "unsloth_studio")
+ expected = root if installed else tmp_path / "home" / ".unsloth" / "studio"
+ assert result["cli"] == str(expected)
+ assert result["backend"] == str(expected)
+ assert result["cli_is_custom"] is installed
+
+
+def test_cli_keeps_custom_root_when_resolution_fails(tmp_path, monkeypatch):
+ from unsloth_cli.commands import studio
+
+ custom = tmp_path / "custom"
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(custom))
+
+ def unavailable(self):
+ raise OSError("filesystem unavailable")
+
+ monkeypatch.setattr(Path, "resolve", unavailable)
+ assert studio._resolve_studio_home() == (custom, True)
+
+
def test_unsloth_home_resolves_to_one_studio_root(tmp_path):
master = tmp_path / "portable"
result = _probe({"UNSLOTH_HOME": str(master)})
@@ -152,11 +189,10 @@ def test_a_plain_custom_root_still_keeps_llama_cpp_inside_it(tmp_path):
def test_a_master_root_the_cli_declined_is_still_told_to_the_backend(tmp_path):
- """A declined UNSLOTH_HOME must still reach the backend, or the CLI and backend use different roots."""
home = tmp_path / "home"
- conf = home / ".unsloth" / "studio" / "share" / "studio.conf"
- conf.parent.mkdir(parents = True)
- conf.write_text("installed\n", encoding = "utf-8")
+ install_id = home / ".unsloth" / "studio" / "share" / "studio_install_id"
+ install_id.parent.mkdir(parents = True)
+ install_id.write_text("ab" * 32 + "\n", encoding = "utf-8")
result = _probe(
{
@@ -174,6 +210,59 @@ def test_a_master_root_the_cli_declined_is_still_told_to_the_backend(tmp_path):
assert result["backend"] == legacy
+def test_a_new_master_install_wins_over_an_existing_legacy_install(tmp_path):
+ home = tmp_path / "home"
+ master = tmp_path / "portable"
+ for root in (home / ".unsloth" / "studio", master / "studio"):
+ (root / "share").mkdir(parents = True)
+ (root / "share" / "studio.conf").write_text("installed\n", encoding = "utf-8")
+ result = _probe({"HOME": str(home), "USERPROFILE": str(home), "UNSLOTH_HOME": str(master)})
+ assert result["cli"] == str(master / "studio")
+ assert result["backend"] == result["cli"]
+ assert result["cli_is_custom"] is True
+ assert result["cli_llama"] == str(master / "llama.cpp")
+
+
+def test_update_keeps_an_existing_legacy_install(tmp_path):
+ home = tmp_path / "home"
+ legacy = home / ".unsloth" / "studio"
+ (legacy / "share").mkdir(parents = True)
+ (legacy / "share" / "studio_install_id").write_text("ab" * 32 + "\n", encoding = "utf-8")
+ source = """
+import contextlib, json, os
+from unsloth_cli.commands import studio as cli
+calls = []
+def capture(**kwargs):
+ calls.append(os.environ.get('UNSLOTH_STUDIO_HOME'))
+cli._studio_runtime_launch_guard = lambda **kwargs: contextlib.nullcontext()
+cli._studio_runtime_gate.consume_runtime_gate_handoff = lambda: False
+cli._studio_runtime_gate.ensure_managed_environment_is_idle = lambda root: None
+class Transaction(contextlib.nullcontext):
+ def __enter__(self): return self
+ def validate_launcher(self): pass
+cli._WindowsLauncherUpdateTransaction = Transaction
+cli._run_setup_script = capture
+cli._refresh_desktop_shortcuts = capture
+cli.update(local=False, package='unsloth', verbose=False, verify=False, stage=False)
+print(json.dumps(calls))
+"""
+ env = dict(os.environ, HOME = str(home), USERPROFILE = str(home), PYTHONPATH = str(REPO_ROOT))
+ for key in ("UNSLOTH_STUDIO_HOME", "STUDIO_HOME", "UNSLOTH_STUDIO_STAGE_ROOT"):
+ env.pop(key, None)
+ env["UNSLOTH_HOME"] = str(tmp_path / "portable")
+ run = subprocess.run(
+ [sys.executable, "-c", source],
+ env = env,
+ cwd = REPO_ROOT,
+ capture_output = True,
+ text = True,
+ check = True,
+ timeout = 60,
+ )
+ assert json.loads(run.stdout.strip().splitlines()[-1]) == [str(legacy), str(legacy)]
+ assert not (tmp_path / "portable").exists()
+
+
def test_a_whitespace_studio_home_does_not_defeat_the_export(tmp_path):
"""Export guard must strip whitespace too: every resolver treats a whitespace-only value as unset."""
home = tmp_path / "home"
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 9baf0f094d0..33fdfe9df4a 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -50,9 +50,10 @@ _CMD_SHIM_MAX_BYTES = 8192
def _looks_like_installer_managed_studio_home(candidate: Path) -> bool:
- """Sentinel (share/studio.conf, or our own bin/unsloth.cmd) so a dev venv named
- unsloth_studio is not taken for a custom root. It must be OUR shim: the dir is on PATH."""
- if (candidate / "share" / "studio.conf").is_file():
+ # Default POSIX installs keep studio.conf outside the install tree.
+ if (candidate / "share" / "studio.conf").is_file() or (
+ candidate / "share" / "studio_install_id"
+ ).is_file():
return True
if platform.system() != "Windows":
return (candidate / "bin" / "unsloth").is_file()
@@ -91,10 +92,7 @@ def _resolve_studio_home() -> tuple[Path, bool]:
legacy = (Path.home() / ".unsloth" / "studio").resolve()
except (OSError, ValueError):
legacy = Path.home() / ".unsloth" / "studio"
- # install.sh and install.ps1 do not read UNSLOTH_HOME yet, so they leave the venv and the
- # launcher at the legacy root while setup puts the runtimes under the master root:
- # preferring <master>/studio unconditionally reported "Unsloth Studio not set up" for an
- # install that is right there. The master root wins only when it HAS an install.
+ # Preserve legacy installs until a managed install exists at the master root.
if candidate != legacy and not _looks_like_installer_managed_studio_home(candidate):
if _looks_like_installer_managed_studio_home(legacy):
return legacy, False