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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: fix the Windows desktop setup log mojibake and double-printed steps (#8083)
Daniel Hand8effae0d551
diff --git a/install.ps1 b/install.ps1index 5fa10c2f9cc..2c1a1c00784 100644--- a/install.ps1+++ b/install.ps1@@ -48,6 +48,27 @@ function Install-UnslothStudio {}}+ # Same UTF-8 invariant as studio/setup.ps1, same ordering constraint: this+ # rebuilds [Console]::Out, so it precedes the first write.+ $_UnslothUtf8NoBom = New-Object System.Text.UTF8Encoding $false+ try {+ [Console]::OutputEncoding = $_UnslothUtf8NoBom+ } catch {+ # No console: the setter drops the cached writer before throwing, so+ # bind UTF-8 ones explicitly. Same fallback as studio/setup.ps1.+ try {+ $_UnslothStdout = New-Object System.IO.StreamWriter -ArgumentList ([Console]::OpenStandardOutput()), $_UnslothUtf8NoBom+ $_UnslothStdout.AutoFlush = $true+ [Console]::SetOut($_UnslothStdout)+ $_UnslothStderr = New-Object System.IO.StreamWriter -ArgumentList ([Console]::OpenStandardError()), $_UnslothUtf8NoBom+ $_UnslothStderr.AutoFlush = $true+ [Console]::SetError($_UnslothStderr)+ } catch { }+ }+ $OutputEncoding = $_UnslothUtf8NoBom+ $env:PYTHONUTF8 = '1'+ $env:PYTHONIOENCODING = 'utf-8'+# ── Tauri structured output ──function Write-TauriLog {param([string]$Tag, [string]$Message)@@ -501,7 +522,6 @@ function Install-UnslothStudio {Write-Host (" {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) }- Write-Host (" {0}" -f $padded) -NoNewline -ForegroundColor DarkGray$fc = switch ($Color) {'Green' { 'DarkGreen' }'Yellow' { 'Yellow' }@@ -509,7 +529,10 @@ function Install-UnslothStudio {'DarkGray' { 'DarkGray' }default { 'DarkGreen' }}- Write-Host $Value -ForegroundColor $fc+ # 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}}diff --git a/studio/setup.ps1 b/studio/setup.ps1index 1ef26a3311e..74f75a8cbf5 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -61,6 +61,38 @@ if ($PSVersionTable.PSEdition -ne 'Core' -and $env:SystemRoot) {}}+# UTF-8 output invariant. 5.1 encodes redirected output with the OEM code page,+# but the desktop app decodes the pipe as UTF-8 (from_utf8_lossy, install.rs):+# U+1F9A5 prints as '??', U+2500 becomes a bare 0xC4 and arrives as U+FFFD.+# Must precede the first write, since this rebuilds [Console]::Out. ASCII-only,+# because 5.1 parses these BOM-less files as ANSI.+$_UnslothUtf8NoBom = New-Object System.Text.UTF8Encoding $false+try {+ [Console]::OutputEncoding = $_UnslothUtf8NoBom+} catch {+ # No console (CREATE_NO_WINDOW). The setter P/Invokes SetConsoleOutputCP and+ # drops the cached writer BEFORE throwing, assigning OutputEncoding only+ # after, so [Console]::Out would rebuild on the OLD code page. Bind UTF-8+ # writers instead: redirected step/substep use Out as their only sink, and+ # Tauri decodes stderr the same way to build its failure text.+ try {+ $_UnslothStdout = New-Object System.IO.StreamWriter -ArgumentList ([Console]::OpenStandardOutput()), $_UnslothUtf8NoBom+ $_UnslothStdout.AutoFlush = $true+ [Console]::SetOut($_UnslothStdout)+ $_UnslothStderr = New-Object System.IO.StreamWriter -ArgumentList ([Console]::OpenStandardError()), $_UnslothUtf8NoBom+ $_UnslothStderr.AutoFlush = $true+ [Console]::SetError($_UnslothStderr)+ } catch { }+}+$OutputEncoding = $_UnslothUtf8NoBom+$env:PYTHONUTF8 = '1'+$env:PYTHONIOENCODING = 'utf-8'++# Resolved once: it picks the output sink in step/substep and must not change+# mid-run. See Write-StudioStdoutMirror.+$script:StudioStdoutRedirected = $false+try { $script:StudioStdoutRedirected = [Console]::IsOutputRedirected } catch { }+# --------------------------------------------------------------------------# Maintainer-editable defaults# Change these in the GitHub-hosted script so users get updated defaults.@@ -148,6 +180,10 @@ function Refresh-Environment {# (which loads Microsoft.PowerShell.Security), so the module path# would be broken again exactly where it has to be right.if ($key -eq 'Path' -or $key -eq 'PSModulePath') { continue }+ # Same exception, for the UTF-8 invariant at the top. This runs+ # repeatedly, so a registry PYTHONUTF8=0 would otherwise reload over+ # ours and every later Python child would go back to mojibake.+ if ($key -eq 'PYTHONUTF8' -or $key -eq 'PYTHONIOENCODING') { continue }Set-Item -Path "Env:$key" -Value $vars[$key] -ErrorAction SilentlyContinue}}@@ -1457,20 +1493,18 @@ function Write-LlamaFailureLog {Write-Host " | $line" -ForegroundColor DarkGray}}-# Mirror the plain (no ANSI) form of step/substep messages to the-# OS-level stdout handle when a parent is consuming our stdout via-# a pipe (CI `tee`, Python subprocess.PIPE, CREATE_NO_WINDOW grandchild).-# Write-Host on PS 5.1 routes through $Host.UI / the Information-# stream, neither of which propagates reliably across the-# install.ps1 -> unsloth.exe -> python -> powershell.exe ->-# setup.ps1 process chain. [Console]::Out always lands on the OS-# stdout file handle. Gated on IsOutputRedirected so the-# interactive-console path keeps the colorized Write-Host output-# only (no double-print).+# Plain (no ANSI) form of a step/substep message on the OS stdout handle.+# Write-Host on 5.1 goes through the Information stream, which does not survive+# every install.ps1 -> unsloth.exe -> python -> powershell.exe chain.+#+# One half of an either/or: when redirected this is the ONLY sink. It used to+# run in ADDITION to Write-Host, assuming that never reached the pipe. It does,+# because the CLI spawns us as `-Command "& 'setup.ps1' *>&1"`, so every step+# printed twice.function Write-StudioStdoutMirror {param([Parameter(Mandatory = $true)][string]$Line)try {- if ([Console]::IsOutputRedirected) {+ if ($script:StudioStdoutRedirected) {[Console]::Out.WriteLine($Line)[Console]::Out.Flush()}@@ -1484,6 +1518,12 @@ function step {[string]$Color = "Green")$padded = if ($Label.Length -ge 15) { $Label.Substring(0, 15) } else { $Label.PadRight(15) }+ # Exactly one sink: the console handle when redirected, Write-Host (the only+ # one that colorizes) when interactive.+ if ($script:StudioStdoutRedirected) {+ Write-StudioStdoutMirror (" {0}{1}" -f $padded, $Value)+ return+ }if ($script:StudioVtOk -and -not $env:NO_COLOR) {$dim = Get-StudioAnsi Dim$rst = Get-StudioAnsi Reset@@ -1496,7 +1536,6 @@ function step {}Write-Host (" {0}{1}{2}{3}{4}{2}" -f $dim, $padded, $rst, $val, $Value)} else {- Write-Host (" {0}" -f $padded) -NoNewline -ForegroundColor DarkGray$fc = switch ($Color) {'Green' { 'DarkGreen' }'Yellow' { 'Yellow' }@@ -1504,9 +1543,11 @@ function step {'DarkGray' { 'DarkGray' }default { 'DarkGreen' }}- Write-Host $Value -ForegroundColor $fc+ # One composed record, not `-NoNewline` label + value: two Write-Host+ # calls are two Information records, and a redirected consumer turns each+ # boundary into a line break. Costs the dimmed label on no-VT consoles.+ Write-Host (" {0}{1}" -f $padded, $Value) -ForegroundColor $fc}- Write-StudioStdoutMirror (" {0}{1}" -f $padded, $Value)}function substep {@@ -1514,6 +1555,11 @@ function substep {[Parameter(Mandatory = $true)][string]$Message,[string]$Color = "DarkGray")+ # Exactly one sink, as in `step` above.+ if ($script:StudioStdoutRedirected) {+ Write-StudioStdoutMirror (" {0,-15}{1}" -f "", $Message)+ return+ }if ($script:StudioVtOk -and -not $env:NO_COLOR) {$msgCol = switch ($Color) {'Yellow' { (Get-StudioAnsi Warn) }@@ -1528,7 +1574,6 @@ function substep {}Write-Host (" {0,-15}{1}" -f "", $Message) -ForegroundColor $fc}- Write-StudioStdoutMirror (" {0,-15}{1}" -f "", $Message)}function Show-NpmRegistryHint {diff --git a/studio/src-tauri/src/install.rs b/studio/src-tauri/src/install.rsindex 25b990f7b40..dad51dbeea5 100644--- a/studio/src-tauri/src/install.rs+++ b/studio/src-tauri/src/install.rs@@ -431,6 +431,15 @@ fn spawn_script(cmd.env_remove("UNSLOTH_STUDIO_HOME");cmd.env_remove("STUDIO_HOME");+ // We decode this child as UTF-8 below, so its Python descendants must emit+ // UTF-8 or the log fills with U+FFFD. The .ps1 entry points set these too;+ // this covers any path reaching Python without them.+ #[cfg(windows)]+ {+ cmd.env("PYTHONUTF8", "1");+ cmd.env("PYTHONIOENCODING", "utf-8");+ }+// On Windows, launch the installer directly with CREATE_NO_WINDOW.// The app process is assigned to a KILL_ON_JOB_CLOSE job in main.rs, so// child cleanup on crash comes from inherited job membership instead.diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rsindex 037c252464b..908f1b4b904 100644--- a/studio/src-tauri/src/process.rs+++ b/studio/src-tauri/src/process.rs@@ -606,6 +606,14 @@ pub fn start_backend(cmd.env_remove("UNSLOTH_STUDIO_HOME");cmd.env_remove("STUDIO_HOME");+ // read_output_stream decodes as UTF-8; without these, Python encodes its+ // redirected streams with the locale code page and non-ASCII lands as U+FFFD.+ #[cfg(windows)]+ {+ cmd.env("PYTHONUTF8", "1");+ cmd.env("PYTHONIOENCODING", "utf-8");+ }+// Reset state, spawn, and store the child while holding the backend mutex.// This keeps the no-child check atomic: a concurrent start/stop cannot slip// into the old window between generation reset and child storage.diff --git a/studio/src-tauri/src/update.rs b/studio/src-tauri/src/update.rsindex d5b11c14052..71318427226 100644--- a/studio/src-tauri/src/update.rs+++ b/studio/src-tauri/src/update.rs@@ -52,7 +52,11 @@ fn build_update_command(bin: &std::path::Path) -> Result<Command, String> {let mut cmd = Command::new(python);// Isolated mode prevents a project-local unsloth_cli module or an// inherited Python search path from shadowing the managed package.- cmd.args(["-I", "-c", WINDOWS_CLI_ENTRYPOINT, "studio", "update"]);+ //+ // -X utf8, not PYTHONUTF8: -I implies -E, so this process ignores every+ // PYTHON* variable and its own output would reach read_lossy_lines in+ // the locale encoding. The env vars still apply to descendants.+ cmd.args(["-X", "utf8", "-I", "-c", WINDOWS_CLI_ENTRYPOINT, "studio", "update"]);cmd.env_remove("PYTHONHOME");cmd.env_remove("PYTHONPATH");Ok(cmd)@@ -94,6 +98,14 @@ fn spawn_update(// shortcuts (Tauri owns its own bundle entries).cmd.env("UNSLOTH_TAURI_UPDATE", "1");+ // read_lossy_lines decodes as UTF-8, and here the child is Python itself,+ // which otherwise encodes redirected streams with the locale code page.+ #[cfg(windows)]+ {+ cmd.env("PYTHONUTF8", "1");+ cmd.env("PYTHONIOENCODING", "utf-8");+ }+#[cfg(windows)]let mut child: Box<dyn ChildWrapper + Send> = {use std::os::windows::process::CommandExt;@@ -484,6 +496,9 @@ mod tests {assert_eq!(cmd.get_args().map(OsString::from).collect::<Vec<_>>(),vec![+ // -X utf8 leads: -I implies -E, so PYTHONUTF8 would be ignored.+ OsString::from("-X"),+ OsString::from("utf8"),OsString::from("-I"),OsString::from("-c"),OsString::from(WINDOWS_CLI_ENTRYPOINT),diff --git a/tests/python/test_windows_setup_output_encoding.py b/tests/python/test_windows_setup_output_encoding.pynew file mode 100644index 00000000000..6a31575155f--- /dev/null+++ b/tests/python/test_windows_setup_output_encoding.py@@ -0,0 +1,244 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The Windows desktop setup log must be UTF-8 and must print each step once.++"Getting things ready..." used to produce::++ ?? Unsloth Studio Setup+ ????????????????????????????????????????????????????+ gpu+ none (chat-only / GGUF)+ gpu none (chat-only / GGUF)++Encoding: 5.1 encodes redirected output with the OEM code page while the desktop+app decodes the pipe as UTF-8 (``from_utf8_lossy``, src-tauri/src/install.rs).+U+1F9A5 has no OEM form so PowerShell writes one ``?`` per UTF-16 surrogate;+U+2500 has one, so it becomes a bare 0xC4 and arrives as U+FFFD.++Duplication: ``step``/``substep`` wrote through Write-Host *and* a console-handle+mirror, and the CLI spawns setup.ps1 as ``-Command "& '...' *>&1"``, which merges+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.++The byte-level tests assert on raw bytes; decoding first would hide the exact+regression being guarded.+"""++from __future__ import annotations++import re+import shutil+import subprocess+import sys+from pathlib import Path++import pytest+++REPO_ROOT = Path(__file__).resolve().parents[2]+SETUP_PS1 = REPO_ROOT / "studio" / "setup.ps1"+INSTALL_PS1 = REPO_ROOT / "install.ps1"+EXTRACTOR = REPO_ROOT / "tests" / "studio_setup_ps1" / "Get-FunctionSource.ps1"++SLOTH = "\U0001f9a5"+RULE_CHAR = "─"+REPLACEMENT = "�"++# The desktop app spawns Windows PowerShell 5.1; pwsh stands in elsewhere. The+# OEM-code-page bug only reproduces on 5.1, which the Windows runner covers.+_PWSH = shutil.which("powershell") if sys.platform == "win32" else shutil.which("pwsh")+pwsh_only = pytest.mark.skipif(_PWSH is None, reason = "PowerShell is unavailable")+++def _harness(redirected_probe: bool) -> str:+ """Emit a known banner + steps using the real helpers.++ Extracted from setup.ps1 rather than restated, so a change in shape fails+ here instead of drifting.+ """+ sink = "$true" if redirected_probe else "[Console]::IsOutputRedirected"+ 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-StudioStdoutMirror', 'step', 'substep')) {{+ $src = Get-FunctionSource -Path '{SETUP_PS1.as_posix()}' -Name $fn+ if (-not $src) {{ throw "missing $fn" }}+ . ([scriptblock]::Create($src))+}}+$script:StudioVtOk = $false+$script:StudioStdoutRedirected = {sink}++$Rule = [string]::new([char]0x2500, 52)+$Sloth = [char]::ConvertFromUtf32(0x1F9A5)+if ($script:StudioStdoutRedirected) {{+ [Console]::Out.WriteLine(" $Sloth Unsloth Studio Setup")+ [Console]::Out.WriteLine(" $Rule")+ [Console]::Out.Flush()+}} else {{+ Write-Host (" " + $Sloth + " Unsloth Studio Setup")+ Write-Host (" " + $Rule)+}}+step "gpu" "none (chat-only / GGUF)"+step "long paths" "enabled"+substep "installing OXC validator runtime..."+"""+++def _run_capturing_bytes(script: str, use_command_shape: bool) -> 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.write_text(script, encoding = "utf-8")+ try:+ base = [_PWSH, "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"]+ if use_command_shape:+ literal = str(tmp).replace("'", "''")+ argv = base + ["-Command", f"& '{literal}' *>&1"]+ else:+ argv = base + ["-File", str(tmp)]+ proc = subprocess.run(argv, stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = 180)+ assert proc.returncode == 0, proc.stderr.decode("utf-8", errors = "replace")+ return proc.stdout+ finally:+ tmp.unlink(missing_ok = True)+++@pwsh_only[email protected]("use_command_shape", [False, True], ids = ["-File", "-Command-merged"])+def test_setup_output_is_valid_utf8(use_command_shape: bool) -> None:+ """Strict decode. Lossy decoding here would hide the exact regression."""+ raw = _run_capturing_bytes(_harness(redirected_probe = True), use_command_shape)+ text = raw.decode("utf-8") # strict on purpose; UnicodeDecodeError is the failure+ assert REPLACEMENT not in text, "output contains U+FFFD (OEM bytes decoded as UTF-8)"+++@pwsh_only[email protected]("use_command_shape", [False, True], ids = ["-File", "-Command-merged"])+def test_banner_glyphs_survive_the_pipe(use_command_shape: bool) -> None:+ raw = _run_capturing_bytes(_harness(redirected_probe = True), use_command_shape)+ text = raw.decode("utf-8")+ assert text.count(SLOTH) == 1, "sloth emoji lost or duplicated"+ assert "??" not in text, "emoji was transcoded to '?' by a non-UTF-8 code page"+ assert RULE_CHAR * 52 in text, "the 52-char rule did not survive intact"+++@pwsh_only[email protected]("use_command_shape", [False, True], ids = ["-File", "-Command-merged"])+def test_every_step_appears_exactly_once(use_command_shape: bool) -> None:+ raw = _run_capturing_bytes(_harness(redirected_probe = True), use_command_shape)+ text = raw.decode("utf-8")+ for sentinel in ("none (chat-only / GGUF)", "enabled", "installing OXC validator runtime..."):+ assert (+ text.count(sentinel) == 1+ ), f"{sentinel!r} appeared {text.count(sentinel)} times, expected 1"+++@pwsh_only[email protected]("use_command_shape", [False, True], ids = ["-File", "-Command-merged"])+def test_step_label_and_value_stay_on_one_line(use_command_shape: bool) -> None:+ """The `gpu` / newline / `none (chat-only / GGUF)` split."""+ raw = _run_capturing_bytes(_harness(redirected_probe = True), use_command_shape)+ lines = raw.decode("utf-8").splitlines()+ matches = [line for line in lines if "gpu" in line]+ assert len(matches) == 1, f"expected one gpu line, got {matches!r}"+ assert matches[0] == " gpu none (chat-only / GGUF)"+++# Source contracts. These run everywhere, including the Linux backend CI job,+# so a regression is caught without waiting for a Windows runner.+++def _strip_comments(source: str) -> str:+ return re.sub(r"(?m)#.*$", "", source)++[email protected]("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")+ assert "[Console]::OutputEncoding = $_UnslothUtf8NoBom" in source+ assert "$env:PYTHONUTF8 = '1'" in source+ assert "$env:PYTHONIOENCODING = 'utf-8'" in source++[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])+def test_entry_scripts_have_no_bom(path: Path) -> None:+ """5.1 parses BOM-less scripts as ANSI, so the fix stays ASCII-only.++ A BOM would be a far wider packaging change: these get concatenated and+ streamed through `irm | iex`.+ """+ assert not path.read_bytes().startswith(b"\xef\xbb\xbf")++[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])+def test_step_helper_emits_one_record(path: Path) -> None:+ """-NoNewline splits a logical line once a redirected consumer sees records."""+ source = _strip_comments(path.read_text(encoding = "utf-8"))+ match = re.search(r"(?m)^\s*function step\b", source)+ assert match, f"no step function in {path.name}"+ body = source[match.start() : match.start() + 2000]+ assert "-NoNewline" not in body+++def test_setup_resolves_the_redirect_sink_once() -> None:+ source = SETUP_PS1.read_text(encoding = "utf-8")+ assert "$script:StudioStdoutRedirected = [Console]::IsOutputRedirected" in source+++def test_refresh_environment_cannot_clobber_the_python_encoding_vars() -> None:+ """Refresh-Environment reloads the registry repeatedly through a long run.++ Without the guard a registry PYTHONUTF8=0 reloads over ours and every later+ Python child goes back to mojibake.+ """+ source = SETUP_PS1.read_text(encoding = "utf-8")+ assert "$key -eq 'PYTHONUTF8' -or $key -eq 'PYTHONIOENCODING'" in source++[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])+def test_entry_scripts_bind_a_utf8_writer_when_there_is_no_console(path: Path) -> None:+ """The setter needs a console handle, and the desktop spawns us without one.++ It drops the cached writer BEFORE throwing, assigning OutputEncoding only+ after, so Console.Out would rebuild on the old code page and redirected+ step/substep, whose only sink it is, would stay locale-encoded.+ """+ source = path.read_text(encoding = "utf-8")+ assert "[Console]::OpenStandardOutput()" in source+ assert "[Console]::SetOut(" in source+ # stderr is decoded identically and the failure text is built from it.+ assert "[Console]::OpenStandardError()" in source+ assert "[Console]::SetError(" in source+++def test_update_command_uses_the_utf8_switch_not_just_env() -> None:+ """-I implies -E, so the isolated update child ignores every PYTHON* var.++ https://docs.python.org/3/using/cmdline.html#cmdoption-I+ """+ source = (REPO_ROOT / "studio" / "src-tauri" / "src" / "update.rs").read_text(encoding = "utf-8")+ assert '"-X", "utf8"' in source, "isolated Python child needs -X utf8, env vars are ignored"+++ "rust_file",+ ["install.rs", "update.rs", "process.rs"],+)+def test_rust_windows_spawns_force_utf8(rust_file: str) -> None:+ """The Rust readers decode as UTF-8, so their Windows children must emit it."""+ source = (REPO_ROOT / "studio" / "src-tauri" / "src" / rust_file).read_text(encoding = "utf-8")+ assert 'cmd.env("PYTHONUTF8", "1");' in source, f"{rust_file} does not force PYTHONUTF8"+ assert (+ 'cmd.env("PYTHONIOENCODING", "utf-8");' in source+ ), f"{rust_file} does not force PYTHONIOENCODING"diff --git a/tests/studio_setup_ps1/Studio.Setup.Output.Tests.ps1 b/tests/studio_setup_ps1/Studio.Setup.Output.Tests.ps1new file mode 100644index 00000000000..b47920ebfaf--- /dev/null+++ b/tests/studio_setup_ps1/Studio.Setup.Output.Tests.ps1@@ -0,0 +1,236 @@+<#+ 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:++ gpu+ none (chat-only / GGUF)+ gpu none (chat-only / GGUF)++ Two causes. step/substep called Write-Host AND the console mirror, and the+ CLI spawns setup.ps1 as `-Command "& '...' *>&1"`, so both reached the pipe.+ And step's non-VT branch built one line from two Write-Host calls with+ -NoNewline, which a redirected consumer splits at the record boundary.++ Invariant now: exactly ONE sink. Redirected -> console handle. Interactive+ -> Write-Host.++ 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+ FAILS loudly rather than silently passing.+#>++BeforeAll {+ . (Join-Path $PSScriptRoot 'Get-FunctionSource.ps1')++ $candidates = @(+ $env:SETUP_PS1_PATH,+ (Join-Path $PSScriptRoot '..\..\studio\setup.ps1')+ ) | Where-Object { $_ }+ $script:SetupPs1 = $candidates | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1+ if (-not $script:SetupPs1) { throw "Could not locate studio/setup.ps1 (set SETUP_PS1_PATH)." }+ Write-Host "setup.ps1 under test: $script:SetupPs1"++ $script:InstallPs1 = Join-Path $PSScriptRoot '..\..\install.ps1'++ foreach ($fn in @('Get-StudioAnsi', '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))+ }++ # Capture the console-handle sink without a real pipe, so the redirected+ # path can be asserted from an ordinary interactive test host.+ function Invoke-CapturingConsoleOut {+ param(+ [Parameter(Mandatory = $true)][scriptblock]$Body,+ [Parameter(Mandatory = $true)][bool]$Redirected+ )+ $script:StudioStdoutRedirected = $Redirected+ $previous = [Console]::Out+ $writer = New-Object System.IO.StringWriter+ try {+ [Console]::SetOut($writer)+ # 6>&1 folds Write-Host into the pipeline so a stray one on the+ # redirected path is caught, not swallowed by the test host.+ $hostRecords = & $Body 6>&1+ } finally {+ [Console]::SetOut($previous)+ }+ [pscustomobject]@{+ Console = $writer.ToString()+ HostRecordCount = @($hostRecords).Count+ }+ }++ # Split on the real line separator only: the split-label bug produced a+ # genuine newline, not a CR redraw.+ #+ # The leading comma is load-bearing. `return @($x)` unrolls a one-element+ # array to a scalar, and a scalar string answers .Count = 1 while [0] gives+ # its first CHARACTER, so a "one line, and it reads X" test would pass the+ # count then compare against a single space.+ function Get-EmittedLines {+ param([string]$Text)+ if ([string]::IsNullOrEmpty($Text)) { return , @() }+ return , @($Text -split "`r?`n" | Where-Object { $_ -ne '' })+ }++ # Strip comments before asserting a construct is absent: the scripts under+ # test describe -NoNewline in prose, which a naive match would hit.+ function Get-CodeWithoutComments {+ param([string]$Source)+ $stripped = $Source -replace '(?m)#.*$', ''+ return $stripped+ }+}++Describe 'step / substep emit exactly one copy when stdout is redirected' {+ BeforeEach {+ $script:StudioVtOk = $false+ $env:NO_COLOR = $null+ }++ It 'emits a step once, with label and value on the SAME line' {+ $r = Invoke-CapturingConsoleOut -Redirected $true -Body {+ step "gpu" "none (chat-only / GGUF)"+ }+ $lines = Get-EmittedLines $r.Console+ $lines.Count | Should -Be 1+ $lines[0] | Should -Be " gpu none (chat-only / GGUF)"+ }++ It 'emits a substep once' {+ $r = Invoke-CapturingConsoleOut -Redirected $true -Body {+ substep "installing OXC validator runtime..."+ }+ (Get-EmittedLines $r.Console).Count | Should -Be 1+ }++ It 'writes NOTHING through Write-Host when redirected (the second copy)' {+ $r = Invoke-CapturingConsoleOut -Redirected $true -Body {+ step "long paths" "enabled"+ substep "detail"+ }+ $r.HostRecordCount | Should -Be 0+ }++ It 'keeps one line per step across a realistic run' {+ $r = Invoke-CapturingConsoleOut -Redirected $true -Body {+ step "gpu" "none (chat-only / GGUF)"+ step "long paths" "enabled"+ step "git" "git version 2.53.0.windows.2"+ substep "setting up Python environment..."+ }+ (Get-EmittedLines $r.Console).Count | Should -Be 4+ }++ It 'truncates an over-long label to the 15-column field without wrapping' {+ $r = Invoke-CapturingConsoleOut -Redirected $true -Body {+ step "an-extremely-long-label" "value"+ }+ $lines = Get-EmittedLines $r.Console+ $lines.Count | Should -Be 1+ $lines[0] | Should -Be " an-extremely-lovalue"+ }+}++Describe 'step / substep stay on Write-Host when attached to a console' {+ BeforeEach {+ $script:StudioVtOk = $false+ $env:NO_COLOR = $null+ }++ It 'writes nothing to the console handle when NOT redirected' {+ $r = Invoke-CapturingConsoleOut -Redirected $false -Body {+ step "gpu" "none (chat-only / GGUF)"+ }+ $r.Console | Should -BeNullOrEmpty+ }++ It 'emits a step as a SINGLE Write-Host record (not -NoNewline label + value)' {+ $r = Invoke-CapturingConsoleOut -Redirected $false -Body {+ step "gpu" "none (chat-only / GGUF)"+ }+ $r.HostRecordCount | Should -Be 1+ }++ It 'emits a substep as a single Write-Host record' {+ $r = Invoke-CapturingConsoleOut -Redirected $false -Body {+ substep "detail"+ }+ $r.HostRecordCount | Should -Be 1+ }++ It 'still emits one record on the ANSI path' {+ $script:StudioVtOk = $true+ $r = Invoke-CapturingConsoleOut -Redirected $false -Body {+ step "gpu" "ok"+ substep "detail"+ }+ $r.HostRecordCount | Should -Be 2+ }++ It 'still emits one record with NO_COLOR set' {+ $script:StudioVtOk = $true+ $env:NO_COLOR = '1'+ try {+ $r = Invoke-CapturingConsoleOut -Redirected $false -Body {+ step "gpu" "ok"+ }+ $r.HostRecordCount | Should -Be 1+ } finally {+ $env:NO_COLOR = $null+ }+ }+}++Describe 'Write-StudioStdoutMirror honors the resolved sink' {+ It 'writes when the sink says redirected' {+ $r = Invoke-CapturingConsoleOut -Redirected $true -Body {+ Write-StudioStdoutMirror "hello"+ }+ (Get-EmittedLines $r.Console) | Should -Be @('hello')+ }++ It 'stays silent when the sink says interactive' {+ $r = Invoke-CapturingConsoleOut -Redirected $false -Body {+ Write-StudioStdoutMirror "hello"+ }+ $r.Console | Should -BeNullOrEmpty+ }+}++Describe 'Source contracts that keep the fix from regressing' {+ It 'resolves the redirected sink once, into a script-scoped variable' {+ $source = Get-Content -Raw -LiteralPath $script:SetupPs1+ $source | Should -Match '\$script:StudioStdoutRedirected\s*=\s*\[Console\]::IsOutputRedirected'+ }++ It 'no longer calls IsOutputRedirected from inside the mirror' {+ # Reading it per-call let the sink disagree with the branch+ # step/substep took; it must be resolved once, up front.+ $src = Get-FunctionSource -Path $script:SetupPs1 -Name 'Write-StudioStdoutMirror'+ $src | Should -Not -Match 'IsOutputRedirected'+ }++ It 'does not use -NoNewline in setup.ps1 step (record boundaries become newlines)' {+ $src = Get-FunctionSource -Path $script:SetupPs1 -Name 'step'+ (Get-CodeWithoutComments $src) | Should -Not -Match '-NoNewline'+ }++ It 'does not use -NoNewline in install.ps1 step either (it has no mirror)' {+ $src = Get-FunctionSource -Path $script:InstallPs1 -Name 'step'+ $src | Should -Not -BeNullOrEmpty+ (Get-CodeWithoutComments $src) | Should -Not -Match '-NoNewline'+ }++ It 'sets the UTF-8 console encoding in both entry scripts' {+ foreach ($path in @($script:SetupPs1, $script:InstallPs1)) {+ $source = Get-Content -Raw -LiteralPath $path+ $source | Should -Match '\[Console\]::OutputEncoding\s*=\s*\$_UnslothUtf8NoBom'+ $source | Should -Match "PYTHONUTF8"+ $source | Should -Match "PYTHONIOENCODING"+ }+ }+}