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.

Make install.ps1 work with the user's PowerShell profile loaded (#8161)

Daniel Hana151ac875c11
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.yml
index 8fa8a36ce69..df3891b9ba1 100644
--- a/.github/workflows/cross-platform-parity-ci.yml
+++ b/.github/workflows/cross-platform-parity-ci.yml
@@ -33,9 +33,13 @@ on:
- 'install.sh'
- 'install.ps1'
- 'unsloth_cli/__init__.py'
+ # test_installer_profile_hardening.py asserts this module directly (unconditional
+ # -NoProfile, the proxy handoff), so a change to it has to run here.
+ - 'unsloth_cli/commands/studio.py'
- 'tests/test_installer_skip_autostart.py'
- 'tests/test_installer_system32_guard.py'
- 'tests/test_installer_interactive_prompts.py'
+ - 'tests/test_installer_profile_hardening.py'
- 'install*.sh'
- 'install*.ps1'
- 'install*.bat'
@@ -77,9 +81,13 @@ on:
- 'install.sh'
- 'install.ps1'
- 'unsloth_cli/__init__.py'
+ # test_installer_profile_hardening.py asserts this module directly (unconditional
+ # -NoProfile, the proxy handoff), so a change to it has to run here.
+ - 'unsloth_cli/commands/studio.py'
- 'tests/test_installer_skip_autostart.py'
- 'tests/test_installer_system32_guard.py'
- 'tests/test_installer_interactive_prompts.py'
+ - 'tests/test_installer_profile_hardening.py'
- 'install*.sh'
- 'install*.ps1'
- 'install*.bat'
@@ -167,7 +175,12 @@ jobs:
with:
python-version: '3.12'
cache: 'pip'
- - run: python -m pip install -U pip pytest
+ # test_installer_profile_hardening.py imports unsloth_cli.commands.studio, which pulls
+ # the CLI's import chain; without these the job dies on ModuleNotFoundError before a
+ # single test runs. rich arrives through typer today, but unsloth_cli imports it
+ # directly, so it is named rather than left to somebody else's dependency list. No
+ # torch: UNSLOTH_NO_TORCH keeps the suite off it.
+ - run: python -m pip install -U pip pytest typer pyyaml pydantic click rich
# -rs: these files are full of platform-gated cases, and a case that
# silently stopped running on the row it exists for still reports green.
- name: Cross-platform parity tests
@@ -181,6 +194,7 @@ jobs:
tests/test_installer_skip_autostart.py
tests/test_installer_system32_guard.py
tests/test_installer_interactive_prompts.py
+ tests/test_installer_profile_hardening.py
-q -rs
- name: PowerShell rollback lifecycle tests
if: runner.os == 'Windows'
diff --git a/install.ps1 b/install.ps1
index e77017c72ed..5d3c4f32441 100644
--- a/install.ps1
+++ b/install.ps1
@@ -18,6 +18,94 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
function Install-UnslothStudio {
$ErrorActionPreference = "Stop"
+
+ # The user's PowerShell profile has already run by the time this does, and the documented
+ # "irm https://unsloth.ai/install.ps1 | iex" entry point has no script file to re-launch
+ # with -NoProfile, so each way a profile can reach in here is cut individually below.
+ #
+ # Off, not Latest: this script predates strict mode, testing environment variables that are
+ # legitimately unset and reading $script: state only some branches assign. Scoped to here
+ # and below, so the caller keeps its own.
+ Set-StrictMode -Off
+
+ # A profile that sets 'None' -- the startup-time tweak people copy -- is fatal on PowerShell
+ # 7, which loads NO modules at startup: Test-Path, Write-Host, Select-Object,
+ # ConvertFrom-Json, Get-FileHash, Invoke-WebRequest, Expand-Archive, Start-Process and
+ # Get-Content stop resolving, while 5.1 preloads Utility and Management and survives. First
+ # of the four, because the proxy handoff below calls ConvertTo-Json from Utility too.
+ $PSModuleAutoLoadingPreference = 'All'
+
+ # Proxy keys are kept rather than dropped: on a locked-down corporate host such an entry may
+ # be the sole route to python.org and the uv release. IsMatch, not -match, so the filter
+ # leaves no $Matches behind for the rest of the install.
+ $_UnslothKeptDefaults = @{}
+ foreach ($_UnslothDefaultKey in @($PSDefaultParameterValues.Keys)) {
+ # IgnoreCase: 'invoke-webrequest:proxy' is valid PowerShell and binds the same
+ # parameter, so a case-sensitive filter drops a working proxy on a technicality.
+ if ($_UnslothDefaultKey -is [string] -and
+ [regex]::IsMatch(
+ $_UnslothDefaultKey,
+ ':Proxy(Credential|UseDefaultCredentials)?$',
+ [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)) {
+ $_UnslothKeptDefaults[$_UnslothDefaultKey] = $PSDefaultParameterValues[$_UnslothDefaultKey]
+ }
+ }
+ # One profile entry such as 'Start-Process:WindowStyle' or 'Invoke-WebRequest:TimeoutSec'
+ # silently rebinds every process launch and download here. Assigning with no scope qualifier
+ # shadows the caller's table for this scope and below only.
+ $PSDefaultParameterValues = $_UnslothKeptDefaults
+
+ # The kept proxies travel to studio/setup.ps1 (launched -NoProfile by unsloth_cli, and it
+ # downloads the VC++ runtime and the uv installer) as JSON in _UNSLOTH_PS_PROXY_DEFAULTS,
+ # since a PowerShell variable does not cross a process boundary. Credentials do not travel:
+ # a PSCredential does not serialize, and an environment variable is the wrong place for one.
+ $_UnslothProxyHandoff = @{}
+ foreach ($_UnslothDefaultKey in @($_UnslothKeptDefaults.Keys)) {
+ $_UnslothDefaultValue = $_UnslothKeptDefaults[$_UnslothDefaultKey]
+ # [uri] is the form the parameter actually takes and serializes to its own string.
+ if ($_UnslothDefaultValue -is [uri]) {
+ $_UnslothProxyHandoff[$_UnslothDefaultKey] = $_UnslothDefaultValue.AbsoluteUri
+ } elseif ($_UnslothDefaultValue -is [string] -or $_UnslothDefaultValue -is [bool]) {
+ $_UnslothProxyHandoff[$_UnslothDefaultKey] = $_UnslothDefaultValue
+ } elseif ($_UnslothDefaultValue -is [scriptblock]) {
+ # A script block is the supported form for a DYNAMIC default, e.g.
+ # { [uri]$env:CORP_PROXY }, evaluated per call by Invoke-WebRequest. Evaluate here
+ # and hand over the RESULT: executable code must not cross into the child.
+ try {
+ $_UnslothDefaultResolved = & $_UnslothDefaultValue
+ if ($_UnslothDefaultResolved -is [uri]) {
+ $_UnslothProxyHandoff[$_UnslothDefaultKey] = $_UnslothDefaultResolved.AbsoluteUri
+ } elseif ($_UnslothDefaultResolved -is [string] -or
+ $_UnslothDefaultResolved -is [bool]) {
+ $_UnslothProxyHandoff[$_UnslothDefaultKey] = $_UnslothDefaultResolved
+ }
+ } catch { }
+ }
+ }
+ # A FUNCTION-local, not $script: or an environment variable: under "irm ... | iex" this runs
+ # in the caller's own session, and the value can carry credentials (http://user:secret@proxy
+ # is the ordinary corporate form) that must not outlive the install on any of the dozens of
+ # return paths. Module-qualified serializer, as in the probe: a profile alias or function
+ # named ConvertTo-Json would otherwise reshape this record or throw out of the prologue.
+ $UnslothProxyHandoffJson =
+ if ($_UnslothProxyHandoff.Count -gt 0) {
+ $_UnslothProxyHandoff | Microsoft.PowerShell.Utility\ConvertTo-Json -Compress
+ }
+ else { $null }
+
+ # PowerShell 7 only, and $false is its default: a profile that flips it on turns every
+ # non-zero native exit into a terminating error, which with "Stop" above would throw out of
+ # the setup handoff instead of reaching Exit-InstallFailure. Harmless on 5.1, where the
+ # variable does not exist.
+ $PSNativeCommandUseErrorActionPreference = $false
+
+ # Reset per invocation, for the reason at $script:IsIntelXpu further down: under
+ # "irm ... | iex" $script: is the caller's session scope, so a second run in the same
+ # console would start on the first run's state. These two are the only ones no later
+ # statement re-assigns unconditionally.
+ $script:UvExe = 'uv'
+ $script:UvInstallDestDir = $null
+
$script:UnslothVerbose = ($env:UNSLOTH_VERBOSE -eq "1")
# Same fix as studio/setup.ps1, for the same reason. This script also calls
@@ -1918,7 +2006,14 @@ exit 0
}
Write-TauriLog "STEP" "Checking system dependencies"
- $script:WingetAvailable = [bool](Get-Command winget -ErrorAction SilentlyContinue)
+ # -CommandType Application, as for Resolve-UvExecutable below: winget installs Python AND uv,
+ # so a profile "function winget {...}" or "Set-Alias winget ..." would otherwise receive both
+ # installs. The resolved path is pinned so the five call sites cannot be re-resolved later.
+ $script:WingetExe = (
+ Get-Command winget -CommandType Application -All -ErrorAction SilentlyContinue |
+ Where-Object { $_.Source } | Select-Object -First 1 -ExpandProperty Source
+ )
+ $script:WingetAvailable = [bool]$script:WingetExe
if ($script:WingetAvailable) {
step "winget" "available"
} else {
@@ -2185,7 +2280,7 @@ exit 0
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = "Continue"
try {
- winget install -e --id "Python.Python.$PythonVersion" --source winget --architecture x64 --accept-package-agreements --accept-source-agreements
+ & $script:WingetExe install -e --id "Python.Python.$PythonVersion" --source winget --architecture x64 --accept-package-agreements --accept-source-agreements
} catch { }
$ErrorActionPreference = $prevEAP
Refresh-SessionPath
@@ -2224,7 +2319,7 @@ exit 0
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = "Continue"
try {
- winget install -e --id $pythonPackageId --source winget --accept-package-agreements --accept-source-agreements
+ & $script:WingetExe install -e --id $pythonPackageId --source winget --accept-package-agreements --accept-source-agreements
$wingetExit = $LASTEXITCODE
} catch { $wingetExit = 1 }
$ErrorActionPreference = $prevEAP
@@ -2241,7 +2336,7 @@ exit 0
substep "Python not found on PATH after winget. Retrying with --force..." "Yellow"
$ErrorActionPreference = "Continue"
try {
- winget install -e --id $pythonPackageId --source winget --accept-package-agreements --accept-source-agreements --force
+ & $script:WingetExe install -e --id $pythonPackageId --source winget --accept-package-agreements --accept-source-agreements --force
$wingetExit = $LASTEXITCODE
} catch { $wingetExit = 1 }
$ErrorActionPreference = $prevEAP
@@ -2300,17 +2395,81 @@ exit 0
# ── Install uv ──
Write-TauriLog "STEP" "Installing uv package manager"
$UvMinVersion = "0.8.16"
+
+ # PowerShell ranks aliases and functions above anything on PATH, so a profile carrying
+ # "Set-Alias uv ..." or "function uv {...}" captures every bare uv call here and the version
+ # probe reads a good uv as broken. $null when nothing named uv resolves to an executable, so
+ # the caller's "not installed yet" branch keeps its meaning.
+ function Resolve-UvExecutable {
+ # @(): a one-element return unrolls to a bare string, and indexing THAT gives its
+ # first character.
+ $candidates = @(Get-UvExecutableCandidates)
+ if ($candidates.Count -gt 0) { return $candidates[0] }
+ return $null
+ }
+
+ # Every uv this machine offers, in the order the bare token would pick them: alias first,
+ # then PATH. A LIST rather than one answer, so the version gate can move past an alias
+ # pointing at a stale uv and still find a current one.
+ function Get-UvExecutableCandidates {
+ # An ALIAS pointing at a real executable FIRST, because PowerShell resolves aliases
+ # ahead of PATH. Followed only as far as an Application, returning the resolved path so
+ # the rest of the script is not back in command discovery.
+ $found = [System.Collections.Generic.List[string]]::new()
+ $alias = Get-Command uv -CommandType Alias -ErrorAction SilentlyContinue
+ while ($alias -and $alias.ResolvedCommand) {
+ $target = $alias.ResolvedCommand
+ if ($target.CommandType -eq 'Application' -and $target.Source) {
+ $found.Add($target.Source)
+ break
+ }
+ if ($target.CommandType -ne 'Alias') { break }
+ $alias = $target
+ }
+ # -All, because Get-Command's choice among several matches is otherwise incidental.
+ # Applications come back in PATH order, so with no profile overrides this is the uv the
+ # bare token would run.
+ $apps = @(
+ Get-Command uv -CommandType Application -All -ErrorAction SilentlyContinue |
+ Where-Object { $_.Source }
+ )
+ foreach ($app in $apps) {
+ if (-not $found.Contains($app.Source)) { $found.Add($app.Source) }
+ }
+ if ($found.Count -gt 0) { return @($found) }
+ # Anything else named uv is a function, a cmdlet, or an alias to one, and handing back
+ # the bare token would let a wrapper answering `--version` pass the gate and then
+ # receive every install command. An empty list means "not installed yet", so uv gets
+ # installed and the gate re-probes.
+ return @()
+ }
+
function Test-UvVersionOk {
- $cmd = Get-Command uv -ErrorAction SilentlyContinue
- if (-not $cmd) { return $false }
+ # EVERY candidate, not just the first, so an alias pointing at a stale uv cannot hide a
+ # current uv on PATH. Alias first still, so a passing alias keeps winning.
+ foreach ($exe in Get-UvExecutableCandidates) {
+ if (Test-UvCandidateVersion $exe) { return $true }
+ }
+ return $false
+ }
+
+ function Test-UvCandidateVersion {
+ param([string]$exe)
+ if (-not $exe) { return $false }
try {
- $raw = (& uv --version 2>$null | Select-Object -First 1)
+ $raw = (& $exe --version 2>$null | Select-Object -First 1)
} catch {
return $false
}
if ($raw -notmatch 'uv\s+([0-9]+(?:\.[0-9]+)+)') { return $false }
try {
- return ([version]$Matches[1] -ge [version]$UvMinVersion)
+ if ([version]$Matches[1] -ge [version]$UvMinVersion) {
+ # Pin the executable that actually answered: every install command below runs
+ # this path, so a later Refresh-SessionPath or a profile alias cannot swap it.
+ $script:UvExe = $exe
+ return $true
+ }
+ return $false
} catch {
return $false
}
@@ -2421,7 +2580,9 @@ exit 0
}
if (-not (Test-UvVersionOk)) {
- if (Get-Command uv -ErrorAction SilentlyContinue) {
+ # Resolve-UvExecutable, not a bare Get-Command: a profile alias named uv would
+ # otherwise report "updating" on what is in fact a first install.
+ if (Resolve-UvExecutable) {
substep "updating uv package manager..."
} else {
substep "installing uv package manager..."
@@ -2429,9 +2590,9 @@ exit 0
if ($script:WingetAvailable) {
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = "Continue"
- try { winget upgrade --id=astral-sh.uv -e --source winget --accept-package-agreements --accept-source-agreements } catch {}
+ try { & $script:WingetExe upgrade --id=astral-sh.uv -e --source winget --accept-package-agreements --accept-source-agreements } catch {}
if (-not (Test-UvVersionOk)) {
- try { winget install --id=astral-sh.uv -e --source winget --accept-package-agreements --accept-source-agreements } catch {}
+ try { & $script:WingetExe install --id=astral-sh.uv -e --source winget --accept-package-agreements --accept-source-agreements } catch {}
}
$ErrorActionPreference = $prevEAP
Refresh-SessionPath
@@ -2820,7 +2981,7 @@ exit 0
if (-not (Test-Path -LiteralPath $VenvPython)) {
step "venv" "creating Python $($DetectedPython.Version) virtual environment"
substep "$VenvDir"
- $venvExit = Invoke-InstallCommand -Label "create virtual environment" { uv venv $VenvDir --python "$($DetectedPython.Path)" }
+ $venvExit = Invoke-InstallCommand -Label "create virtual environment" { & $script:UvExe venv $VenvDir --python "$($DetectedPython.Path)" }
if ($venvExit -ne 0) {
Write-StudioLine "[ERROR] Failed to create virtual environment (exit code $venvExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to create virtual environment (exit code $venvExit)" $venvExit)
@@ -3994,21 +4155,21 @@ exit 0
if ($SkipTorch) {
# No-torch: install unsloth + unsloth-zoo with --no-deps, then
# runtime deps (typer, safetensors, transformers, etc.) with --no-deps.
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (migrated no-torch)" { uv pip install --python $VenvPython --no-deps --reinstall-package unsloth --reinstall-package unsloth-zoo "unsloth>=2026.8.9" "unsloth-zoo>=2026.8.6" }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (migrated no-torch)" { & $script:UvExe pip install --python $VenvPython --no-deps --reinstall-package unsloth --reinstall-package unsloth-zoo "unsloth>=2026.8.9" "unsloth-zoo>=2026.8.6" }
if ($baseInstallExit -eq 0) {
# Resolve pydantic WITH deps so pip pins pydantic-core
# to the matching version (no-torch-runtime.txt below
# is --no-deps). All transitive deps are torch-free.
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install pydantic" { uv pip install --python $VenvPython pydantic }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install pydantic" { & $script:UvExe pip install --python $VenvPython pydantic }
}
if ($baseInstallExit -eq 0) {
$NoTorchReq = Find-NoTorchRuntimeFile
if ($NoTorchReq) {
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install no-torch runtime deps" { uv pip install --python $VenvPython --no-deps -r $NoTorchReq }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install no-torch runtime deps" { & $script:UvExe pip install --python $VenvPython --no-deps -r $NoTorchReq }
}
}
} else {
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (migrated)" { uv pip install --python $VenvPython --reinstall-package unsloth --reinstall-package unsloth-zoo "unsloth>=2026.8.9" "unsloth-zoo>=2026.8.6" }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (migrated)" { & $script:UvExe pip install --python $VenvPython --reinstall-package unsloth --reinstall-package unsloth-zoo "unsloth>=2026.8.9" "unsloth-zoo>=2026.8.6" }
}
if ($baseInstallExit -ne 0) {
Write-StudioLine "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
@@ -4016,13 +4177,13 @@ exit 0
}
if ($StudioLocalInstall) {
substep "overlaying local repo (editable)..."
- $overlayExit = Invoke-InstallCommand -Label "overlay local repo" { uv pip install --python $VenvPython -e $RepoRoot --no-deps }
+ $overlayExit = Invoke-InstallCommand -Label "overlay local repo" { & $script:UvExe pip install --python $VenvPython -e $RepoRoot --no-deps }
if ($overlayExit -ne 0) {
Write-StudioLine "[ERROR] Failed to overlay local repo (exit code $overlayExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to overlay local repo (exit code $overlayExit)" $overlayExit)
}
substep "overlaying unsloth-zoo from git main..."
- $zooOverlayExit = Invoke-InstallCommandRetry -Label "overlay unsloth-zoo (git main)" { uv pip install --python $VenvPython --no-deps --reinstall-package unsloth-zoo "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo" }
+ $zooOverlayExit = Invoke-InstallCommandRetry -Label "overlay unsloth-zoo (git main)" { & $script:UvExe pip install --python $VenvPython --no-deps --reinstall-package unsloth-zoo "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo" }
if ($zooOverlayExit -ne 0) {
Write-StudioLine "[ERROR] Failed to overlay unsloth-zoo (exit code $zooOverlayExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to overlay unsloth-zoo (exit code $zooOverlayExit)" $zooOverlayExit)
@@ -4039,7 +4200,7 @@ exit 0
# ABI-incompatible torchvision/torchaudio on AMD's per-arch index.
$visionSpec = if ($PinnedRocmVisionSpec) { $PinnedRocmVisionSpec } elseif ($ROCmGfxArch -and $torchvisionFloorMap -and $torchvisionFloorMap.ContainsKey($ROCmGfxArch)) { $torchvisionFloorMap[$ROCmGfxArch] } else { "torchvision" }
$audioSpec = if ($PinnedRocmAudioSpec) { $PinnedRocmAudioSpec } elseif ($ROCmGfxArch -and $torchaudioFloorMap -and $torchaudioFloorMap.ContainsKey($ROCmGfxArch)) { $torchaudioFloorMap[$ROCmGfxArch] } else { "torchaudio" }
- $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (AMD ROCm)" { uv pip install --python $VenvPython --force-reinstall --default-index $ROCmIndexUrl $torchSpec $visionSpec $audioSpec }
+ $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (AMD ROCm)" { & $script:UvExe pip install --python $VenvPython --force-reinstall --default-index $ROCmIndexUrl $torchSpec $visionSpec $audioSpec }
if ($torchInstallExit -ne 0) {
# Transient AMD-index failure: fall back to a CPU base (Unsloth setup retries
# ROCm). Use an explicit CPU index -- for a pinned ROCm index $TorchIndexUrl IS
@@ -4050,7 +4211,7 @@ exit 0
# torch (e.g. 2.10.0+rocm on gfx110X/gfx90a) that still satisfies the CPU
# torch>= range, so without it uv would keep the ROCm build and only swap
# the companions -- a mismatched venv the flavor-repair block won't fix.
- $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (CPU fallback)" { uv pip install --python $VenvPython --force-reinstall "torch>=2.4,<2.11.0" "torchvision>=0.19,<0.26.0" "torchaudio>=2.4,<2.11.0" --default-index $CpuFallbackIndexUrl }
+ $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (CPU fallback)" { & $script:UvExe pip install --python $VenvPython --force-reinstall "torch>=2.4,<2.11.0" "torchvision>=0.19,<0.26.0" "torchaudio>=2.4,<2.11.0" --default-index $CpuFallbackIndexUrl }
if ($torchInstallExit -ne 0) {
Write-StudioLine "[ERROR] Failed to install PyTorch (ROCm and CPU base both failed, exit code $torchInstallExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to install PyTorch (exit code $torchInstallExit)" $torchInstallExit)
@@ -4082,12 +4243,12 @@ exit 0
substep "windows on arm: skipping torchaudio (upstream publishes no win_arm64 wheel)."
$_xpuCpuSpecs = @("torch>=2.4,<2.11.0", "torchvision>=0.19,<0.26.0")
}
- $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (Intel XPU)" { uv pip install --python $VenvPython --force-reinstall @_xpuSpecs --default-index $TorchIndexUrl }
+ $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (Intel XPU)" { & $script:UvExe pip install --python $VenvPython --force-reinstall @_xpuSpecs --default-index $TorchIndexUrl }
if ($torchInstallExit -ne 0) {
# Transient XPU-index failure: fall back to CPU base.
$CpuFallbackIndexUrl = if ($env:UNSLOTH_PYTORCH_MIRROR) { "$($env:UNSLOTH_PYTORCH_MIRROR.TrimEnd('/'))/cpu" } else { "https://download.pytorch.org/whl/cpu" }
substep "XPU PyTorch install failed (exit $torchInstallExit); using a CPU base." "Yellow"
- $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (CPU fallback)" { uv pip install --python $VenvPython --force-reinstall @_xpuCpuSpecs --default-index $CpuFallbackIndexUrl }
+ $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (CPU fallback)" { & $script:UvExe pip install --python $VenvPython --force-reinstall @_xpuCpuSpecs --default-index $CpuFallbackIndexUrl }
if ($torchInstallExit -ne 0) {
Write-StudioLine "[ERROR] Failed to install PyTorch (XPU and CPU base both failed, exit code $torchInstallExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to install PyTorch (exit code $torchInstallExit)" $torchInstallExit)
@@ -4123,7 +4284,7 @@ exit 0
substep "win_arm64 wheel); torch and torchvision install normally."
$_torchSpecs = @("torch>=2.4,<2.11.0", $_pinVisionSpec)
}
- $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch" { uv pip install --python $VenvPython @_torchSpecs --default-index $TorchIndexUrl }
+ $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch" { & $script:UvExe pip install --python $VenvPython @_torchSpecs --default-index $TorchIndexUrl }
if ($torchInstallExit -ne 0) {
Write-StudioLine "[ERROR] Failed to install PyTorch (exit code $torchInstallExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to install PyTorch (exit code $torchInstallExit)" $torchInstallExit)
@@ -4135,21 +4296,21 @@ exit 0
if ($SkipTorch) {
# No-torch: install unsloth + unsloth-zoo with --no-deps, then
# runtime deps (typer, safetensors, transformers, etc.) with --no-deps.
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (no-torch)" { uv pip install --python $VenvPython --no-deps --upgrade-package unsloth --upgrade-package unsloth-zoo "unsloth>=2026.8.9" "unsloth-zoo>=2026.8.6" }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (no-torch)" { & $script:UvExe pip install --python $VenvPython --no-deps --upgrade-package unsloth --upgrade-package unsloth-zoo "unsloth>=2026.8.9" "unsloth-zoo>=2026.8.6" }
if ($baseInstallExit -eq 0) {
# Same pydantic-with-deps trick as the migrated branch.
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install pydantic" { uv pip install --python $VenvPython pydantic }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install pydantic" { & $script:UvExe pip install --python $VenvPython pydantic }
}
if ($baseInstallExit -eq 0) {
$NoTorchReq = Find-NoTorchRuntimeFile
if ($NoTorchReq) {
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install no-torch runtime deps" { uv pip install --python $VenvPython --no-deps -r $NoTorchReq }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install no-torch runtime deps" { & $script:UvExe pip install --python $VenvPython --no-deps -r $NoTorchReq }
}
}
} elseif ($StudioLocalInstall) {
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (local)" { uv pip install --python $VenvPython --upgrade-package unsloth "unsloth>=2026.8.9" "unsloth-zoo>=2026.8.6" }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (local)" { & $script:UvExe pip install --python $VenvPython --upgrade-package unsloth "unsloth>=2026.8.9" "unsloth-zoo>=2026.8.6" }
} else {
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth" { uv pip install --python $VenvPython --upgrade-package unsloth -- "$PackageName" }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth" { & $script:UvExe pip install --python $VenvPython --upgrade-package unsloth -- "$PackageName" }
}
if ($baseInstallExit -ne 0) {
Write-StudioLine "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
@@ -4158,13 +4319,13 @@ exit 0
if ($StudioLocalInstall) {
substep "overlaying local repo (editable)..."
- $overlayExit = Invoke-InstallCommand -Label "overlay local repo" { uv pip install --python $VenvPython -e $RepoRoot --no-deps }
+ $overlayExit = Invoke-InstallCommand -Label "overlay local repo" { & $script:UvExe pip install --python $VenvPython -e $RepoRoot --no-deps }
if ($overlayExit -ne 0) {
Write-StudioLine "[ERROR] Failed to overlay local repo (exit code $overlayExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to overlay local repo (exit code $overlayExit)" $overlayExit)
}
substep "overlaying unsloth-zoo from git main..."
- $zooOverlayExit = Invoke-InstallCommandRetry -Label "overlay unsloth-zoo (git main)" { uv pip install --python $VenvPython --no-deps --reinstall-package unsloth-zoo "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo" }
+ $zooOverlayExit = Invoke-InstallCommandRetry -Label "overlay unsloth-zoo (git main)" { & $script:UvExe pip install --python $VenvPython --no-deps --reinstall-package unsloth-zoo "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo" }
if ($zooOverlayExit -ne 0) {
Write-StudioLine "[ERROR] Failed to overlay unsloth-zoo (exit code $zooOverlayExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to overlay unsloth-zoo (exit code $zooOverlayExit)" $zooOverlayExit)
@@ -4175,25 +4336,25 @@ exit 0
Write-TauriLog "STEP" "Installing unsloth"
substep "installing unsloth (this may take a few minutes)..."
if ($StudioLocalInstall) {
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (auto torch backend)" { uv pip install --python $VenvPython "unsloth-zoo>=2026.8.6" "unsloth>=2026.8.9" --torch-backend=auto }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (auto torch backend)" { & $script:UvExe pip install --python $VenvPython "unsloth-zoo>=2026.8.6" "unsloth>=2026.8.9" --torch-backend=auto }
if ($baseInstallExit -ne 0) {
Write-StudioLine "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to install unsloth (exit code $baseInstallExit)" $baseInstallExit)
}
substep "overlaying local repo (editable)..."
- $overlayExit = Invoke-InstallCommand -Label "overlay local repo" { uv pip install --python $VenvPython -e $RepoRoot --no-deps }
+ $overlayExit = Invoke-InstallCommand -Label "overlay local repo" { & $script:UvExe pip install --python $VenvPython -e $RepoRoot --no-deps }
if ($overlayExit -ne 0) {
Write-StudioLine "[ERROR] Failed to overlay local repo (exit code $overlayExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to overlay local repo (exit code $overlayExit)" $overlayExit)
}
substep "overlaying unsloth-zoo from git main..."
- $zooOverlayExit = Invoke-InstallCommandRetry -Label "overlay unsloth-zoo (git main)" { uv pip install --python $VenvPython --no-deps --reinstall-package unsloth-zoo "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo" }
+ $zooOverlayExit = Invoke-InstallCommandRetry -Label "overlay unsloth-zoo (git main)" { & $script:UvExe pip install --python $VenvPython --no-deps --reinstall-package unsloth-zoo "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo" }
if ($zooOverlayExit -ne 0) {
Write-StudioLine "[ERROR] Failed to overlay unsloth-zoo (exit code $zooOverlayExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to overlay unsloth-zoo (exit code $zooOverlayExit)" $zooOverlayExit)
}
} else {
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (auto torch backend)" { uv pip install --python $VenvPython --torch-backend=auto -- "$PackageName" }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (auto torch backend)" { & $script:UvExe pip install --python $VenvPython --torch-backend=auto -- "$PackageName" }
if ($baseInstallExit -ne 0) {
Write-StudioLine "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to install unsloth (exit code $baseInstallExit)" $baseInstallExit)
@@ -4215,7 +4376,7 @@ exit 0
# $TorchIndexUrl, so a failed XPU install reads as "cpu" here. Best-effort: a failure warns.
if (-not $SkipTorch -and (Get-TorchIndexLeafName $TorchIndexUrl) -eq "xpu") {
substep "installing bitsandbytes with Intel XPU kernels..."
- $bnbXpuExit = Invoke-InstallCommandRetry -Label "install bitsandbytes (Intel XPU)" { uv pip install --python $VenvPython --no-deps "bitsandbytes>=0.50.0" }
+ $bnbXpuExit = Invoke-InstallCommandRetry -Label "install bitsandbytes (Intel XPU)" { & $script:UvExe pip install --python $VenvPython --no-deps "bitsandbytes>=0.50.0" }
if ($bnbXpuExit -ne 0) {
substep "[WARN] could not install an XPU-capable bitsandbytes (exit $bnbXpuExit); 4-bit QLoRA may be unavailable." "Yellow"
}
@@ -4249,7 +4410,7 @@ exit 0
$visionSpec = if ($PinnedRocmVisionSpec) { $PinnedRocmVisionSpec } elseif ($ROCmGfxArch -and $torchvisionFloorMap -and $torchvisionFloorMap.ContainsKey($ROCmGfxArch)) { $torchvisionFloorMap[$ROCmGfxArch] } else { "torchvision" }
$audioSpec = if ($PinnedRocmAudioSpec) { $PinnedRocmAudioSpec } elseif ($ROCmGfxArch -and $torchaudioFloorMap -and $torchaudioFloorMap.ContainsKey($ROCmGfxArch)) { $torchaudioFloorMap[$ROCmGfxArch] } else { "torchaudio" }
substep "PyTorch flavor mismatch (installed $installedTorchTag, need ROCm) -- reinstalling correct build..." "Yellow"
- $torchFixExit = Invoke-InstallCommand -Label "reinstall PyTorch (ROCm)" { uv pip install --python $VenvPython --force-reinstall --default-index $ROCmIndexUrl $rocmSpec $visionSpec $audioSpec }
+ $torchFixExit = Invoke-InstallCommand -Label "reinstall PyTorch (ROCm)" { & $script:UvExe pip install --python $VenvPython --force-reinstall --default-index $ROCmIndexUrl $rocmSpec $visionSpec $audioSpec }
if ($torchFixExit -ne 0) {
Write-StudioLine "[ERROR] Failed to reinstall PyTorch with the correct ROCm build (exit code $torchFixExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to reinstall PyTorch (ROCm) (exit code $torchFixExit)" $torchFixExit)
@@ -4263,7 +4424,7 @@ exit 0
# fails the repair before setup.ps1's ARM-aware fallback.
$_fixSpecs = if ($expectedTorchTag -eq 'xpu') { Get-XpuTorchSpecs -Platform (Get-VenvPlatformTag -PythonExe $VenvPython) }
else { @("torch>=2.4,<2.11.0", "torchvision>=0.19,<0.26.0", "torchaudio>=2.4,<2.11.0") }
- $torchFixExit = Invoke-InstallCommand -Label "reinstall PyTorch ($expectedTorchTag)" { uv pip install --python $VenvPython @_fixSpecs --default-index $TorchIndexUrl --reinstall-package torch --reinstall-package torchvision --reinstall-package torchaudio }
+ $torchFixExit = Invoke-InstallCommand -Label "reinstall PyTorch ($expectedTorchTag)" { & $script:UvExe pip install --python $VenvPython @_fixSpecs --default-index $TorchIndexUrl --reinstall-package torch --reinstall-package torchvision --reinstall-package torchaudio }
if ($torchFixExit -ne 0) {
Write-StudioLine "[ERROR] Failed to reinstall PyTorch with the correct CUDA build (exit code $torchFixExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to reinstall PyTorch ($expectedTorchTag) (exit code $torchFixExit)" $torchFixExit)
@@ -4411,7 +4572,7 @@ exit 0
}
substep "CI: overlaying source checkout (editable, no deps): $CiOverlayRoot"
# Retry: the editable build fetches its backend from PyPI, same network risk.
- $CiOverlayExit = Invoke-InstallCommandRetry -Label "overlay CI source checkout" -Command { uv pip install --python $VenvPython --no-deps -e $CiOverlayRoot }
+ $CiOverlayExit = Invoke-InstallCommandRetry -Label "overlay CI source checkout" -Command { & $script:UvExe pip install --python $VenvPython --no-deps -e $CiOverlayRoot }
if ($CiOverlayExit -ne 0) {
return (Exit-InstallFailure "Failed to overlay the CI source checkout (exit code $CiOverlayExit)" $CiOverlayExit)
}
@@ -4483,6 +4644,15 @@ exit 0
$previousSetupRuntimeGateHandoff = $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF
$hadPreviousSetupRuntimeGateHandoff = ($null -ne $previousSetupRuntimeGateHandoff)
$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"
+ # The proxy defaults kept out of the discarded profile table, for the duration of the child
+ # only. setup.ps1 runs with -NoProfile and downloads on its own; see the prologue.
+ $previousProxyHandoff = $env:_UNSLOTH_PS_PROXY_DEFAULTS
+ $hadPreviousProxyHandoff = ($null -ne $previousProxyHandoff)
+ # Set even when there is nothing to hand over: its ABSENCE is how the CLI recognises a
+ # standalone update and goes looking through the user's profiles. An empty object says "the
+ # installer looked, and there is none".
+ $env:_UNSLOTH_PS_PROXY_DEFAULTS =
+ if ($UnslothProxyHandoffJson) { $UnslothProxyHandoffJson } else { '{}' }
try {
& $UnslothExe @studioArgs
$setupExit = $LASTEXITCODE
@@ -4502,6 +4672,14 @@ exit 0
} else {
Remove-Item Env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF -ErrorAction SilentlyContinue
}
+ if ($hadPreviousProxyHandoff) {
+ $env:_UNSLOTH_PS_PROXY_DEFAULTS = $previousProxyHandoff
+ } else {
+ Remove-Item Env:_UNSLOTH_PS_PROXY_DEFAULTS -ErrorAction SilentlyContinue
+ }
+ # ...and the copy this function holds goes with it, rather than sitting in the frame for
+ # the rest of a long install.
+ $UnslothProxyHandoffJson = $null
Remove-Item Env:UNSLOTH_LOCAL_LLAMA_CPP_DIR -ErrorAction SilentlyContinue
Remove-Item Env:UNSLOTH_INSTALL_ROLLBACK_MANAGED -ErrorAction SilentlyContinue
Remove-Item Env:UNSLOTH_SETUP_PYTHON -ErrorAction SilentlyContinue
diff --git a/tests/python/test_windows_installer_concurrency_guard.py b/tests/python/test_windows_installer_concurrency_guard.py
index 945c70689ae..7dee41767a0 100644
--- a/tests/python/test_windows_installer_concurrency_guard.py
+++ b/tests/python/test_windows_installer_concurrency_guard.py
@@ -780,7 +780,8 @@ def test_guard_and_mutex_precede_rollback_and_release_after_restore():
)
assert "if ($StudioRedirectMode -eq 'legacy')" not in source
assert "& $UnslothExe studio -p 8888" not in source
- assert "--clear" not in source[source.index("uv venv $VenvDir") :][:200]
+ # Anchored past the command token: uv is invoked as the resolved $script:UvExe.
+ assert "--clear" not in source[source.index("venv $VenvDir") :][:200]
def test_tauri_runtime_uses_the_same_gate_before_backend_spawn():
diff --git a/tests/python/test_windows_python_venv_hardening.py b/tests/python/test_windows_python_venv_hardening.py
index 4e71d89dc9f..82ec1b7c725 100644
--- a/tests/python/test_windows_python_venv_hardening.py
+++ b/tests/python/test_windows_python_venv_hardening.py
@@ -417,7 +417,8 @@ def test_readiness_gate_precedes_installs_and_names_both_interpreters():
marker = source.index(
'[System.IO.File]::WriteAllText((Join-Path $VenvDir ".unsloth-studio-owned"), "")'
)
- first_uv_pip = source.index("uv pip install --python $VenvPython")
+ # Anchored past the command token: uv is invoked as the resolved $script:UvExe.
+ first_uv_pip = source.index("pip install --python $VenvPython")
gpu_detection = source.index("function Invoke-AmdSmiNoElevate")
assert marker < gate < gpu_detection < first_uv_pip
diff --git a/tests/test_installer_interactive_prompts.py b/tests/test_installer_interactive_prompts.py
index d0c3b3d41b6..a292bb4e2e4 100644
--- a/tests/test_installer_interactive_prompts.py
+++ b/tests/test_installer_interactive_prompts.py
@@ -560,6 +560,10 @@ def test_the_workflow_runs_for_every_scanned_script():
if collecting is not None and entry:
collecting.append(entry.group(1))
continue
+ # A comment or a blank line inside the list does not end it. Treating one as the end
+ # dropped every filter after it, so this guard passed while reading nothing.
+ if collecting is not None and (not line.strip() or line.strip().startswith("#")):
+ continue
if collecting:
blocks.append(collecting)
collecting = [] if line.strip() == "paths:" else None
diff --git a/tests/test_installer_profile_hardening.py b/tests/test_installer_profile_hardening.py
new file mode 100644
index 00000000000..fbbd6ab05d2
--- /dev/null
+++ b/tests/test_installer_profile_hardening.py
@@ -0,0 +1,1715 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression tests for install.ps1 under a user PowerShell profile.
+
+The installer used to succeed only from a console started with -NoProfile. A profile runs before
+"irm https://unsloth.ai/install.ps1 | iex" does and shares its scope, and there is no script file
+to re-launch without it, so four couplings were cut individually: $PSDefaultParameterValues,
+Set-StrictMode, $PSNativeCommandUseErrorActionPreference, and command discovery finding a profile
+alias or function named "uv" ahead of PATH. A fifth lived outside install.ps1 -- the handoff to
+`unsloth studio setup` passed -NoProfile only when stdout was not a tty, which is never true for
+the console install this is about; setup.ps1 itself is not otherwise covered here.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import stat
+import subprocess
+import time
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+INSTALL_PS1 = REPO_ROOT / "install.ps1"
+STUDIO_COMMAND = REPO_ROOT / "unsloth_cli" / "commands" / "studio.py"
+
+
+def _framed(record: str, *, banner: str = "") -> str:
+ """What the probe child really prints: the framed record, plus whatever the profile said."""
+ from unsloth_cli.commands import studio as studio_cmd
+ return f"{banner}{studio_cmd._PROXY_PROBE_BEGIN}\n{record}\n{studio_cmd._PROXY_PROBE_END}\n"
+
+
+requires_pwsh = pytest.mark.skipif(shutil.which("pwsh") is None, reason = "PowerShell is unavailable")
+
+
+def _install_ps1() -> str:
+ return INSTALL_PS1.read_text(encoding = "utf-8")
+
+
+def _locate(haystack: str, needle: str, what: str) -> int:
+ """str.index, but a removed anchor reads as a failed guard rather than a ValueError."""
+ index = haystack.find(needle)
+ if index < 0:
+ pytest.fail(f"install.ps1 no longer contains {what}: {needle!r}")
+ return index
+
+
+def _extract_function(name: str) -> str:
+ """install.ps1's own function text, verbatim, so these tests cannot drift from it."""
+ src = _install_ps1()
+ start = _locate(src, f" function {name} {{", f"the {name} helper")
+ end = _locate(src[start:], "\n }\n", f"the end of {name}") + start
+ return src[start : end + len("\n }\n")]
+
+
+def _code_only() -> str:
+ """install.ps1 with whole-line comments blanked, so ordering is judged on what executes.
+
+ The hardening block names the very cmdlets it protects, and those mentions would otherwise
+ read as the first use of each.
+ """
+ return "\n".join(
+ "" if line.lstrip().startswith("#") else line for line in _install_ps1().splitlines()
+ )
+
+
+def _extract_prologue() -> str:
+ """The profile-hardening block, from its opening comment through the last $script: reset."""
+ src = _install_ps1()
+ start = _locate(src, " # The user's PowerShell profile has already run", "the prologue")
+ end = _locate(src[start:], "$script:UnslothVerbose = ($env:UNSLOTH_VERBOSE", "the prologue end")
+ return src[start : start + end]
+
+
+def _ps_literal(value: object) -> str:
+ """A single-quoted PowerShell literal. Doubling escapes an apostrophe, which a Windows
+ account named O'Brien puts in tmp_path; unsloth_cli/commands/studio.py does the same."""
+ return "'" + str(value).replace("'", "''") + "'"
+
+
+# ── source-level: the couplings stay cut ──
+
+
+def test_prologue_neutralizes_profile_state():
+ block = _extract_prologue()
+ assert (
+ "Set-StrictMode -Off" in block
+ ), "this script's $env:X -in @(...) and unassigned-$script: idioms are errors under Latest"
+ assert (
+ "$PSDefaultParameterValues = $_UnslothKeptDefaults" in block
+ ), "a profile entry like 'Start-Process:WindowStyle' otherwise rebinds cmdlets here"
+ assert (
+ "$PSNativeCommandUseErrorActionPreference = $false" in block
+ ), "with it on, a failing native command throws past Exit-InstallFailure and skips rollback"
+
+
+def test_proxy_defaults_are_carried_across_rather_than_dropped():
+ """Clearing the table wholesale would break the corporate hosts where a profile proxy
+ entry is the only route to python.org -- and those users are the ones who never run
+ -NoProfile, so they would be trading one broken install for another."""
+ block = _extract_prologue()
+ assert (
+ ":Proxy(Credential|UseDefaultCredentials)?$" in block
+ ), "the filter must keep proxy-shaped keys, which can only ever enable a download"
+
+
+def test_profile_hardening_precedes_every_use_it_protects():
+ """Ordering, not presence: a fix applied after the first unset-env test or the first
+ download protects nothing.
+
+ Only in-process first uses are anchored. The first textual Invoke-RestMethod and
+ Start-Process are inside the launcher here-string, which is text for a separate process
+ that install.ps1 starts with -NoProfile of its own.
+ """
+ code = _code_only()
+ strict_idx = _locate(code, "Set-StrictMode -Off", "the strict-mode pin")
+ defaults_idx = _locate(code, "$PSDefaultParameterValues = $_UnslothKeptDefaults", "the filter")
+ native_idx = _locate(
+ code, "$PSNativeCommandUseErrorActionPreference = $false", "the native pin"
+ )
+ for marker, what in (
+ ("$env:UNSLOTH_NO_TORCH -in @(", "the first unset-env test"),
+ ("Invoke-WebRequest", "the first in-process download"),
+ ("& $UnslothExe @studioArgs", "the setup handoff"),
+ ):
+ idx = _locate(code, marker, what)
+ assert strict_idx < idx, f"{what} must be reached with strict mode pinned"
+ assert defaults_idx < idx, f"{what} must be reached with the profile's defaults filtered"
+ assert native_idx < idx, f"{what} must be reached with native error handling pinned"
+
+
+def test_script_scoped_uv_state_is_reset_per_invocation():
+ """Same hazard as $script:IsIntelXpu: under irm | iex, $script: is the caller's session."""
+ src = _install_ps1()
+ # Anchored on the newline plus exactly four spaces. The real assignments sit deeper in the
+ # function and would otherwise satisfy this by accident, which is how a dropped reset for
+ # $script:UvInstallDestDir once slipped past.
+ for reset, first_read in (
+ ("\n $script:UvExe = 'uv'\n", "& $script:UvExe"),
+ ("\n $script:UvInstallDestDir = $null\n", "foreach ($d in @($script:UvInstallDestDir"),
+ ):
+ init_idx = _locate(src, reset, "a per-invocation reset")
+ assert init_idx < _locate(
+ src, first_read, "the first read"
+ ), f"{reset.strip()} must come before the first read"
+ assert (
+ "$script:UvExe = 'uv'" in src
+ ), "the reset value must stay the bare token, so an unforeseen path behaves as it does today"
+
+
+def test_no_bare_uv_token_survives_at_a_call_site():
+ """A profile alias or function named uv outranks PATH, so every invocation goes through
+ the resolved executable."""
+ src = _install_ps1()
+ assert "{ uv " not in src, "install scriptblocks must invoke $script:UvExe, not the bare token"
+ assert "& uv " not in src, "the version probe must invoke the resolved executable"
+ assert (
+ src.count("{ & $script:UvExe ") >= 27
+ ), "every uv scriptblock must route through the resolved path"
+
+
+def test_uv_is_resolved_as_an_application():
+ body = _extract_function("Get-UvExecutableCandidates")
+ # The whole invocation, not the flags separately: the function's own comment mentions both,
+ # so a substring test for either passes on a body that no longer uses them.
+ assert "Get-Command uv -CommandType Application -All -ErrorAction SilentlyContinue" in body, (
+ "Application-only lookup is what skips an alias or function, and ordering across "
+ "several matches is only documented for -All"
+ )
+ assert "return 'uv'" not in body, (
+ "the bare token must NOT come back as a fallback: a profile `function uv` that answers "
+ "--version with a plausible number would clear the version gate and then receive every "
+ "install command, which is the hijack this function exists to stop"
+ )
+ assert "-CommandType Alias" in body and "ResolvedCommand" in body, (
+ "an alias pointing at a real executable is still a legitimate way to have uv, so follow "
+ "it -- but only as far as an Application, and hand back the resolved path"
+ )
+ probe = _extract_function("Test-UvVersionOk") + _extract_function("Test-UvCandidateVersion")
+ assert (
+ "Get-UvExecutableCandidates" in probe and "$script:UvExe = $exe" in probe
+ ), "the probe must pin the executable that answered, so later PATH edits cannot swap it"
+
+
+def test_setup_ps1_handoff_never_inherits_the_profile():
+ """install.ps1 ends by running `unsloth studio setup`, which re-enters PowerShell. That
+ launch used to add -NoProfile only when stdout was not a tty, so the console install this
+ whole file is about ran setup.ps1 with the user's profile loaded and its bare `uv` calls
+ exposed to the same alias."""
+ src = STUDIO_COMMAND.read_text(encoding = "utf-8")
+ start = _locate(src, 'powershell_args = ["powershell.exe"]', "the setup.ps1 launch")
+ branch = _locate(src[start:], "_should_hide_windows_subprocesses()", "the hidden-window branch")
+ assert (
+ '"-NoProfile"' in src[start : start + branch]
+ ), "-NoProfile must be added unconditionally, before the hidden-window branch"
+
+
+# ── executable: run the extracted code under a hostile profile ──
+
+
+_HOSTILE_PROFILE = """
+Set-StrictMode -Version Latest
+Set-Alias uv Write-Host
+$PSDefaultParameterValues['Invoke-WebRequest:Proxy'] = 'http://127.0.0.1:9'
+$PSDefaultParameterValues['Get-Date:Format'] = 'HOSTILE'
+$PSNativeCommandUseErrorActionPreference = $true
+"""
+
+
+def _write_exe(directory: Path, stem: str, posix_body: str, cmd_body: str) -> Path:
+ """A tiny executable discoverable as an Application on either platform."""
+ directory.mkdir(parents = True, exist_ok = True)
+ if os.name == "nt":
+ exe = directory / f"{stem}.cmd"
+ # newline = "" so write_text does not translate \n and leave \r\r\n on disk.
+ exe.write_text(cmd_body, encoding = "ascii", newline = "")
+ else:
+ exe = directory / stem
+ exe.write_text(posix_body, encoding = "ascii", newline = "")
+ exe.chmod(exe.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+ return exe
+
+
+def _fake_uv(directory: Path, version: str = "0.12.1") -> Path:
+ """A uv on PATH that reports a modern version."""
+ return _write_exe(
+ directory,
+ "uv",
+ f'#!/bin/sh\necho "uv {version}"\n',
+ f"@echo uv {version}\r\n",
+ )
+
+
+def _fake_failing_exe(directory: Path) -> Path:
+ """A native command that exits non-zero, without being an error in itself."""
+ return _write_exe(directory, "failer", "#!/bin/sh\nexit 7\n", "@exit /b 7\r\n")
+
+
+def _hostile_env(
+ tmp_path: Path,
+ path_prepend: Path | None = None,
+ path_override: Path | None = None,
+) -> dict[str, str]:
+ env = dict(os.environ)
+ home = tmp_path / "home"
+ home.mkdir(parents = True, exist_ok = True)
+ drive, tail = os.path.splitdrive(str(home))
+ env.update({"HOME": str(home), "USERPROFILE": str(home), "HOMEDRIVE": drive, "HOMEPATH": tail})
+ # HOME on its own does not move $PROFILE on Unix: PowerShell reads $XDG_CONFIG_HOME first and
+ # only falls back to $HOME/.config when it is unset, and GitHub's ubuntu image writes
+ # XDG_CONFIG_HOME into /etc/environment, so an inherited value kept naming the real account
+ # and this file's isolation leaked on a hosted runner and nowhere else. Pointed at the
+ # directory HOME already implies, so the two rules agree whichever the host applies. Windows
+ # ignores it: $PROFILE comes from the known-folder API there.
+ env["XDG_CONFIG_HOME"] = str(home / ".config")
+ if path_override is not None:
+ path_override.mkdir(parents = True, exist_ok = True)
+ env["PATH"] = str(path_override)
+ if path_prepend is not None:
+ env["PATH"] = str(path_prepend) + os.pathsep + env.get("PATH", "")
+ return env
+
+
+_PROFILE_SCOPES = (
+ "AllUsersAllHosts",
+ "AllUsersCurrentHost",
+ "CurrentUserAllHosts",
+ "CurrentUserCurrentHost",
+)
+
+
+def _profile_paths(env: dict[str, str]) -> dict[str, Path]:
+ """The four profile paths pwsh itself reports under `env`.
+
+ Asked rather than assumed. The path this replaces was hardcoded to the ".config under $HOME"
+ branch, which is only PowerShell's fallback when XDG_CONFIG_HOME is unset, so on a host that
+ exports it the fixture wrote a file pwsh never opened and the profile silently did not apply.
+ """
+ res = subprocess.run(
+ [
+ shutil.which("pwsh") or "pwsh",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "foreach ($n in "
+ + ", ".join(_ps_literal(scope) for scope in _PROFILE_SCOPES)
+ + ') { "$n=$($PROFILE.$n)" }',
+ ],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 120,
+ env = env,
+ )
+ assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"
+ reported = dict(line.strip().split("=", 1) for line in res.stdout.splitlines() if "=" in line)
+ return {scope: Path(reported.get(scope, "")) for scope in _PROFILE_SCOPES}
+
+
+def _run_with_profile(
+ tmp_path: Path,
+ body: str,
+ path_prepend: Path | None = None,
+ path_override: Path | None = None,
+ profile: str | None = None,
+) -> subprocess.CompletedProcess:
+ """Run `body` with the hostile profile dot-sourced into the scope that encloses it.
+
+ That is the scope relationship a profile has to the installer: the profile runs at global
+ scope, then "irm ... | iex" defines and calls Install-UnslothStudio in that same scope.
+ Dot-sourcing reproduces it on every OS, which planting a profile file does not -- Windows
+ resolves the Documents folder through the known-folder API, so no environment variable can
+ redirect $PROFILE at a fixture. test_a_real_profile_reproduces_the_same_state anchors this
+ against a genuinely loaded profile where that is possible.
+ """
+ profile_path = tmp_path / "hostile_profile.ps1"
+ profile_path.write_text(_HOSTILE_PROFILE if profile is None else profile, encoding = "utf-8")
+ script = tmp_path / "body.ps1"
+ script.write_text(f". {_ps_literal(profile_path)}\n{body}\n", encoding = "utf-8")
+ # Absolute path: PATH is replaced in some cases, so pwsh could not be found by name.
+ return subprocess.run(
+ [shutil.which("pwsh") or "pwsh", "-NoProfile", "-NonInteractive", "-File", str(script)],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 120,
+ env = _hostile_env(tmp_path, path_prepend, path_override),
+ )
+
+
+_STATE_PROBE = "\n".join(
+ [
+ '"ALIAS:$([bool](Get-Alias uv -ErrorAction SilentlyContinue))"',
+ "\"PROXY:$($PSDefaultParameterValues['Invoke-WebRequest:Proxy'])\"",
+ '"NATIVEEAP:$PSNativeCommandUseErrorActionPreference"',
+ 'try { $q = $global:neverAssigned; "STRICT:off" } catch { "STRICT:on" }',
+ ]
+)
+
+_PROBE_PREFIXES = ("ALIAS:", "PROXY:", "NATIVEEAP:", "STRICT:")
+
+
+def _probe_lines(stdout: str) -> list[str]:
+ return [line.strip() for line in stdout.splitlines() if line.startswith(_PROBE_PREFIXES)]
+
+
+ os.name == "nt", reason = "Windows resolves $PROFILE through the known-folder API"
+)
+@requires_pwsh
+def test_a_real_profile_reproduces_the_same_state(tmp_path):
+ """Anchor for the simulation: a profile pwsh actually loads leaves the same state.
+
+ If these ever diverge, every test below is measuring something the installer never meets.
+ Only the probe lines are compared, so a system-wide profile that prints a banner does not
+ turn this into a flake.
+ """
+ env = _hostile_env(tmp_path)
+ paths = _profile_paths(env)
+ # The two machine-wide profiles load into the real leg only and no environment variable can
+ # move them, so one touching a probed setting would read as a divergence that says nothing
+ # about the simulation. Neither ships with PowerShell, so this skip is for an administered
+ # host, and it names the file so the reason is checkable.
+ for scope in ("AllUsersAllHosts", "AllUsersCurrentHost"):
+ if paths[scope].is_file():
+ pytest.skip(f"a machine-wide profile at {paths[scope]} loads into the real leg only")
+ profile = paths["CurrentUserCurrentHost"]
+ # Not an assert: on a host whose $PROFILE cannot be redirected into the fixture at all, the
+ # real leg would load whatever the actual account has (or nothing) and prove nothing either
+ # way. XDG_CONFIG_HOME in _hostile_env is what keeps this true on Linux and macOS, so the
+ # skip is unreachable there and a regression in the simulation still fails locally and in CI.
+ if tmp_path not in profile.parents:
+ pytest.skip(f"pwsh resolves $PROFILE to {profile}, which this fixture cannot plant into")
+ profile.parent.mkdir(parents = True, exist_ok = True)
+ profile.write_text(_HOSTILE_PROFILE, encoding = "utf-8")
+ script = tmp_path / "real.ps1"
+ script.write_text(_STATE_PROBE, encoding = "utf-8")
+
+ # -NoProfile deliberately omitted; this is the one place the profile is really loaded.
+ real = subprocess.run(
+ [shutil.which("pwsh") or "pwsh", "-NonInteractive", "-File", str(script)],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 120,
+ env = env,
+ )
+ assert real.returncode == 0, f"stdout={real.stdout!r} stderr={real.stderr!r}"
+ simulated = _run_with_profile(tmp_path, _STATE_PROBE)
+ # All four probes coming back at their defaults means the file was planted somewhere pwsh
+ # does not read, which is a broken fixture rather than a divergence; the path says which.
+ assert _probe_lines(real.stdout) == _probe_lines(simulated.stdout), (
+ f"dot-sourced profile diverges from the one pwsh loaded from {profile}: "
+ f"{_probe_lines(simulated.stdout)} vs {_probe_lines(real.stdout)}"
+ )
+
+
+@requires_pwsh
+def test_the_hostile_profile_really_is_hostile(tmp_path):
+ """Control. Without it, every assertion below could pass on a profile that never applied."""
+ res = _run_with_profile(tmp_path, _STATE_PROBE, path_prepend = _fake_uv(tmp_path / "bin").parent)
+ assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"
+ assert _probe_lines(res.stdout) == [
+ "ALIAS:True",
+ "PROXY:http://127.0.0.1:9",
+ "NATIVEEAP:True",
+ "STRICT:on",
+ ], f"the profile did not apply; the tests below would be vacuous: {res.stdout!r}"
+
+
+@requires_pwsh
+def test_bare_uv_token_is_hijacked_by_the_profile(tmp_path):
+ """The bug itself: the pre-fix `& uv --version` runs the alias, so a working uv reads as
+ missing and the install stops at 'uv could not be installed'."""
+ res = _run_with_profile(
+ tmp_path,
+ "$raw = (& uv --version 2>$null | Select-Object -First 1)\n"
+ '"RAW:[$raw]"\n'
+ "if ($raw -match 'uv\\s+([0-9]+(?:\\.[0-9]+)+)') "
+ "{ \"MATCHED:$($Matches[1])\" } else { 'MATCHED:none' }\n",
+ path_prepend = _fake_uv(tmp_path / "bin").parent,
+ )
+ assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"
+ assert (
+ "MATCHED:none" in res.stdout
+ ), "if the bare token resolves past the alias, this suite can no longer detect a regression"
+ # Write-Host swallowed the arguments instead of running uv, which is the whole failure mode.
+ assert "RAW:[]" in res.stdout, f"expected the alias to eat the call; got {res.stdout!r}"
+
+
+def _guarded(*body: str) -> str:
+ """The prologue, verbatim from install.ps1, wrapped in the function it lives in."""
+ return "\n".join(
+ ["function Install-UnslothStudio {", ' $ErrorActionPreference = "Stop"']
+ + [_extract_prologue()]
+ + list(body)
+ + ["}"]
+ )
+
+
+@requires_pwsh
+def test_prologue_clears_profile_state_without_disturbing_the_session(tmp_path):
+ body = "\n".join(
+ [
+ _guarded(
+ ' "INSIDE_DEFAULTS:$($PSDefaultParameterValues.Count)"',
+ " \"INSIDE_PROXY:$($PSDefaultParameterValues['Invoke-WebRequest:Proxy'])\"",
+ ' "INSIDE_NATIVEEAP:$PSNativeCommandUseErrorActionPreference"',
+ " Show-NestedState",
+ " if ($env:UNSLOTH_TOTALLY_UNSET -in @('1', 'true'))"
+ ' { "INSIDE_ENVTEST:hit" } else { "INSIDE_ENVTEST:ok" }',
+ ' "INSIDE_UVEXE:$script:UvExe"',
+ ' "INSIDE_DESTDIR:[$script:UvInstallDestDir]"',
+ ),
+ "function Show-NestedState {",
+ ' "NESTED_DEFAULTS:$($PSDefaultParameterValues.Count)"',
+ " \"NESTED_DATE:$(Get-Date -Date '2020-01-02T03:04:05')\"",
+ ' & { if ($script:neverAssignedAnywhere) { "SB:hit" } else { "SB:ok" } }',
+ "}",
+ "Install-UnslothStudio",
+ '"AFTER_DEFAULTS:$($PSDefaultParameterValues.Count)"',
+ '"AFTER_NATIVEEAP:$PSNativeCommandUseErrorActionPreference"',
+ 'try { $q = $global:neverAssigned2; "AFTER_STRICT:off" } catch { "AFTER_STRICT:on" }',
+ ]
+ )
+ res = _run_with_profile(tmp_path, body)
+ assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"
+ # The interfering default is gone; the proxy one is kept, for the installer and its callees.
+ assert "INSIDE_DEFAULTS:1" in res.stdout
+ assert "NESTED_DEFAULTS:1" in res.stdout
+ assert "INSIDE_PROXY:http://127.0.0.1:9" in res.stdout, "a proxy default must survive"
+ assert "HOSTILE" not in res.stdout, "a nested cmdlet still bound the profile's Get-Date default"
+ assert "INSIDE_NATIVEEAP:False" in res.stdout
+ # Strict mode off for the idioms that predate it, in nested functions and scriptblocks too.
+ assert "INSIDE_ENVTEST:ok" in res.stdout
+ assert "SB:ok" in res.stdout
+ # The $script: state a second run must not inherit.
+ assert "INSIDE_UVEXE:uv" in res.stdout
+ assert "INSIDE_DESTDIR:[]" in res.stdout
+ # And the user's own session is left exactly as the profile configured it.
+ assert "AFTER_DEFAULTS:2" in res.stdout, "the caller's default-parameter table must survive"
+ assert "AFTER_NATIVEEAP:True" in res.stdout, "the caller's native error handling must survive"
+ assert "AFTER_STRICT:on" in res.stdout, "the caller's strict mode must survive"
+
+
+@requires_pwsh
+def test_a_profile_cannot_make_a_failing_native_command_terminating(tmp_path):
+ """$PSNativeCommandUseErrorActionPreference plus this script's $ErrorActionPreference = Stop
+ turns a non-zero exit into a throw, which would leave the setup handoff bypassing
+ Exit-InstallFailure and its rollback."""
+ failer = _fake_failing_exe(tmp_path / "bin")
+ body = "\n".join(
+ [
+ _guarded(
+ f" & {_ps_literal(failer)}",
+ ' "AFTER_NATIVE:$LASTEXITCODE"',
+ ),
+ 'try { Install-UnslothStudio } catch { "THREW:$($_.Exception.GetType().Name)" }',
+ ]
+ )
+ res = _run_with_profile(tmp_path, body)
+ assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"
+ assert (
+ "THREW:" not in res.stdout
+ ), f"a failing native command became terminating: {res.stdout!r}"
+ assert (
+ "AFTER_NATIVE:7" in res.stdout
+ ), "the exit code must still be readable, which is how every caller here branches"
+
+
+def _uv_probe_body(*extra: str) -> str:
+ return "\n".join(
+ [
+ _guarded(
+ ' $UvMinVersion = "0.8.16"',
+ _extract_function("Get-UvExecutableCandidates"),
+ _extract_function("Resolve-UvExecutable"),
+ _extract_function("Test-UvCandidateVersion"),
+ _extract_function("Test-UvVersionOk"),
+ ' "OK:$(Test-UvVersionOk)"',
+ ' "PINNED:$script:UvExe"',
+ *extra,
+ ),
+ "Install-UnslothStudio",
+ ]
+ )
+
+
+@requires_pwsh
+def test_uv_probe_finds_the_real_uv_behind_a_profile_alias(tmp_path):
+ fake = _fake_uv(tmp_path / "bin")
+ # The stub stands in for Invoke-InstallCommand, which is how all 27 real call sites run:
+ # a scriptblock built in one scope and invoked with & from another. It has to be defined
+ # ahead of the call, which is what the "Install-UnslothStudio" line inside _uv_probe_body is.
+ body = "\n".join(
+ [
+ "function Invoke-InstallCommandStub "
+ '{ param([ScriptBlock]$Command); "CALLSITE:$(& $Command)" }',
+ _uv_probe_body(" Invoke-InstallCommandStub { & $script:UvExe pip install nothing }"),
+ ]
+ )
+ res = _run_with_profile(tmp_path, body, path_prepend = fake.parent)
+ assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"
+ assert (
+ "OK:True" in res.stdout
+ ), "a uv on PATH must be detected even with an alias shadowing the name"
+ assert (
+ f"PINNED:{fake}" in res.stdout
+ ), f"the probe must pin {str(fake)!r} exactly; got {res.stdout!r}"
+ # The scriptblock form the installer actually uses must reach the executable, not the alias.
+ assert (
+ "CALLSITE:uv 0.12.1" in res.stdout
+ ), "install scriptblocks must run the resolved uv; the alias would echo the arguments"
+
+
+@requires_pwsh
+def test_uv_probe_rejects_a_too_old_uv_and_leaves_the_reset_value(tmp_path):
+ """The version gate still has to fail closed, or a stale uv would be pinned and used.
+
+ PATH is REPLACED, not prepended to: since the gate now walks every candidate, a real uv on
+ the machine running this would legitimately rescue the run and hide the branch under test.
+ """
+ fake = _fake_uv(tmp_path / "bin", version = "0.7.0")
+ res = _run_with_profile(tmp_path, _uv_probe_body(), path_override = fake.parent)
+ assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"
+ assert "OK:False" in res.stdout
+ assert "PINNED:uv" in res.stdout, "a rejected uv must not be pinned over the reset value"
+
+
+@requires_pwsh
+def test_uv_probe_reports_missing_when_only_the_alias_exists(tmp_path):
+ """With no uv on PATH the installer must still take its install-uv branch, not pin the alias."""
+ # The inherited PATH is replaced, not prepended to: the machine running this may well have a
+ # real uv, and it would answer the probe and hide the branch under test.
+ res = _run_with_profile(tmp_path, _uv_probe_body(), path_override = tmp_path / "emptybin")
+ assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"
+ assert "OK:False" in res.stdout
+ assert "PINNED:uv" in res.stdout
+
+
+@requires_pwsh
+def test_a_convincing_uv_function_is_not_accepted_as_uv(tmp_path):
+ """The dangerous shape is a wrapper that ANSWERS the version probe.
+
+ An alias to a missing file fails loudly, so the earlier tests catch it. A profile
+ `function uv` that prints a modern version number does not: it clears the version gate,
+ gets pinned, and then receives every install command the script runs -- with the user's
+ torch, index URL and venv path as arguments. Nothing on PATH, so only the wrapper exists.
+ """
+ profile = 'function uv { Write-Output "uv 99.0.0" }\n'
+ body = _uv_probe_body(' "RESOLVED:$(Resolve-UvExecutable)"')
+ res = _run_with_profile(tmp_path, body, path_override = tmp_path / "emptybin", profile = profile)
+ assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"
+ assert "RESOLVED:" in res.stdout and "RESOLVED:uv" not in res.stdout, (
+ "a function named uv must not resolve to the bare token; it would then be pinned and "
+ f"handed every install command. got {res.stdout!r}"
+ )
+ assert "OK:False" in res.stdout, "the version gate must not be satisfied by a wrapper"
+ assert "PINNED:uv" in res.stdout, "the reset value must survive, so uv is installed for real"
+
+
+@requires_pwsh
+def test_an_alias_to_a_real_uv_is_followed_to_the_executable(tmp_path):
+ """The legitimate wrapper shape still has to work, and resolve to a PATH, not the alias.
+
+ People do alias uv at a specific build. Refusing that outright would install a second uv
+ over a working machine, which is the failure this whole function was written to avoid.
+ """
+ fake = _fake_uv(tmp_path / "aliased", version = "0.12.4")
+ profile = f"Set-Alias uv {_ps_literal(fake)}\n"
+ body = _uv_probe_body(' "RESOLVED:$(Resolve-UvExecutable)"')
+ res = _run_with_profile(tmp_path, body, path_override = tmp_path / "emptybin", profile = profile)
+ assert res.returncode == 0, f"stdout={res.stdout!r} stderr={res.stderr!r}"
+ assert f"RESOLVED:{fake}" in res.stdout, (
+ f"an alias to a real executable must resolve to {str(fake)!r}, not to the alias name; "
+ f"got {res.stdout!r}"
+ )
+ assert "OK:True" in res.stdout
+ assert f"PINNED:{fake}" in res.stdout
+
+
+def test_no_bare_winget_token_survives_at_a_call_site():
+ """winget installs both Python and uv, so an alias on it owns the same ground.
+
+ Detection used a bare Get-Command, and all five invocations were bare tokens, so the fix
+ applied to uv left the other half of the bootstrap exposed to the identical wrapper.
+ """
+ src = _install_ps1()
+ assert (
+ "Get-Command winget -CommandType Application -All" in src
+ ), "winget detection must skip aliases and functions, exactly as uv detection does"
+ for bare in ("\n winget ", "\n winget ", "{ winget "):
+ assert bare not in src, f"winget must be invoked through the resolved path, found {bare!r}"
+ assert (
+ src.count("& $script:WingetExe ") >= 5
+ ), "every winget invocation must route through the resolved path"
+
+
+def test_module_autoloading_is_restored():
+ """A profile setting 'None' removes Test-Path, Write-Host and Invoke-WebRequest on pwsh 7,
+ which loads no modules at startup. Windows PowerShell 5.1 preloads them and survives, which
+ is what makes this reproduce on one machine and not another."""
+ src = _install_ps1()
+ idx = _locate(src, "$PSModuleAutoLoadingPreference = 'All'", "the autoloading reset")
+ assert idx < _locate(src, "Write-TauriLog", "the first cmdlet that needs a module")
+
+
+@requires_pwsh
+def test_install_ps1_parses():
+ """A syntax error here is a total install failure, and the file is not imported by anything."""
+ res = subprocess.run(
+ [
+ shutil.which("pwsh") or "pwsh",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "$errs = $null; $null = [System.Management.Automation.Language.Parser]::ParseFile("
+ f"{_ps_literal(INSTALL_PS1)}, [ref]$null, [ref]$errs); "
+ 'if ($errs) { $errs | ForEach-Object { "ERR $($_.Extent.StartLineNumber): '
+ '$($_.Message)" }; exit 1 }',
+ ],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 120,
+ )
+ assert res.returncode == 0, res.stdout + res.stderr
+
+
+# ── the proxy has to survive the process boundary, not just the filter ──
+
+
+def _proxy_prelude() -> str:
+ """The PowerShell the setup launch prepends to its -Command, read from the shipped source."""
+ src = STUDIO_COMMAND.read_text(encoding = "utf-8")
+ start = _locate(src, "_PS_PROXY_DEFAULTS_PRELUDE = (", "the proxy handoff prelude")
+ namespace: dict = {}
+ exec(src[start : src.index(")\n", start) + 1], namespace) # noqa: S102 - our own source
+ return namespace["_PS_PROXY_DEFAULTS_PRELUDE"]
+
+
+def test_the_setup_launch_reapplies_the_proxy_it_told_the_child_to_forget():
+ """-NoProfile on the setup handoff drops the whole $PSDefaultParameterValues table, proxy
+ entries included, and setup.ps1 downloads on its own (the VC++ runtime, the uv installer).
+ Where a profile proxy entry is the only egress, keeping it in install.ps1 and losing it one
+ process later is the same broken install. A PowerShell variable cannot cross a process
+ boundary, so it travels as environment."""
+ assert "_UNSLOTH_PS_PROXY_DEFAULTS" in _install_ps1(), "install.ps1 must publish the handoff"
+ prelude = _proxy_prelude()
+ assert "_UNSLOTH_PS_PROXY_DEFAULTS" in prelude, "the child must read it back"
+
+ src = STUDIO_COMMAND.read_text(encoding = "utf-8")
+ start = _locate(src, 'powershell_args = ["powershell.exe"]', "the setup.ps1 launch")
+ # The f-string itself, not the comment above it that also quotes *>&1.
+ command = _locate(src[start:], 'f"', "the -Command f-string")
+ assert (
+ "_PS_PROXY_DEFAULTS_PRELUDE" in src[start + command : start + command + 200]
+ ), "the prelude has to run before setup.ps1, not merely exist"
+
+
+@requires_pwsh
+def test_only_serializable_proxy_keys_reach_the_child(tmp_path):
+ """A credential is deliberately left behind: PSCredential does not survive ConvertTo-Json,
+ and an environment variable is the wrong place for one. Everything non-proxy stays dropped."""
+ block = tmp_path / "block.ps1"
+ block.write_text(_extract_prologue(), encoding = "utf-8", newline = "")
+ driver = tmp_path / "drive.ps1"
+ driver.write_text(
+ "$PSDefaultParameterValues = @{\n"
+ " 'Invoke-WebRequest:Proxy' = 'http://proxy.corp:8080'\n"
+ " 'Invoke-WebRequest:ProxyUseDefaultCredentials' = $true\n"
+ " 'Invoke-WebRequest:ProxyCredential' = (New-Object "
+ "System.Management.Automation.PSCredential('u',"
+ "(ConvertTo-SecureString 'p' -AsPlainText -Force)))\n"
+ " 'Start-Process:WindowStyle' = 'Hidden'\n"
+ "}\n"
+ f". '{block}'\n"
+ "Write-Output $script:UnslothProxyHandoffJson\n",
+ encoding = "utf-8",
+ newline = "",
+ )
+ handoff = subprocess.run(
+ [shutil.which("pwsh") or "pwsh", "-NoProfile", "-NonInteractive", "-File", str(driver)],
+ capture_output = True,
+ text = True,
+ check = False,
+ ).stdout
+
+ # Parsed, not substring-matched: the handoff IS JSON, so an exact value comparison is both
+ # stronger and free of the "URL may sit anywhere in the string" reading a bare `in` invites.
+ carried = json.loads(handoff.strip().splitlines()[-1])
+ assert carried["Invoke-WebRequest:Proxy"] == "http://proxy.corp:8080"
+ assert "ProxyUseDefaultCredentials" in handoff
+ assert "ProxyCredential" not in handoff, "a credential must not be written to the environment"
+ assert "WindowStyle" not in handoff, "only proxy keys are carried"
+
+
+@requires_pwsh
+def test_the_child_restores_the_proxy_and_nothing_else(tmp_path):
+ """End to end through real pwsh: with the handoff set the child's table has the proxy back;
+ without it, or with a corrupt value, the child is left exactly as -NoProfile made it and the
+ launch still succeeds. A prelude that could throw would take setup.ps1 down with it."""
+ probe = (
+ _proxy_prelude()
+ + "Write-Output ('IWR=' + $PSDefaultParameterValues['Invoke-WebRequest:Proxy']); "
+ "Write-Output ('OTHER=' + $PSDefaultParameterValues['Start-Process:WindowStyle'])"
+ )
+ pwsh = shutil.which("pwsh") or "pwsh"
+
+ def _run(value):
+ env = {k: v for k, v in os.environ.items() if k != "_UNSLOTH_PS_PROXY_DEFAULTS"}
+ if value is not None:
+ env["_UNSLOTH_PS_PROXY_DEFAULTS"] = value
+ return subprocess.run(
+ [pwsh, "-NoProfile", "-NonInteractive", "-Command", probe],
+ capture_output = True,
+ text = True,
+ check = False,
+ env = env,
+ )
+
+ restored = _run(
+ '{"Invoke-WebRequest:Proxy":"http://proxy.corp:8080",'
+ '"Start-Process:WindowStyle":"Hidden"}'
+ )
+ assert restored.returncode == 0
+ assert "IWR=http://proxy.corp:8080" in restored.stdout
+ # install.ps1 never publishes a non-proxy key, but the child trusts the table wholesale, so
+ # pin that the round trip carries what it was given and the FILTER is the one place that
+ # decides.
+ assert "OTHER=Hidden" in restored.stdout
+
+ for absent in (None, "{not json", ""):
+ result = _run(absent)
+ assert result.returncode == 0, f"the prelude must not fail the launch on {absent!r}"
+ assert "IWR=\n" in result.stdout or result.stdout.startswith("IWR=\n")
+ assert not result.stderr.strip(), f"the prelude leaked an error on {absent!r}"
+
+
+# ── the proxy handoff, hardened ───────────────────────────────────────────────
+
+
+def test_module_autoloading_is_restored_before_the_handoff_needs_it():
+ """Ordering. The handoff calls ConvertTo-Json, which lives in Microsoft.PowerShell.Utility,
+ so under a profile's $PSModuleAutoLoadingPreference = 'None' a fresh PowerShell 7 session
+ would terminate there -- taking out the exact configuration the handoff exists to support."""
+ source = _install_ps1()
+ autoload = _locate(source, "$PSModuleAutoLoadingPreference = 'All'", "the autoloading reset")
+ convert = _locate(source, "ConvertTo-Json -Compress", "the handoff serialization")
+ assert autoload < convert, (
+ "ConvertTo-Json runs before module autoloading is restored, so a profile that disables "
+ "it kills the install before the proxy is ever carried across"
+ )
+
+
+@requires_pwsh
+def test_the_filter_takes_lowercase_keys_and_uri_values(tmp_path):
+ """Both are ordinary PowerShell. Parameter names bind case-insensitively, and [uri] is the
+ type the Proxy parameter actually takes, so a careful profile writes it that way. Dropping
+ either leaves a corporate host with no route out."""
+ block = tmp_path / "block.ps1"
+ block.write_text(_extract_prologue(), encoding = "utf-8", newline = "")
+ driver = tmp_path / "drive.ps1"
+ driver.write_text(
+ "$PSDefaultParameterValues = @{\n"
+ " 'invoke-webrequest:proxy' = [uri]'http://proxy.corp:8080'\n"
+ " 'Invoke-RestMethod:PROXYUSEDEFAULTCREDENTIALS' = $true\n"
+ " 'Start-Process:WindowStyle' = 'Hidden'\n"
+ "}\n"
+ f". '{block}'\n"
+ "Write-Output $script:UnslothProxyHandoffJson\n",
+ encoding = "utf-8",
+ newline = "",
+ )
+ handoff = subprocess.run(
+ [shutil.which("pwsh") or "pwsh", "-NoProfile", "-NonInteractive", "-File", str(driver)],
+ capture_output = True,
+ text = True,
+ check = False,
+ ).stdout
+
+ assert "proxy.corp:8080" in handoff, "a [uri] value was dropped at the process boundary"
+ assert "PROXYUSEDEFAULTCREDENTIALS" in handoff, "a lowercase-cmdlet key was filtered out"
+ assert "WindowStyle" not in handoff, "only proxy keys are carried"
+
+
+def test_the_handoff_is_published_only_around_the_setup_child():
+ """Under "irm ... | iex" the prologue runs in the CALLER's session, so an environment
+ variable set there outlives the install on every path, early returns included. A later
+ `unsloth studio update` from that console would then reapply stale proxy JSON."""
+ source = _install_ps1()
+ prologue = _extract_prologue()
+ assert (
+ "$env:_UNSLOTH_PS_PROXY_DEFAULTS =" not in prologue
+ ), "the prologue publishes the handoff into the session it was invoked from"
+ assert "$UnslothProxyHandoffJson" in prologue, "the prologue must hold it instead"
+ # Set beside the other child-scoped variables, and restored with them.
+ assert "$previousProxyHandoff = $env:_UNSLOTH_PS_PROXY_DEFAULTS" in source
+ assert "$env:_UNSLOTH_PS_PROXY_DEFAULTS = $previousProxyHandoff" in source
+ gate = _locate(source, "$previousSetupRuntimeGateHandoff =", "the runtime-gate handoff")
+ proxy = _locate(source, "$previousProxyHandoff =", "the proxy handoff save")
+ call = _locate(source, " try {\n & $UnslothExe @studioArgs", "the child invocation")
+ assert gate < call and proxy < call, "the handoff must be in place before the child runs"
+
+
+def test_a_standalone_update_reconstructs_the_proxy_for_itself():
+ """install.ps1 publishes the handoff; `unsloth studio update` typed into a console has no
+ installer above it, and the profile that holds the proxy ran in a shell whose variables
+ never reach this Python process. So it is asked for, before -NoProfile drops it."""
+ src = STUDIO_COMMAND.read_text(encoding = "utf-8")
+ assert "_probe_profile_proxy_defaults" in src
+ start = _locate(src, 'powershell_args = ["powershell.exe"]', "the setup.ps1 launch")
+ guard = _locate(src[start:], "_probe_profile_proxy_defaults(", "the probe call")
+ noprofile = _locate(src[start:], '"-NoProfile"', "the -NoProfile flag")
+ assert guard < noprofile, "the probe has to run while the profile is still reachable"
+ # ...and only when the installer did not already hand one over.
+ assert "_UNSLOTH_PS_PROXY_DEFAULTS" in src[start : start + guard]
+
+
+@requires_pwsh
+def test_the_probe_reads_a_hostile_profile_without_carrying_anything_else(tmp_path):
+ """Executable, against a profile pwsh genuinely loads: strict mode on, module autoloading
+ off, a lowercase key and a [uri] value. The probe has to survive all of it and return only
+ the proxy entries."""
+ src = STUDIO_COMMAND.read_text(encoding = "utf-8")
+ # From the markers, not just the script: the record is framed, and the frame is part of
+ # what has to survive a profile that prints.
+ start = _locate(src, "_PROXY_PROBE_BEGIN = ", "the probe framing")
+ namespace: dict = {}
+ exec( # noqa: S102 - our own source
+ src[start : src.index("\n)\n", start) + 3], namespace
+ )
+
+ home = tmp_path / "config"
+ (home / "powershell").mkdir(parents = True)
+ (home / "powershell" / "Microsoft.PowerShell_profile.ps1").write_text(
+ "Set-StrictMode -Version Latest\n"
+ "$PSModuleAutoLoadingPreference = 'None'\n"
+ "$PSDefaultParameterValues['invoke-webrequest:proxy'] = [uri]'http://proxy.corp:8080'\n"
+ "$PSDefaultParameterValues['Start-Process:WindowStyle'] = 'Hidden'\n",
+ encoding = "utf-8",
+ newline = "",
+ )
+ result = subprocess.run(
+ [
+ shutil.which("pwsh") or "pwsh",
+ "-NonInteractive",
+ "-Command",
+ namespace["_PS_PROXY_PROBE"],
+ ],
+ capture_output = True,
+ text = True,
+ check = False,
+ env = {**os.environ, "XDG_CONFIG_HOME": str(home), "HOME": str(tmp_path)},
+ )
+ from unsloth_cli.commands import studio as studio_cmd
+
+ if "proxy.corp" not in (result.stdout or ""):
+ pytest.skip(f"pwsh did not load the planted profile (got {result.stdout!r})")
+ payload = studio_cmd._framed_probe_record(result.stdout)
+ assert payload, "the probe must emit a framed record"
+ assert "WindowStyle" not in payload, "the probe carried a non-proxy default across"
+ import json as _json
+
+ assert isinstance(_json.loads(payload), dict), "the probe must emit parseable JSON"
+
+
+def test_a_profile_that_prints_a_banner_does_not_cost_the_proxy(monkeypatch):
+ """The profile has already run by the time the record is printed and is free to say
+ anything: a MOTD, a "loading modules" line, a corporate banner. With the record bare, that
+ output arrived first, the parse threw, and the answer was dropped -- so the locked-down host
+ that needed the proxy handed the -NoProfile child nothing."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ noisy = _framed(
+ '{"invoke-webrequest:proxy": "http://proxy.corp:8080"}',
+ banner = "Loading personal and system profiles took 812ms.\nWelcome to Contoso.\n",
+ )
+ monkeypatch.setattr(studio_cmd.subprocess, "run", lambda argv, **kw: _Result(noisy))
+
+ merged = studio_cmd._probe_profile_proxy_defaults(["pwsh.exe"])
+ assert json.loads(merged) == {"invoke-webrequest:proxy": "http://proxy.corp:8080"}
+
+
+def test_a_profile_that_prints_nothing_useful_is_still_no_answer(monkeypatch):
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ monkeypatch.setattr(studio_cmd.subprocess, "run", lambda argv, **kw: _Result("just a banner\n"))
+ assert studio_cmd._probe_profile_proxy_defaults(["pwsh.exe"]) is None
+
+
+def test_the_caller_edition_is_read_from_the_order_not_the_absence(monkeypatch):
+ """A machine can carry BOTH module trees on PSModulePath -- 5.1 launched from a session
+ that already had 7's path, or a profile that appends it, the mixed case setup.ps1
+ documents. Reading "7 is present, so the caller is 7" then gave the wrong profile
+ precedence and let its proxy override the console the command was typed into. Each host
+ puts its own module directory first, so the earliest tree names the caller."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ monkeypatch.setattr(studio_cmd.shutil, "which", lambda name: f"C:\\{name}")
+ windows = "C:\\Users\\me\\Documents\\WindowsPowerShell\\Modules"
+ seven = "C:\\Program Files\\PowerShell\\7\\Modules"
+
+ # Both present, 5.1 first: the caller is Windows PowerShell.
+ monkeypatch.setenv("PSModulePath", f"{windows};{seven}")
+ assert studio_cmd._profile_probe_hosts()[0] == "powershell.exe"
+ # Both present, 7 first: the caller is pwsh.
+ monkeypatch.setenv("PSModulePath", f"{seven};{windows}")
+ assert studio_cmd._profile_probe_hosts()[0] == "pwsh.exe"
+ # Only one tree: unchanged from before.
+ monkeypatch.setenv("PSModulePath", windows)
+ assert studio_cmd._profile_probe_hosts()[0] == "powershell.exe"
+ monkeypatch.setenv("PSModulePath", seven)
+ assert studio_cmd._profile_probe_hosts()[0] == "pwsh.exe"
+ # Nothing to read: the previous default order.
+ monkeypatch.setenv("PSModulePath", "")
+ assert studio_cmd._profile_probe_hosts() == ["pwsh.exe", "powershell.exe"]
+
+
+def test_the_probe_pins_its_own_output_encoding(monkeypatch):
+ """Windows PowerShell 5.1 writes REDIRECTED output in the console code page while this
+ process decodes UTF-8, so a non-ASCII proxy value came back with replacement characters,
+ still parsed as JSON, and handed setup a proxy that does not resolve."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ probe = studio_cmd._PS_PROXY_PROBE
+ assert "[Console]::OutputEncoding" in probe
+ assert "UTF8Encoding" in probe
+ assert probe.index("OutputEncoding") < probe.index("PSDefaultParameterValues")
+
+
+def test_one_host_owns_a_cmdlet_outright(monkeypatch):
+ """Filling a missing companion parameter from the other edition's profile builds a
+ configuration neither host has: the earlier host's Proxy with the later host's
+ ProxyUseDefaultCredentials, which offers the user's Windows credentials to a proxy whose
+ own profile never asked for that."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ answers = [
+ _framed('{"Invoke-WebRequest:Proxy": "http://first.corp:8080"}'),
+ _framed(
+ '{"Invoke-WebRequest:ProxyUseDefaultCredentials": true, '
+ '"Start-BitsTransfer:Proxy": "http://second.corp:8080"}'
+ ),
+ ]
+ monkeypatch.setattr(studio_cmd.subprocess, "run", lambda argv, **kw: _Result(answers.pop(0)))
+
+ merged = json.loads(studio_cmd._probe_profile_proxy_defaults(["pwsh.exe", "powershell.exe"]))
+
+ # The first host owns Invoke-WebRequest whole, so the second host's credential flag for
+ # that same cmdlet is dropped...
+ assert merged == {
+ "Invoke-WebRequest:Proxy": "http://first.corp:8080",
+ # ...while a cmdlet the first host never configured still comes across.
+ "Start-BitsTransfer:Proxy": "http://second.corp:8080",
+ }
+
+
+def test_the_probe_signature_evaluates_on_the_oldest_supported_python():
+ """No `from __future__ import annotations` here, so an unquoted `str | list[str]` is
+ evaluated at def time -- a TypeError on 3.9 that takes the whole CLI import with it."""
+ import ast
+
+ tree = ast.parse(STUDIO_COMMAND.read_text(encoding = "utf-8"))
+ assert not any(
+ isinstance(node, ast.ImportFrom) and node.module == "__future__" for node in ast.walk(tree)
+ ), "this test's premise changed: the module now postpones annotations"
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.FunctionDef):
+ continue
+ for arg in [*node.args.args, *node.args.kwonlyargs]:
+ annotation = arg.annotation
+ if annotation is None:
+ continue
+ assert not isinstance(
+ annotation, ast.BinOp
+ ), f"{node.name}({arg.arg}) uses an unquoted PEP 604 union, which raises on 3.9"
+
+
+def test_the_probe_asks_both_powershell_editions(monkeypatch):
+ """pwsh and powershell.exe keep SEPARATE profiles.
+
+ `unsloth studio update` is typed into whichever host the user has open, and probing only
+ powershell.exe missed a proxy living in the PowerShell 7 profile -- the likelier place on
+ a machine that has pwsh at all. The -NoProfile child then had no proxy and setup.ps1's
+ downloads failed.
+ """
+ from unsloth_cli.commands import studio as studio_cmd
+
+ asked: list[str] = []
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ answers = {
+ "pwsh.exe": _framed('{"invoke-webrequest:proxy": "http://seven.corp:8080"}'),
+ "powershell.exe": _framed('{"invoke-restmethod:proxy": "http://five.corp:8080"}'),
+ }
+
+ def _run(argv, **kwargs):
+ asked.append(argv[0])
+ return _Result(answers[argv[0]])
+
+ monkeypatch.setattr(studio_cmd.subprocess, "run", _run)
+ merged = studio_cmd._probe_profile_proxy_defaults(["pwsh.exe", "powershell.exe"])
+
+ assert asked == ["pwsh.exe", "powershell.exe"]
+ assert json.loads(merged) == {
+ "invoke-webrequest:proxy": "http://seven.corp:8080",
+ "invoke-restmethod:proxy": "http://five.corp:8080",
+ }
+
+
+def test_the_callers_edition_wins_where_the_two_profiles_disagree(monkeypatch):
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ answers = {
+ "pwsh.exe": _framed('{"invoke-webrequest:proxy": "http://seven.corp:8080"}'),
+ "powershell.exe": _framed('{"invoke-webrequest:proxy": "http://five.corp:8080"}'),
+ }
+ monkeypatch.setattr(studio_cmd.subprocess, "run", lambda argv, **kw: _Result(answers[argv[0]]))
+ merged = studio_cmd._probe_profile_proxy_defaults(["powershell.exe", "pwsh.exe"])
+ assert json.loads(merged) == {"invoke-webrequest:proxy": "http://five.corp:8080"}
+
+
+def test_two_spellings_of_one_key_are_one_key(monkeypatch):
+ """$PSDefaultParameterValues is case-insensitive; a Python dict is not.
+
+ With both spellings carried across, the prelude replayed them in order and the
+ lower-priority host's value landed last -- the exact reverse of earlier-host-wins, and on
+ a stricter host the case-colliding JSON is rejected outright."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ answers = {
+ "pwsh.exe": _framed('{"Invoke-WebRequest:Proxy": "http://seven.corp:8080"}'),
+ "powershell.exe": _framed('{"invoke-webrequest:proxy": "http://five.corp:8080"}'),
+ }
+ monkeypatch.setattr(studio_cmd.subprocess, "run", lambda argv, **kw: _Result(answers[argv[0]]))
+ merged = json.loads(studio_cmd._probe_profile_proxy_defaults(["pwsh.exe", "powershell.exe"]))
+
+ assert merged == {"Invoke-WebRequest:Proxy": "http://seven.corp:8080"}
+
+
+def test_one_profile_that_prints_both_spellings_is_folded_too(monkeypatch):
+ # Same collision inside a single host's answer: the first spelling wins and the second
+ # never reaches the child.
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ payload = (
+ '{"Invoke-WebRequest:Proxy": "http://first.corp:8080",'
+ ' "invoke-webrequest:PROXY": "http://second.corp:8080",'
+ ' "Invoke-RestMethod:Proxy": "http://rest.corp:8080"}'
+ )
+ monkeypatch.setattr(studio_cmd.subprocess, "run", lambda argv, **kw: _Result(_framed(payload)))
+ merged = json.loads(studio_cmd._probe_profile_proxy_defaults(["pwsh.exe"]))
+
+ assert merged == {
+ "Invoke-WebRequest:Proxy": "http://first.corp:8080",
+ "Invoke-RestMethod:Proxy": "http://rest.corp:8080",
+ }
+
+
+def test_a_wildcard_key_claims_the_whole_cmdlet_family(monkeypatch):
+ """The command half of a $PSDefaultParameterValues key may be a wildcard, and PowerShell
+ applies such an entry to every cmdlet it matches. Comparing the strings literally let
+ Invoke-Web*:Proxy from one host merge with Invoke-WebRequest:ProxyUseDefaultCredentials from
+ the other -- one invocation configured from two profiles, offering the user's Windows
+ credentials to a proxy whose own profile never asked for that."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ answers = {
+ "pwsh.exe": _framed('{"Invoke-Web*:Proxy": "http://seven.corp:8080"}'),
+ "powershell.exe": _framed(
+ '{"Invoke-WebRequest:ProxyUseDefaultCredentials": true,'
+ ' "Invoke-RestMethod:Proxy": "http://five.corp:8080"}'
+ ),
+ }
+ monkeypatch.setattr(studio_cmd.subprocess, "run", lambda argv, **kw: _Result(answers[argv[0]]))
+ merged = json.loads(studio_cmd._probe_profile_proxy_defaults(["pwsh.exe", "powershell.exe"]))
+
+ assert merged == {
+ "Invoke-Web*:Proxy": "http://seven.corp:8080",
+ # An unrelated family from the second host is still merged.
+ "Invoke-RestMethod:Proxy": "http://five.corp:8080",
+ }
+
+
+def test_two_wildcards_that_share_a_cmdlet_are_one_family(monkeypatch):
+ """Matching either pattern against the other as a STRING does not establish whether their
+ match sets overlap: Invoke-Web* and *-WebRequest both apply to Invoke-WebRequest and neither
+ matches the other. Overlap between two patterns is assumed, so the lower-priority profile
+ cannot slip ProxyUseDefaultCredentials in beside the other's proxy."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ answers = {
+ "pwsh.exe": _framed('{"Invoke-Web*:Proxy": "http://seven.corp:8080"}'),
+ "powershell.exe": _framed(
+ '{"*-WebRequest:ProxyUseDefaultCredentials": true,'
+ ' "Invoke-RestMethod:Proxy": "http://five.corp:8080"}'
+ ),
+ }
+ monkeypatch.setattr(studio_cmd.subprocess, "run", lambda argv, **kw: _Result(answers[argv[0]]))
+ merged = json.loads(studio_cmd._probe_profile_proxy_defaults(["pwsh.exe", "powershell.exe"]))
+
+ assert merged == {
+ "Invoke-Web*:Proxy": "http://seven.corp:8080",
+ "Invoke-RestMethod:Proxy": "http://five.corp:8080",
+ }
+
+
+def test_the_probe_re_pins_utf8_after_the_profiles_have_run():
+ """A profile setting [Console]::OutputEncoding is an ordinary customization and it
+ overrides the pin at the top of the probe. The parent decodes this stream as UTF-8, so a
+ profile that leaves the console on UTF-16 or a legacy code page corrupts the framed record
+ and a non-ASCII proxy URI goes with it."""
+ from unsloth_cli.commands.studio import _PS_PROXY_PROBE as probe
+
+ pin = "[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false"
+ assert probe.count(pin) == 2, "pinned before the profiles and again after them"
+ assert probe.index(pin) < probe.index("$__unslothProfile") < probe.rindex(pin)
+ assert probe.rindex(pin) < probe.index("ConvertTo-Json")
+
+
+def test_the_record_is_emitted_through_the_builtin_cmdlets():
+ """An alias or function named ConvertTo-Json or Write-Output in the profile shadows the bare
+ name, and clearing $PSDefaultParameterValues does not cover a command override. A wrapper
+ that reshapes the output produces a frame the reader cannot parse, which costs a standalone
+ update its only proxy."""
+ from unsloth_cli.commands.studio import _PS_PROXY_PROBE as probe
+
+ assert probe.count("Microsoft.PowerShell.Utility\\Write-Output") == 2
+ assert "Microsoft.PowerShell.Utility\\ConvertTo-Json -Compress" in probe
+ # No bare invocation left to be shadowed.
+ assert "; Write-Output " not in probe
+ assert "| ConvertTo-Json" not in probe
+
+
+def test_a_vscode_terminal_still_reads_its_own_host_profile():
+ """TERM_PROGRAM=vscode is set by EVERY VS Code integrated terminal, not only the PowerShell
+ extension's host. Substituting Microsoft.VSCode_profile.ps1 for the current-host profile
+ therefore missed the proxy a plain pwsh terminal in VS Code actually has, while applying an
+ unrelated one. Both are read, current-host last."""
+ from unsloth_cli.commands.studio import _PS_PROXY_PROBE as probe
+
+ assert "$__unslothProfiles += $PROFILE.CurrentUserCurrentHost; " in probe
+ assert "$__unslothProfiles += $PROFILE.AllUsersCurrentHost; " in probe
+ # The named host profile is an addition, never an else-branch replacement.
+ assert "} else { " not in probe.split("$out = @{}")[0]
+ assert probe.index("Split-Path -Parent $PROFILE.CurrentUserCurrentHost") < probe.index(
+ "$__unslothProfiles += $PROFILE.CurrentUserCurrentHost; "
+ )
+
+
+def test_the_probe_host_order_follows_the_console_the_user_typed_into(monkeypatch):
+ from unsloth_cli.commands import studio as studio_cmd
+
+ monkeypatch.setattr(studio_cmd.shutil, "which", lambda name: f"C:/{name}")
+
+ monkeypatch.setenv("PSModulePath", r"C:\Program Files\PowerShell\7\Modules")
+ assert studio_cmd._profile_probe_hosts()[0] == "pwsh.exe"
+
+ monkeypatch.setenv("PSModulePath", r"C:\Windows\System32\WindowsPowerShell\v1.0\Modules")
+ assert studio_cmd._profile_probe_hosts()[0] == "powershell.exe"
+
+ # A host that is not installed is not asked.
+ monkeypatch.setattr(
+ studio_cmd.shutil, "which", lambda name: None if name == "pwsh.exe" else "x"
+ )
+ assert studio_cmd._profile_probe_hosts() == ["powershell.exe"]
+
+
+def test_the_uv_alias_is_resolved_before_the_path_candidates():
+ """PowerShell resolves an alias ahead of PATH, so `uv` in a profile that aliases it means
+ that binary -- and checking PATH first made the alias branch unreachable on any machine
+ that also has some uv on PATH."""
+ src = INSTALL_PS1.read_text(encoding = "utf-8")
+ start = _locate(src, "function Get-UvExecutableCandidates {", "the uv resolver")
+ body = src[start : start + 2500]
+ alias = _locate(body, "Get-Command uv -CommandType Alias", "the alias lookup")
+ apps = _locate(body, "Get-Command uv -CommandType Application", "the PATH lookup")
+ assert alias < apps, "the PATH candidates are consulted before the alias"
+
+
[email protected](shutil.which("pwsh") is None, reason = "PowerShell is unavailable")
+def test_a_stale_alias_does_not_block_a_current_uv_on_path(tmp_path):
+ """Executed: the version gate walks EVERY candidate.
+
+ An alias pointing at a real but stale uv used to be the only binary ever probed, so a
+ current uv already on PATH -- or one winget had just installed -- could not rescue the
+ run, and the install ended at "uv could not be installed" on a machine that had one.
+ """
+ src = INSTALL_PS1.read_text(encoding = "utf-8")
+ gate = src[
+ _locate(src, " function Test-UvVersionOk {", "the version gate") : _locate(
+ src, " # Fallback for hosts without winget", "the end of the gate"
+ )
+ ]
+ script = (
+ "$UvMinVersion = '0.9.0'\n"
+ f"{gate}\n"
+ # Two candidates: a stale alias target first, a current one second.
+ "function Get-UvExecutableCandidates { @('stale', 'current') }\n"
+ "function Test-UvCandidateVersionShim { }\n"
+ "Write-Output ([string](Test-UvVersionOk))\n"
+ "Write-Output $script:UvExe\n"
+ )
+ # The candidates are invoked as executables, so stand in two shims that answer --version.
+ stale = tmp_path / "stale.ps1"
+ stale.write_text("Write-Output 'uv 0.4.30'", encoding = "utf-8")
+ current = tmp_path / "current.ps1"
+ current.write_text("Write-Output 'uv 0.12.1'", encoding = "utf-8")
+ script = script.replace(
+ "@('stale', 'current')",
+ f"@('{stale.as_posix()}', '{current.as_posix()}')",
+ )
+ result = subprocess.run(
+ [shutil.which("pwsh"), "-NoProfile", "-NonInteractive", "-Command", script],
+ capture_output = True,
+ text = True,
+ check = False,
+ )
+ lines = [line.strip() for line in result.stdout.splitlines() if line.strip()]
+ assert (
+ lines and lines[0] == "True"
+ ), f"the gate stopped at the stale alias: {result.stdout!r} {result.stderr!r}"
+ assert lines[-1].endswith("current.ps1"), "the passing candidate must be the pinned one"
+
+
+def test_the_parity_workflow_runs_when_the_studio_command_changes():
+ """The suite asserts unsloth_cli/commands/studio.py's behaviour directly, so a PR touching
+ only that module has to run it. No other workflow invokes this file."""
+ workflow = (
+ Path(__file__).resolve().parents[1]
+ / ".github"
+ / "workflows"
+ / "cross-platform-parity-ci.yml"
+ ).read_text(encoding = "utf-8")
+ assert (
+ workflow.count("unsloth_cli/commands/studio.py") == 2
+ ), "both the pull_request and push path filters need the module"
+
+
+def test_the_parity_job_installs_what_this_suite_imports():
+ """Three tests here import unsloth_cli.commands.studio, which pulls typer -> pyyaml ->
+ pydantic -> click. The job installed pip and pytest only, so on a clean setup-python it
+ died with ModuleNotFoundError before a single test ran, on both matrix legs."""
+ workflow = (
+ Path(__file__).resolve().parents[1]
+ / ".github"
+ / "workflows"
+ / "cross-platform-parity-ci.yml"
+ ).read_text(encoding = "utf-8")
+ install = [line for line in workflow.splitlines() if "pip install" in line and "pytest" in line]
+ assert install, "the parity job's install step was not found"
+ for package in ("typer", "pyyaml", "pydantic", "click", "rich"):
+ assert all(
+ package in line for line in install
+ ), f"the parity job does not install {package}, which this suite's imports need"
+
+
+def test_the_probe_output_is_decoded_lossily():
+ """The profile ran before the record was printed and may have said anything in any
+ encoding. `text=True` alone decodes with the locale codec and STRICT errors, so a UTF-8
+ banner on an ANSI console raised UnicodeDecodeError -- neither OSError nor
+ SubprocessError, so it escaped the handler and took the update down before the
+ -NoProfile child ever ran."""
+ import ast
+
+ tree = ast.parse(STUDIO_COMMAND.read_text(encoding = "utf-8"))
+ probe = next(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name == "_probe_profile_proxy_defaults"
+ )
+ runs = [
+ node
+ for node in ast.walk(probe)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "run"
+ ]
+ assert runs, "the probe no longer shells out"
+ for call in runs:
+ keywords = {kw.arg for kw in call.keywords}
+ assert "encoding" in keywords and "errors" in keywords, (
+ "a strict locale decode of the profile's own output can raise before the framing "
+ "is ever consulted"
+ )
+
+
+def test_a_non_ascii_banner_does_not_cost_the_proxy(monkeypatch):
+ # The decode is the parent's job, so this drives the extractor with the mangled text the
+ # lossy decode produces: the record is ASCII and has to survive whatever precedes it.
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ banner = "Bienvenue \ufffd\ufffd\ufffd chez Contoso\n"
+ noisy = _framed('{"invoke-webrequest:proxy": "http://proxy.corp:8080"}', banner = banner)
+ monkeypatch.setattr(studio_cmd.subprocess, "run", lambda argv, **kw: _Result(noisy))
+
+ merged = studio_cmd._probe_profile_proxy_defaults(["pwsh.exe"])
+ assert json.loads(merged) == {"invoke-webrequest:proxy": "http://proxy.corp:8080"}
+
+
+def test_the_setup_child_does_not_hand_the_proxy_secret_to_its_descendants():
+ """A profile proxy is routinely an authenticated URI (http://user:secret@proxy). The prelude
+ copies it into $PSDefaultParameterValues, which is NOT inherited -- but the environment
+ variable it read from is, so every native process setup.ps1 starts, and everything they
+ start in turn, saw the plaintext credential. It is removed the moment it has been read."""
+ from unsloth_cli.commands.studio import _PS_PROXY_DEFAULTS_PRELUDE
+
+ prelude = _PS_PROXY_DEFAULTS_PRELUDE
+ read_at = prelude.find("$env:_UNSLOTH_PS_PROXY_DEFAULTS")
+ removed_at = prelude.find("Remove-Item Env:_UNSLOTH_PS_PROXY_DEFAULTS")
+ assert read_at >= 0, "the prelude must still read the handoff"
+ assert removed_at > read_at, "and must clear it straight after reading it"
+ # Before anything that could start a child process -- i.e. before the defaults are applied,
+ # which is the last thing the prelude does.
+ assert removed_at < prelude.find("$PSDefaultParameterValues[$_.Name]")
+
+
+def test_the_probe_adds_the_callers_host_profile_beside_the_current_host_one(monkeypatch):
+ """pwsh.exe and powershell.exe run the CONSOLEHOST profile, so a caller in the VS Code
+ Integrated Console -- whose defaults live in Microsoft.VSCode_profile.ps1 -- got no proxy
+ and the -NoProfile child could not download.
+
+ Added beside the current-host profile, never in place of it: TERM_PROGRAM=vscode is set by
+ every VS Code integrated terminal, so substitution robbed a plain pwsh terminal there of the
+ only profile it has. Named hosts only, since a directory-wide sweep of
+ Microsoft.*_profile.ps1 ran profiles for hosts nobody was using."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ probe = studio_cmd._PS_PROXY_PROBE
+ assert "$env:_UNSLOTH_PS_HOST_PROFILE" in probe
+ assert "Microsoft.*_profile.ps1" not in probe, "no directory-wide sourcing"
+ # The two the caller's session would have loaded, named explicitly...
+ assert "$PROFILE.CurrentUserAllHosts" in probe
+ assert "CurrentUserCurrentHost" in probe
+ assert "Split-Path -Parent $PROFILE.CurrentUserCurrentHost" in probe
+ # ...and before the table is read, or it would snapshot the wrong defaults.
+ assert probe.find("_UNSLOTH_PS_HOST_PROFILE") < probe.find("$out = @{}")
+ # Unconditional and last, so the profile the probe's own host would have loaded is still
+ # there and still gets the final word on a key both of them set.
+ for scope in ("AllUsersCurrentHost", "CurrentUserCurrentHost"):
+ named = probe.find(f"Split-Path -Parent $PROFILE.{scope}")
+ plain = probe.find(f"$__unslothProfiles += $PROFILE.{scope};")
+ assert named >= 0, f"the caller's own host profile is named beside {scope}"
+ assert plain > named, f"{scope} is kept and runs after it"
+
+ # The caller's host is named from the environment it announces itself in.
+ monkeypatch.setenv("TERM_PROGRAM", "vscode")
+ assert studio_cmd._profile_probe_env()["_UNSLOTH_PS_HOST_PROFILE"] == (
+ "Microsoft.VSCode_profile.ps1"
+ )
+ # An unidentifiable host gets no extra profile rather than someone else's.
+ monkeypatch.setenv("TERM_PROGRAM", "Apple_Terminal")
+ assert "_UNSLOTH_PS_HOST_PROFILE" not in studio_cmd._profile_probe_env()
+ monkeypatch.delenv("TERM_PROGRAM", raising = False)
+ assert "_UNSLOTH_PS_HOST_PROFILE" not in studio_cmd._profile_probe_env()
+
+
+def test_the_probe_loads_the_all_users_profiles_in_startup_order():
+ """A machine-managed proxy lives in an all-users profile on a domain-joined box and the
+ user's own profile never mentions it, so sourcing only the current-user pair reported no
+ proxy on exactly the locked-down host that has one. Order is part of the fix: the user's
+ profile is entitled to override the machine's, which it only does if it runs last."""
+ from unsloth_cli.commands.studio import _PS_PROXY_PROBE as probe
+
+ assert "$PROFILE.AllUsersAllHosts" in probe
+ assert "Split-Path -Parent $PROFILE.AllUsersCurrentHost" in probe
+ assert (
+ probe.find("$PROFILE.AllUsersAllHosts")
+ < probe.find("$PROFILE.AllUsersCurrentHost")
+ < probe.find("$PROFILE.CurrentUserAllHosts")
+ < probe.find("$PROFILE.CurrentUserCurrentHost")
+ )
+ # Still the caller's own host, never a directory sweep, for the all-users pair too.
+ assert "Microsoft.*_profile.ps1" not in probe
+ assert probe.count("Join-Path (Split-Path -Parent") == 2
+
+
+def test_the_probe_clears_profile_defaults_before_it_serializes():
+ """The profile's $PSDefaultParameterValues aims at every cmdlet in the probe, including the
+ two that emit the record. ConvertTo-Json:AsArray = $true is a legitimate setting and it
+ turns the payload into a JSON array, which the reader rejects for not being a dictionary --
+ dropping the caller's proxy on the host that needed it. $out already holds copies."""
+ from unsloth_cli.commands.studio import _PS_PROXY_PROBE as probe
+
+ assert "$PSDefaultParameterValues = @{}" in probe
+ # After the table has been read, and before anything is written.
+ assert (
+ probe.find("$out = @{}")
+ < probe.find("$PSDefaultParameterValues = @{}")
+ < probe.find("ConvertTo-Json")
+ )
+
+
+def test_a_script_block_proxy_default_is_evaluated_not_dropped():
+ """{ [uri]$env:CORP_PROXY } is PowerShell's supported form for a dynamic default and
+ Invoke-WebRequest evaluates it per call, so the caller downloads fine while the handoff
+ silently omitted it. Both serializers evaluate the block and carry the RESULT -- executable
+ code must not cross into the child."""
+ from unsloth_cli.commands.studio import _PS_PROXY_PROBE
+
+ assert "[scriptblock]" in _PS_PROXY_PROBE
+ assert "& $v" in _PS_PROXY_PROBE, "the block has to be invoked, not serialized"
+ assert "$out[$k] = $r.AbsoluteUri" in _PS_PROXY_PROBE
+
+ installer = INSTALL_PS1.read_text(encoding = "utf-8")
+ assert "$_UnslothDefaultValue -is [scriptblock]" in installer
+ assert "& $_UnslothDefaultValue" in installer
+ assert "$_UnslothDefaultResolved.AbsoluteUri" in installer
+
+
+def test_an_installer_launch_with_no_proxy_still_skips_the_probe(monkeypatch):
+ """The ABSENCE of the handoff is how a standalone update is recognised. install.ps1 used to
+ remove the variable when it had no proxy, so an installer launch -- including one started
+ with -NoProfile or by the desktop app -- went off and reloaded the very profiles it had
+ deliberately discarded, reapplying a stale proxy during setup."""
+ installer = INSTALL_PS1.read_text(encoding = "utf-8")
+ handoff = installer[
+ installer.index("$previousProxyHandoff = $env:_UNSLOTH_PS_PROXY_DEFAULTS") :
+ ]
+ handoff = handoff[: handoff.index("try {")]
+ assert (
+ "Remove-Item Env:_UNSLOTH_PS_PROXY_DEFAULTS" not in handoff
+ ), "the installer must publish an explicit empty handoff, not remove the variable"
+ assert "'{}'" in handoff
+
+ # And the CLI keys on presence, so "{}" means "the installer looked, there is none".
+ source = STUDIO_COMMAND.read_text(encoding = "utf-8")
+ assert 'os.environ.get("_UNSLOTH_PS_PROXY_DEFAULTS") is None' in source
+
+
+def test_the_profile_probe_shares_one_timeout_across_hosts(monkeypatch):
+ """Both editions installed and both profiles hung meant two full timeouts back to back, so
+ every standalone setup stalled for twice the cost the helper documents."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ budget = 0.4
+ monkeypatch.setattr(studio_cmd, "_PROFILE_PROBE_TIMEOUT_SECONDS", budget)
+ asked: list[float] = []
+
+ def _hang(argv, **kwargs):
+ # A profile that really does hang burns the timeout it was given, which is what makes
+ # a per-host budget cost twice as much wall clock as the helper documents.
+ asked.append(kwargs["timeout"])
+ time.sleep(kwargs["timeout"])
+ raise subprocess.TimeoutExpired(argv, kwargs["timeout"])
+
+ monkeypatch.setattr(studio_cmd.subprocess, "run", _hang)
+ started = time.monotonic()
+ assert studio_cmd._probe_profile_proxy_defaults(["pwsh.exe", "powershell.exe"]) is None
+ elapsed = time.monotonic() - started
+ assert asked, "the probe must have been attempted"
+ # One budget for the whole probe, however many hosts it tries.
+ assert sum(asked) <= budget + 0.05, asked
+ assert elapsed < budget * 1.8, elapsed
+
+
+def test_the_probe_child_runs_with_no_profile(monkeypatch):
+ """Without -NoProfile the probe host loads its OWN ConsoleHost profile first: an unrelated
+ profile that prints, rewrites $PSDefaultParameterValues or calls exit got in the way, and it
+ is still not the profile a VS Code caller keeps its defaults in. With -NoProfile nothing has
+ run, and the profiles the caller's session would have loaded ($PROFILE.CurrentUserAllHosts
+ plus its host profile) are dot-sourced by name -- $PROFILE is fully populated under
+ -NoProfile because the paths are computed, not loaded."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ seen: list[list[str]] = []
+
+ def _capture(argv, **kwargs):
+ seen.append(list(argv))
+ raise OSError("no powershell here")
+
+ monkeypatch.setattr(studio_cmd.subprocess, "run", _capture)
+ studio_cmd._probe_profile_proxy_defaults(["pwsh.exe"])
+
+ assert seen, "the probe must have been attempted"
+ assert "-NoProfile" in seen[0]
+ # Ahead of -Command, like every other PowerShell child in the tree spells it.
+ assert seen[0].index("-NoProfile") < seen[0].index("-Command")
+
+
+def test_the_proxy_handoff_does_not_outlive_the_installer():
+ """Under the documented `irm ... | iex` path $script: IS the caller's session scope, so a
+ serialized authenticated proxy stayed readable in that console after the installer
+ returned. Cleanup near the setup child covers one exit out of dozens -- -ShortcutsOnly, an
+ argument error, lock contention, a failed dependency install all return earlier -- so the
+ value is held in a FUNCTION-local, which dies with the frame on every path."""
+ installer = INSTALL_PS1.read_text(encoding = "utf-8")
+
+ assert "$script:UnslothProxyHandoffJson" not in installer
+ assert "\n $UnslothProxyHandoffJson =\n" in installer
+ # Still dropped explicitly once the child it exists for has run.
+ cleared = "$UnslothProxyHandoffJson = $null"
+ assert cleared in installer
+ child = installer.index("& $UnslothExe @studioArgs")
+ assert child < installer.index(cleared, child)
+
+
+def test_the_installer_serializes_the_handoff_through_the_builtin():
+ """A profile alias or function named ConvertTo-Json would otherwise reshape this record or
+ throw out of the prologue, and setup then gets an empty proxy configuration on a host whose
+ only egress is that same profile proxy."""
+ installer = INSTALL_PS1.read_text(encoding = "utf-8")
+
+ assert "Microsoft.PowerShell.Utility\\ConvertTo-Json -Compress" in installer
+ prologue = _extract_prologue()
+ assert "| ConvertTo-Json" not in prologue
+
+
+def test_disjoint_wildcard_families_from_two_hosts_both_survive(monkeypatch):
+ """Assuming every wildcard pair overlaps threw away entries that provably cannot: a
+ higher-priority Start-Bits* dropped the other host's Invoke-Web*, so setup was left without
+ the proxy Invoke-WebRequest needs on a locked-down box."""
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ answers = {
+ "pwsh.exe": _framed('{"Start-Bits*:Proxy": "http://seven.corp:8080"}'),
+ "powershell.exe": _framed('{"Invoke-Web*:Proxy": "http://five.corp:8080"}'),
+ }
+ monkeypatch.setattr(studio_cmd.subprocess, "run", lambda argv, **kw: _Result(answers[argv[0]]))
+ merged = json.loads(studio_cmd._probe_profile_proxy_defaults(["pwsh.exe", "powershell.exe"]))
+
+ assert merged == {
+ "Start-Bits*:Proxy": "http://seven.corp:8080",
+ "Invoke-Web*:Proxy": "http://five.corp:8080",
+ }
+
+
+ ("left", "right", "overlaps"),
+ [
+ ("invoke-web*", "*-webrequest", True),
+ ("invoke-web*", "invoke-webrequest", True),
+ ("*", "invoke-webrequest", True),
+ ("invoke-?ebrequest", "invoke-webrequest", True),
+ ("invoke-web*", "invoke-restmethod", False),
+ ("start-bits*", "invoke-web*", False),
+ ("*-webrequest", "*-restmethod", False),
+ # A character class is assumed to overlap rather than decided: the conservative answer.
+ ("invoke-[wr]*", "start-bits*", True),
+ ],
+)
+def test_two_command_patterns_overlap_exactly_when_a_name_matches_both(left, right, overlaps):
+ from unsloth_cli.commands import studio as studio_cmd
+ assert studio_cmd._patterns_can_overlap(left, right) is overlaps
+ assert studio_cmd._patterns_can_overlap(right, left) is overlaps
+
+
+def _windows_probe_env(monkeypatch, host, module_path):
+ from unsloth_cli.commands import studio as studio_cmd
+
+ monkeypatch.setattr(studio_cmd.platform, "system", lambda: "Windows")
+ monkeypatch.setenv("SystemRoot", r"C:\Windows")
+ monkeypatch.setenv("PSModulePath", module_path)
+ return studio_cmd._profile_probe_env(host)
+
+
+_PS7_MODULE_PATH = (
+ r"C:\Users\me\Documents\PowerShell\Modules;"
+ r"C:\Program Files\PowerShell\7\Modules;"
+ r"C:\Windows\System32\WindowsPowerShell\v1.0\Modules"
+)
+_WINDOWS_PS_MODULES = r"C:\Windows\System32\WindowsPowerShell\v1.0\Modules"
+
+
+def test_the_windows_powershell_probe_is_given_its_own_modules_first(monkeypatch):
+ """PowerShell 7 strips its module paths only when IT launches powershell.exe. Through this
+ Python process the child kept them in front and loaded PS7 copies of 5.1's own modules, so a
+ profile importing one threw while it was dot-sourced and its proxy never reached setup."""
+ env = _windows_probe_env(monkeypatch, "powershell.exe", _PS7_MODULE_PATH)
+
+ entries = env["PSModulePath"].split(";")
+ assert entries[0] == _WINDOWS_PS_MODULES
+ # Reordered, not pruned: everything the caller had is still reachable, just second.
+ assert entries[1:] == _PS7_MODULE_PATH.split(";")[:2]
+ assert entries.count(_WINDOWS_PS_MODULES) == 1
+
+
+def test_a_module_path_already_led_by_windows_powershell_is_left_alone(monkeypatch):
+ already = _WINDOWS_PS_MODULES + r";C:\Program Files\PowerShell\7\Modules"
+ env = _windows_probe_env(monkeypatch, "powershell.exe", already)
+
+ assert env["PSModulePath"] == already
+
+
+def test_the_pwsh_probe_keeps_the_inherited_module_path(monkeypatch):
+ # PowerShell 7 prefixes its own paths at startup, so reordering here would only demote them.
+ env = _windows_probe_env(monkeypatch, "pwsh.exe", _PS7_MODULE_PATH)
+
+ assert env["PSModulePath"] == _PS7_MODULE_PATH
+
+
+def test_the_module_path_is_untouched_off_windows(monkeypatch):
+ from unsloth_cli.commands import studio as studio_cmd
+
+ monkeypatch.setattr(studio_cmd.platform, "system", lambda: "Linux")
+ monkeypatch.setenv("PSModulePath", _PS7_MODULE_PATH)
+
+ assert studio_cmd._profile_probe_env("powershell.exe")["PSModulePath"] == _PS7_MODULE_PATH
+
+
+def test_each_probed_host_gets_its_own_module_path(monkeypatch):
+ # The wiring: the repair is per host, so the env has to be built from the host being run.
+ from unsloth_cli.commands import studio as studio_cmd
+
+ class _Result:
+ def __init__(self, stdout):
+ self.stdout = stdout
+
+ seen: dict = {}
+
+ def _run(argv, **kwargs):
+ seen[argv[0]] = kwargs["env"]["PSModulePath"]
+ return _Result(_framed('{"Invoke-WebRequest:Proxy": "http://corp:8080"}'))
+
+ monkeypatch.setattr(studio_cmd.platform, "system", lambda: "Windows")
+ monkeypatch.setenv("SystemRoot", r"C:\Windows")
+ monkeypatch.setenv("PSModulePath", _PS7_MODULE_PATH)
+ monkeypatch.setattr(studio_cmd.subprocess, "run", _run)
+ studio_cmd._probe_profile_proxy_defaults(["pwsh.exe", "powershell.exe"])
+
+ assert seen["pwsh.exe"] == _PS7_MODULE_PATH
+ assert seen["powershell.exe"].split(";")[0] == _WINDOWS_PS_MODULES
diff --git a/tests/test_installer_system32_guard.py b/tests/test_installer_system32_guard.py
index 6abd35ddfe6..07608e28b79 100644
--- a/tests/test_installer_system32_guard.py
+++ b/tests/test_installer_system32_guard.py
@@ -35,7 +35,8 @@ def test_install_ps1_leaves_system_directory_before_installing():
guard_idx = src.index("$InSystemDir = Test-UnderSystemRoot $CurrentDir")
for marker in (
'step "winget" "available"',
- "uv venv $VenvDir --python",
+ # No "uv " prefix: the installer invokes the resolved $script:UvExe, not the bare token.
+ "venv $VenvDir --python",
'step "setup" "running unsloth studio setup..."',
):
assert guard_idx < src.index(marker), (
diff --git a/tests/test_studio_install_workspace_guard.py b/tests/test_studio_install_workspace_guard.py
index 711344cb67d..fad3ab616a0 100644
--- a/tests/test_studio_install_workspace_guard.py
+++ b/tests/test_studio_install_workspace_guard.py
@@ -336,7 +336,8 @@ def test_install_sh_writes_venv_marker_after_uv_venv():
def test_install_ps1_writes_venv_marker_after_uv_venv():
"""install.ps1 must write .unsloth-studio-owned into $VenvDir after `uv venv` succeeds."""
src = INSTALL_PS1.read_text(encoding = "utf-8")
- venv_create = src.index("uv venv $VenvDir --python")
+ # Anchored past the command token: uv is invoked as the resolved $script:UvExe.
+ venv_create = src.index("venv $VenvDir --python")
tail = src[venv_create : venv_create + 1500]
assert (
".unsloth-studio-owned" in tail
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 535a8d40cc6..a0bdc8eb583 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -2,6 +2,7 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import contextlib
+import functools
import importlib.util
import hashlib
import hmac
@@ -11,6 +12,7 @@ import platform
import re
import secrets
import shlex
+import shutil
import sqlite3
import subprocess
import sys
@@ -2819,6 +2821,328 @@ def _wait_for_windows_setup_process(process) -> int:
raise
+# -NoProfile below drops $PSDefaultParameterValues wholesale, and on a corporate host a profile
+# entry such as 'Invoke-WebRequest:Proxy' may be the only route to the VC++ runtime and the uv
+# installer setup.ps1 downloads. install.ps1 hands over the keys it kept; a standalone update
+# has no installer above it, so the probe below asks a short-lived PowerShell that DOES load
+# the profile.
+
+# Markers unlikely in a banner, and fixed so both sides agree.
+_PROXY_PROBE_BEGIN = "<<UNSLOTH_PROXY_DEFAULTS>>"
+_PROXY_PROBE_END = "<</UNSLOTH_PROXY_DEFAULTS>>"
+
+_PS_PROXY_PROBE = (
+ "$ErrorActionPreference = 'SilentlyContinue'; "
+ # Windows PowerShell 5.1 writes REDIRECTED output in the console code page while this
+ # process decodes UTF-8, so a non-ASCII proxy value came back with replacement characters,
+ # still parsed as JSON, and handed setup a proxy that does not work.
+ "try { [Console]::OutputEncoding = "
+ "New-Object System.Text.UTF8Encoding $false } catch { }; "
+ "try { $OutputEncoding = [Console]::OutputEncoding } catch { }; "
+ "$PSModuleAutoLoadingPreference = 'All'; "
+ # Launched -NoProfile, with the caller's profiles dot-sourced by name instead, because left
+ # to itself this process loads the CONSOLEHOST profile -- an unrelated host's for a caller
+ # in the VS Code console. $PROFILE is fully populated under -NoProfile (the paths are
+ # computed, not loaded), so naming them is exact.
+ "$__unslothHostProfileName = $env:_UNSLOTH_PS_HOST_PROFILE; "
+ # All-users first, PowerShell's own startup order: a machine-managed proxy lives in
+ # AllUsersAllHosts on a domain-joined box, and the user's profile only overrides it by
+ # running last.
+ "try { $__unslothProfiles = @($PROFILE.AllUsersAllHosts); "
+ # ONLY the caller's host profile, and only when the caller could be identified: sourcing
+ # every Microsoft.*_profile.ps1 in the directory ran profiles for hosts nobody was using,
+ # which can print, clobber $PSDefaultParameterValues, or exit before the record is written.
+ "if ($__unslothHostProfileName) { "
+ "$__unslothProfiles += (Join-Path (Split-Path -Parent $PROFILE.AllUsersCurrentHost) "
+ "$__unslothHostProfileName) }; "
+ "$__unslothProfiles += $PROFILE.AllUsersCurrentHost; "
+ "$__unslothProfiles += $PROFILE.CurrentUserAllHosts; "
+ # ADDED, never substituted: TERM_PROGRAM=vscode is set by every VS Code integrated terminal,
+ # not only the PowerShell extension's own host, so a plain pwsh terminal there loads
+ # Microsoft.PowerShell_profile.ps1 and substitution missed the proxy it actually has.
+ "if ($__unslothHostProfileName) { "
+ "$__unslothProfiles += (Join-Path (Split-Path -Parent $PROFILE.CurrentUserCurrentHost) "
+ "$__unslothHostProfileName) }; "
+ # Current-host profile LAST.
+ "$__unslothProfiles += $PROFILE.CurrentUserCurrentHost; "
+ "foreach ($__unslothProfile in ($__unslothProfiles | Select-Object -Unique)) { "
+ "if ($__unslothProfile -and (Test-Path -LiteralPath $__unslothProfile -PathType Leaf)) { "
+ "try { . $__unslothProfile } catch { } } } } catch { }; "
+ # Re-pinned, because setting [Console]::OutputEncoding is an ordinary profile customization
+ # that overrides the pin above. The parent decodes this stream as UTF-8, so a console left
+ # on a legacy code page corrupts the framed record and the proxy URI with it.
+ "try { [Console]::OutputEncoding = "
+ "New-Object System.Text.UTF8Encoding $false } catch { }; "
+ "try { $OutputEncoding = [Console]::OutputEncoding } catch { }; "
+ "$out = @{}; "
+ "foreach ($k in @($PSDefaultParameterValues.Keys)) { "
+ "if ($k -is [string] -and [regex]::IsMatch($k, ':Proxy(Credential|UseDefaultCredentials)?$', "
+ "[System.Text.RegularExpressions.RegexOptions]::IgnoreCase)) { "
+ "$v = $PSDefaultParameterValues[$k]; "
+ "if ($v -is [uri]) { $out[$k] = $v.AbsoluteUri } "
+ "elseif ($v -is [string] -or $v -is [bool]) { $out[$k] = $v } "
+ # A script block is the supported form for a DYNAMIC default -- e.g.
+ # { [uri]$env:CORP_PROXY } -- evaluated per call by Invoke-WebRequest. Evaluate here and
+ # serialize the RESULT: executable code must not cross the handoff.
+ "elseif ($v -is [scriptblock]) { try { $r = & $v; "
+ "if ($r -is [uri]) { $out[$k] = $r.AbsoluteUri } "
+ "elseif ($r -is [string] -or $r -is [bool]) { $out[$k] = $r } } catch { } } } }; "
+ # $out already holds copies, so the profile's table is now only a hazard:
+ # ConvertTo-Json:AsArray = $true is a legitimate setting that turns this record into a JSON
+ # array, which the reader rejects for not being a dictionary.
+ "$PSDefaultParameterValues = @{}; "
+ # FRAMED, not bare: the profile is free to print a banner or a MOTD, and that output
+ # arriving ahead of the JSON made the parse throw. Module-qualified, as with the uv lookup:
+ # an alias named ConvertTo-Json or Write-Output would otherwise reshape the frame.
+ f"if ($out.Count -gt 0) {{ "
+ f"Microsoft.PowerShell.Utility\\Write-Output '{_PROXY_PROBE_BEGIN}'; "
+ f"$out | Microsoft.PowerShell.Utility\\ConvertTo-Json -Compress; "
+ f"Microsoft.PowerShell.Utility\\Write-Output '{_PROXY_PROBE_END}' }}"
+)
+
+
+# What the CALLER's host names its own CurrentUserCurrentHost profile, when we can tell. An
+# unidentifiable host gets no extra profile rather than someone else's.
+_HOST_PROFILE_BY_TERM_PROGRAM = {"vscode": "Microsoft.VSCode_profile.ps1"}
+
+
+def _caller_host_profile_name() -> Optional[str]:
+ term_program = (os.environ.get("TERM_PROGRAM") or "").strip().casefold()
+ return _HOST_PROFILE_BY_TERM_PROGRAM.get(term_program)
+
+
+# Windows PowerShell's own module directory, under %SystemRoot%.
+_WINDOWS_PS_MODULE_DIR = r"System32\WindowsPowerShell\v1.0\Modules"
+_WINDOWS_PS_HOSTS = frozenset({"powershell.exe", "powershell", "powershell_ise.exe"})
+
+
+def _fold_module_entry(entry: str) -> str:
+ """A PSModulePath entry reduced to a comparable form (separator and case insensitive)."""
+ return entry.replace("/", "\\").rstrip("\\").casefold()
+
+
+def _windows_powershell_module_path(current: str) -> Optional[str]:
+ """``current`` with Windows PowerShell's own module directory first, or None to leave it be.
+
+ PowerShell 7 strips its module paths only when IT launches powershell.exe, so reached through
+ this Python process the child keeps them in FRONT and resolves 5.1's own modules to the
+ PowerShell 7 copies. A profile that imports one then throws while it is dot-sourced and the
+ proxy it was going to publish is lost. Same repair as install.ps1, applied per probed host:
+ pwsh needs none, because PowerShell 7 prefixes its own paths on startup."""
+ root = os.environ.get("SystemRoot")
+ if not root:
+ return None
+ own = root.rstrip("\\/") + "\\" + _WINDOWS_PS_MODULE_DIR
+ entries = [entry for entry in current.split(";") if entry.strip()]
+ if entries and _fold_module_entry(entries[0]) == _fold_module_entry(own):
+ return None
+ kept = [e for e in entries if _fold_module_entry(e) != _fold_module_entry(own)]
+ return ";".join([own] + kept)
+
+
+def _profile_probe_env(host: str = "") -> dict:
+ """The probe child's environment: the caller's host profile when it is known, and the probed
+ host's own module precedence."""
+ env = dict(os.environ)
+ name = _caller_host_profile_name()
+ if name:
+ env["_UNSLOTH_PS_HOST_PROFILE"] = name
+ else:
+ env.pop("_UNSLOTH_PS_HOST_PROFILE", None)
+ if platform.system() == "Windows" and _fold_module_entry(host).rsplit("\\", 1)[-1] in (
+ _WINDOWS_PS_HOSTS
+ ):
+ reordered = _windows_powershell_module_path(env.get("PSModulePath", ""))
+ if reordered:
+ env["PSModulePath"] = reordered
+ return env
+
+
+def _framed_probe_record(stdout: str) -> Optional[str]:
+ """The JSON between the markers, or None. Tolerates anything the profile printed."""
+ start = stdout.find(_PROXY_PROBE_BEGIN)
+ if start < 0:
+ return None
+ start += len(_PROXY_PROBE_BEGIN)
+ end = stdout.find(_PROXY_PROBE_END, start)
+ if end < 0:
+ return None
+ return stdout[start:end].strip() or None
+
+
+def _profile_probe_hosts() -> list[str]:
+ r"""The PowerShell hosts whose profile to ask, most likely caller first.
+
+ The two editions keep SEPARATE profiles, so both are asked and the caller's edition goes
+ first, its value winning on merge.
+
+ The caller is inferred from PSModulePath, which every host exports: Windows PowerShell's
+ points at ``...\WindowsPowerShell\v1.0\Modules`` and pwsh's at ``...\PowerShell\7\Modules``.
+ By ORDER, not by absence, since a machine can have both trees on PSModulePath at once and
+ each host puts its OWN module directory first. Neither present, or both at the same
+ position: keep the default order rather than guess.
+ """
+ hosts = ["pwsh.exe", "powershell.exe"]
+ module_path = os.environ.get("PSModulePath", "").lower()
+ windows_at = module_path.find("windowspowershell")
+ seven_at = module_path.find("powershell\\7")
+ if windows_at >= 0 and (seven_at < 0 or windows_at < seven_at):
+ hosts = ["powershell.exe", "pwsh.exe"]
+ return [host for host in hosts if shutil.which(host)]
+
+
+# Annotations below are quoted: this module has no `from __future__ import annotations`, and on
+# Python 3.9 evaluating `str | list[str]` at def time raises TypeError, taking the CLI import
+# with it.
+
+# The whole profile probe's budget, shared across however many hosts are tried.
+_PROFILE_PROBE_TIMEOUT_SECONDS = 20.0
+
+
+def _probe_profile_proxy_defaults(powershell: "str | list[str]") -> Optional[str]:
+ """The caller's profile proxy defaults as JSON, or None.
+
+ install.ps1 hands these over in the environment, but a standalone `unsloth studio update`
+ has no installer above it and a PowerShell variable does not reach this Python process. So
+ ask for it, in a throwaway process whose only job is to print the table.
+
+ Several hosts may be given: their answers are MERGED, earlier hosts winning per key.
+
+ Best effort. A slow, interactive or broken profile costs one timeout and the child proceeds
+ as it does today."""
+ hosts = [powershell] if isinstance(powershell, str) else list(powershell)
+ # ONE budget for the whole probe, not one per host: with both editions installed, two hung
+ # profiles would otherwise stall every standalone update for twice the stated cost.
+ deadline = time.monotonic() + _PROFILE_PROBE_TIMEOUT_SECONDS
+ merged: dict = {}
+ # $PSDefaultParameterValues keys are case-INSENSITIVE, so "Invoke-WebRequest:Proxy" and
+ # "invoke-webrequest:proxy" are one entry to PowerShell and two to a Python dict. Only the
+ # first spelling seen is handed on, or the prelude would replay both and let the
+ # lower-priority host's land last.
+ claimed: dict = {}
+ seen_keys: set = set()
+ for host in hosts:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ try:
+ probe = subprocess.run(
+ [
+ host,
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-Command",
+ _PS_PROXY_PROBE,
+ ],
+ env = _profile_probe_env(host),
+ capture_output = True,
+ text = True,
+ # text=True alone decodes with the locale codec and STRICT errors, so a UTF-8
+ # profile banner on an ANSI console raised UnicodeDecodeError -- neither
+ # OSError nor SubprocessError, so it escaped the handler below and took the
+ # update down.
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = remaining,
+ **_windows_hidden_subprocess_kwargs(),
+ )
+ except (OSError, subprocess.SubprocessError):
+ continue
+ payload = _framed_probe_record(probe.stdout or "")
+ if not payload:
+ continue
+ try:
+ # Validated, not trusted: the framing finds the record, this confirms it is one, so
+ # nothing hands the child a string ConvertFrom-Json throws on.
+ parsed = json.loads(payload)
+ except ValueError:
+ continue
+ if not isinstance(parsed, dict) or not parsed:
+ continue
+ # Per CMDLET, not per key: pairing the earlier host's Proxy with the later host's
+ # ProxyUseDefaultCredentials would offer the user's Windows credentials to a proxy whose
+ # own profile never asked for that. A cmdlet is claimed whole by the first host.
+ for key, value in parsed.items():
+ if not isinstance(key, str):
+ continue
+ cmdlet = key.split(":", 1)[0].casefold()
+ folded = key.casefold()
+ if _cmdlet_claimed_elsewhere(cmdlet, claimed, parsed):
+ continue
+
+ if folded in seen_keys:
+ continue
+ claimed[cmdlet] = parsed
+ seen_keys.add(folded)
+ merged[key] = value
+ if not merged:
+ return None
+ return json.dumps(merged)
+
+
+def _cmdlet_claimed_elsewhere(cmdlet: str, claimed: dict, source: object) -> bool:
+ """Whether another host already owns the cmdlet family ``cmdlet`` belongs to.
+
+ A literal comparison is not enough: the command half of a $PSDefaultParameterValues key may
+ be a wildcard, and PowerShell applies such an entry to every cmdlet it matches. Overlap in
+ either direction claims the family.
+ """
+ for owned, owner in claimed.items():
+ if owner is source:
+ continue
+ if owned == cmdlet or _patterns_can_overlap(cmdlet, owned):
+ return True
+ return False
+
+
[email protected]_cache(maxsize = 512)
+def _patterns_can_overlap(left: str, right: str) -> bool:
+ """Whether any command name matches BOTH wildcard patterns.
+
+ Two patterns can share matches without either matching the other as a STRING (Invoke-Web* and
+ *-WebRequest both apply to Invoke-WebRequest), so the languages are intersected rather than
+ string-matched -- otherwise a host's Start-Bits* entry swallowed the other host's unrelated
+ Invoke-Web* one. A character class is not decided, only assumed to overlap: that is the
+ conservative answer, and no cmdlet name is written that way.
+ """
+ if "[" in left or "[" in right:
+ return True
+
+ @functools.lru_cache(maxsize = None)
+ def walk(i: int, j: int) -> bool:
+ # Both patterns are consumed in step, except at a '*', which may absorb one more
+ # character from the other side or match nothing at all.
+ if i == len(left):
+ return all(char == "*" for char in right[j:])
+ if j == len(right):
+ return all(char == "*" for char in left[i:])
+ here, there = left[i], right[j]
+ if here == "*":
+ return walk(i + 1, j) or walk(i, j + 1)
+ if there == "*":
+ return walk(i, j + 1) or walk(i + 1, j)
+ if here == "?" or there == "?" or here == there:
+ return walk(i + 1, j + 1)
+ return False
+
+ return walk(0, 0)
+
+
+_PS_PROXY_DEFAULTS_PRELUDE = (
+ "$__unslothProxyDefaults = $env:_UNSLOTH_PS_PROXY_DEFAULTS; "
+ # Read once, then GONE from the environment: a profile proxy can carry credentials
+ # (http://user:secret@proxy is the ordinary corporate form) and every native process setup
+ # starts would otherwise inherit it. Needed only by this session's
+ # $PSDefaultParameterValues, which is not inherited.
+ "Remove-Item Env:_UNSLOTH_PS_PROXY_DEFAULTS -ErrorAction SilentlyContinue; "
+ "if ($__unslothProxyDefaults) { try { "
+ "(ConvertFrom-Json $__unslothProxyDefaults).PSObject.Properties | ForEach-Object { "
+ "$PSDefaultParameterValues[$_.Name] = $_.Value } } catch { } }; "
+)
+
+
def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None) -> None:
"""Find and run the studio setup/update script."""
script = _find_setup_script(repo_root)
@@ -2836,10 +3160,19 @@ def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None
if platform.system() == "Windows":
powershell_args = ["powershell.exe"]
+ # PRESENCE, not truthiness: install.ps1 publishes this around the handoff and sets it to
+ # "{}" when it found no proxy, so treating that as "nobody handed anything over" would
+ # send an installer launch off to reload the profiles it deliberately discarded.
+ if os.environ.get("_UNSLOTH_PS_PROXY_DEFAULTS") is None:
+ probed = _probe_profile_proxy_defaults(_profile_probe_hosts() or ["powershell.exe"])
+ if probed:
+ env = {**(env or os.environ), "_UNSLOTH_PS_PROXY_DEFAULTS": probed}
+ # -NoProfile unconditionally, not just on the hidden branch: install.ps1 hands off to
+ # exactly here from a console where stdout is a tty, so the hidden branch does not fire
+ # and a profile that aliases uv or python would break setup.ps1.
+ powershell_args.append("-NoProfile")
if _should_hide_windows_subprocesses():
- powershell_args.extend(
- ["-NoLogo", "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden"]
- )
+ powershell_args.extend(["-NoLogo", "-NonInteractive", "-WindowStyle", "Hidden"])
# Use -Command + `*>&1` (not -File) so setup.ps1's Write-Host output
# (Information stream #6) merges into stdout. -File drops it when
# stdout is a pipe, e.g. `unsloth studio update --local 2>&1 | tee`.
@@ -2850,7 +3183,7 @@ def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None
"-ExecutionPolicy",
"Bypass",
"-Command",
- f"& '{script_pwsh_literal}' *>&1",
+ f"{_PS_PROXY_DEFAULTS_PRELUDE}& '{script_pwsh_literal}' *>&1",
]
)
# Explicitly hand std handles to the child so CI tee sees setup.ps1's
@@ -2904,8 +3237,11 @@ def _refresh_desktop_shortcuts(*, verbose: bool = False) -> None:
if is_windows:
ps_argv: list[str] = ["powershell.exe"]
+ # -NoProfile unconditionally, as in _run_setup_script above: gating it on the hidden
+ # branch left the visible console path, where a profile is exactly what IS loaded.
+ ps_argv.append("-NoProfile")
if _should_hide_windows_subprocesses():
- ps_argv.extend(["-NoLogo", "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden"])
+ ps_argv.extend(["-NoLogo", "-NonInteractive", "-WindowStyle", "Hidden"])
for script in candidates:
try: