Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: route every Windows installer line through the UTF-8 stdout sink (#8148)

Daniel Han07df95079ef0
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.yml
index ae455f42ca9..8fa8a36ce69 100644
--- a/.github/workflows/cross-platform-parity-ci.yml
+++ b/.github/workflows/cross-platform-parity-ci.yml
@@ -16,6 +16,14 @@
# the same scripts, refusing new yes/no questions (see #7016, reverted in #8040).
# Its paths are globbed, since a newly named installer has to trigger the very
# check that refuses to let it land unregistered.
+#
+# The setup-output encoding tests ride along for the same reason again, and it is
+# the sharpest case of it: they spawn install.ps1's and setup.ps1's own banner
+# under Windows PowerShell 5.1 with the flags and the CREATE_NO_WINDOW the
+# desktop app uses, so on Linux they either skip or fall back to pwsh 7, which is
+# UTF-8 by default and cannot reproduce anything. Backend CI already collects
+# that file on ubuntu, which covers its source contracts; this row is the only
+# place its byte-level half means something.
name: Cross-platform parity
@@ -51,6 +59,7 @@ on:
- 'studio/backend/requirements/single-env/patch_metadata.py'
- 'tests/python/test_cross_platform_parity.py'
- 'tests/python/test_windows_python_venv_hardening.py'
+ - 'tests/python/test_windows_setup_output_encoding.py'
- 'tests/sh/test_install_rollback_lifecycle.sh'
- 'tests/studio/test_install_rollback_lifecycle.ps1'
- 'tests/studio/test_intel_registry_fallback.ps1'
@@ -94,6 +103,7 @@ on:
- 'studio/backend/requirements/single-env/patch_metadata.py'
- 'tests/python/test_cross_platform_parity.py'
- 'tests/python/test_windows_python_venv_hardening.py'
+ - 'tests/python/test_windows_setup_output_encoding.py'
- 'tests/sh/test_install_rollback_lifecycle.sh'
- 'tests/studio/test_install_rollback_lifecycle.ps1'
- 'tests/studio/test_intel_registry_fallback.ps1'
@@ -158,6 +168,8 @@ jobs:
python-version: '3.12'
cache: 'pip'
- run: python -m pip install -U pip pytest
+ # -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
env:
UNSLOTH_NO_TORCH: '1'
@@ -165,10 +177,11 @@ jobs:
python -m pytest
tests/python/test_cross_platform_parity.py
tests/python/test_windows_python_venv_hardening.py
+ tests/python/test_windows_setup_output_encoding.py
tests/test_installer_skip_autostart.py
tests/test_installer_system32_guard.py
tests/test_installer_interactive_prompts.py
- -q
+ -q -rs
- name: PowerShell rollback lifecycle tests
if: runner.os == 'Windows'
shell: pwsh
diff --git a/.github/workflows/studio-windows-api-smoke.yml b/.github/workflows/studio-windows-api-smoke.yml
index 5dd6ea2d3b3..725968540c4 100644
--- a/.github/workflows/studio-windows-api-smoke.yml
+++ b/.github/workflows/studio-windows-api-smoke.yml
@@ -154,17 +154,18 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # *>&1 captures Write-Host (Information stream) output;
- # plain 2>&1 does not. setup.ps1 emits "prebuilt installed
- # and validated" via Write-Host, and we grep for that.
- $ProgressPreference = 'SilentlyContinue'
- & ./install.ps1 --local --no-torch *>&1 | Tee-Object -FilePath logs/install.log
+ # install.ps1 runs as a CHILD process so its stdout is pipeline
+ # input; in-process its Write-StudioLine output goes straight to
+ # [Console]::Out and skips Tee-Object. See studio-windows-ui-smoke.yml
+ # for the full explanation.
+ $child = '$ErrorActionPreference = ''Stop''; $ProgressPreference = ''SilentlyContinue''; & ./install.ps1 --local --no-torch; exit $LASTEXITCODE'
+ pwsh -NoProfile -ExecutionPolicy Bypass -Command $child 2>&1 | Tee-Object -FilePath logs/install.log
+ if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
run: |
- # Filesystem-based check (setup.ps1's stream output isn't
- # captured back through this parent step's pipeline; see
- # studio-windows-ui-smoke.yml for full explanation).
+ # Filesystem-based check: it does not depend on which process
+ # emitted a marker (see studio-windows-ui-smoke.yml).
LLAMA_DIR=~/.unsloth/llama.cpp
INFO="$LLAMA_DIR/UNSLOTH_PREBUILT_INFO.json"
BIN="$LLAMA_DIR/build/bin/Release/llama-server.exe"
diff --git a/.github/workflows/studio-windows-inference-smoke.yml b/.github/workflows/studio-windows-inference-smoke.yml
index 5dadf15b4ce..50b733673cb 100644
--- a/.github/workflows/studio-windows-inference-smoke.yml
+++ b/.github/workflows/studio-windows-inference-smoke.yml
@@ -199,18 +199,20 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # *>&1 captures Write-Host (Information stream) output;
- # plain 2>&1 does not. setup.ps1 emits "prebuilt installed
- # and validated" via Write-Host, and we grep for that.
- $ProgressPreference = 'SilentlyContinue'
- & ./install.ps1 --local --no-torch *>&1 | Tee-Object -FilePath logs/install.log
+ # install.ps1 runs as a CHILD process so its stdout is pipeline
+ # input; in-process its Write-StudioLine output goes straight to
+ # [Console]::Out and skips Tee-Object. See studio-windows-ui-smoke.yml
+ # for the full explanation.
+ $child = '$ErrorActionPreference = ''Stop''; $ProgressPreference = ''SilentlyContinue''; & ./install.ps1 --local --no-torch; exit $LASTEXITCODE'
+ pwsh -NoProfile -ExecutionPolicy Bypass -Command $child 2>&1 | Tee-Object -FilePath logs/install.log
+ if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
id: assert-prebuilt
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
timeout-minutes: 5
run: |
- # Filesystem check; setup.ps1's stream output isn't captured.
+ # Filesystem check: it does not depend on which process emitted a marker.
LLAMA_DIR=~/.unsloth/llama.cpp
INFO="$LLAMA_DIR/UNSLOTH_PREBUILT_INFO.json"
BIN="$LLAMA_DIR/build/bin/Release/llama-server.exe"
@@ -1583,8 +1585,14 @@ jobs:
${env:ProgramFiles(x86)} = $env:NO_BUILD_TOOLS_PROGRAMFILES_X86
$env:Path = $env:NO_BUILD_TOOLS_PATH
New-Item -ItemType Directory -Force -Path logs | Out-Null
- $ProgressPreference = 'SilentlyContinue'
- & ./install.ps1 --local --no-torch *>&1 | Tee-Object -FilePath logs/install.log
+ # Child process, so install.ps1's own lines reach logs/install.log
+ # (see the shared install step above). The $env: overrides set
+ # immediately above are environment variables, so the child inherits
+ # them; $ProgressPreference is a preference variable and does not,
+ # which is why this passes -Command rather than -File.
+ $child = '$ErrorActionPreference = ''Stop''; $ProgressPreference = ''SilentlyContinue''; & ./install.ps1 --local --no-torch; exit $LASTEXITCODE'
+ pwsh -NoProfile -ExecutionPolicy Bypass -Command $child 2>&1 | Tee-Object -FilePath logs/install.log
+ if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }
- name: Assert prebuilt used AND no build tools were installed
run: |
@@ -2015,13 +2023,15 @@ jobs:
. (Join-Path $env:GITHUB_WORKSPACE 'tests/studio_setup_ps1/Get-FunctionSource.ps1')
$setup = Join-Path $env:GITHUB_WORKSPACE 'studio/setup.ps1'
# Dot-source the guard + the logging closure it reaches
- # (step/substep -> Write-StudioStdoutMirror / Get-StudioAnsi).
+ # (step/substep -> Write-StudioStdoutMirror / Get-StudioAnsi, and
+ # Ensure-VCRedist -> Write-StudioLine).
$script:StudioVtOk = $false
$script:UnslothVerbose = $false
# Get-HostMachineArch is reached only on the absent path, where
# Test-VCRedistInstalled consults it before trusting the System32 DLL, so
# part A passes without it and only the clean-box part fails.
- foreach ($fn in @('Get-StudioAnsi', 'Write-StudioStdoutMirror', 'step', 'substep',
+ foreach ($fn in @('Get-StudioAnsi', 'Write-StudioLine', 'Write-StudioStdoutMirror',
+ 'step', 'substep',
'Invoke-SetupCommand', 'Refresh-Environment', 'Get-HostMachineArch',
'Test-VCRedistInstalled', 'Ensure-VCRedist')) {
$src = Get-FunctionSource -Path $setup -Name $fn
diff --git a/.github/workflows/studio-windows-ui-smoke.yml b/.github/workflows/studio-windows-ui-smoke.yml
index 73017d1057e..dcfc32a2cbd 100644
--- a/.github/workflows/studio-windows-ui-smoke.yml
+++ b/.github/workflows/studio-windows-ui-smoke.yml
@@ -185,27 +185,28 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # *>&1 redirects ALL PowerShell streams (stdout, stderr,
- # warning, verbose, debug, information) into the success
- # stream so Tee-Object captures everything. install.ps1
- # and setup.ps1 emit step/substep markers via Write-Host
- # which lands on the Information stream (PS 5+); without
- # the wildcard redirect, those markers (including
- # "prebuilt installed and validated") never reach
- # logs/install.log and the post-step grep asserter fails.
- $ProgressPreference = 'SilentlyContinue'
- & ./install.ps1 --local --no-torch *>&1 | Tee-Object -FilePath logs/install.log
+ # install.ps1 runs as a CHILD process, not in-process. Its own
+ # lines now go to [Console]::Out (Write-StudioLine), not the
+ # Information stream, so an in-process `*>&1 | Tee-Object` would
+ # put them on the step log and never in logs/install.log. As a
+ # native command its stdout IS the pipeline, and the setup.ps1
+ # grandchild inherits that handle, so its markers land in the log
+ # too -- they used to bypass Tee-Object entirely.
+ # -Command rather than -File: $ProgressPreference is a preference
+ # variable, so it does not cross a process boundary on its own.
+ $child = '$ErrorActionPreference = ''Stop''; $ProgressPreference = ''SilentlyContinue''; & ./install.ps1 --local --no-torch; exit $LASTEXITCODE'
+ pwsh -NoProfile -ExecutionPolicy Bypass -Command $child 2>&1 | Tee-Object -FilePath logs/install.log
+ if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
run: |
- # install.ps1's setup.ps1 child writes "prebuilt installed
- # and validated" to its own console host -- that output
- # does NOT come back through this parent step's stdout
- # pipeline (no matter how aggressively we redirect: *>&1,
- # tee, etc.). Verify the install via the filesystem
- # instead. setup.ps1 writes UNSLOTH_PREBUILT_INFO.json
- # next to the install dir on success, and lays the
- # binaries under build/bin/Release/ on Windows.
+ # The filesystem is the authority here: setup.ps1's "prebuilt
+ # installed and validated" reaches logs/install.log only because
+ # install.ps1 is spawned as a child process, and a marker that
+ # depends on process topology is a weak thing to gate on.
+ # setup.ps1 writes UNSLOTH_PREBUILT_INFO.json next to the install
+ # dir on success, and lays the binaries under build/bin/Release/
+ # on Windows.
STUDIO_HOME=~/.unsloth/studio
LLAMA_DIR=~/.unsloth/llama.cpp
INFO="$LLAMA_DIR/UNSLOTH_PREBUILT_INFO.json"
diff --git a/.github/workflows/studio-windows-update-smoke.yml b/.github/workflows/studio-windows-update-smoke.yml
index 616a4e1bc16..7964badffdc 100644
--- a/.github/workflows/studio-windows-update-smoke.yml
+++ b/.github/workflows/studio-windows-update-smoke.yml
@@ -168,16 +168,18 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # *>&1 captures Write-Host (Information stream) output;
- # plain 2>&1 does not. setup.ps1 emits "prebuilt installed
- # and validated" via Write-Host, and we grep for that.
- $ProgressPreference = 'SilentlyContinue'
- & ./install.ps1 --local --no-torch *>&1 | Tee-Object -FilePath logs/install.log
+ # install.ps1 runs as a CHILD process so its stdout is pipeline
+ # input; in-process its Write-StudioLine output goes straight to
+ # [Console]::Out and skips Tee-Object. See studio-windows-ui-smoke.yml
+ # for the full explanation.
+ $child = '$ErrorActionPreference = ''Stop''; $ProgressPreference = ''SilentlyContinue''; & ./install.ps1 --local --no-torch; exit $LASTEXITCODE'
+ pwsh -NoProfile -ExecutionPolicy Bypass -Command $child 2>&1 | Tee-Object -FilePath logs/install.log
+ if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
run: |
- # Filesystem-based check (setup.ps1's stream output isn't
- # captured back through the parent pipeline).
+ # Filesystem-based check: it does not depend on which process
+ # emitted a marker.
LLAMA_DIR=~/.unsloth/llama.cpp
INFO="$LLAMA_DIR/UNSLOTH_PREBUILT_INFO.json"
BIN="$LLAMA_DIR/build/bin/Release/llama-server.exe"
diff --git a/install.ps1 b/install.ps1
index c1a38e83c35..3b2e1ab54a7 100644
--- a/install.ps1
+++ b/install.ps1
@@ -69,11 +69,37 @@ function Install-UnslothStudio {
$env:PYTHONUTF8 = '1'
$env:PYTHONIOENCODING = 'utf-8'
+ # Resolved once: it picks the output sink in Write-StudioLine and must not
+ # change mid-run. Same probe as studio/setup.ps1.
+ $script:StudioStdoutRedirected = $false
+ try { $script:StudioStdoutRedirected = [Console]::IsOutputRedirected } catch { }
+
+ # Write-Host is written by 5.1's console host with its own writer on the OEM
+ # code page, not the UTF-8 [Console]::Out rebound above. The desktop app
+ # spawns this script with CREATE_NO_WINDOW and decodes the pipe as UTF-8
+ # (from_utf8_lossy, studio/src-tauri/src/install.rs), so the banner emoji,
+ # the U+2500 rule and every warning arrived as U+FFFD. One sink instead: the
+ # console handle when redirected, Write-Host when interactive, since it is
+ # the only one that colorizes. Defined above the first write, for the same
+ # ordering reason as the encoding block.
+ function Write-StudioLine {
+ param([string]$Message = "", [string]$ForegroundColor)
+ if ($script:StudioStdoutRedirected) {
+ try { [Console]::Out.WriteLine($Message); [Console]::Out.Flush() } catch {}
+ return
+ }
+ if ($PSBoundParameters.ContainsKey('ForegroundColor')) {
+ Write-Host $Message -ForegroundColor $ForegroundColor
+ } else {
+ Write-Host $Message
+ }
+ }
+
# ── Tauri structured output ──
function Write-TauriLog {
param([string]$Tag, [string]$Message)
if ($TauriMode) {
- Write-Host "[TAURI:$Tag] $Message"
+ Write-StudioLine "[TAURI:$Tag] $Message"
}
}
@@ -195,7 +221,7 @@ function Install-UnslothStudio {
"--package" {
$i++
if ($i -ge $argList.Count) {
- Write-Host "[ERROR] --package requires an argument." -ForegroundColor Red
+ Write-StudioLine "[ERROR] --package requires an argument." -ForegroundColor Red
return (Exit-InstallFailure "--package requires an argument.")
}
$PackageName = $argList[$i]
@@ -203,7 +229,7 @@ function Install-UnslothStudio {
"--with-llama-cpp-dir" {
$i++
if ($i -ge $argList.Count) {
- Write-Host "[ERROR] --with-llama-cpp-dir requires a path argument." -ForegroundColor Red
+ Write-StudioLine "[ERROR] --with-llama-cpp-dir requires a path argument." -ForegroundColor Red
return (Exit-InstallFailure "--with-llama-cpp-dir requires a path argument.")
}
$WithLlamaCppDir = $argList[$i]
@@ -224,14 +250,14 @@ function Install-UnslothStudio {
if ($StudioLocalInstall) {
$RepoRoot = (Resolve-Path (Split-Path -Parent $PSCommandPath)).Path
if (-not (Test-Path (Join-Path $RepoRoot "pyproject.toml"))) {
- Write-Host "[ERROR] --local must be run from the unsloth repo root (pyproject.toml not found at $RepoRoot)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] --local must be run from the unsloth repo root (pyproject.toml not found at $RepoRoot)" -ForegroundColor Red
return (Exit-InstallFailure "--local must be run from the unsloth repo root")
}
}
# Validate --package to prevent injection into shell/Python commands
if ($PackageName -notmatch '^[a-zA-Z0-9][a-zA-Z0-9._-]*$') {
- Write-Host "[ERROR] --package name contains invalid characters (allowed: a-z A-Z 0-9 . _ -)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] --package name contains invalid characters (allowed: a-z A-Z 0-9 . _ -)" -ForegroundColor Red
return (Exit-InstallFailure "--package name contains invalid characters")
}
@@ -431,10 +457,10 @@ public static class UnslothStudioFinalPathV2
$_tauriOverride = $_tauriOverride.TrimEnd($_trimSeps)
$_legacyTauriRoot = $_legacyTauriRoot.TrimEnd($_trimSeps)
if ($_tauriOverride -ne $_legacyTauriRoot) {
- Write-Host "ERROR: $envOverrideVar is not supported with --tauri." -ForegroundColor Red
- Write-Host " The desktop app uses the Windows profile .unsloth\studio root." -ForegroundColor Red
- Write-Host " Run install.ps1 without --tauri for custom-root shell installs," -ForegroundColor Yellow
- Write-Host " or unset the env var for default desktop installs." -ForegroundColor Yellow
+ Write-StudioLine "ERROR: $envOverrideVar is not supported with --tauri." -ForegroundColor Red
+ Write-StudioLine " The desktop app uses the Windows profile .unsloth\studio root." -ForegroundColor Red
+ Write-StudioLine " Run install.ps1 without --tauri for custom-root shell installs," -ForegroundColor Yellow
+ Write-StudioLine " or unset the env var for default desktop installs." -ForegroundColor Yellow
throw "$envOverrideVar is not supported with --tauri."
}
}
@@ -457,7 +483,7 @@ public static class UnslothStudioFinalPathV2
[System.IO.Directory]::CreateDirectory($envOverride) | Out-Null
$StudioHome = (Resolve-Path -LiteralPath $envOverride).Path
} catch {
- Write-Host "ERROR: $envOverrideVar=$envOverride cannot be created or accessed." -ForegroundColor Red
+ Write-StudioLine "ERROR: $envOverrideVar=$envOverride cannot be created or accessed." -ForegroundColor Red
throw "$envOverrideVar=$envOverride cannot be created or accessed."
}
$probe = Join-Path $StudioHome (".unsloth-write-probe-" + [guid]::NewGuid())
@@ -466,7 +492,7 @@ public static class UnslothStudioFinalPathV2
[System.IO.File]::WriteAllText($probe, "")
Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
} catch {
- Write-Host "ERROR: $envOverrideVar=$StudioHome is not writable." -ForegroundColor Red
+ Write-StudioLine "ERROR: $envOverrideVar=$StudioHome is not writable." -ForegroundColor Red
throw "$envOverrideVar=$StudioHome is not writable."
}
$StudioDataDir = Join-Path $StudioHome "share"
@@ -523,15 +549,15 @@ public static class UnslothStudioFinalPathV2
}
}
- Write-Host ""
+ Write-StudioLine ""
if ($script:StudioVtOk -and -not $env:NO_COLOR) {
- Write-Host (" " + (Get-StudioAnsi Title) + $Sloth + " Unsloth Studio Installer (Windows)" + (Get-StudioAnsi Reset))
- Write-Host (" {0}{1}{2}" -f (Get-StudioAnsi Dim), $Rule, (Get-StudioAnsi Reset))
+ Write-StudioLine (" " + (Get-StudioAnsi Title) + $Sloth + " Unsloth Studio Installer (Windows)" + (Get-StudioAnsi Reset))
+ Write-StudioLine (" {0}{1}{2}" -f (Get-StudioAnsi Dim), $Rule, (Get-StudioAnsi Reset))
} else {
- Write-Host (" {0} Unsloth Studio Installer (Windows)" -f $Sloth) -ForegroundColor DarkGreen
- Write-Host " $Rule" -ForegroundColor DarkGray
+ Write-StudioLine (" {0} Unsloth Studio Installer (Windows)" -f $Sloth) -ForegroundColor DarkGreen
+ Write-StudioLine " $Rule" -ForegroundColor DarkGray
}
- Write-Host ""
+ Write-StudioLine ""
# ── Helper: refresh PATH from registry (deduplicating entries) ──
# Merge order: venv Scripts (if active) > Machine > User > current $env:Path.
@@ -611,7 +637,7 @@ public static class UnslothStudioFinalPathV2
} catch { }
}
if (-not $rawPath) {
- Write-Host "[WARN] User PATH is empty - initializing with $Directory" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] User PATH is empty - initializing with $Directory" -ForegroundColor Yellow
}
$newPath = if ($rawPath) {
if ($Position -eq 'Prepend') {
@@ -638,7 +664,7 @@ public static class UnslothStudioFinalPathV2
$regKey.Close()
}
} catch {
- Write-Host "[WARN] Could not update User PATH: $($_.Exception.Message)" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Could not update User PATH: $($_.Exception.Message)" -ForegroundColor Yellow
return $false
}
}
@@ -660,7 +686,7 @@ public static class UnslothStudioFinalPathV2
default { Get-StudioAnsi Ok }
}
$padded = if ($Label.Length -ge 15) { $Label.Substring(0, 15) } else { $Label.PadRight(15) }
- Write-Host (" {0}{1}{2}{3}{4}{2}" -f $dim, $padded, $rst, $val, $Value)
+ Write-StudioLine (" {0}{1}{2}{3}{4}{2}" -f $dim, $padded, $rst, $val, $Value)
} else {
$padded = if ($Label.Length -ge 15) { $Label.Substring(0, 15) } else { $Label.PadRight(15) }
$fc = switch ($Color) {
@@ -670,10 +696,11 @@ public static class UnslothStudioFinalPathV2
'DarkGray' { 'DarkGray' }
default { 'DarkGreen' }
}
- # One composed record: two Write-Host calls are two Information
- # records, and a redirected consumer splits the label from the value
- # at the boundary. No mirror here, so this is the only sink.
- Write-Host (" {0}{1}" -f $padded, $Value) -ForegroundColor $fc
+ # One composed record: two calls are two records, and a redirected
+ # consumer splits the label from the value at the boundary.
+ # Write-StudioLine picks the sink, so this stays a single line on
+ # both of them.
+ Write-StudioLine (" {0}{1}" -f $padded, $Value) -ForegroundColor $fc
}
}
@@ -689,14 +716,14 @@ public static class UnslothStudioFinalPathV2
default { (Get-StudioAnsi Dim) }
}
$pad = "".PadRight(15)
- Write-Host (" {0}{1}{2}{3}" -f $msgCol, $pad, $Message, (Get-StudioAnsi Reset))
+ Write-StudioLine (" {0}{1}{2}{3}" -f $msgCol, $pad, $Message, (Get-StudioAnsi Reset))
} else {
$fc = switch ($Color) {
'Yellow' { 'Yellow' }
'Red' { 'Red' }
default { 'DarkGray' }
}
- Write-Host (" {0,-15}{1}" -f "", $Message) -ForegroundColor $fc
+ Write-StudioLine (" {0,-15}{1}" -f "", $Message) -ForegroundColor $fc
}
}
@@ -857,7 +884,7 @@ public static class UnslothStudioFinalPathV2
if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { return $null }
$dir = Get-ManagedLlamaCppDir
if ((Get-LlamaCppInstallReadState -Path $dir) -ne "Denied") { return $null }
- Write-Host ""
+ Write-StudioLine ""
# A denied custom home cannot be claimed as an Unsloth-managed cache.
$homeIsCustom = Test-StudioHomeIsCustom
# Preserve user-supplied wording when either override names this tree.
@@ -868,7 +895,7 @@ public static class UnslothStudioFinalPathV2
-UserSupplied:$userSupplied -OwnershipUnverified:$homeIsCustom
substep "Stopping here, before phase 1: nothing has been downloaded or installed" "Yellow"
substep "Fix access, then run the same install, setup, or update command again" "Yellow"
- Write-Host ""
+ Write-StudioLine ""
return "$reason Nothing was installed."
}
@@ -922,7 +949,7 @@ public static class UnslothStudioFinalPathV2
} else {
$output = & $Command 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
- Write-Host (Redact-InstallOutput $output) -ForegroundColor Red
+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red
}
}
$exitCode = [int]$LASTEXITCODE
@@ -1325,13 +1352,13 @@ exit 0
try {
Copy-Item -LiteralPath $bundledIcon -Destination $iconPath -Force
} catch {
- Write-Host "[DEBUG] Error copying bundled icon: $($_.Exception.Message)" -ForegroundColor DarkGray
+ Write-StudioLine "[DEBUG] Error copying bundled icon: $($_.Exception.Message)" -ForegroundColor DarkGray
}
} elseif (-not (Test-Path -LiteralPath $iconPath)) {
try {
Invoke-WebRequest -Uri $iconUrl -OutFile $iconPath -UseBasicParsing
} catch {
- Write-Host "[DEBUG] Error downloading icon: $($_.Exception.Message)" -ForegroundColor DarkGray
+ Write-StudioLine "[DEBUG] Error downloading icon: $($_.Exception.Message)" -ForegroundColor DarkGray
}
}
@@ -1350,7 +1377,7 @@ exit 0
Remove-Item -LiteralPath $iconPath -Force -ErrorAction SilentlyContinue
}
} catch {
- Write-Host "[DEBUG] Error validating or removing icon: $($_.Exception.Message)" -ForegroundColor DarkGray
+ Write-StudioLine "[DEBUG] Error validating or removing icon: $($_.Exception.Message)" -ForegroundColor DarkGray
Remove-Item -LiteralPath $iconPath -Force -ErrorAction SilentlyContinue
}
}
@@ -1480,7 +1507,7 @@ exit 0
if ($TauriMode) { return }
$UnslothExe = Join-Path $VenvDir "Scripts\unsloth.exe"
if (-not (Test-Path -LiteralPath $UnslothExe)) {
- Write-Host "[ERROR] unsloth.exe missing at $UnslothExe; run install.ps1 first." -ForegroundColor Red
+ Write-StudioLine "[ERROR] unsloth.exe missing at $UnslothExe; run install.ps1 first." -ForegroundColor Red
# throw (not Exit-InstallFailure) so non-Tauri callers see rc != 0.
throw "unsloth.exe missing"
}
@@ -1554,14 +1581,14 @@ exit 0
$StudioHomeFull = ""
try { $StudioHomeFull = [System.IO.Path]::GetFullPath($StudioHome).TrimEnd('\') } catch {}
if ($SafeDir -and (Test-UnderSystemRoot $StudioHomeFull)) {
- Write-Host ""
- Write-Host "[ERROR] Unsloth would install into $StudioHomeFull," -ForegroundColor Red
- Write-Host " which is inside $SystemRootDir." -ForegroundColor Yellow
- Write-Host " That is where a service or the SYSTEM account keeps its profile." -ForegroundColor Yellow
- Write-Host " Sign in as a normal user, open PowerShell there, and run the" -ForegroundColor Yellow
- Write-Host " installer again:" -ForegroundColor Yellow
- Write-Host " irm https://unsloth.ai/install.ps1 | iex" -ForegroundColor Cyan
- Write-Host ""
+ Write-StudioLine ""
+ Write-StudioLine "[ERROR] Unsloth would install into $StudioHomeFull," -ForegroundColor Red
+ Write-StudioLine " which is inside $SystemRootDir." -ForegroundColor Yellow
+ Write-StudioLine " That is where a service or the SYSTEM account keeps its profile." -ForegroundColor Yellow
+ Write-StudioLine " Sign in as a normal user, open PowerShell there, and run the" -ForegroundColor Yellow
+ Write-StudioLine " installer again:" -ForegroundColor Yellow
+ Write-StudioLine " irm https://unsloth.ai/install.ps1 | iex" -ForegroundColor Cyan
+ Write-StudioLine ""
return (Exit-InstallFailure "Refusing to install into $StudioHomeFull, which is inside $SystemRootDir. Run the installer from a normal user account.")
}
if ($SafeDir) {
@@ -1571,21 +1598,21 @@ exit 0
substep " $SafeDir" "Yellow"
substep "This is normal: 'Run as administrator' opens PowerShell in System32." "Yellow"
} else {
- Write-Host ""
- Write-Host "[ERROR] Unsloth cannot be installed from $CurrentDir." -ForegroundColor Red
- Write-Host " That is a Windows system folder, and Unsloth writes its virtual" -ForegroundColor Yellow
- Write-Host " environment caches, model downloads and build files into the" -ForegroundColor Yellow
- Write-Host " working directory, which Windows blocks there." -ForegroundColor Yellow
- Write-Host " 'Run as administrator' opens PowerShell in System32, which is how" -ForegroundColor Yellow
- Write-Host " most people land here." -ForegroundColor Yellow
+ Write-StudioLine ""
+ Write-StudioLine "[ERROR] Unsloth cannot be installed from $CurrentDir." -ForegroundColor Red
+ Write-StudioLine " That is a Windows system folder, and Unsloth writes its virtual" -ForegroundColor Yellow
+ Write-StudioLine " environment caches, model downloads and build files into the" -ForegroundColor Yellow
+ Write-StudioLine " working directory, which Windows blocks there." -ForegroundColor Yellow
+ Write-StudioLine " 'Run as administrator' opens PowerShell in System32, which is how" -ForegroundColor Yellow
+ Write-StudioLine " most people land here." -ForegroundColor Yellow
# USERPROFILE was just rejected as a candidate, so naming it here would send
# the user back into the same tree.
- Write-Host " Nothing outside $SystemRootDir was usable either (USERPROFILE," -ForegroundColor Yellow
- Write-Host " HOME, PUBLIC, TEMP), which normally means a service or the SYSTEM" -ForegroundColor Yellow
- Write-Host " account. Sign in as a normal user, open PowerShell there, and run" -ForegroundColor Yellow
- Write-Host " the installer again:" -ForegroundColor Yellow
- Write-Host " irm https://unsloth.ai/install.ps1 | iex" -ForegroundColor Cyan
- Write-Host ""
+ Write-StudioLine " Nothing outside $SystemRootDir was usable either (USERPROFILE," -ForegroundColor Yellow
+ Write-StudioLine " HOME, PUBLIC, TEMP), which normally means a service or the SYSTEM" -ForegroundColor Yellow
+ Write-StudioLine " account. Sign in as a normal user, open PowerShell there, and run" -ForegroundColor Yellow
+ Write-StudioLine " the installer again:" -ForegroundColor Yellow
+ Write-StudioLine " irm https://unsloth.ai/install.ps1 | iex" -ForegroundColor Cyan
+ Write-StudioLine ""
return (Exit-InstallFailure "Refusing to install from the Windows system directory $CurrentDir, and no folder outside $SystemRootDir was usable. Run the installer from a normal user account.")
}
}
@@ -1643,7 +1670,7 @@ exit 0
$leftFull = Get-StudioFinalPath -Path $Left
$rightFull = Get-StudioFinalPath -Path $Right
} catch {
- Write-Host "[WARN] Could not resolve Studio path identity; using the runtime lock." -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Could not resolve Studio path identity; using the runtime lock." -ForegroundColor Yellow
return $null
}
return [string]::Equals(
@@ -1805,12 +1832,12 @@ exit 0
try {
$studioInstallMutex = Enter-StudioInstallMutex -Path $StudioHome
} catch {
- Write-Host "[ERROR] Could not create the Studio install lock: $($_.Exception.Message)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] Could not create the Studio install lock: $($_.Exception.Message)" -ForegroundColor Red
return (Exit-InstallFailure "Could not create the Studio install lock")
}
if ($null -eq $studioInstallMutex) {
- Write-Host "[ERROR] Another Unsloth Studio install or repair is already running." -ForegroundColor Red
- Write-Host " Wait for it to finish, then re-run install.ps1." -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] Another Unsloth Studio install or repair is already running." -ForegroundColor Red
+ Write-StudioLine " Wait for it to finish, then re-run install.ps1." -ForegroundColor Yellow
return (Exit-InstallFailure "Another Unsloth Studio install or repair is already running")
}
@@ -1834,14 +1861,14 @@ exit 0
foreach ($studioRuntimeMutexName in $studioRuntimeMutexNames) {
$mutex = Enter-StudioNamedMutex -Name $studioRuntimeMutexName
if ($null -eq $mutex) {
- Write-Host "[ERROR] Unsloth Studio is starting or installation is already running." -ForegroundColor Red
- Write-Host " Close Unsloth Studio completely, wait for the other operation, then re-run install.ps1." -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] Unsloth Studio is starting or installation is already running." -ForegroundColor Red
+ Write-StudioLine " Close Unsloth Studio completely, wait for the other operation, then re-run install.ps1." -ForegroundColor Yellow
return (Exit-InstallFailure "The managed Studio environment is busy")
}
$studioRuntimeMutexes += $mutex
}
} catch {
- Write-Host "[ERROR] Could not create the Studio runtime lock: $($_.Exception.Message)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] Could not create the Studio runtime lock: $($_.Exception.Message)" -ForegroundColor Red
return (Exit-InstallFailure "Could not create the Studio runtime lock")
}
}
@@ -1874,9 +1901,9 @@ exit 0
$runningVenvProcesses = @($runningVenvProcessesById.Values)
if ($runningVenvProcesses.Count -gt 0) {
$runningSummary = ($runningVenvProcesses | ForEach-Object { "$($_.ProcessName) (PID $($_.Id))" }) -join ", "
- Write-Host "[ERROR] Unsloth Studio is using the managed Python environment." -ForegroundColor Red
- Write-Host " Active processes: $runningSummary" -ForegroundColor Yellow
- Write-Host " Close Unsloth Studio completely, including its tray process, then re-run install.ps1." -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] Unsloth Studio is using the managed Python environment." -ForegroundColor Red
+ Write-StudioLine " Active processes: $runningSummary" -ForegroundColor Yellow
+ Write-StudioLine " Close Unsloth Studio completely, including its tray process, then re-run install.ps1." -ForegroundColor Yellow
return (Exit-InstallFailure "The managed Python environment is still in use")
}
@@ -1884,8 +1911,8 @@ exit 0
$runningDesktopApps = @(Get-StudioDesktopProcessesForCurrentUser)
if ($runningDesktopApps.Count -gt 0) {
$desktopSummary = ($runningDesktopApps | ForEach-Object { "PID $($_.Id)" }) -join ", "
- Write-Host "[ERROR] The Unsloth Studio desktop app is still running ($desktopSummary)." -ForegroundColor Red
- Write-Host " Close the app completely, including its tray process, then re-run install.ps1." -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] The Unsloth Studio desktop app is still running ($desktopSummary)." -ForegroundColor Red
+ Write-StudioLine " Close the app completely, including its tray process, then re-run install.ps1." -ForegroundColor Yellow
return (Exit-InstallFailure "The Unsloth Studio desktop app is still running")
}
}
@@ -2237,10 +2264,10 @@ exit 0
if (-not $DetectedPython) {
$exitNote = if ($null -ne $wingetExit) { " (winget exit code $wingetExit)" } else { "" }
- Write-Host "[ERROR] Python installation failed$exitNote" -ForegroundColor Red
- Write-Host " Please install Python $PythonVersion manually from https://www.python.org/downloads/" -ForegroundColor Yellow
- Write-Host " Make sure to check 'Add Python to PATH' during installation." -ForegroundColor Yellow
- Write-Host " Then re-run this installer." -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] Python installation failed$exitNote" -ForegroundColor Red
+ Write-StudioLine " Please install Python $PythonVersion manually from https://www.python.org/downloads/" -ForegroundColor Yellow
+ Write-StudioLine " Make sure to check 'Add Python to PATH' during installation." -ForegroundColor Yellow
+ Write-StudioLine " Then re-run this installer." -ForegroundColor Yellow
return (Exit-InstallFailure "Python installation failed")
}
}
@@ -2255,12 +2282,12 @@ exit 0
$DetectedPython = $X64Python
step "python" "using x64 Python $($DetectedPython.Version) under emulation"
} else {
- Write-Host "[WARN] Could not install an x64 Python on this ARM64 machine." -ForegroundColor Yellow
- Write-Host " Continuing with ARM64 Python $($DetectedPython.Version), but the install is likely to fail:" -ForegroundColor Yellow
- Write-Host " pyarrow (via datasets) and hf-transfer ship no win_arm64 wheels and will be" -ForegroundColor Yellow
- Write-Host " built from source, which needs CMake plus the MSVC and Rust toolchains." -ForegroundColor Yellow
- Write-Host " Fix: install x64 Python from https://www.python.org/downloads/windows/" -ForegroundColor Yellow
- Write-Host " (choose 'Windows installer (64-bit)', not ARM64), then re-run this installer." -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Could not install an x64 Python on this ARM64 machine." -ForegroundColor Yellow
+ Write-StudioLine " Continuing with ARM64 Python $($DetectedPython.Version), but the install is likely to fail:" -ForegroundColor Yellow
+ Write-StudioLine " pyarrow (via datasets) and hf-transfer ship no win_arm64 wheels and will be" -ForegroundColor Yellow
+ Write-StudioLine " built from source, which needs CMake plus the MSVC and Rust toolchains." -ForegroundColor Yellow
+ Write-StudioLine " Fix: install x64 Python from https://www.python.org/downloads/windows/" -ForegroundColor Yellow
+ Write-StudioLine " (choose 'Windows installer (64-bit)', not ARM64), then re-run this installer." -ForegroundColor Yellow
}
}
@@ -2539,11 +2566,11 @@ exit 0
# environment, so restoration must merge them rather than clear the
# destination first the way the committed-replacement path does.
$script:StudioVenvRollbackPartial = $true
- Write-Host "[WARN] Moving the existing environment aside stopped partway -- files are in both places." -ForegroundColor Yellow
- Write-Host " still in place: $ExistingDir" -ForegroundColor Yellow
- Write-Host " moved aside: $candidate" -ForegroundColor Yellow
- Write-Host " A running 'unsloth studio' process usually holds a file open here." -ForegroundColor Yellow
- Write-Host " Close Unsloth Studio and re-run the installer to reverse the move." -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Moving the existing environment aside stopped partway -- files are in both places." -ForegroundColor Yellow
+ Write-StudioLine " still in place: $ExistingDir" -ForegroundColor Yellow
+ Write-StudioLine " moved aside: $candidate" -ForegroundColor Yellow
+ Write-StudioLine " A running 'unsloth studio' process usually holds a file open here." -ForegroundColor Yellow
+ Write-StudioLine " Close Unsloth Studio and re-run the installer to reverse the move." -ForegroundColor Yellow
}
throw
}
@@ -2565,8 +2592,8 @@ exit 0
if (-not (Test-Path -LiteralPath $Path)) { return $true }
if ($attempt -lt 3) { Start-Sleep -Milliseconds (250 * $attempt) }
}
- Write-Host "[WARN] Could not remove $Label at $Path" -ForegroundColor Yellow
- if ($lastError) { Write-Host " $lastError" -ForegroundColor Yellow }
+ Write-StudioLine "[WARN] Could not remove $Label at $Path" -ForegroundColor Yellow
+ if ($lastError) { Write-StudioLine " $lastError" -ForegroundColor Yellow }
return $false
}
@@ -2589,13 +2616,13 @@ exit 0
Where-Object { $_.Name -like 'unsloth_studio.rollback.*' }
)
} catch {
- Write-Host "[WARN] Could not inspect stale environment rollbacks in $StudioHome" -ForegroundColor Yellow
- Write-Host " $($_.Exception.Message)" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Could not inspect stale environment rollbacks in $StudioHome" -ForegroundColor Yellow
+ Write-StudioLine " $($_.Exception.Message)" -ForegroundColor Yellow
return
}
foreach ($rollback in $rollbacks) {
if (($rollback.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
- Write-Host "[WARN] Refusing to remove rollback reparse point $($rollback.FullName)" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Refusing to remove rollback reparse point $($rollback.FullName)" -ForegroundColor Yellow
continue
}
# A concurrent installer may have moved its live venv aside. The PID
@@ -2644,9 +2671,9 @@ exit 0
}
continue
}
- Write-Host "[WARN] Kept both copies of $($entry.Name)" -ForegroundColor Yellow
- Write-Host " $($entry.FullName)" -ForegroundColor Yellow
- Write-Host " $entryTarget" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Kept both copies of $($entry.Name)" -ForegroundColor Yellow
+ Write-StudioLine " $($entry.FullName)" -ForegroundColor Yellow
+ Write-StudioLine " $entryTarget" -ForegroundColor Yellow
$complete = $false
}
if ($complete) {
@@ -2675,8 +2702,8 @@ exit 0
try {
$merged = Merge-StudioVenvRollbackTree -Source $backup -Destination $target
} catch {
- Write-Host "[WARN] Could not merge $backup back into $target" -ForegroundColor Yellow
- Write-Host " $($_.Exception.Message)" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Could not merge $backup back into $target" -ForegroundColor Yellow
+ Write-StudioLine " $($_.Exception.Message)" -ForegroundColor Yellow
}
if ($merged) {
substep "restored previous environment"
@@ -2684,10 +2711,10 @@ exit 0
$script:StudioVenvRollbackDir = $null
$script:StudioVenvRollbackPartial = $false
} else {
- Write-Host "[WARN] The previous environment is still split in two." -ForegroundColor Yellow
- Write-Host " still in place: $target" -ForegroundColor Yellow
- Write-Host " moved aside: $backup" -ForegroundColor Yellow
- Write-Host " Close Unsloth Studio and re-run the installer to finish reversing the move." -ForegroundColor Yellow
+ Write-StudioLine "[WARN] The previous environment is still split in two." -ForegroundColor Yellow
+ Write-StudioLine " still in place: $target" -ForegroundColor Yellow
+ Write-StudioLine " moved aside: $backup" -ForegroundColor Yellow
+ Write-StudioLine " Close Unsloth Studio and re-run the installer to finish reversing the move." -ForegroundColor Yellow
}
return
}
@@ -2702,8 +2729,8 @@ exit 0
$script:StudioVenvRollbackActive = $false
$script:StudioVenvRollbackDir = $null
} catch {
- Write-Host "[WARN] Could not restore previous environment from $backup to $target" -ForegroundColor Yellow
- Write-Host " $($_.Exception.Message)" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Could not restore previous environment from $backup to $target" -ForegroundColor Yellow
+ Write-StudioLine " $($_.Exception.Message)" -ForegroundColor Yellow
}
}
@@ -2734,8 +2761,8 @@ exit 0
-not (Test-Path -LiteralPath (Join-Path $StudioHome "share\studio.conf") -PathType Leaf) -and
-not (Test-Path -LiteralPath (Join-Path $StudioHome "bin\unsloth.exe") -PathType Leaf)
) {
- Write-Host "[ERROR] $VenvDir already exists but does not look like an Unsloth Studio install." -ForegroundColor Red
- Write-Host " Move it aside or choose an empty UNSLOTH_STUDIO_HOME." -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] $VenvDir already exists but does not look like an Unsloth Studio install." -ForegroundColor Red
+ Write-StudioLine " Move it aside or choose an empty UNSLOTH_STUDIO_HOME." -ForegroundColor Yellow
throw "Refusing to delete non-Unsloth venv at $VenvDir"
}
# New layout already exists -- replace only after preserving rollback copy.
@@ -2743,7 +2770,7 @@ exit 0
try {
Start-StudioVenvRollback -ExistingDir $VenvDir
} catch {
- Write-Host "[ERROR] Could not prepare existing environment for reinstall: $($_.Exception.Message)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] Could not prepare existing environment for reinstall: $($_.Exception.Message)" -ForegroundColor Red
return (Exit-InstallFailure "Could not prepare existing environment for reinstall")
}
} elseif (
@@ -2795,7 +2822,7 @@ exit 0
substep "$VenvDir"
$venvExit = Invoke-InstallCommand -Label "create virtual environment" { uv venv $VenvDir --python "$($DetectedPython.Path)" }
if ($venvExit -ne 0) {
- Write-Host "[ERROR] Failed to create virtual environment (exit code $venvExit)" -ForegroundColor Red
+ 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)
}
} else {
@@ -2810,12 +2837,12 @@ exit 0
if (-not (Test-VenvPythonReady -PythonExe $VenvPython)) {
$recordedBaseHome = Get-VenvBaseHome -VenvRoot $VenvDir
- Write-Host "[ERROR] The managed Python interpreter is missing or cannot be launched." -ForegroundColor Red
- Write-Host " Managed Python: $VenvPython" -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] The managed Python interpreter is missing or cannot be launched." -ForegroundColor Red
+ Write-StudioLine " Managed Python: $VenvPython" -ForegroundColor Yellow
if (-not $recordedBaseHome) { $recordedBaseHome = "unavailable" }
- Write-Host " Recorded base Python home: $recordedBaseHome" -ForegroundColor Yellow
+ Write-StudioLine " Recorded base Python home: $recordedBaseHome" -ForegroundColor Yellow
# The ownership marker is written above, so a plain re-run replaces this venv.
- Write-Host " Restore that Python installation, or just re-run install.ps1." -ForegroundColor Yellow
+ Write-StudioLine " Restore that Python installation, or just re-run install.ps1." -ForegroundColor Yellow
return (Exit-InstallFailure "Managed Python is unavailable at $VenvPython (recorded base home: $recordedBaseHome)")
}
@@ -3009,16 +3036,16 @@ exit 0
continue
}
if (Test-HipinfoIsVenvInternal $hipinfoCandidate) { continue } # venv copy (AMD wheel): not a HIP SDK
- Write-Host " [WARN] hipinfo not on PATH -- located via ${hipEnvLabel}: $hipinfoCandidate" -ForegroundColor Yellow
- Write-Host " Add '$(Join-Path $hipRoot 'bin')' to your PATH to suppress this warning" -ForegroundColor Yellow
- Write-Host " Quick fix: [Environment]::SetEnvironmentVariable('PATH',`$env:PATH+';$(Join-Path $hipRoot 'bin')','User')" -ForegroundColor Yellow
+ Write-StudioLine " [WARN] hipinfo not on PATH -- located via ${hipEnvLabel}: $hipinfoCandidate" -ForegroundColor Yellow
+ Write-StudioLine " Add '$(Join-Path $hipRoot 'bin')' to your PATH to suppress this warning" -ForegroundColor Yellow
+ Write-StudioLine " Quick fix: [Environment]::SetEnvironmentVariable('PATH',`$env:PATH+';$(Join-Path $hipRoot 'bin')','User')" -ForegroundColor Yellow
$hipinfoExe = [PSCustomObject]@{ Source = $hipinfoCandidate }
break
}
if ((-not $hipinfoExe) -and $hipMissingLabel) {
- Write-Host " [WARN] ${hipMissingLabel}=$hipMissingRoot is set but hipinfo.exe not found at $hipMissingCandidate" -ForegroundColor Yellow
- Write-Host " HIP SDK install may be incomplete -- re-install from:" -ForegroundColor Yellow
- Write-Host " https://rocm.docs.amd.com/en/latest/deploy/windows/index.html" -ForegroundColor Yellow
+ Write-StudioLine " [WARN] ${hipMissingLabel}=$hipMissingRoot is set but hipinfo.exe not found at $hipMissingCandidate" -ForegroundColor Yellow
+ Write-StudioLine " HIP SDK install may be incomplete -- re-install from:" -ForegroundColor Yellow
+ Write-StudioLine " https://rocm.docs.amd.com/en/latest/deploy/windows/index.html" -ForegroundColor Yellow
}
}
if ($hipinfoExe) {
@@ -3038,16 +3065,16 @@ exit 0
$ROCmGpuLabel = "AMD ROCm"
}
if ($LASTEXITCODE -ne 0) {
- Write-Host " [INFO] hipinfo exited with code $LASTEXITCODE but reported gcnArchName -- treating as ROCm-capable (see #6043)" -ForegroundColor Cyan
+ Write-StudioLine " [INFO] hipinfo exited with code $LASTEXITCODE but reported gcnArchName -- treating as ROCm-capable (see #6043)" -ForegroundColor Cyan
}
} elseif ($LASTEXITCODE -ne 0) {
# hipinfo ran but returned a HIP runtime error without any gcnArchName
# output (e.g. "no ROCm-capable device detected"), or crashed before
# printing device info.
$firstLine = ($hipOut -split '\r?\n' | Where-Object { $_.Trim() } | Select-Object -First 1)
- Write-Host " [WARN] hipinfo returned a HIP runtime error (exit $LASTEXITCODE)" -ForegroundColor Yellow
- Write-Host " $firstLine" -ForegroundColor Yellow
- Write-Host " Ensure ROCm drivers are installed: https://rocm.docs.amd.com/en/latest/deploy/windows/index.html" -ForegroundColor Yellow
+ Write-StudioLine " [WARN] hipinfo returned a HIP runtime error (exit $LASTEXITCODE)" -ForegroundColor Yellow
+ Write-StudioLine " $firstLine" -ForegroundColor Yellow
+ Write-StudioLine " Ensure ROCm drivers are installed: https://rocm.docs.amd.com/en/latest/deploy/windows/index.html" -ForegroundColor Yellow
}
} catch {}
}
@@ -3155,7 +3182,7 @@ exit 0
$hipConfigCandidate = Join-Path $hipRoot "bin\hipconfig.exe"
if (Test-Path $hipConfigCandidate) {
$hipConfigEnvLabel = if ($env:HIP_PATH) { "HIP_PATH" } else { "ROCM_PATH" }
- Write-Host " [WARN] hipconfig not on PATH -- located via ${hipConfigEnvLabel}: $hipConfigCandidate" -ForegroundColor Yellow
+ Write-StudioLine " [WARN] hipconfig not on PATH -- located via ${hipConfigEnvLabel}: $hipConfigCandidate" -ForegroundColor Yellow
$hipConfigExe = [PSCustomObject]@{ Source = $hipConfigCandidate }
}
}
@@ -3758,7 +3785,7 @@ exit 0
# ── Print CPU-only hint when no GPU detected ──
if (-not $SkipTorch -and -not $ROCmIndexUrl -and $TorchIndexUrl -like "*/cpu") {
- Write-Host ""
+ Write-StudioLine ""
if ($ROCmGfxArch) {
# Only an unmapped arch reaches here (a mapped one set $ROCmIndexUrl
# above). No ROCm torch wheels for this arch (e.g. RDNA2 gfx103X) -> CPU.
@@ -3781,7 +3808,7 @@ exit 0
substep "re-run with --no-torch for a faster, lighter install:" "Yellow"
substep ".\install.ps1 --no-torch" "Yellow"
}
- Write-Host ""
+ Write-StudioLine ""
}
# ── Install PyTorch first, then unsloth separately ──
@@ -3838,20 +3865,20 @@ exit 0
$baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (migrated)" { uv pip install --python $VenvPython --reinstall-package unsloth --reinstall-package unsloth-zoo "unsloth>=2026.8.8" "unsloth-zoo>=2026.8.5" }
}
if ($baseInstallExit -ne 0) {
- Write-Host "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to install unsloth (exit code $baseInstallExit)" $baseInstallExit)
}
if ($StudioLocalInstall) {
substep "overlaying local repo (editable)..."
$overlayExit = Invoke-InstallCommand -Label "overlay local repo" { uv pip install --python $VenvPython -e $RepoRoot --no-deps }
if ($overlayExit -ne 0) {
- Write-Host "[ERROR] Failed to overlay local repo (exit code $overlayExit)" -ForegroundColor Red
+ 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" }
if ($zooOverlayExit -ne 0) {
- Write-Host "[ERROR] Failed to overlay unsloth-zoo (exit code $zooOverlayExit)" -ForegroundColor Red
+ 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)
}
}
@@ -3879,7 +3906,7 @@ exit 0
# 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 }
if ($torchInstallExit -ne 0) {
- Write-Host "[ERROR] Failed to install PyTorch (ROCm and CPU base both failed, exit code $torchInstallExit)" -ForegroundColor Red
+ 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)
}
# CPU base is in; drop the ROCm expectation so the flavor-repair
@@ -3916,7 +3943,7 @@ exit 0
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 }
if ($torchInstallExit -ne 0) {
- Write-Host "[ERROR] Failed to install PyTorch (XPU and CPU base both failed, exit code $torchInstallExit)" -ForegroundColor Red
+ 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)
}
# Drop the XPU expectation so flavor-repair below skips the failed index (as ROCm does).
@@ -3952,7 +3979,7 @@ exit 0
}
$torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch" { uv pip install --python $VenvPython @_torchSpecs --default-index $TorchIndexUrl }
if ($torchInstallExit -ne 0) {
- Write-Host "[ERROR] Failed to install PyTorch (exit code $torchInstallExit)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] Failed to install PyTorch (exit code $torchInstallExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to install PyTorch (exit code $torchInstallExit)" $torchInstallExit)
}
}
@@ -3979,7 +4006,7 @@ exit 0
$baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth" { uv pip install --python $VenvPython --upgrade-package unsloth -- "$PackageName" }
}
if ($baseInstallExit -ne 0) {
- Write-Host "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to install unsloth (exit code $baseInstallExit)" $baseInstallExit)
}
@@ -3987,13 +4014,13 @@ exit 0
substep "overlaying local repo (editable)..."
$overlayExit = Invoke-InstallCommand -Label "overlay local repo" { uv pip install --python $VenvPython -e $RepoRoot --no-deps }
if ($overlayExit -ne 0) {
- Write-Host "[ERROR] Failed to overlay local repo (exit code $overlayExit)" -ForegroundColor Red
+ 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" }
if ($zooOverlayExit -ne 0) {
- Write-Host "[ERROR] Failed to overlay unsloth-zoo (exit code $zooOverlayExit)" -ForegroundColor Red
+ 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)
}
}
@@ -4004,25 +4031,25 @@ exit 0
if ($StudioLocalInstall) {
$baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (auto torch backend)" { uv pip install --python $VenvPython "unsloth-zoo>=2026.8.5" "unsloth>=2026.8.8" --torch-backend=auto }
if ($baseInstallExit -ne 0) {
- Write-Host "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
+ 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 }
if ($overlayExit -ne 0) {
- Write-Host "[ERROR] Failed to overlay local repo (exit code $overlayExit)" -ForegroundColor Red
+ 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" }
if ($zooOverlayExit -ne 0) {
- Write-Host "[ERROR] Failed to overlay unsloth-zoo (exit code $zooOverlayExit)" -ForegroundColor Red
+ 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" }
if ($baseInstallExit -ne 0) {
- Write-Host "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
return (Exit-InstallFailure "Failed to install unsloth (exit code $baseInstallExit)" $baseInstallExit)
}
}
@@ -4078,7 +4105,7 @@ exit 0
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 }
if ($torchFixExit -ne 0) {
- Write-Host "[ERROR] Failed to reinstall PyTorch with the correct ROCm build (exit code $torchFixExit)" -ForegroundColor Red
+ 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)
}
$installedTorchTag = Get-InstalledTorchTag -PythonExe $VenvPython
@@ -4092,7 +4119,7 @@ exit 0
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 }
if ($torchFixExit -ne 0) {
- Write-Host "[ERROR] Failed to reinstall PyTorch with the correct CUDA build (exit code $torchFixExit)" -ForegroundColor Red
+ 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)
}
$installedTorchTag = Get-InstalledTorchTag -PythonExe $VenvPython
@@ -4100,10 +4127,10 @@ exit 0
}
# Safety net (incl. AMD): GPU build expected but still CPU -> warn loudly.
if ($installedTorchTag -eq 'cpu') {
- Write-Host ""
- Write-Host " [WARN] PyTorch is CPU-only but a $expectedTorchTag GPU build was expected for this machine." -ForegroundColor Yellow
- Write-Host " [WARN] Training and GPU inference will run on CPU until this is fixed." -ForegroundColor Yellow
- Write-Host " [WARN] Re-run this installer, or reinstall the GPU build manually for your GPU." -ForegroundColor Yellow
+ Write-StudioLine ""
+ Write-StudioLine " [WARN] PyTorch is CPU-only but a $expectedTorchTag GPU build was expected for this machine." -ForegroundColor Yellow
+ Write-StudioLine " [WARN] Training and GPU inference will run on CPU until this is fixed." -ForegroundColor Yellow
+ Write-StudioLine " [WARN] Re-run this installer, or reinstall the GPU build manually for your GPU." -ForegroundColor Yellow
}
}
}
@@ -4125,7 +4152,7 @@ exit 0
if ($env:UNSLOTH_CI_SOURCE_OVERLAY) {
$CiOverlayRoot = $env:UNSLOTH_CI_SOURCE_OVERLAY
if (-not (Test-Path -LiteralPath (Join-Path $CiOverlayRoot "pyproject.toml"))) {
- Write-Host "[ERROR] UNSLOTH_CI_SOURCE_OVERLAY is set to '$CiOverlayRoot' but there is no pyproject.toml there." -ForegroundColor Red
+ Write-StudioLine "[ERROR] UNSLOTH_CI_SOURCE_OVERLAY is set to '$CiOverlayRoot' but there is no pyproject.toml there." -ForegroundColor Red
return (Exit-InstallFailure "UNSLOTH_CI_SOURCE_OVERLAY has no pyproject.toml: $CiOverlayRoot")
}
substep "CI: overlaying source checkout (editable, no deps): $CiOverlayRoot"
@@ -4146,10 +4173,10 @@ exit 0
$UnslothExe = Join-Path $VenvDir "Scripts\unsloth.exe"
if (-not (Test-Path -LiteralPath $UnslothExe)) {
Write-TauriLog "ERROR" "unsloth CLI was not installed correctly"
- Write-Host "[ERROR] unsloth CLI was not installed correctly." -ForegroundColor Red
- Write-Host " Expected: $UnslothExe" -ForegroundColor Yellow
- Write-Host " This usually means an older unsloth version was installed that does not include the Unsloth CLI." -ForegroundColor Yellow
- Write-Host " Try re-running the installer or see: https://github.com/unslothai/unsloth?tab=readme-ov-file#-quickstart" -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] unsloth CLI was not installed correctly." -ForegroundColor Red
+ Write-StudioLine " Expected: $UnslothExe" -ForegroundColor Yellow
+ Write-StudioLine " This usually means an older unsloth version was installed that does not include the Unsloth CLI." -ForegroundColor Yellow
+ Write-StudioLine " Try re-running the installer or see: https://github.com/unslothai/unsloth?tab=readme-ov-file#-quickstart" -ForegroundColor Yellow
return (Exit-InstallFailure "unsloth CLI was not installed correctly")
}
# Tell setup.ps1 to skip base package installation (install.ps1 already did it)
@@ -4186,7 +4213,7 @@ exit 0
if ($script:UnslothVerbose) { $studioArgs += '--verbose' }
if ($WithLlamaCppDir) {
if (-not (Test-Path -LiteralPath $WithLlamaCppDir -PathType Container)) {
- Write-Host "[ERROR] --with-llama-cpp-dir path does not exist: $WithLlamaCppDir" -ForegroundColor Red
+ Write-StudioLine "[ERROR] --with-llama-cpp-dir path does not exist: $WithLlamaCppDir" -ForegroundColor Red
return (Exit-InstallFailure "--with-llama-cpp-dir path does not exist.")
}
$env:UNSLOTH_LOCAL_LLAMA_CPP_DIR = (Resolve-Path -LiteralPath $WithLlamaCppDir).Path
@@ -4227,7 +4254,7 @@ exit 0
}
if ($setupExit -ne 0) {
if (-not $TauriMode) {
- Write-Host "[ERROR] unsloth studio setup failed (exit code $setupExit)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] unsloth studio setup failed (exit code $setupExit)" -ForegroundColor Red
}
return (Exit-InstallFailure "unsloth studio setup failed (exit code $setupExit)" $setupExit)
}
@@ -4276,8 +4303,8 @@ exit 0
# the shim path must not be downgraded to "Continuing with the existing
# launcher", or the install finishes with no usable shim.
if (Test-Path -LiteralPath $ShimExe -PathType Container) {
- Write-Host "[ERROR] Cannot create unsloth launcher: $ShimExe is a directory." -ForegroundColor Red
- Write-Host " Move or remove it manually, then re-run the installer." -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] Cannot create unsloth launcher: $ShimExe is a directory." -ForegroundColor Red
+ Write-StudioLine " Move or remove it manually, then re-run the installer." -ForegroundColor Yellow
throw "Cannot create unsloth launcher: $ShimExe is a directory."
}
# try/catch: if unsloth.exe is locked (Unsloth running), keep the old shim.
@@ -4296,14 +4323,14 @@ exit 0
$shimUpdated = $true
} catch {
if (Test-Path -LiteralPath $ShimExe) {
- Write-Host "[WARN] Could not refresh unsloth launcher at $ShimExe." -ForegroundColor Yellow
- Write-Host " This usually means a running 'unsloth studio' process still holds the file open." -ForegroundColor Yellow
- Write-Host " Close Unsloth and re-run the installer to pick up the latest launcher." -ForegroundColor Yellow
- Write-Host " Continuing with the existing launcher." -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Could not refresh unsloth launcher at $ShimExe." -ForegroundColor Yellow
+ Write-StudioLine " This usually means a running 'unsloth studio' process still holds the file open." -ForegroundColor Yellow
+ Write-StudioLine " Close Unsloth and re-run the installer to pick up the latest launcher." -ForegroundColor Yellow
+ Write-StudioLine " Continuing with the existing launcher." -ForegroundColor Yellow
} else {
- Write-Host "[WARN] Could not create unsloth launcher at $ShimExe" -ForegroundColor Yellow
- Write-Host " $($_.Exception.Message)" -ForegroundColor Yellow
- Write-Host " Launch unsloth studio directly via '$UnslothExe' until the next successful install." -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Could not create unsloth launcher at $ShimExe" -ForegroundColor Yellow
+ Write-StudioLine " $($_.Exception.Message)" -ForegroundColor Yellow
+ Write-StudioLine " Launch unsloth studio directly via '$UnslothExe' until the next successful install." -ForegroundColor Yellow
}
}
# Add to PATH only when launcher exists. Env-mode: session-only export,
@@ -4356,14 +4383,14 @@ exit 0
$_installedHash = (Get-FileHash -LiteralPath $UnslothExe -Algorithm SHA256 -ErrorAction SilentlyContinue).Hash
$_pathHash = (Get-FileHash -LiteralPath $_pathExe -Algorithm SHA256 -ErrorAction SilentlyContinue).Hash
if ($_installedHash -and $_pathHash -and ($_installedHash -ne $_pathHash)) {
- Write-Host ""
+ Write-StudioLine ""
step "warning" "another 'unsloth' wins on PATH:" "Yellow"
substep $_pathExe
substep "this installer's binary is at:"
substep $UnslothExe
substep "to use this install, call the absolute path above,"
substep "or put its dir earlier on PATH."
- Write-Host ""
+ Write-StudioLine ""
}
}
} catch {
@@ -4375,7 +4402,7 @@ exit 0
# In non-interactive environments (CI, Docker) just print instructions.
$IsInteractive = (-not $SkipAutostart) -and [Environment]::UserInteractive -and (-not [Console]::IsInputRedirected)
if ($IsInteractive) {
- Write-Host ""
+ Write-StudioLine ""
$reply = Read-Host " Start Unsloth Studio now? [Y/n]"
if ([string]::IsNullOrWhiteSpace($reply) -or $reply -match '^[Yy]') {
# Keep both locks until the process exists: a second installer can
@@ -4398,7 +4425,7 @@ exit 0
substep "unsloth studio -p 8888"
substep "(add -H 0.0.0.0 for LAN / cloud access; exposes the raw port only, not a public URL)"
substep "(add -H 0.0.0.0 --cloudflare for a public Cloudflare HTTPS link, or --secure to keep the raw port private; anyone with the API key can run code)"
- Write-Host ""
+ Write-StudioLine ""
}
} else {
step "launch" "manual commands:"
@@ -4419,7 +4446,7 @@ exit 0
}
substep "(add -H 0.0.0.0 for LAN / cloud access; exposes the raw port only, not a public URL)"
substep "(add -H 0.0.0.0 --cloudflare for a public Cloudflare HTTPS link, or --secure to keep the raw port private; anyone with the API key can run code)"
- Write-Host ""
+ Write-StudioLine ""
}
} finally {
for ($i = $studioRuntimeMutexes.Count - 1; $i -ge 0; $i--) {
diff --git a/studio/backend/tests/test_setup_llama_cpp_backend.py b/studio/backend/tests/test_setup_llama_cpp_backend.py
index a18827d96b3..29d6e8b3b8a 100644
--- a/studio/backend/tests/test_setup_llama_cpp_backend.py
+++ b/studio/backend/tests/test_setup_llama_cpp_backend.py
@@ -318,6 +318,12 @@ def _run_ps1(value: str | None) -> str:
if value is not None:
env["UNSLOTH_LLAMA_CPP_BACKEND"] = value
harness = (
+ # The spliced snippet warns through setup.ps1's output sink, which the real
+ # script defines above every call site. Stub it to Write-Host so the warning
+ # lands on stdout, where the assertions below read it: without this the call
+ # errors out and the harness returns a bare "ARGS:".
+ "function Write-StudioLine { param([string]$Message, [string]$ForegroundColor) "
+ "Write-Host $Message }\n"
"$prebuiltArgs = @()\n"
'$sourceLlamaBackend = "$($env:UNSLOTH_LLAMA_CPP_BACKEND)".Trim().ToLowerInvariant()\n'
'$sourceLegacyForceVulkan = "$($env:UNSLOTH_FORCE_VULKAN)".Trim().ToLowerInvariant()\n'
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 0dad5793236..e9d88bd7a08 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -93,6 +93,27 @@ $env:PYTHONIOENCODING = 'utf-8'
$script:StudioStdoutRedirected = $false
try { $script:StudioStdoutRedirected = [Console]::IsOutputRedirected } catch { }
+# Every other line in this script reached the pipe through Write-Host, which
+# 5.1's console host writes with its own writer on the OEM code page, not the
+# UTF-8 [Console]::Out rebound above. Under CREATE_NO_WINDOW that writer is
+# still what the desktop app reads, so the banner emoji, the U+2500 rule and
+# every warning arrived as U+FFFD out of from_utf8_lossy. One sink instead: the
+# console handle when redirected, Write-Host when interactive, since it is the
+# only one that colorizes. Defined above the first write, for the same ordering
+# reason as the encoding block.
+function Write-StudioLine {
+ param([string]$Message = "", [string]$ForegroundColor)
+ if ($script:StudioStdoutRedirected) {
+ try { [Console]::Out.WriteLine($Message); [Console]::Out.Flush() } catch {}
+ return
+ }
+ if ($PSBoundParameters.ContainsKey('ForegroundColor')) {
+ Write-Host $Message -ForegroundColor $ForegroundColor
+ } else {
+ Write-Host $Message
+ }
+}
+
# --------------------------------------------------------------------------
# Maintainer-editable defaults
# Change these in the GitHub-hosted script so users get updated defaults.
@@ -263,7 +284,7 @@ function Add-ToUserPath {
} catch { }
}
if (-not $rawPath) {
- Write-Host "[WARN] User PATH is empty - initializing with $Directory" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] User PATH is empty - initializing with $Directory" -ForegroundColor Yellow
}
$newPath = if ($rawPath) {
if ($Position -eq 'Prepend') {
@@ -290,7 +311,7 @@ function Add-ToUserPath {
$regKey.Close()
}
} catch {
- Write-Host "[WARN] Could not update User PATH: $($_.Exception.Message)" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Could not update User PATH: $($_.Exception.Message)" -ForegroundColor Yellow
return $false
}
}
@@ -492,7 +513,7 @@ function Invoke-ManagedLlamaCppPreflight {
if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { return $null }
$dir = Get-ManagedLlamaCppDir
if ((Get-LlamaCppInstallReadState -Path $dir) -ne "Denied") { return $null }
- Write-Host ""
+ Write-StudioLine ""
# A denied custom home cannot be claimed as an Unsloth-managed cache.
$homeIsCustom = Test-StudioHomeIsCustom
# Preserve user-supplied wording when either override names this tree.
@@ -503,7 +524,7 @@ function Invoke-ManagedLlamaCppPreflight {
-UserSupplied:$userSupplied -OwnershipUnverified:$homeIsCustom
substep "Stopping here, before phase 1: nothing has been downloaded or installed" "Yellow"
substep "Fix access, then run the same install, setup, or update command again" "Yellow"
- Write-Host ""
+ Write-StudioLine ""
return "$reason Nothing was installed."
}
@@ -1373,7 +1394,7 @@ function Find-VsBuildTools {
function Ensure-BuildToolsForLlamaSourceBuild {
# CMake
if ($null -eq (Get-Command cmake -ErrorAction SilentlyContinue)) {
- Write-Host "CMake not found -- installing via winget (needed for the llama.cpp source build)..." -ForegroundColor Yellow
+ Write-StudioLine "CMake not found -- installing via winget (needed for the llama.cpp source build)..." -ForegroundColor Yellow
if ($null -ne (Get-Command winget -ErrorAction SilentlyContinue)) {
try {
Invoke-SetupCommand { winget install Kitware.CMake --source winget --accept-package-agreements --accept-source-agreements } | Out-Null
@@ -1402,8 +1423,8 @@ function Ensure-BuildToolsForLlamaSourceBuild {
if ($script:VsInstallPath) { return } # already detected by the early probe
$vsResult = Find-VsBuildTools
if (-not $vsResult) {
- Write-Host "Visual Studio Build Tools not found -- installing via winget..." -ForegroundColor Yellow
- Write-Host " (Needed only for the llama.cpp source build; may take several minutes)" -ForegroundColor Gray
+ Write-StudioLine "Visual Studio Build Tools not found -- installing via winget..." -ForegroundColor Yellow
+ Write-StudioLine " (Needed only for the llama.cpp source build; may take several minutes)" -ForegroundColor Gray
if ($null -ne (Get-Command winget -ErrorAction SilentlyContinue)) {
$prevEAPTemp = $ErrorActionPreference
$ErrorActionPreference = "Continue"
@@ -1419,10 +1440,10 @@ function Ensure-BuildToolsForLlamaSourceBuild {
step "vs" "$($vsResult.Generator) ($($vsResult.Source))"
if ($vsResult.ClExe) { substep "cl.exe: $($vsResult.ClExe)" }
} else {
- Write-Host "[ERROR] Visual Studio Build Tools are required for the llama.cpp source build but could not be found or installed." -ForegroundColor Red
- Write-Host " Manual install:" -ForegroundColor Red
- Write-Host ' 1. winget install Microsoft.VisualStudio.2022.BuildTools --source winget' -ForegroundColor Yellow
- Write-Host ' 2. Open Visual Studio Installer -> Modify -> check "Desktop development with C++"' -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] Visual Studio Build Tools are required for the llama.cpp source build but could not be found or installed." -ForegroundColor Red
+ Write-StudioLine " Manual install:" -ForegroundColor Red
+ Write-StudioLine ' 1. winget install Microsoft.VisualStudio.2022.BuildTools --source winget' -ForegroundColor Yellow
+ Write-StudioLine ' 2. Open Visual Studio Installer -> Modify -> check "Desktop development with C++"' -ForegroundColor Yellow
Exit-SetupFailure "Visual Studio Build Tools are required for the llama.cpp source build"
}
}
@@ -1462,7 +1483,7 @@ function Test-VCRedistInstalled {
# and Build Tools torch cannot import without it, and winget is absent on LTSC/Server images.
function Ensure-VCRedist {
if (Test-VCRedistInstalled) { step "vcredist" "present"; return }
- Write-Host "Microsoft Visual C++ Redistributable (2015-2022) is missing; the prebuilt llama.cpp and PyTorch need it. Installing the runtime..." -ForegroundColor Yellow
+ Write-StudioLine "Microsoft Visual C++ Redistributable (2015-2022) is missing; the prebuilt llama.cpp and PyTorch need it. Installing the runtime..." -ForegroundColor Yellow
if ($null -ne (Get-Command winget -ErrorAction SilentlyContinue)) {
try {
Invoke-SetupCommand { winget install --id Microsoft.VCRedist.2015+.x64 --source winget --accept-package-agreements --accept-source-agreements } | Out-Null
@@ -1573,7 +1594,7 @@ function Write-SetupVerboseDetail {
'Red' { (Get-StudioAnsi Err) }
default { (Get-StudioAnsi Dim) }
}
- Write-Host ($ansi + $Message + (Get-StudioAnsi Reset))
+ Write-StudioLine ($ansi + $Message + (Get-StudioAnsi Reset))
} else {
$fc = switch ($Color) {
'Green' { 'DarkGreen' }
@@ -1581,7 +1602,7 @@ function Write-SetupVerboseDetail {
'Cyan' { 'Green' }
default { $Color }
}
- Write-Host $Message -ForegroundColor $fc
+ Write-StudioLine $Message -ForegroundColor $fc
}
}
@@ -1606,7 +1627,7 @@ function Invoke-SetupCommand {
} else {
$output = & $Command 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
- Write-Host (Redact-InstallOutput $output) -ForegroundColor Red
+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red
}
}
return [int]$LASTEXITCODE
@@ -1626,11 +1647,11 @@ function Write-LlamaFailureLog {
)
if ($lines.Count -eq 0) { return }
if ($lines.Count -gt $MaxLines) {
- Write-Host " Showing last $MaxLines lines:" -ForegroundColor DarkGray
+ Write-StudioLine " Showing last $MaxLines lines:" -ForegroundColor DarkGray
$lines = $lines | Select-Object -Last $MaxLines
}
foreach ($line in $lines) {
- Write-Host " | $line" -ForegroundColor DarkGray
+ Write-StudioLine " | $line" -ForegroundColor DarkGray
}
}
# Plain (no ANSI) form of a step/substep message on the OS stdout handle.
@@ -1736,7 +1757,7 @@ function Show-NpmRegistryHint {
if ($mirror -in @("", "undefined", "null", "https://registry.npmjs.org", "https://registry.npmjs.org/")) {
$mirror = ""
}
- Write-Host ""
+ Write-StudioLine ""
step "frontend" "registry.npmjs.org looks blocked (corporate firewall/proxy?)" "Yellow"
if ($mirror) {
substep "Unsloth pins the public npm registry; your mirror is being ignored."
@@ -1754,13 +1775,13 @@ function Show-NpmRegistryHint {
# ─────────────────────────────────────────────
# Banner
# ─────────────────────────────────────────────
-Write-Host ""
+Write-StudioLine ""
if ($script:StudioVtOk -and -not $env:NO_COLOR) {
- Write-Host (" " + (Get-StudioAnsi Title) + [char]::ConvertFromUtf32(0x1F9A5) + " Unsloth Studio Setup" + (Get-StudioAnsi Reset))
- Write-Host (" {0}{1}{2}" -f (Get-StudioAnsi Dim), $Rule, (Get-StudioAnsi Reset))
+ Write-StudioLine (" " + (Get-StudioAnsi Title) + [char]::ConvertFromUtf32(0x1F9A5) + " Unsloth Studio Setup" + (Get-StudioAnsi Reset))
+ Write-StudioLine (" {0}{1}{2}" -f (Get-StudioAnsi Dim), $Rule, (Get-StudioAnsi Reset))
} else {
- Write-Host (" " + [char]::ConvertFromUtf32(0x1F9A5) + " Unsloth Studio Setup") -ForegroundColor Green
- Write-Host " $Rule" -ForegroundColor DarkGray
+ Write-StudioLine (" " + [char]::ConvertFromUtf32(0x1F9A5) + " Unsloth Studio Setup") -ForegroundColor Green
+ Write-StudioLine " $Rule" -ForegroundColor DarkGray
}
# WebView2 caches keyed by the bundle id can keep serving the previous frontend
@@ -1798,7 +1819,7 @@ function Clear-WebViewCaches {
# blank one must fail here instead of throwing a raw binding error under "Stop".
# Null or empty only: Join-Path accepts whitespace, and those runs used to complete.
if ([string]::IsNullOrEmpty($env:USERPROFILE)) {
- Write-Host "ERROR: USERPROFILE is not set." -ForegroundColor Red
+ Write-StudioLine "ERROR: USERPROFILE is not set." -ForegroundColor Red
Exit-SetupFailure "USERPROFILE is not set"
}
$_studioOverrideVar = $null
@@ -1822,12 +1843,12 @@ if ($_studioOverride) {
[System.IO.File]::WriteAllText($_setupWriteProbe, "")
Remove-Item -LiteralPath $_setupWriteProbe -Force -ErrorAction SilentlyContinue
} catch {
- Write-Host "ERROR: $_studioOverrideVar=$StudioHome is not writable." -ForegroundColor Red
+ Write-StudioLine "ERROR: $_studioOverrideVar=$StudioHome is not writable." -ForegroundColor Red
Exit-SetupFailure "$_studioOverrideVar=$StudioHome is not writable"
}
} else {
- Write-Host "ERROR: $_studioOverrideVar=$_studioOverride does not exist." -ForegroundColor Red
- Write-Host " Run install.ps1 to create the install root before 'unsloth studio update'." -ForegroundColor Red
+ Write-StudioLine "ERROR: $_studioOverrideVar=$_studioOverride does not exist." -ForegroundColor Red
+ Write-StudioLine " Run install.ps1 to create the install root before 'unsloth studio update'." -ForegroundColor Red
Exit-SetupFailure "$_studioOverrideVar=$_studioOverride does not exist"
}
} else {
@@ -1870,7 +1891,7 @@ try {
}
}
} catch {
- Write-Host "[DEBUG] Could not back up User PATH: $($_.Exception.Message)" -ForegroundColor DarkGray
+ Write-StudioLine "[DEBUG] Could not back up User PATH: $($_.Exception.Message)" -ForegroundColor DarkGray
}
# ==========================================================================
@@ -1952,7 +1973,7 @@ if (-not $HasNvidiaSmi) {
if (Test-NvidiaSmiHasGpu $p) {
$HasNvidiaSmi = $true
$NvidiaSmiExe = $p
- Write-Host " Found nvidia-smi at $(Split-Path $p -Parent)" -ForegroundColor Gray
+ Write-StudioLine " Found nvidia-smi at $(Split-Path $p -Parent)" -ForegroundColor Gray
break
}
} catch {}
@@ -2507,11 +2528,11 @@ if ($HasNvidiaSmi) {
} elseif ($script:IsIntelXpu) {
# Ranks above every AMD branch: only true when AMD gets no GPU wheel ($AmdHasGpuWheels gates
# the scan above), so those branches would all end on CPU torch.
- Write-Host ""
+ Write-StudioLine ""
step "gpu" "Intel GPU detected" "Green"
substep "$IntelGpuLabel"
substep "PyTorch XPU (SYCL) wheels provide training and GPU inference on this GPU." "Cyan"
- Write-Host ""
+ Write-StudioLine ""
} elseif ($HasROCm) {
step "gpu" $ROCmGpuLabel
$hipSdkPath = if ($env:HIP_PATH) { $env:HIP_PATH } elseif ($env:ROCM_PATH) { $env:ROCM_PATH } else { "on system PATH" }
@@ -2520,7 +2541,7 @@ if ($HasNvidiaSmi) {
} elseif ($HipSdkInstalled -and $ROCmGpuLabel) {
# HIP SDK is installed but ROCm can't see the device (driver issue, not SDK issue)
$sdkVer = if ($script:ROCmVersionFull) { " (HIP $script:ROCmVersionFull)" } else { "" }
- Write-Host ""
+ Write-StudioLine ""
step "gpu" "AMD GPU detected -- not ROCm-accessible$sdkVer" "Yellow"
substep "Detected: $ROCmGpuLabel" "Yellow"
substep "[WARN] HIP SDK is installed but hipinfo reports no ROCm-capable device." "Yellow"
@@ -2530,24 +2551,24 @@ if ($HasNvidiaSmi) {
} elseif ($script:ROCmGfxArch) {
# Known arch: PyTorch comes from AMD's bundled-runtime ROCm wheels (repo.amd.com),
# which ship their own runtime -- HIP SDK optional (only adds the system toolchain).
- Write-Host ""
+ Write-StudioLine ""
step "gpu" "AMD ROCm ($script:ROCmGfxArch)" "Cyan"
substep "Detected: $ROCmGpuLabel" "Cyan"
substep "GPU PyTorch uses AMD's bundled-runtime ROCm wheels -- HIP SDK not required (optional)." "Cyan"
- Write-Host ""
+ Write-StudioLine ""
} elseif ($ROCmGpuLabel) {
- Write-Host ""
+ Write-StudioLine ""
step "gpu" "AMD GPU detected -- arch unknown" "Yellow"
substep "Detected: $ROCmGpuLabel" "Yellow"
substep "Could not determine the GPU arch (gfx...). Install the HIP SDK or set" "Yellow"
substep "UNSLOTH_ROCM_GFX_ARCH to enable GPU ROCm PyTorch:" "Yellow"
substep "https://rocm.docs.amd.com/en/latest/deploy/windows/index.html" "Yellow"
- Write-Host ""
+ Write-StudioLine ""
} else {
- Write-Host ""
+ Write-StudioLine ""
step "gpu" "none (chat-only / GGUF)" "Yellow"
substep "Training and GPU inference require an NVIDIA, AMD ROCm, or Intel Arc GPU." "Yellow"
- Write-Host ""
+ Write-StudioLine ""
}
# ============================================
@@ -2564,8 +2585,8 @@ try {
if ($LongPathsEnabled) {
step "long paths" "enabled"
} else {
- Write-Host "Windows Long Paths not enabled (required for Triton compilation and deep dependency paths)." -ForegroundColor Yellow
- Write-Host " Requesting admin access to fix..." -ForegroundColor Yellow
+ Write-StudioLine "Windows Long Paths not enabled (required for Triton compilation and deep dependency paths)." -ForegroundColor Yellow
+ Write-StudioLine " Requesting admin access to fix..." -ForegroundColor Yellow
try {
# Spawn an elevated process to set the registry key (triggers UAC prompt)
$proc = Start-Process -FilePath "reg.exe" `
@@ -2579,8 +2600,8 @@ if ($LongPathsEnabled) {
}
} catch {
step "long paths" "could not enable (UAC declined/unavailable)" "Yellow"
- Write-Host " Run this manually in an Admin terminal:" -ForegroundColor Yellow
- Write-Host ' reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f' -ForegroundColor Cyan
+ Write-StudioLine " Run this manually in an Admin terminal:" -ForegroundColor Yellow
+ Write-StudioLine ' reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f' -ForegroundColor Cyan
}
}
@@ -2626,7 +2647,7 @@ if (-not $HasGit) {
if ($_prForce -match '^\d+$' -and [int]$_prForce -gt 0) { $gitNeeded = $true }
if ($_llamaSrc -ne "https://github.com/ggml-org/llama.cpp") { $gitNeeded = $true }
}
- Write-Host "Git not found -- attempting install via winget..." -ForegroundColor Yellow
+ Write-StudioLine "Git not found -- attempting install via winget..." -ForegroundColor Yellow
$HasWinget = $null -ne (Get-Command winget -ErrorAction SilentlyContinue)
if ($HasWinget) {
try {
@@ -2637,9 +2658,9 @@ if (-not $HasGit) {
}
if (-not $HasGit) {
if ($gitNeeded) {
- Write-Host "[ERROR] Git is required for --local and llama.cpp source-build installs but could not be installed." -ForegroundColor Red
- Write-Host " --local clones unsloth-zoo, and a source build clones llama.cpp." -ForegroundColor Red
- Write-Host " Install Git from https://git-scm.com/download/win and re-run." -ForegroundColor Red
+ Write-StudioLine "[ERROR] Git is required for --local and llama.cpp source-build installs but could not be installed." -ForegroundColor Red
+ Write-StudioLine " --local clones unsloth-zoo, and a source build clones llama.cpp." -ForegroundColor Red
+ Write-StudioLine " Install Git from https://git-scm.com/download/win and re-run." -ForegroundColor Red
Exit-SetupFailure "Git is required for --local / source-build installs but could not be installed"
}
step "git" "not found (not required)" "Yellow"
@@ -2810,16 +2831,16 @@ if (-not $NvccPath -and $IncompatibleToolkit) {
}
# Reached only by a source build (forced, or after a prebuilt-install failure);
# with no compatible toolkit it must fail (setup.sh degrades to CPU instead).
- Write-Host "" -ForegroundColor Red
- Write-Host "========================================================================" -ForegroundColor Red
- Write-Host "[ERROR] CUDA source build cannot use the installed toolkit with this driver." -ForegroundColor Red
- Write-Host "========================================================================" -ForegroundColor Red
+ Write-StudioLine "" -ForegroundColor Red
+ Write-StudioLine "========================================================================" -ForegroundColor Red
+ Write-StudioLine "[ERROR] CUDA source build cannot use the installed toolkit with this driver." -ForegroundColor Red
+ Write-StudioLine "========================================================================" -ForegroundColor Red
Exit-SetupFailure "The installed CUDA toolkit is incompatible with the current driver"
}
# -- No toolkit at all: install via winget (only when a source build needs it) --
if (-not $NvccPath -and $RequireOrExit) {
- Write-Host "CUDA toolkit (nvcc) not found -- installing via winget..." -ForegroundColor Yellow
+ Write-StudioLine "CUDA toolkit (nvcc) not found -- installing via winget..." -ForegroundColor Yellow
$HasWinget = $null -ne (Get-Command winget -ErrorAction SilentlyContinue)
if ($HasWinget) {
if ($DriverMaxCuda) {
@@ -2880,11 +2901,11 @@ if (-not $NvccPath) {
$script:CudaToolkitReady = $false
return
}
- Write-Host "[ERROR] CUDA Toolkit (nvcc) is required but could not be found or installed." -ForegroundColor Red
+ Write-StudioLine "[ERROR] CUDA Toolkit (nvcc) is required but could not be found or installed." -ForegroundColor Red
if ($DriverMaxCuda) {
- Write-Host " Install a CUDA Toolkit with major version $($DriverMaxCuda.Split('.')[0]) from https://developer.nvidia.com/cuda-toolkit-archive" -ForegroundColor Yellow
+ Write-StudioLine " Install a CUDA Toolkit with major version $($DriverMaxCuda.Split('.')[0]) from https://developer.nvidia.com/cuda-toolkit-archive" -ForegroundColor Yellow
} else {
- Write-Host " Install CUDA Toolkit from https://developer.nvidia.com/cuda-downloads" -ForegroundColor Yellow
+ Write-StudioLine " Install CUDA Toolkit from https://developer.nvidia.com/cuda-downloads" -ForegroundColor Yellow
}
Exit-SetupFailure "A compatible CUDA Toolkit could not be found or installed"
}
@@ -3034,8 +3055,8 @@ if (-not $IsPipInstall) {
$NodeOverride = (Join-Path $env:USERPROFILE $NodeOverride.Substring(1).TrimStart('/', '\'))
}
if (-not (Test-Path -LiteralPath $NodeOverride -PathType Container)) {
- Write-Host "ERROR: UNSLOTH_STUDIO_HOME/STUDIO_HOME=$NodeOverride does not exist." -ForegroundColor Red
- Write-Host " Run install.ps1 to create the install root before 'unsloth studio update'." -ForegroundColor Red
+ Write-StudioLine "ERROR: UNSLOTH_STUDIO_HOME/STUDIO_HOME=$NodeOverride does not exist." -ForegroundColor Red
+ Write-StudioLine " Run install.ps1 to create the install root before 'unsloth studio update'." -ForegroundColor Red
Exit-SetupFailure "UNSLOTH_STUDIO_HOME/STUDIO_HOME=$NodeOverride does not exist"
}
$NodeParent = (Resolve-Path -LiteralPath $NodeOverride).Path
@@ -3210,7 +3231,7 @@ if ($PythonOk) {
# minors). Try winget as before -- gating on $HasPython alone, not also
# on $PyLauncher, so a launcher-only install with just 3.14 still gets
# an automatic 3.12 install instead of a hard error.
- Write-Host "Python 3.11-3.13 not found -- installing Python 3.12 via winget..." -ForegroundColor Yellow
+ Write-StudioLine "Python 3.11-3.13 not found -- installing Python 3.12 via winget..." -ForegroundColor Yellow
$HasWinget = $null -ne (Get-Command winget -ErrorAction SilentlyContinue)
if ($HasWinget) {
winget install -e --id Python.Python.3.12 --source winget --accept-package-agreements --accept-source-agreements
@@ -3218,8 +3239,8 @@ if ($PythonOk) {
}
$HasPython = $null -ne (Get-Command python -ErrorAction SilentlyContinue)
if (-not $HasPython) {
- Write-Host "[ERROR] Python could not be installed automatically." -ForegroundColor Red
- Write-Host " Install Python 3.12 from https://python.org/downloads/" -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] Python could not be installed automatically." -ForegroundColor Red
+ Write-StudioLine " Install Python 3.12 from https://python.org/downloads/" -ForegroundColor Yellow
Exit-SetupFailure "Python could not be installed automatically"
}
step "python" "$(python --version 2>&1)"
@@ -3227,9 +3248,9 @@ if ($PythonOk) {
} else {
# python.exe is on PATH but its version is unsupported, and py.exe (if
# present) had no supported minor either.
- Write-Host "[ERROR] No supported Python (3.11-3.13) found on this system." -ForegroundColor Red
- Write-Host " py.exe could not locate -3.11/-3.12/-3.13 and `python` on PATH is unsupported." -ForegroundColor Yellow
- Write-Host " Install Python 3.12 from https://python.org/downloads/" -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] No supported Python (3.11-3.13) found on this system." -ForegroundColor Red
+ Write-StudioLine " py.exe could not locate -3.11/-3.12/-3.13 and `python` on PATH is unsupported." -ForegroundColor Yellow
+ Write-StudioLine " Install Python 3.12 from https://python.org/downloads/" -ForegroundColor Yellow
Exit-SetupFailure "No supported Python 3.11-3.13 was found"
}
@@ -3247,9 +3268,9 @@ if ($LASTEXITCODE -eq 0 -and $ScriptsDir -and (Test-Path $ScriptsDir)) {
}
}
-Write-Host ""
+Write-StudioLine ""
step "system" "prerequisites ready"
-Write-Host ""
+Write-StudioLine ""
# ==========================================================================
# PHASE 2: Frontend build (skip if pip-installed -- already bundled)
@@ -3310,8 +3331,8 @@ if ($NeedNodeForSetup) {
$nodeOwnedMarker = Join-Path $NodeDir ".unsloth-studio-owned"
$nodeMeta = Join-Path $NodeDir "UNSLOTH_NODE_PREBUILT_INFO.json"
if (-not (Test-Path -LiteralPath $nodeOwnedMarker) -and -not (Test-Path -LiteralPath $nodeMeta)) {
- Write-Host "[ERROR] $NodeDir already exists and is not an Unsloth-owned Node install." -ForegroundColor Red
- Write-Host " Move it aside or choose an empty UNSLOTH_STUDIO_HOME before re-running." -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] $NodeDir already exists and is not an Unsloth-owned Node install." -ForegroundColor Red
+ Write-StudioLine " Move it aside or choose an empty UNSLOTH_STUDIO_HOME before re-running." -ForegroundColor Yellow
Exit-SetupFailure "$NodeDir is not an Unsloth-owned Node install"
}
}
@@ -3322,13 +3343,13 @@ if ($NeedNodeForSetup) {
$nodeOut = & $NodeInstallPython "$PSScriptRoot\install_node_prebuilt.py" --install-dir $NodeDir 2>&1 | Out-String
$nodeExit = $LASTEXITCODE
if ($nodeExit -eq 3) {
- Write-Host $nodeOut -ForegroundColor DarkGray
+ Write-StudioLine $nodeOut -ForegroundColor DarkGray
step "node" "install blocked by another active Unsloth install" "Red"
Exit-SetupFailure "Node install is blocked by another active Unsloth install" 3
} elseif ($nodeExit -ne 0) {
- Write-Host $nodeOut -ForegroundColor DarkGray
- Write-Host "[ERROR] Could not install an isolated Node automatically." -ForegroundColor Red
- Write-Host " Install Node >= 20.19 (with npm >= 11) from https://nodejs.org/ and re-run, or check your network." -ForegroundColor Yellow
+ Write-StudioLine $nodeOut -ForegroundColor DarkGray
+ Write-StudioLine "[ERROR] Could not install an isolated Node automatically." -ForegroundColor Red
+ Write-StudioLine " Install Node >= 20.19 (with npm >= 11) from https://nodejs.org/ and re-run, or check your network." -ForegroundColor Yellow
Exit-SetupFailure "Could not install an isolated Node runtime"
}
if ($NodeOverride -and (Test-Path -LiteralPath $NodeDir -PathType Container)) {
@@ -3370,7 +3391,7 @@ if ($NeedNodeForSetup) {
}
}
if ($NeedFrontendBuild -and -not $IsPipInstall) {
- Write-Host ""
+ Write-StudioLine ""
substep "building frontend..."
# ── Tailwind v4 .gitignore workaround ──
@@ -3407,7 +3428,7 @@ if ($NeedFrontendBuild -and -not $IsPipInstall) {
# exits 0 but leaves binaries missing. We validate after install and clear
# the cache + retry once before falling back to npm.
if ($UseBun) {
- Write-Host " Using bun for package install (faster)" -ForegroundColor DarkGray
+ Write-StudioLine " Using bun for package install (faster)" -ForegroundColor DarkGray
$bunExit = Invoke-SetupCommand { bun install @NpmRegistryArgs }
# On Windows, .bin/ entries vary by package manager:
# npm → tsc, tsc.cmd, tsc.ps1
@@ -3417,7 +3438,7 @@ if ($NeedFrontendBuild -and -not $IsPipInstall) {
if ($bunExit -eq 0 -and $hasTsc -and $hasVite) {
# bun install succeeded and critical binaries are present
} elseif ($bunExit -eq 0) {
- Write-Host " bun install exited 0 but critical binaries are missing, clearing cache and retrying..." -ForegroundColor Yellow
+ Write-StudioLine " bun install exited 0 but critical binaries are missing, clearing cache and retrying..." -ForegroundColor Yellow
if (Test-Path "node_modules") {
Remove-Item "node_modules" -Recurse -Force -ErrorAction SilentlyContinue
}
@@ -3426,7 +3447,7 @@ if ($NeedFrontendBuild -and -not $IsPipInstall) {
$hasTsc = (Test-Path "node_modules\.bin\tsc") -or (Test-Path "node_modules\.bin\tsc.cmd") -or (Test-Path "node_modules\.bin\tsc.exe") -or (Test-Path "node_modules\.bin\tsc.bunx")
$hasVite = (Test-Path "node_modules\.bin\vite") -or (Test-Path "node_modules\.bin\vite.cmd") -or (Test-Path "node_modules\.bin\vite.exe") -or (Test-Path "node_modules\.bin\vite.bunx")
if ($bunExit -ne 0 -or -not $hasTsc -or -not $hasVite) {
- Write-Host " bun retry failed, falling back to npm" -ForegroundColor Yellow
+ Write-StudioLine " bun retry failed, falling back to npm" -ForegroundColor Yellow
if (Test-Path "node_modules") {
Remove-Item "node_modules" -Recurse -Force -ErrorAction SilentlyContinue
}
@@ -3446,8 +3467,8 @@ if ($NeedFrontendBuild -and -not $IsPipInstall) {
Pop-Location
$ErrorActionPreference = $prevEAP_npm
foreach ($gi in $HiddenGitignores) { Rename-Item -Path "$gi._twbuild" -NewName (Split-Path $gi -Leaf) -Force -ErrorAction SilentlyContinue }
- Write-Host "[ERROR] npm install failed (exit code $npmExit)" -ForegroundColor Red
- Write-Host " Try running 'npm install' manually in frontend/ to see errors" -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] npm install failed (exit code $npmExit)" -ForegroundColor Red
+ Write-StudioLine " Try running 'npm install' manually in frontend/ to see errors" -ForegroundColor Yellow
Show-NpmRegistryHint
Exit-SetupFailure "Frontend dependency installation failed (exit code $npmExit)"
}
@@ -3459,7 +3480,7 @@ if ($NeedFrontendBuild -and -not $IsPipInstall) {
Pop-Location
$ErrorActionPreference = $prevEAP_npm
foreach ($gi in $HiddenGitignores) { Rename-Item -Path "$gi._twbuild" -NewName (Split-Path $gi -Leaf) -Force -ErrorAction SilentlyContinue }
- Write-Host "[ERROR] npm run build failed (exit code $buildExit)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] npm run build failed (exit code $buildExit)" -ForegroundColor Red
Exit-SetupFailure "Frontend build failed (exit code $buildExit)"
}
Pop-Location
@@ -3489,7 +3510,7 @@ if ((Test-Path $OxcValidatorDir) -and $NodeSource -ne "skip" -and (Get-Command n
if ($oxcInstallExit -ne 0) {
Pop-Location
$ErrorActionPreference = $prevEAP_oxc
- Write-Host "[ERROR] OXC validator npm install failed (exit code $oxcInstallExit)" -ForegroundColor Red
+ Write-StudioLine "[ERROR] OXC validator npm install failed (exit code $oxcInstallExit)" -ForegroundColor Red
Show-NpmRegistryHint
Exit-SetupFailure "OXC validator dependency installation failed (exit code $oxcInstallExit)"
}
@@ -3510,7 +3531,7 @@ Remove-AgentInstructionFiles -Roots @(
# ==========================================================================
# PHASE 3: Python environment + dependencies
# ==========================================================================
-Write-Host ""
+Write-StudioLine ""
substep "setting up Python environment..."
# Find Python -- skip Anaconda/Miniconda distributions ($CondaSkipPattern and
@@ -3587,9 +3608,9 @@ if (-not $PythonCmd) {
}
if (-not $PythonCmd) {
- Write-Host "[ERROR] No standalone Python 3.11-3.13 found (conda Python is not supported)." -ForegroundColor Red
- Write-Host " Install Python from https://python.org/downloads/ or via:" -ForegroundColor Yellow
- Write-Host " winget install -e --id Python.Python.3.12" -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] No standalone Python 3.11-3.13 found (conda Python is not supported)." -ForegroundColor Red
+ Write-StudioLine " Install Python from https://python.org/downloads/ or via:" -ForegroundColor Yellow
+ Write-StudioLine " winget install -e --id Python.Python.3.12" -ForegroundColor Yellow
Exit-SetupFailure "No standalone Python 3.11-3.13 was found"
}
@@ -3674,8 +3695,8 @@ function Assert-StudioOwnedOrAbsent {
Mark-StudioOwned $Path
return
}
- Write-Host "[ERROR] $Path already exists and is not marked as an Unsloth-owned $Label." -ForegroundColor Red
- Write-Host " Move it aside or choose an empty UNSLOTH_STUDIO_HOME before re-running." -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] $Path already exists and is not marked as an Unsloth-owned $Label." -ForegroundColor Red
+ Write-StudioLine " Move it aside or choose an empty UNSLOTH_STUDIO_HOME before re-running." -ForegroundColor Yellow
Exit-SetupFailure "$Label path is not an Unsloth-owned install: $Path"
}
}
@@ -3908,8 +3929,8 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
$reason = if ($installedTorchTag) { "torch $installedTorchTag != required $expectedTorchTag" } else { "torch could not be imported" }
if ($InstallerManagedSetup) {
substep "Stale venv detected ($reason)." "Yellow"
- Write-Host " [ERROR] The existing Unsloth environment needs repair." -ForegroundColor Red
- Write-Host " Re-run install.ps1 so it can replace the environment safely with rollback." -ForegroundColor Yellow
+ Write-StudioLine " [ERROR] The existing Unsloth environment needs repair." -ForegroundColor Red
+ Write-StudioLine " Re-run install.ps1 so it can replace the environment safely with rollback." -ForegroundColor Yellow
Exit-SetupFailure "The existing Unsloth environment needs repair"
}
substep "Stale venv detected ($reason) -- rebuilding..." "Yellow"
@@ -3922,24 +3943,24 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
-not (Test-Path -LiteralPath (Join-Path $StudioHome "share\studio.conf") -PathType Leaf) -and
-not (Test-Path -LiteralPath (Join-Path $StudioHome "bin\unsloth.exe") -PathType Leaf)
) {
- Write-Host "[ERROR] $VenvDir already exists but does not look like an Unsloth Studio install." -ForegroundColor Red
- Write-Host " Move it aside or choose an empty UNSLOTH_STUDIO_HOME before re-running." -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] $VenvDir already exists but does not look like an Unsloth Studio install." -ForegroundColor Red
+ Write-StudioLine " Move it aside or choose an empty UNSLOTH_STUDIO_HOME before re-running." -ForegroundColor Yellow
Exit-SetupFailure "$VenvDir is not an Unsloth Studio environment"
}
try {
Remove-Item -LiteralPath $VenvDir -Recurse -Force -ErrorAction Stop
} catch {
- Write-Host " [ERROR] Could not remove stale venv: $($_.Exception.Message)" -ForegroundColor Red
- Write-Host " Close any running Unsloth/Python processes and re-run setup." -ForegroundColor Red
+ Write-StudioLine " [ERROR] Could not remove stale venv: $($_.Exception.Message)" -ForegroundColor Red
+ Write-StudioLine " Close any running Unsloth/Python processes and re-run setup." -ForegroundColor Red
Exit-SetupFailure "Could not remove the stale environment at $VenvDir"
}
}
}
if (-not (Test-Path -LiteralPath $VenvDir)) {
- Write-Host "[ERROR] Virtual environment not found at $VenvDir" -ForegroundColor Red
- Write-Host " Run install.ps1 first to create the environment:" -ForegroundColor Yellow
- Write-Host " irm https://unsloth.ai/install.ps1 | iex" -ForegroundColor Yellow
+ Write-StudioLine "[ERROR] Virtual environment not found at $VenvDir" -ForegroundColor Red
+ Write-StudioLine " Run install.ps1 first to create the environment:" -ForegroundColor Yellow
+ Write-StudioLine " irm https://unsloth.ai/install.ps1 | iex" -ForegroundColor Yellow
Exit-SetupFailure "Virtual environment not found at $VenvDir"
} else {
substep "reusing existing virtual environment at $VenvDir"
@@ -4224,8 +4245,8 @@ sys.exit(0 if install_manifest.remove_manifest() else 1)
if ($LASTEXITCODE -ne 0) { $_ManifestDropped = $false }
} catch { $_ManifestDropped = $false }
if (-not $_ManifestDropped) {
- Write-Host "[ERROR] Could not remove the stale unsloth_install_manifest.json." -ForegroundColor Red
- Write-Host " Refusing to install behind a marker that still reports this venv as complete." -ForegroundColor Red
+ Write-StudioLine "[ERROR] Could not remove the stale unsloth_install_manifest.json." -ForegroundColor Red
+ Write-StudioLine " Refusing to install behind a marker that still reports this venv as complete." -ForegroundColor Red
Exit-SetupFailure "Could not remove the stale unsloth_install_manifest.json"
}
@@ -4409,8 +4430,8 @@ if ($ROCmIndexUrl) {
$torchInstallExit = $LASTEXITCODE
}
if ($torchInstallExit -ne 0) {
- Write-Host "[WARN] AMD ROCm PyTorch install failed -- falling back to CPU" -ForegroundColor Yellow
- Write-Host (Redact-InstallOutput $output) -ForegroundColor Yellow
+ Write-StudioLine "[WARN] AMD ROCm PyTorch install failed -- falling back to CPU" -ForegroundColor Yellow
+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Yellow
$ROCmIndexUrl = $null
$ROCmCpuFallback = $true
} else {
@@ -4451,8 +4472,8 @@ if ($XpuIndexUrl) {
if ($torchInstallExit -ne 0) {
# Transient XPU-index failure: fall back to a CPU base rather than leaving no torch
# (same shape as ROCm above).
- Write-Host "[WARN] Intel XPU PyTorch install failed -- falling back to CPU" -ForegroundColor Yellow
- Write-Host (Redact-InstallOutput $output) -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Intel XPU PyTorch install failed -- falling back to CPU" -ForegroundColor Yellow
+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Yellow
$XpuIndexUrl = $null
$XpuCpuFallback = $true
$TorchInstallIndexUrl = "$PyTorchWhlBase/cpu"
@@ -4503,8 +4524,8 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
$torchInstallExit = $LASTEXITCODE
}
if ($torchInstallExit -ne 0) {
- Write-Host "[FAILED] PyTorch install failed (exit code $torchInstallExit)" -ForegroundColor Red
- Write-Host (Redact-InstallOutput $output) -ForegroundColor Red
+ Write-StudioLine "[FAILED] PyTorch install failed (exit code $torchInstallExit)" -ForegroundColor Red
+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red
Exit-SetupFailure "PyTorch installation failed (exit code $torchInstallExit)"
}
} elseif (-not $ROCmIndexUrl -and -not $XpuIndexUrl) {
@@ -4539,8 +4560,8 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
$torchInstallExit = $LASTEXITCODE
}
if ($torchInstallExit -ne 0) {
- Write-Host "[FAILED] PyTorch CUDA install failed (exit code $torchInstallExit)" -ForegroundColor Red
- Write-Host (Redact-InstallOutput $output) -ForegroundColor Red
+ Write-StudioLine "[FAILED] PyTorch CUDA install failed (exit code $torchInstallExit)" -ForegroundColor Red
+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red
Exit-SetupFailure "PyTorch CUDA installation failed (exit code $torchInstallExit)"
}
@@ -4556,7 +4577,7 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
}
if ($tritonInstallExit -ne 0) {
substep "Triton install failed -- torch.compile may not work" "Yellow"
- Write-Host (Redact-InstallOutput $output) -ForegroundColor Yellow
+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Yellow
} else {
substep "Triton for Windows installed (enables torch.compile)"
}
@@ -4599,7 +4620,7 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
}
if ($bnbXpuExit -ne 0) {
substep "[WARN] could not install an XPU-capable bitsandbytes (exit $bnbXpuExit); 4-bit QLoRA may be unavailable." "Yellow"
- Write-Host (Redact-InstallOutput $bnbOutput) -ForegroundColor Yellow
+ Write-StudioLine (Redact-InstallOutput $bnbOutput) -ForegroundColor Yellow
}
}
@@ -4650,7 +4671,7 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
$_tritonWheel = @(Get-ChildItem -LiteralPath $_tritonTmp -Filter "*.whl" -ErrorAction SilentlyContinue) | Select-Object -First 1 -ExpandProperty FullName
if ($tritonDlExit -ne 0 -or -not $_tritonWheel) {
substep "[WARN] could not fetch $_tritonXpuSpec (exit $tritonDlExit); triton-windows $_tritonWinVer left in place -- it still shadows torch XPU triton, so torch.compile will not use the XPU." "Yellow"
- Write-Host (Redact-InstallOutput $tritonDlOutput) -ForegroundColor Yellow
+ Write-StudioLine (Redact-InstallOutput $tritonDlOutput) -ForegroundColor Yellow
} else {
# From here to the reinstall below is a window where a kill leaves a venv with
# no triton that the next update still reads as complete and fast-paths past.
@@ -4711,15 +4732,15 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
Fast-Install --force-reinstall --no-deps "triton-windows<3.7" | Out-Null
$tritonBackExit = $LASTEXITCODE
$_tritonPresent = ($tritonBackExit -eq 0)
- Write-Host (Redact-InstallOutput $tritonOutput) -ForegroundColor Yellow
+ Write-StudioLine (Redact-InstallOutput $tritonOutput) -ForegroundColor Yellow
if ($tritonBackExit -eq 0) {
substep "[WARN] could not install $_tritonXpuSpec (exit $tritonXpuExit); restored triton-windows, so triton still imports -- but torch.compile will not use the XPU." "Yellow"
} else {
# Redacted: a mirror pin can carry a token, and this is the only place
# setup.ps1 shows an index URL. A tokenless URL survives verbatim.
$_tritonRepairUrl = Redact-InstallOutput $XpuIndexUrl
- Write-Host "[ERROR] triton-windows was removed and neither triton would reinstall -- torch.compile is broken." -ForegroundColor Red
- Write-Host " Repair with: python -m pip install --force-reinstall --no-deps $_tritonXpuSpec --index-url $_tritonRepairUrl" -ForegroundColor Red
+ Write-StudioLine "[ERROR] triton-windows was removed and neither triton would reinstall -- torch.compile is broken." -ForegroundColor Red
+ Write-StudioLine " Repair with: python -m pip install --force-reinstall --no-deps $_tritonXpuSpec --index-url $_tritonRepairUrl" -ForegroundColor Red
# Printing alone left $stackExit at 0, so setup reported success and
# install.ps1 COMMITTED this venv over its rollback copy. It has no
# importable triton at all; the caller must not accept it.
@@ -4750,8 +4771,8 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
# Restore ErrorActionPreference after pip/python work
$ErrorActionPreference = $prevEAP
if ($stackExit -ne 0) {
- Write-Host "[FAILED] Python dependency installation failed (exit code $stackExit)" -ForegroundColor Red
- Write-Host " Re-run the installer or check the error above for details." -ForegroundColor Red
+ Write-StudioLine "[FAILED] Python dependency installation failed (exit code $stackExit)" -ForegroundColor Red
+ Write-StudioLine " Re-run the installer or check the error above for details." -ForegroundColor Red
Exit-SetupFailure "Python dependency installation failed (exit code $stackExit)"
}
@@ -4806,7 +4827,7 @@ if (-not (Test-TargetPackageVersion -TargetDir $VenvT5_510Dir -PackageName "tran
if (-not $SkipPythonDeps) { $_NeedT5Install = $true }
if ($_NeedT5Install) {
-Write-Host ""
+Write-StudioLine ""
$prevEAP_t5 = $ErrorActionPreference
$ErrorActionPreference = "Continue"
@@ -4827,8 +4848,8 @@ foreach ($pkg in @("transformers==5.3.0", "huggingface_hub==1.8.0", "hf_xet==1.4
$t5PkgExit = $LASTEXITCODE
}
if ($t5PkgExit -ne 0) {
- Write-Host "[FAIL] Could not install $pkg into .venv_t5_530/" -ForegroundColor Red
- Write-Host (Redact-InstallOutput $output) -ForegroundColor Red
+ Write-StudioLine "[FAIL] Could not install $pkg into .venv_t5_530/" -ForegroundColor Red
+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red
$ErrorActionPreference = $prevEAP_t5
Exit-SetupFailure "Could not install $pkg into .venv_t5_530"
}
@@ -4862,8 +4883,8 @@ foreach ($pkg in @("transformers==5.5.0", "huggingface_hub==1.8.0", "hf_xet==1.4
$t5PkgExit = $LASTEXITCODE
}
if ($t5PkgExit -ne 0) {
- Write-Host "[FAIL] Could not install $pkg into .venv_t5_550/" -ForegroundColor Red
- Write-Host (Redact-InstallOutput $output) -ForegroundColor Red
+ Write-StudioLine "[FAIL] Could not install $pkg into .venv_t5_550/" -ForegroundColor Red
+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red
$ErrorActionPreference = $prevEAP_t5
Exit-SetupFailure "Could not install $pkg into .venv_t5_550"
}
@@ -4897,8 +4918,8 @@ foreach ($pkg in @("transformers==5.10.2", "huggingface_hub==1.8.0", "hf_xet==1.
$t5PkgExit = $LASTEXITCODE
}
if ($t5PkgExit -ne 0) {
- Write-Host "[FAIL] Could not install $pkg into .venv_t5_510/" -ForegroundColor Red
- Write-Host (Redact-InstallOutput $output) -ForegroundColor Red
+ Write-StudioLine "[FAIL] Could not install $pkg into .venv_t5_510/" -ForegroundColor Red
+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red
$ErrorActionPreference = $prevEAP_t5
Exit-SetupFailure "Could not install $pkg into .venv_t5_510"
}
@@ -5018,7 +5039,7 @@ if (-not $LlamaPr -and $LlamaPrForce -and $LlamaPrForce -match '^\d+$' -and [int
if ($LlamaPr) {
if ($LlamaPr -notmatch '^\d+$' -or [int]$LlamaPr -le 0) {
- Write-Host "[ERROR] UNSLOTH_LLAMA_PR=$LlamaPr is not a valid PR number" -ForegroundColor Red
+ Write-StudioLine "[ERROR] UNSLOTH_LLAMA_PR=$LlamaPr is not a valid PR number" -ForegroundColor Red
Exit-SetupFailure "UNSLOTH_LLAMA_PR=$LlamaPr is not a valid PR number"
}
step "llama.cpp" "UNSLOTH_LLAMA_PR=$LlamaPr -- will build from PR head" "Yellow"
@@ -5132,7 +5153,7 @@ if ($LocalLlamaCppSrc) {
Copy-Item -Recurse -LiteralPath $ResolvedLocal -Destination $LlamaCppDir
Remove-AgentInstructionFiles -Roots @($LlamaCppDir)
}
- Write-Host ""
+ Write-StudioLine ""
step "llama.cpp" "linked local directory: $ResolvedLocal"
$LocalLlamaCppLinked = $true
$NeedLlamaSourceBuild = $false
@@ -5142,19 +5163,19 @@ if ($LocalLlamaCppSrc) {
if ($LocalLlamaCppLinked) {
# local directory linked above; skip prebuilt install
} elseif ($explicitVulkanSourceBuild -and $NeedLlamaSourceBuild) {
- Write-Host ""
+ Write-StudioLine ""
step "llama.cpp" "Vulkan was explicitly requested, but this installation requires a source build" "Red"
substep "Vulkan source builds are not supported by this installer; use the prebuilt Vulkan bundle or unset the Vulkan override" "Yellow"
Exit-SetupFailure "Vulkan was explicitly requested, but this installation requires a source build, which this installer does not support. Use the prebuilt Vulkan bundle or unset the Vulkan override."
} elseif ($env:UNSLOTH_LLAMA_FORCE_COMPILE -eq "1") {
- Write-Host ""
+ Write-StudioLine ""
substep "UNSLOTH_LLAMA_FORCE_COMPILE=1 -- skipping prebuilt llama.cpp install" "Yellow"
$NeedLlamaSourceBuild = $true
} elseif ($SkipPrebuiltInstall) {
- Write-Host ""
+ Write-StudioLine ""
substep "Skipping prebuilt install -- falling back to source build" "Yellow"
} else {
- Write-Host ""
+ Write-StudioLine ""
# Keep this late guard as defense in depth before the prebuilt installer.
$llamaDirState = Get-LlamaCppInstallReadState -Path $LlamaCppDir
if ($llamaDirState -eq "Denied") {
@@ -5236,16 +5257,16 @@ if ($LocalLlamaCppLinked) {
$prebuiltArgs += "--force-cpu"
} elseif ($llamaBackend -eq "vulkan") {
if ($IsMacOS) {
- Write-Host "[WARN] Vulkan has no effect on macOS; the universal build uses Metal" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Vulkan has no effect on macOS; the universal build uses Metal" -ForegroundColor Yellow
} elseif ($windowsArm64) {
throw "Vulkan was requested, but no Windows ARM64 Vulkan bundle is published. Unset UNSLOTH_LLAMA_CPP_BACKEND or compile llama.cpp from source."
} else {
$prebuiltArgs += @("--llama-backend", "vulkan")
$explicitVulkanBackend = $true
- Write-Host " llama.cpp Vulkan selected for GGUF inference; the PyTorch training backend is unchanged" -ForegroundColor Cyan
+ Write-StudioLine " llama.cpp Vulkan selected for GGUF inference; the PyTorch training backend is unchanged" -ForegroundColor Cyan
}
} elseif ($llamaBackend -and $llamaBackend -notin @("auto", "hip", "rocm")) {
- Write-Host "[WARN] Ignoring UNSLOTH_LLAMA_CPP_BACKEND='$llamaBackend' (expected 'auto', 'cpu', 'vulkan', 'hip', or 'rocm')" -ForegroundColor Yellow
+ Write-StudioLine "[WARN] Ignoring UNSLOTH_LLAMA_CPP_BACKEND='$llamaBackend' (expected 'auto', 'cpu', 'vulkan', 'hip', or 'rocm')" -ForegroundColor Yellow
}
if (
-not $IsMacOS -and
@@ -5459,7 +5480,7 @@ if ($NeedLlamaSourceBuild) {
$OpenSslAvailable = $true
substep "OpenSSL dev found at $OpenSslRoot"
} else {
- Write-Host ""
+ Write-StudioLine ""
substep "installing OpenSSL dev (for HTTPS in llama-server)..."
$HasWinget = $null -ne (Get-Command winget -ErrorAction SilentlyContinue)
if ($HasWinget) {
@@ -5523,10 +5544,10 @@ if ($llamaBinState -eq "Present") {
Exit-PathAccessDenied -Path $LlamaCppDir -Label "llama.cpp install" -OwnershipUnverified:$StudioHomeIsCustom
}
if ($HasNvidiaSmi -and -not $cachedCuda) {
- Write-Host " Existing llama-server is CPU-only but GPU is available -- rebuilding" -ForegroundColor Yellow
+ Write-StudioLine " Existing llama-server is CPU-only but GPU is available -- rebuilding" -ForegroundColor Yellow
$NeedRebuild = $true
} elseif (-not $HasNvidiaSmi -and $cachedCuda) {
- Write-Host " Existing llama-server was built with CUDA but no GPU detected -- rebuilding" -ForegroundColor Yellow
+ Write-StudioLine " Existing llama-server was built with CUDA but no GPU detected -- rebuilding" -ForegroundColor Yellow
$NeedRebuild = $true
}
}
@@ -5566,29 +5587,29 @@ if ($LocalLlamaCppLinked) {
# Local dir linked above -- honor the flag's contract: skip BOTH the prebuilt
# download and the source build. Falling through here would run CMake inside
# the user's checkout (via the junction) when it lacks build\bin\Release\llama-server.exe.
- Write-Host ""
+ Write-StudioLine ""
step "llama.cpp" "linked (skipping build)"
} elseif (-not $NeedLlamaSourceBuild) {
- Write-Host ""
+ Write-StudioLine ""
step "llama.cpp" "prebuilt (validated)"
} elseif ((Test-PathQuiet $LlamaServerBin "Leaf") -and -not $NeedRebuild -and $RequestedLlamaTag -ne "master") {
# Skip rebuild only for pinned tags (e.g. b8635). When the requested
# tag is "master" (a moving target), always rebuild so the binary picks
# up new model architecture support (e.g. Gemma 4).
- Write-Host ""
+ Write-StudioLine ""
step "llama.cpp" "already built"
} elseif (-not $HasGitForBuild) {
# Before cmake: the toolchain install is skipped without git, so cmake may be missing
# purely as a consequence. Degrade rather than abort; the opt-in source triggers already
# required git in Phase 1, so only the automatic fallback lands here.
- Write-Host ""
+ Write-StudioLine ""
step "llama.cpp" "build skipped (git not available)" "Yellow"
substep "The prebuilt download failed and a source build clones llama.cpp." "Yellow"
substep "GGUF inference and export will not be available." "Yellow"
substep "Install Git from https://git-scm.com/download/win and re-run setup." "Yellow"
$script:LlamaCppDegraded = $true
} elseif (-not $HasCmakeForBuild) {
- Write-Host ""
+ Write-StudioLine ""
if (-not $HasNvidiaSmi) {
# CPU-only machines depend entirely on llama-server for GGUF chat -- cmake is required
substep "CMake is required to build llama-server for GGUF chat mode." "Yellow"
@@ -5637,8 +5658,8 @@ if ($LocalLlamaCppLinked) {
$CmakeGenerator = $fallback.Generator
$VsInstallPath = $fallback.InstallPath
} else {
- Write-Host "[ERROR] CMake 4.2+ is required to build llama.cpp with the Visual Studio 2026 generator, and no older Visual Studio toolchain was found to fall back to." -ForegroundColor Red
- Write-Host " Upgrade CMake from https://cmake.org/download/ and re-run, or use a prebuilt llama.cpp bundle." -ForegroundColor Red
+ Write-StudioLine "[ERROR] CMake 4.2+ is required to build llama.cpp with the Visual Studio 2026 generator, and no older Visual Studio toolchain was found to fall back to." -ForegroundColor Red
+ Write-StudioLine " Upgrade CMake from https://cmake.org/download/ and re-run, or use a prebuilt llama.cpp bundle." -ForegroundColor Red
Exit-SetupFailure "CMake cannot drive the Visual Studio 2026 generator"
}
}
@@ -5650,7 +5671,7 @@ if ($LocalLlamaCppLinked) {
# .targets land in the toolset cmake actually uses.
if ($HasNvidiaSmi) { Resolve-CudaToolkit -RequireOrExit }
- Write-Host ""
+ Write-StudioLine ""
if ($HasNvidiaSmi) {
substep "building llama.cpp with CUDA support..."
} elseif ($HasROCm -or $script:ROCmGfxArch) {
@@ -5669,7 +5690,7 @@ if ($LocalLlamaCppLinked) {
substep "building llama.cpp (CPU-only, no NVIDIA GPU detected)..."
}
substep "This typically takes 5-10 minutes on first build."
- Write-Host ""
+ Write-StudioLine ""
# Start total build timer
$totalSw = [System.Diagnostics.Stopwatch]::StartNew()
@@ -5760,7 +5781,7 @@ if ($LocalLlamaCppLinked) {
if ($StudioHomeIsCustom) {
Assert-StudioOwnedOrAbsent -Path $LlamaCppDir -Label "llama.cpp install"
}
- Write-Host " Syncing llama.cpp to $ResolvedSourceRef..." -ForegroundColor Gray
+ Write-StudioLine " Syncing llama.cpp to $ResolvedSourceRef..." -ForegroundColor Gray
# Always sync the remote URL so switching between default/fork sources works
Invoke-SetupCommand -AlwaysQuiet { git -C $LlamaCppDir remote set-url origin "$ResolvedSourceUrl.git" } | Out-Null
if ($LlamaPr) {
@@ -5837,7 +5858,7 @@ if ($LocalLlamaCppLinked) {
Mark-StudioOwned -Path $LlamaCppDir
}
} else {
- Write-Host " Cloning llama.cpp @ $ResolvedSourceRef..." -ForegroundColor Gray
+ Write-StudioLine " Cloning llama.cpp @ $ResolvedSourceRef..." -ForegroundColor Gray
$buildTmp = "$LlamaCppDir.build.$PID"
$null = [System.IO.Directory]::CreateDirectory((Split-Path -LiteralPath $LlamaCppDir))
if (Test-Path -LiteralPath $buildTmp) { Remove-Item -LiteralPath $buildTmp -Recurse -Force }
@@ -5933,8 +5954,8 @@ if ($LocalLlamaCppLinked) {
# -- Step B: cmake configure --
if ($BuildOk) {
- Write-Host ""
- Write-Host "--- cmake configure ---" -ForegroundColor Cyan
+ Write-StudioLine ""
+ Write-StudioLine "--- cmake configure ---" -ForegroundColor Cyan
$CmakeArgs = @(
'-S', $LlamaCppDir,
@@ -6018,13 +6039,13 @@ if ($LocalLlamaCppLinked) {
$FailedStep = "cmake configure"
Write-LlamaFailureLog -Output $cmakeOutput
if ($cmakeOutput -match 'No CUDA toolset found|CUDA_TOOLKIT_ROOT_DIR|nvcc') {
- Write-Host ""
- Write-Host " Hint: CUDA VS integration may be missing. Try running as admin:" -ForegroundColor Yellow
- Write-Host " Copy contents of:" -ForegroundColor Yellow
- Write-Host " <CUDA_PATH>\extras\visual_studio_integration\MSBuildExtensions" -ForegroundColor Yellow
- Write-Host " into:" -ForegroundColor Yellow
+ Write-StudioLine ""
+ Write-StudioLine " Hint: CUDA VS integration may be missing. Try running as admin:" -ForegroundColor Yellow
+ Write-StudioLine " Copy contents of:" -ForegroundColor Yellow
+ Write-StudioLine " <CUDA_PATH>\extras\visual_studio_integration\MSBuildExtensions" -ForegroundColor Yellow
+ Write-StudioLine " into:" -ForegroundColor Yellow
$hintCustomizations = if ($VsInstallPath) { Get-VcBuildCustomizationsDir -VsInstallPath $VsInstallPath -Generator $CmakeGenerator } else { "<VS_PATH>\MSBuild\Microsoft\VC\v170\BuildCustomizations" }
- Write-Host " $hintCustomizations" -ForegroundColor Yellow
+ Write-StudioLine " $hintCustomizations" -ForegroundColor Yellow
}
}
}
@@ -6033,10 +6054,10 @@ if ($LocalLlamaCppLinked) {
$NumCpu = Get-LlamaBuildJobs
if ($BuildOk) {
- Write-Host ""
- Write-Host "--- cmake build (llama-server) ---" -ForegroundColor Cyan
- Write-Host " Parallel jobs: $NumCpu of $([Environment]::ProcessorCount) cores (RAM-capped; UNSLOTH_LLAMA_BUILD_JOBS overrides)" -ForegroundColor Gray
- Write-Host ""
+ Write-StudioLine ""
+ Write-StudioLine "--- cmake build (llama-server) ---" -ForegroundColor Cyan
+ Write-StudioLine " Parallel jobs: $NumCpu of $([Environment]::ProcessorCount) cores (RAM-capped; UNSLOTH_LLAMA_BUILD_JOBS overrides)" -ForegroundColor Gray
+ Write-StudioLine ""
$output = cmake --build $BuildDir --config Release --target llama-server -j $NumCpu 2>&1 | Out-String
$cmakeBuildServerExit = $LASTEXITCODE
@@ -6049,8 +6070,8 @@ if ($LocalLlamaCppLinked) {
# -- Step D: Build llama-quantize (optional, best-effort) --
if ($BuildOk) {
- Write-Host ""
- Write-Host "--- cmake build (llama-quantize) ---" -ForegroundColor Cyan
+ Write-StudioLine ""
+ Write-StudioLine "--- cmake build (llama-quantize) ---" -ForegroundColor Cyan
$output = cmake --build $BuildDir --config Release --target llama-quantize -j $NumCpu 2>&1 | Out-String
$cmakeBuildQuantizeExit = $LASTEXITCODE
if ($cmakeBuildQuantizeExit -ne 0) {
@@ -6149,26 +6170,26 @@ if (-not $llamaCppIsLink -and (
# ─────────────────────────────────────────────
$DoneLabel = if ($env:SKIP_STUDIO_BASE -eq "1") { "Unsloth Studio Setup Complete" } else { "Unsloth Studio Updated" }
if ($script:StudioVtOk -and -not $env:NO_COLOR) {
- Write-Host (" {0}{1}{2}" -f (Get-StudioAnsi Dim), $Rule, (Get-StudioAnsi Reset))
+ Write-StudioLine (" {0}{1}{2}" -f (Get-StudioAnsi Dim), $Rule, (Get-StudioAnsi Reset))
if ($script:LlamaCppDegraded) {
- Write-Host (" " + (Get-StudioAnsi Warn) + "$DoneLabel (limited: llama.cpp unavailable)" + (Get-StudioAnsi Reset))
+ Write-StudioLine (" " + (Get-StudioAnsi Warn) + "$DoneLabel (limited: llama.cpp unavailable)" + (Get-StudioAnsi Reset))
} else {
- Write-Host (" " + (Get-StudioAnsi Title) + $DoneLabel + (Get-StudioAnsi Reset))
+ Write-StudioLine (" " + (Get-StudioAnsi Title) + $DoneLabel + (Get-StudioAnsi Reset))
}
- Write-Host (" {0}{1}{2}" -f (Get-StudioAnsi Dim), $Rule, (Get-StudioAnsi Reset))
+ Write-StudioLine (" {0}{1}{2}" -f (Get-StudioAnsi Dim), $Rule, (Get-StudioAnsi Reset))
} else {
- Write-Host " $Rule" -ForegroundColor DarkGray
+ Write-StudioLine " $Rule" -ForegroundColor DarkGray
if ($script:LlamaCppDegraded) {
- Write-Host " $DoneLabel (limited: llama.cpp unavailable)" -ForegroundColor Yellow
+ Write-StudioLine " $DoneLabel (limited: llama.cpp unavailable)" -ForegroundColor Yellow
} else {
- Write-Host " $DoneLabel" -ForegroundColor Green
+ Write-StudioLine " $DoneLabel" -ForegroundColor Green
}
- Write-Host " $Rule" -ForegroundColor DarkGray
+ Write-StudioLine " $Rule" -ForegroundColor DarkGray
}
step "launch" "unsloth studio -p 8888"
substep "(add -H 0.0.0.0 for LAN / cloud access; exposes the raw port only, not a public URL)"
substep "(add -H 0.0.0.0 --cloudflare for a public Cloudflare HTTPS link, or --secure to keep the raw port private; anyone with the API key can run code)"
-Write-Host ""
+Write-StudioLine ""
# Match studio/setup.sh: exit non-zero for degraded llama.cpp when called
# from install.ps1 (SKIP_STUDIO_BASE=1) so the installer can detect the
diff --git a/tests/python/test_cross_platform_parity.py b/tests/python/test_cross_platform_parity.py
index 43d384b6117..83382060a59 100644
--- a/tests/python/test_cross_platform_parity.py
+++ b/tests/python/test_cross_platform_parity.py
@@ -847,13 +847,14 @@ class TestInstallOutputRedactionParity:
def test_helper_wired_into_failure_print(self):
# install.sh dumps the captured log through the redactor on failure.
assert '_redact_install_output "$_log"' in INSTALL_SH.read_text(encoding = "utf-8")
- # Both ps1 installers redact the captured $output before Write-Host on non-zero exit.
+ # Both ps1 installers redact the captured $output before printing it on a
+ # non-zero exit. Write-StudioLine is the UTF-8 stdout sink both now use.
assert (
- "Write-Host (Redact-InstallOutput $output) -ForegroundColor Red"
+ "Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red"
in INSTALL_PS1.read_text(encoding = "utf-8")
)
assert (
- "Write-Host (Redact-InstallOutput $output) -ForegroundColor Red"
+ "Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red"
in SETUP_PS1.read_text(encoding = "utf-8")
)
# Python redacts the captured stdout before printing.
diff --git a/tests/python/test_windows_installer_concurrency_guard.py b/tests/python/test_windows_installer_concurrency_guard.py
index 42212ab969a..945c70689ae 100644
--- a/tests/python/test_windows_installer_concurrency_guard.py
+++ b/tests/python/test_windows_installer_concurrency_guard.py
@@ -188,6 +188,10 @@ def test_installer_decision_stops_active_process_and_allows_idle(tmp_path: Path,
script = f"""
$ErrorActionPreference = "Stop"
{_process_helpers(source)}
+# The block names the blocking processes through install.ps1's UTF-8 stdout sink
+# before it hands off to Exit-InstallFailure. Unstubbed that is a command-not-found
+# terminating error under "Stop", so the active case never reaches RESULT:blocked.
+function Write-StudioLine {{ param([string]$Message, [string]$ForegroundColor) Write-Host $Message }}
function Exit-InstallFailure {{
param([string]$Message)
return "blocked"
diff --git a/tests/python/test_windows_python_venv_hardening.py b/tests/python/test_windows_python_venv_hardening.py
index cba4e7335bc..4e71d89dc9f 100644
--- a/tests/python/test_windows_python_venv_hardening.py
+++ b/tests/python/test_windows_python_venv_hardening.py
@@ -160,6 +160,10 @@ def test_rollback_keeps_state_when_the_move_stops_partway(tmp_path: Path, shell:
$ErrorActionPreference = "Stop"
$StudioHome = $env:TEST_STUDIO_HOME
function substep {{ param([string]$Text, [string]$Color) }}
+# The split-move warning goes through install.ps1's UTF-8 stdout sink. Echo it so
+# the assertions below can read it; without this the call is a command-not-found
+# terminating error that the try/catch swallows, and the warning is simply lost.
+function Write-StudioLine {{ param([string]$Message, [string]$ForegroundColor) Write-Host $Message }}
function Move-Item {{
param([string]$LiteralPath, [string]$Destination, [string]$ErrorAction, [switch]$Force)
if ($env:TEST_ROLLBACK_CASE -eq "partial") {{
@@ -192,7 +196,11 @@ Write-Output ("dir=" + [string]$script:StudioVenvRollbackDir)
assert state["dir"].startswith(os.path.join(str(tmp_path), "unsloth_studio.rollback.")), out
assert Path(state["dir"]).is_dir(), out
# Both halves are named, so the user is not left hunting for the moved tree.
- assert str(existing) in out and state["dir"] in out, out
+ # Match the warning lines themselves rather than the bare paths: $existing is a
+ # prefix of the rollback dir, so "str(existing) in out" alone is satisfied by the
+ # dir= line and would stay green even with the warning missing entirely.
+ assert f"still in place: {existing}" in out, out
+ assert f"moved aside: {state['dir']}" in out, out
@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")
@@ -226,6 +234,10 @@ def test_restoring_a_split_move_never_deletes_the_half_left_behind(tmp_path: Pat
script = f"""
$ErrorActionPreference = "Stop"
function substep {{ param([string]$Text, [string]$Color) }}
+# The merge/restore helpers warn through install.ps1's UTF-8 stdout sink on their
+# conflict branches. This run does not take one, but leaving the sink undefined
+# means any future case that does would die on a command-not-found instead.
+function Write-StudioLine {{ param([string]$Message, [string]$ForegroundColor) Write-Host $Message }}
{blocks}
$script:StudioVenvRollbackActive = $true
$script:StudioVenvRollbackDir = $env:TEST_BACKUP_DIR
@@ -283,6 +295,10 @@ def test_merging_a_split_move_keeps_every_sibling_at_its_own_path(tmp_path: Path
script = f"""
$ErrorActionPreference = "Stop"
function substep {{ param([string]$Text, [string]$Color) }}
+# The merge/restore helpers warn through install.ps1's UTF-8 stdout sink on their
+# conflict branches. This run does not take one, but leaving the sink undefined
+# means any future case that does would die on a command-not-found instead.
+function Write-StudioLine {{ param([string]$Message, [string]$ForegroundColor) Write-Host $Message }}
{blocks}
$script:StudioVenvRollbackActive = $true
$script:StudioVenvRollbackDir = $env:TEST_BACKUP_DIR
@@ -347,6 +363,9 @@ def test_merging_a_split_move_never_walks_through_a_link(tmp_path: Path, shell:
script = f"""
$ErrorActionPreference = "Stop"
function substep {{ param([string]$Text, [string]$Color) }}
+# Restore-StudioVenvRollback warns through install.ps1's UTF-8 stdout sink. Echo it
+# rather than swallowing it, so a warning stays visible in the assertion message.
+function Write-StudioLine {{ param([string]$Message, [string]$ForegroundColor) Write-Host $Message }}
{blocks}
$script:StudioVenvRollbackActive = $true
$script:StudioVenvRollbackDir = $env:TEST_BACKUP_DIR
@@ -402,6 +421,6 @@ def test_readiness_gate_precedes_installs_and_names_both_interpreters():
gpu_detection = source.index("function Invoke-AmdSmiNoElevate")
assert marker < gate < gpu_detection < first_uv_pip
- assert 'Write-Host " Managed Python: $VenvPython"' in source
- assert 'Write-Host " Recorded base Python home: $recordedBaseHome"' in source
+ assert 'Write-StudioLine " Managed Python: $VenvPython"' in source
+ assert 'Write-StudioLine " Recorded base Python home: $recordedBaseHome"' in source
assert 'return (Exit-InstallFailure "Managed Python is unavailable' in source
diff --git a/tests/python/test_windows_setup_output_encoding.py b/tests/python/test_windows_setup_output_encoding.py
index 6a31575155f..9b047d31f65 100644
--- a/tests/python/test_windows_setup_output_encoding.py
+++ b/tests/python/test_windows_setup_output_encoding.py
@@ -23,16 +23,34 @@ the Information stream into stdout.
Splitting: ``step`` built one line from two Write-Host calls with -NoNewline,
which a redirected consumer splits at the record boundary.
+Sink: fixing ``step``/``substep`` left every other line on Write-Host, which
+5.1's console host writes through its own console-attached writer rather than
+the UTF-8 one bound to ``[Console]::Out``. The banner and the footer are not
+steps, so they never entered the sink #8083 built. Both entry scripts now
+funnel through ``Write-StudioLine``, and Write-Host survives only inside
+helpers that have already ruled out the redirected sink.
+
+No console: the transcode above needs a console to transcode against. Where
+``CREATE_NO_WINDOW`` really leaves the child without one, which is the state
+install.rs's own comment assumes, Write-Host has no screen buffer to query and
+throws instead, taking the whole script down under ``-ErrorActionPreference
+Stop``. The banner is then not mangled, it is absent. That is what
+``test_banner_survives_a_console_less_spawn`` measures, and it is the only case
+here that separates this fix from what shipped before it.
+
The byte-level tests assert on raw bytes; decoding first would hide the exact
regression being guarded.
"""
from __future__ import annotations
+import os
import re
import shutil
import subprocess
import sys
+import tempfile
+from functools import lru_cache
from pathlib import Path
import pytest
@@ -91,14 +109,59 @@ substep "installing OXC validator runtime..."
"""
-def _run_capturing_bytes(script: str, use_command_shape: bool) -> bytes:
+def _section(source: str, title: str) -> str:
+ """The statements under a ``# <title>`` box header, up to the blank line.
+
+ Sliced out of setup.ps1 rather than restated, so the banner and the footer
+ are exercised as written. A rewrite that drops them back onto Write-Host
+ fails here.
+ """
+ match = re.search(rf"(?m)^# {re.escape(title)}\n#[^\n]*\n", source)
+ assert match, f"no '{title}' section header in {SETUP_PS1.name}"
+ body = source[match.end() :]
+ return body[: body.index("\n\n")]
+
+
+def _banner_footer_harness() -> str:
+ """Print setup.ps1's real banner and footer with the redirected sink on."""
+ source = SETUP_PS1.read_text(encoding = "utf-8")
+ return f"""
+$ErrorActionPreference = 'Stop'
+$_UnslothUtf8NoBom = New-Object System.Text.UTF8Encoding $false
+try {{ [Console]::OutputEncoding = $_UnslothUtf8NoBom }} catch {{ }}
+$OutputEncoding = $_UnslothUtf8NoBom
+
+. '{EXTRACTOR.as_posix()}'
+foreach ($fn in @('Get-StudioAnsi', 'Write-StudioLine', 'Write-StudioStdoutMirror', 'step', 'substep')) {{
+ $src = Get-FunctionSource -Path '{SETUP_PS1.as_posix()}' -Name $fn
+ if (-not $src) {{ throw "missing $fn" }}
+ . ([scriptblock]::Create($src))
+}}
+# No console handle under CREATE_NO_WINDOW, so the real run never takes the
+# ANSI branch; pin it here instead of depending on the test host.
+$script:StudioVtOk = $false
+$script:StudioStdoutRedirected = $true
+$script:LlamaCppDegraded = $false
+$env:SKIP_STUDIO_BASE = '1'
+
+$Rule = [string]::new([char]0x2500, 52)
+{_section(source, "Banner")}
+{_section(source, "Footer")}
+"""
+
+
+def _run_capturing_bytes(
+ script: str,
+ use_command_shape: bool,
+ stem: str = "setup_output",
+) -> bytes:
"""Run through a real pipe, in both launch shapes the product uses.
``-File`` is how the desktop app spawns the installer; ``-Command ... *>&1``
is how the CLI spawns setup for ``unsloth studio update``. Piped stdout is
required to reproduce, and is captured as bytes, never decoded here.
"""
- tmp = REPO_ROOT / "tests" / "python" / "_setup_output_probe.ps1"
+ tmp = REPO_ROOT / "tests" / "python" / f"_{stem}_probe_{int(use_command_shape)}.ps1"
tmp.write_text(script, encoding = "utf-8")
try:
base = [_PWSH, "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"]
@@ -155,6 +218,33 @@ def test_step_label_and_value_stay_on_one_line(use_command_shape: bool) -> None:
assert matches[0] == " gpu none (chat-only / GGUF)"
+# The banner and the footer are the two blocks a user actually reads in the
+# desktop setup log, and neither goes through step/substep, so they need their
+# own byte-level coverage.
+
+
+@pwsh_only
[email protected]("use_command_shape", [False, True], ids = ["-File", "-Command-merged"])
+def test_banner_and_footer_are_valid_utf8(use_command_shape: bool) -> None:
+ raw = _run_capturing_bytes(_banner_footer_harness(), use_command_shape, stem = "banner_footer")
+ text = raw.decode("utf-8") # strict on purpose
+ assert REPLACEMENT not in text, "banner/footer contain U+FFFD (OEM bytes decoded as UTF-8)"
+ assert "??" not in text, "emoji was transcoded to '?' by a non-UTF-8 code page"
+
+
+@pwsh_only
[email protected]("use_command_shape", [False, True], ids = ["-File", "-Command-merged"])
+def test_banner_and_footer_print_once_each(use_command_shape: bool) -> None:
+ """One sink, so no line survives twice even when *>&1 merges the streams."""
+ raw = _run_capturing_bytes(_banner_footer_harness(), use_command_shape, stem = "banner_footer")
+ text = raw.decode("utf-8")
+ assert text.count(SLOTH) == 1, "sloth emoji lost or duplicated"
+ assert text.count(f" {SLOTH} Unsloth Studio Setup") == 1
+ assert text.count(" Unsloth Studio Setup Complete") == 1
+ # One rule under the banner, two around the footer.
+ assert text.count(" " + RULE_CHAR * 52) == 3, "the 52-char rule did not survive intact"
+
+
# Source contracts. These run everywhere, including the Linux backend CI job,
# so a regression is caught without waiting for a Windows runner.
@@ -163,6 +253,87 @@ def _strip_comments(source: str) -> str:
return re.sub(r"(?m)#.*$", "", source)
+def _mask_literals(source: str) -> str:
+ """Blank comments and string literals, keeping every offset in place.
+
+ A regex over the raw text would trip over the launcher script install.ps1
+ builds in a here-string (it has its own Write-Host and no helper to call)
+ and over the commented-out block in setup.ps1.
+ """
+ out = list(source)
+ index, size = 0, len(source)
+
+ def blank(start: int, stop: int) -> None:
+ for k in range(start, stop):
+ if out[k] != "\n":
+ out[k] = " "
+
+ while index < size:
+ char = source[index]
+ if source.startswith("<#", index):
+ stop = source.find("#>", index + 2)
+ stop = size if stop < 0 else stop + 2
+ elif char == "@" and index + 1 < size and source[index + 1] in "\"'":
+ terminator = "\n" + source[index + 1] + "@"
+ stop = source.find(terminator, index + 2)
+ stop = size if stop < 0 else stop + len(terminator)
+ elif char == "#" and (index == 0 or source[index - 1] in " \t\r\n(){};,|=&"):
+ stop = source.find("\n", index)
+ stop = size if stop < 0 else stop
+ elif char in "\"'":
+ stop = index + 1
+ while stop < size:
+ if char == '"' and source[stop] == "`":
+ stop += 2
+ continue
+ if source[stop] == char:
+ if stop + 1 < size and source[stop + 1] == char:
+ stop += 2
+ continue
+ stop += 1
+ break
+ stop += 1
+ else:
+ index += 1
+ continue
+ blank(index, stop)
+ index = stop
+ return "".join(out)
+
+
+def _close_brace(masked: str, open_offset: int) -> int:
+ """Offset of the `}` closing the `{` at `open_offset`, over masked source."""
+ depth = 0
+ for offset in range(open_offset, len(masked)):
+ if masked[offset] == "{":
+ depth += 1
+ elif masked[offset] == "}":
+ depth -= 1
+ if depth == 0:
+ return offset
+ raise AssertionError("unbalanced braces")
+
+
+def _function_span(masked: str, name: str) -> tuple[int, int]:
+ """Offsets of `function <name> { ... }`, brace-matched over masked source."""
+ match = _function_match(masked, name)
+ assert match, f"no function {name}"
+ return match.start(), _close_brace(masked, masked.index("{", match.end())) + 1
+
+
+def _function_match(masked: str, name: str) -> re.Match[str] | None:
+ return re.search(r"(?im)^[ \t]*function\s+" + re.escape(name) + r"\b", masked)
+
+
+# Write-Host may only appear inside a helper that has already ruled out the
+# redirected sink: Write-StudioLine itself, and setup.ps1's step/substep, which
+# return through the console mirror before reaching their interactive branch.
+WRITE_HOST_ALLOW_LIST = {
+ SETUP_PS1: ("Write-StudioLine", "step", "substep"),
+ INSTALL_PS1: ("Write-StudioLine",),
+}
+
+
@pytest.mark.parametrize("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])
def test_entry_scripts_set_the_utf8_invariant(path: Path) -> None:
source = path.read_text(encoding = "utf-8")
@@ -191,8 +362,62 @@ def test_step_helper_emits_one_record(path: Path) -> None:
assert "-NoNewline" not in body
-def test_setup_resolves_the_redirect_sink_once() -> None:
- source = SETUP_PS1.read_text(encoding = "utf-8")
[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])
+def test_write_host_only_survives_inside_gated_helpers(path: Path) -> None:
+ source = path.read_text(encoding = "utf-8")
+ masked = _mask_literals(source)
+ spans = [_function_span(masked, name) for name in WRITE_HOST_ALLOW_LIST[path]]
+ lines = source.splitlines()
+ stray = [
+ f" {path.name}:{source.count(chr(10), 0, m.start()) + 1}: "
+ f"{lines[source.count(chr(10), 0, m.start())].strip()}"
+ for m in re.finditer(r"\bWrite-Host\b", masked)
+ if not any(lo <= m.start() < hi for lo, hi in spans)
+ ]
+ assert not stray, (
+ "Write-Host is written by 5.1's console host, not by the UTF-8 writer bound to "
+ "[Console]::Out, so under CREATE_NO_WINDOW the desktop app renders these lines as "
+ "U+FFFD. Call Write-StudioLine instead (same arguments, same colors when "
+ "interactive):\n" + "\n".join(stray)
+ )
+
+
[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])
+def test_every_allow_listed_helper_rules_out_the_redirected_sink(path: Path) -> None:
+ """The allow-list is only safe while each entry still checks the sink."""
+ masked = _mask_literals(path.read_text(encoding = "utf-8"))
+ for name in WRITE_HOST_ALLOW_LIST[path]:
+ lo, hi = _function_span(masked, name)
+ assert "$script:StudioStdoutRedirected" in masked[lo:hi], (
+ f"{name} in {path.name} reaches Write-Host without testing "
+ "$script:StudioStdoutRedirected; drop it from the allow-list or gate it"
+ )
+
+
[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])
+def test_the_sink_helper_is_defined_before_the_first_line_it_prints(path: Path) -> None:
+ """PowerShell resolves functions at call time, but not before their line runs."""
+ masked = _mask_literals(path.read_text(encoding = "utf-8"))
+ definition = masked.index("function Write-StudioLine")
+ first_call = min(m.start() for m in re.finditer(r"\bWrite-StudioLine\b", masked))
+ assert first_call == definition + len(
+ "function "
+ ), f"{path.name} calls Write-StudioLine before defining it"
+
+
[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])
+def test_the_sink_helper_writes_through_the_console_handle(path: Path) -> None:
+ masked = _mask_literals(path.read_text(encoding = "utf-8"))
+ lo, hi = _function_span(masked, "Write-StudioLine")
+ body = path.read_text(encoding = "utf-8")[lo:hi]
+ assert "[Console]::Out.WriteLine($Message)" in body
+ # Tauri reads line by line, so a buffered line is a line the user never sees.
+ assert "[Console]::Out.Flush()" in body
+
+
[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])
+def test_entry_scripts_resolve_the_redirect_sink_once(path: Path) -> None:
+ source = path.read_text(encoding = "utf-8")
assert "$script:StudioStdoutRedirected = [Console]::IsOutputRedirected" in source
@@ -242,3 +467,255 @@ def test_rust_windows_spawns_force_utf8(rust_file: str) -> None:
assert (
'cmd.env("PYTHONIOENCODING", "utf-8");' in source
), f"{rust_file} does not force PYTHONIOENCODING"
+
+
+# The console-less spawn. Windows only, and last in the file because it reuses
+# the literal masking above to brace-match the blocks it lifts.
+#
+# A GitHub runner hands a CREATE_NO_WINDOW child a console anyway
+# (GetConsoleOutputCP 437, GetConsoleWindow 0), so the UTF-8 setter in the
+# preamble succeeds there and every version of these scripts emits a clean
+# banner. The cases above therefore cannot tell this fix from what preceded it.
+# Calling FreeConsole() in the child first puts it in the state install.rs's own
+# comment assumes CREATE_NO_WINDOW produces, and there the two diverge hard:
+# without the sink, Write-Host throws `HostException: GetConsoleScreenBufferInfo,
+# The Win32 internal error "The handle is invalid" 0x6`, the script dies with
+# exit 1 and 2 bytes of stdout, and the user's setup log holds a PowerShell
+# stack trace where the banner should be.
+#
+# Everything the probe prints is sliced out of the script under test; only the
+# FreeConsole prologue and the stderr diagnostics are harness. Restating the
+# banner here would only assert that this file can print a sloth.
+
+CREATE_NO_WINDOW = 0x08000000
+
+# studio/src-tauri/src/install.rs::powershell_launch_args, minus the -File the
+# runner appends. Not Bypass: RemoteSigned is what the shipped spawn uses.
+TAURI_FLAGS = ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "RemoteSigned"]
+
+# install.rs::powershell_exe. Resolved absolutely for the same reason it is
+# there, and not fallen back to a bare `powershell.exe`: pwsh 7 is UTF-8 by
+# default and would pass this without exercising anything.
+_WINDOWS_POWERSHELL = (
+ Path(os.environ.get("SystemRoot", r"C:\Windows"))
+ / r"System32\WindowsPowerShell\v1.0\powershell.exe"
+ if sys.platform == "win32"
+ else None
+)
+
+windows_only = pytest.mark.skipif(
+ sys.platform != "win32", reason = "the console-less spawn is a Win32 state"
+)
+powershell_51_only = pytest.mark.skipif(
+ _WINDOWS_POWERSHELL is None or not _WINDOWS_POWERSHELL.is_file(),
+ reason = "Windows PowerShell 5.1 is unavailable",
+)
+
+# Documented kernel32 calls and nothing else, so the probe reaches the target
+# state without the scripts under test knowing they are being tested.
+_FREE_CONSOLE = """Add-Type -Namespace Force -Name Native -MemberDefinition @'
+[DllImport("kernel32.dll")] public static extern bool FreeConsole();
+'@
+$null = [Force.Native]::FreeConsole()"""
+
+# The first line of the preamble, and the anchor the slice starts from.
+_UTF8_ENCODER = "$_UnslothUtf8NoBom = New-Object System.Text.UTF8Encoding $false"
+
+
+def _dedent(block: str) -> str:
+ """Strip the common indent; install.ps1 defines all of this inside a block."""
+ indents = [len(line) - len(line.lstrip()) for line in block.split("\n") if line.strip()]
+ cut = min(indents) if indents else 0
+ return "\n".join(line[cut:] if line.strip() else "" for line in block.split("\n"))
+
+
+def _slice_preamble(source: str) -> str:
+ """The UTF-8 output invariant, from the encoder to the PYTHONIOENCODING line."""
+ head = source.rindex("\n", 0, source.index(_UTF8_ENCODER)) + 1
+ tail = source.index("\n", source.index("$env:PYTHONIOENCODING = 'utf-8'")) + 1
+ return _dedent(source[head:tail])
+
+
+def _slice_optional(source: str, pattern: str) -> str | None:
+ """None is an answer: main's install.ps1 has neither probe nor sink helper."""
+ match = re.search(pattern, source)
+ return _dedent(match.group(0)) if match else None
+
+
+def _slice_if_chain(source: str, masked: str, start: int) -> str:
+ """A whole `if {} else {}`; brace-matching alone drops the non-ANSI branch.
+
+ The redirected run is exactly the one that takes that branch.
+ """
+ end = _close_brace(masked, masked.index("{", start))
+ chained = r"[ \t\r\n]*(?:elseif[ \t]*\(.*?\)|else)[ \t\r\n]*\{"
+ while True:
+ tail = re.match(chained, masked[end + 1 :], re.S)
+ if not tail:
+ return source[start : end + 1]
+ end = _close_brace(masked, end + tail.end())
+
+
+def _slice_banner(source: str, masked: str) -> str:
+ """The blank line, the VT/plain branch and the trailing blank, verbatim."""
+ match = re.search(
+ r'(?m)^[ \t]*(?:Write-Host|Write-StudioLine) ""\n'
+ r"[ \t]*if \(\$script:StudioVtOk -and -not \$env:NO_COLOR\) \{",
+ source,
+ )
+ assert match, "no banner block"
+ block = _slice_if_chain(source, masked, match.end() - 1)
+ end = match.end() - 1 + len(block)
+ trailing = re.match(r'\n[ \t]*(?:Write-Host|Write-StudioLine) ""(?=\n)', source[end:])
+ return _dedent(source[match.start() : end + (trailing.end() if trailing else 0)])
+
+
+def _console_less_probe(path: Path) -> str:
+ """Assemble a probe out of the script's own preamble, helpers and banner."""
+ source = path.read_text(encoding = "utf-8")
+ masked = _mask_literals(source)
+ # Sliced too: it is what turns the Write-Host throw into a dead script
+ # rather than a skipped line, so restating it would be assuming the result.
+ eap = _slice_optional(source, r'(?m)^[ \t]*\$ErrorActionPreference = "Stop"')
+ assert eap, f"{path.name} no longer stops on error before the banner"
+ parts = [eap, _FREE_CONSOLE, "", _slice_preamble(source), ""]
+ redirect_probe = _slice_optional(
+ source,
+ r"(?m)^[ \t]*\$script:StudioStdoutRedirected = \$false\n"
+ r"[ \t]*try \{ \$script:StudioStdoutRedirected = \[Console\]::IsOutputRedirected \} catch \{ \}",
+ )
+ parts += [redirect_probe or "$script:StudioStdoutRedirected = $false", ""]
+ for name in ("Write-StudioLine", "Enable-StudioVirtualTerminal", "Get-StudioAnsi"):
+ if _function_match(masked, name):
+ lo, hi = _function_span(masked, name)
+ parts += [_dedent(source[lo:hi]), ""]
+ parts += ["$script:StudioVtOk = Enable-StudioVirtualTerminal", ""]
+ for pattern in (
+ r"(?m)^[ \t]*\$Rule = \[string\]::new\(\[char\]0x2500, 52\)",
+ r"(?m)^[ \t]*\$Sloth = \[char\]::ConvertFromUtf32\(0x1F9A5\)",
+ ):
+ # setup.ps1 inlines the sloth in the banner; install.ps1 binds it first.
+ assignment = _slice_optional(source, pattern)
+ if assignment:
+ parts.append(assignment)
+ parts += ["", _slice_banner(source, masked), ""]
+ # On stderr, which the app reads on a separate reader, so stdout stays
+ # exactly the byte stream the log panel is built from.
+ parts += [
+ '[Console]::Error.WriteLine("psversion=" + $PSVersionTable.PSVersion.ToString())',
+ '[Console]::Error.WriteLine("console_outputencoding_codepage=" + [Console]::OutputEncoding.CodePage)',
+ '[Console]::Error.WriteLine("output_redirected=" + [Console]::IsOutputRedirected)',
+ '[Console]::Error.WriteLine("studio_stdout_redirected=" + $script:StudioStdoutRedirected)',
+ '[Console]::Error.WriteLine("studio_vt_ok=" + $script:StudioVtOk)',
+ ]
+ assembled = "\n".join(parts) + "\n"
+ # 5.1 parses a BOM-less file as ANSI, which is why both scripts are ASCII-only.
+ assembled.encode("ascii")
+ return assembled
+
+
+@lru_cache(maxsize = None)
+def _run_console_less(path: Path) -> tuple[int, bytes, str]:
+ """Spawn the probe the way install.rs spawns the installer, and read bytes."""
+ with tempfile.TemporaryDirectory() as workdir:
+ # A file written here has no Zone.Identifier, so RemoteSigned admits it.
+ probe = Path(workdir) / f"{path.stem}_console_less_probe.ps1"
+ probe.write_bytes(_console_less_probe(path).replace("\n", "\r\n").encode("ascii"))
+ proc = subprocess.run(
+ [str(_WINDOWS_POWERSHELL), *TAURI_FLAGS, "-File", str(probe)],
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ creationflags = CREATE_NO_WINDOW,
+ timeout = 180,
+ )
+ return proc.returncode, proc.stdout, proc.stderr.decode("utf-8", errors = "replace")
+
+
+def _decode_like_install_rs(raw: bytes) -> str:
+ """install.rs: read_until(b'\\n') -> trim_line_endings -> from_utf8_lossy.
+
+ One record per `install-progress` event, so this is what the log panel
+ renders. Python's 'replace' emits one U+FFFD per maximal subpart, the rule
+ Rust's from_utf8_lossy uses.
+ """
+ records = raw.split(b"\n")
+ if records and records[-1] == b"":
+ records.pop() # read_until returning Ok(0) at EOF, not an empty line
+ return "\n".join(r.rstrip(b"\r\n").decode("utf-8", errors = "replace") for r in records)
+
+
+def _explain(path: Path, code: int, raw: bytes, err: str) -> str:
+ tail = "\n".join(line for line in err.splitlines() if line.strip())[-1200:]
+ return (
+ f"\n{path.name} under a console-less CREATE_NO_WINDOW spawn: exit {code}, "
+ f"{len(raw)} stdout bytes.\nstderr:\n{tail}\n"
+ )
+
+
+# A floor, not the 191 and 207 bytes these banners currently produce. The point
+# is only to outrun a dead script: without the sink the run aborts having
+# written 2 bytes, and every "nothing is wrong with this stream" assertion below
+# holds trivially over 2 bytes. Two of the three cases here are phrased that way
+# because that is the regression they guard, so they need this floor underneath
+# them or they pass on the very code they exist to reject. Pinning the exact
+# count instead would make editing the banner wording a test failure.
+_MIN_BANNER_BYTES = 64
+
+
+def _banner_or_explain(path: Path) -> tuple[str, str]:
+ """Run the probe, insist the banner actually arrived, and decode it.
+
+ Every console-less case starts here. `raw` being truthy is not enough: the
+ aborted run is truthy too.
+ """
+ code, raw, err = _run_console_less(path)
+ detail = _explain(path, code, raw, err)
+ assert code == 0, (
+ "the banner block aborted the script instead of printing. Write-Host needs a "
+ "console screen buffer, and CREATE_NO_WINDOW is documented not to give the "
+ "child one, so it throws and -ErrorActionPreference Stop takes the run down. "
+ "The desktop setup log gets a PowerShell stack trace and no banner at all. "
+ "Route the line through Write-StudioLine." + detail
+ )
+ assert len(raw) >= _MIN_BANNER_BYTES, (
+ f"only {len(raw)} stdout bytes, under the {_MIN_BANNER_BYTES}-byte floor: the "
+ "banner was LOST, not mangled. Exiting 0 having printed nothing is the same "
+ "empty setup log to the user as throwing." + detail
+ )
+ return _decode_like_install_rs(raw), detail
+
+
+@windows_only
+@powershell_51_only
[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])
+def test_banner_survives_a_console_less_spawn(path: Path) -> None:
+ """Without the sink this exits 1 with 2 bytes: the banner never arrives."""
+ _banner_or_explain(path)
+
+
+@windows_only
+@powershell_51_only
[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])
+def test_console_less_banner_is_valid_utf8(path: Path) -> None:
+ """Lossy first: it names how bad the stream is before the strict decode."""
+ lossy, detail = _banner_or_explain(path)
+ assert REPLACEMENT not in lossy, (
+ "the desktop app decodes this pipe as UTF-8 and got bytes that are not, so the "
+ "log shows U+FFFD. With no console the UTF-8 setter throws, and only the "
+ "writers bound in its catch branch keep the stream UTF-8." + detail
+ )
+ # Strict on purpose; UnicodeDecodeError is the failure. Reruns the cached
+ # bytes rather than trusting the lossy pass above to have caught everything.
+ _run_console_less(path)[1].decode("utf-8")
+
+
+@windows_only
+@powershell_51_only
[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])
+def test_console_less_banner_keeps_its_glyphs(path: Path) -> None:
+ text, detail = _banner_or_explain(path)
+ assert SLOTH in text, "the sloth did not reach stdout" + detail
+ assert "??" not in text, "the sloth was transcoded to '?' by a non-UTF-8 code page" + detail
+ assert text.count(RULE_CHAR * 52) == 1, (
+ f"expected one 52-char U+2500 rule, found {text.count(RULE_CHAR * 52)}" + detail
+ )
diff --git a/tests/studio/test_install_rollback_lifecycle.ps1 b/tests/studio/test_install_rollback_lifecycle.ps1
index d70f384ca7a..49498c2fe16 100644
--- a/tests/studio/test_install_rollback_lifecycle.ps1
+++ b/tests/studio/test_install_rollback_lifecycle.ps1
@@ -29,6 +29,10 @@ foreach ($name in $helperNames) {
}
function substep { param([string]$Message, [string]$Color) }
+# The rollback helpers report through install.ps1's UTF-8 stdout sink on their warn
+# and error branches. None of the cases below take one today, but this file runs
+# under "Stop", so an undefined sink would abort the suite rather than fail a check.
+function Write-StudioLine { param([string]$Message, [string]$ForegroundColor) Write-Host $Message }
$failures = 0
function Check($name, $condition) {
diff --git a/tests/studio/test_path_probe_access_denied.ps1 b/tests/studio/test_path_probe_access_denied.ps1
index 060640028d9..1550a496f71 100644
--- a/tests/studio/test_path_probe_access_denied.ps1
+++ b/tests/studio/test_path_probe_access_denied.ps1
@@ -256,6 +256,7 @@ if ($exitDeniedSrc -and $writeDeniedSrc) {
`$ErrorActionPreference = "Stop"
function step { param([string]`$Label, [string]`$Value, [string]`$Color = "Green") Write-Host " `$Label `$Value" }
function substep { param([string]`$Message, [string]`$Color = "DarkGray") Write-Host " `$Message" }
+function Write-StudioLine { param([string]`$Message, [string]`$ForegroundColor) Write-Host `$Message }
function Get-PathDenialDetail { param([string]`$Path) return "" }
$exitSetupSrc
$writeDeniedSrc
@@ -358,6 +359,10 @@ if ($assertSrc -and $markSrc) {
function Exit-SetupFailure { param($Message, $Code) throw "EXIT-SETUP" }
function step { param($a, $b, $c) }
function substep { param($a, $b) }
+ # The unowned-tree branch reports through setup.ps1's UTF-8 stdout sink before it
+ # exits. Unstubbed it is a command-not-found terminating error, which the catch
+ # below would score as the intended failure while never reaching Exit-SetupFailure.
+ function Write-StudioLine { param([string]$Message, [string]$ForegroundColor) Write-Host $Message }
$StudioOwnedMarker = ".unsloth-studio-owned"
$StudioHomeIsCustom = $true
@@ -431,9 +436,13 @@ if ($assertSrc -and $markSrc) {
}
}
# -NonFatal rescues the denial only: someone else's folder must still stop.
+ # Pin the stop to Exit-SetupFailure rather than to "something threw": any
+ # missing helper in the guard would also throw, and would pass a bare check.
$threw = $false
- try { $null = Assert-StudioOwnedOrAbsent -Path $nfUnowned -Label "whisper.cpp install" -NonFatal } catch { $threw = $true }
- Check "-NonFatal does not excuse an unowned tree" $threw
+ $thrownBy = $null
+ try { $null = Assert-StudioOwnedOrAbsent -Path $nfUnowned -Label "whisper.cpp install" -NonFatal }
+ catch { $threw = $true; $thrownBy = $_.Exception.Message }
+ Check "-NonFatal does not excuse an unowned tree" ($threw -and $thrownBy -eq "EXIT-SETUP")
} finally {
Set-NfDenied $false
Remove-Item -Recurse -Force -LiteralPath $nfRoot -ErrorAction SilentlyContinue
@@ -459,6 +468,7 @@ if ($preflightSrc.Count -eq $preflightFns.Count) {
`$ErrorActionPreference = "Stop"
function step { param([string]`$Label, [string]`$Value, [string]`$Color = "Green") Write-Host " `$Label `$Value" }
function substep { param([string]`$Message, [string]`$Color = "DarkGray") Write-Host " `$Message" }
+function Write-StudioLine { param([string]`$Message, [string]`$ForegroundColor) Write-Host `$Message }
$($preflightSrc -join "`n")
`$env:USERPROFILE = `$args[0]
`$onWindows = (`$args[1] -eq "win")
diff --git a/tests/studio/test_resolve_cuda_toolkit.ps1 b/tests/studio/test_resolve_cuda_toolkit.ps1
index c1114f7b388..67d9b7f33b4 100644
--- a/tests/studio/test_resolve_cuda_toolkit.ps1
+++ b/tests/studio/test_resolve_cuda_toolkit.ps1
@@ -72,6 +72,7 @@ function Run-Case {
`$NvccCompatibleFake = '$nvccCompatibleFake'
function substep { param(`$m, `$c) Write-Host " `$m" }
function step { param(`$l, `$v, `$c) Write-Host "[`$l] `$v" }
+function Write-StudioLine { param([string]`$Message, [string]`$ForegroundColor) Write-Host `$Message }
function Add-ToUserPath { param(`$Directory, `$Position) `$true }
function Refresh-Environment { }
function Get-CudaComputeCapability { '120' }
diff --git a/tests/studio_setup_ps1/Studio.Setup.Output.Tests.ps1 b/tests/studio_setup_ps1/Studio.Setup.Output.Tests.ps1
index b47920ebfaf..24f84de26d5 100644
--- a/tests/studio_setup_ps1/Studio.Setup.Output.Tests.ps1
+++ b/tests/studio_setup_ps1/Studio.Setup.Output.Tests.ps1
@@ -1,7 +1,7 @@
<#
- Pester v5 unit tests for step / substep / Write-StudioStdoutMirror in
- studio/setup.ps1, guarding the desktop setup log printing every step twice
- with the first copy split across two lines:
+ Pester v5 unit tests for Write-StudioLine / step / substep /
+ Write-StudioStdoutMirror in studio/setup.ps1, guarding the desktop setup log
+ printing every step twice with the first copy split across two lines:
gpu
none (chat-only / GGUF)
@@ -13,7 +13,10 @@
-NoNewline, which a redirected consumer splits at the record boundary.
Invariant now: exactly ONE sink. Redirected -> console handle. Interactive
- -> Write-Host.
+ -> Write-Host. Every other line in both entry scripts goes through
+ Write-StudioLine for the same reason: Write-Host is written by 5.1's console
+ host on the OEM code page, not by the UTF-8 writer bound to [Console]::Out,
+ so the banner and the footer used to arrive as U+FFFD.
Pure string formatting, so it runs on any pwsh host. Functions are extracted
and dot-sourced because setup.ps1 is a top-level installer; a missing one
@@ -33,7 +36,7 @@ BeforeAll {
$script:InstallPs1 = Join-Path $PSScriptRoot '..\..\install.ps1'
- foreach ($fn in @('Get-StudioAnsi', 'Write-StudioStdoutMirror', 'step', 'substep')) {
+ foreach ($fn in @('Get-StudioAnsi', 'Write-StudioLine', 'Write-StudioStdoutMirror', 'step', 'substep')) {
$src = Get-FunctionSource -Path $script:SetupPs1 -Name $fn
if (-not $src) { throw "Function '$fn' not found in $script:SetupPs1 - cannot test the real code." }
. ([scriptblock]::Create($src))
@@ -60,6 +63,9 @@ BeforeAll {
[pscustomobject]@{
Console = $writer.ToString()
HostRecordCount = @($hostRecords).Count
+ # Rendered to strings: 6>&1 yields InformationRecord objects, and the
+ # tests care about the text the user would have read.
+ HostRecords = @(@($hostRecords) | ForEach-Object { "$_" })
}
}
@@ -85,6 +91,73 @@ BeforeAll {
}
}
+Describe 'Write-StudioLine is the single sink for every non-step line' {
+ BeforeEach {
+ $script:StudioVtOk = $false
+ $env:NO_COLOR = $null
+ }
+
+ It 'writes to the console handle, and nothing to Write-Host, when redirected' {
+ $r = Invoke-CapturingConsoleOut -Redirected $true -Body {
+ Write-StudioLine "plain"
+ Write-StudioLine "colored" -ForegroundColor Red
+ }
+ (Get-EmittedLines $r.Console) | Should -Be @('plain', 'colored')
+ $r.HostRecordCount | Should -Be 0
+ }
+
+ It 'keeps the banner emoji and the U+2500 rule intact when redirected' {
+ $rule = [string]::new([char]0x2500, 52)
+ $sloth = [char]::ConvertFromUtf32(0x1F9A5)
+ $r = Invoke-CapturingConsoleOut -Redirected $true -Body {
+ Write-StudioLine (" " + $sloth + " Unsloth Studio Setup") -ForegroundColor Green
+ Write-StudioLine " $rule" -ForegroundColor DarkGray
+ }
+ $lines = Get-EmittedLines $r.Console
+ $lines.Count | Should -Be 2
+ $lines[0] | Should -Be " $sloth Unsloth Studio Setup"
+ $lines[1] | Should -Be " $rule"
+ }
+
+ It 'emits a blank line as a blank line, not as nothing' {
+ $r = Invoke-CapturingConsoleOut -Redirected $true -Body { Write-StudioLine "" }
+ $r.Console | Should -Not -BeNullOrEmpty
+ $r.Console.Trim() | Should -BeNullOrEmpty
+ }
+
+ It 'never leaks an ANSI escape onto the redirected sink' {
+ # Enable-StudioVirtualTerminal returns false without a console handle, so
+ # the colored branch must be unreachable there.
+ $r = Invoke-CapturingConsoleOut -Redirected $true -Body {
+ Write-StudioLine "warning" -ForegroundColor Yellow
+ }
+ $r.Console | Should -Not -Match ([regex]::Escape([char]27))
+ }
+
+ It 'stays on Write-Host, message intact, when attached to a console' {
+ $r = Invoke-CapturingConsoleOut -Redirected $false -Body {
+ Write-StudioLine "plain"
+ Write-StudioLine "colored" -ForegroundColor Red
+ }
+ $r.Console | Should -BeNullOrEmpty
+ $r.HostRecordCount | Should -Be 2
+ $r.HostRecords | Should -Be @('plain', 'colored')
+ }
+
+ It 'still prints an interactive blank line' {
+ $r = Invoke-CapturingConsoleOut -Redirected $false -Body { Write-StudioLine "" }
+ $r.HostRecordCount | Should -Be 1
+ }
+
+ It 'passes -ForegroundColor through only when the caller supplied one' {
+ # An omitted color must not become an empty string: Write-Host cannot
+ # bind that to ConsoleColor and the install would abort under "Stop".
+ { Invoke-CapturingConsoleOut -Redirected $false -Body {
+ Write-StudioLine "no color here"
+ } } | Should -Not -Throw
+ }
+}
+
Describe 'step / substep emit exactly one copy when stdout is redirected' {
BeforeEach {
$script:StudioVtOk = $false
@@ -219,12 +292,33 @@ Describe 'Source contracts that keep the fix from regressing' {
(Get-CodeWithoutComments $src) | Should -Not -Match '-NoNewline'
}
- It 'does not use -NoNewline in install.ps1 step either (it has no mirror)' {
+ It 'does not use -NoNewline in install.ps1 step either' {
$src = Get-FunctionSource -Path $script:InstallPs1 -Name 'step'
$src | Should -Not -BeNullOrEmpty
(Get-CodeWithoutComments $src) | Should -Not -Match '-NoNewline'
}
+ It 'defines Write-StudioLine in install.ps1 too, with the same body' {
+ # install.ps1 cannot dot-source setup.ps1, so it holds a copy. A copy
+ # that drifts is a copy that stops routing the installer's own banner.
+ $setup = ((Get-FunctionSource -Path $script:SetupPs1 -Name 'Write-StudioLine') -replace '\s+', ' ').Trim()
+ $install = ((Get-FunctionSource -Path $script:InstallPs1 -Name 'Write-StudioLine') -replace '\s+', ' ').Trim()
+ $setup | Should -Not -BeNullOrEmpty
+ $install | Should -Be $setup
+ }
+
+ It 'defines Write-StudioLine before the first line either script prints' {
+ # PowerShell resolves functions at call time, but a top-level call above
+ # the definition still fails. Comments are stripped first: both scripts
+ # name the helper in the prose above it.
+ foreach ($path in @($script:SetupPs1, $script:InstallPs1)) {
+ $source = Get-CodeWithoutComments (Get-Content -Raw -LiteralPath $path)
+ $definition = $source.IndexOf('function Write-StudioLine')
+ $definition | Should -BeGreaterThan -1
+ $source.IndexOf('Write-StudioLine') | Should -Be ($definition + 'function '.Length)
+ }
+ }
+
It 'sets the UTF-8 console encoding in both entry scripts' {
foreach ($path in @($script:SetupPs1, $script:InstallPs1)) {
$source = Get-Content -Raw -LiteralPath $path
diff --git a/tests/studio_setup_ps1/Studio.Setup.Vs2026.Tests.ps1 b/tests/studio_setup_ps1/Studio.Setup.Vs2026.Tests.ps1
index 409c0689f56..f4f682fa3bb 100644
--- a/tests/studio_setup_ps1/Studio.Setup.Vs2026.Tests.ps1
+++ b/tests/studio_setup_ps1/Studio.Setup.Vs2026.Tests.ps1
@@ -27,6 +27,12 @@ BeforeAll {
if (-not $script:SetupPs1) { throw "Could not locate studio/setup.ps1 (set SETUP_PS1_PATH)." }
Write-Host "setup.ps1 under test: $script:SetupPs1"
+ # Ensure-BuildToolsForLlamaSourceBuild reports through setup.ps1's UTF-8 stdout
+ # sink, which the real script defines above every call site. On a host without
+ # cmake the "CMake not found" line is the first thing it reaches, so unstubbed it
+ # is a command-not-found terminating error and the no-op case fails on the throw.
+ function Write-StudioLine { param([string]$Message, [string]$ForegroundColor) Write-Host $Message }
+
foreach ($fn in @('Resolve-VsGeneratorFromLabel', 'Find-VsBuildTools', 'Get-VcBuildCustomizationsDir',
'Test-CmakeSupportsGenerator', 'Get-CmakeVersion', 'Test-CmakeListsGenerator',
'Test-CmakeCanDriveGenerator', 'Get-FallbackVsGenerator',
diff --git a/tests/test_installer_system32_guard.py b/tests/test_installer_system32_guard.py
index 5d1f8a21a2b..6abd35ddfe6 100644
--- a/tests/test_installer_system32_guard.py
+++ b/tests/test_installer_system32_guard.py
@@ -162,6 +162,8 @@ _PS_STUBS = (
'function step { param($Label, $Value, $Color) Write-Host "STEP:$Label|$Value" }\n'
'function substep { param($Message, $Color) Write-Host "SUBSTEP:$Message" }\n'
'function Exit-InstallFailure { param($Message, $Code = 1) Write-Host "FAILED:$Message"; exit 42 }\n'
+ # install.ps1 prints through its UTF-8 stdout sink; the harness only needs the text.
+ "function Write-StudioLine { param([string]$Message, [string]$ForegroundColor) Write-Host $Message }\n"
"$InSystemDir = $true\n"
)