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.

Windows: stop compiling C# for colour on hosts that already render it (#8767)

Daniel Han9c69529705a2
diff --git a/install.ps1 b/install.ps1
index b668222f4b1..692a8ed1d76 100644
--- a/install.ps1
+++ b/install.ps1
@@ -610,6 +610,11 @@ public static class UnslothStudioFinalPathV2
function Enable-StudioVirtualTerminal {
if ($env:NO_COLOR) { return $false }
+ # A redirected stdout is not a console and GetConsoleMode fails on a non-console handle,
+ # so the block below could only return $false anyway. Answer without Add-Type, which runs
+ # csc.exe and drops source in %TEMP%. install.rs spawns us with a pipe, so this is the path
+ # the compile was on.
+ if ($script:StudioStdoutRedirected) { return $false }
try {
if (-not ("StudioVT.Native" -as [type])) {
Add-Type -Namespace StudioVT -Name Native -MemberDefinition @'
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 1fcc83686b6..f773c6dc9c2 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -1615,6 +1615,11 @@ $Rule = [string]::new([char]0x2500, 52)
function Enable-StudioVirtualTerminal {
if ($env:NO_COLOR) { return $false }
+ # A redirected stdout is not a console and GetConsoleMode fails on a non-console handle, so the
+ # block below could only return $false anyway. Answer without Add-Type, which runs csc.exe and
+ # drops source in %TEMP%. The CLI and the desktop app both pipe us, so this is the path the
+ # compile was on.
+ if ($script:StudioStdoutRedirected) { return $false }
try {
Add-Type -Namespace StudioVT -Name Native -MemberDefinition @'
[DllImport("kernel32.dll")] public static extern IntPtr GetStdHandle(int nStdHandle);
diff --git a/tests/python/test_windows_setup_output_encoding.py b/tests/python/test_windows_setup_output_encoding.py
index 27bd973fed8..a96aeea4c08 100644
--- a/tests/python/test_windows_setup_output_encoding.py
+++ b/tests/python/test_windows_setup_output_encoding.py
@@ -623,12 +623,17 @@ def _console_less_probe(path: Path) -> str:
@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."""
+def _run_console_less(path: Path, source: str | None = None) -> tuple[int, bytes, str]:
+ """Spawn the probe the way install.rs spawns the installer, and read bytes.
+
+ `source` is for the VT parity case, which runs this file's own function beside the one it
+ replaced. A str keeps the lru_cache above workable; a dict would not hash.
+ """
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"))
+ text = _console_less_probe(path) if source is None else source
+ probe.write_bytes(text.replace("\n", "\r\n").encode("ascii"))
proc = subprocess.run(
[str(_WINDOWS_POWERSHELL), *TAURI_FLAGS, "-File", str(probe)],
stdout = subprocess.PIPE,
@@ -727,3 +732,58 @@ def test_console_less_banner_keeps_its_glyphs(path: Path) -> None:
assert text.count(RULE_CHAR * 52) == 1, (
f"expected one 52-char U+2500 rule, found {text.count(RULE_CHAR * 52)}" + detail
)
+
+
+# Sliced back out to rebuild the function this replaced, so parity is measured against the real
+# predecessor. The comments go with the guard: they do not execute, but leaving them behind
+# would make the reconstruction something this test invented rather than the merge-base function.
+_VT_FAST_PATH = re.compile(
+ r"(?m)^[ \t]*# A redirected stdout is not a console.*?\n"
+ r"(?:^[ \t]*#.*\n)*"
+ r"^[ \t]*if \(\$script:StudioStdoutRedirected\) \{ return \$false \}\n"
+)
+
+
+def _probe_without_the_vt_fast_path(path: Path) -> str:
+ probe = _console_less_probe(path)
+ stripped, count = _VT_FAST_PATH.subn("", probe, count = 1)
+ assert count == 1, (
+ f"{path.name}: the VT fast path is not in the sliced probe in the shape this test "
+ f"removes, so nothing was being compared. Update _VT_FAST_PATH."
+ )
+ return stripped
+
+
+def _vt_verdict(err: str) -> str:
+ for line in err.splitlines():
+ if line.startswith("studio_vt_ok="):
+ return line.split("=", 1)[1].strip()
+ raise AssertionError(f"the probe printed no studio_vt_ok line:\n{err}")
+
+
+@windows_only
+@powershell_51_only
[email protected]("path", [SETUP_PS1, INSTALL_PS1], ids = ["setup.ps1", "install.ps1"])
+def test_vt_fast_path_decides_exactly_as_the_compile_did(path: Path) -> None:
+ """Skipping csc.exe must not change one byte the user sees.
+
+ This probe is the changed branch, not a bystander: install.rs spawns with a pipe, so
+ `$script:StudioStdoutRedirected` is true here and the early return is what runs. The
+ reconstructed predecessor reaches Add-Type instead, and has to land on the same verdict.
+ """
+ new_code, new_raw, new_err = _run_console_less(path)
+ old_code, old_raw, old_err = _run_console_less(
+ path, source = _probe_without_the_vt_fast_path(path)
+ )
+ assert new_code == old_code == 0, (
+ f"probe exit codes {new_code} (with the fast path) and {old_code} (without)"
+ f"{_explain(path, new_code, new_raw, new_err)}"
+ )
+ assert _vt_verdict(new_err) == _vt_verdict(old_err) == "False", (
+ f"a redirected stream cannot render VT: the fast path returned "
+ f"{_vt_verdict(new_err)} where the compile returned {_vt_verdict(old_err)}"
+ )
+ assert new_raw == old_raw, (
+ "the banner bytes moved. Same verdict in, same bytes out is the whole contract of "
+ "this change" + _explain(path, new_code, new_raw, new_err)
+ )
diff --git a/tests/studio/test_installer_av_shapes.py b/tests/studio/test_installer_av_shapes.py
index c428882eea7..599419a0771 100644
--- a/tests/studio/test_installer_av_shapes.py
+++ b/tests/studio/test_installer_av_shapes.py
@@ -111,13 +111,18 @@ def test_a_hidden_window_never_pairs_with_a_bypassed_policy(name: str) -> None:
ALLOWED_PINVOKES = {
# Canonicalising linked ancestors of security-relevant paths. No PS 5.1 equivalent:
# ResolveLinkTarget is .NET 6+, and .Target misses a linked ancestor of a non-link leaf.
+ # Not skippable either: Get-StudioRuntimePathHash hashes this spelling byte for byte and
+ # Python derives the same mutex name from its own, so a GetFullPath fast path differing on
+ # case or an 8.3 name would let two installers each believe they hold the lock.
"CreateFileW",
"GetFinalPathNameByHandleW",
- # ANSI colour on legacy conhost.
+ # ANSI colour on a real console. Skipped entirely when stdout is redirected, see
+ # test_virtual_terminal_answers_a_redirected_stream_without_compiling.
"GetStdHandle",
"GetConsoleMode",
"SetConsoleMode",
- # Per-item Explorer icon refresh; the global broadcast alone does not recover a stale .lnk.
+ # Per-item Explorer icon refresh, standalone path only. ie4uinit.exe -show is the global
+ # broadcast, which alone does not recover a stale .lnk, so it is not a substitute.
"SHChangeNotify",
# PID -> image path for the venv-holder check. Win32_Process answers the same question,
# but test_windows_installer_concurrency_guard.py bans it and $process.Path there: the
@@ -147,6 +152,32 @@ def test_no_new_native_imports(name: str) -> None:
)
[email protected]("name", ("install.ps1", "studio/setup.ps1"))
+def test_virtual_terminal_answers_a_redirected_stream_without_compiling(name: str) -> None:
+ """Add-Type runs the C# compiler, so the answer we already know must come first.
+
+ Only the redirected case is decided early, and it is decided FALSE. A redirected stdout is
+ not a console, GetConsoleMode fails on a non-console handle, and the compiled path could
+ only have returned false too. Anything that claimed VT here would put raw escape sequences
+ in the Studio log panel, which is a pipe.
+ """
+ text = _text(name)
+ start = text.index("function Enable-StudioVirtualTerminal")
+ # The call, not the comment above it.
+ call = re.compile(r"(?m)^[ \t]*Add-Type\b").search(text, start)
+ assert call, f"{name} no longer compiles the console thunk; update this guard"
+ compile_at = call.start()
+ fast_path = text.index("if ($script:StudioStdoutRedirected) { return $false }", start)
+ assert fast_path < compile_at, (
+ f"{name} compiles C# for colour before checking the stream: move the redirect guard "
+ f"above Add-Type, or every install spawns csc.exe again."
+ )
+ assert "$true" not in text[fast_path:compile_at], (
+ f"{name} returns something other than $false before the compile. The early answer is "
+ f"only sound because a redirected stream can never render VT."
+ )
+
+
@pytest.mark.parametrize("name", ALL_SCRIPTS)
def test_no_process_memory_apis(name: str) -> None:
# The installer reads image paths, nothing more. Reaching into another process's memory