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: record how a Windows install was launched and what it produced (#8066)

Michael Han42e7ff09838c
diff --git a/install.ps1 b/install.ps1
index 134531c9e74..afde611d1cc 100644
--- a/install.ps1
+++ b/install.ps1
@@ -735,6 +735,87 @@ function Install-UnslothStudio {
# able to complete, over a package it will not install.
if ($SkipTorch) { $PythonSkip = @() }
+ # An elevated run writes the install root as Administrators and the same account cannot
+ # read it back afterwards. Twin in studio/setup.ps1.
+ function Get-ElevationState {
+ try {
+ $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
+ $principal = New-Object System.Security.Principal.WindowsPrincipal($identity)
+ if ($principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
+ return "true"
+ }
+ return "false"
+ } catch {
+ return "unknown"
+ }
+ }
+
+ # Recorded either way; install.rs record_diag_marker puts it in the support report.
+ function Write-ElevationNotice {
+ param(
+ [Parameter(Mandatory = $true)][string]$State,
+ [Parameter(Mandatory = $true)][AllowEmptyString()][string]$Root,
+ # UNSLOTH_TAURI_MODE is not assigned until the setup call far below; --tauri is.
+ [switch]$Tauri
+ )
+
+ if ($Tauri) {
+ [Console]::Out.WriteLine("[TAURI:DIAG] elevated=$State")
+ [Console]::Out.Flush()
+ }
+ if ($State -ne "true") { return }
+ Write-StudioLine " [WARNING] Running as administrator. Unsloth does not need this." -ForegroundColor Yellow
+ Write-StudioLine " Anything written to $Root will be owned by Administrators," -ForegroundColor Yellow
+ Write-StudioLine " and your normal account will not be able to read it afterwards." -ForegroundColor Yellow
+ Write-StudioLine " That folder outlives an uninstall, so a later install, setup or" -ForegroundColor Yellow
+ Write-StudioLine " update run normally fails on it." -ForegroundColor Yellow
+ Write-StudioLine " Stop and start again without 'Run as administrator'." -ForegroundColor Yellow
+ Write-StudioLine ""
+ }
+
+ function Get-CanonicalRootPath {
+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
+ if ([string]::IsNullOrWhiteSpace($Path)) { return "" }
+ $_p = $Path.Trim()
+ if (($_p -eq "~" -or $_p -like "~/*" -or $_p -like "~\*") -and
+ -not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
+ # A bare "~" leaves an empty child path, which Join-Path rejects on PS 5.1.
+ $_rest = $_p.Substring(1).TrimStart('/', '\')
+ $_p = if ($_rest) { Join-Path $env:USERPROFILE $_rest } else { $env:USERPROFILE }
+ }
+ # GetFullPath anchors a relative path to [Environment]::CurrentDirectory, which
+ # Set-Location does not move, so it disagreed with the Resolve-Path based resolver
+ # (PowerShell#10278, by design). It stays as the fallback, never the first answer.
+ try {
+ $_p = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_p)
+ } catch {
+ try { $_p = [System.IO.Path]::GetFullPath($_p) } catch { }
+ }
+ return $_p.TrimEnd('\', '/')
+ }
+
+ # Warn before the resolver below creates and probes the root, so mirror its precedence
+ # rather than reuse the unassigned $StudioHome. USERPROFILE can be unset (service, CI).
+ $UnslothRoot = if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
+ '%USERPROFILE%\.unsloth'
+ } else {
+ Join-Path $env:USERPROFILE ".unsloth"
+ }
+ $ElevationRoot = 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 {
+ $UnslothRoot
+ }
+ # A legacy-equal override is not a custom root: llama.cpp and node stay siblings of
+ # studio under ~/.unsloth, so name that parent.
+ if ((Get-CanonicalRootPath $ElevationRoot) -ieq
+ (Get-CanonicalRootPath (Join-Path $UnslothRoot "studio"))) {
+ $ElevationRoot = $UnslothRoot
+ }
+ Write-ElevationNotice -State (Get-ElevationState) -Root $ElevationRoot -Tauri:$TauriMode
+
# Whitespace-only == unset (matches the Python resolvers' .strip()).
$envOverrideVar = $null
$envOverride = $null
@@ -6446,85 +6527,120 @@ sys.exit(2 if conflict else (0 if installed else 1))
Write-StudioLine " Re-run the installer to rebuild the environment." -ForegroundColor Yellow
return (Exit-InstallFailure "managed Python is missing at $VenvPython")
}
- # Tell setup.ps1 to skip base package installation (install.ps1 already did it)
- $env:SKIP_STUDIO_BASE = "1"
- $env:STUDIO_PACKAGE_NAME = $PackageName
- $env:UNSLOTH_NO_TORCH = if ($SkipTorch) { "true" } else { "false" }
- # The torch family THIS run settled on, for setup.ps1's preserve guard (full rationale there,
- # at $InstallerTorchTag): "a GPU wheel is in the venv" is not on its own evidence that this
- # installer put it there -- the migrated-venv arm above installs unsloth only and never
- # touches torch. Empty means "no answer": --no-torch, or a custom index whose leaf names no
- # flavor. Always assigned so a previous run in the same session cannot leak a value; 7.5+
- # keeps it present and blank, 5.1 / 7.0-7.4 remove it, and setup.ps1 treats both as unknown.
- $env:UNSLOTH_INSTALLER_TORCH_TAG = if ($SkipTorch) { "" } else {
- [string](Get-ExpectedTorchFlavorTag -TorchIndexUrl $TorchIndexUrl -ROCmIndexUrl $ROCmIndexUrl)
- }
- # Tauri desktop app bundles its own frontend — skip Node/npm/frontend build
- $env:SKIP_STUDIO_FRONTEND = if ($TauriMode) { "1" } else { "0" }
- # Always set explicitly: a stale value from a previous --local run would leak.
- if ($StudioLocalInstall) {
- $env:STUDIO_LOCAL_INSTALL = "1"
- $env:STUDIO_LOCAL_REPO = $RepoRoot
- } else {
- $env:STUDIO_LOCAL_INSTALL = "0"
- Remove-Item Env:STUDIO_LOCAL_REPO -ErrorAction SilentlyContinue
- }
- # 'setup', not 'update': update pops SKIP_STUDIO_BASE and skips the #4667 fast path.
+ # `irm | iex` runs in the caller's shell, so every handoff variable is saved and restored.
+ # Captures sit above the try, or a finally reached first reads the unset $hadPrevious* as
+ # "there was nothing here" and clears a value it never set.
+ $previousSkipStudioBase = $env:SKIP_STUDIO_BASE
+ $hadPreviousSkipStudioBase = ($null -ne $previousSkipStudioBase)
+ # Propagate UNSLOTH_STUDIO_HOME only for env-override installs; otherwise
+ # an inherited value would put llama.cpp in the wrong place.
$previousUnslothStudioHome = $env:UNSLOTH_STUDIO_HOME
$hadPreviousUnslothStudioHome = ($null -ne $previousUnslothStudioHome)
$previousTauriMode = $env:UNSLOTH_TAURI_MODE
$hadPreviousTauriMode = ($null -ne $previousTauriMode)
- $env:UNSLOTH_TAURI_MODE = if ($TauriMode) { "1" } else { "0" }
- if ($StudioRedirectMode -eq 'env') {
- $env:UNSLOTH_STUDIO_HOME = $StudioHome
- } else {
- Remove-Item Env:UNSLOTH_STUDIO_HOME -ErrorAction SilentlyContinue
- }
- $studioArgs = @('studio', 'setup')
- if ($script:UnslothVerbose) { $studioArgs += '--verbose' }
- if ($WithLlamaCppDir) {
- if (-not (Test-Path -LiteralPath $WithLlamaCppDir -PathType Container)) {
- Write-StudioLine "[ERROR] --with-llama-cpp-dir path does not exist: $WithLlamaCppDir" -ForegroundColor Red
- return (Exit-InstallFailure "--with-llama-cpp-dir path does not exist.")
- }
- $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR = (Resolve-Path -LiteralPath $WithLlamaCppDir).Path
- }
- $env:UNSLOTH_INSTALL_ROLLBACK_MANAGED = "1"
- # Hand setup.ps1 the venv interpreter so it does not re-probe a PATH led by a stub.
- $env:UNSLOTH_SETUP_PYTHON = Join-Path $VenvDir "Scripts\python.exe"
- # Installer already owns the runtime mutex; the child inherits it rather
- # than deadlocking trying to reacquire it.
$previousSetupRuntimeGateHandoff = $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF
$hadPreviousSetupRuntimeGateHandoff = ($null -ne $previousSetupRuntimeGateHandoff)
- $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"
- # The proxy defaults kept out of the discarded profile table, for the duration of the child
- # only. setup.ps1 runs with -NoProfile and downloads on its own; see the prologue.
$previousProxyHandoff = $env:_UNSLOTH_PS_PROXY_DEFAULTS
$hadPreviousProxyHandoff = ($null -ne $previousProxyHandoff)
- # Set even when there is nothing to hand over: its ABSENCE is how the CLI recognises a
- # standalone update and goes looking through the user's profiles. An empty object says "the
- # installer looked, and there is none".
- $env:_UNSLOTH_PS_PROXY_DEFAULTS =
- if ($UnslothProxyHandoffJson) { $UnslothProxyHandoffJson } else { '{}' }
- # Forward the arch this run resolved. Both scripts scan WMI, so a scan that answers here but
- # not there leaves setup expecting cpu torch against the ROCm wheels just installed: it
- # reports "needs repair", the installer rolls back, and the app retries that forever.
- #
- # PRIVATE, not UNSLOTH_ROCM_GFX_ARCH: install_llama_prebuilt.py reads that one back as
- # _manual to decide whether a forwarded --rocm-gfx outranks its own probe, and this scan is
- # the weaker of the two anyway (first AMD adapter, no visible-device mask, no shadowing-iGPU
- # repick, all of which setup.ps1 applies). So setup consumes it only after its own probes
- # come up empty, and nested installers never see it.
$previousRocmGfxHandoff = $env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF
$hadPreviousRocmGfxHandoff = ($null -ne $previousRocmGfxHandoff)
- if ($ROCmGfxArch) {
- $env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF = $ROCmGfxArch
- } else {
- # Cleared, not left alone: an inherited value from an outer process is not this run's
- # answer, and handing it down would forward an arch nothing here detected.
- Remove-Item Env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF -ErrorAction SilentlyContinue
- }
+ # SKIP_STUDIO_FRONTEND is the one with teeth: a leaked "1" makes the next direct
+ # `unsloth studio setup` skip the frontend build, leaving a source install with no web UI.
+ $previousStudioPackageName = $env:STUDIO_PACKAGE_NAME
+ $hadPreviousStudioPackageName = ($null -ne $previousStudioPackageName)
+ $previousNoTorch = $env:UNSLOTH_NO_TORCH
+ $hadPreviousNoTorch = ($null -ne $previousNoTorch)
+ $previousInstallerTorchTag = $env:UNSLOTH_INSTALLER_TORCH_TAG
+ $hadPreviousInstallerTorchTag = ($null -ne $previousInstallerTorchTag)
+ $previousSkipStudioFrontend = $env:SKIP_STUDIO_FRONTEND
+ $hadPreviousSkipStudioFrontend = ($null -ne $previousSkipStudioFrontend)
+ $previousStudioLocalInstall = $env:STUDIO_LOCAL_INSTALL
+ $hadPreviousStudioLocalInstall = ($null -ne $previousStudioLocalInstall)
+ $previousStudioLocalRepo = $env:STUDIO_LOCAL_REPO
+ $hadPreviousStudioLocalRepo = ($null -ne $previousStudioLocalRepo)
+ # Cleared unconditionally before, which the --with-llama-cpp-dir bail reaches without
+ # having set them. UNSLOTH_LOCAL_LLAMA_CPP_DIR is a user-facing input this script reads.
+ $previousLocalLlamaCppDir = $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR
+ $hadPreviousLocalLlamaCppDir = ($null -ne $previousLocalLlamaCppDir)
+ $previousInstallRollbackManaged = $env:UNSLOTH_INSTALL_ROLLBACK_MANAGED
+ $hadPreviousInstallRollbackManaged = ($null -ne $previousInstallRollbackManaged)
+ $previousSetupPython = $env:UNSLOTH_SETUP_PYTHON
+ $hadPreviousSetupPython = ($null -ne $previousSetupPython)
try {
+ $env:SKIP_STUDIO_BASE = "1"
+ $env:STUDIO_PACKAGE_NAME = $PackageName
+ $env:UNSLOTH_NO_TORCH = if ($SkipTorch) { "true" } else { "false" }
+ # The torch family THIS run settled on, for setup.ps1's preserve guard (full rationale there,
+ # at $InstallerTorchTag): "a GPU wheel is in the venv" is not on its own evidence that this
+ # installer put it there -- the migrated-venv arm above installs unsloth only and never
+ # touches torch. Empty means "no answer": --no-torch, or a custom index whose leaf names no
+ # flavor. Always assigned so a previous run in the same session cannot leak a value; 7.5+
+ # keeps it present and blank, 5.1 / 7.0-7.4 remove it, and setup.ps1 treats both as unknown.
+ $env:UNSLOTH_INSTALLER_TORCH_TAG = if ($SkipTorch) { "" } else {
+ [string](Get-ExpectedTorchFlavorTag -TorchIndexUrl $TorchIndexUrl -ROCmIndexUrl $ROCmIndexUrl)
+ }
+ # Tauri desktop app bundles its own frontend — skip Node/npm/frontend build
+ $env:SKIP_STUDIO_FRONTEND = if ($TauriMode) { "1" } else { "0" }
+ # Always set STUDIO_LOCAL_INSTALL explicitly to avoid stale values from
+ # a previous --local run in the same PowerShell session.
+ if ($StudioLocalInstall) {
+ $env:STUDIO_LOCAL_INSTALL = "1"
+ $env:STUDIO_LOCAL_REPO = $RepoRoot
+ } else {
+ $env:STUDIO_LOCAL_INSTALL = "0"
+ Remove-Item Env:STUDIO_LOCAL_REPO -ErrorAction SilentlyContinue
+ }
+ # Use 'studio setup' (not 'studio update') because 'update' pops
+ # SKIP_STUDIO_BASE, which would cause redundant package reinstallation
+ # and bypass the fast-path version check from PR #4667.
+ $env:UNSLOTH_TAURI_MODE = if ($TauriMode) { "1" } else { "0" }
+ if ($StudioRedirectMode -eq 'env') {
+ $env:UNSLOTH_STUDIO_HOME = $StudioHome
+ } else {
+ Remove-Item Env:UNSLOTH_STUDIO_HOME -ErrorAction SilentlyContinue
+ }
+ $studioArgs = @('studio', 'setup')
+ if ($script:UnslothVerbose) { $studioArgs += '--verbose' }
+ if ($WithLlamaCppDir) {
+ if (-not (Test-Path -LiteralPath $WithLlamaCppDir -PathType Container)) {
+ Write-StudioLine "[ERROR] --with-llama-cpp-dir path does not exist: $WithLlamaCppDir" -ForegroundColor Red
+ return (Exit-InstallFailure "--with-llama-cpp-dir path does not exist.")
+ }
+ $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR = (Resolve-Path -LiteralPath $WithLlamaCppDir).Path
+ }
+ $env:UNSLOTH_INSTALL_ROLLBACK_MANAGED = "1"
+ # Hand the venv interpreter to setup.ps1 so it reuses the Python we already
+ # resolved and built the venv with, instead of re-probing the system (which
+ # can trip over an unsupported `python` 3.14 or a Store stub on PATH even
+ # though the venv is fine). setup.ps1 Test-Path-guards this before use.
+ $env:UNSLOTH_SETUP_PYTHON = Join-Path $VenvDir "Scripts\python.exe"
+ # Installer already owns the runtime mutex; the child inherits it rather
+ # than deadlocking trying to reacquire it.
+ $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"
+ # The proxy defaults kept out of the discarded profile table, for the duration of the child
+ # only. setup.ps1 runs with -NoProfile and downloads on its own; see the prologue.
+ #
+ # Set even when there is nothing to hand over: its ABSENCE is how the CLI recognises a
+ # standalone update and goes looking through the user's profiles. An empty object says "the
+ # installer looked, and there is none".
+ $env:_UNSLOTH_PS_PROXY_DEFAULTS =
+ if ($UnslothProxyHandoffJson) { $UnslothProxyHandoffJson } else { '{}' }
+ # Forward the arch this run resolved. Both scripts scan WMI, so a scan that answers here but
+ # not there leaves setup expecting cpu torch against the ROCm wheels just installed: it
+ # reports "needs repair", the installer rolls back, and the app retries that forever.
+ #
+ # PRIVATE, not UNSLOTH_ROCM_GFX_ARCH: install_llama_prebuilt.py reads that one back as
+ # _manual to decide whether a forwarded --rocm-gfx outranks its own probe, and this scan is
+ # the weaker of the two anyway (first AMD adapter, no visible-device mask, no shadowing-iGPU
+ # repick, all of which setup.ps1 applies). So setup consumes it only after its own probes
+ # come up empty, and nested installers never see it.
+ if ($ROCmGfxArch) {
+ $env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF = $ROCmGfxArch
+ } else {
+ # Cleared, not left alone: an inherited value from an outer process is not this run's
+ # answer, and handing it down would forward an arch nothing here detected.
+ Remove-Item Env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF -ErrorAction SilentlyContinue
+ }
Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs
$setupExit = $script:ManagedUnslothCliExit
} finally {
@@ -6538,6 +6654,11 @@ sys.exit(2 if conflict else (0 if installed else 1))
} else {
Remove-Item Env:UNSLOTH_TAURI_MODE -ErrorAction SilentlyContinue
}
+ if ($hadPreviousSkipStudioBase) {
+ $env:SKIP_STUDIO_BASE = $previousSkipStudioBase
+ } else {
+ Remove-Item Env:SKIP_STUDIO_BASE -ErrorAction SilentlyContinue
+ }
if ($hadPreviousSetupRuntimeGateHandoff) {
$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = $previousSetupRuntimeGateHandoff
} else {
@@ -6553,12 +6674,54 @@ sys.exit(2 if conflict else (0 if installed else 1))
} else {
Remove-Item Env:_UNSLOTH_PS_PROXY_DEFAULTS -ErrorAction SilentlyContinue
}
+ if ($hadPreviousStudioPackageName) {
+ $env:STUDIO_PACKAGE_NAME = $previousStudioPackageName
+ } else {
+ Remove-Item Env:STUDIO_PACKAGE_NAME -ErrorAction SilentlyContinue
+ }
+ if ($hadPreviousNoTorch) {
+ $env:UNSLOTH_NO_TORCH = $previousNoTorch
+ } else {
+ Remove-Item Env:UNSLOTH_NO_TORCH -ErrorAction SilentlyContinue
+ }
+ if ($hadPreviousInstallerTorchTag) {
+ $env:UNSLOTH_INSTALLER_TORCH_TAG = $previousInstallerTorchTag
+ } else {
+ Remove-Item Env:UNSLOTH_INSTALLER_TORCH_TAG -ErrorAction SilentlyContinue
+ }
+ if ($hadPreviousSkipStudioFrontend) {
+ $env:SKIP_STUDIO_FRONTEND = $previousSkipStudioFrontend
+ } else {
+ Remove-Item Env:SKIP_STUDIO_FRONTEND -ErrorAction SilentlyContinue
+ }
+ if ($hadPreviousStudioLocalInstall) {
+ $env:STUDIO_LOCAL_INSTALL = $previousStudioLocalInstall
+ } else {
+ Remove-Item Env:STUDIO_LOCAL_INSTALL -ErrorAction SilentlyContinue
+ }
+ if ($hadPreviousStudioLocalRepo) {
+ $env:STUDIO_LOCAL_REPO = $previousStudioLocalRepo
+ } else {
+ Remove-Item Env:STUDIO_LOCAL_REPO -ErrorAction SilentlyContinue
+ }
# ...and the copy this function holds goes with it, rather than sitting in the frame for
# the rest of a long install.
$UnslothProxyHandoffJson = $null
- Remove-Item Env:UNSLOTH_LOCAL_LLAMA_CPP_DIR -ErrorAction SilentlyContinue
- Remove-Item Env:UNSLOTH_INSTALL_ROLLBACK_MANAGED -ErrorAction SilentlyContinue
- Remove-Item Env:UNSLOTH_SETUP_PYTHON -ErrorAction SilentlyContinue
+ if ($hadPreviousLocalLlamaCppDir) {
+ $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR = $previousLocalLlamaCppDir
+ } else {
+ Remove-Item Env:UNSLOTH_LOCAL_LLAMA_CPP_DIR -ErrorAction SilentlyContinue
+ }
+ if ($hadPreviousInstallRollbackManaged) {
+ $env:UNSLOTH_INSTALL_ROLLBACK_MANAGED = $previousInstallRollbackManaged
+ } else {
+ Remove-Item Env:UNSLOTH_INSTALL_ROLLBACK_MANAGED -ErrorAction SilentlyContinue
+ }
+ if ($hadPreviousSetupPython) {
+ $env:UNSLOTH_SETUP_PYTHON = $previousSetupPython
+ } else {
+ Remove-Item Env:UNSLOTH_SETUP_PYTHON -ErrorAction SilentlyContinue
+ }
}
# $null, not a code: Application Control refused to create the process, so there is
# no exit code to report. Checked first because in PowerShell $null -ne 0 is true,
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 5b6c31359c5..f4e466643ad 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -1859,6 +1859,72 @@ function Clear-WebViewCaches {
if ($wvCleared) { substep "cleared stale WebView caches (ai.unsloth.studio); settings and data kept" }
}
+# install.ps1 (SKIP_STUDIO_BASE=1) already reported this for the install it drives, so this
+# covers direct setup, update and desktop repair. Keep in step with the copies in install.ps1.
+if ($env:SKIP_STUDIO_BASE -ne "1") {
+ $ElevationState = "unknown"
+ try {
+ $_identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
+ $_principal = New-Object System.Security.Principal.WindowsPrincipal($_identity)
+ $ElevationState = if ($_principal.IsInRole(
+ [System.Security.Principal.WindowsBuiltInRole]::Administrator)) { "true" } else { "false" }
+ } catch { }
+ if ((@("1", "true") -contains $env:UNSLOTH_TAURI_MODE) -or
+ (@("1", "true") -contains $env:UNSLOTH_TAURI_UPDATE)) {
+ [Console]::Out.WriteLine("[TAURI:DIAG] elevated=$ElevationState")
+ [Console]::Out.Flush()
+ }
+ function Get-CanonicalRootPath {
+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
+ if ([string]::IsNullOrWhiteSpace($Path)) { return "" }
+ $_p = $Path.Trim()
+ if (($_p -eq "~" -or $_p -like "~/*" -or $_p -like "~\*") -and
+ -not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
+ # A bare "~" leaves an empty child path, which Join-Path rejects on PS 5.1.
+ $_rest = $_p.Substring(1).TrimStart('/', '\')
+ $_p = if ($_rest) { Join-Path $env:USERPROFILE $_rest } else { $env:USERPROFILE }
+ }
+ # GetFullPath anchors a relative path to [Environment]::CurrentDirectory, which
+ # Set-Location does not move, so it disagreed with the Resolve-Path based resolver
+ # (PowerShell#10278, by design). It stays as the fallback, never the first answer.
+ try {
+ $_p = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_p)
+ } catch {
+ try { $_p = [System.IO.Path]::GetFullPath($_p) } catch { }
+ }
+ return $_p.TrimEnd('\', '/')
+ }
+
+ if ($ElevationState -eq "true") {
+ # $StudioHome is resolved much later, so mirror its precedence for the message only.
+ # USERPROFILE can be unset (service, CI), where a bare Join-Path throws under Stop.
+ $_unslothRoot = if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
+ '%USERPROFILE%\.unsloth'
+ } else {
+ Join-Path $env:USERPROFILE ".unsloth"
+ }
+ $_elevRoot = 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 {
+ $_unslothRoot
+ }
+ # A legacy-equal override is not a custom root: name the parent that holds llama.cpp.
+ if ((Get-CanonicalRootPath $_elevRoot) -ieq
+ (Get-CanonicalRootPath (Join-Path $_unslothRoot "studio"))) {
+ $_elevRoot = $_unslothRoot
+ }
+ Write-StudioLine ""
+ Write-StudioLine " [WARNING] Running as administrator. Unsloth does not need this." -ForegroundColor Yellow
+ Write-StudioLine " Anything written to $_elevRoot will be owned by Administrators," -ForegroundColor Yellow
+ Write-StudioLine " and your normal account will not be able to read it afterwards." -ForegroundColor Yellow
+ Write-StudioLine " That folder outlives an uninstall, so a later install, setup or" -ForegroundColor Yellow
+ Write-StudioLine " update run normally fails on it." -ForegroundColor Yellow
+ Write-StudioLine " Stop and start again without 'Run as administrator'." -ForegroundColor Yellow
+ }
+}
+
# Resolve and preflight the install root before phase 1, with the same override
# precedence as the other resolvers. Everything below joins onto USERPROFILE, so a
# blank one must fail here instead of throwing a raw binding error under "Stop".
@@ -6774,10 +6840,21 @@ if ($script:LlamaCppDegraded -and $env:SKIP_STUDIO_BASE -eq "1") {
# footer just said complete. [TAURI:PROGRESS] (not [TAURI:STEP], which would
# push the frontend step counter past the seven INSTALL_STEPS entries) reaches
# the user as install-progress-detail text.
+ # DIAG as well: the progress detail is cleared by the next install-step, so only the
+ # marker can still answer "why is GGUF missing" afterwards.
if (@("1", "true") -contains $env:UNSLOTH_TAURI_MODE) {
[Console]::Out.WriteLine("[TAURI:PROGRESS] llama.cpp unavailable; GGUF inference is disabled until 'unsloth studio update' succeeds")
+ [Console]::Out.WriteLine("[TAURI:DIAG] llama_cpp=unavailable")
[Console]::Out.Flush()
} else {
Exit-SetupFailure "llama.cpp setup did not produce a usable server"
}
}
+
+# A desktop repair runs update.rs, which sets UNSLOTH_TAURI_UPDATE alone, so the block above
+# is skipped and a degraded repair recorded nothing. Marker only: the update stays successful.
+if ($script:LlamaCppDegraded -and $env:SKIP_STUDIO_BASE -ne "1" -and
+ (@("1", "true") -contains $env:UNSLOTH_TAURI_UPDATE)) {
+ [Console]::Out.WriteLine("[TAURI:DIAG] llama_cpp=unavailable")
+ [Console]::Out.Flush()
+}
diff --git a/studio/setup.sh b/studio/setup.sh
index a76557472f3..1636b323e1c 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -3748,13 +3748,27 @@ if [ "$_LLAMA_CPP_DEGRADED" = true ] && [ "${SKIP_STUDIO_BASE:-0}" = "1" ]; then
# install.sh already emits in full, so an eighth marker renders "Step 8 of 7" and
# discards the payload. [TAURI:PROGRESS] becomes install-progress-detail, which
# InstallingContent renders verbatim, so the user actually reads the limitation.
+ #
+ # DIAG as well: progress detail is cleared by the next install-step and is gone
+ # once the install screen closes, so it cannot answer "why is GGUF missing"
+ # afterwards. record_diag_marker keeps this in the support report.
case "${UNSLOTH_TAURI_MODE:-0}" in
1|true)
printf '[TAURI:PROGRESS] %s\n' \
"llama.cpp unavailable; GGUF inference is disabled until 'unsloth studio update' succeeds"
+ printf '[TAURI:DIAG] %s\n' "llama_cpp=unavailable"
;;
*)
setup_fail 1 "llama.cpp setup did not produce a usable server"
;;
esac
fi
+
+# A desktop repair runs update.rs, which sets UNSLOTH_TAURI_UPDATE alone, so the
+# block above is skipped and a degraded repair recorded nothing. update.rs parses
+# [TAURI:DIAG] the same way. Marker only: the update contract stays successful.
+if [ "$_LLAMA_CPP_DEGRADED" = true ] && [ "${SKIP_STUDIO_BASE:-0}" != "1" ]; then
+ case "${UNSLOTH_TAURI_UPDATE:-0}" in
+ 1|true) printf '[TAURI:DIAG] %s\n' "llama_cpp=unavailable" ;;
+ esac
+fi
diff --git a/tests/python/test_windows_installer_concurrency_guard.py b/tests/python/test_windows_installer_concurrency_guard.py
index ada52d64a6c..b5d7d47147f 100644
--- a/tests/python/test_windows_installer_concurrency_guard.py
+++ b/tests/python/test_windows_installer_concurrency_guard.py
@@ -1003,11 +1003,15 @@ def test_runtime_gate_handoff_covers_managed_children():
)
assert save < set_handoff < autostart < restore
- setup_python = install_source.index("$env:UNSLOTH_SETUP_PYTHON =")
- setup_save = install_source.index("$previousSetupRuntimeGateHandoff =", setup_python)
+ # The save sits above the try that now covers the whole handoff, not beside
+ # the set: a finally reached before its own $hadPrevious* was assigned reads
+ # an unset flag as "there was nothing here" and clears a value it never set.
+ setup_save = install_source.index("$previousSetupRuntimeGateHandoff =")
+ setup_try = install_source.index("\n try {\n $env:SKIP_STUDIO_BASE", setup_save)
+ setup_python = install_source.index("$env:UNSLOTH_SETUP_PYTHON =", setup_try)
setup_set = install_source.index(
'$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"',
- setup_save,
+ setup_python,
)
setup_invoke = install_source.index(
"Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs", setup_set
@@ -1017,7 +1021,15 @@ def test_runtime_gate_handoff_covers_managed_children():
setup_invoke,
)
tauri_remove = install_source.index("Remove-Item Env:UNSLOTH_TAURI_MODE", setup_invoke)
- assert setup_python < setup_save < setup_set < setup_invoke < tauri_remove < setup_restore
+ assert (
+ setup_save
+ < setup_try
+ < setup_python
+ < setup_set
+ < setup_invoke
+ < tauri_remove
+ < setup_restore
+ )
assert (
studio_source.count(
diff --git a/tests/sh/test_llama_degraded_tauri_mode.sh b/tests/sh/test_llama_degraded_tauri_mode.sh
index 771c51de9cb..fbe4a3b1a22 100755
--- a/tests/sh/test_llama_degraded_tauri_mode.sh
+++ b/tests/sh/test_llama_degraded_tauri_mode.sh
@@ -46,6 +46,9 @@ echo "=== llama.cpp degraded verdict ==="
# The fix: a transient prebuilt failure must not abort the desktop first-launch install.
run_case "tauri mode reports instead of aborting" true 1 1 0 "[TAURI:PROGRESS]"
run_case "tauri mode names the recovery command" true 1 true 0 "unsloth studio update"
+# Progress detail is cleared by the next install-step and discarded when the
+# install screen closes, so the verdict also has to reach the support report.
+run_case "tauri mode records the verdict" true 1 1 0 "[TAURI:DIAG] llama_cpp=unavailable"
# The half that must not regress: install.sh still needs the non-zero exit.
run_case "shell install still fails" true 1 0 1 "SETUP_FAIL"
run_case "unset tauri mode still fails" true 1 "" 1 "SETUP_FAIL"
@@ -67,6 +70,52 @@ case "$_step_out" in
echo " PASS: notice does not consume an install step"; PASS=$((PASS + 1)) ;;
esac
+# ── Desktop repair: update.rs sets UNSLOTH_TAURI_UPDATE alone ──
+# Neither SKIP_STUDIO_BASE nor UNSLOTH_TAURI_MODE is set on a repair, so the block
+# above never runs and a degraded repair recorded nothing. Marker only: the update
+# path stays silent and successful for everyone else.
+_REPAIR=$(mktemp)
+sed -n '/^# A desktop repair runs update\.rs/,/^fi$/p' "$SETUP_SH" > "$_REPAIR"
+if [ ! -s "$_REPAIR" ]; then
+ echo " FAIL: could not find the repair block in setup.sh"; FAIL=$((FAIL + 1))
+fi
+
+# degraded, skip_base, tauri_update -> expected rc, expected substring ("" = none)
+run_repair() {
+ _label="$1"; _degraded="$2"; _skip="$3"; _upd="$4"; _rc_want="$5"; _want="$6"
+ set +e
+ _out=$(
+ _LLAMA_CPP_DEGRADED="$_degraded" \
+ SKIP_STUDIO_BASE="$_skip" \
+ UNSLOTH_TAURI_UPDATE="$_upd" \
+ bash -c 'setup_fail() { printf "SETUP_FAIL: %s\n" "$*"; exit "$1"; }; . "$1"' _ "$_REPAIR" 2>&1
+ )
+ _rc=$?
+ set -e
+ if [ "$_rc" != "$_rc_want" ]; then
+ echo " FAIL: $_label (expected rc $_rc_want, got $_rc; output: $_out)"; FAIL=$((FAIL + 1)); return
+ fi
+ case "$_want" in
+ "") [ -z "$_out" ] || { echo " FAIL: $_label (expected no output, got: $_out)"; FAIL=$((FAIL + 1)); return; } ;;
+ *) case "$_out" in *"$_want"*) ;; *) echo " FAIL: $_label (expected '$_want' in: $_out)"; FAIL=$((FAIL + 1)); return ;; esac ;;
+ esac
+ echo " PASS: $_label"; PASS=$((PASS + 1))
+}
+
+echo "=== desktop repair verdict ==="
+run_repair "tauri repair records the verdict" true 0 1 0 "[TAURI:DIAG] llama_cpp=unavailable"
+run_repair "true spelling also records" true 0 true 0 "[TAURI:DIAG] llama_cpp=unavailable"
+# Must not leak into the paths the existing contract keeps silent.
+run_repair "plain 'studio update' stays silent" true 0 0 0 ""
+run_repair "a healthy repair says nothing" false 0 1 0 ""
+run_repair "the install path is left to the block above" true 1 1 0 ""
+# Marker only: a repair must not start failing where it used to succeed.
+if grep -qE 'setup_fail|exit ' "$_REPAIR"; then
+ echo " FAIL: the repair block must not change the exit contract"; FAIL=$((FAIL + 1))
+else
+ echo " PASS: the repair block is marker-only"; PASS=$((PASS + 1))
+fi
+
# ── Windows parity: setup.ps1 must degrade the same way (static check) ──
# install.ps1 turns any non-zero setup.ps1 status into Exit-InstallFailure, which
# install.rs reports as "Installation failed", so an unconditional
@@ -83,9 +132,23 @@ else
*)
echo " FAIL: setup.ps1 does not mirror the Tauri degraded handling"; FAIL=$((FAIL + 1)) ;;
esac
+ case "$_PS_BLOCK" in
+ *'[TAURI:DIAG] llama_cpp=unavailable'*)
+ echo " PASS: setup.ps1 records the verdict too"; PASS=$((PASS + 1)) ;;
+ *)
+ echo " FAIL: setup.ps1 does not record the degraded verdict"; FAIL=$((FAIL + 1)) ;;
+ esac
fi
-rm -f "$_BLOCK"
+_PS_REPAIR=$(sed -n '/^# A desktop repair runs update\.rs/,/^}$/p' "$SETUP_PS1")
+case "$_PS_REPAIR" in
+ *'UNSLOTH_TAURI_UPDATE'*'[TAURI:DIAG] llama_cpp=unavailable'*)
+ echo " PASS: setup.ps1 mirrors the repair marker"; PASS=$((PASS + 1)) ;;
+ *)
+ echo " FAIL: setup.ps1 does not record a degraded desktop repair"; FAIL=$((FAIL + 1)) ;;
+esac
+
+rm -f "$_BLOCK" "$_REPAIR"
echo ""
echo "Passed: $PASS Failed: $FAIL"
[ "$FAIL" -eq 0 ]
diff --git a/tests/test_installer_elevation_report.py b/tests/test_installer_elevation_report.py
new file mode 100644
index 00000000000..72150650434
--- /dev/null
+++ b/tests/test_installer_elevation_report.py
@@ -0,0 +1,392 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression tests for what a Windows install records about itself.
+
+Two things a support report could not answer, both from the same install:
+
+1. Whether the run was elevated. An install started with "Run as administrator"
+ writes %USERPROFILE%\\.unsloth as Administrators, the normal account cannot
+ read it back, and the folder outlives an uninstall, so the next install fails
+ on a folder nobody remembers creating. The reporter spent the debugging
+ session on it; "ran as admin: yes/no" would have ended it immediately.
+
+2. Whether llama.cpp actually landed. In Tauri mode a degraded llama.cpp is
+ deliberately not fatal (see tests/sh/test_llama_degraded_tauri_mode.sh), but
+ it was announced only through install-progress-detail, which the next
+ install-step clears and the install screen discards on close. The install
+ then looked clean and the first sign of trouble was a GGUF failing to load.
+
+Both now also go out as [TAURI:DIAG], which install.rs hands to
+record_diag_marker and the support report prints under installer_diag_markers.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+INSTALL_PS1 = REPO_ROOT / "install.ps1"
+SETUP_PS1 = REPO_ROOT / "studio" / "setup.ps1"
+SETUP_SH = REPO_ROOT / "studio" / "setup.sh"
+INSTALL_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "install.rs"
+UPDATE_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "update.rs"
+REPORT_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "diagnostics" / "report.rs"
+
+
+def _read(path: Path) -> str:
+ return path.read_text(encoding = "utf-8")
+
+
+def _code_only(text: str) -> str:
+ """Drop whole-line comments so an assertion about what the code reads is not
+ satisfied, or defeated, by prose explaining it."""
+ return "\n".join(line for line in text.splitlines() if not line.strip().startswith("#"))
+
+
+def _repair_block(path: Path) -> str:
+ """The marker-only block that covers a desktop repair, which runs without
+ SKIP_STUDIO_BASE and so never reaches the install-side block."""
+ src = _read(path)
+ return src[src.index("# A desktop repair runs update.rs") :]
+
+
+
+
+def test_diag_marker_prefix_is_still_parsed_and_reported():
+ """Both scripts write [TAURI:DIAG]; if the Rust side stops reading it the
+ markers become invisible without either file changing."""
+ assert '"[TAURI:DIAG] "' in _read(INSTALL_RS), "install.rs no longer parses [TAURI:DIAG]"
+ assert "record_diag_marker" in _read(INSTALL_RS), "the marker is parsed but not recorded"
+ assert "installer_diag_markers" in _read(
+ REPORT_RS
+ ), "the support report no longer prints markers"
+
+
+
+
+def test_install_ps1_reports_elevation():
+ src = _read(INSTALL_PS1)
+ assert "function Get-ElevationState" in src
+ assert "WindowsBuiltInRole]::Administrator" in src, "elevation must come from the process token"
+ assert "[TAURI:DIAG] elevated=$State" in src, "the state must reach the support report"
+ # Recorded on every run: "false" rules elevation out, absence would be ambiguous.
+ notice = src[src.index("function Write-ElevationNotice") :]
+ diag_idx = notice.index("[TAURI:DIAG] elevated=$State")
+ warn_idx = notice.index('if ($State -ne "true") { return }')
+ assert diag_idx < warn_idx, "the marker must be written before the warning returns early"
+
+
+def test_install_ps1_elevation_state_covers_unreadable_tokens():
+ src = _read(INSTALL_PS1)
+ block = src[
+ src.index("function Get-ElevationState") : src.index("function Write-ElevationNotice")
+ ]
+ assert '"unknown"' in block, "an unreadable token must report unknown, not a confident false"
+ for value in ('"true"', '"false"'):
+ assert value in block, f"Get-ElevationState must be able to return {value}"
+
+
+def test_install_ps1_warns_before_anything_is_created():
+ """Telling the user to stop is only honest while stopping leaves nothing
+ behind. The override resolver creates the custom root and writes a probe
+ into it, so an elevated run that warned afterwards had already made the
+ admin-owned folder the warning is about."""
+ src = _read(INSTALL_PS1)
+ notice_idx = src.index("Write-ElevationNotice -State (Get-ElevationState)")
+ for marker in (
+ "[System.IO.Directory]::CreateDirectory($envOverride)",
+ '$probe = Join-Path $StudioHome (".unsloth-write-probe-',
+ 'step "winget" "available"',
+ # `& $script:UvExe`, not a bare `uv`, since #8161 resolved the binary up front.
+ "venv $VenvDir --python",
+ 'step "setup" "running unsloth studio setup..."',
+ ):
+ assert notice_idx < src.index(
+ marker
+ ), f"the elevation notice must be printed before {marker!r}"
+
+
+def test_install_ps1_marker_uses_the_parsed_tauri_flag():
+ """install.rs launches this with --tauri and never sets UNSLOTH_TAURI_MODE;
+ install.ps1 assigns that variable itself, far below, right before invoking
+ setup.ps1. Gating on the env var here would emit nothing for the desktop
+ install, and setup.ps1 then skips its own marker under SKIP_STUDIO_BASE=1,
+ so the flow this exists for would produce no elevated= line at all."""
+ src = _read(INSTALL_PS1)
+ notice = _code_only(
+ src[src.index("function Write-ElevationNotice") : src.index("$ElevationRoot = if")]
+ )
+ assert "[TAURI:DIAG] elevated=$State" in notice
+ assert (
+ "$env:UNSLOTH_TAURI_MODE" not in notice
+ ), "the env var is unset at this point; gate on the --tauri flag instead"
+ assert "-Tauri:$TauriMode" in src, "the parsed --tauri flag must be what drives the marker"
+ # The flag has to be parsed before the call, or it is always false.
+ assert src.index('"--tauri" { $TauriMode = $true }') < src.index("-Tauri:$TauriMode")
+ # And the env var must still be unassigned there, or this test proves nothing.
+ assert src.index("-Tauri:$TauriMode") < src.index("$env:UNSLOTH_TAURI_MODE = if ($TauriMode)")
+
+
+def test_install_ps1_warning_names_the_root_actually_written():
+ """A custom UNSLOTH_STUDIO_HOME holds every artefact, so naming
+ %USERPROFILE%\\.unsloth there points the user at the wrong directory."""
+ src = _read(INSTALL_PS1)
+ notice = src[src.index("function Write-ElevationNotice") : src.index("-Tauri:$TauriMode")]
+ assert "$Root" in notice, "the warning must name the resolved root, not a fixed path"
+ assert "outlives an uninstall" in notice, "the warning must say reinstalling does not clear it"
+ # Anchored on the assignment: the right-hand side must stay free to change.
+ root = src[src.index("$UnslothRoot =") : src.index("-Tauri:$TauriMode")]
+ assert '".unsloth"' in root, "a default install must name the parent that also holds llama.cpp"
+ # The notice runs before the resolver, so $StudioHome does not exist yet and
+ # naming it would render empty; mirror the override precedence instead.
+ assert "$StudioHome" not in root, "$StudioHome is not assigned until the resolver below"
+ assert (
+ "UNSLOTH_STUDIO_HOME" in root and "$env:STUDIO_HOME" in root
+ ), "both override names must be honoured, in that order"
+ assert root.index("UNSLOTH_STUDIO_HOME") < root.index(
+ "$env:STUDIO_HOME"
+ ), "UNSLOTH_STUDIO_HOME wins when both are set"
+
+
+def test_a_legacy_equal_override_names_its_parent():
+ """An override that resolves to %USERPROFILE%\\.unsloth\\studio is not a custom
+ root downstream: the canonical comparison in setup.ps1 treats it as a default
+ install and keeps llama.cpp and node as siblings under ~/.unsloth. Naming only
+ the studio directory would send the user past the admin-owned assets."""
+ for path, var in ((INSTALL_PS1, "$ElevationRoot"), (SETUP_PS1, "$_elevRoot")):
+ src = _read(path)
+ idx = src.index(f"{var} = if") - 400
+ block = src[idx : idx + 1200]
+ assert '"studio"' in block, f"{path.name} does not compare against the legacy root"
+ assert "-ieq" in block, f"{path.name} must compare case-insensitively"
+ assert (
+ block.count("Get-CanonicalRootPath") >= 2
+ ), f"{path.name} must canonicalize both sides before comparing"
+
+
+def test_the_legacy_root_comparison_is_canonical():
+ """A raw string compare misses the spellings a user actually types. The env
+ override reaches this unresolved: `~/.unsloth/studio`, a trailing separator,
+ forward slashes, or a `..` segment all name the legacy root but compare
+ unequal, and the notice then sends the user past the admin-owned llama.cpp."""
+ for path in (INSTALL_PS1, SETUP_PS1):
+ src = _code_only(_read(path))
+ idx = src.index("function Get-CanonicalRootPath")
+ body = src[idx : src.index("\n }\n", idx)]
+ # GetFullPath alone keeps a literal ~ and resolves it against the cwd.
+ assert '-eq "~"' in body and '"~/*"' in body, f"{path.name} must expand a leading ~"
+ assert "$env:USERPROFILE" in body, f"{path.name} must expand ~ to the profile"
+ assert (
+ "[System.IO.Path]::GetFullPath" in body
+ ), f"{path.name} must normalize separators and .. segments"
+ # ...but not FIRST: GetFullPath uses [Environment]::CurrentDirectory, which
+ # Set-Location does not move, so it disagreed with the Resolve-Path resolver.
+ assert (
+ "GetUnresolvedProviderPathFromPSPath" in body
+ ), f"{path.name} must resolve a relative override against the PowerShell location"
+ assert body.index("GetUnresolvedProviderPathFromPSPath") < body.index(
+ "[System.IO.Path]::GetFullPath"
+ ), f"{path.name} must try the provider location before the .NET working directory"
+ assert "TrimEnd('\\', '/')" in body, (
+ f"{path.name} must ignore a trailing separator -- with its arguments, since a bare "
+ "TrimEnd() strips whitespace only and leaves the case this exists for unhandled"
+ )
+ # A bare "~" leaves an empty child path, which Join-Path rejects on PS 5.1.
+ assert "Substring(1)" in body, f"{path.name} must handle a bare ~"
+ # An unresolvable path must not take the install down.
+ assert "catch { }" in body, f"{path.name} must survive an unresolvable path"
+
+
+def test_installer_restores_skip_studio_base():
+ """`irm ... | iex` runs in the caller's shell. A leaked SKIP_STUDIO_BASE=1
+ makes the next direct setup or update look like an installer child, which
+ suppresses both the elevation notice and the degraded-repair marker."""
+ src = _read(INSTALL_PS1)
+ assert "$previousSkipStudioBase = $env:SKIP_STUDIO_BASE" in src
+ set_idx = src.index('$env:SKIP_STUDIO_BASE = "1"')
+ save_idx = src.index("$previousSkipStudioBase = $env:SKIP_STUDIO_BASE")
+ assert save_idx < set_idx, "the previous value must be captured before it is overwritten"
+ restore = src[src.index("} finally {") :]
+ assert (
+ "$env:SKIP_STUDIO_BASE = $previousSkipStudioBase" in restore
+ ), "the flag must be restored alongside UNSLOTH_TAURI_MODE"
+ assert (
+ "Remove-Item Env:SKIP_STUDIO_BASE" in restore
+ ), "an unset value must be removed again, not left as an empty string"
+
+
+def test_every_handoff_variable_is_restored_not_just_skip_studio_base():
+ """The same argument covers the whole handoff table, not one variable of it. Under
+ `irm ... | iex` all of these are the caller's own session variables, and
+ SKIP_STUDIO_FRONTEND is the one that bites: a leaked "1" from a desktop install makes
+ the next direct `unsloth studio setup` in that console report "bundled (Tauri)" and skip
+ the frontend build, which on a local/source install leaves Studio with no web UI."""
+ src = _read(INSTALL_PS1)
+ restore = src[src.index("} finally {") :]
+ # The handoff try specifically; install.ps1 opens several.
+ handoff_try = src.index('\n try {\n $env:SKIP_STUDIO_BASE')
+ for var, saved in (
+ ("SKIP_STUDIO_BASE", "$previousSkipStudioBase"),
+ ("STUDIO_PACKAGE_NAME", "$previousStudioPackageName"),
+ ("UNSLOTH_NO_TORCH", "$previousNoTorch"),
+ ("UNSLOTH_INSTALLER_TORCH_TAG", "$previousInstallerTorchTag"),
+ ("SKIP_STUDIO_FRONTEND", "$previousSkipStudioFrontend"),
+ ("STUDIO_LOCAL_INSTALL", "$previousStudioLocalInstall"),
+ ("STUDIO_LOCAL_REPO", "$previousStudioLocalRepo"),
+ # Cleared unconditionally before, which the --with-llama-cpp-dir bail now reaches
+ # without having set them. UNSLOTH_LOCAL_LLAMA_CPP_DIR is a user-facing input.
+ ("UNSLOTH_LOCAL_LLAMA_CPP_DIR", "$previousLocalLlamaCppDir"),
+ ("UNSLOTH_INSTALL_ROLLBACK_MANAGED", "$previousInstallRollbackManaged"),
+ ("UNSLOTH_SETUP_PYTHON", "$previousSetupPython"),
+ ):
+ save = f"{saved} = $env:{var}"
+ assert save in src, f"{var} is mutated for the child but never captured"
+ assert src.index(save) < handoff_try, (
+ f"{var} must be captured above the try, or a finally entered early reads an "
+ "unassigned $hadPrevious* as 'there was nothing here'"
+ )
+ assert f"$env:{var} = {saved}" in restore, f"{var} is never restored"
+ assert f"Remove-Item Env:{var}" in restore, (
+ f"{var} must be REMOVED when it was originally unset, not left as an empty string"
+ )
+
+
+def test_the_early_bail_restores_the_environment_too():
+ """--with-llama-cpp-dir with a missing path returns before `& $UnslothExe`.
+ That return used to sit between the env mutations and the `try`, so the bail
+ leaked SKIP_STUDIO_BASE, UNSLOTH_STUDIO_HOME and UNSLOTH_TAURI_MODE into the
+ caller's shell. The try has to open before the first mutation."""
+ src = _code_only(_read(INSTALL_PS1))
+ try_idx = src.index(" try {\n $env:SKIP_STUDIO_BASE")
+ finally_idx = src.index(" } finally {", try_idx)
+ body = src[try_idx:finally_idx]
+ assert (
+ "--with-llama-cpp-dir path does not exist." in body
+ ), "the early bail must sit inside the try that the finally covers"
+ for var in ("SKIP_STUDIO_BASE", "UNSLOTH_STUDIO_HOME", "UNSLOTH_TAURI_MODE"):
+ assert f"$env:{var} =" in body, f"{var} is mutated outside the try"
+ # The saves read the previous value, so they must stay outside and before it.
+ for save in (
+ "$previousSkipStudioBase = $env:SKIP_STUDIO_BASE",
+ "$previousUnslothStudioHome = $env:UNSLOTH_STUDIO_HOME",
+ "$previousTauriMode = $env:UNSLOTH_TAURI_MODE",
+ ):
+ assert src.index(save) < try_idx, f"'{save}' must be captured before the try opens"
+
+
+def test_both_scripts_resolve_the_warning_root_the_same_way():
+ """install.ps1 and setup.ps1 each mirror the resolver's precedence for the
+ message, so a drift in one would send only half the flows to the right
+ directory."""
+ install_root = _read(INSTALL_PS1)
+ install_root = install_root[
+ install_root.index("$UnslothRoot =") : install_root.index("-Tauri:$TauriMode")
+ ]
+ setup_src = _read(SETUP_PS1)
+ setup_root = setup_src[
+ setup_src.index("$_unslothRoot =") : setup_src.index("# Back up User PATH")
+ ]
+ for fragment in (
+ "IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)",
+ "$env:UNSLOTH_STUDIO_HOME.Trim()",
+ "IsNullOrWhiteSpace($env:STUDIO_HOME)",
+ "$env:STUDIO_HOME.Trim()",
+ 'Join-Path $env:USERPROFILE ".unsloth"',
+ # Both copies run above the resolver's own USERPROFILE fallback, so both must guard
+ # it; dropping it in one file aborts the install rather than misnaming a folder.
+ "IsNullOrWhiteSpace($env:USERPROFILE)",
+ ):
+ assert fragment in install_root, f"install.ps1 root resolution lost {fragment!r}"
+ assert fragment in setup_root, f"setup.ps1 root resolution lost {fragment!r}"
+
+
+def test_install_ps1_warning_does_not_assume_a_powershell_window():
+ """install.rs spawns this from the desktop app, where there is no console to
+ close and no PowerShell prompt to re-run from."""
+ src = _read(INSTALL_PS1)
+ notice = src[src.index("function Write-ElevationNotice") : src.index("$ElevationRoot = if")]
+ for phrase in ("Close this window", "normal PowerShell"):
+ assert phrase not in notice, f"{phrase!r} is wrong for the desktop flow"
+
+
+def test_setup_ps1_reports_elevation_without_duplicating_the_installer():
+ """install.ps1 runs setup.ps1 with SKIP_STUDIO_BASE=1 and has already
+ reported; this covers direct setup, update and desktop repair."""
+ src = _read(SETUP_PS1)
+ idx = src.index('if ($env:SKIP_STUDIO_BASE -ne "1") {')
+ block = src[idx : src.index("# Back up User PATH")]
+ assert "WindowsBuiltInRole]::Administrator" in block
+ assert "[TAURI:DIAG] elevated=$ElevationState" in block
+ # Desktop repair runs with UNSLOTH_TAURI_UPDATE rather than UNSLOTH_TAURI_MODE.
+ assert "UNSLOTH_TAURI_UPDATE" in block, "repair updates must emit the marker too"
+
+
+def test_setup_ps1_warning_names_the_root_actually_written():
+ """$StudioHome is not resolved until much later in setup.ps1, so the message
+ mirrors the documented override precedence rather than a fixed path."""
+ src = _read(SETUP_PS1)
+ idx = src.index('if ($env:SKIP_STUDIO_BASE -ne "1") {')
+ block = src[idx : src.index("# Back up User PATH")]
+ assert "$_elevRoot" in block, "the warning must name a resolved root"
+ assert (
+ "UNSLOTH_STUDIO_HOME" in block and "STUDIO_HOME" in block
+ ), "both override names must be honoured, in that order"
+ assert block.index("UNSLOTH_STUDIO_HOME") < block.index(
+ "$env:STUDIO_HOME"
+ ), "UNSLOTH_STUDIO_HOME wins when both are set"
+ for phrase in ("Close this window", "normal PowerShell"):
+ assert phrase not in block, f"{phrase!r} is wrong for the desktop repair flow"
+ # Naming $StudioHome directly here would render empty.
+ assert idx < src.index(
+ "$StudioHome = Join-Path $env:USERPROFILE"
+ ), "this test is only meaningful while the notice precedes the resolver"
+
+
+
+
+def test_degraded_llama_cpp_is_recorded_not_only_flashed():
+ """[TAURI:PROGRESS] is transient UI text; the marker is what survives."""
+ for path in (SETUP_PS1, SETUP_SH):
+ src = _read(path)
+ assert "llama_cpp=unavailable" in src, f"{path.name} does not record the degraded verdict"
+ progress_idx = src.index("llama.cpp unavailable; GGUF inference is disabled")
+ marker_idx = src.index("llama_cpp=unavailable")
+ assert (
+ marker_idx > progress_idx
+ ), f"{path.name} must keep the user-facing progress line and add the marker beside it"
+
+
+def test_degraded_llama_cpp_still_fails_outside_tauri_mode():
+ """The marker must not soften the non-desktop contract: install.sh and
+ install.ps1 still need the non-zero exit."""
+ assert 'setup_fail 1 "llama.cpp setup did not produce a usable server"' in _read(SETUP_SH)
+ assert 'Exit-SetupFailure "llama.cpp setup did not produce a usable server"' in _read(SETUP_PS1)
+
+
+def test_degraded_llama_cpp_is_recorded_on_a_desktop_repair():
+ """update.rs sets UNSLOTH_TAURI_UPDATE alone, neither SKIP_STUDIO_BASE nor
+ UNSLOTH_TAURI_MODE, so the install-side block never runs on a repair. It
+ parses [TAURI:DIAG] the same way install.rs does."""
+ assert 'strip_prefix("[TAURI:DIAG] ")' in _read(UPDATE_RS), "update.rs must parse the marker"
+ assert "record_diag_marker" in _read(UPDATE_RS), "the marker is parsed but not recorded"
+ for path, guard in (
+ (SETUP_SH, '[ "${SKIP_STUDIO_BASE:-0}" != "1" ]'),
+ (SETUP_PS1, '$env:SKIP_STUDIO_BASE -ne "1"'),
+ ):
+ block = _repair_block(path)
+ assert guard in block, f"{path.name} must record the repair path the install block skips"
+ assert "llama_cpp=unavailable" in block, f"{path.name} repair block emits no marker"
+ assert "UNSLOTH_TAURI_UPDATE" in block, f"{path.name} must gate the repair marker on it"
+
+
+def test_desktop_repair_marker_does_not_change_the_update_contract():
+ """A plain 'unsloth studio update' stays silent and successful; only a Tauri
+ repair emits, and neither path gains an exit-code change."""
+ for path in (SETUP_SH, SETUP_PS1):
+ block = _code_only(_repair_block(path))
+ for forbidden in ("setup_fail", "Exit-SetupFailure", "TAURI:PROGRESS", "exit "):
+ assert (
+ forbidden not in block
+ ), f"{path.name}: the repair block must be marker-only, found {forbidden!r}"
diff --git a/tests/test_installer_profile_hardening.py b/tests/test_installer_profile_hardening.py
index e2658fc3253..f3b54e6350b 100644
--- a/tests/test_installer_profile_hardening.py
+++ b/tests/test_installer_profile_hardening.py
@@ -860,12 +860,18 @@ def test_the_handoff_is_published_only_around_the_setup_child():
assert "$env:_UNSLOTH_PS_PROXY_DEFAULTS = $previousProxyHandoff" in source
gate = _locate(source, "$previousSetupRuntimeGateHandoff =", "the runtime-gate handoff")
proxy = _locate(source, "$previousProxyHandoff =", "the proxy handoff save")
+ # Anchored on the invocation's own line: pinning it to "try {\n" pinned the block's
+ # shape instead of the ordering this test is about, and broke on the restructure.
call = _locate(
source,
- " try {\n Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs",
+ " Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs",
"the child invocation",
)
+ opened = _locate(source, '\n try {\n $env:SKIP_STUDIO_BASE', "the handoff try")
assert gate < call and proxy < call, "the handoff must be in place before the child runs"
+ # ...and both saves stay above the try, or the finally reads an unassigned
+ # $hadPrevious* as "there was nothing here" and clears a value it did not set.
+ assert gate < opened and proxy < opened, "the saves must precede the try that restores them"
def test_a_standalone_update_reconstructs_the_proxy_for_itself():
@@ -1527,7 +1533,11 @@ def test_an_installer_launch_with_no_proxy_still_skips_the_probe(monkeypatch):
handoff = installer[
installer.index("$previousProxyHandoff = $env:_UNSLOTH_PS_PROXY_DEFAULTS") :
]
- handoff = handoff[: handoff.index("try {")]
+ # The publish moved inside the try, so the slice runs to the child invocation. It must
+ # still stop before the finally, which legitimately does remove the variable.
+ handoff = handoff[
+ : handoff.index(" Invoke-ManagedUnslothCli -Python $VenvPython")
+ ]
assert (
"Remove-Item Env:_UNSLOTH_PS_PROXY_DEFAULTS" not in handoff
), "the installer must publish an explicit empty handoff, not remove the variable"