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: check llama.cpp cache access before setup (#8032)

oobabooga69d555b98e51
diff --git a/install.ps1 b/install.ps1
index 5a654dda6ad..d5f800eca46 100644
--- a/install.ps1
+++ b/install.ps1
@@ -700,6 +700,180 @@ public static class UnslothStudioFinalPathV2
}
}
+ # Managed llama.cpp access check. This script cannot dot-source setup.ps1, so
+ # it holds byte-identical copies; test_denied_llama_cpp_preflight.py enforces that.
+ # ── BEGIN SHARED WITH studio/setup.ps1 ──
+
+ # Recognize ERROR_ACCESS_DENIED through PowerShell's wrapper exceptions.
+ function Test-AccessDeniedError {
+ param($ErrorRecord)
+
+ $ex = if ($ErrorRecord -is [System.Management.Automation.ErrorRecord]) { $ErrorRecord.Exception } else { $ErrorRecord }
+ while ($ex) {
+ if ($ex -is [System.UnauthorizedAccessException]) { return $true }
+ # IOException uses HRESULT; Win32Exception uses NativeErrorCode.
+ if ($ex.HResult -eq -2147024891) { return $true }
+ if ($ex -is [System.ComponentModel.Win32Exception] -and $ex.NativeErrorCode -eq 5) { return $true }
+ $ex = $ex.InnerException
+ }
+ if ($ErrorRecord -is [System.Management.Automation.ErrorRecord]) {
+ return ($ErrorRecord.CategoryInfo.Category -eq [System.Management.Automation.ErrorCategory]::PermissionDenied)
+ }
+ return $false
+ }
+
+ # Keep denied ACLs distinct from absent paths instead of letting Test-Path throw.
+ function Get-PathState {
+ param(
+ [Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path,
+ [ValidateSet("Any", "Leaf", "Container")][string]$PathType = "Any"
+ )
+
+ if ([string]::IsNullOrWhiteSpace($Path)) { return "Absent" }
+ try {
+ if (Test-Path -LiteralPath $Path -PathType $PathType -ErrorAction Stop) { return "Present" }
+ return "Absent"
+ } catch {
+ if (Test-AccessDeniedError $_) { return "Denied" }
+ # Malformed path, offline drive, dangling link: nothing usable there.
+ return "Absent"
+ }
+ }
+
+ # Dir, marker and listing: no single probe separates readable/absent/denied.
+ function Get-LlamaCppInstallReadState {
+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
+
+ $dirState = Get-PathState -Path $Path -PathType Container
+ if ($dirState -eq "Denied") { return "Denied" }
+ if ($dirState -ne "Present") { return "Absent" }
+ switch (Get-PathState -Path (Join-Path $Path "UNSLOTH_PREBUILT_INFO.json") -PathType Leaf) {
+ "Denied" { return "Denied" }
+ }
+ try { $null = @(Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop | Select-Object -First 1) }
+ catch {
+ if (Test-AccessDeniedError $_) { return "Denied" }
+ # Nonfatal here: nothing has been installed yet.
+ }
+ return "Readable"
+ }
+
+ # Describe a denied link target without risking another reporting failure.
+ function Get-PathDenialDetail {
+ param([Parameter(Mandatory = $true)][AllowNull()][AllowEmptyString()][string]$Path)
+
+ if ([string]::IsNullOrWhiteSpace($Path)) { return "" }
+ $item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
+ if (-not $item) { return "" }
+ # Non-filesystem providers do not expose FileSystemInfo attributes.
+ if ($item -isnot [System.IO.FileSystemInfo]) { return "" }
+ if (-not ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) { return "" }
+ $target = $null
+ try { $target = $item.Target } catch { $target = $null }
+ # PS 5.1 exposes .Target as a collection; PS 7 as a string.
+ if ($target) { return " (it is a link to $(@($target) -join ', '))" }
+ return " (it is a link)"
+ }
+
+ # Print guidance; returns the failure reason as its only pipeline output.
+ function Write-PathAccessDenied {
+ param(
+ [Parameter(Mandatory = $true)][AllowNull()][AllowEmptyString()][string]$Path,
+ [Parameter(Mandatory = $true)][AllowEmptyString()][string]$Label,
+ # Never tell users to delete a build they supplied.
+ [switch]$UserSupplied,
+ # Unreadable custom homes cannot be identified as managed caches.
+ [switch]$OwnershipUnverified
+ )
+
+ step "permissions" "$Label at $Path cannot be read: access is denied$(Get-PathDenialDetail -Path $Path)" "Red"
+ if ($UserSupplied) {
+ substep "Unsloth will not touch a directory you pointed it at, so this has to be fixed at the source" "Yellow"
+ substep "Restore access with these two in an elevated PowerShell, or point UNSLOTH_LOCAL_LLAMA_CPP_DIR at a readable build:" "Yellow"
+ } elseif ($OwnershipUnverified) {
+ substep "Unsloth cannot confirm this folder is its own install while it is unreadable, so it will not tell you to remove it" "Yellow"
+ substep "Restore access with these two in an elevated PowerShell, or move the folder aside and re-run setup:" "Yellow"
+ } else {
+ substep "This folder lives outside the app, so reinstalling Unsloth Studio, to any drive, reuses it and fails the same way" "Yellow"
+ substep "Simplest fix: close Unsloth, delete or rename $Path, then re-run setup (it is a managed cache and gets reinstalled)" "Yellow"
+ substep "If deleting is also denied, run these two in an elevated PowerShell, then re-run setup:" "Yellow"
+ }
+ substep "takeown /F `"$Path`" /R /D Y" "Yellow"
+ substep "icacls `"$Path`" /reset /T" "Yellow"
+ substep "Antivirus or Controlled folder access can deny this path too; allow or exclude it, then retry" "Yellow"
+ if ($UserSupplied) {
+ return "Access denied reading $Label at $Path. Restore access with takeown/icacls, or point UNSLOTH_LOCAL_LLAMA_CPP_DIR at a readable build, then re-run setup."
+ }
+ if ($OwnershipUnverified) {
+ return "Access denied reading $Label at $Path. Unsloth cannot confirm that folder is its own install while it is unreadable: restore access with takeown/icacls, or move it aside, then re-run setup."
+ }
+ return "Access denied reading the existing $Label at $Path. Delete or rename that folder (Unsloth reinstalls it) or restore access with takeown/icacls, then re-run setup. Reinstalling the app does not reset it."
+ }
+
+ # Canonicalize a directory for comparison; unresolvable ones are only normalized.
+ function Get-CanonicalDir {
+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
+
+ $trimmedPath = $Path.Trim()
+ if ([string]::IsNullOrWhiteSpace($trimmedPath)) { return $trimmedPath }
+ $resolvedPath = $null
+ if ((Get-PathState -Path $trimmedPath -PathType Container) -eq "Present") {
+ try { $resolvedPath = (Resolve-Path -LiteralPath $trimmedPath).Path } catch {}
+ }
+ if (-not $resolvedPath) {
+ try {
+ $resolvedPath =
+ $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($trimmedPath)
+ } catch {
+ $resolvedPath = [System.Environment]::ExpandEnvironmentVariables($trimmedPath)
+ }
+ try { $resolvedPath = [System.IO.Path]::GetFullPath($resolvedPath) } catch {}
+ }
+ # Resolve-Path keeps a trailing separator, so trim after both branches (never a root).
+ try {
+ $root = [System.IO.Path]::GetPathRoot($resolvedPath)
+ if ($root -and $resolvedPath.Length -gt $root.Length) { return $resolvedPath.TrimEnd('\', '/') }
+ } catch {}
+ return $resolvedPath
+ }
+
+ # Compare canonical homes so path spelling does not change ownership policy.
+ function Test-StudioHomeIsCustom {
+ return ((Get-CanonicalDir -Path $StudioHome) -ne
+ (Get-CanonicalDir -Path (Join-Path $env:USERPROFILE ".unsloth\studio")))
+ }
+
+ # Shared default cache, or the custom Studio home's llama.cpp tree.
+ function Get-ManagedLlamaCppDir {
+ if (-not (Test-StudioHomeIsCustom)) {
+ return (Join-Path $env:USERPROFILE ".unsloth\llama.cpp")
+ }
+ return (Join-Path (Get-CanonicalDir -Path $StudioHome) "llama.cpp")
+ }
+
+ # Failure reason when the managed tree is denied; never touches its ACLs.
+ function Invoke-ManagedLlamaCppPreflight {
+ # Let the existing profile validation handle a missing USERPROFILE later.
+ if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { return $null }
+ $dir = Get-ManagedLlamaCppDir
+ if ((Get-LlamaCppInstallReadState -Path $dir) -ne "Denied") { return $null }
+ Write-Host ""
+ # A denied custom home cannot be claimed as an Unsloth-managed cache.
+ $homeIsCustom = Test-StudioHomeIsCustom
+ # Preserve user-supplied wording when either override names this tree.
+ $suppliedDir = if ($WithLlamaCppDir) { $WithLlamaCppDir } else { $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR }
+ $userSupplied = (-not [string]::IsNullOrWhiteSpace($suppliedDir)) -and
+ ((Get-CanonicalDir -Path $suppliedDir) -eq (Get-CanonicalDir -Path $dir))
+ $reason = Write-PathAccessDenied -Path $dir -Label "llama.cpp install" `
+ -UserSupplied:$userSupplied -OwnershipUnverified:$homeIsCustom
+ substep "Stopping here, before phase 1: nothing has been downloaded or installed" "Yellow"
+ substep "Fix access, then run the same install, setup, or update command again" "Yellow"
+ Write-Host ""
+ return "$reason Nothing was installed."
+ }
+
+ # ── END SHARED WITH studio/setup.ps1 ──
+
# Redact index-URL credentials (userinfo + ?query= + #fragment) from captured installer
# output before printing on failure; uv/pip errors echo the failing --index-url verbatim.
# Mirrors the other installers. Verbose mode streams uncaptured, so it isn't redacted.
@@ -891,18 +1065,8 @@ public static class UnslothStudioFinalPathV2
# through one global mutex on 8888..8908. Default installs get an
# empty prefix to match pre-PR behavior.
$studioHomeExport = if ($StudioRedirectMode -eq 'env') {
- # When override == legacy default, llama.cpp stays at
- # ~/.unsloth/llama.cpp (one shared build). Canonicalize the
- # legacy side so the comparison survives path normalization.
- $_legacyStudio = Join-Path $env:USERPROFILE ".unsloth\studio"
- if (Test-Path -LiteralPath $_legacyStudio -PathType Container) {
- $_legacyStudio = (Resolve-Path -LiteralPath $_legacyStudio).Path
- }
- $_llamaPath = if ($StudioHome -eq $_legacyStudio) {
- Join-Path $env:USERPROFILE ".unsloth\llama.cpp"
- } else {
- Join-Path $StudioHome "llama.cpp"
- }
+ # Reuse the preflight's managed path for legacy-home overrides.
+ $_llamaPath = Get-ManagedLlamaCppDir
$_sq = $StudioHome -replace "'", "''"
$_llama = $_llamaPath -replace "'", "''"
$_appDirSq = $appDir -replace "'", "''"
@@ -1408,6 +1572,13 @@ exit 0
}
}
+ # ── Preflight the managed llama.cpp cache ──
+ # After System32 relocation (it picks the profile), before any download.
+ $llamaPreflightFailure = Invoke-ManagedLlamaCppPreflight
+ if ($llamaPreflightFailure) {
+ return (Exit-InstallFailure $llamaPreflightFailure)
+ }
+
# ── Check winget ──
# winget is only needed to install Python or uv. If both are
# already on PATH (Windows ARM64 GitHub-hosted runners, manual
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 356d4b026ee..0dad5793236 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -150,7 +150,8 @@ function Exit-SetupFailure {
[int]$Code = 1
)
if ($Code -eq 0) { $Code = 1 }
- if (@("1", "true") -contains $env:UNSLOTH_TAURI_MODE) {
+ if ((@("1", "true") -contains $env:UNSLOTH_TAURI_MODE) -or
+ (@("1", "true") -contains $env:UNSLOTH_TAURI_UPDATE)) {
$singleLine = ($Message -replace '[\r\n]+', ' ').Trim()
[Console]::Out.WriteLine("[TAURI:ERROR] $singleLine")
[Console]::Out.Flush()
@@ -325,16 +326,14 @@ function Remove-AgentInstructionFiles {
}
}
-# ERROR_ACCESS_DENIED in any of its disguises. PowerShell wraps .NET exceptions
-# in MethodInvocationException, so walk the chain instead of catching by type.
+# Recognize ERROR_ACCESS_DENIED through PowerShell's wrapper exceptions.
function Test-AccessDeniedError {
param($ErrorRecord)
$ex = if ($ErrorRecord -is [System.Management.Automation.ErrorRecord]) { $ErrorRecord.Exception } else { $ErrorRecord }
while ($ex) {
if ($ex -is [System.UnauthorizedAccessException]) { return $true }
- # IOException carries ERROR_ACCESS_DENIED as an HRESULT; Win32Exception
- # keeps E_FAIL there and puts the code in NativeErrorCode instead.
+ # IOException uses HRESULT; Win32Exception uses NativeErrorCode.
if ($ex.HResult -eq -2147024891) { return $true }
if ($ex -is [System.ComponentModel.Win32Exception] -and $ex.NativeErrorCode -eq 5) { return $true }
$ex = $ex.InnerException
@@ -345,10 +344,7 @@ function Test-AccessDeniedError {
return $false
}
-# Test-Path throws UnauthorizedAccessException (it does not return $false) when
-# an ACL denies the probe, and this script runs under "Stop", so a denied path
-# aborted setup with a raw error. "Denied" is kept distinct from "Absent"
-# because a denial needs reporting, not a silent retry.
+# Keep denied ACLs distinct from absent paths instead of letting Test-Path throw.
function Get-PathState {
param(
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path,
@@ -377,16 +373,34 @@ function Test-PathQuiet {
return ((Get-PathState -Path $Path -PathType $PathType) -eq "Present")
}
-# Names the link target of a denied dir, since that is where the user must look.
-# Empty/null tolerated: this runs while reporting a failure and must not add one.
+# install.ps1 carries a verbatim copy because it cannot dot-source this file;
+# test_denied_llama_cpp_preflight.py enforces parity.
+# Dir, marker and listing: no single probe separates readable/absent/denied.
+function Get-LlamaCppInstallReadState {
+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
+
+ $dirState = Get-PathState -Path $Path -PathType Container
+ if ($dirState -eq "Denied") { return "Denied" }
+ if ($dirState -ne "Present") { return "Absent" }
+ switch (Get-PathState -Path (Join-Path $Path "UNSLOTH_PREBUILT_INFO.json") -PathType Leaf) {
+ "Denied" { return "Denied" }
+ }
+ try { $null = @(Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop | Select-Object -First 1) }
+ catch {
+ if (Test-AccessDeniedError $_) { return "Denied" }
+ # Nonfatal here: nothing has been installed yet.
+ }
+ return "Readable"
+}
+
+# Describe a denied link target without risking another reporting failure.
function Get-PathDenialDetail {
param([Parameter(Mandatory = $true)][AllowNull()][AllowEmptyString()][string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) { return "" }
$item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
if (-not $item) { return "" }
- # Non-filesystem providers expose an unrelated .Attributes with no -band
- # overload, and throwing here would replace the failure we are reporting.
+ # Non-filesystem providers do not expose FileSystemInfo attributes.
if ($item -isnot [System.IO.FileSystemInfo]) { return "" }
if (-not ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) { return "" }
$target = $null
@@ -396,19 +410,14 @@ function Get-PathDenialDetail {
return " (it is a link)"
}
-# One stop for every unreadable install tree. Nothing downstream (validate,
-# replace, junction, source build, swap) can work without this access, and the
-# folder outlives an app reinstall, so retrying cannot help.
-function Exit-PathAccessDenied {
+# Print guidance; returns the failure reason as its only pipeline output.
+function Write-PathAccessDenied {
param(
[Parameter(Mandatory = $true)][AllowNull()][AllowEmptyString()][string]$Path,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$Label,
- # "delete it, we reinstall it" is true of the managed cache and wrong for
- # a tree the user pointed us at. Never tell them to delete their build.
+ # Never tell users to delete a build they supplied.
[switch]$UserSupplied,
- # Same rule, one step weaker: the ownership guard stops because it could
- # not read the marker, so it cannot claim the tree is ours either. It
- # already says "move it aside" when it CAN prove the tree is not ours.
+ # Unreadable custom homes cannot be identified as managed caches.
[switch]$OwnershipUnverified
)
@@ -428,12 +437,87 @@ function Exit-PathAccessDenied {
substep "icacls `"$Path`" /reset /T" "Yellow"
substep "Antivirus or Controlled folder access can deny this path too; allow or exclude it, then retry" "Yellow"
if ($UserSupplied) {
- Exit-SetupFailure "Access denied reading $Label at $Path. Restore access with takeown/icacls, or point UNSLOTH_LOCAL_LLAMA_CPP_DIR at a readable build, then re-run setup."
+ return "Access denied reading $Label at $Path. Restore access with takeown/icacls, or point UNSLOTH_LOCAL_LLAMA_CPP_DIR at a readable build, then re-run setup."
}
if ($OwnershipUnverified) {
- Exit-SetupFailure "Access denied reading $Label at $Path. Unsloth cannot confirm that folder is its own install while it is unreadable: restore access with takeown/icacls, or move it aside, then re-run setup."
+ return "Access denied reading $Label at $Path. Unsloth cannot confirm that folder is its own install while it is unreadable: restore access with takeown/icacls, or move it aside, then re-run setup."
+ }
+ return "Access denied reading the existing $Label at $Path. Delete or rename that folder (Unsloth reinstalls it) or restore access with takeown/icacls, then re-run setup. Reinstalling the app does not reset it."
+}
+
+# Canonicalize a directory for comparison; unresolvable ones are only normalized.
+function Get-CanonicalDir {
+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
+
+ $trimmedPath = $Path.Trim()
+ if ([string]::IsNullOrWhiteSpace($trimmedPath)) { return $trimmedPath }
+ $resolvedPath = $null
+ if ((Get-PathState -Path $trimmedPath -PathType Container) -eq "Present") {
+ try { $resolvedPath = (Resolve-Path -LiteralPath $trimmedPath).Path } catch {}
}
- Exit-SetupFailure "Access denied reading the existing $Label at $Path. Delete or rename that folder (Unsloth reinstalls it) or restore access with takeown/icacls, then re-run setup. Reinstalling the app does not reset it."
+ if (-not $resolvedPath) {
+ try {
+ $resolvedPath =
+ $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($trimmedPath)
+ } catch {
+ $resolvedPath = [System.Environment]::ExpandEnvironmentVariables($trimmedPath)
+ }
+ try { $resolvedPath = [System.IO.Path]::GetFullPath($resolvedPath) } catch {}
+ }
+ # Resolve-Path keeps a trailing separator, so trim after both branches (never a root).
+ try {
+ $root = [System.IO.Path]::GetPathRoot($resolvedPath)
+ if ($root -and $resolvedPath.Length -gt $root.Length) { return $resolvedPath.TrimEnd('\', '/') }
+ } catch {}
+ return $resolvedPath
+}
+
+# Compare canonical homes so path spelling does not change ownership policy.
+function Test-StudioHomeIsCustom {
+ return ((Get-CanonicalDir -Path $StudioHome) -ne
+ (Get-CanonicalDir -Path (Join-Path $env:USERPROFILE ".unsloth\studio")))
+}
+
+# Shared default cache, or the custom Studio home's llama.cpp tree.
+function Get-ManagedLlamaCppDir {
+ if (-not (Test-StudioHomeIsCustom)) {
+ return (Join-Path $env:USERPROFILE ".unsloth\llama.cpp")
+ }
+ return (Join-Path (Get-CanonicalDir -Path $StudioHome) "llama.cpp")
+}
+
+# Failure reason when the managed tree is denied; never touches its ACLs.
+function Invoke-ManagedLlamaCppPreflight {
+ # Let the existing profile validation handle a missing USERPROFILE later.
+ if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { return $null }
+ $dir = Get-ManagedLlamaCppDir
+ if ((Get-LlamaCppInstallReadState -Path $dir) -ne "Denied") { return $null }
+ Write-Host ""
+ # A denied custom home cannot be claimed as an Unsloth-managed cache.
+ $homeIsCustom = Test-StudioHomeIsCustom
+ # Preserve user-supplied wording when either override names this tree.
+ $suppliedDir = if ($WithLlamaCppDir) { $WithLlamaCppDir } else { $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR }
+ $userSupplied = (-not [string]::IsNullOrWhiteSpace($suppliedDir)) -and
+ ((Get-CanonicalDir -Path $suppliedDir) -eq (Get-CanonicalDir -Path $dir))
+ $reason = Write-PathAccessDenied -Path $dir -Label "llama.cpp install" `
+ -UserSupplied:$userSupplied -OwnershipUnverified:$homeIsCustom
+ substep "Stopping here, before phase 1: nothing has been downloaded or installed" "Yellow"
+ substep "Fix access, then run the same install, setup, or update command again" "Yellow"
+ Write-Host ""
+ return "$reason Nothing was installed."
+}
+
+# Stop every install path consistently when its destination is unreadable.
+function Exit-PathAccessDenied {
+ param(
+ [Parameter(Mandatory = $true)][AllowNull()][AllowEmptyString()][string]$Path,
+ [Parameter(Mandatory = $true)][AllowEmptyString()][string]$Label,
+ [switch]$UserSupplied,
+ [switch]$OwnershipUnverified
+ )
+
+ Exit-SetupFailure (Write-PathAccessDenied -Path $Path -Label $Label `
+ -UserSupplied:$UserSupplied -OwnershipUnverified:$OwnershipUnverified)
}
function Get-InstalledLlamaPrebuiltRelease {
@@ -1709,6 +1793,61 @@ function Clear-WebViewCaches {
if ($wvCleared) { substep "cleared stale WebView caches (ai.unsloth.studio); settings and data kept" }
}
+# 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".
+# Null or empty only: Join-Path accepts whitespace, and those runs used to complete.
+if ([string]::IsNullOrEmpty($env:USERPROFILE)) {
+ Write-Host "ERROR: USERPROFILE is not set." -ForegroundColor Red
+ Exit-SetupFailure "USERPROFILE is not set"
+}
+$_studioOverrideVar = $null
+$_studioOverride = $null
+if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) {
+ $_studioOverrideVar = "UNSLOTH_STUDIO_HOME"
+ $_studioOverride = $env:UNSLOTH_STUDIO_HOME.Trim()
+} elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) {
+ $_studioOverrideVar = "STUDIO_HOME"
+ $_studioOverride = $env:STUDIO_HOME.Trim()
+}
+if ($_studioOverride) {
+ if ($_studioOverride -eq "~" -or $_studioOverride -like "~/*" -or $_studioOverride -like "~\*") {
+ $_studioOverride = (Join-Path $env:USERPROFILE $_studioOverride.Substring(1).TrimStart('/','\'))
+ }
+ if (Test-Path -LiteralPath $_studioOverride -PathType Container) {
+ $StudioHome = (Resolve-Path -LiteralPath $_studioOverride).Path
+ # Mirror setup.sh and install.ps1: fail before install work if it is read-only.
+ $_setupWriteProbe = Join-Path $StudioHome (".unsloth-write-probe-" + [guid]::NewGuid())
+ try {
+ [System.IO.File]::WriteAllText($_setupWriteProbe, "")
+ Remove-Item -LiteralPath $_setupWriteProbe -Force -ErrorAction SilentlyContinue
+ } catch {
+ Write-Host "ERROR: $_studioOverrideVar=$StudioHome is not writable." -ForegroundColor Red
+ Exit-SetupFailure "$_studioOverrideVar=$StudioHome is not writable"
+ }
+ } else {
+ Write-Host "ERROR: $_studioOverrideVar=$_studioOverride does not exist." -ForegroundColor Red
+ Write-Host " Run install.ps1 to create the install root before 'unsloth studio update'." -ForegroundColor Red
+ Exit-SetupFailure "$_studioOverrideVar=$_studioOverride does not exist"
+ }
+} else {
+ $StudioHome = Join-Path $env:USERPROFILE ".unsloth\studio"
+}
+$VenvDir = Join-Path $StudioHome "unsloth_studio"
+$StudioOwnedMarker = ".unsloth-studio-owned"
+# Mirrors install_manifest.NO_TORCH_MARKER; keep the two in step.
+$NoTorchMarker = ".unsloth-no-torch"
+$LegacyStudioHome = Join-Path $env:USERPROFILE ".unsloth\studio"
+$StudioHomeIsCustom = Test-StudioHomeIsCustom
+$LlamaCppDir = Get-ManagedLlamaCppDir
+$UnslothHome = Split-Path -Parent $LlamaCppDir
+
+$WithLlamaCppDir = $null
+$llamaPreflightFailure = Invoke-ManagedLlamaCppPreflight
+if ($llamaPreflightFailure) {
+ Exit-SetupFailure $llamaPreflightFailure
+}
+
# Back up User PATH under HKCU\Software\Unsloth before any modifications.
try {
$envKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)
@@ -3456,51 +3595,10 @@ if (-not $PythonCmd) {
substep "Python found: $PythonCmd"
-# The venv must already exist (created by install.ps1); this script only
-# updates packages. UNSLOTH_STUDIO_HOME (or STUDIO_HOME alias) overrides the
-# root. UNSLOTH_STUDIO_HOME wins when both are set. Whitespace-only values
-# are treated as unset to match Python .strip() semantics.
-$_studioOverrideVar = $null
-$_studioOverride = $null
-if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) {
- $_studioOverrideVar = "UNSLOTH_STUDIO_HOME"
- $_studioOverride = $env:UNSLOTH_STUDIO_HOME.Trim()
-} elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) {
- $_studioOverrideVar = "STUDIO_HOME"
- $_studioOverride = $env:STUDIO_HOME.Trim()
-}
-if ($_studioOverride) {
- if ($_studioOverride -eq "~" -or $_studioOverride -like "~/*" -or $_studioOverride -like "~\*") {
- $_studioOverride = (Join-Path $env:USERPROFILE $_studioOverride.Substring(1).TrimStart('/','\'))
- }
- if (Test-Path -LiteralPath $_studioOverride -PathType Container) {
- $StudioHome = (Resolve-Path -LiteralPath $_studioOverride).Path
- # why: mirror setup.sh:417 and install.ps1:130 -- fail fast when the
- # custom root is read-only instead of erroring later while creating
- # sidecar venvs / installing packages.
- $_setupWriteProbe = Join-Path $StudioHome (".unsloth-write-probe-" + [guid]::NewGuid())
- try {
- [System.IO.File]::WriteAllText($_setupWriteProbe, "")
- Remove-Item -LiteralPath $_setupWriteProbe -Force -ErrorAction SilentlyContinue
- } catch {
- Write-Host "ERROR: $_studioOverrideVar=$StudioHome is not writable." -ForegroundColor Red
- Exit-SetupFailure "$_studioOverrideVar=$StudioHome is not writable"
- }
- } else {
- Write-Host "ERROR: $_studioOverrideVar=$_studioOverride does not exist." -ForegroundColor Red
- Write-Host " Run install.ps1 to create the install root before 'unsloth studio update'." -ForegroundColor Red
- Exit-SetupFailure "$_studioOverrideVar=$_studioOverride does not exist"
- }
-} else {
- $StudioHome = Join-Path $env:USERPROFILE ".unsloth\studio"
-}
-
-$VenvDir = Join-Path $StudioHome "unsloth_studio"
-
-# The override is validated, so a typo can no longer cost the cache. Venv-gated because
-# a writable-but-empty override still fails at the venv check below, and clearing first
-# would cost the cache for a run that then does nothing; a fresh install has neither venv
-# nor cache. Still before any install work.
+# $StudioHome / $VenvDir are resolved and preflighted before phase 1, so only the
+# cache clear stays here. Venv-gated: a writable-but-empty override still fails the
+# venv check below, and clearing first would cost the cache for a run that then does
+# nothing. Still before any install work.
if (Test-Path -LiteralPath (Join-Path $VenvDir "Scripts\python.exe") -PathType Leaf) {
Clear-WebViewCaches
}
@@ -3509,18 +3607,6 @@ if (Test-Path -LiteralPath (Join-Path $VenvDir "Scripts\python.exe") -PathType L
# ownership marker before Remove-Item so unrelated dirs survive. Gated on
# the canonical comparison so an override pointing at the legacy default
# still behaves like a default install.
-$StudioOwnedMarker = ".unsloth-studio-owned"
-# Mirrors install_manifest.NO_TORCH_MARKER; keep the two in step.
-$NoTorchMarker = ".unsloth-no-torch"
-$LegacyStudioHome = Join-Path $env:USERPROFILE ".unsloth\studio"
-$_studioHomeCanon = $StudioHome
-if (Test-Path -LiteralPath $_studioHomeCanon -PathType Container) {
- $_studioHomeCanon = (Resolve-Path -LiteralPath $_studioHomeCanon).Path
-}
-if (Test-Path -LiteralPath $LegacyStudioHome -PathType Container) {
- $LegacyStudioHome = (Resolve-Path -LiteralPath $LegacyStudioHome).Path
-}
-$StudioHomeIsCustom = ($_studioHomeCanon -ne $LegacyStudioHome)
# Directory-local evidence that Unsloth created $Path, used to adopt a custom-home
# llama.cpp or whisper.cpp predating the .unsloth-studio-owned marker (see
# setup.sh). Only Unsloth prebuilt markers count; source builds are
@@ -4836,16 +4922,8 @@ step "transformers" "5.10.2 pre-installed"
# ==========================================================================
# PHASE 3.4: Prefer prebuilt llama.cpp bundles before source build
# ==========================================================================
-# Nest llama.cpp under $StudioHome only for real env-overrides, never the
-# legacy default. Reuses $StudioHomeIsCustom from the canonical comparison
-# computed above so the llama.cpp nest matches ownership-guard semantics.
-if ($StudioHomeIsCustom) {
- $UnslothHome = $StudioHome
-} else {
- $UnslothHome = Join-Path $env:USERPROFILE ".unsloth"
-}
+# Reuse the managed path resolved and preflighted before phase 1.
if (-not (Test-Path -LiteralPath $UnslothHome)) { [System.IO.Directory]::CreateDirectory($UnslothHome) | Out-Null }
-$LlamaCppDir = Join-Path $UnslothHome "llama.cpp"
$NeedLlamaSourceBuild = $false
$SkipPrebuiltInstall = $false
$RequestedLlamaTag = if ($env:UNSLOTH_LLAMA_TAG) { $env:UNSLOTH_LLAMA_TAG } else { $DefaultLlamaTag }
@@ -5077,25 +5155,19 @@ if ($LocalLlamaCppLinked) {
substep "Skipping prebuilt install -- falling back to source build" "Yellow"
} else {
Write-Host ""
- # Denied on the dir itself means an unreadable parent; Denied on the file
- # below means an unreadable install. Either way nothing here can proceed,
- # and the bare probes used to die under "Stop" with a raw
- # "Test-Path : Access is denied" and exit 1.
- $llamaDirState = Get-PathState -Path $LlamaCppDir
+ # Keep this late guard as defense in depth before the prebuilt installer.
+ $llamaDirState = Get-LlamaCppInstallReadState -Path $LlamaCppDir
if ($llamaDirState -eq "Denied") {
- Exit-PathAccessDenied -Path $LlamaCppDir -Label "llama.cpp install"
+ Exit-PathAccessDenied -Path $LlamaCppDir -Label "llama.cpp install" -OwnershipUnverified:$StudioHomeIsCustom
}
- if ($llamaDirState -eq "Present") {
+ if ($llamaDirState -eq "Readable") {
substep "Existing llama.cpp install detected -- validating staged prebuilt update before replacement"
# If the existing install is the wrong kind (e.g. windows-cpu on a ROCm
# machine that should have windows-rocm), remove it so the installer is
# forced to download the correct variant rather than skipping on tag match.
$existingMetaPath = Join-Path $LlamaCppDir "UNSLOTH_PREBUILT_INFO.json"
- $existingMetaState = Get-PathState -Path $existingMetaPath -PathType Leaf
- if ($existingMetaState -eq "Denied") {
- Exit-PathAccessDenied -Path $LlamaCppDir -Label "llama.cpp install"
- }
- if ($existingMetaState -eq "Present") {
+ # Readable state leaves only marker presence to decide here.
+ if (Test-PathQuiet -Path $existingMetaPath -PathType Leaf) {
try {
$existingMeta = Get-Content -LiteralPath $existingMetaPath -Raw | ConvertFrom-Json
$existingKind = $existingMeta.install_kind
diff --git a/studio/setup.sh b/studio/setup.sh
index 0e43221c428..6fed3ddc4d3 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -75,9 +75,13 @@ setup_fail() {
[ "$exit_code" -ne 0 ] || exit_code=1
local message
message=$(printf '%s' "$*" | tr '\r\n' ' ')
- case "${UNSLOTH_TAURI_MODE:-0}" in
- 1|true) printf '[TAURI:ERROR] %s\n' "$message" ;;
- esac
+ # Match setup.ps1: update.rs sets UNSLOTH_TAURI_UPDATE everywhere and promotes
+ # this line over the generic "Update exited with code N". Test each variable
+ # separately: one joined subject lets a comma in either value alias the other arm.
+ local tauri_marker=0
+ case "${UNSLOTH_TAURI_MODE:-0}" in 1|true) tauri_marker=1 ;; esac
+ case "${UNSLOTH_TAURI_UPDATE:-0}" in 1|true) tauri_marker=1 ;; esac
+ if [ "$tauri_marker" -eq 1 ]; then printf '[TAURI:ERROR] %s\n' "$message"; fi
exit "$exit_code"
}
@@ -982,6 +986,15 @@ _studio_dir_unsearchable() {
return 0
}
+# Also needs +r, for callers that list or replace the tree: mode 111 is searchable
+# but still fails install_llama_prebuilt.py.
+_studio_dir_unreadable() {
+ [ -d "$1" ] || return 1
+ _studio_dir_unsearchable "$1" && return 0
+ ls -A "$1" >/dev/null 2>&1 && return 1
+ return 0
+}
+
# Mirrors Exit-PathAccessDenied in setup.ps1. owner-unverified means the marker
# was unreadable, so do not claim the tree is ours or advise deleting it.
_path_access_denied() {
@@ -1986,7 +1999,9 @@ if [ -n "${UNSLOTH_LOCAL_LLAMA_CPP_DIR:-}" ]; then
fi
rm -rf "$LLAMA_CPP_DIR" || true
if [ -e "$LLAMA_CPP_DIR" ]; then
- if _studio_dir_unsearchable "$LLAMA_CPP_DIR"; then
+ # Unreadable, not just unsearchable: mode 111 defeats the rm above and
+ # would fall through to the generic message.
+ if _studio_dir_unreadable "$LLAMA_CPP_DIR"; then
_path_access_denied "$LLAMA_CPP_DIR" "llama.cpp install"
fi
step "llama.cpp" "the existing install could not be replaced with a link" "$C_ERR"
@@ -2001,6 +2016,18 @@ if [ -n "${UNSLOTH_LOCAL_LLAMA_CPP_DIR:-}" ]; then
fi
fi
+# Every branch below replaces $LLAMA_CPP_DIR or builds into it, and the source-build
+# swap only reaches its own guards after the whole build, so check here instead.
+# Local-link paths are excluded: they already replaced or reused the tree above.
+if [ "$_LOCAL_LLAMA_CPP_LINKED" != true ]; then
+ if [ "$_STUDIO_HOME_IS_CUSTOM" = true ]; then
+ _assert_studio_owned_or_absent "$LLAMA_CPP_DIR" "llama.cpp install"
+ fi
+ if _studio_dir_unreadable "$LLAMA_CPP_DIR"; then
+ _path_access_denied "$LLAMA_CPP_DIR" "llama.cpp install"
+ fi
+fi
+
if [ "$_LOCAL_LLAMA_CPP_LINKED" = true ]; then
: # local directory linked above; skip prebuilt install
elif [ "$_explicit_vulkan_source_build" = true ] && [ "$_NEED_LLAMA_SOURCE_BUILD" = true ]; then
@@ -2023,6 +2050,11 @@ else
if [ "$_STUDIO_HOME_IS_CUSTOM" = true ]; then
_assert_studio_owned_or_absent "$LLAMA_CPP_DIR" "llama.cpp install"
fi
+ # The ownership check above misses the default cache; stop before pathlib
+ # turns an unreadable one into a traceback.
+ if _studio_dir_unreadable "$LLAMA_CPP_DIR"; then
+ _path_access_denied "$LLAMA_CPP_DIR" "llama.cpp install"
+ fi
_PREBUILT_CMD=(
python "$SCRIPT_DIR/install_llama_prebuilt.py"
--install-dir "$LLAMA_CPP_DIR"
@@ -2692,7 +2724,9 @@ else
# code, build stranded. Keep stderr: rm names the exact subpath, we cannot.
rm -rf "$LLAMA_CPP_DIR" || true
if [ -e "$LLAMA_CPP_DIR" ]; then
- if _studio_dir_unsearchable "$LLAMA_CPP_DIR"; then
+ # Same probe as the other replace sites: the hoisted guard covers a
+ # tree already denied, this catches one denied mid-build.
+ if _studio_dir_unreadable "$LLAMA_CPP_DIR"; then
_path_access_denied "$LLAMA_CPP_DIR" "llama.cpp install"
fi
step "llama.cpp" "built, but the existing install could not be replaced" "$C_ERR"
diff --git a/studio/src-tauri/src/update.rs b/studio/src-tauri/src/update.rs
index 020ffaa15e9..5ff44ccfb9f 100644
--- a/studio/src-tauri/src/update.rs
+++ b/studio/src-tauri/src/update.rs
@@ -153,11 +153,19 @@ fn read_lossy_lines<R: std::io::Read>(
}
}
+fn structured_update_error(text: &str) -> Option<String> {
+ text.strip_prefix("[TAURI:ERROR] ")
+ .map(str::trim)
+ .filter(|message| !message.is_empty())
+ .map(str::to_owned)
+}
+
fn stream_output(
app: &AppHandle,
progress_event: &'static str,
diagnostics: DiagnosticsState,
attempt: AttemptLog,
+ explicit_error: Arc<Mutex<Option<String>>>,
stdout: Option<std::process::ChildStdout>,
stderr: Option<std::process::ChildStderr>,
) -> Vec<std::thread::JoinHandle<()>> {
@@ -167,6 +175,7 @@ fn stream_output(
let app_clone = app.clone();
let diagnostics_clone = diagnostics.clone();
let attempt_clone = attempt.clone();
+ let explicit_error_clone = explicit_error.clone();
threads.push(std::thread::spawn(move || {
if let Err(e) = read_lossy_lines(out, |text| {
diagnostics::append_phase_line(&attempt_clone.handle, "stdout", &text);
@@ -177,6 +186,11 @@ fn stream_output(
} else if let Some(marker) = text.strip_prefix("[TAURI:DIAG] ") {
diagnostics::record_diag_marker(&diagnostics_clone, &attempt_clone, marker);
}
+ if let Some(message) = structured_update_error(&text) {
+ if let Ok(mut error) = explicit_error_clone.lock() {
+ *error = Some(message);
+ }
+ }
info!("[update][stdout] {}", text);
let _ = app_clone.emit(progress_event, &text);
}) {
@@ -290,6 +304,7 @@ fn run_backend_update_with_terminal_events(
};
let _ = app.emit(progress_event, "Starting backend update...");
+ let explicit_error = Arc::new(Mutex::new(None));
// Update mutates the managed environment for its whole lifetime. This function
// is synchronous, so the thread-owned Win32 mutex never crosses an await.
let result = crate::process::with_studio_runtime_launch_guard(|| {
@@ -301,6 +316,7 @@ fn run_backend_update_with_terminal_events(
progress_event,
diagnostics.clone(),
attempt.clone(),
+ explicit_error.clone(),
stdout,
stderr,
);
@@ -311,6 +327,8 @@ fn run_backend_update_with_terminal_events(
}
result
});
+ // Read only after the guard returned, so both reader threads are joined.
+ let explicit_error = explicit_error.lock().ok().and_then(|error| error.clone());
match result {
Ok((status, _)) if status.success() => {
@@ -342,7 +360,7 @@ fn run_backend_update_with_terminal_events(
}
Ok((status, intentional)) => {
let code = status.code().unwrap_or(-1);
- let msg = format!("Update exited with code {}", code);
+ let msg = explicit_error.unwrap_or_else(|| format!("Update exited with code {}", code));
diagnostics::finish_attempt(
&diagnostics,
&attempt,
@@ -475,6 +493,16 @@ mod tests {
assert_eq!(lines, ["bad\u{fffd}", "[TAURI:STEP] next"]);
}
+ #[test]
+ fn structured_update_error_is_promoted_from_stdout() {
+ assert_eq!(
+ structured_update_error("[TAURI:ERROR] Access denied reading llama.cpp"),
+ Some("Access denied reading llama.cpp".to_string())
+ );
+ assert_eq!(structured_update_error("[TAURI:ERROR] "), None);
+ assert_eq!(structured_update_error("ordinary update output"), None);
+ }
+
#[cfg(windows)]
#[test]
fn windows_update_command_uses_python_not_replaceable_console_stub() {
diff --git a/tests/sh/test_setup_sh_denied_install_tree.sh b/tests/sh/test_setup_sh_denied_install_tree.sh
index afa3f6034e4..894ec6a2902 100755
--- a/tests/sh/test_setup_sh_denied_install_tree.sh
+++ b/tests/sh/test_setup_sh_denied_install_tree.sh
@@ -37,6 +37,42 @@ assert_contains "the ownership guard checks readability before blaming ownership
assert_contains "an unverifiable tree is never described as not ours" \
"$SETUP_SH" "Unsloth cannot confirm this folder is its own install while it is unreadable"
+# The custom-home ownership guard misses the default cache, so check the prebuilt
+# path rejects an unreadable one before Python runs.
+PREBUILT_BLOCK="$(awk '/substep "installing prebuilt llama.cpp\.\.\."/,/_PREBUILT_CMD=\(/' "$SETUP_SH")"
+if printf '%s' "$PREBUILT_BLOCK" | grep -qF '_studio_dir_unreadable "$LLAMA_CPP_DIR"' &&
+ printf '%s' "$PREBUILT_BLOCK" | grep -qF '_path_access_denied "$LLAMA_CPP_DIR" "llama.cpp install"'; then
+ ok "the default-home prebuilt install stops on an unreadable tree"
+else
+ bad "the default-home prebuilt install stops on an unreadable tree"
+fi
+# The source build only guards after building, so check before the prebuilt/source
+# branch, skipping the local-link paths.
+PRE_BRANCH="$(awk '/^if \[ "\$_LOCAL_LLAMA_CPP_LINKED" != true \]; then/,/^fi$/' "$SETUP_SH")"
+if printf '%s' "$PRE_BRANCH" | grep -qF '_studio_dir_unreadable "$LLAMA_CPP_DIR"' &&
+ printf '%s' "$PRE_BRANCH" | grep -qF '_assert_studio_owned_or_absent "$LLAMA_CPP_DIR"'; then
+ ok "the access guard runs before the prebuilt/source branch"
+else
+ bad "the access guard runs before the prebuilt/source branch"
+fi
+PRE_AT="$(grep -n '^if \[ "\$_LOCAL_LLAMA_CPP_LINKED" != true \]; then' "$SETUP_SH" | cut -d: -f1 | head -1)"
+BRANCH_AT="$(grep -n '^if \[ "\$_LOCAL_LLAMA_CPP_LINKED" = true \]; then' "$SETUP_SH" | cut -d: -f1 | head -1)"
+if [ -n "$PRE_AT" ] && [ -n "$BRANCH_AT" ] && [ "$PRE_AT" -lt "$BRANCH_AT" ]; then
+ ok "the early guard precedes the branch it protects"
+else
+ bad "the early guard precedes the branch it protects"
+fi
+
+# Ownership guard first, to keep its cautious wording. Line numbers are checked for
+# emptiness so a vanished grep fails loudly.
+OWNED_LINE="$(printf '%s' "$PREBUILT_BLOCK" | grep -n '_assert_studio_owned_or_absent' | cut -d: -f1 | head -1)"
+UNREADABLE_LINE="$(printf '%s' "$PREBUILT_BLOCK" | grep -n '_studio_dir_unreadable' | cut -d: -f1 | head -1)"
+if [ -n "$OWNED_LINE" ] && [ -n "$UNREADABLE_LINE" ] && [ "$OWNED_LINE" -lt "$UNREADABLE_LINE" ]; then
+ ok "the ownership guard still reports a custom home first"
+else
+ bad "the ownership guard still reports a custom home first"
+fi
+
echo ""
echo "=== setup.sh: neither destructive replace runs blind ==="
@@ -53,6 +89,13 @@ if grep -q 'rm -rf "$LLAMA_CPP_DIR" 2>/dev/null' "$SETUP_SH"; then
else
ok "the failing rm keeps its stderr"
fi
+# Mode 111 defeats the rm but stays searchable, so a search-only postcondition falls
+# through to the generic "could not be replaced" message.
+if [ "$(grep -c '_studio_dir_unsearchable "\$LLAMA_CPP_DIR"' "$SETUP_SH")" = 0 ]; then
+ ok "no replace site still uses the search-only probe"
+else
+ bad "no replace site still uses the search-only probe"
+fi
if [ "$(grep -c 'if \[ -e "$LLAMA_CPP_DIR" \]; then' "$SETUP_SH")" -ge 2 ]; then
ok "both replace sites check the postcondition"
else
@@ -80,6 +123,7 @@ import sys, pathlib
src = pathlib.Path(sys.argv[1]).read_text()
out = []
for name in ("_studio_owned_adoptable", "_studio_dir_unsearchable",
+ "_studio_dir_unreadable",
"_path_access_denied", "_assert_studio_owned_or_absent"):
i = src.index(name + "() {")
out.append(src[i:src.index("\n}\n", i) + 3])
@@ -136,6 +180,51 @@ else
fi
chmod 755 "$OURS"
+# setup_fail gates [TAURI:ERROR] on two variables. Test them separately: one joined
+# case subject lets a comma in either value alias the other's arm.
+python3 - "$SETUP_SH" "$WORK/gate.sh" <<'PY'
+import sys, pathlib
+src = pathlib.Path(sys.argv[1]).read_text()
+i = src.index("setup_fail() {")
+pathlib.Path(sys.argv[2]).write_text(src[i:src.index("\n}\n", i) + 3])
+PY
+gate_marker() { # $1=MODE ("-" for unset), $2=UPDATE ("-" for unset)
+ env -u UNSLOTH_TAURI_MODE -u UNSLOTH_TAURI_UPDATE \
+ ${1:+$([ "$1" = - ] || echo UNSLOTH_TAURI_MODE="$1")} \
+ ${2:+$([ "$2" = - ] || echo UNSLOTH_TAURI_UPDATE="$2")} \
+ bash -c '. "$1"; setup_fail 1 boom' _ "$WORK/gate.sh" 2>/dev/null | grep -c 'TAURI:ERROR' || true
+}
+[ "$(gate_marker 1 -)" = 1 ] && ok "the Tauri marker prints for UNSLOTH_TAURI_MODE=1" \
+ || bad "the Tauri marker prints for UNSLOTH_TAURI_MODE=1"
+[ "$(gate_marker - 1)" = 1 ] && ok "the Tauri marker prints for UNSLOTH_TAURI_UPDATE=1" \
+ || bad "the Tauri marker prints for UNSLOTH_TAURI_UPDATE=1"
+[ "$(gate_marker - -)" = 0 ] && ok "a plain CLI run prints no Tauri marker" \
+ || bad "a plain CLI run prints no Tauri marker"
+[ "$(gate_marker 0 'a,1')" = 0 ] && ok "a comma in UNSLOTH_TAURI_UPDATE does not alias the marker" \
+ || bad "a comma in UNSLOTH_TAURI_UPDATE does not alias the marker"
+[ "$(gate_marker '1,2' -)" = 0 ] && ok "a comma in UNSLOTH_TAURI_MODE does not alias the marker" \
+ || bad "a comma in UNSLOTH_TAURI_MODE does not alias the marker"
+
+# Mode 111 is searchable but not listable, and still breaks install_llama_prebuilt.py.
+NOLIST="$WORK/nolist"; mkdir -p "$NOLIST"; : > "$NOLIST/UNSLOTH_PREBUILT_INFO.json"
+chmod 111 "$NOLIST"
+if ls -A "$NOLIST" >/dev/null 2>&1; then
+ echo " SKIP: this host cannot make a directory unlistable (running as root?)"
+else
+ ok "the host really cannot list the tree (negative control)"
+ probe=$(bash -c '. "$1"; _studio_dir_unsearchable "$2" && echo SEARCH_CAUGHT
+ _studio_dir_unreadable "$2" && echo READ_CAUGHT' _ "$WORK/helpers.sh" "$NOLIST")
+ case "$probe" in
+ *SEARCH_CAUGHT*) bad "mode 111 is searchable, so the search probe must not fire" ;;
+ *) ok "mode 111 is searchable, so the search probe does not fire" ;;
+ esac
+ case "$probe" in
+ *READ_CAUGHT*) ok "the read probe catches a searchable but unlistable tree" ;;
+ *) bad "the read probe catches a searchable but unlistable tree (got: $probe)" ;;
+ esac
+fi
+chmod 755 "$NOLIST"
+
echo ""
echo "=== Results ==="
echo " PASS: $PASS"
diff --git a/tests/studio/install/test_denied_llama_cpp_preflight.py b/tests/studio/install/test_denied_llama_cpp_preflight.py
new file mode 100644
index 00000000000..4b8c32c8749
--- /dev/null
+++ b/tests/studio/install/test_denied_llama_cpp_preflight.py
@@ -0,0 +1,305 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Check managed llama.cpp access before Windows installer work.
+
+The standalone installer copies setup.ps1's preflight helpers. These tests enforce
+their parity and cover real denied trees through the PowerShell harness.
+"""
+
+import re
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[3]
+INSTALL_PS1 = (ROOT / "install.ps1").read_text(encoding = "utf-8")
+SETUP_PS1 = (ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
+SETUP_SH = (ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8")
+ACL_PS1 = (ROOT / "tests" / "studio" / "test_path_probe_access_denied.ps1").read_text(
+ encoding = "utf-8"
+)
+
+SHARED_BEGIN = "# ── BEGIN SHARED WITH studio/setup.ps1 ──"
+SHARED_END = "# ── END SHARED WITH studio/setup.ps1 ──"
+
+# Helpers copied byte-for-byte into install.ps1.
+SHARED_FUNCTIONS = (
+ "Test-AccessDeniedError",
+ "Get-PathState",
+ "Get-LlamaCppInstallReadState",
+ "Get-PathDenialDetail",
+ "Write-PathAccessDenied",
+ "Get-CanonicalDir",
+ "Test-StudioHomeIsCustom",
+ "Get-ManagedLlamaCppDir",
+ "Invoke-ManagedLlamaCppPreflight",
+)
+
+
+def _function_source(text: str, name: str) -> str:
+ """Extract a PowerShell function by matching balanced braces."""
+ match = re.search(rf"(?im)^[ \t]*function[ \t]+{re.escape(name)}\b", text)
+ assert match, f"{name} is not defined"
+ start = text.index("{", match.start())
+ depth = 0
+ for index in range(start, len(text)):
+ if text[index] == "{":
+ depth += 1
+ elif text[index] == "}":
+ depth -= 1
+ if depth == 0:
+ return text[match.start() : index + 1]
+ raise AssertionError(f"unbalanced braces in {name}")
+
+
+def _normalized(source: str) -> str:
+ """Remove only the common indentation before comparing helper copies."""
+ lines = [line.rstrip() for line in source.splitlines()]
+ body = [line for line in lines if line.strip()]
+ indent = min(len(line) - len(line.lstrip(" ")) for line in body)
+ return "\n".join(line[indent:] if line.strip() else "" for line in lines)
+
+
[email protected]("name", SHARED_FUNCTIONS)
+def test_installer_copy_matches_setup(name: str) -> None:
+ """Edit one file, not the other, and this fails naming the function."""
+ assert _normalized(_function_source(INSTALL_PS1, name)) == _normalized(
+ _function_source(SETUP_PS1, name)
+ ), name
+
+
+def test_every_function_in_the_shared_block_is_compared() -> None:
+ """The parity list cannot silently fall behind the block it guards."""
+ assert SHARED_BEGIN in INSTALL_PS1
+ assert SHARED_END in INSTALL_PS1
+ block = INSTALL_PS1.split(SHARED_BEGIN, 1)[1].split(SHARED_END, 1)[0]
+ declared = re.findall(r"(?m)^[ \t]*function[ \t]+([A-Za-z-]+)", block)
+ assert sorted(declared) == sorted(SHARED_FUNCTIONS), declared
+
+
+def test_the_shared_block_carries_the_drift_note() -> None:
+ """A reader who does not know these are copies will paraphrase one of them."""
+ head = INSTALL_PS1.split(SHARED_BEGIN, 1)[0].rsplit("\n\n", 3)[-1]
+ assert "byte-identical copies" in head
+ assert "test_denied_llama_cpp_preflight.py" in head
+ assert "cannot dot-source" in head
+ setup_note = SETUP_PS1.split("function Get-LlamaCppInstallReadState", 1)[0]
+ assert "install.ps1 carries a verbatim copy" in setup_note
+
+
+def test_setup_and_the_installer_use_the_same_probe() -> None:
+ """Both Windows entrypoints must use the shared tri-state probe."""
+ assert "$llamaDirState = Get-LlamaCppInstallReadState -Path $LlamaCppDir" in SETUP_PS1
+ assert '$llamaDirState -eq "Denied"' in SETUP_PS1
+ assert '$llamaDirState -eq "Readable"' in SETUP_PS1
+ assert '(Get-LlamaCppInstallReadState -Path $dir) -ne "Denied"' in INSTALL_PS1
+
+
+def test_the_probe_keeps_all_three_answers() -> None:
+ """Keep denied, absent, and readable states distinct."""
+ probe = _function_source(SETUP_PS1, "Get-LlamaCppInstallReadState")
+ for verdict in ('return "Denied"', 'return "Absent"', 'return "Readable"'):
+ assert verdict in probe, verdict
+ # Listing catches denied directories whose missing marker appears absent.
+ assert "Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop" in probe
+ assert "Test-AccessDeniedError" in probe
+ # A readable marker is not enough: replacement also needs directory listing.
+ # Regex, not a literal: whitespace alone must not reintroduce the early return.
+ assert not re.search(r'"Present"\s*\{\s*return\s+"Readable"', probe)
+ assert probe.index("Get-ChildItem -LiteralPath") < probe.rindex('return "Readable"')
+ # It runs before anything is installed, so it must not terminate.
+ assert probe.count("try {") == 1
+ assert "catch" in probe
+
+
+def test_the_preflight_runs_before_anything_expensive() -> None:
+ """The whole fix is the ordering. Every step below costs network, disk or both."""
+ call = "$llamaPreflightFailure = Invoke-ManagedLlamaCppPreflight"
+ assert INSTALL_PS1.count(call) == 1
+ position = INSTALL_PS1.index(call)
+ for later in (
+ 'Write-TauriLog "STEP" "Checking system dependencies"',
+ 'Write-TauriLog "STEP" "Installing Python"',
+ 'Write-TauriLog "STEP" "Installing uv package manager"',
+ 'Write-TauriLog "STEP" "Creating virtual environment"',
+ 'Write-TauriLog "STEP" "Installing PyTorch"',
+ 'Write-TauriLog "STEP" "Installing unsloth"',
+ 'Write-TauriLog "STEP" "Running studio setup"',
+ ):
+ assert position < INSTALL_PS1.index(later), later
+ # Relocation decides which user profile owns the managed cache.
+ relocation = "# ── Leave Windows system directories before installing ──"
+ assert INSTALL_PS1.index(relocation) < position
+
+
+def test_direct_setup_and_update_preflight_before_phase_one() -> None:
+ """Direct setup, update, and repair must preflight before phase one."""
+ call = "$llamaPreflightFailure = Invoke-ManagedLlamaCppPreflight"
+ assert SETUP_PS1.count(call) == 1
+ position = SETUP_PS1.index(call)
+ assert SETUP_PS1.index("$LlamaCppDir = Get-ManagedLlamaCppDir") < position
+ for later in (
+ "PHASE 1: System-level prerequisites",
+ "PHASE 2: Frontend build",
+ "PHASE 3: Python environment + dependencies",
+ "PHASE 3.4: Prefer prebuilt llama.cpp",
+ ):
+ assert position < SETUP_PS1.index(later), later
+ failure = SETUP_PS1[position : SETUP_PS1.index("# Back up User PATH", position)]
+ assert "Exit-SetupFailure $llamaPreflightFailure" in failure
+
+
+def test_acl_suite_runs_every_complete_windows_entrypoint() -> None:
+ """Windows CI must run every entrypoint and trap expensive work."""
+ assert '& (Join-Path $repoRoot "install.ps1") --tauri' in ACL_PS1
+ assert '& (Join-Path $repoRoot "studio/setup.ps1")' in ACL_PS1
+ assert 'foreach ($mode in @("install", "setup", "update", "repair"))' in ACL_PS1
+ assert "icacls $entryLocked /deny" in ACL_PS1
+ assert "else { chmod 000 $entryLocked }" in ACL_PS1
+ for trap in (
+ "Invoke-WebRequest",
+ "Invoke-RestMethod",
+ "Start-Process",
+ "winget",
+ "python",
+ "uv",
+ "git",
+ "npm",
+ ):
+ assert f'function global:{trap} {{ Stop-EntrypointExpense "{trap}" }}' in ACL_PS1
+ for marker in (
+ "Checking system dependencies",
+ "frontend",
+ "Installing Python",
+ "Installing uv package manager",
+ "Creating virtual environment",
+ "Installing PyTorch",
+ "Installing unsloth",
+ "Unsloth Studio Installed",
+ ):
+ assert marker in ACL_PS1
+ assert ".unsloth-studio-owned" in ACL_PS1
+ assert "unsloth_install_manifest.json" in ACL_PS1
+
+
+def test_the_preflight_fails_the_install_with_the_shared_reason() -> None:
+ """The shared reason must reach the desktop app."""
+ body = _function_source(INSTALL_PS1, "Invoke-ManagedLlamaCppPreflight")
+ assert 'Write-PathAccessDenied -Path $dir -Label "llama.cpp install"' in body
+ assert "Nothing was installed." in body
+ call = INSTALL_PS1.split("$llamaPreflightFailure = Invoke-ManagedLlamaCppPreflight", 1)[1]
+ call = call.split("# ── Check winget ──", 1)[0]
+ assert "Exit-InstallFailure $llamaPreflightFailure" in call
+
+
+def test_the_preflight_cannot_be_the_thing_that_breaks_the_run() -> None:
+ """The early preflight must tolerate an unavailable profile or path."""
+ body = _function_source(INSTALL_PS1, "Invoke-ManagedLlamaCppPreflight")
+ guard = "if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { return $null }"
+ assert guard in body
+ assert body.index(guard) < body.index("Get-ManagedLlamaCppDir")
+ # Both probes swallow their own failures rather than terminating.
+ probe = _function_source(INSTALL_PS1, "Get-LlamaCppInstallReadState")
+ assert "-ErrorAction Stop" in probe and "catch" in probe
+ assert "Get-PathState" in probe
+
+
+def test_a_custom_studio_home_is_never_called_a_cache_we_own() -> None:
+ """Do not call an unreadable custom Studio home a managed cache."""
+ body = _function_source(INSTALL_PS1, "Invoke-ManagedLlamaCppPreflight")
+ # Use the same predicate for path selection and ownership wording.
+ assert "$homeIsCustom = Test-StudioHomeIsCustom" in body
+ assert "-OwnershipUnverified:$homeIsCustom" in body
+ assert (
+ 'Exit-PathAccessDenied -Path $LlamaCppDir -Label "llama.cpp install"'
+ " -OwnershipUnverified:$StudioHomeIsCustom" in SETUP_PS1
+ )
+
+
+def test_a_tree_the_user_pointed_at_is_never_called_a_cache_we_own() -> None:
+ """Preserve user-supplied wording when an override names the managed path."""
+ body = _function_source(INSTALL_PS1, "Invoke-ManagedLlamaCppPreflight")
+ assert "-UserSupplied:$userSupplied" in body
+ # Cover both the flag and its environment equivalent.
+ assert (
+ "$suppliedDir = if ($WithLlamaCppDir) { $WithLlamaCppDir }"
+ " else { $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR }" in body
+ )
+ # Compare canonical paths, including denied paths whose spelling differs.
+ assert "(Get-CanonicalDir -Path $suppliedDir) -eq (Get-CanonicalDir -Path $dir)" in body
+ assert "$LocalIsCanonical = ($ResolvedLocal -eq $LlamaCppDir)" in SETUP_PS1
+ assert (
+ "Exit-PathAccessDenied -Path $ResolvedLocal"
+ ' -Label "the UNSLOTH_LOCAL_LLAMA_CPP_DIR build" -UserSupplied' in SETUP_PS1
+ )
+
+
+def test_the_managed_path_rule_is_not_duplicated_in_the_installer() -> None:
+ """Keep managed path selection in one resolver."""
+ resolver = _function_source(INSTALL_PS1, "Get-ManagedLlamaCppDir")
+ assert 'Join-Path $env:USERPROFILE ".unsloth\\llama.cpp"' in resolver
+ assert 'Join-Path (Get-CanonicalDir -Path $StudioHome) "llama.cpp"' in resolver
+ assert INSTALL_PS1.count('Join-Path $StudioHome "llama.cpp"') == 0
+ assert INSTALL_PS1.count("$_llamaPath = Get-ManagedLlamaCppDir") == 1
+ # The resolver uses the single default-versus-custom predicate.
+ assert "if (-not (Test-StudioHomeIsCustom)) {" in resolver
+ assert "$legacyStudio" not in resolver
+ # Canonicalize both sides before comparing.
+ predicate = _function_source(INSTALL_PS1, "Test-StudioHomeIsCustom")
+ assert predicate.count("Get-CanonicalDir -Path") == 2
+ # Keep canonicalization in one helper.
+ canonicalizer = _function_source(INSTALL_PS1, "Get-CanonicalDir")
+ assert "Resolve-Path -LiteralPath $trimmedPath" in canonicalizer
+ # A denied path cannot resolve, so compare lexical full paths instead.
+ assert "GetUnresolvedProviderPathFromPSPath" in canonicalizer
+ assert "[System.IO.Path]::GetFullPath(" in canonicalizer
+ # One trim, after both branches: Resolve-Path keeps a trailing separator too.
+ assert canonicalizer.count("TrimEnd('\\', '/')") == 1
+ assert canonicalizer.index("Resolve-Path") < canonicalizer.index("TrimEnd")
+ assert INSTALL_PS1.count("Resolve-Path -LiteralPath $trimmedPath") == 1
+
+
+def test_both_entrypoints_resolve_and_reuse_the_same_managed_directory() -> None:
+ """Both entrypoints must resolve and reuse one managed path."""
+ assert '$LegacyStudioHome = Join-Path $env:USERPROFILE ".unsloth\\studio"' in SETUP_PS1
+ assert "$StudioHomeIsCustom = Test-StudioHomeIsCustom" in SETUP_PS1
+ assert SETUP_PS1.count("$LlamaCppDir = Get-ManagedLlamaCppDir") == 1
+ assert "$UnslothHome = Split-Path -Parent $LlamaCppDir" in SETUP_PS1
+ for name in (
+ "Get-CanonicalDir",
+ "Test-StudioHomeIsCustom",
+ "Get-ManagedLlamaCppDir",
+ ):
+ assert _normalized(_function_source(INSTALL_PS1, name)) == _normalized(
+ _function_source(SETUP_PS1, name)
+ )
+ phase = SETUP_PS1.split("PHASE 3.4", 1)[1].split("$NeedLlamaSourceBuild", 1)[0]
+ assert "resolved and preflighted before phase 1" in phase
+ assert "$LlamaCppDir =" not in phase
+
+
+def test_the_installer_never_repairs_permissions_by_itself() -> None:
+ """Print ACL repair commands but never run them."""
+ # Match direct, chained, captured, and delegated invocation forms.
+ invocation = re.compile(
+ r"(^|[&|;=]\s*|\(\s*|Start-Process\s+|Invoke-Expression\s+)(takeown|icacls)\b"
+ )
+ for text, label in ((INSTALL_PS1, "install.ps1"), (SETUP_PS1, "setup.ps1")):
+ for line in text.splitlines():
+ code = line.split("#", 1)[0].strip()
+ if "takeown" not in code and "icacls" not in code:
+ continue
+ assert not invocation.search(code), f"{label}: {line.strip()}"
+
+
+def test_setup_sh_reports_a_denied_default_home_cache() -> None:
+ """The POSIX prebuilt path must report a denied default cache."""
+ block = SETUP_SH.split('substep "installing prebuilt llama.cpp..."', 1)[1]
+ block = block.split("_PREBUILT_CMD=(", 1)[0]
+ # Listing, not just search: mode 111 passes cd and still breaks the installer.
+ assert 'if _studio_dir_unreadable "$LLAMA_CPP_DIR"; then' in block
+ assert '_path_access_denied "$LLAMA_CPP_DIR" "llama.cpp install"' in block
+ # Preserve the custom-home ownership guard's more cautious wording.
+ assert block.index("_assert_studio_owned_or_absent") < block.index("_studio_dir_unreadable")
diff --git a/tests/studio/install/test_setup_denied_install_tree.py b/tests/studio/install/test_setup_denied_install_tree.py
index a131f116ff3..506a82e1953 100644
--- a/tests/studio/install/test_setup_denied_install_tree.py
+++ b/tests/studio/install/test_setup_denied_install_tree.py
@@ -24,6 +24,26 @@ ROOT = Path(__file__).resolve().parents[3]
SETUP_PS1 = (ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
+def _denial_reporter() -> str:
+ """The body that owns the denial wording.
+
+ Split out of Exit-PathAccessDenied so install.ps1's preflight, which cannot
+ dot-source this file, can copy it; test_denied_llama_cpp_preflight.py compares
+ the copies.
+ """
+ assert "function Write-PathAccessDenied" in SETUP_PS1
+ return SETUP_PS1.split("function Write-PathAccessDenied", 1)[1].split("\nfunction ", 1)[0]
+
+
+def test_the_denial_exit_delegates_to_the_shared_reporter():
+ """Exit-PathAccessDenied stays the only stop, with no second copy of the wording."""
+ body = SETUP_PS1.split("function Exit-PathAccessDenied", 1)[1].split("\nfunction ", 1)[0]
+ assert "Exit-SetupFailure (Write-PathAccessDenied -Path $Path -Label $Label" in body
+ assert "-UserSupplied:$UserSupplied -OwnershipUnverified:$OwnershipUnverified)" in body
+ assert "takeown" not in body
+ assert "substep" not in body
+
+
def test_setup_defines_non_throwing_path_probes():
for name in ("Test-AccessDeniedError", "Get-PathState", "Test-PathQuiet"):
assert re.search(rf"^function {re.escape(name)} \{{", SETUP_PS1, re.M), name
@@ -34,17 +54,23 @@ def test_setup_defines_non_throwing_path_probes():
def test_prebuilt_metadata_probe_cannot_terminate_setup():
+ """The bare probe of this file is what threw. Get-LlamaCppInstallReadState now
+ decides denial one level up, so only presence is left here."""
assert "if (Test-Path $existingMetaPath)" not in SETUP_PS1
- assert "$existingMetaState = Get-PathState -Path $existingMetaPath -PathType Leaf" in SETUP_PS1
- assert '$existingMetaState -eq "Denied"' in SETUP_PS1
- assert '$existingMetaState -eq "Present"' in SETUP_PS1
+ assert "Test-PathQuiet -Path $existingMetaPath -PathType Leaf" in SETUP_PS1
+ assert "$llamaDirState = Get-LlamaCppInstallReadState -Path $LlamaCppDir" in SETUP_PS1
+ assert '$llamaDirState -eq "Denied"' in SETUP_PS1
+ assert (
+ 'Get-PathState -Path (Join-Path $Path "UNSLOTH_PREBUILT_INFO.json") -PathType Leaf'
+ in SETUP_PS1
+ )
def test_every_denial_route_reports_instead_of_proceeding():
"""An unreadable parent dir, metadata file, .git checkout, or ownership root
must all stop. Treating any of them as absent lets the caller replace or
delete a tree it cannot read."""
- assert "$llamaDirState = Get-PathState -Path $LlamaCppDir" in SETUP_PS1
+ assert "$llamaDirState = Get-LlamaCppInstallReadState -Path $LlamaCppDir" in SETUP_PS1
assert '$llamaDirState -eq "Denied"' in SETUP_PS1
assert '$llamaGitState = Get-PathState -Path (Join-Path $LlamaCppDir ".git")' in SETUP_PS1
assert '$llamaGitState -eq "Denied"' in SETUP_PS1
@@ -61,21 +87,21 @@ def test_every_denial_route_reports_instead_of_proceeding():
def test_denied_install_reports_an_actionable_failure():
- body = SETUP_PS1.split("function Exit-PathAccessDenied", 1)[1].split("\nfunction ", 1)[0]
+ body = _denial_reporter()
assert "cannot be read: access is denied" in body
# The reporter reinstalled to a different drive and hit the same line; the
# message has to say why that cannot help.
assert "reinstalling Unsloth Studio, to any drive, reuses it" in body
assert "delete or rename $Path" in body
assert "Controlled folder access" in body
- assert 'Exit-SetupFailure "Access denied reading the existing $Label' in body
+ assert 'return "Access denied reading the existing $Label' in body
assert "Reinstalling the app does not reset it." in body
def test_recovery_commands_are_separately_runnable():
"""On one line "then" is not a PowerShell separator: takeown would take the
rest as arguments and icacls would never run."""
- body = SETUP_PS1.split("function Exit-PathAccessDenied", 1)[1].split("\nfunction ", 1)[0]
+ body = _denial_reporter()
command_lines = [
line for line in body.splitlines() if "takeown /F" in line or "/reset /T" in line
]
@@ -88,6 +114,7 @@ def test_failure_reaches_the_desktop_ui():
desktop app prefers over its generic exit-code message."""
body = SETUP_PS1.split("function Exit-SetupFailure", 1)[1].split("\n}", 1)[0]
assert "UNSLOTH_TAURI_MODE" in body
+ assert "UNSLOTH_TAURI_UPDATE" in body
assert "[TAURI:ERROR] $singleLine" in body
@@ -206,7 +233,7 @@ def test_adoption_markers_keep_their_denial():
def test_user_supplied_paths_are_never_told_to_delete_themselves():
"""The managed advice ("delete it, Unsloth reinstalls it") is wrong for a tree
the user pointed us at with UNSLOTH_LOCAL_LLAMA_CPP_DIR."""
- body = SETUP_PS1.split("function Exit-PathAccessDenied", 1)[1].split("\nfunction ", 1)[0]
+ body = _denial_reporter()
assert "[switch]$UserSupplied" in body
user_branch = body.split("if ($UserSupplied) {", 1)[1].split("} else {", 1)[0]
assert "delete or rename" not in user_branch
@@ -239,7 +266,7 @@ def test_the_ownership_guard_never_advises_deleting_an_unverified_tree():
assert len(calls) >= 3, calls
for line in calls:
assert "-OwnershipUnverified" in line, line
- body = SETUP_PS1.split("function Exit-PathAccessDenied", 1)[1].split("\nfunction ", 1)[0]
+ body = _denial_reporter()
assert "[switch]$OwnershipUnverified" in body
branch = body.split("} elseif ($OwnershipUnverified) {", 1)[1].split("} else {", 1)[0]
assert "delete" not in branch.lower(), branch
diff --git a/tests/studio/test_path_probe_access_denied.ps1 b/tests/studio/test_path_probe_access_denied.ps1
index 58151e446c2..060640028d9 100644
--- a/tests/studio/test_path_probe_access_denied.ps1
+++ b/tests/studio/test_path_probe_access_denied.ps1
@@ -1,15 +1,5 @@
-# Regression test for setup.ps1 path probes on an ACL-denied install tree.
-#
-# Test-Path raises UnauthorizedAccessException instead of returning $false when
-# an ACL denies the probe, and setup.ps1 runs under "Stop", so the bare probe of
-# the llama.cpp prebuilt metadata aborted setup with a raw "Test-Path : Access
-# is denied" and exit code 1. ~/.unsloth/llama.cpp outlives an app reinstall, so
-# reinstalling, even to another drive, hit the same line again.
-#
-# The probes now go through Get-PathState / Test-PathQuiet, which never
-# terminate and keep "Denied" distinct from "Absent". This runs the real
-# functions against a genuinely unreadable directory (chmod on Unix, icacls deny
-# on Windows).
+# Regression tests for denied setup.ps1 install trees.
+# Run the real probes against chmod on POSIX and icacls deny on Windows.
$ErrorActionPreference = "Stop"
$script:failures = 0
function Check($name, $cond) {
@@ -22,8 +12,8 @@ $setupPath = [System.IO.Path]::Combine($repoRoot, "studio", "setup.ps1")
. ([System.IO.Path]::Combine($repoRoot, "tests", "studio_setup_ps1", "Get-FunctionSource.ps1"))
foreach ($fn in @("Test-AccessDeniedError", "Get-PathState", "Test-PathQuiet",
- "Get-PathDenialDetail", "Get-StudioAdoptableState",
- "Test-StudioOwnedAdoptable")) {
+ "Get-LlamaCppInstallReadState", "Get-PathDenialDetail",
+ "Get-StudioAdoptableState", "Test-StudioOwnedAdoptable")) {
$src = Get-FunctionSource -Path $setupPath -Name $fn
Check "setup.ps1 defines $fn" ($null -ne $src)
if ($src) { . ([scriptblock]::Create($src)) }
@@ -33,16 +23,30 @@ foreach ($fn in @("Test-AccessDeniedError", "Get-PathState", "Test-PathQuiet",
$setupText = Get-Content -Raw -LiteralPath $setupPath
Check "prebuilt metadata probe no longer uses a bare Test-Path" (
$setupText -notmatch '\n\s*if \(Test-Path \$existingMetaPath\)')
-Check "prebuilt metadata probe goes through Get-PathState" (
- $setupText -match '\$existingMetaState = Get-PathState -Path \$existingMetaPath -PathType Leaf')
+Check "prebuilt metadata probe goes through a non-throwing helper" (
+ $setupText -match 'Test-PathQuiet -Path \$existingMetaPath -PathType Leaf')
+# Get-LlamaCppInstallReadState decides denial before this marker probe.
Check "a denied llama.cpp install fails with an actionable message" (
- $setupText -match '\$existingMetaState -eq "Denied"' -and
- $setupText -match 'Exit-SetupFailure "Access denied reading the existing \$Label')
-# Every denial route reports instead of proceeding: an unreadable parent dir, an
-# unreadable metadata file, an unreadable .git checkout, and the ownership guard.
+ $setupText -match '\$llamaDirState -eq "Denied"' -and
+ $setupText -match 'return "Access denied reading the existing \$Label')
+# Shared reporting returns a reason instead of exiting directly.
+Check "Exit-PathAccessDenied delegates the wording to Write-PathAccessDenied" (
+ $setupText -match 'Exit-SetupFailure \(Write-PathAccessDenied -Path \$Path -Label \$Label')
+# Every denial route must report instead of proceeding.
Check "the prebuilt phase stops on a denied llama.cpp dir" (
- $setupText -match '\$llamaDirState = Get-PathState -Path \$LlamaCppDir' -and
+ $setupText -match '\$llamaDirState = Get-LlamaCppInstallReadState -Path \$LlamaCppDir' -and
$setupText -match '\$llamaDirState -eq "Denied"')
+$setupPreflightCall = '$llamaPreflightFailure = Invoke-ManagedLlamaCppPreflight'
+$setupPreflightAt = $setupText.IndexOf($setupPreflightCall)
+$setupPhaseOneAt = $setupText.IndexOf('PHASE 1: System-level prerequisites')
+Check "direct setup/update preflight runs exactly once before phase 1" (
+ $setupPreflightAt -ge 0 -and
+ $setupPreflightAt -lt $setupPhaseOneAt -and
+ $setupText.IndexOf($setupPreflightCall, $setupPreflightAt + 1) -eq -1)
+Check "direct setup/update resolves one managed path and reuses it in phase 3.4" (
+ $setupText -match '\$LlamaCppDir = Get-ManagedLlamaCppDir' -and
+ $setupText -match '\$UnslothHome = Split-Path -Parent \$LlamaCppDir' -and
+ $setupText -notmatch '\$LlamaCppDir = Join-Path \$UnslothHome')
Check "the source-build .git probe stops on a denied checkout" (
$setupText -match '\$llamaGitState = Get-PathState -Path \(Join-Path \$LlamaCppDir "\.git"\)' -and
$setupText -match '\$llamaGitState -eq "Denied"')
@@ -80,12 +84,14 @@ try {
Check "readable install is adoptable" (Test-StudioOwnedAdoptable $locked)
Check "absent path reports Absent" (
(Get-PathState -Path (Join-Path $root "missing.json") -PathType Leaf) -eq "Absent")
+ Check "a readable llama.cpp install reads Readable" (
+ (Get-LlamaCppInstallReadState -Path $locked) -eq "Readable")
+ Check "a missing llama.cpp install reads Absent" (
+ (Get-LlamaCppInstallReadState -Path (Join-Path $root "missing")) -eq "Absent")
Set-Denied $true
- # Negative control AND environment gate: the old unguarded form must blow up
- # here, otherwise this host cannot produce a denial (root / admin bypass)
- # and the assertions below would pass vacuously.
+ # Require a real denial so the assertions cannot pass vacuously as root.
$oldFormTerminated = $false
try { $null = Test-Path $meta } catch { $oldFormTerminated = $true }
@@ -110,16 +116,76 @@ try {
try { $adoptable = Test-StudioOwnedAdoptable $locked } catch { $threw = $true }
Check "Test-StudioOwnedAdoptable does not terminate on a denied tree" (-not $threw)
Check "Test-StudioOwnedAdoptable cannot adopt an unreadable tree" ($adoptable -eq $false)
+
+ # This is the state the early installer preflight must recognize.
+ $treeState = $null
+ $threw = $false
+ try { $treeState = Get-LlamaCppInstallReadState -Path $locked } catch { $threw = $true }
+ Check "Get-LlamaCppInstallReadState does not terminate on a denied tree" (-not $threw)
+ Check "Get-LlamaCppInstallReadState reports Denied" ($treeState -eq "Denied")
}
} finally {
Set-Denied $false
Remove-Item -Recurse -Force -LiteralPath $root -ErrorAction SilentlyContinue
}
+# ── A denied tree with NO metadata inside it ──
+# A missing child of a denied Windows dir looks absent, so the listing must catch
+# it. POSIX mode 111 is the same shape.
+$bareRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_bare_" + [guid]::NewGuid().ToString("N"))
+$bareLocked = Join-Path $bareRoot "llama.cpp"
+New-Item -ItemType Directory -Force -Path (Join-Path $bareLocked "build") | Out-Null
+$bareModes = if ($onWindows) { @("acl") } else { @("000", "111") }
+foreach ($mode in $bareModes) {
+ if ($mode -eq "acl") { icacls $bareLocked /deny "$env:USERDOMAIN\${env:USERNAME}:(OI)(CI)(RX)" *>$null }
+ else { chmod $mode $bareLocked }
+ try {
+ # Ensure the listing, not the absent marker, decides this case.
+ $metaProbe = Get-PathState -Path (Join-Path $bareLocked "UNSLOTH_PREBUILT_INFO.json") -PathType Leaf
+ $state = $null
+ $threw = $false
+ try { $state = Get-LlamaCppInstallReadState -Path $bareLocked } catch { $threw = $true }
+ Check "a denied tree with no metadata does not terminate the probe ($mode)" (-not $threw)
+ if ($metaProbe -eq "Absent") {
+ Check "the listing catches a denied tree the metadata probe calls absent ($mode)" (
+ $state -eq "Denied")
+ } else {
+ Check "a denied tree with no metadata still reports Denied ($mode)" ($state -eq "Denied")
+ }
+ } finally {
+ if ($mode -eq "acl") { icacls $bareLocked /remove:d "$env:USERDOMAIN\$env:USERNAME" *>$null }
+ else { chmod 755 $bareLocked }
+ }
+}
+Remove-Item -Recurse -Force -LiteralPath $bareRoot -ErrorAction SilentlyContinue
+
+# ── A readable marker inside a tree that cannot be listed ──
+# What a marker-only probe would call Readable. Windows denies ReadData; POSIX
+# mode 111 keeps the named child stat-able.
+$listRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_list_" + [guid]::NewGuid().ToString("N"))
+$listLocked = Join-Path $listRoot "llama.cpp"
+New-Item -ItemType Directory -Force -Path $listLocked | Out-Null
+Set-Content -LiteralPath (Join-Path $listLocked "UNSLOTH_PREBUILT_INFO.json") -Value '{"release_tag":"app-1"}'
+if ($onWindows) { icacls $listLocked /deny "$env:USERDOMAIN\${env:USERNAME}:(RD)" *>$null }
+else { chmod 111 $listLocked }
+try {
+ $markerReadable = ((Get-PathState -Path (Join-Path $listLocked "UNSLOTH_PREBUILT_INFO.json") -PathType Leaf) -eq "Present")
+ $listDenied = $false
+ try { $null = Get-ChildItem -LiteralPath $listLocked -Force -ErrorAction Stop } catch { $listDenied = $true }
+ if ($markerReadable -and $listDenied) {
+ Check "a readable marker does not excuse an unlistable tree" (
+ (Get-LlamaCppInstallReadState -Path $listLocked) -eq "Denied")
+ } else {
+ Write-Host " SKIP host cannot deny listing while keeping the marker readable"
+ }
+} finally {
+ if ($onWindows) { icacls $listLocked /remove:d "$env:USERDOMAIN\$env:USERNAME" *>$null }
+ else { chmod 755 $listLocked }
+ Remove-Item -Recurse -Force -LiteralPath $listRoot -ErrorAction SilentlyContinue
+}
+
# ── Test-Path parity: the regression-safety invariant ──
-# Wherever the old bare probe returned a value instead of throwing, Get-PathState
-# must agree. Denied may only appear where the old probe threw, so no path that
-# used to work can take a different branch now.
+# Preserve every non-throwing Test-Path result; only thrown probes may be denied.
$parityRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_par_" + [guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Force -Path (Join-Path $parityRoot "tree/sub") | Out-Null
Set-Content -LiteralPath (Join-Path $parityRoot "tree/UNSLOTH_PREBUILT_INFO.json") -Value "{}"
@@ -144,9 +210,8 @@ Check "Get-PathState matches bare Test-Path on every non-throwing probe ($probed
Check "Denied never appears where the old probe did not throw" ($deniedWithoutThrow -eq 0)
# ── A denied marker FILE under a readable directory ──
-# Windows only: POSIX keeps a mode-000 file stat-able, so this state cannot be
-# built on Unix. Collapsing it to "No" made the ownership guard report an
-# Unsloth tree as an unrelated directory instead of a permissions problem.
+# Windows only (POSIX keeps mode-000 files stat-able): a denied marker must not be
+# mistaken for an unrelated directory.
$adoptRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_adopt_" + [guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Force -Path $adoptRoot | Out-Null
$adoptMarker = Join-Path $adoptRoot "UNSLOTH_PREBUILT_INFO.json"
@@ -172,8 +237,7 @@ Remove-Item -Recurse -Force -LiteralPath $adoptRoot -ErrorAction SilentlyContinu
Check "a missing marker reports No" ((Get-StudioAdoptableState -Path ([System.IO.Path]::GetTempPath())) -eq "No")
# ── The reporting path must not itself fail ──
-# Get-PathDenialDetail runs while a failure is being reported, so a null or empty
-# path must not replace the actionable message with a binding exception.
+# Reporting must tolerate an empty path without masking the original failure.
foreach ($edge in @($null, "", " ")) {
$edgeOk = $true
try { $null = Get-PathDenialDetail -Path $edge } catch { $edgeOk = $false }
@@ -181,19 +245,20 @@ foreach ($edge in @($null, "", " ")) {
}
# ── The desktop app must receive the reason, not just "exit code 1" ──
-# The real Exit-PathAccessDenied with the real Exit-SetupFailure in Tauri mode:
-# install.rs prefers a [TAURI:ERROR] line over its generic exit-code message, so
-# this is what the user reads.
+# Exercise the real Tauri failure path, which prefers [TAURI:ERROR] details.
$exitDeniedSrc = Get-FunctionSource -Path $setupPath -Name Exit-PathAccessDenied
+$writeDeniedSrc = Get-FunctionSource -Path $setupPath -Name Write-PathAccessDenied
$exitSetupSrc = Get-FunctionSource -Path $setupPath -Name Exit-SetupFailure
Check "setup.ps1 defines Exit-PathAccessDenied" ($null -ne $exitDeniedSrc)
-if ($exitDeniedSrc) {
+Check "setup.ps1 defines Write-PathAccessDenied" ($null -ne $writeDeniedSrc)
+if ($exitDeniedSrc -and $writeDeniedSrc) {
$harness = @"
`$ErrorActionPreference = "Stop"
function step { param([string]`$Label, [string]`$Value, [string]`$Color = "Green") Write-Host " `$Label `$Value" }
function substep { param([string]`$Message, [string]`$Color = "DarkGray") Write-Host " `$Message" }
function Get-PathDenialDetail { param([string]`$Path) return "" }
$exitSetupSrc
+$writeDeniedSrc
$exitDeniedSrc
Exit-PathAccessDenied -Path "C:\Users\test\.unsloth\llama.cpp" -Label "llama.cpp install"
Write-Host "REACHED_UNREACHABLE"
@@ -218,8 +283,7 @@ Write-Host "REACHED_UNREACHABLE"
$out -match '\[TAURI:ERROR\] Access denied reading the existing llama\.cpp install')
Check "the reason names the folder to remove" ($out -match [regex]::Escape('C:\Users\test\.unsloth\llama.cpp'))
Check "the reason says a reinstall will not help" ($out -match 'Reinstalling the app does not reset it')
- # takeown and icacls must be copy-pasteable. On one line, "then" is not a
- # PowerShell separator and takeown would swallow the rest as arguments.
+ # Keep takeown and icacls on separate copy-pasteable lines.
$takeownLines = @($out -split "`r?`n" | Where-Object { $_ -match 'takeown /F' })
Check "takeown is printed on its own line" ($takeownLines.Count -eq 1)
Check "icacls is not appended to the takeown line" (
@@ -228,6 +292,51 @@ Write-Host "REACHED_UNREACHABLE"
@($out -split "`r?`n" | Where-Object { $_ -match 'icacls .* /reset /T' }).Count -eq 1)
}
+# ── The reporter must return one string, not a pipeline ──
+# The shared reporter must return one value even when Tauri stdout mirroring runs.
+$mirrorFns = @("Get-StudioAnsi", "Write-StudioStdoutMirror", "step", "substep", "Write-PathAccessDenied")
+$mirrorSrc = @()
+foreach ($fn in $mirrorFns) {
+ $src = Get-FunctionSource -Path $setupPath -Name $fn
+ Check "setup.ps1 defines $fn" ($null -ne $src)
+ if ($src) { $mirrorSrc += $src }
+}
+if ($mirrorSrc.Count -eq $mirrorFns.Count) {
+ $mirrorHarness = @"
+`$ErrorActionPreference = "Stop"
+function Get-PathDenialDetail { param([string]`$Path) return "" }
+$($mirrorSrc -join "`n")
+`$script:StudioVtOk = `$false
+Add-Content -LiteralPath `$args[0] -Value "REDIRECTED=`$([Console]::IsOutputRedirected)"
+foreach (`$mode in @(@{}, @{OwnershipUnverified=`$true}, @{UserSupplied=`$true})) {
+ `$out = @(Write-PathAccessDenied -Path "C:\Users\t\.unsloth\llama.cpp" -Label "llama.cpp install" @mode)
+ Add-Content -LiteralPath `$args[0] -Value "EMITTED=`$(`$out.Count)/`$(`$out[0].GetType().Name)"
+}
+"@
+ $mirrorFile = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_mir_" + [guid]::NewGuid().ToString("N") + ".ps1")
+ Set-Content -LiteralPath $mirrorFile -Value $mirrorHarness -Encoding utf8
+ $pwshExe3 = (Get-Command pwsh -ErrorAction SilentlyContinue).Source
+ if (-not $pwshExe3) { $pwshExe3 = (Get-Command powershell).Source }
+ $mirrorOutFile = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_mir_" + [guid]::NewGuid().ToString("N") + ".txt")
+ $mirrorResFile = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_res_" + [guid]::NewGuid().ToString("N") + ".txt")
+ $lines = @()
+ try {
+ # Redirect stdout to activate the mirror; return verdicts in another file.
+ & $pwshExe3 -NoProfile -File $mirrorFile $mirrorResFile *> $mirrorOutFile
+ if (Test-Path -LiteralPath $mirrorResFile) { $lines = @(Get-Content -LiteralPath $mirrorResFile) }
+ } finally {
+ Remove-Item -LiteralPath $mirrorFile -ErrorAction SilentlyContinue
+ Remove-Item -LiteralPath $mirrorOutFile -ErrorAction SilentlyContinue
+ Remove-Item -LiteralPath $mirrorResFile -ErrorAction SilentlyContinue
+ }
+ $emitted = @($lines | Where-Object { $_ -match "^EMITTED=" })
+ Check "the reporter ran with its stdout redirected, so the mirror is live" (
+ $lines -contains "REDIRECTED=True")
+ Check "the reporter ran in all three modes" ($emitted.Count -eq 3)
+ Check "each mode returns exactly one string, not a pipeline" (
+ $emitted.Count -eq 3 -and @($emitted | Where-Object { $_ -ne "EMITTED=1/String" }).Count -eq 0)
+}
+
# ── Denial classification ──
Check "UnauthorizedAccessException classifies as access denied" (
Test-AccessDeniedError ([System.UnauthorizedAccessException]::new("denied")))
@@ -237,8 +346,7 @@ Check "an unrelated exception does not classify as access denied" (
-not (Test-AccessDeniedError ([System.IO.FileNotFoundException]::new("missing"))))
# -- Assert-StudioOwnedOrAbsent -NonFatal, run for real --
-# whisper.cpp promises "failure is never fatal", so a denied tree there is handed
-# back instead of exiting the run. Everything else about the guard stays fatal.
+# Whisper denial remains nonfatal while other ownership failures remain fatal.
$assertSrc = Get-FunctionSource -Path $setupPath -Name Assert-StudioOwnedOrAbsent
$markSrc = Get-FunctionSource -Path $setupPath -Name Mark-StudioOwned
Check "setup.ps1 defines Assert-StudioOwnedOrAbsent" ($null -ne $assertSrc)
@@ -258,9 +366,7 @@ if ($assertSrc -and $markSrc) {
$nfUnowned = Join-Path $nfRoot "unowned"
$nfInner = Join-Path $nfDenied "inner"
$nfMarker = Join-Path $nfDenied $StudioOwnedMarker
- # Populate before locking: Windows returns $false for a MISSING child of a
- # denied directory instead of throwing, so a probe target that does not exist
- # makes the negative control read as "this host cannot deny".
+ # Populate first so the denial negative control probes an existing child.
New-Item -ItemType Directory -Force -Path $nfInner | Out-Null
Set-Content -LiteralPath $nfMarker -Value ""
New-Item -ItemType Directory -Force -Path $nfUnowned | Out-Null
@@ -294,8 +400,7 @@ if ($assertSrc -and $markSrc) {
try { $null = Assert-StudioOwnedOrAbsent -Path $nfDenied -Label "whisper.cpp install" } catch { $threw = $true }
Check "without -NonFatal a denied tree still stops setup" $threw
- # A locked directory still probes Present from its readable parent, so
- # the case above only covers the marker read; lock the parent instead.
+ # Lock the parent to cover a denied directory probe too.
$out = $null
$threw = $false
try { $out = @(Assert-StudioOwnedOrAbsent -Path $nfInner -Label "whisper.cpp install" -NonFatal) }
@@ -303,13 +408,8 @@ if ($assertSrc -and $markSrc) {
Check "-NonFatal hands back a tree whose parent is unreadable" (
-not $threw -and $out.Count -eq 1 -and $out[0] -eq "Denied")
- # The fresh-custom-home case: no marker was ever written. Windows
- # reports a MISSING child of a denied directory as Absent, so there the
- # adoptable-state read catches this, not the marker probe. Either route
- # is fine; anything other than Denied is not.
- # chmod 000 blocks the child probes outright; chmod 111 allows stat of a
- # named child but forbids listing, matching Windows, and is the only
- # shape reaching the directory listing in Get-StudioAdoptableState.
+ # A fresh custom home with no marker. Mode 111 allows child stat but
+ # denies listing, matching Windows here.
$bareWho = "$env:USERDOMAIN\$env:USERNAME"
$bareModes = if ($onWindows) { @("acl") } else { @("000", "111") }
foreach ($mode in $bareModes) {
@@ -340,6 +440,243 @@ if ($assertSrc -and $markSrc) {
}
}
+# ── install.ps1's preflight, run for real ──
+# Its copied helpers run in a child so they do not shadow setup.ps1's, and must
+# return actionable guidance for a real denied tree.
+$installPath = [System.IO.Path]::Combine($repoRoot, "install.ps1")
+$preflightFns = @("Test-AccessDeniedError", "Get-PathState", "Get-LlamaCppInstallReadState",
+ "Get-PathDenialDetail", "Write-PathAccessDenied", "Get-CanonicalDir",
+ "Test-StudioHomeIsCustom", "Get-ManagedLlamaCppDir",
+ "Invoke-ManagedLlamaCppPreflight")
+$preflightSrc = @()
+foreach ($fn in $preflightFns) {
+ $src = Get-FunctionSource -Path $installPath -Name $fn
+ Check "install.ps1 defines $fn" ($null -ne $src)
+ if ($src) { $preflightSrc += $src }
+}
+if ($preflightSrc.Count -eq $preflightFns.Count) {
+ $preflightHarness = @"
+`$ErrorActionPreference = "Stop"
+function step { param([string]`$Label, [string]`$Value, [string]`$Color = "Green") Write-Host " `$Label `$Value" }
+function substep { param([string]`$Message, [string]`$Color = "DarkGray") Write-Host " `$Message" }
+$($preflightSrc -join "`n")
+`$env:USERPROFILE = `$args[0]
+`$onWindows = (`$args[1] -eq "win")
+`$StudioHome = Join-Path `$env:USERPROFILE ".unsloth\studio"
+`$dir = Join-Path `$env:USERPROFILE ".unsloth\llama.cpp"
+New-Item -ItemType Directory -Force -Path `$StudioHome | Out-Null
+New-Item -ItemType Directory -Force -Path (Join-Path `$dir "build") | Out-Null
+Set-Content -LiteralPath (Join-Path `$dir "UNSLOTH_PREBUILT_INFO.json") -Value '{"release_tag":"app-1"}'
+Write-Host "RESOLVED_DIR: `$(Get-ManagedLlamaCppDir)"
+`$readable = Invoke-ManagedLlamaCppPreflight
+Write-Host "READABLE_VERDICT: `$(if (`$null -eq `$readable) { "continue" } else { "stop" })"
+if (`$onWindows) { icacls `$dir /deny "`$env:USERDOMAIN\`${env:USERNAME}:(OI)(CI)(RX)" *>`$null }
+else { chmod 000 `$dir }
+`$oldFormTerminated = `$false
+try { `$null = Test-Path (Join-Path `$dir "UNSLOTH_PREBUILT_INFO.json") } catch { `$oldFormTerminated = `$true }
+Write-Host "CAN_DENY: `$oldFormTerminated"
+# Both override forms must switch to user-supplied wording.
+if (`$args[2] -eq "supplied") { `$WithLlamaCppDir = `$dir }
+if (`$args[2] -eq "env") { `$env:UNSLOTH_LOCAL_LLAMA_CPP_DIR = `$dir }
+`$denied = Invoke-ManagedLlamaCppPreflight
+Write-Host "DENIED_VERDICT: `$(if (`$null -eq `$denied) { "continue" } else { "stop" })"
+Write-Host "DENIED_REASON: `$denied"
+if (`$onWindows) { icacls `$dir /remove:d "`$env:USERDOMAIN\`$env:USERNAME" *>`$null }
+else { chmod 755 `$dir }
+"@
+ $preflightFile = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_pre_" + [guid]::NewGuid().ToString("N") + ".ps1")
+ Set-Content -LiteralPath $preflightFile -Value $preflightHarness -Encoding utf8
+ $pwshExe2 = (Get-Command pwsh -ErrorAction SilentlyContinue).Source
+ if (-not $pwshExe2) { $pwshExe2 = (Get-Command powershell).Source }
+ # Use one child per mode so command-line counts remain unambiguous.
+ $preflightRuns = @{}
+ $preflightHome = ""
+ try {
+ foreach ($mode in @("managed", "supplied", "env")) {
+ $runHome = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_home_" + [guid]::NewGuid().ToString("N"))
+ New-Item -ItemType Directory -Force -Path $runHome | Out-Null
+ if ($mode -eq "managed") { $preflightHome = $runHome }
+ try {
+ $preflightRuns[$mode] = & $pwshExe2 -NoProfile -File $preflightFile $runHome $(if ($onWindows) { "win" } else { "posix" }) $mode 2>&1 | Out-String
+ } finally {
+ Remove-Item -Recurse -Force -LiteralPath $runHome -ErrorAction SilentlyContinue
+ }
+ }
+ } finally {
+ Remove-Item -LiteralPath $preflightFile -ErrorAction SilentlyContinue
+ }
+ $out = $preflightRuns["managed"]
+ # The path it decides about, not a path the test computed for it.
+ $expectedDir = Join-Path $preflightHome ".unsloth\llama.cpp"
+ Check "the preflight resolves the managed llama.cpp dir under the profile" (
+ $out -match ("RESOLVED_DIR: " + [regex]::Escape($expectedDir)))
+ Check "a readable llama.cpp cache does not stop the install" ($out -match "READABLE_VERDICT: continue")
+ if ($out -notmatch "CAN_DENY: True") {
+ Write-Host " SKIP cannot deny access on this host (running as root/admin?) -- preflight denial checks skipped" -ForegroundColor Yellow
+ } else {
+ Check "an unreadable llama.cpp cache stops the install" ($out -match "DENIED_VERDICT: stop")
+ Check "the preflight reason names the folder" (
+ $out -match ("DENIED_REASON: .*" + [regex]::Escape($expectedDir)))
+ Check "the preflight reason says a reinstall will not help" (
+ $out -match "Reinstalling the app does not reset it")
+ Check "the preflight says nothing was installed" ($out -match "Nothing was installed\.")
+ Check "the preflight prints the takeown command on its own line" (
+ @($out -split "`r?`n" | Where-Object { $_ -match 'takeown /F' -and $_ -notmatch '^DENIED_REASON' }).Count -eq 1)
+ Check "the preflight prints the icacls command on its own line" (
+ @($out -split "`r?`n" | Where-Object { $_ -match 'icacls .* /reset /T' }).Count -eq 1)
+ Check "the preflight says the download has not happened yet" (
+ $out -match "nothing has been downloaded or installed")
+ # Guidance may print ACL repair commands but must never run them.
+ Check "the preflight does not run takeown or icacls itself" (
+ $out -notmatch "SUCCESS: The file \(or folder\)" -and
+ $out -notmatch "processed file:")
+
+ # Overrides may name the managed location itself; never call it disposable.
+ foreach ($mode in @("supplied", "env")) {
+ $supplied = $preflightRuns[$mode]
+ Check "a tree the user named ($mode) still stops the install" (
+ $supplied -match "DENIED_VERDICT: stop")
+ Check "a tree the user named ($mode) is not called a cache we own" (
+ $supplied -match "DENIED_REASON: .*point UNSLOTH_LOCAL_LLAMA_CPP_DIR at a readable build" -and
+ $supplied -notmatch "DENIED_REASON: .*Delete or rename")
+ }
+ Check "the managed cache is still called one" (
+ $out -match "DENIED_REASON: .*Delete or rename that folder")
+ }
+}
+
+# ── Complete install/setup/update entrypoints ──
+# Run every public entrypoint with network and expensive work trapped. Windows CI
+# uses real ACLs; POSIX chmod is the local equivalent.
+$entrypointHarness = @'
+$ErrorActionPreference = "Stop"
+$repoRoot = $args[0]
+$testHome = $args[1]
+$mode = $args[2]
+$env:USERPROFILE = $testHome
+$env:HOME = $testHome
+$env:UNSLOTH_SKIP_AUTOSTART = "1"
+Remove-Item Env:UNSLOTH_TAURI_MODE -ErrorAction SilentlyContinue
+Remove-Item Env:UNSLOTH_TAURI_UPDATE -ErrorAction SilentlyContinue
+Remove-Item Env:UNSLOTH_STUDIO_HOME -ErrorAction SilentlyContinue
+Remove-Item Env:STUDIO_HOME -ErrorAction SilentlyContinue
+Remove-Item Env:UNSLOTH_LOCAL_LLAMA_CPP_DIR -ErrorAction SilentlyContinue
+
+function Stop-EntrypointExpense {
+ param([string]$Name)
+ Write-Host "[TEST:EXPENSIVE] $Name"
+ throw "entrypoint reached expensive operation: $Name"
+}
+function global:Invoke-WebRequest { Stop-EntrypointExpense "Invoke-WebRequest" }
+function global:Invoke-RestMethod { Stop-EntrypointExpense "Invoke-RestMethod" }
+function global:Invoke-Expression { Stop-EntrypointExpense "Invoke-Expression" }
+function global:Start-Process { Stop-EntrypointExpense "Start-Process" }
+function global:Expand-Archive { Stop-EntrypointExpense "Expand-Archive" }
+function global:winget { Stop-EntrypointExpense "winget" }
+function global:python { Stop-EntrypointExpense "python" }
+function global:python3 { Stop-EntrypointExpense "python3" }
+function global:py { Stop-EntrypointExpense "py" }
+function global:uv { Stop-EntrypointExpense "uv" }
+function global:pip { Stop-EntrypointExpense "pip" }
+function global:nvidia-smi { Stop-EntrypointExpense "nvidia-smi" }
+function global:amd-smi { Stop-EntrypointExpense "amd-smi" }
+function global:rocm-smi { Stop-EntrypointExpense "rocm-smi" }
+function global:git { Stop-EntrypointExpense "git" }
+function global:cmake { Stop-EntrypointExpense "cmake" }
+function global:node { Stop-EntrypointExpense "node" }
+function global:npm { Stop-EntrypointExpense "npm" }
+function global:bun { Stop-EntrypointExpense "bun" }
+function global:cmd { Stop-EntrypointExpense "cmd" }
+
+if ($mode -eq "install") {
+ & (Join-Path $repoRoot "install.ps1") --tauri
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+} else {
+ if ($mode -in @("update", "repair")) {
+ $env:STUDIO_PACKAGE_NAME = "unsloth"
+ $env:STUDIO_LOCAL_INSTALL = "0"
+ }
+ if ($mode -eq "repair") {
+ $env:UNSLOTH_TAURI_UPDATE = "1"
+ $env:SKIP_STUDIO_FRONTEND = "1"
+ } else {
+ Remove-Item Env:UNSLOTH_TAURI_UPDATE -ErrorAction SilentlyContinue
+ Remove-Item Env:SKIP_STUDIO_FRONTEND -ErrorAction SilentlyContinue
+ }
+ if ($mode -eq "setup") {
+ Remove-Item Env:STUDIO_PACKAGE_NAME -ErrorAction SilentlyContinue
+ Remove-Item Env:STUDIO_LOCAL_INSTALL -ErrorAction SilentlyContinue
+ }
+ & (Join-Path $repoRoot "studio/setup.ps1")
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+}
+Write-Host "[TEST:ENTRYPOINT_RETURNED]"
+'@
+$entrypointFile = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_entry_" + [guid]::NewGuid().ToString("N") + ".ps1")
+Set-Content -LiteralPath $entrypointFile -Value $entrypointHarness -Encoding utf8
+$pwshEntrypoint = (Get-Command pwsh -ErrorAction SilentlyContinue).Source
+if (-not $pwshEntrypoint) { $pwshEntrypoint = (Get-Command powershell).Source }
+
+try {
+ foreach ($mode in @("install", "setup", "update", "repair")) {
+ $entryHome = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_whole_" + [guid]::NewGuid().ToString("N"))
+ $entryLocked = Join-Path $entryHome ".unsloth\llama.cpp"
+ New-Item -ItemType Directory -Force -Path (Join-Path $entryLocked "build") | Out-Null
+ Set-Content -LiteralPath (Join-Path $entryLocked "UNSLOTH_PREBUILT_INFO.json") -Value '{"release_tag":"app-1"}'
+ $entryWho = "$env:USERDOMAIN\$env:USERNAME"
+ if ($onWindows) { icacls $entryLocked /deny "${entryWho}:(OI)(CI)(RX)" *>$null }
+ else { chmod 000 $entryLocked }
+ $canDenyEntrypoint = $false
+ try {
+ try { $null = Test-Path (Join-Path $entryLocked "UNSLOTH_PREBUILT_INFO.json") }
+ catch { $canDenyEntrypoint = $true }
+ if (-not $canDenyEntrypoint) {
+ Write-Host " SKIP cannot deny access on this host -- whole $mode entrypoint skipped" -ForegroundColor Yellow
+ } else {
+ $entryOutput = & $pwshEntrypoint -NoProfile -File $entrypointFile $repoRoot $entryHome $mode 2>&1 | Out-String
+ $entryExit = $LASTEXITCODE
+ Check "whole $mode entrypoint fails on the denied managed cache" ($entryExit -ne 0)
+ Check "whole $mode entrypoint reports the denied managed path" (
+ $entryOutput -match "access is denied" -and
+ $entryOutput -match [regex]::Escape($entryLocked))
+ Check "whole $mode entrypoint prints the actionable recovery reason" (
+ $entryOutput -match "This folder lives outside the app, so reinstalling Unsloth Studio, to any drive, reuses it and fails the same way")
+ if ($mode -in @("install", "repair")) {
+ $tauriTag = if ($mode -eq "install") { "[TAURI:ERROR_DEFAULT]" } else { "[TAURI:ERROR]" }
+ Check "whole $mode entrypoint hands the actionable reason to Tauri" (
+ $entryOutput.Contains($tauriTag))
+ }
+ Check "whole $mode entrypoint never reaches a trapped expensive operation" (
+ $entryOutput -notmatch '\[TEST:EXPENSIVE\]')
+ Check "whole $mode entrypoint stops before dependency, frontend, Python, uv, venv, and PyTorch markers" (
+ $entryOutput -notmatch 'Checking system dependencies' -and
+ $entryOutput -notmatch '(?im)^\s*frontend\s' -and
+ $entryOutput -notmatch 'downloading Python|Installing Python|Python found:' -and
+ $entryOutput -notmatch 'Installing uv package manager|installing uv package manager' -and
+ $entryOutput -notmatch 'Creating virtual environment|setting up Python environment' -and
+ $entryOutput -notmatch 'Installing PyTorch|installing PyTorch' -and
+ $entryOutput -notmatch '\[TAURI:STEP\] (Installing unsloth|Running studio setup)' -and
+ $entryOutput -notmatch '(?im)^\s*(Installing unsloth|Unsloth Studio Installed)' -and
+ $entryOutput -notmatch '\[TEST:ENTRYPOINT_RETURNED\]')
+ }
+ } finally {
+ if ($onWindows) { icacls $entryLocked /remove:d "$entryWho" *>$null }
+ else { chmod 755 $entryLocked }
+ }
+
+ $installMarkers = @(
+ Get-ChildItem -LiteralPath $entryHome -Recurse -Force -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -in @(".unsloth-studio-owned", ".unsloth-no-torch", "unsloth_install_manifest.json") }
+ )
+ Check "whole $mode denial leaves no venv or install marker" (
+ -not (Test-Path -LiteralPath (Join-Path $entryHome ".unsloth\studio\unsloth_studio")) -and
+ $installMarkers.Count -eq 0)
+ Remove-Item -Recurse -Force -LiteralPath $entryHome -ErrorAction SilentlyContinue
+ }
+} finally {
+ Remove-Item -LiteralPath $entrypointFile -ErrorAction SilentlyContinue
+}
+
if ($script:failures -gt 0) {
Write-Host "$($script:failures) check(s) failed" -ForegroundColor Red
exit 1