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
Windows: stop depending on the generated unsloth.exe console script (#8592)
Daniel Han1b48147d8e9f
diff --git a/.github/scripts/virgin-windows-install.ps1 b/.github/scripts/virgin-windows-install.ps1index 8655d4483e3..616e968c6c2 100644--- a/.github/scripts/virgin-windows-install.ps1+++ b/.github/scripts/virgin-windows-install.ps1@@ -83,6 +83,12 @@ if ($rc -ne 0) {if (Test-Path -LiteralPath $cli) { Write-Host "unsloth CLI: $cli" }else { $failures += "installer exited 0 but left no unsloth CLI at $cli" }}+ # issue #8490: the generated .exe launchers above are unsigned, so Application+ # Control can deny them. The .cmd shim runs the managed interpreter instead and+ # is the escape hatch a locked-down machine has, so its absence is a failure.+ $cmdShim = Join-Path $env:UNSLOTH_STUDIO_HOME 'bin\unsloth.cmd'+ if (Test-Path -LiteralPath $cmdShim) { Write-Host "unsloth CLI shim: $cmdShim" }+ else { $failures += "installer exited 0 but left no policy-safe CLI shim at $cmdShim" }}Section 'assert: torch imports'diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.ymlindex 88afed5eed6..502ff282b18 100644--- a/.github/workflows/cross-platform-parity-ci.yml+++ b/.github/workflows/cross-platform-parity-ci.yml@@ -75,6 +75,10 @@ on:- 'tests/studio/test_xpu_arm64_torchaudio.ps1'- 'tests/studio/test_amd_venv_repair_loop.ps1'- 'tests/studio/test_amd_name_arch_r9700.ps1'+ - 'tests/studio/test_application_control_cli_fallback.ps1'+ # test_application_control_cli_fallback.ps1 pins install.ps1's trampoline against+ # process.rs's, so a change to either spelling has to run here.+ - 'studio/src-tauri/src/process.rs'- 'tests/sh/test_install_sh_xpu_flavor_probe.sh'- 'tests/sh/test_setup_xpu_fastpath_escape.sh'- 'tests/sh/test_setup_xpu_posix_summary.sh'@@ -128,6 +132,10 @@ on:- 'tests/studio/test_xpu_arm64_torchaudio.ps1'- 'tests/studio/test_amd_venv_repair_loop.ps1'- 'tests/studio/test_amd_name_arch_r9700.ps1'+ - 'tests/studio/test_application_control_cli_fallback.ps1'+ # test_application_control_cli_fallback.ps1 pins install.ps1's trampoline against+ # process.rs's, so a change to either spelling has to run here.+ - 'studio/src-tauri/src/process.rs'- 'tests/sh/test_install_sh_xpu_flavor_probe.sh'- 'tests/sh/test_setup_xpu_fastpath_escape.sh'- 'tests/sh/test_setup_xpu_posix_summary.sh'@@ -240,6 +248,13 @@ jobs:- name: AMD GPU-name arch table testsshell: pwshrun: pwsh -NoProfile -File tests/studio/test_amd_name_arch_r9700.ps1+ # AST-extracted helpers plus a real .cmd written to a temp dir, so no venv and no+ # Windows needed. The 1260 classification is exercised against crafted exceptions:+ # a hosted runner has no Application Control policy to be denied by. The enforced+ # end-to-end leg lives in the AppLocker workflow.+ - name: Application Control CLI fallback tests+ shell: pwsh+ run: pwsh -NoProfile -File tests/studio/test_application_control_cli_fallback.ps1- name: POSIX rollback lifecycle testsif: runner.os == 'Linux'run: sh tests/sh/test_install_rollback_lifecycle.shdiff --git a/.github/workflows/windows-application-control-ci.yml b/.github/workflows/windows-application-control-ci.ymlnew file mode 100644index 00000000000..18ca06a6e3b--- /dev/null+++ b/.github/workflows/windows-application-control-ci.yml@@ -0,0 +1,458 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++# Regression leg for issue #8490: Windows Application Control blocks the+# generated unsloth.exe console launcher, and the installer died on it at+# "Running studio setup".+#+# The launcher pip generates for `[project.scripts] unsloth` is an unsigned PE+# wrapper. AppLocker, WDAC and Smart App Control deny it. The managed python.exe+# beside it is a copy of the signed CPython binary and still runs, so every+# internal invocation goes through the interpreter instead.+#+# This job installs a local AppLocker policy that denies ONLY the generated+# Scripts\unsloth.exe, for a purpose-made standard user, then requires the FULL+# installer to SUCCEED under it. That inverts the maintainer's original+# reproduction, which asserted the failure. The runner is ephemeral and the+# policy is still removed in the final cleanup.+#+# What must hold under the deny rule:+# 1. The deny rule is really enforced. A negative control runs the stub as the+# denied user on purpose and requires Windows error 1260 plus AppLocker+# event 8004. Enforcement cannot be inferred from the installer instead:+# the whole point of the fix is that nothing executes the stub, so a+# correct run produces no block event of its own, and Test-AppLockerPolicy+# only predicts a decision, it never records one. Without this control a+# policy that silently failed to apply would let a green installer run+# masquerade as a fix.+# 2. install.ps1 exits 0 (the setup handoff no longer runs the stub) and never+# trips the block itself.+# 3. bin\unsloth.cmd, the policy-safe PATH shim, runs the CLI.+#+# UNSLOTH_STUDIO_HOME is pinned to a fixed path for every step. The deny rule+# names one absolute file, and the installer under test runs as a DIFFERENT user+# whose profile install.ps1 would otherwise resolve on its own: without the pin+# the job can install somewhere the rule never covered and pass having proved+# nothing. Start-Process -Credential -LoadUserProfile gives the child the target+# user's environment block rather than this job's, so the probe wrappers set the+# variable themselves rather than relying on inheritance.++name: Windows Application Control CI++on:+ pull_request:+ paths:+ - 'install.ps1'+ - 'scripts/uninstall.ps1'+ - 'studio/setup.ps1'+ - 'unsloth_cli/**'+ - 'studio/src-tauri/src/process.rs'+ - 'studio/src-tauri/src/update.rs'+ - 'studio/src-tauri/src/commands.rs'+ - 'studio/src-tauri/src/desktop_auth.rs'+ - 'studio/src-tauri/src/preflight/managed.rs'+ - 'pyproject.toml'+ - '.github/workflows/windows-application-control-ci.yml'+ push:+ branches: [main]+ workflow_dispatch:++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}++permissions:+ contents: read++jobs:+ applocker-denied-launcher:+ name: installer survives a denied unsloth.exe+ runs-on: windows-latest+ timeout-minutes: 45++ env:+ # Outside any user profile, so the admin who installs and the standard+ # user who re-runs the installer resolve the same absolute paths.+ UNSLOTH_STUDIO_HOME: 'C:\Users\Public\issue-8490-home'+ UNSLOTH_PROBE_ROOT: 'C:\Users\Public\issue-8490-application-control'+ UNSLOTH_PROBE_USER: 'AppLockerProbe'+ UNSLOTH_PROBE_PASSWORD: 'Us8490!Probe'+ # Not --tauri: the desktop mode refuses UNSLOTH_STUDIO_HOME, and the pinned home is+ # what makes the file the deny rule names the file the installer actually creates.+ # The blocked call site is the same in both modes, and the shell path additionally+ # exercises the PATH shim and the launch instructions this fix changed.+ UNSLOTH_SKIP_AUTOSTART: '1'++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - name: Create the managed install and generated launcher+ shell: powershell+ env:+ UNSLOTH_VERBOSE: '1'+ run: |+ $ErrorActionPreference = 'Continue'+ New-Item -ItemType Directory -Force -Path logs | Out-Null++ & powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `+ -File .\install.ps1 --no-torch *>&1 |+ Tee-Object -FilePath logs\baseline-install.log+ $installerExit = $LASTEXITCODE+ $global:LASTEXITCODE = 0+ if ($installerExit -ne 0) {+ Write-Host "::error::Baseline desktop install failed with exit $installerExit."+ exit 1+ }++ # The exact file the deny rule will name. install.ps1 puts the venv at+ # <UNSLOTH_STUDIO_HOME>\unsloth_studio, so this is fully determined by+ # the pinned home rather than by whose profile is running.+ $unslothExe = Join-Path $env:UNSLOTH_STUDIO_HOME 'unsloth_studio\Scripts\unsloth.exe'+ if (-not (Test-Path -LiteralPath $unslothExe -PathType Leaf)) {+ Write-Host "::error::Baseline install did not create $unslothExe."+ exit 1+ }+ Write-Host "Baseline install created: $unslothExe"++ - name: Enforce a narrow AppLocker deny rule for a standard user+ shell: powershell+ run: |+ $ErrorActionPreference = 'Stop'++ $probeUser = $env:UNSLOTH_PROBE_USER+ $probePassword = $env:UNSLOTH_PROBE_PASSWORD+ & net.exe user $probeUser $probePassword /add /passwordchg:no+ if ($LASTEXITCODE -ne 0) { throw "Could not create $probeUser (exit $LASTEXITCODE)" }+ $probeAccount = [System.Security.Principal.NTAccount]::new($env:COMPUTERNAME, $probeUser)+ $probeSid = $probeAccount.Translate(+ [System.Security.Principal.SecurityIdentifier]+ ).Value++ $blockedExe = Join-Path $env:UNSLOTH_STUDIO_HOME 'unsloth_studio\Scripts\unsloth.exe'+ $escapedBlockedExe = [System.Security.SecurityElement]::Escape($blockedExe)+ $allowId = [guid]::NewGuid()+ $denyId = [guid]::NewGuid()+ $policy = @"+ <AppLockerPolicy Version="1">+ <RuleCollection Type="Exe" EnforcementMode="Enabled">+ <FilePathRule Id="$allowId" Name="Allow all other executables" Description="Keep the hosted runner usable" UserOrGroupSid="S-1-1-0" Action="Allow">+ <Conditions>+ <FilePathCondition Path="*" />+ </Conditions>+ </FilePathRule>+ <FilePathRule Id="$denyId" Name="Block generated Unsloth console launcher" Description="Regression guard for issue 8490" UserOrGroupSid="$probeSid" Action="Deny">+ <Conditions>+ <FilePathCondition Path="$escapedBlockedExe" />+ </Conditions>+ </FilePathRule>+ </RuleCollection>+ </AppLockerPolicy>+ "@+ $policyPath = Join-Path $PWD 'logs\applocker-policy.xml'+ $policy | Set-Content -LiteralPath $policyPath -Encoding UTF8++ & sc.exe config AppIDSvc start= auto+ if ($LASTEXITCODE -ne 0) { throw "Could not configure AppIDSvc (exit $LASTEXITCODE)" }+ Start-Service -Name AppIDSvc+ Set-AppLockerPolicy -XmlPolicy $policyPath+ & gpupdate.exe /target:computer /force+ if ($LASTEXITCODE -ne 0) { throw "gpupdate failed (exit $LASTEXITCODE)" }+ # AppIDSvc reads the effective policy when it starts. Starting it first+ # and setting the policy afterwards left the service enforcing nothing,+ # and the first run of this job watched the stub launch happily for the+ # denied user. Restart AFTER the policy is in place, every time.+ Restart-Service -Name AppIDSvc -Force+ (Get-Service -Name AppIDSvc).WaitForStatus('Running', [timespan]::FromSeconds(60))++ Get-AppLockerPolicy -Effective -Xml |+ Set-Content -LiteralPath logs\applocker-effective.xml -Encoding UTF8++ $probeIdentity = "$env:COMPUTERNAME\$probeUser"+ Test-AppLockerPolicy -XmlPolicy $policyPath -Path $blockedExe -User $probeIdentity |+ Format-List * | Out-File -LiteralPath logs\applocker-test.txt -Encoding utf8+ $policyTest = Get-Content -LiteralPath logs\applocker-test.txt -Raw+ if ($policyTest -notmatch 'Denied') {+ throw "Test-AppLockerPolicy did not deny $blockedExe for $probeIdentity.`n$policyTest"+ }++ & icacls.exe $env:UNSLOTH_STUDIO_HOME `+ /grant "${probeUser}:(OI)(CI)M" /T /C /Q | Out-File logs\icacls.txt+ if ($LASTEXITCODE -ne 0) { throw "Could not grant the probe user access (exit $LASTEXITCODE)" }+ Write-Host "AppLocker will block only $blockedExe for standard user $probeIdentity."++ - name: Negative control -- the denied user really cannot run the stub+ shell: powershell+ run: |+ $ErrorActionPreference = 'Stop'++ # The probe user needs a writable place to work; its own profile is+ # created by -LoadUserProfile.+ $probeRoot = $env:UNSLOTH_PROBE_ROOT+ New-Item -ItemType Directory -Force -Path $probeRoot | Out-Null+ & icacls.exe $probeRoot /grant "$($env:UNSLOTH_PROBE_USER):(OI)(CI)M" /Q | Out-Null+ if ($LASTEXITCODE -ne 0) { throw "Could not grant access to $probeRoot" }++ (Get-Date).ToString('o') |+ Set-Content -LiteralPath logs\negative-control-started-at.txt++ # Run the stub on purpose, as the denied user, and require Windows to+ # refuse it with ERROR_ACCESS_DISABLED_BY_POLICY. This is the only+ # thing in the job that generates a block event, because everything+ # else is supposed to avoid the stub entirely.+ $blockedExe = Join-Path $env:UNSLOTH_STUDIO_HOME 'unsloth_studio\Scripts\unsloth.exe'+ $wrapperTemplate = @'+ $ErrorActionPreference = 'Stop'+ try {+ & '__BLOCKED_EXE__' --version+ } catch {+ # $LASTEXITCODE says nothing here: no process was created, so it+ # holds whatever the previous native command left behind.+ $ex = $_.Exception+ while ($null -ne $ex) {+ if ($ex -is [System.ComponentModel.Win32Exception] -and+ $ex.NativeErrorCode -eq 1260) { exit 0 }+ if ($ex.HResult -eq -2147023636) { exit 0 }+ $ex = $ex.InnerException+ }+ Write-Output "unexpected failure: $($_.Exception.GetType().FullName): $($_.Exception.Message)"+ exit 91+ }+ exit 90+ '@+ $wrapper = $wrapperTemplate.Replace('__BLOCKED_EXE__', $blockedExe.Replace("'", "''"))+ $wrapperPath = Join-Path $probeRoot 'invoke-blocked-exe.ps1'+ $wrapper | Set-Content -LiteralPath $wrapperPath -Encoding UTF8+ $controlOut = Join-Path $probeRoot 'control-stdout.log'+ $controlErr = Join-Path $probeRoot 'control-stderr.log'+ New-Item -ItemType File -Force -Path $controlOut, $controlErr | Out-Null++ $securePassword = ConvertTo-SecureString $env:UNSLOTH_PROBE_PASSWORD -AsPlainText -Force+ $credential = [System.Management.Automation.PSCredential]::new(+ "$env:COMPUTERNAME\$($env:UNSLOTH_PROBE_USER)",+ $securePassword+ )+ # Enforcement goes live asynchronously: the service has to load the+ # policy and the user's token has to pick it up, and neither is+ # signalled. Retry rather than sample once, or the job fails on timing+ # and reports a regression that is not there.+ $exitCode = $null+ foreach ($attempt in 1..12) {+ $process = Start-Process -FilePath powershell.exe `+ -ArgumentList @('-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', $wrapperPath) `+ -Credential $credential -LoadUserProfile -WorkingDirectory $probeRoot `+ -RedirectStandardOutput $controlOut -RedirectStandardError $controlErr `+ -Wait -PassThru+ $exitCode = $process.ExitCode+ # One file per attempt. Enforcement was observed going live on the+ # fourth try, and a single overwritten log left the evidence artifact+ # showing an earlier attempt's output next to a passing step, which+ # reads like a contradiction.+ "attempt ${attempt}: exit $exitCode" |+ Set-Content -LiteralPath "logs\negative-control-$attempt.log" -Encoding UTF8+ Get-Content -LiteralPath $controlOut, $controlErr |+ Add-Content -LiteralPath "logs\negative-control-$attempt.log" -Encoding UTF8+ Copy-Item -LiteralPath "logs\negative-control-$attempt.log" `+ -Destination logs\negative-control.log -Force+ Write-Host "attempt ${attempt}: exit $exitCode"+ if ($exitCode -eq 0) { break }+ Start-Sleep -Seconds 10+ }+ Get-Content -LiteralPath logs\negative-control.log | Write-Host++ if ($exitCode -eq 90) {+ Write-Host "::error::$blockedExe ran for the denied user. The AppLocker policy is not enforced, so the rest of this job would prove nothing."+ exit 1+ }+ if ($exitCode -ne 0) {+ Write-Host "::error::The negative control failed for an unexpected reason (exit $exitCode); enforcement is unproven."+ exit 1+ }+ Write-Host 'PASS: the denied user cannot start the generated launcher (Windows error 1260).'++ - name: Require the installer to succeed with the launcher denied+ shell: powershell+ env:+ UNSLOTH_VERBOSE: '1'+ run: |+ $ErrorActionPreference = 'Stop'+ (Get-Date).ToString('o') | Set-Content -LiteralPath logs\install-started-at.txt++ $probeRoot = $env:UNSLOTH_PROBE_ROOT+ & icacls.exe $PWD /grant "$($env:UNSLOTH_PROBE_USER):(OI)(CI)RX" /T /C /Q | Out-Null+ if ($LASTEXITCODE -ne 0) { throw "Could not grant repo read access to the probe user" }++ # Re-run the whole installer as the denied user. This is the path that+ # regressed in issue #8490: the setup handoff must reach the CLI+ # through the managed interpreter, never through the blocked stub.+ $wrapperTemplate = @'+ $ErrorActionPreference = 'Continue'+ # Set here, not inherited: -Credential -LoadUserProfile hands the child+ # the probe user's environment block, so without this install.ps1 would+ # resolve that user's own profile and install outside the deny rule.+ $env:UNSLOTH_STUDIO_HOME = '__HOME__'+ $env:UNSLOTH_SKIP_AUTOSTART = '1'+ Set-Location -LiteralPath '__REPO__'+ & powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `+ -File .\install.ps1 --no-torch *>&1+ exit $(if ($LASTEXITCODE) { $LASTEXITCODE } else { 0 })+ '@+ # Two statements, not a chain with the dot at end of line: this step+ # runs under Windows PowerShell 5.1, which does not accept that+ # continuation. Both values are single-quoted in the template, so an+ # apostrophe in either path is doubled to escape it.+ $wrapper = $wrapperTemplate.Replace('__REPO__', "$PWD".Replace("'", "''"))+ $wrapper = $wrapper.Replace('__HOME__', $env:UNSLOTH_STUDIO_HOME.Replace("'", "''"))+ $wrapperPath = Join-Path $probeRoot 'invoke-installer.ps1'+ $wrapper | Set-Content -LiteralPath $wrapperPath -Encoding UTF8+ $probeStdout = Join-Path $probeRoot 'stdout.log'+ $probeStderr = Join-Path $probeRoot 'stderr.log'+ New-Item -ItemType File -Force -Path $probeStdout, $probeStderr | Out-Null++ $securePassword = ConvertTo-SecureString $env:UNSLOTH_PROBE_PASSWORD -AsPlainText -Force+ $credential = [System.Management.Automation.PSCredential]::new(+ "$env:COMPUTERNAME\$($env:UNSLOTH_PROBE_USER)",+ $securePassword+ )+ $process = Start-Process -FilePath powershell.exe `+ -ArgumentList @('-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', $wrapperPath) `+ -Credential $credential -LoadUserProfile -WorkingDirectory $probeRoot `+ -RedirectStandardOutput $probeStdout -RedirectStandardError $probeStderr `+ -Wait -PassThru+ $installerExit = $process.ExitCode+ Get-Content -LiteralPath $probeStdout, $probeStderr |+ Set-Content -LiteralPath logs\install.log -Encoding UTF8+ $installerExit | Set-Content -LiteralPath logs\installer-exit-code.txt+ Get-Content -LiteralPath logs\install.log | Select-Object -Last 80 | Write-Host++ if ($installerExit -ne 0) {+ Write-Host "::error::install.ps1 failed (exit $installerExit) with only unsloth.exe denied. Issue 8490 has regressed."+ exit 1+ }++ # The installer must have written to the home the deny rule covers. If+ # it resolved somewhere else, everything above passed against a file no+ # policy ever touched.+ $blockedExe = Join-Path $env:UNSLOTH_STUDIO_HOME 'unsloth_studio\Scripts\unsloth.exe'+ if (-not (Test-Path -LiteralPath $blockedExe -PathType Leaf)) {+ Write-Host "::error::The installer did not install to the denied home; $blockedExe is missing, so this run proved nothing."+ exit 1+ }++ $installLog = Get-Content -LiteralPath logs\install.log -Raw+ # A run that never reached the handoff would exit 0 having proved nothing.+ if ($installLog -notmatch 'Running studio setup|running unsloth studio setup') {+ Write-Host '::error::The installer exited 0 without reaching the studio setup handoff.'+ exit 1+ }+ # Both wordings: the first is PowerShell's own launch failure, the+ # second is install.ps1's diagnostic for a blocked managed interpreter.+ if ($installLog -match 'Application Control policy has blocked|Windows Application Control blocked') {+ Write-Host '::error::The installer still tried to execute a program the policy denies.'+ exit 1+ }++ Write-Host "PASS: install.ps1 completed (exit $installerExit) with unsloth.exe denied."+ $global:LASTEXITCODE = 0+ exit 0++ - name: Require the policy-safe shim to run the CLI+ shell: powershell+ run: |+ $ErrorActionPreference = 'Stop'+ $shim = Join-Path $env:UNSLOTH_STUDIO_HOME 'bin\unsloth.cmd'+ if (-not (Test-Path -LiteralPath $shim -PathType Leaf)) {+ Write-Host "::error::The installer left no policy-safe shim at $shim."+ exit 1+ }+ # As the denied user, so the .exe next to it stays unrunnable.+ $probeRoot = $env:UNSLOTH_PROBE_ROOT+ $wrapperPath = Join-Path $probeRoot 'invoke-shim.ps1'+ @"+ `$ErrorActionPreference = 'Continue'+ & '$($shim.Replace("'", "''"))' --version+ exit `$(if (`$LASTEXITCODE) { `$LASTEXITCODE } else { 0 })+ "@ | Set-Content -LiteralPath $wrapperPath -Encoding UTF8+ $shimOut = Join-Path $probeRoot 'shim-stdout.log'+ $shimErr = Join-Path $probeRoot 'shim-stderr.log'+ New-Item -ItemType File -Force -Path $shimOut, $shimErr | Out-Null++ $securePassword = ConvertTo-SecureString $env:UNSLOTH_PROBE_PASSWORD -AsPlainText -Force+ $credential = [System.Management.Automation.PSCredential]::new(+ "$env:COMPUTERNAME\$($env:UNSLOTH_PROBE_USER)",+ $securePassword+ )+ $process = Start-Process -FilePath powershell.exe `+ -ArgumentList @('-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', $wrapperPath) `+ -Credential $credential -LoadUserProfile -WorkingDirectory $probeRoot `+ -RedirectStandardOutput $shimOut -RedirectStandardError $shimErr `+ -Wait -PassThru+ Get-Content -LiteralPath $shimOut, $shimErr |+ Set-Content -LiteralPath logs\shim.log -Encoding UTF8+ Get-Content -LiteralPath logs\shim.log | Write-Host+ if ($process.ExitCode -ne 0) {+ Write-Host "::error::unsloth.cmd --version failed (exit $($process.ExitCode)) for the denied user."+ exit 1+ }+ Write-Host 'PASS: the .cmd shim runs the CLI with the .exe denied.'++ - name: Require an AppLocker block event for the negative control+ if: always()+ shell: powershell+ run: |+ if (-not (Test-Path -LiteralPath logs\negative-control-started-at.txt)) {+ Write-Host '::warning::The negative control did not start; no AppLocker event is expected.'+ exit 0+ }+ # Scoped to the negative control, the only thing in this job that+ # deliberately starts the stub. The installer window is the wrong one+ # to look in: a correct installer never touches it.+ $startedAt = [datetime](Get-Content -LiteralPath logs\negative-control-started-at.txt -Raw)+ $events = @(+ Get-WinEvent -FilterHashtable @{+ LogName = 'Microsoft-Windows-AppLocker/EXE and DLL'+ # 8004 is "was prevented from running". 8002 ("was allowed") is+ # also logged under EnforcementMode=Enabled, so without this an+ # allowed launch would pass as proof of a block.+ Id = 8004+ StartTime = $startedAt.AddSeconds(-5)+ } -ErrorAction SilentlyContinue |+ Where-Object { $_.Message -match 'unsloth\.exe' }+ )+ $events | Format-List TimeCreated, Id, LevelDisplayName, Message |+ Out-File -LiteralPath logs\applocker-events.txt -Encoding utf8 -Width 300++ # Without this the job is vacuous: an unenforced policy would let a+ # green installer run masquerade as a fix.+ if ($events.Count -eq 0) {+ Write-Host '::error::No AppLocker 8004 event naming unsloth.exe was recorded; the deny rule never applied.'+ exit 1+ }+ $events | ForEach-Object {+ Write-Host "AppLocker event $($_.Id): $($_.Message)"+ }+ Write-Host 'PASS: Windows recorded the unsloth.exe policy block.'++ - name: Upload evidence+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: windows-application-control+ path: logs/+ retention-days: 7+ if-no-files-found: warn++ - name: Remove the local AppLocker policy+ if: always()+ shell: powershell+ run: |+ $emptyPolicy = Join-Path $env:RUNNER_TEMP 'empty-applocker-policy.xml'+ '<AppLockerPolicy Version="1" />' |+ Set-Content -LiteralPath $emptyPolicy -Encoding UTF8+ Set-AppLockerPolicy -XmlPolicy $emptyPolicy+ Stop-Service -Name AppIDSvc -Force -ErrorAction SilentlyContinue+ if (Get-LocalUser -Name $env:UNSLOTH_PROBE_USER -ErrorAction SilentlyContinue) {+ & net.exe user $env:UNSLOTH_PROBE_USER /delete 2>$null | Out-Null+ }+ $global:LASTEXITCODE = 0diff --git a/install.ps1 b/install.ps1index 3749e68ea7f..1f7bc4c2ec5 100644--- a/install.ps1+++ b/install.ps1@@ -109,6 +109,11 @@ function Install-UnslothStudio {# statement re-assigns unconditionally.$script:UvExe = 'uv'$script:UvInstallDestDir = $null+ # Same reason, and this one caches a decision about the machine: a policy added or+ # removed between two runs in one console, or a replaced launcher under a hash rule,+ # would otherwise be answered from the first run's probe.+ $script:ShimLaunchBlockedCache = $null+ $script:ShimLaunchBlockedPath = $null$script:UnslothVerbose = ($env:UNSLOTH_VERBOSE -eq "1")@@ -1091,22 +1096,349 @@ public static class UnslothStudioFinalPathV2}}+ # ── Managed CLI invocation, Application Control safe ──+ # Windows materializes the `unsloth` console script as a generated, unsigned .exe.+ # AppLocker, WDAC and Smart App Control deny it while the venv's python.exe, a copy+ # of the signed CPython binary, still runs, so setup died at "running unsloth studio+ # setup" (#8490). Everything here goes through the interpreter instead; the console+ # script is still installed and hardlinked, so an unaffected machine sees no change.+ #+ # Byte-identical to WINDOWS_CLI_ENTRYPOINT in studio/src-tauri/src/process.rs. Two+ # halves, both load bearing:+ # argv[0] BEFORE the import, because unsloth_cli/__init__ decides at import time+ # whether it is the console script (UTF-8 streams, the -np<N> rewrite) and typer+ # reads it for the program name in usage text.+ # sys.path[:1] drops the working directory `python -c` adds and a console script+ # does not, so a stray `unsloth_cli` folder cannot shadow the managed package. It+ # is a no-op under -P or PYTHONSAFEPATH. -I would drop it too, but -I implies -E,+ # and discarding PYTHONPATH, PYTHONWARNINGS and user site-packages diverges from+ # the console script on machines with no policy at all.+ # Written into every generated bin\unsloth.cmd and required by every ownership+ # check that accepts one. Mirrored in scripts/uninstall.ps1 and studio/setup.ps1.+ $script:UnslothCmdShimMarker = "unsloth-studio-managed-launcher"+ $script:UnslothCliTrampoline = "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())"++ # Recognize ERROR_ACCESS_DISABLED_BY_POLICY through PowerShell's wrapper exceptions,+ # the same way Test-AccessDeniedError above recognizes ERROR_ACCESS_DENIED.+ # $LASTEXITCODE cannot answer this: no process was created, so it still holds the+ # exit code of whichever native command ran last.+ function Test-ApplicationControlBlock {+ param($ErrorRecord)++ $ex = if ($ErrorRecord -is [System.Management.Automation.ErrorRecord]) { $ErrorRecord.Exception } else { $ErrorRecord }+ while ($ex) {+ # Win32Exception carries NativeErrorCode; outer wrappers keep only the HRESULT+ # form of the same code (0x800704EC).+ if ($ex -is [System.ComponentModel.Win32Exception] -and $ex.NativeErrorCode -eq 1260) { return $true }+ if ($ex.HResult -eq -2147023636) { return $true }+ $ex = $ex.InnerException+ }+ return $false+ }++ # Print guidance; returns the failure reason as its only pipeline output, matching+ # Write-PathAccessDenied. Never suggests turning a security policy off: the fix is+ # for whoever owns the policy, and Unsloth already stopped needing the blocked file.+ function Write-ApplicationControlBlocked {+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)++ Write-StudioLine "[ERROR] Windows Application Control blocked the managed Python runtime." -ForegroundColor Red+ Write-StudioLine " Windows error 1260 (ERROR_ACCESS_DISABLED_BY_POLICY)" -ForegroundColor Yellow+ Write-StudioLine " Blocked program: $Path" -ForegroundColor Yellow+ Write-StudioLine " Ask your administrator to review AppLocker `"EXE and DLL`" event 8004," -ForegroundColor Yellow+ Write-StudioLine " or CodeIntegrity/Operational event 3077." -ForegroundColor Yellow+ return "Windows Application Control blocked the managed Python runtime at $Path (Windows error 1260)."+ }++ # One pre-quoted command line, not an argument array: Start-Process joins+ # -ArgumentList with spaces and quotes nothing, so the trampoline as an array+ # element reaches python as a dozen arguments. It holds no double quote and no+ # backslash, so wrapping it is unambiguous under CommandLineToArgvW.+ function Get-ManagedUnslothCliCommandLine {+ param([string[]]$Arguments = @())++ $quoted = '"' + $script:UnslothCliTrampoline + '"'+ # Callers pass bare subcommands today, but the signature invites a path:+ # unquoted, `--model C:\my models\a.gguf` arrives as three arguments.+ $safeArgs = @($Arguments | ForEach-Object {+ if ($_ -match '\s') { '"' + $_ + '"' } else { $_ }+ })+ return (@("-X", "utf8", "-c", $quoted) + $safeArgs) -join " "+ }++ # Run the managed `unsloth` CLI through the interpreter. The exit code is published+ # in $script:ManagedUnslothCliExit rather than returned, because the child's stdout+ # shares this function's output stream and capturing it would stop the install+ # streaming to the console and the Tauri log. $null means the interpreter never+ # started under Application Control, which is not an exit code.+ function Invoke-ManagedUnslothCli {+ param(+ [Parameter(Mandatory = $true)][string]$Python,+ [string[]]$Arguments = @()+ )++ # -X utf8, not the env var, so the child decodes whatever the console code page+ # is. No -I: it would discard PYTHONPATH and friends, which the console script+ # honors, and the trampoline already drops the -c working-directory entry.+ # Same form as the desktop's build_managed_cli_command.+ $pythonArgs = @("-X", "utf8", "-c", $script:UnslothCliTrampoline) + $Arguments+ $script:ManagedUnslothCliExit = $null+ try {+ # Otherwise a child that exits 0 inherits the last native command's code.+ $global:LASTEXITCODE = 0+ & $Python @pythonArgs+ $script:ManagedUnslothCliExit = [int]$LASTEXITCODE+ } catch {+ # $PSNativeCommandUseErrorActionPreference is off, so a nonzero exit never+ # lands here: anything caught is a failure to create the process at all.+ if (-not (Test-ApplicationControlBlock $_)) { throw }+ }+ }++ # Does Application Control deny this launcher here? Windows cannot be asked without+ # trying: AppLocker's cmdlets need the policy and an admin token, WDAC and Smart App+ # Control expose nothing. A denial is free (CreateProcess fails synchronously, no+ # child, 1260 straight back); an unaffected machine pays one `--version`, measured+ # at a quarter second. A process that started is not blocked whatever it does next,+ # so the timeout path still answers "not blocked" and just stops waiting.+ function Test-ShimLaunchBlocked {+ param([Parameter(Mandatory = $true)][string]$Path)++ if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false }+ # Both the PATH-shadow warning and the launch instructions ask, and the answer+ # cannot change between them.+ if ($null -ne $script:ShimLaunchBlockedCache -and+ $script:ShimLaunchBlockedPath -eq $Path) {+ return $script:ShimLaunchBlockedCache+ }+ $script:ShimLaunchBlockedPath = $Path+ try {+ $psi = New-Object System.Diagnostics.ProcessStartInfo+ $psi.FileName = $Path+ $psi.Arguments = "--version"+ # UseShellExecute = false surfaces a denial as a Win32Exception rather than+ # a shell dialog, and is required before output can be redirected.+ $psi.UseShellExecute = $false+ $psi.CreateNoWindow = $true+ $psi.RedirectStandardOutput = $true+ $psi.RedirectStandardError = $true+ $proc = [System.Diagnostics.Process]::Start($psi)+ try {+ # Drain both pipes BEFORE waiting. With two redirected streams and no+ # reader, a child that fills a pipe buffer blocks writing while we block+ # waiting, and neither side moves. It is reachable here: the trampoline+ # no longer passes -I, so PYTHONPROFILEIMPORTTIME=1 in the environment+ # reaches this child and produces ~24 KB of stderr against a 4 KB buffer.+ # Reading them sequentially would not help, since the child can fill one+ # while we block on the other; async is the only correct answer.+ $stdout = $proc.StandardOutput.ReadToEndAsync()+ $stderr = $proc.StandardError.ReadToEndAsync()+ if ($proc.WaitForExit(20000)) {+ # The timed overload does not wait for the readers to finish; the+ # parameterless one does, and returns at once for an exited process.+ $proc.WaitForExit()+ } else {+ # It started, so it is not blocked, but leaving it running would+ # hold the launcher open against the next update.+ try { $proc.Kill() } catch { }+ }+ # Observed so a faulted read cannot surface later as an unobserved task.+ foreach ($reader in @($stdout, $stderr)) {+ try { $null = $reader.Result } catch { }+ }+ } finally {+ $proc.Dispose()+ }+ $script:ShimLaunchBlockedCache = $false+ return $false+ } catch {+ $script:ShimLaunchBlockedCache = (Test-ApplicationControlBlock $_)+ return $script:ShimLaunchBlockedCache+ }+ }++ # Which launcher should the printed instructions name? The .cmd, when the .exe+ # cannot be used: either a policy denies it, or it is not there at all. The second+ # case is real -- antivirus quarantine takes the unsigned .exe, and the hardlink and+ # its copy fallback can both fail -- and Test-ShimLaunchBlocked answers $false for a+ # missing file, since nothing refused to start it. Naming a path that does not exist+ # is the one outcome worse than naming a blocked one.+ function Test-UnslothCmdShimPreferred {+ param(+ [Parameter(Mandatory = $true)][string]$ShimExe,+ [Parameter(Mandatory = $true)][string]$ShimCmd+ )++ if (-not (Test-Path -LiteralPath $ShimCmd -PathType Leaf)) { return $false }+ if (-not (Test-Path -LiteralPath $ShimExe -PathType Leaf)) { return $true }+ return (Test-ShimLaunchBlocked -Path $ShimExe)+ }++ # Relative path from $From (a directory) to $To, or $null with no common root+ # (different volumes, UNC vs local). Longhand because Path.GetRelativePath is .NET+ # Core only and Uri.MakeRelativeUri percent-encodes the spaces, '#' and '%' that+ # appear in real profile paths.+ function Get-RelativeShimPath {+ param(+ [Parameter(Mandatory = $true)][AllowEmptyString()][string]$From,+ [Parameter(Mandatory = $true)][AllowEmptyString()][string]$To+ )++ if ([string]::IsNullOrWhiteSpace($From) -or [string]::IsNullOrWhiteSpace($To)) { return $null }+ $fromParts = @($From.TrimEnd('\', '/') -split '[\\/]+' | Where-Object { $_ -ne "" })+ $toParts = @($To -split '[\\/]+' | Where-Object { $_ -ne "" })+ if ($fromParts.Count -eq 0 -or $toParts.Count -eq 0) { return $null }+ # Drive letter or share name: no common root means no relative path exists.+ if ($fromParts[0] -ne $toParts[0]) { return $null }+ $shared = 0+ while ($shared -lt $fromParts.Count -and $shared -lt $toParts.Count -and+ $fromParts[$shared] -eq $toParts[$shared]) {+ $shared+++ }+ # Guarded: a PowerShell range whose start passes its end counts DOWN, so+ # $toParts[2..1] returns the path reversed, not the empty tail it reads like.+ if ($shared -ge $toParts.Count) { return $null }+ $up = @("..") * ($fromParts.Count - $shared)+ $down = @($toParts[$shared..($toParts.Count - 1)])+ return (@($up + $down) -join '\')+ }++ # The `unsloth.cmd` companion to the shim .exe. A pure function of the two paths, so+ # a re-run reproduces it byte for byte, and %~dp0 keeps profile paths containing+ # spaces, '$', brackets and apostrophes out of the file. CRLF and ASCII, no BOM:+ # cmd.exe reads a BOM as part of the first command.+ #+ # Scope, stated plainly: this answers EXE-and-DLL enforcement of the unsigned+ # console script, which is issue #8490. A machine that also enforces AppLocker's+ # Script collection denies .cmd and .ps1 alike, and install.ps1 itself would not+ # have run there. The interpreter route is what carries such a machine; the shim+ # is the convenience on top of it.+ function Get-UnslothCmdShimContent {+ param(+ [Parameter(Mandatory = $true)][string]$ShimDir,+ [Parameter(Mandatory = $true)][string]$PythonPath+ )++ $relative = Get-RelativeShimPath -From $ShimDir -To $PythonPath+ $target = if ($relative) { "%~dp0$relative" } else {+ # Different volume: an absolute path is the only option left. '%' is the one+ # character cmd still expands inside double quotes, so double it.+ $PythonPath -replace '%', '%%'+ }+ $lines = @(+ "@echo off",+ "rem Runs the Unsloth CLI through the managed interpreter. The generated",+ "rem unsloth.exe beside it is unsigned, and Windows Application Control",+ "rem denies it on managed machines; this file is the way through.",+ # The ownership marker, and the only reason a .cmd may stand in for the other+ # sentinels. It gates a recursive delete, so it has to be something nobody+ # writes by accident: `from unsloth_cli import app` is a plausible line in+ # anyone's hand-rolled wrapper, this is not.+ "rem $script:UnslothCmdShimMarker",+ # With delayed expansion on (cmd /V:ON, or the machine-wide default) a '!'+ # is eaten out of every argument. exit /b ends the scope, so nothing leaks.+ "setlocal DisableDelayedExpansion",+ "`"$target`" -X utf8 -c `"$script:UnslothCliTrampoline`" %*",+ "@exit /b %errorlevel%"+ )+ return (($lines -join "`r`n") + "`r`n")+ }++ # Write bin\unsloth.cmd, but only when the bytes would change, so a re-run is a+ # no-op. Never fatal: the .exe shim is still the primary launcher and nothing+ # requires this file to exist.+ function Write-UnslothCmdShim {+ param(+ [Parameter(Mandatory = $true)][string]$ShimDir,+ [Parameter(Mandatory = $true)][string]$PythonPath+ )++ # Probes inside the try too: this runs under the venv rollback guard, so a throw+ # here would undo a successful install over an optional launcher.+ $shimCmd = Join-Path $ShimDir "unsloth.cmd"+ try {+ if (Test-Path -LiteralPath $shimCmd -PathType Container) {+ substep "cannot write $shimCmd, a directory is in the way" "Yellow"+ return+ }+ # A run killed between the write and the rename leaves its temp file behind,+ # and the next run has a different PID and would never look at it. Swept+ # before the unchanged-content return below, which is the path an interrupted+ # install takes on its way out. Only this file's own temps, only ones no+ # live process is still writing.+ Get-ChildItem -LiteralPath $ShimDir -Filter "unsloth.cmd.*.tmp" -File `+ -ErrorAction SilentlyContinue | ForEach-Object {+ $ownerPid = 0+ if ([int]::TryParse(($_.Name -replace '^unsloth\.cmd\.', '' -replace '\.tmp$', ''),+ [ref]$ownerPid) -and $ownerPid -eq $PID) { return }+ if ($ownerPid -gt 0 -and (Get-Process -Id $ownerPid -ErrorAction SilentlyContinue)) { return }+ Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue+ }+ $content = Get-UnslothCmdShimContent -ShimDir $ShimDir -PythonPath $PythonPath+ $desired = (New-Object System.Text.UTF8Encoding($false)).GetBytes($content)+ # Bytes, not ReadAllText: that strips a BOM before comparing and PowerShell's+ # -eq is case insensitive, so a BOM-prefixed file (which cmd.exe reads as part+ # of the first command) would be declared unchanged and left broken forever.+ if (Test-Path -LiteralPath $shimCmd -PathType Leaf) {+ $existing = [System.IO.File]::ReadAllBytes($shimCmd)+ if (@(Compare-Object $existing $desired -SyncWindow 0).Count -eq 0) { return }+ # This directory is the installer's own, so the file is replaced either+ # way, but a file that carries neither our marker nor our trampoline was+ # written by something else and its owner deserves to read that it went.+ if (-not (Test-UnslothCmdShimFile -Path $shimCmd)) {+ substep "replacing an unrecognised $shimCmd" "Yellow"+ }+ }+ # Publish by rename so a shell reading it mid-install never sees half a file.+ $tmp = "$shimCmd.$PID.tmp"+ [System.IO.File]::WriteAllBytes($tmp, $desired)+ try {+ Move-Item -LiteralPath $tmp -Destination $shimCmd -Force -ErrorAction Stop+ } finally {+ Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue+ }+ } catch {+ substep "could not write $shimCmd`: $($_.Exception.Message)" "Yellow"+ }+ }++ # Is this bin\unsloth.cmd one we wrote? The name alone is a plausible wrapper for+ # anything built on unsloth, and callers use the answer to decide whether a+ # user-chosen directory may be deleted. Mirrored in scripts/uninstall.ps1+ # (_IsUnslothCmdShim) and studio/setup.ps1.+ function Test-UnslothCmdShimFile {+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)++ if ([string]::IsNullOrWhiteSpace($Path)) { return $false }+ if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false }+ try {+ if ((Get-Item -LiteralPath $Path -ErrorAction Stop).Length -gt 8192) { return $false }+ $text = [System.IO.File]::ReadAllText($Path)+ } catch {+ # Unreadable proves nothing, and "proves nothing" must not mean "deletable".+ return $false+ }+ return ($text -like "*unsloth-studio-managed-launcher*" -and $text -like "*from unsloth_cli import app*")+ }+function New-StudioShortcuts {param(- [Parameter(Mandatory = $true)][string]$UnslothExePath+ [Parameter(Mandatory = $true)][string]$ManagedPythonPath)- if (-not (Test-Path -LiteralPath $UnslothExePath)) {- substep "cannot create shortcuts, unsloth.exe not found at $UnslothExePath" "Yellow"+ if (-not (Test-Path -LiteralPath $ManagedPythonPath)) {+ substep "cannot create shortcuts, managed Python not found at $ManagedPythonPath" "Yellow"return}try {# Persist an absolute path in launcher scripts so shortcut working# directory changes do not break process startup.- $UnslothExePath = (Resolve-Path -LiteralPath $UnslothExePath).Path+ $ManagedPythonPath = (Resolve-Path -LiteralPath $ManagedPythonPath).Path# Escape for single-quoted embedding in generated launcher script.# This prevents runtime variable expansion for paths containing '$'.- $SingleQuotedExePath = $UnslothExePath -replace "'", "''"+ $SingleQuotedPythonPath = $ManagedPythonPath -replace "'", "''"+ # Same escaping for the trampoline: it contains apostrophes of its own.+ $SingleQuotedTrampoline = $script:UnslothCliTrampoline -replace "'", "''"# $StudioDataDir = LOCALAPPDATA\Unsloth Studio, or $StudioHome\share in env-mode.if (-not $StudioDataDir -or [string]::IsNullOrWhiteSpace($StudioDataDir)) {@@ -1344,7 +1676,10 @@ try {}`$powershellExe = Join-Path `$env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'- `$studioExe = '$SingleQuotedExePath'+ # The managed interpreter, not the generated unsloth.exe console script: that one is+ # unsigned and Application Control denies it on managed machines (#8490).+ `$studioPython = '$SingleQuotedPythonPath'+ `$studioEntry = '$SingleQuotedTrampoline'`$launchPort = Find-FreeLaunchPortif (-not `$launchPort) {`$msg = "No free port found in range `$basePort-`$(`$basePort + `$maxPortOffset)"@@ -1356,7 +1691,10 @@ try {}# Single-quote the path in the child -Command so `$` / backtick in custom# roots don't get reparsed; double any apostrophes so 'O''Brien' survives.- `$studioCommand = "& '" + (`$studioExe -replace "'", "''") + "' studio -p " + `$launchPort+ # The entry point is single-quoted for the same reason: it carries apostrophes+ # around 'unsloth', and unquoted they would end the string mid-expression.+ `$studioCommand = "& '" + (`$studioPython -replace "'", "''") + "' -X utf8 -c '" ++ (`$studioEntry -replace "'", "''") + "' studio -p " + `$launchPort# RemoteSigned, not Bypass: the child runs an inline -Command against an executable, so no# script file is loaded and the two behave identically here. No reason to spend a scored# token on a launch that needs no policy relief.@@ -1416,16 +1754,45 @@ exit 0# Write UTF-8 with BOM for reliable decoding by Windows PowerShell 5.1,# even when install.ps1 is executed from PowerShell 7.+ #+ # Content-compared first, like the .cmd shim: the launcher is regenerated by+ # every reinstall and by every `unsloth studio update` (--shortcuts-only),+ # and rewriting identical bytes moves its timestamp for no reason. A re-run+ # has to be a true no-op on disk.$utf8Bom = New-Object System.Text.UTF8Encoding($true)- [System.IO.File]::WriteAllText($launcherPs1, $launcherContent, $utf8Bom)- # WriteAllText replaces the unnamed data stream and leaves any other NTFS stream on+ # Bytes including the BOM, not ReadAllText: that decodes and discards the+ # preamble, so a BOM-less launcher written by an older installer would be+ # called unchanged and never gain the BOM 5.1 needs to decode it.+ $desiredLauncher = $utf8Bom.GetPreamble() + $utf8Bom.GetBytes($launcherContent)+ $launcherUnchanged = $false+ if (Test-Path -LiteralPath $launcherPs1 -PathType Leaf) {+ try {+ $existingLauncher = [System.IO.File]::ReadAllBytes($launcherPs1)+ $launcherUnchanged =+ (@(Compare-Object $existingLauncher $desiredLauncher -SyncWindow 0).Count -eq 0)+ } catch {+ # Unreadable is not "unchanged"; fall through and rewrite it.+ $launcherUnchanged = $false+ }+ }+ if (-not $launcherUnchanged) {+ [System.IO.File]::WriteAllBytes($launcherPs1, $desiredLauncher)+ }+ # WriteAllBytes replaces the unnamed data stream and leaves any other NTFS stream on# an existing file alone, so a launcher that somehow acquired a mark of the web keeps# it across the rewrite. The shortcut loads this under RemoteSigned, which refuses a# marked unsigned script, so clear the mark on the file we just authored. A no-op on# every ordinary install, where the stream was never there.- # -Confirm:$false: Unblock-File is SupportsShouldProcess at Medium impact, so a- # profile lowering $ConfirmPreference would prompt here, and ErrorAction does not- # suppress a ShouldProcess prompt. On a noninteractive host that skips shortcut setup.+ #+ # Outside the content check on purpose: a launcher whose bytes already match still+ # has to lose the mark, and clearing an absent stream neither writes nor restamps+ # the file, so an unchanged re-run stays a no-op on disk either way.+ #+ # -Confirm:$false: Unblock-File declares SupportsShouldProcess at the default+ # Medium impact, so a profile setting $ConfirmPreference to Medium or Low would+ # prompt here, even for a launcher that never had the stream. ErrorAction does+ # not suppress a ShouldProcess prompt, and a noninteractive host turns it into+ # an error that skips shortcut setup entirely.Unblock-File -LiteralPath $launcherPs1 -Confirm:$false -ErrorAction SilentlyContinue# No .vbs launcher is written. A WScript.Shell .vbs that spawns a hidden# ExecutionPolicy-Bypass PowerShell is exactly the shape VBS-dropper@@ -1551,20 +1918,35 @@ exit 0$wshell = New-Object -ComObject WScript.Shell$createdShortcutCount = 0$createdShortcutPaths = @()+ $desiredIconLocation = if ($hasValidIcon) { "$iconPath,0" } else { $null }foreach ($linkPath in @($desktopLink, $startMenuLink)) {if (-not $linkPath -or [string]::IsNullOrWhiteSpace($linkPath)) { continue }try {$shortcut = $wshell.CreateShortcut($linkPath)- $shortcut.TargetPath = $shortcutTarget- $shortcut.Arguments = $shortcutArgs- $shortcut.WorkingDirectory = $appDir- # Start minimized so the brief PowerShell console flash is muted.- $shortcut.WindowStyle = 7- $shortcut.Description = "Launch Unsloth Studio"- if ($hasValidIcon) {- $shortcut.IconLocation = "$iconPath,0"+ # CreateShortcut returns an existing .lnk populated, so the+ # incumbent's fields are readable before anything is assigned.+ # Save() rewrites even when every field matches, moving the+ # timestamp on a no-op reinstall. IconLocation carries the ",0"+ # index back, so compare against the string we would set.+ $shortcutUnchanged = (Test-Path -LiteralPath $linkPath -PathType Leaf) -and+ ($shortcut.TargetPath -eq $shortcutTarget) -and+ ($shortcut.Arguments -eq $shortcutArgs) -and+ ($shortcut.WorkingDirectory -eq $appDir) -and+ ($shortcut.WindowStyle -eq 7) -and+ ($shortcut.Description -eq "Launch Unsloth Studio") -and+ ((-not $desiredIconLocation) -or ($shortcut.IconLocation -eq $desiredIconLocation))+ if (-not $shortcutUnchanged) {+ $shortcut.TargetPath = $shortcutTarget+ $shortcut.Arguments = $shortcutArgs+ $shortcut.WorkingDirectory = $appDir+ # Start minimized so the brief PowerShell console flash is muted.+ $shortcut.WindowStyle = 7+ $shortcut.Description = "Launch Unsloth Studio"+ if ($hasValidIcon) {+ $shortcut.IconLocation = $desiredIconLocation+ }+ $shortcut.Save()}- $shortcut.Save()$createdShortcutCount++$createdShortcutPaths += $linkPath} catch {@@ -1628,13 +2010,45 @@ exit 0# Regen .lnk + launcher only; used by `unsloth studio update`.if ($ShortcutsOnly) {if ($TauriMode) { return }- $UnslothExe = Join-Path $VenvDir "Scripts\unsloth.exe"- if (-not (Test-Path -LiteralPath $UnslothExe)) {- Write-StudioLine "[ERROR] unsloth.exe missing at $UnslothExe; run install.ps1 first." -ForegroundColor Red+ # The launcher runs the interpreter, so that is what has to be there. Checking+ # unsloth.exe instead would refuse to regenerate shortcuts on exactly the+ # machines that need them, where the console script is present but denied.+ $ShortcutPython = Join-Path $VenvDir "Scripts\python.exe"+ if (-not (Test-Path -LiteralPath $ShortcutPython)) {+ Write-StudioLine "[ERROR] managed Python missing at $ShortcutPython; run install.ps1 first." -ForegroundColor Red# throw (not Exit-InstallFailure) so non-Tauri callers see rc != 0.- throw "unsloth.exe missing"+ throw "managed Python missing"+ }+ # `unsloth studio update` reaches the installer only through here, so without+ # this an install predating the .cmd never gets one -- and that population is+ # exactly the one that needs the escape hatch.+ # No-op when the bytes already match, and never fatal.+ # Created, not required: installers older than the shim directory never made+ # one, and those are precisely the installs that reach this branch through+ # `unsloth studio update` and never see the full installer again. Requiring+ # it here left them without the escape hatch forever. Directory creation is+ # idempotent, and a failure to create it must not fail an update, so the+ # write stays inside the same non-fatal helper.+ $ShortcutShimDir = Join-Path $StudioHome "bin"+ try {+ [System.IO.Directory]::CreateDirectory($ShortcutShimDir) | Out-Null+ } catch {+ substep "could not create $ShortcutShimDir`: $($_.Exception.Message)" "Yellow"+ }+ if (Test-Path -LiteralPath $ShortcutShimDir -PathType Container) {+ Write-UnslothCmdShim -ShimDir $ShortcutShimDir -PythonPath $ShortcutPython+ # An installer older than the shim directory put the venv's Scripts dir on+ # PATH instead, so the .cmd we just wrote would sit somewhere nothing looks.+ # Add-ToUserPath is idempotent and a no-op for every modern install, so this+ # only moves a machine that update is the sole route back into the installer+ # for. Env mode never writes the registry.+ if ($StudioRedirectMode -ne 'env') {+ if (Add-ToUserPath -Directory $ShortcutShimDir -Position 'Prepend') {+ substep "added $ShortcutShimDir to PATH"+ }+ }}- New-StudioShortcuts -UnslothExePath $UnslothExe+ New-StudioShortcuts -ManagedPythonPath $ShortcutPythonreturn}@@ -3060,11 +3474,15 @@ exit 0# existing $StudioHome\unsloth_studio that lacks Unsloth sentinels.# -PathType Leaf rejects a directory at the sentinel path. Accept the# in-VENV ownership marker so partial-install retries are not blocked.+ # The .cmd counts too, and for the same reason the uninstaller accepts it: a+ # policy's quarantine can take the unsigned .exe and leave a root that is still+ # ours. Content-checked, never by name -- this guard gates a recursive delete.if ($StudioRedirectMode -eq 'env' -and-not (Test-Path -LiteralPath (Join-Path $VenvDir ".unsloth-studio-owned") -PathType Leaf) -and-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)+ -not (Test-Path -LiteralPath (Join-Path $StudioHome "bin\unsloth.exe") -PathType Leaf) -and+ -not (Test-UnslothCmdShimFile (Join-Path $StudioHome "bin\unsloth.cmd"))) {Write-StudioLine "[ERROR] $VenvDir already exists but does not look like an Unsloth Studio install." -ForegroundColor RedWrite-StudioLine " Move it aside or choose an empty UNSLOTH_STUDIO_HOME." -ForegroundColor Yellow@@ -4851,7 +5269,7 @@ exit 0# PyPI, the consumer path, so everything Python-side (studio/setup.ps1,# install_python_stack.py and every requirements/constraints file they reach via# Path(__file__)) would be the released wheel's and a branch could not be- # validated. `& $UnslothExe studio setup` below goes through the CLI, and an+ # validated. The `studio setup` handoff below goes through the CLI, and an# editable overlay makes _PACKAGE_ROOT in unsloth_cli/commands/studio.py resolve to# the working tree by PEP 660 __file__, so setup.ps1 comes from this ref. NOT# --local: that also installs `unsloth-zoo @ git+https://...`, which genuinely needs@@ -4878,14 +5296,42 @@ exit 0# never touches the system Node/npm.Write-TauriLog "STEP" "Running studio setup"step "setup" "running unsloth studio setup..."+ # Tested, never executed: pip generates the console script whatever the policy says+ # about running it, so it stays the cheapest "this wheel shipped the CLI" signal.+ #+ # Cheapest, but no longer required. A policy DENIES this file and leaves it on disk,+ # so it answers there, but antivirus QUARANTINES it, deleting it out of a venv that+ # is otherwise perfectly able to run. Nothing after this point executes it -- the+ # setup handoff, the shortcuts and bin\unsloth.cmd all go through $VenvPython -- so+ # failing here would refuse to install or repair Studio for exactly the machines+ # this change is for. Ask the interpreter instead, and only then give up.$UnslothExe = Join-Path $VenvDir "Scripts\unsloth.exe"if (-not (Test-Path -LiteralPath $UnslothExe)) {- Write-TauriLog "ERROR" "unsloth CLI was not installed correctly"- 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")+ $cliImportable = $false+ if (Test-Path -LiteralPath $VenvPython) {+ # The trampoline's own import, so this answers for what actually launches.+ Invoke-ManagedUnslothCli -Python $VenvPython -Arguments @("--version")+ $cliImportable = ($script:ManagedUnslothCliExit -eq 0)+ }+ if ($cliImportable) {+ substep "the generated unsloth.exe is gone (antivirus quarantine); the managed CLI still runs." "Yellow"+ } else {+ Write-TauriLog "ERROR" "unsloth CLI was not installed correctly"+ 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")+ }+ }+ # This is the file the handoff actually starts, so it gets its own check rather+ # than being discovered as a launch failure halfway through setup.+ if (-not (Test-Path -LiteralPath $VenvPython)) {+ Write-TauriLog "ERROR" "managed Python is missing"+ Write-StudioLine "[ERROR] The managed Python interpreter is missing." -ForegroundColor Red+ Write-StudioLine " Expected: $VenvPython" -ForegroundColor Yellow+ Write-StudioLine " Re-run the installer to rebuild the environment." -ForegroundColor Yellow+ return (Exit-InstallFailure "managed Python is missing at $VenvPython")}# Tell setup.ps1 to skip base package installation (install.ps1 already did it)$env:SKIP_STUDIO_BASE = "1"@@ -4974,8 +5420,8 @@ exit 0Remove-Item Env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF -ErrorAction SilentlyContinue}try {- & $UnslothExe @studioArgs- $setupExit = $LASTEXITCODE+ Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs+ $setupExit = $script:ManagedUnslothCliExit} finally {if ($hadPreviousUnslothStudioHome) {$env:UNSLOTH_STUDIO_HOME = $previousUnslothStudioHome@@ -5009,6 +5455,12 @@ exit 0Remove-Item Env:UNSLOTH_INSTALL_ROLLBACK_MANAGED -ErrorAction SilentlyContinueRemove-Item Env:UNSLOTH_SETUP_PYTHON -ErrorAction SilentlyContinue}+ # $null, not a code: Application Control refused to create the process, so there is+ # no exit code to report. Checked first because in PowerShell $null -ne 0 is true,+ # and the branch below would print "exit code " with nothing after it.+ if ($null -eq $setupExit) {+ return (Exit-InstallFailure (Write-ApplicationControlBlocked -Path $VenvPython))+ }if ($setupExit -ne 0) {if (-not $TauriMode) {Write-StudioLine "[ERROR] unsloth studio setup failed (exit code $setupExit)" -ForegroundColor Red@@ -5087,13 +5539,30 @@ exit 0} else {Write-StudioLine "[WARN] Could not create unsloth launcher at $ShimExe" -ForegroundColor YellowWrite-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,- # no registry change (workspace path may be deleted later).+ # The interpreter, not $UnslothExe: this arm is reached on machines whose+ # policy denies the generated console script, where that advice cannot work.+ Write-StudioLine " Until the next successful install, start Studio with:" -ForegroundColor Yellow+ Write-StudioLine " & '$VenvPython' -I -m unsloth_cli studio -p 8888" -ForegroundColor Yellow+ }+ }+ # Companion launcher for machines whose policy denies the generated .exe. PATHEXT+ # resolves .EXE ahead of .CMD, so bare `unsloth` still picks the .exe wherever it+ # runs; where it is denied, `unsloth.cmd` is what the user has left.+ Write-UnslothCmdShim -ShimDir $ShimDir -PythonPath $VenvPython++ # Add to PATH only when a launcher exists. Either one counts: if the .exe could not+ # be hardlinked or copied, or a policy's quarantine removed it, the .cmd beside it+ # is a working launcher and its directory still belongs on PATH. Env-mode:+ # session-only export, no registry change (workspace path may be deleted later).+ # Test-UnslothCmdShimFile, not Test-Path: Write-UnslothCmdShim warns and leaves an+ # unwritable file alone, so a foreign bin\unsloth.cmd in a custom root can survive+ # this run. Counting it would put its directory on PATH and advertise someone+ # else's command as the policy-safe launcher.+ $ShimCmd = Join-Path $ShimDir "unsloth.cmd"+ $ShimUsable = (Test-Path -LiteralPath $ShimExe -PathType Leaf) -or+ (Test-UnslothCmdShimFile -Path $ShimCmd)$pathAdded = $false- if (Test-Path -LiteralPath $ShimExe) {+ if ($ShimUsable) {if ($StudioRedirectMode -ne 'env') {$pathAdded = Add-ToUserPath -Directory $ShimDir -Position 'Prepend'}@@ -5113,7 +5582,7 @@ exit 0# Env-mode session export AFTER Refresh-SessionPath; otherwise a legacy# User PATH entry (Machine > User > current $env:Path) would win.- if ($StudioRedirectMode -eq 'env' -and (Test-Path -LiteralPath $ShimExe)) {+ if ($StudioRedirectMode -eq 'env' -and $ShimUsable) {$env:Path = "$ShimDir;$env:Path"step "path" "exported $ShimDir for this session (no registry PATH change in env-override mode)"}@@ -5125,7 +5594,7 @@ exit 0}# New-StudioShortcuts gates the .lnk shortcuts on env-mode internally.- New-StudioShortcuts -UnslothExePath $UnslothExe+ New-StudioShortcuts -ManagedPythonPath $VenvPython# Warn if another 'unsloth' wins on PATH (different venv, system pip).# Mirrors install.sh; absolute path is still the most reliable launch.@@ -5137,9 +5606,15 @@ exit 0$_pathCmd = Get-Command unsloth -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1if ($_pathCmd) {$_pathExe = $_pathCmd.Source+ # This installer's own unsloth.cmd is not a foreign 'unsloth'. It only wins+ # when the .exe beside it is gone, and hashing it against a PE would always+ # differ and always warn.+ $_ourCmdShim = Join-Path $ShimDir "unsloth.cmd"+ $_isOurCmdShim = $_pathExe -and+ ($_pathExe.TrimEnd('\', '/') -ieq $_ourCmdShim.TrimEnd('\', '/'))$_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)) {+ if ((-not $_isOurCmdShim) -and $_installedHash -and $_pathHash -and ($_installedHash -ne $_pathHash)) {Write-StudioLine ""step "warning" "another 'unsloth' wins on PATH:" "Yellow"substep $_pathExe@@ -5147,6 +5622,11 @@ exit 0substep $UnslothExesubstep "to use this install, call the absolute path above,"substep "or put its dir earlier on PATH."+ # That absolute path is the generated console script, which is exactly+ # what an Application Control policy denies; name the launcher that works.+ if (Test-ShimLaunchBlocked -Path $ShimExe) {+ substep "(Windows blocks that file here; use $_ourCmdShim instead)"+ }Write-StudioLine ""}}@@ -5167,8 +5647,11 @@ exit 0$_runtimeGateHandoff = $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFFtry {$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"- $studioAutoStartProcess = Start-Process -FilePath $UnslothExe `- -ArgumentList @("studio", "-p", "8888") `+ # Through the interpreter, not the generated console script: the+ # autostart must not be the one step an Application Control policy+ # can still refuse after a clean install.+ $studioAutoStartProcess = Start-Process -FilePath $VenvPython `+ -ArgumentList (Get-ManagedUnslothCliCommandLine -Arguments @("studio", "-p", "8888")) `-NoNewWindow -PassThru} finally {if ($null -eq $_runtimeGateHandoff) {@@ -5179,7 +5662,16 @@ exit 0}} else {step "launch" "to start later, run:"- substep "unsloth studio -p 8888"+ # PATHEXT resolves .EXE before .CMD, so bare `unsloth` picks the generated+ # console script, which a denying machine cannot run. Probed, not assumed:+ # an unaffected machine must see the line it has always seen.+ if (Test-UnslothCmdShimPreferred -ShimExe $ShimExe -ShimCmd $ShimCmd) {+ substep "unsloth.cmd studio -p 8888"+ substep "(the generated unsloth.exe is not usable on this machine;"+ substep " unsloth.cmd beside it runs the same CLI through the managed Python)"+ } else {+ 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-StudioLine ""@@ -5189,17 +5681,29 @@ exit 0# Single-quote the printed paths so $-vars / backticks in custom roots# do not reparse when the user pastes the command.$_actLiteral = "'" + ((Join-Path $VenvDir "Scripts\Activate.ps1") -replace "'", "''") + "'"+ # Activating the venv puts Scripts\unsloth.exe first and PATHEXT prefers .EXE,+ # so every bare `unsloth` below is unusable where the policy denies it. Same+ # probe, same reason: unaffected machines must see unchanged text.+ $_shimBlocked = Test-UnslothCmdShimPreferred -ShimExe $ShimExe -ShimCmd $ShimCmd+ $_bareLaunch = if ($_shimBlocked) { "unsloth.cmd studio -p 8888" } else { "unsloth studio -p 8888" }if ($StudioRedirectMode -eq 'env') {- # Env-mode skips registry PATH; print the absolute shim path.- $_shim = Join-Path $StudioHome "bin\unsloth.exe"+ # Env-mode skips registry PATH; print the absolute shim path. The .cmd+ # beside it goes through the interpreter, so it is the one that works where+ # the policy denies the generated .exe -- named only when it is needed.+ $_shimLeaf = if ($_shimBlocked) { "bin\unsloth.cmd" } else { "bin\unsloth.exe" }+ $_shim = Join-Path $StudioHome $_shimLeaf$_shimLiteral = "'" + ($_shim -replace "'", "''") + "'"substep "& $_shimLiteral studio -p 8888"substep "or activate env first:"substep "& $_actLiteral"- substep "unsloth studio -p 8888"+ substep $_bareLaunch} else {substep "& $_actLiteral"- substep "unsloth studio -p 8888"+ substep $_bareLaunch+ }+ if ($_shimBlocked) {+ substep "(the generated unsloth.exe is not usable on this machine;"+ substep " unsloth.cmd runs the same CLI through the managed Python)"}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)"diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1index 57d5d7328c9..13f969300fe 100644--- a/scripts/uninstall.ps1+++ b/scripts/uninstall.ps1@@ -183,15 +183,43 @@ Environment:}}+ # Is this bin\unsloth.cmd the launcher install.ps1 wrote, or just a file with that+ # name? The distinction decides whether a directory gets deleted recursively, so a+ # name alone is not enough -- `unsloth.cmd` is a plausible wrapper for anyone who+ # ships an unsloth-based tool, and pointing UNSLOTH_STUDIO_HOME at such a project+ # must not hand its whole tree to _RemovePath.+ #+ # The trampoline is the marker: install.ps1 bakes that exact expression into the+ # shim, no other file has a reason to carry it, and it survives every layout the+ # shim has (relative %~dp0 or an absolute cross-volume path, unsloth_studio or the+ # legacy .venv). Bounded read: the real shim is a few hundred bytes.+ function _IsUnslothCmdShim {+ param([string]$Path)+ if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false }+ try {+ $item = Get-Item -LiteralPath $Path -ErrorAction Stop+ if ($item.Length -gt 8192) { return $false }+ $text = [System.IO.File]::ReadAllText($Path)+ } catch {+ # Unreadable proves nothing, and "proves nothing" must not mean "delete it".+ return $false+ }+ return ($text -like "*unsloth-studio-managed-launcher*" -and $text -like "*from unsloth_cli import app*")+ }+# A path is an Unsloth-owned root iff one of install.ps1's sentinels exists:# <root>\share\studio.conf, <root>\unsloth_studio\.unsloth-studio-owned,- # or <root>\bin\unsloth.exe.+ # <root>\bin\unsloth.exe, or a <root>\bin\unsloth.cmd this installer wrote.+ # The .cmd is the interpreter-based launcher install.ps1 writes beside the .exe for+ # machines whose Application Control policy denies the generated console script. An+ # install whose .exe was removed by that policy's quarantine still owns its root.function _IsStudioRoot {param([string]$Path)if ([string]::IsNullOrWhiteSpace($Path)) { return $false }if (Test-Path -LiteralPath (Join-Path $Path "share\studio.conf") -PathType Leaf) { return $true }if (Test-Path -LiteralPath (Join-Path $Path "unsloth_studio\.unsloth-studio-owned") -PathType Leaf) { return $true }if (Test-Path -LiteralPath (Join-Path $Path "bin\unsloth.exe") -PathType Leaf) { return $true }+ if (_IsUnslothCmdShim (Join-Path $Path "bin\unsloth.cmd")) { return $true }return $false}diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.pyindex 73e6a78cbb0..e630272aded 100644--- a/studio/backend/routes/auth.py+++ b/studio/backend/routes/auth.py@@ -6,6 +6,7 @@from fastapi import APIRouter, Depends, HTTPException, Request, Response, statusimport base64+import importlib.utilimport ipaddressimport osimport shlex@@ -14,6 +15,7 @@ import threadingimport timefrom collections import dequefrom datetime import datetime, timedelta, timezone+from pathlib import Pathfrom models.auth import (ApiKeyListResponse,@@ -42,6 +44,33 @@ from auth.authentication import (router = APIRouter()+# Byte-identical to _WINDOWS_CLI_ENTRYPOINT in unsloth_cli/commands/studio.py and to+# the bootstrap unsloth_cli/__main__.py documents for user-site installs.+_CLI_BOOTSTRAP = (+ "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "+ "sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())"+)+++def _cli_is_inside(prefix: str) -> bool:+ """Whether unsloth_cli lives under *prefix*, so -I would still find it.++ Located rather than imported: this runs in a request handler, and a spec+ lookup answers the only question asked here, which is where the package is+ on disk and not whether it starts.+ """+ try:+ spec = importlib.util.find_spec("unsloth_cli")+ origin = getattr(spec, "origin", None)+ if not origin:+ # A namespace package, or nothing found. Either way there is no+ # location to compare, so do not claim isolation would work.+ return False+ return Path(origin).resolve().is_relative_to(Path(prefix).resolve())+ except (ImportError, OSError, ValueError, AttributeError):+ return False++def _reset_password_command() -> str:"""Shell command shown in the 'incorrect password' hint.@@ -51,19 +80,42 @@ def _reset_password_command() -> str:POSIX paths are shell-quoted. On Windows we use the bare absolute path onlywhen it has no spaces (a quoted path differs between cmd and PowerShell);otherwise, or if the launcher can't be located, fall back to the PATH form.++ Windows never names unsloth.exe here, present or not. Existing is not the+ same as runnable: an Application Control policy leaves the generated,+ unsigned unsloth.exe on disk and denies it at CreateProcess (issue #8490),+ and a bare `unsloth` resolves to that same file because PATHEXT puts .EXE+ ahead of the .cmd shim. Whoever is locked out of Studio is exactly who needs+ this command to work, so it must not be the one a policy refuses. Preference+ order is therefore the interpreter's module entry, which needs no quoting in+ cmd or PowerShell, then `unsloth.cmd` -- spelling the extension is what stops+ PATHEXT reaching for the executable.++ -I only when the package is inside this interpreter's own prefix. -I implies+ -s, so a ``pip install --user`` install would be told to run a command that+ cannot find itself; unsloth_cli/__main__.py documents that exception and the+ bootstrap to use instead, and this prints that bootstrap. It is safe to show+ to either shell: the trampoline contains single quotes only, so one pair of+ double quotes wraps it identically in cmd and in PowerShell."""try:bin_dir = os.path.dirname(os.path.abspath(sys.executable))if os.name == "nt":- exe = os.path.join(bin_dir, "unsloth.exe")- if os.path.isfile(exe) and " " not in exe:- return f"{exe} studio reset-password"+ python = os.path.abspath(sys.executable)+ if " " not in python:+ if _cli_is_inside(sys.prefix):+ return f"{python} -I -m unsloth_cli studio reset-password"+ return f'{python} -X utf8 -c "{_CLI_BOOTSTRAP}" studio reset-password'+ # A spaced interpreter path cannot be written unquoted, so fall+ # through to the PATH form below.else:exe = os.path.join(bin_dir, "unsloth")if os.path.isfile(exe):return f"{shlex.quote(exe)} studio reset-password"except Exception:pass+ if os.name == "nt":+ return "unsloth.cmd studio reset-password"return "unsloth studio reset-password"diff --git a/studio/backend/run.py b/studio/backend/run.pyindex 47aa01c6f29..760b4d3e077 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -2432,7 +2432,15 @@ def run_server("\n""Fix one of:\n"f" - run the installer's binary directly: {installer_bin} studio\n"- " - pass --frontend <path/to/studio/frontend/dist>\n"+ + (+ # An Application Control policy can block the generated+ # unsloth.exe while the signed interpreter beside it still+ # runs, so name a route that does not go through it.+ f" - or through the interpreter: {sys.executable} -I -m unsloth_cli studio\n"+ if sys.platform == "win32"+ else ""+ )+ + " - pass --frontend <path/to/studio/frontend/dist>\n"" - pass --api-only to skip serving the web UI\n"" - reinstall: curl -fsSL https://unsloth.ai/install.sh | sh")diff --git a/studio/backend/tests/test_reset_password_command.py b/studio/backend/tests/test_reset_password_command.pynew file mode 100644index 00000000000..961d4dfd645--- /dev/null+++ b/studio/backend/tests/test_reset_password_command.py@@ -0,0 +1,149 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The command a locked-out user is told to run has to run.++It is printed exactly when someone cannot get into Studio, so every way of+being wrong here is a way of stranding them: naming the executable a policy+denies (issue #8490), or naming an isolated module route that cannot see the+site its own package lives in.+"""++from __future__ import annotations++import ast+import importlib.util+import sys+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parents[1]+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++[email protected](scope = "module")+def auth():+ """routes/auth.py by path, as test_desktop_auth.py loads it.++ `from routes import auth` runs routes/__init__.py, which imports the whole+ router set and with it structlog, so the module under test would be+ unreachable wherever the full backend stack is not installed.+ """+ route_path = _BACKEND / "routes" / "auth.py"+ spec = importlib.util.spec_from_file_location("_reset_command_auth_route", route_path)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def windows(monkeypatch, auth):+ monkeypatch.setattr(auth.os, "name", "nt")+++def test_a_venv_install_gets_the_isolated_module_route(auth, monkeypatch, windows):+ """-I is right when the package is inside the interpreter's own prefix.++ It drops the working directory from sys.path, so a shell sitting in a+ directory that happens to hold an unsloth_cli folder cannot shadow the+ managed one.+ """+ monkeypatch.setattr(+ auth.sys, "executable", r"C:\Users\dan\.unsloth\studio\unsloth_studio\Scripts\python.exe"+ )+ monkeypatch.setattr(auth, "_cli_is_inside", lambda _prefix: True)++ command = auth._reset_password_command()++ assert command.endswith("-I -m unsloth_cli studio reset-password")+ assert "unsloth.exe" not in command+++def test_a_user_site_install_is_not_told_to_isolate_itself(auth, monkeypatch, windows):+ """-I implies -s, which hides the user site the package is installed in.++ A `pip install --user` install told to run that command gets+ `No module named unsloth_cli`, which is worse than useless to someone who is+ already locked out.+ """+ monkeypatch.setattr(auth.sys, "executable", r"C:\Python313\python.exe")+ monkeypatch.setattr(auth, "_cli_is_inside", lambda _prefix: False)++ command = auth._reset_password_command()++ assert " -I " not in command+ assert "-m unsloth_cli" not in command+ # The bootstrap unsloth_cli/__main__.py documents for exactly this case.+ assert auth._CLI_BOOTSTRAP in command+ assert command.endswith(" studio reset-password")+ # One pair of double quotes wraps it for cmd and PowerShell alike, which+ # only holds while the bootstrap itself carries no double quote.+ assert '"' not in auth._CLI_BOOTSTRAP+ assert command.count('"') == 2+ assert "unsloth.exe" not in command+++def test_the_bootstrap_matches_the_one_the_cli_uses(auth):+ """Three copies of this string, and a drift changes argv[0] handling.++ Read from the CLI's own source rather than imported, since the backend may+ be running from a venv that has a different unsloth on it, and via AST+ because the constant there is written as adjacent literals.+ """+ repo_root = _BACKEND.parents[1]+ studio_py = (repo_root / "unsloth_cli" / "commands" / "studio.py").read_text(encoding = "utf-8")+ canonical = None+ for node in ast.walk(ast.parse(studio_py)):+ if isinstance(node, ast.Assign) and any(+ isinstance(target, ast.Name) and target.id == "_WINDOWS_CLI_ENTRYPOINT"+ for target in node.targets+ ):+ canonical = ast.literal_eval(node.value)+ assert canonical, "_WINDOWS_CLI_ENTRYPOINT is gone from unsloth_cli/commands/studio.py"+ assert auth._CLI_BOOTSTRAP == canonical+++def test_a_spaced_interpreter_path_still_falls_through_to_the_cmd_shim(auth, monkeypatch, windows):+ """Unchanged: a quoted path is written differently in cmd and PowerShell."""+ monkeypatch.setattr(auth.sys, "executable", r"C:\Program Files\Python313\python.exe")+ monkeypatch.setattr(auth, "_cli_is_inside", lambda _prefix: True)++ assert auth._reset_password_command() == "unsloth.cmd studio reset-password"+++def test_the_prefix_check_locates_rather_than_imports(auth, tmp_path, monkeypatch):+ """A package outside the prefix must answer False, and a missing one too."""+ inside = tmp_path / "venv" / "Lib" / "site-packages" / "unsloth_cli"+ inside.mkdir(parents = True)+ (inside / "__init__.py").write_text("", encoding = "utf-8")++ class _Spec:+ def __init__(self, origin):+ self.origin = origin++ monkeypatch.setattr(+ auth.importlib.util, "find_spec", lambda _name: _Spec(str(inside / "__init__.py"))+ )+ assert auth._cli_is_inside(str(tmp_path / "venv"))+ assert not auth._cli_is_inside(str(tmp_path / "elsewhere"))++ # A namespace package has no origin, and nothing found returns None. Neither+ # is evidence that isolation would work.+ monkeypatch.setattr(auth.importlib.util, "find_spec", lambda _name: _Spec(None))+ assert not auth._cli_is_inside(str(tmp_path / "venv"))+ monkeypatch.setattr(auth.importlib.util, "find_spec", lambda _name: None)+ assert not auth._cli_is_inside(str(tmp_path / "venv"))+++def test_posix_is_untouched(auth, monkeypatch, tmp_path):+ """The console script is what a POSIX user should run; nothing here changes."""+ monkeypatch.setattr(auth.os, "name", "posix")+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ (bin_dir / "unsloth").write_text("", encoding = "utf-8")+ monkeypatch.setattr(auth.sys, "executable", str(bin_dir / "python"))++ assert auth._reset_password_command() == f"{bin_dir / 'unsloth'} studio reset-password"diff --git a/studio/setup.ps1 b/studio/setup.ps1index 9330f31ce31..1fcc83686b6 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -508,6 +508,26 @@ function Test-StudioHomeIsCustom {(Get-CanonicalDir -Path (Join-Path $env:USERPROFILE ".unsloth\studio")))}+# Is this bin\unsloth.cmd one install.ps1 wrote? Only then does it prove the root is+# ours. The name alone is a plausible wrapper for anything built on unsloth, and the+# caller uses the answer to decide whether a user-chosen venv may be deleted. The+# trampoline is the marker; no other file carries it. Mirrored in install.ps1+# (Test-UnslothCmdShimFile) and scripts/uninstall.ps1 (_IsUnslothCmdShim).+function Test-UnslothCmdShimFile {+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)++ if ([string]::IsNullOrWhiteSpace($Path)) { return $false }+ if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false }+ try {+ if ((Get-Item -LiteralPath $Path -ErrorAction Stop).Length -gt 8192) { return $false }+ $text = [System.IO.File]::ReadAllText($Path)+ } catch {+ # Unreadable proves nothing, and "proves nothing" must not mean "deletable".+ return $false+ }+ return ($text -like "*unsloth-studio-managed-launcher*" -and $text -like "*from unsloth_cli import app*")+}+# Shared default cache, or the custom Studio home's llama.cpp tree.function Get-ManagedLlamaCppDir {if (-not (Test-StudioHomeIsCustom)) {@@ -1707,7 +1727,7 @@ function Write-LlamaFailureLog {}# 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.+# every install.ps1 -> 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,@@ -4236,7 +4256,7 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode# Repair in place instead of wiping: the dependency pass force-reinstalls the torch trio from# the resolved index over this venv, the route an index-pin change and a cu* family change# already take above. Deleting is not an option here anyway -- install.ps1 invokes setup- # through the venv's own unsloth.exe, so python.exe is locked by the process running this.+ # through the venv's own python.exe, which is therefore locked by the process running this.if ($shouldRebuild -and $InstallerManagedSetup) {substep "Environment does not match this host ($reason) -- reinstalling PyTorch in place." "Yellow"substep "install.ps1 keeps a rollback copy of the previous environment until this run succeeds." "DarkGray"@@ -4249,11 +4269,15 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode# why: mirror install.ps1 env-mode guard so an update against a custom# UNSLOTH_STUDIO_HOME never wipes an unrelated unsloth_studio venv;# -PathType Leaf rejects a directory masquerading as the sentinel.+ # The .cmd counts too, and for the same reason the uninstaller accepts it: a+ # policy's quarantine can take the unsigned .exe and leave a root that is still+ # ours. Content-checked, never by name -- this guard gates a recursive delete.if ($StudioHomeIsCustom -and-not (Test-Path -LiteralPath (Join-Path $VenvDir $StudioOwnedMarker) -PathType Leaf) -and-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)+ -not (Test-Path -LiteralPath (Join-Path $StudioHome "bin\unsloth.exe") -PathType Leaf) -and+ -not (Test-UnslothCmdShimFile (Join-Path $StudioHome "bin\unsloth.cmd"))) {Write-StudioLine "[ERROR] $VenvDir already exists but does not look like an Unsloth Studio install." -ForegroundColor RedWrite-StudioLine " Move it aside or choose an empty UNSLOTH_STUDIO_HOME before re-running." -ForegroundColor Yellow@@ -5223,11 +5247,12 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCpsubstep "skipping direct PyTorch and Triton installation (no-torch mode)." "Yellow"}-# No unsloth.exe rename needed. setup.ps1 runs *via* unsloth.exe, so renaming the-# running launcher only ever failed (WinError 32) and printed a scary warning. It's-# also unnecessary: install.ps1 sets SKIP_STUDIO_BASE=1 (base never reinstalled) and-# 'studio update' goes through uv (--upgrade-package), whose pip fallback no-ops on-# the already-satisfied bare unsloth/unsloth-zoo. Either way unsloth.exe stays.+# No unsloth.exe rename needed. install.ps1 no longer starts the generated console+# script at all (it runs the CLI through the venv's python.exe, #8490), so the rename+# would now target a file nothing is holding -- but it was never needed either:+# install.ps1 sets SKIP_STUDIO_BASE=1 (base never reinstalled) and 'studio update'+# goes through uv (--upgrade-package), whose pip fallback no-ops on the+# already-satisfied bare unsloth/unsloth-zoo. Either way unsloth.exe stays.# Ordered heavy dependency installation -- shared cross-platform scriptsubstep "running ordered dependency installation..."diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rsindex 347e9d758bb..6f5566e95f5 100644--- a/studio/src-tauri/src/commands.rs+++ b/studio/src-tauri/src/commands.rs@@ -148,9 +148,17 @@ pub async fn check_install_status() -> bool {return false;};- let mut cmd = tokio::process::Command::new(&bin);- cmd.arg("-h")- .stdout(std::process::Stdio::null())+ let mut cmd = match process::build_managed_cli_command_tokio(&bin, &["-h"]) {+ Ok(cmd) => cmd,+ Err(e) => {+ warn!(+ "Install check: cannot run the managed CLI for {:?}: {}",+ bin, e+ );+ return false;+ }+ };+ cmd.stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());if let Err(error) = process::apply_managed_cli_context_tokio(&mut cmd) {diff --git a/studio/src-tauri/src/desktop_auth.rs b/studio/src-tauri/src/desktop_auth.rsindex f3b0c046e4a..536c8c2e2b3 100644--- a/studio/src-tauri/src/desktop_auth.rs+++ b/studio/src-tauri/src/desktop_auth.rs@@ -226,9 +226,12 @@ async fn exchange_desktop_secret(async fn provision_desktop_auth() -> Result<(), String> {let bin = crate::process::resolve_backend_binary()?;- let mut cmd = tokio::process::Command::new(&bin);- cmd.args(["studio", "provision-desktop-auth"])- .stdout(std::process::Stdio::null())+ let mut cmd = crate::process::build_managed_cli_command_tokio(+ &bin,+ &["studio", "provision-desktop-auth"],+ )+ .map_err(|e| format!("Desktop auth provisioning failed: {}", e))?;+ cmd.stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped());crate::process::apply_managed_cli_context_tokio(&mut cmd).map_err(|error| format!("Desktop auth provisioning failed: {}", error))?;diff --git a/studio/src-tauri/src/preflight/managed.rs b/studio/src-tauri/src/preflight/managed.rsindex 9f00a0df293..0e56338397e 100644--- a/studio/src-tauri/src/preflight/managed.rs+++ b/studio/src-tauri/src/preflight/managed.rs@@ -9,7 +9,6 @@ use std::path::{Path, PathBuf};use std::process::Stdio;use std::time::{Duration, Instant, UNIX_EPOCH};use tokio::io::AsyncReadExt;-use tokio::process::Command;// 3: the cached capability gained studio_install_ok / studio_install_reason.const MANAGED_CAPABILITY_CACHE_SCHEMA: u16 = 3;@@ -202,8 +201,35 @@ fn marker_candidates_for_bin(bin: &Path) -> Vec<PathBuf> {out}+/// The file whose size and mtime stand for "this CLI", which is the launcher when there+/// is one.+///+/// On Windows there may not be. Antivirus quarantine deletes the generated unsloth.exe+/// and leaves a venv that still runs through its interpreter, and since that is now a+/// supported layout, find_unsloth_binary_in_studio_dir hands back a launcher path that+/// does not exist. Keying the fingerprint on it would fail fs::metadata, so the+/// capability cache could be neither read nor written, and every preflight would pay+/// both the -h and the desktop-capabilities subprocess with their own 10s ceilings.+/// python.exe is the right stand-in: it is what actually starts the CLI there, and an+/// update replaces the whole venv, so it moves when the launcher would have.+fn fingerprint_identity_file(bin: &Path) -> Option<PathBuf> {+ if bin.exists() {+ return Some(bin.to_path_buf());+ }+ #[cfg(windows)]+ {+ let interpreter = bin.parent()?.join("python.exe");+ if interpreter.exists() {+ return Some(interpreter);+ }+ }+ None+}+fn managed_bin_fingerprint(bin: &Path) -> Option<ManagedBinFingerprint> {- let bin_metadata = fs::metadata(bin).ok()?;+ // Metadata from whatever identifies this CLI, but the cache key below stays the+ // launcher path, so the two layouts of one install cannot collide.+ let bin_metadata = fs::metadata(fingerprint_identity_file(bin)?).ok()?;let bin_path = bin.canonicalize().unwrap_or_else(|_| bin.to_path_buf())@@ -344,8 +370,17 @@ fn write_cached_capability(fingerprint: &ManagedBinFingerprint, capability: &Desasync fn run_cli_probe(bin: &Path, args: &[&str]) -> Result<bool, String> {let started = Instant::now();- let mut cmd = Command::new(bin);- cmd.args(args).stdout(Stdio::null()).stderr(Stdio::null());+ let Ok(mut cmd) = crate::process::build_managed_cli_command_tokio(bin, args) else {+ info!(+ "Managed preflight probe {:?} has no managed interpreter to run",+ args+ );+ // Ok, not Err: main's Err arm means "the probe could not be set up and the+ // install is untested". A venv with no interpreter beside the launcher IS a+ // result, and the same one this arm always gave.+ return Ok(false);+ };+ cmd.stdout(Stdio::null()).stderr(Stdio::null());// Reported, not folded into `false`: the CLI never ran, so calling it broken// would start a repair needing the same context. Re-checking afterwards is not@@ -402,10 +437,15 @@ async fn run_cli_probe(bin: &Path, args: &[&str]) -> Result<bool, String> {async fn probe_cli_capability(bin: &Path) -> Result<Option<DesktopCapability>, String> {let started = Instant::now();- let mut cmd = Command::new(bin);- cmd.args(["studio", "desktop-capabilities", "--json"])- .stdout(Stdio::piped())- .stderr(Stdio::null());+ let Ok(mut cmd) = crate::process::build_managed_cli_command_tokio(+ bin,+ &["studio", "desktop-capabilities", "--json"],+ ) else {+ info!("Managed desktop-capabilities probe has no managed interpreter to run");+ // As above: a missing interpreter is a verdict, not a failure to ask.+ return Ok(None);+ };+ cmd.stdout(Stdio::piped()).stderr(Stdio::null());// As above: a context that cannot be built is not a probe result.if let Err(error) = crate::process::apply_managed_cli_context_tokio(&mut cmd) {@@ -782,6 +822,42 @@ mod tests {assert!(!cache_matches(&cache, &fingerprint));}+ // Quarantine deletes the generated unsloth.exe, so the supported stubless layout+ // hands back a launcher path that is not on disk. Without a stand-in the+ // fingerprint is None, the capability cache can be neither read nor written, and+ // every preflight pays both probe subprocesses again.+ #[cfg(windows)]+ #[test]+ fn a_quarantined_launcher_is_fingerprinted_through_its_interpreter() {+ let venv = std::env::temp_dir().join(format!(+ "unsloth-fingerprint-quarantined-{}-{:?}",+ std::process::id(),+ std::thread::current().id()+ ));+ let scripts = venv.join("Scripts");+ fs::create_dir_all(&scripts).unwrap();+ let bin = scripts.join("unsloth.exe");+ let interpreter = scripts.join("python.exe");+ fs::write(&interpreter, "python").unwrap();+ assert!(!bin.exists(), "this case is about the launcher being gone");++ let fingerprint = managed_bin_fingerprint(&bin)+ .expect("a stubless venv must still fingerprint, through python.exe");+ // The identity stays the launcher path, so the two layouts of one install+ // cannot share a cache entry.+ assert!(fingerprint.bin_path.ends_with("unsloth.exe"));+ // And it tracks the interpreter, so a venv replaced by an update invalidates.+ fs::write(&interpreter, "python-after-an-update").unwrap();+ let after = managed_bin_fingerprint(&bin).unwrap();+ assert_ne!(fingerprint.bin_size, after.bin_size);++ // With no interpreter either there is nothing to stand in, and None is right.+ fs::remove_file(&interpreter).unwrap();+ assert!(managed_bin_fingerprint(&bin).is_none());++ let _ = fs::remove_dir_all(&venv);+ }+#[test]fn dropping_the_manifest_changes_the_fingerprint() {// Otherwise a cache entry written while healthy outlives the manifest,diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rsindex f5344e1fa22..0c4b43f42ac 100644--- a/studio/src-tauri/src/process.rs+++ b/studio/src-tauri/src/process.rs@@ -498,6 +498,49 @@ mod studio_runtime_launch_guard_tests {with_named_studio_runtime_launch_guard(&name, || Ok(())).unwrap();}+ // Since issue #8490 the long-lived Studio image is Scripts\python.exe, not+ // Scripts\unsloth.exe. ensure_managed_environment_is_idle matches by venv+ // root, so both must still register as "the environment is in use" -- a+ // miss here would let an update mutate a venv somebody is running.+ #[test]+ fn idle_scan_still_covers_a_python_hosted_studio() {+ let venv = std::env::temp_dir().join(format!(+ "unsloth-idle-scan-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let scripts = venv.join("Scripts");+ std::fs::create_dir_all(&scripts).unwrap();+ let python = scripts.join("python.exe");+ let stub = scripts.join("unsloth.exe");+ std::fs::write(&python, "").unwrap();+ std::fs::write(&stub, "").unwrap();++ let root = normalized_existing_windows_path(&venv).unwrap();+ for image in [&python, &stub] {+ let key = normalized_existing_windows_path(image).unwrap();+ assert!(+ windows_path_is_within(&key, &root).unwrap(),+ "{key} escaped the managed venv root {root}"+ );+ }++ // A sibling directory sharing the root's prefix must still be outside.+ let sibling = venv.with_file_name(format!(+ "{}-other",+ venv.file_name().unwrap().to_string_lossy()+ ));+ std::fs::create_dir_all(&sibling).unwrap();+ let sibling_key = normalized_existing_windows_path(&sibling).unwrap();+ assert!(!windows_path_is_within(&sibling_key, &root).unwrap());++ std::fs::remove_dir_all(&venv).unwrap();+ std::fs::remove_dir_all(&sibling).unwrap();+ }+#[test]fn managed_environment_scan_finds_a_process_inside_the_target_root() {let current_exe = std::env::current_exe().unwrap();@@ -906,6 +949,33 @@ pub(crate) fn force_kill_process_tree(info!("{} process tree force stopped", label);}+/// Whether a Windows venv's site-packages still holds something the CLI trampoline+/// could import.+///+/// The dist-info is accepted alongside the package directory, and for the same reason+/// `_managed_cli_site_packages_layout` in unsloth_cli/commands/studio.py accepts it: a+/// PEP 660 editable install of the checkout leaves a .pth and a `unsloth-*.dist-info`+/// here and no `unsloth_cli/` at all. Ranking that below an empty new layout would send+/// every capability probe at the interpreter with nothing to import.+///+/// It cannot prove the package imports, and does not try to. This runs on the launch+/// path, so it stays filesystem-only; the two Python-side probes that DO run an import+/// are the ones allowed to spawn an interpreter.+#[cfg(windows)]+fn windows_site_packages_carries_the_cli(site_packages: &std::path::Path) -> bool {+ if site_packages.join("unsloth_cli").exists() {+ return true;+ }+ let Ok(entries) = std::fs::read_dir(site_packages) else {+ return false;+ };+ entries.flatten().any(|entry| {+ let name = entry.file_name();+ let name = name.to_string_lossy();+ name.starts_with("unsloth-") && name.ends_with(".dist-info")+ })+}+/// Returns the path to the unsloth binary inside the managed venv, if it exists./// Checks the new layout (~/.unsloth/studio/unsloth_studio/) first,/// then falls back to the old layout (~/.unsloth/studio/.venv/) for compat.@@ -915,12 +985,69 @@ fn find_unsloth_binary_in_studio_dir(studio: &std::path::Path) -> Option<std::pa// Old layout (bundled scripts, older upstream)let old_base = studio.join(".venv");- for base in [new_base, old_base] {+ let bases = [new_base, old_base];++ // Three passes rather than one, because a migration interrupted by an open+ // handle can leave HALF of either layout behind (install.ps1 says so where it+ // renames the tree), and layout order alone then picks the half that cannot+ // run. Preference is by usefulness first, layout second:+ //+ // 1. a launcher with the interpreter beside it -- a complete environment;+ // 2. Windows only, an interpreter with no launcher -- quarantine takes the+ // unsigned stub and leaves a working install, and nothing executes the+ // stub any more, so its absence no longer means "not installed". Within+ // this pass, a layout that still holds the CLI package outranks one+ // that holds only an interpreter, whichever layout it is;+ // 3. a launcher with no interpreter -- useless to every caller here, but it+ // is what this function answered before, and its error message names the+ // missing interpreter, which is more use than "not installed".+ //+ // The returned path is the canonical handle whether or not the file exists:+ // every Windows caller reaches the CLI through its parent directory.+ for base in &bases {#[cfg(unix)]let bin = base.join("bin").join("unsloth");#[cfg(windows)]let bin = base.join("Scripts").join("unsloth.exe");+ #[cfg(unix)]+ let complete = bin.exists();+ #[cfg(windows)]+ let complete = bin.exists() && base.join("Scripts").join("python.exe").exists();++ if complete {+ return Some(bin);+ }+ }++ // Pass 2 twice over, package first. When an interrupted migration leaves an+ // interpreter in BOTH layouts, layout order alone would hand back the new+ // one even if its site-packages is empty and the old one still carries the+ // package the trampoline imports, and every capability probe would then+ // report an install that cannot start. A directory test, not an import+ // probe: this is called on the launch path and from the capability checks,+ // so it must stay a stat rather than an interpreter spawn. It cannot prove+ // the package is importable, only that one candidate has something to+ // import and the other has nothing, which is the whole difference here.+ #[cfg(windows)]+ for base in &bases {+ if base.join("Scripts").join("python.exe").exists()+ && windows_site_packages_carries_the_cli(&base.join("Lib").join("site-packages"))+ {+ return Some(base.join("Scripts").join("unsloth.exe"));+ }+ }++ #[cfg(windows)]+ for base in &bases {+ if base.join("Scripts").join("python.exe").exists() {+ return Some(base.join("Scripts").join("unsloth.exe"));+ }+ }++ #[cfg(windows)]+ for base in &bases {+ let bin = base.join("Scripts").join("unsloth.exe");if bin.exists() {return Some(bin);}@@ -936,6 +1063,169 @@ pub fn find_unsloth_binary() -> Option<std::path::PathBuf> {find_unsloth_binary_in_studio_dir(&studio)}+/// The Windows console script is a generated, unsigned PE wrapper. Application+/// Control (AppLocker, WDAC, Smart App Control) denies it while the managed+/// python.exe beside it - a copy of the signed CPython binary - still runs, so+/// every managed CLI invocation goes through the interpreter instead.+///+/// The leading sys.path edit is what `-I` used to buy, without the rest of it.+/// `python -c` puts the working directory on sys.path[0] and the console script+/// never does, so a stray unsloth_cli beside the caller would shadow the managed+/// package; stripping that one entry closes it and leaves alone everything the+/// console script honours. `-I` implies `-E`, which discarded PYTHONPATH,+/// PYTHONWARNINGS, PYTHONHASHSEED, PYTHONPROFILEIMPORTTIME and user+/// site-packages, an observable difference on machines with no policy at all.+///+/// The safe_path guard is why the comprehension is not simply `x not in (...)`.+/// Under -P or PYTHONSAFEPATH there is no implicit `-c` entry to remove, so+/// whatever sits at sys.path[0] is an explicit PYTHONPATH entry the console+/// script would have honoured; a PYTHONPATH that starts at the working+/// directory was measured selecting a different package before and after.+/// getattr, not sys.flags.safe_path: the attribute is 3.11+ and this repo+/// supports 3.9.+///+/// -X utf8 is the one deliberate divergence from the console script, and it+/// predates this work: the shipped updater already spelled it this way, and+/// mangled setup output on a non-UTF-8 console code page is what it exists to+/// prevent (see tests/python/test_windows_setup_output_encoding.py). Under an+/// explicit PYTHONUTF8=0 the child therefore runs in UTF-8 mode where the stub+/// would not have.+///+/// sys.argv[0] is assigned before the import because unsloth_cli decides at+/// import time whether it is the console script, which gates the Windows UTF-8+/// stream reconfigure and the -np<N> argv rewrite. It also sets Typer's+/// prog_name to "unsloth"; the stub prints "unsloth.exe", so usage text reads+/// slightly cleaner here rather than matching byte for byte.+#[cfg(windows)]+pub(crate) const WINDOWS_CLI_ENTRYPOINT: &str =+ "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())";++/// The program and argument vector that run the managed CLI without executing+/// `bin` itself. On non-Windows platforms `bin` is a plain script with a+/// shebang and stays the program.+#[derive(Debug)]+pub(crate) struct ManagedCliInvocation {+ pub program: std::path::PathBuf,+ pub args: Vec<std::ffi::OsString>,+}++impl ManagedCliInvocation {+ /// The single place an invocation becomes a process. Callers that need the+ /// resolved program before spawning, to log what they are about to start,+ /// resolve first and come back through here rather than rebuilding argv.+ pub(crate) fn to_command(&self) -> Command {+ let mut cmd = Command::new(&self.program);+ cmd.args(&self.args);+ cmd+ }+}++/// Resolve how to run `bin <args>` for the managed install. Fails closed on+/// Windows when the interpreter is missing rather than falling back to the+/// stub, which is exactly what a policy-blocked machine cannot run.+pub(crate) fn resolve_managed_cli_invocation(+ bin: &std::path::Path,+ args: &[&str],+) -> Result<ManagedCliInvocation, String> {+ resolve_managed_cli_invocation_with(bin, args, Isolation::Inherit)+}++/// Whether a managed invocation runs isolated from the ambient Python environment.+///+/// Everything the user could equally have typed themselves inherits, because the+/// console script does and the swap has to be invisible. The desktop updater does+/// not: it shipped with `-I` before any of this, nobody types it, and it rewrites+/// the very environment it runs in, so a `pip install --user unsloth_cli` deciding+/// which package gets updated is a real hazard rather than a parity question.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub(crate) enum Isolation {+ Inherit,+ Isolated,+}++pub(crate) fn resolve_managed_cli_invocation_with(+ bin: &std::path::Path,+ args: &[&str],+ isolation: Isolation,+) -> Result<ManagedCliInvocation, String> {+ #[cfg(windows)]+ {+ let python = bin+ .parent()+ .ok_or_else(|| "Managed Unsloth executable has no parent directory.".to_string())?+ .join("python.exe");+ if !python.is_file() {+ return Err(format!(+ "Managed Python interpreter not found beside Unsloth: {}",+ python.display()+ ));+ }+ // No -I, for the reason on WINDOWS_CLI_ENTRYPOINT. -X utf8 stays, so this+ // process writes UTF-8 into read_lossy_lines whatever the locale, and a+ // caller's PYTHONIOENCODING overrides it exactly as it overrides the+ // console script's.+ // -X utf8 before -I: -I implies -E, which would discard PYTHONUTF8, and the+ // flag form survives it.+ let mut argv: Vec<std::ffi::OsString> = match isolation {+ Isolation::Inherit => vec!["-X", "utf8", "-c", WINDOWS_CLI_ENTRYPOINT],+ Isolation::Isolated => vec!["-X", "utf8", "-I", "-c", WINDOWS_CLI_ENTRYPOINT],+ }+ .into_iter()+ .map(std::ffi::OsString::from)+ .collect();+ argv.extend(args.iter().copied().map(std::ffi::OsString::from));+ Ok(ManagedCliInvocation {+ program: python,+ args: argv,+ })+ }++ #[cfg(not(windows))]+ {+ // Isolation is a Windows-only concept: POSIX executes the console script+ // itself, so there is no interpreter command line to isolate.+ let _ = isolation;+ Ok(ManagedCliInvocation {+ program: bin.to_path_buf(),+ args: args.iter().copied().map(std::ffi::OsString::from).collect(),+ })+ }+}++/// Blocking flavour of [`resolve_managed_cli_invocation`].+pub(crate) fn build_managed_cli_command(+ bin: &std::path::Path,+ args: &[&str],+) -> Result<Command, String> {+ build_managed_cli_command_with(bin, args, Isolation::Inherit)+}++pub(crate) fn build_managed_cli_command_with(+ bin: &std::path::Path,+ args: &[&str],+ isolation: Isolation,+) -> Result<Command, String> {+ let cmd = resolve_managed_cli_invocation_with(bin, args, isolation)?.to_command();+ // PYTHONHOME and PYTHONPATH are deliberately left alone. Removing them was+ // belt and braces under -I, which dropped them anyway. Without -I it would+ // bite: the console script honours both, so scrubbing them here would make+ // the swap observable.+ Ok(cmd)+}++/// Async flavour of [`resolve_managed_cli_invocation`], for the probe and+/// provisioning call sites that already drive tokio children.+pub(crate) fn build_managed_cli_command_tokio(+ bin: &std::path::Path,+ args: &[&str],+) -> Result<tokio::process::Command, String> {+ let invocation = resolve_managed_cli_invocation(bin, args)?;+ let mut cmd = tokio::process::Command::new(&invocation.program);+ cmd.args(&invocation.args);+ // PYTHONHOME / PYTHONPATH left alone, for the reason in the blocking flavour.+ Ok(cmd)+}+/// Whether the user's profile is reachable at all: the managed install lives/// under it, so an unmounted roaming profile looks like no install.pub(crate) fn home_dir_available() -> Result<(), String> {@@ -1977,6 +2267,373 @@ mod tests {);}+ // issue #8490: Application Control denies the generated unsloth.exe. Every+ // managed invocation must reach the CLI through the interpreter beside it.+ #[cfg(windows)]+ fn managed_venv(test_name: &str) -> (PathBuf, PathBuf, PathBuf) {+ let dir = temp_studio_dir(test_name);+ let python = dir.join("python.exe");+ let bin = dir.join("unsloth.exe");+ fs::write(&python, "").unwrap();+ fs::write(&bin, "").unwrap();+ (dir, python, bin)+ }++ // Quarantine takes the unsigned stub and leaves the environment intact. The+ // finder gates the backend, the updater and the install-status probe, so a None+ // here reports "not installed" for a Studio that still runs.+ #[cfg(windows)]+ #[test]+ fn a_quarantined_stub_is_still_a_managed_install() {+ let studio = temp_studio_dir("quarantined-stub");+ let scripts = studio.join("unsloth_studio").join("Scripts");+ fs::create_dir_all(&scripts).unwrap();++ // No interpreter yet: there is genuinely nothing to run.+ assert_eq!(find_unsloth_binary_in_studio_dir(&studio), None);++ fs::write(scripts.join("python.exe"), "").unwrap();+ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(scripts.join("unsloth.exe")),+ "a stub-less environment with an interpreter is still an install"+ );++ // And the handle it hands back drives the interpreter as usual.+ let invocation =+ resolve_managed_cli_invocation(&scripts.join("unsloth.exe"), &["studio"]).unwrap();+ assert_eq!(invocation.program, scripts.join("python.exe"));++ fs::remove_dir_all(studio).unwrap();+ }++ // An interrupted migration leaves a half-built new environment beside a legacy+ // one that still works. A launcher anywhere outranks a bare interpreter, or the+ // desktop would drive the broken half and report an install it cannot start.+ #[cfg(windows)]+ #[test]+ fn a_legacy_launcher_outranks_a_stubless_new_environment() {+ let studio = temp_studio_dir("interrupted-migration");+ let new_scripts = studio.join("unsloth_studio").join("Scripts");+ let old_scripts = studio.join(".venv").join("Scripts");+ fs::create_dir_all(&new_scripts).unwrap();+ fs::create_dir_all(&old_scripts).unwrap();+ fs::write(new_scripts.join("python.exe"), "").unwrap();+ fs::write(old_scripts.join("python.exe"), "").unwrap();+ fs::write(old_scripts.join("unsloth.exe"), "").unwrap();++ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(old_scripts.join("unsloth.exe")),+ "a working legacy install must win over a partial new one"+ );++ // Once the new layout has its own launcher, layout order takes over again.+ fs::write(new_scripts.join("unsloth.exe"), "").unwrap();+ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(new_scripts.join("unsloth.exe"))+ );++ fs::remove_dir_all(studio).unwrap();+ }++ // The other half of the same interruption: the new layout kept the launcher and+ // the legacy one kept the interpreter. Returning the new launcher there fails+ // later with "Managed Python interpreter not found beside Unsloth" while a+ // usable environment sits in the other base.+ #[cfg(windows)]+ #[test]+ fn a_complete_legacy_environment_beats_a_launcher_with_no_interpreter() {+ let studio = temp_studio_dir("split-migration");+ let new_scripts = studio.join("unsloth_studio").join("Scripts");+ let old_scripts = studio.join(".venv").join("Scripts");+ fs::create_dir_all(&new_scripts).unwrap();+ fs::create_dir_all(&old_scripts).unwrap();+ fs::write(new_scripts.join("unsloth.exe"), "").unwrap();+ fs::write(old_scripts.join("python.exe"), "").unwrap();+ fs::write(old_scripts.join("unsloth.exe"), "").unwrap();++ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(old_scripts.join("unsloth.exe")),+ "a complete environment must win over a launcher that cannot start"+ );++ // With nothing usable anywhere, still answer what this function always+ // answered: the caller's error then names the missing interpreter.+ fs::remove_file(old_scripts.join("python.exe")).unwrap();+ fs::remove_file(old_scripts.join("unsloth.exe")).unwrap();+ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(new_scripts.join("unsloth.exe"))+ );++ fs::remove_dir_all(studio).unwrap();+ }++ // Both halves of an interrupted migration kept an interpreter and neither kept+ // a launcher, so pass 1 cannot decide and layout order alone would hand back+ // the new base whether or not anything is installed in it. The base that still+ // holds the package the trampoline imports has to win, in either direction, or+ // every capability probe drives an interpreter with nothing to run.+ #[cfg(windows)]+ #[test]+ fn an_interpreter_that_still_has_the_package_outranks_one_that_does_not() {+ let studio = temp_studio_dir("stubless-both-halves");+ let new_base = studio.join("unsloth_studio");+ let old_base = studio.join(".venv");+ for base in [&new_base, &old_base] {+ fs::create_dir_all(base.join("Scripts")).unwrap();+ fs::write(base.join("Scripts").join("python.exe"), "").unwrap();+ }++ // Neither carries the package: layout order decides, exactly as before.+ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(new_base.join("Scripts").join("unsloth.exe")),+ "with nothing to choose between them the new layout still wins"+ );++ // The legacy base has the package and the new one does not.+ fs::create_dir_all(old_base.join("Lib").join("site-packages").join("unsloth_cli")).unwrap();+ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(old_base.join("Scripts").join("unsloth.exe")),+ "the only base with a package to import must win"+ );++ // Once the new base has it too, layout order takes over again.+ fs::create_dir_all(new_base.join("Lib").join("site-packages").join("unsloth_cli")).unwrap();+ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(new_base.join("Scripts").join("unsloth.exe")),+ "package on both sides is not a reason to prefer the legacy layout"+ );++ // A complete environment anywhere still outranks this whole pass.+ fs::write(old_base.join("Scripts").join("unsloth.exe"), "").unwrap();+ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(old_base.join("Scripts").join("unsloth.exe"))+ );++ fs::remove_dir_all(studio).unwrap();+ }++ // An editable install of the checkout leaves a .pth and a dist-info in+ // site-packages and no unsloth_cli/ directory at all, so a package-directory test+ // alone would rank a working legacy venv below an empty new one. The Python side+ // accepts the dist-info for this exact shape; this side has to agree.+ #[cfg(windows)]+ #[test]+ fn an_editable_install_counts_as_carrying_the_package() {+ let studio = temp_studio_dir("stubless-editable");+ let new_base = studio.join("unsloth_studio");+ let old_base = studio.join(".venv");+ for base in [&new_base, &old_base] {+ fs::create_dir_all(base.join("Scripts")).unwrap();+ fs::write(base.join("Scripts").join("python.exe"), "").unwrap();+ fs::create_dir_all(base.join("Lib").join("site-packages")).unwrap();+ }++ let legacy_site_packages = old_base.join("Lib").join("site-packages");+ fs::create_dir_all(legacy_site_packages.join("unsloth-2026.8.1.dist-info")).unwrap();+ fs::write(legacy_site_packages.join("__editable__.unsloth.pth"), "").unwrap();++ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(old_base.join("Scripts").join("unsloth.exe")),+ "an editable install has a package to import and must outrank an empty venv"+ );++ // Unrelated metadata is not this package. A dist-info for something else must+ // not make an empty venv look installed.+ fs::create_dir_all(+ new_base+ .join("Lib")+ .join("site-packages")+ .join("unsloth_zoo-2026.8.1.dist-info"),+ )+ .unwrap();+ assert_eq!(+ find_unsloth_binary_in_studio_dir(&studio),+ Some(old_base.join("Scripts").join("unsloth.exe")),+ "a dist-info for another distribution must not count"+ );++ fs::remove_dir_all(studio).unwrap();+ }++ #[cfg(windows)]+ #[test]+ fn managed_invocation_runs_python_with_the_trampoline_and_caller_args() {+ use std::ffi::OsString;++ let (dir, python, bin) = managed_venv("managed-cli-invocation");+ let invocation =+ resolve_managed_cli_invocation(&bin, &["studio", "--api-only", "-p", "8888"]).unwrap();++ assert_eq!(invocation.program, python);+ assert_ne!(invocation.program, bin);+ assert_eq!(+ invocation.args,+ vec![+ // No -I; see WINDOWS_CLI_ENTRYPOINT.+ OsString::from("-X"),+ OsString::from("utf8"),+ OsString::from("-c"),+ OsString::from(WINDOWS_CLI_ENTRYPOINT),+ // Caller arguments follow the script, in order.+ OsString::from("studio"),+ OsString::from("--api-only"),+ OsString::from("-p"),+ OsString::from("8888"),+ ]+ );+ fs::remove_dir_all(dir).unwrap();+ }++ #[cfg(windows)]+ #[test]+ fn managed_invocation_does_not_isolate_the_interpreter() {+ // Measured on a machine with no policy: PYTHONPROFILEIMPORTTIME=1 gave+ // ~24 KB of stderr from the console script and nothing from a -I+ // trampoline, and PYTHONPATH stopped shadowing.+ let (dir, _python, bin) = managed_venv("managed-cli-no-isolation");+ let invocation = resolve_managed_cli_invocation(&bin, &["-h"]).unwrap();++ assert!(+ !invocation.args.iter().any(|arg| arg == "-I"),+ "{:?}",+ invocation.args+ );+ assert!(+ WINDOWS_CLI_ENTRYPOINT.contains("sys.path[:1]"),+ "{WINDOWS_CLI_ENTRYPOINT}"+ );+ fs::remove_dir_all(dir).unwrap();+ }++ // The exception, and the only one: the updater rewrites the environment it+ // runs in, so it stays isolated exactly as it shipped. Asserted here as well+ // as in update.rs so the two halves of the rule are stated together.+ #[cfg(windows)]+ #[test]+ fn only_the_isolated_flavour_carries_the_isolation_flag() {+ let (dir, _python, bin) = managed_venv("managed-cli-isolated");++ let inherit =+ resolve_managed_cli_invocation_with(&bin, &["studio"], Isolation::Inherit).unwrap();+ let isolated =+ resolve_managed_cli_invocation_with(&bin, &["studio"], Isolation::Isolated).unwrap();++ assert!(!inherit.args.iter().any(|arg| arg == "-I"), "{:?}", inherit.args);+ assert!(isolated.args.iter().any(|arg| arg == "-I"), "{:?}", isolated.args);+ // -X utf8 comes first either way: -I implies -E, which would drop+ // PYTHONUTF8, and the flag form survives it.+ assert_eq!(isolated.args[0], std::ffi::OsString::from("-X"));+ assert_eq!(isolated.args[1], std::ffi::OsString::from("utf8"));+ assert_eq!(isolated.args[2], std::ffi::OsString::from("-I"));+ // Same program, same trailing arguments; only the flag differs.+ assert_eq!(inherit.program, isolated.program);+ assert_eq!(inherit.args.last(), isolated.args.last());+ // And the default entry point is the inheriting one.+ assert_eq!(+ resolve_managed_cli_invocation(&bin, &["studio"]).unwrap().args,+ inherit.args+ );+ fs::remove_dir_all(dir).unwrap();+ }++ #[cfg(windows)]+ #[test]+ fn managed_trampoline_assigns_argv0_before_importing_the_cli() {+ // The order is the whole point: unsloth_cli decides at import time+ // whether it is the console script, which gates the UTF-8 stream+ // reconfigure, the -np<N> rewrite and Typer's prog_name.+ let strip = WINDOWS_CLI_ENTRYPOINT.find("sys.path[:1]");+ let assignment = WINDOWS_CLI_ENTRYPOINT.find("sys.argv[0] = 'unsloth'");+ let import = WINDOWS_CLI_ENTRYPOINT.find("from unsloth_cli import app");+ assert!(strip.is_some() && assignment.is_some() && import.is_some());+ assert!(assignment < import, "{WINDOWS_CLI_ENTRYPOINT}");+ // The cwd must leave sys.path before the import too, or the entry it+ // guards against is still live for that one import.+ assert!(strip < import, "{WINDOWS_CLI_ENTRYPOINT}");+ }++ #[cfg(windows)]+ #[test]+ fn managed_commands_leave_the_python_environment_alone() {+ use std::ffi::OsStr;++ // Harmless under -I, which discarded them anyway; without it, a change+ // the console script does not make.+ let (dir, _python, bin) = managed_venv("managed-cli-env");+ let cmd = build_managed_cli_command(&bin, &["-h"]).unwrap();+ for name in ["PYTHONHOME", "PYTHONPATH"] {+ assert!(+ !cmd.get_envs().any(|(key, _)| key == OsStr::new(name)),+ "{name} must be inherited, not overridden"+ );+ }+ // The async flavour must not drift from the blocking one.+ let tokio_cmd = build_managed_cli_command_tokio(&bin, &["-h"]).unwrap();+ let std_cmd = tokio_cmd.as_std();+ for name in ["PYTHONHOME", "PYTHONPATH"] {+ assert!(+ !std_cmd.get_envs().any(|(key, _)| key == OsStr::new(name)),+ "{name} must be inherited, not overridden"+ );+ }+ assert_eq!(std_cmd.get_program(), cmd.get_program());+ fs::remove_dir_all(dir).unwrap();+ }++ #[cfg(windows)]+ #[test]+ fn managed_invocation_fails_closed_without_the_interpreter() {+ // Falling back to the stub is exactly what a policy-blocked machine+ // cannot run, so a missing interpreter is an error, not a downgrade.+ let bin = temp_studio_dir("managed-cli-no-python").join("unsloth.exe");+ let error = resolve_managed_cli_invocation(&bin, &["-h"]).unwrap_err();+ assert!(error.contains("python.exe"), "{error}");+ }++ // Parity guard: the change is Windows-only. macOS and Linux keep execing+ // the console script with the caller's arguments and nothing else.+ #[cfg(not(windows))]+ #[test]+ fn posix_managed_invocation_still_execs_the_console_script() {+ use std::ffi::OsString;++ let bin = std::path::Path::new("/opt/unsloth/bin/unsloth");+ let invocation = resolve_managed_cli_invocation(bin, &["studio", "--api-only"]).unwrap();++ assert_eq!(invocation.program, bin);+ assert_eq!(+ invocation.args,+ vec![OsString::from("studio"), OsString::from("--api-only")]+ );++ let cmd = build_managed_cli_command(bin, &["studio", "--api-only"]).unwrap();+ assert_eq!(cmd.get_program(), bin.as_os_str());+ assert_eq!(+ cmd.get_args().map(OsString::from).collect::<Vec<_>>(),+ vec![OsString::from("studio"), OsString::from("--api-only")]+ );+ assert!(cmd.get_envs().next().is_none());+ }++ #[cfg(not(windows))]+ #[test]+ fn posix_managed_invocation_needs_no_interpreter_beside_the_script() {+ // The Windows arm fails closed on a missing python.exe; the POSIX arm+ // must not acquire that failure mode for a path that never had it.+ let bin = std::path::Path::new("/definitely/not/here/bin/unsloth");+ assert!(resolve_managed_cli_invocation(bin, &["-h"]).is_ok());+ }+fn listening_non_studio_port() -> (u16, mpsc::Sender<()>, std::thread::JoinHandle<()>) {let listener = TcpListener::bind("127.0.0.1:0").unwrap();listener.set_nonblocking(true).unwrap();@@ -2141,7 +2798,38 @@ pub fn start_backend(};let args = backend_args(port);- let start_line = format!("Starting backend: {:?} {}", bin, args.join(" "));+ // Built before ownership is claimed: a missing managed interpreter must not+ // leave a pending owner behind for a backend that was never spawned.+ let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();+ let invocation = match resolve_managed_cli_invocation(&bin, &arg_refs) {+ Ok(invocation) => invocation,+ Err(msg) => {+ diagnostics::record_backend_start_failure(+ diagnostics_state,+ Some(port),+ None,+ "build_backend_command",+ &msg,+ );+ return Err(msg);+ }+ };+ // The program actually spawned, not the console script it resolved from. This+ // line is what a user attaches to an issue, and naming the stub would point+ // every Application Control report at a binary we never start.+ // Same shape as before, so a support log reads the same on every platform; only+ // the program differs, and only where the interpreter is what actually starts.+ let start_line = format!(+ "Starting backend: {:?} {}",+ invocation.program,+ invocation+ .args+ .iter()+ .map(|arg| arg.to_string_lossy().into_owned())+ .collect::<Vec<_>>()+ .join(" ")+ );+ let mut cmd = invocation.to_command();let pending_owner = match crate::desktop_backend_owner::new_pending_owner() {Ok(pending_owner) => pending_owner,Err(error) => {@@ -2156,10 +2844,7 @@ pub fn start_backend(return Err(msg);}};- let mut cmd = Command::new(&bin);- cmd.args(&args)- .stdout(Stdio::piped())- .stderr(Stdio::piped());+ cmd.stdout(Stdio::piped()).stderr(Stdio::piped());if let Err(error) = apply_managed_cli_context_at(&mut cmd, &work_dir) {// The drive holding an override can go between the preflight check and@@ -2198,6 +2883,8 @@ pub fn start_backend(// 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.+ // The backend gets UTF-8 from -X utf8 in its argv; these reach it too now+ // that -I is gone, and carry on down to whatever it spawns.#[cfg(windows)]{cmd.env("PYTHONUTF8", "1");diff --git a/studio/src-tauri/src/update.rs b/studio/src-tauri/src/update.rsindex 5cf36deb757..586ca20cf16 100644--- a/studio/src-tauri/src/update.rs+++ b/studio/src-tauri/src/update.rs@@ -7,10 +7,6 @@ use std::process::{Command, ExitStatus, Stdio};use std::sync::{Arc, Mutex};use tauri::{AppHandle, Emitter};-#[cfg(windows)]-const WINDOWS_CLI_ENTRYPOINT: &str =- "import sys; sys.argv[0] = 'unsloth'; from unsloth_cli import app; app()";-// ── Types ──#[derive(Default)]@@ -28,45 +24,28 @@ pub fn new_update_state() -> UpdateState {// ── Spawn ──fn build_update_command(bin: &std::path::Path) -> Result<Command, String> {+ // Only the Windows arm below mutates it.+ #[cfg_attr(not(windows), allow(unused_mut))]+ // Isolated, as this call site shipped. It is the one managed invocation nobody+ // types by hand, and the one that decides which install gets rewritten: a+ // user-site unsloth_cli must not be able to answer `from unsloth_cli import app`+ // here. Everything else inherits, because the console script does.+ let mut cmd = crate::process::build_managed_cli_command_with(+ bin,+ &["studio", "update"],+ crate::process::Isolation::Isolated,+ )?;+ // The only managed invocation that scrubs, and the only one that shipped doing it.+ // Elsewhere inheriting is the point, since the console script honours these. Here+ // the failure is unrecoverable: a foreign PYTHONHOME stops the managed interpreter+ // finding its own site-packages, and a PYTHONPATH pointing at another checkout+ // makes `from unsloth_cli import app` update the wrong install.#[cfg(windows)]{- let python = bin- .parent()- .ok_or_else(|| "Managed Unsloth executable has no parent directory.".to_string())?- .join("python.exe");- if !python.is_file() {- return Err(format!(- "Managed Python interpreter not found beside Unsloth: {}",- python.display()- ));- }- 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.- //- // -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)- }-- #[cfg(not(windows))]- {- let mut cmd = Command::new(bin);- cmd.args(["studio", "update"]);- Ok(cmd)}+ Ok(cmd)}fn configure_tauri_update_environment(cmd: &mut Command) {@@ -540,7 +519,7 @@ mod tests {#[cfg(windows)]#[test]fn windows_update_command_uses_python_not_replaceable_console_stub() {- use std::ffi::{OsStr, OsString};+ use std::ffi::OsString;let dir =std::env::temp_dir().join(format!("unsloth-update-command-{}", std::process::id()));@@ -557,21 +536,23 @@ mod tests {assert_eq!(cmd.get_args().map(OsString::from).collect::<Vec<_>>(),vec![- // -X utf8 leads: -I implies -E, so PYTHONUTF8 would be ignored.+ // -I here and nowhere else. This is the invocation that decides+ // which install gets rewritten, and it shipped isolated; a+ // user-site unsloth_cli answering `from unsloth_cli import app`+ // would update the wrong one. Every invocation a user could have+ // typed instead inherits, because the console script does.OsString::from("-X"),OsString::from("utf8"),OsString::from("-I"),OsString::from("-c"),- OsString::from(WINDOWS_CLI_ENTRYPOINT),+ OsString::from(crate::process::WINDOWS_CLI_ENTRYPOINT),OsString::from("studio"),OsString::from("update")]);- for name in ["PYTHONHOME", "PYTHONPATH"] {- assert!(cmd- .get_envs()- .any(|(key, value)| key == OsStr::new(name) && value.is_none()));- }+ // The updater's PYTHONHOME / PYTHONPATH handling is asserted once, in+ // windows_update_command_still_scrubs_the_python_search_path below. This+ // test owns the program and the argument vector.std::fs::remove_dir_all(dir).unwrap();}@@ -585,4 +566,54 @@ mod tests {.unwrap_err().contains("python.exe"));}++ // The Windows trampoline moved into process.rs; nothing about the POSIX+ // Dropping -I made this load bearing rather than belt and braces: without -E the+ // child now reads both. See build_update_command for what each one breaks.+ #[cfg(windows)]+ #[test]+ fn windows_update_command_still_scrubs_the_python_search_path() {+ let dir = std::env::temp_dir().join(format!(+ "unsloth-update-scrub-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::create_dir_all(&dir).unwrap();+ let python = dir.join("python.exe");+ let bin = dir.join("unsloth.exe");+ std::fs::write(&python, "").unwrap();+ std::fs::write(&bin, "").unwrap();++ let cmd = build_update_command(&bin).unwrap();+ for name in ["PYTHONHOME", "PYTHONPATH"] {+ assert!(+ cmd.get_envs()+ .any(|(key, value)| key == std::ffi::OsStr::new(name) && value.is_none()),+ "{name} is not scrubbed for the updater"+ );+ }+ std::fs::remove_dir_all(dir).unwrap();+ }++ // command may move with it. macOS and Linux still exec the console script.+ #[cfg(not(windows))]+ #[test]+ fn posix_update_command_still_execs_the_console_script() {+ use std::ffi::OsString;++ let bin = std::path::Path::new("/opt/unsloth/bin/unsloth");+ let cmd = build_update_command(bin).unwrap();++ assert_eq!(cmd.get_program(), bin.as_os_str());+ assert_eq!(+ cmd.get_args().map(OsString::from).collect::<Vec<_>>(),+ vec![OsString::from("studio"), OsString::from("update")]+ );+ // No PYTHONHOME/PYTHONPATH scrubbing off Windows: the console script is+ // not the interpreter, and callers that need it do it themselves.+ assert!(cmd.get_envs().next().is_none());+ }}diff --git a/tests/python/test_module_entry_point.py b/tests/python/test_module_entry_point.pynew file mode 100644index 00000000000..9e4f905a630--- /dev/null+++ b/tests/python/test_module_entry_point.py@@ -0,0 +1,441 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""`python -m unsloth_cli` must be the console script, byte for byte.++Windows materialises the `unsloth` entry point as a generated, unsigned+`unsloth.exe`, and an Application Control policy (AppLocker / WDAC / Smart App+Control) denies it while the signed interpreter beside it keeps running, so the+installer, the desktop app and locked-down users all need a route to the CLI+that does not go through that executable (issue #8490).++Two such routes exist and both must behave exactly like the console script,+because everything above them assumes the swap is invisible:++ * ``python -X utf8 -m unsloth_cli`` -- the public, documented one.+ * ``python -X utf8 -c "<trampoline>"`` -- the internal one, used by+ install.ps1, studio/src-tauri and the `studio run` respawn. It is spelled+ out here rather than imported so a silent edit to the constant on either+ side of the language boundary fails this test.++`sys.argv[0] = 'unsloth'` is what buys that equivalence: unsloth_cli/__init__+gates its entry-point behaviour (UTF-8 streams, the `-np<N>` rewrite) on the+basename of argv[0], and typer/click derive the program name printed in every+usage and error string from it.+"""++from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path++import pytest++# Byte-identical to WINDOWS_CLI_ENTRYPOINT in studio/src-tauri/src/process.rs,+# $script:UnslothCliTrampoline in install.ps1, and _WINDOWS_CLI_ENTRYPOINT in+# unsloth_cli/commands/studio.py. Spelled out rather than imported so an edit on+# any one side of the language boundary fails this test.+TRAMPOLINE = (+ "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "+ "sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())"+)++# No -I. It implies -E, which would discard every PYTHON* variable the console+# script honours, and that divergence is exactly what the sys.path[:1] filter in+# the trampoline exists to avoid needing.+INTERPRETER = [sys.executable, "-X", "utf8"]++# Not .resolve(): a POSIX venv's bin/python is a symlink to the base interpreter,+# and resolving it would look for the console script next to /usr/bin/python3.+_SCRIPT_DIR = Path(sys.executable).parent+_CONSOLE_SCRIPT = _SCRIPT_DIR / ("unsloth.exe" if os.name == "nt" else "unsloth")++requires_console_script = pytest.mark.skipif(+ not _CONSOLE_SCRIPT.is_file(),+ reason = f"no `unsloth` console script beside {sys.executable}; install the package first",+)++_REPO_ROOT = Path(__file__).resolve().parents[2]+_REPO_PACKAGE = _REPO_ROOT / "unsloth_cli"+++def _installed_package_dir() -> Path | None:+ """Where a child interpreter's `import unsloth_cli` actually lands.++ The trampoline strips the working directory from sys.path, so a child+ resolves the INSTALLED package and never this checkout by way of the cwd.+ When the two differ, the subprocess cases below would be testing a released+ wheel rather than the tree under test, so they skip instead of failing for+ the wrong reason. The in-process and source-contract cases still run+ everywhere.++ The probe therefore has to strip the cwd exactly as the trampoline does, or+ it would answer for a search path the tests never use.+ """+ probe = _run(+ [+ *INTERPRETER,+ "-c",+ "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "+ "import unsloth_cli; print(os.path.dirname(unsloth_cli.__file__))",+ ]+ )+ if probe.returncode != 0:+ return None+ return Path(probe.stdout.decode("utf-8", "replace").strip())+++def _run(argv: list[str], env: dict[str, str] | None = None) -> subprocess.CompletedProcess:+ """Run *argv* with captured bytes. Text mode would hide an encoding fault."""+ return subprocess.run(+ argv,+ capture_output = True,+ timeout = 120,+ env = env,+ )+++_INSTALLED_PACKAGE = _installed_package_dir()++requires_this_checkout_installed = pytest.mark.skipif(+ _INSTALLED_PACKAGE is None or _INSTALLED_PACKAGE.resolve() != _REPO_PACKAGE,+ reason = (+ f"`import unsloth_cli` in a child resolves to {_INSTALLED_PACKAGE}, not "+ f"{_REPO_PACKAGE}; install this checkout (pip install -e .) to run the "+ "subprocess parity cases"+ ),+)+++def _module_argv(*args: str) -> list[str]:+ return [*INTERPRETER, "-m", "unsloth_cli", *args]+++def _trampoline_argv(*args: str) -> list[str]:+ return [*INTERPRETER, "-c", TRAMPOLINE, *args]+++def _console_argv(*args: str) -> list[str]:+ return [str(_CONSOLE_SCRIPT), *args]+++# Cover a clean exit, both help renderers (rich draws box characters here), and+# the two error shapes: an unknown option at the root and inside a subcommand.+PARITY_CASES = [+ pytest.param(["--version"], id = "version"),+ pytest.param(["--help"], id = "help"),+ pytest.param(["studio", "--help"], id = "studio-help"),+ pytest.param(["--definitely-not-a-flag"], id = "unknown-root-flag"),+ pytest.param(["studio", "run", "--definitely-not-a-flag"], id = "unknown-subcommand-flag"),+]+++@requires_this_checkout_installed+def test_the_module_entry_point_exists():+ """A missing __main__.py degrades to a confusing "cannot be directly executed"."""+ result = _run(_module_argv("--version"))+ assert result.returncode == 0, (+ f"`python -m unsloth_cli --version` failed ({result.returncode}):\n"+ f"{result.stderr.decode('utf-8', 'replace')}"+ )+ assert result.stdout.startswith(b"unsloth "), result.stdout+++@requires_console_script+@requires_this_checkout_installed[email protected]("args", PARITY_CASES)+def test_module_entry_matches_the_console_script(args):+ reference = _run(_console_argv(*args))+ module = _run(_module_argv(*args))+ assert module.returncode == reference.returncode+ assert module.stdout == reference.stdout+ assert module.stderr == reference.stderr+++@requires_console_script+@requires_this_checkout_installed[email protected]("args", PARITY_CASES)+def test_trampoline_matches_the_console_script(args):+ """The form install.ps1 and the Tauri app use, pinned against the real thing."""+ reference = _run(_console_argv(*args))+ trampoline = _run(_trampoline_argv(*args))+ assert trampoline.returncode == reference.returncode+ assert trampoline.stdout == reference.stdout+ assert trampoline.stderr == reference.stderr+++@requires_this_checkout_installed+ "argv_builder",+ [_module_argv, _trampoline_argv],+ ids = ["module", "trampoline"],+)+def test_the_program_name_is_unsloth_not_the_launcher(argv_builder):+ """Without the argv[0] rewrite, usage strings read `__main__.py` or `-c`."""+ result = _run(argv_builder("--help"))+ assert result.returncode == 0, result.stderr.decode("utf-8", "replace")+ text = result.stdout.decode("utf-8", "replace")+ assert "unsloth" in text+ assert "__main__.py" not in text+ # `-c` would surface as the program name in the Usage line.+ assert "Usage: -c" not in text+++def test_the_attached_np_short_is_still_canonicalised(monkeypatch):+ """`-np8` must reach typer as `-np 8`, not click's `-n -p 8`.++ This is the one thing a naive __main__.py silently loses. The gate in+ unsloth_cli/__init__ keys on argv[0], and `-m` imports the package to find+ __main__, so the gate has already run and seen "-m" before __main__ can fix+ argv[0]. The damage is quiet and severe: click reads `-np8` as `-n -p 8` and+ `-p` is --port, so `unsloth studio run -np8` was observed serving on port 8+ instead of 8888 with the parallel count dropped.++ Driven in-process because the outward symptom is a bound socket: only a+ started server reveals the wrong port, and the argv the CLI is handed is the+ same fact one step earlier.+ """+ import runpy++ import unsloth_cli++ recorded = {}++ def fake_app(*args, **kwargs):+ recorded["argv"] = list(sys.argv)+ recorded["kwargs"] = kwargs++ monkeypatch.setattr(unsloth_cli, "app", fake_app)+ # The one-shot guard may already have fired in this interpreter.+ monkeypatch.setattr(unsloth_cli, "_entry_point_prepared", False)+ monkeypatch.setattr(sys, "argv", ["-m", "studio", "run", "-np8"])++ # SystemExit, because __main__ ends in sys.exit(app()) exactly as the console+ # script does. The fake app returns None, so the status is None: a clean exit.+ with pytest.raises(SystemExit) as exit_info:+ runpy.run_module("unsloth_cli", run_name = "__main__", alter_sys = True)+ assert exit_info.value.code in (None, 0)++ assert recorded["argv"] == ["unsloth", "studio", "run", "-np", "8"], (+ "__main__ must apply the console-script argv canonicalisation; got " f"{recorded['argv']}"+ )+ # Without this click prints `Usage: python -m unsloth_cli`, because it reads+ # __main__.__package__ rather than argv[0].+ assert recorded["kwargs"].get("prog_name") == "unsloth"+++@requires_console_script+@requires_this_checkout_installed+ "argv_builder",+ [_module_argv, _trampoline_argv],+ ids = ["module", "trampoline"],+)+def test_help_matches_the_console_script_under_a_narrow_encoding(argv_builder):+ """rich draws box characters cp1252 cannot encode; --help must still agree.++ -X utf8 is dropped for this case on purpose: it would hand the child a utf+ stream anyway, which is exactly the situation the stream guard in+ unsloth_cli/__init__ does not need to handle.+ """+ strip = ("-X", "utf8")+ argv = [arg for arg in argv_builder("--help") if arg not in strip]+ env = dict(os.environ)+ env["PYTHONIOENCODING"] = "cp1252"++ reference = _run(_console_argv("--help"), env = env)+ result = _run(argv, env = env)++ assert result.returncode == reference.returncode, (+ "--help died under a narrow stdout encoding:\n"+ f"{result.stderr.decode('utf-8', 'replace')}"+ )+ assert result.stdout == reference.stdout+ assert result.stderr == reference.stderr+++def test_the_module_entry_source_keeps_its_two_load_bearing_details():+ """Runs everywhere, including where the subprocess cases skip.++ The parity cases above need this checkout installed, so on a machine holding+ a released wheel they would go quiet and a deleted __main__.py or a dropped+ prog_name would sail through. Both details are invisible at a glance and+ each has already been shipped wrong once, so pin them in the source too.+ """+ source = (_REPO_PACKAGE / "__main__.py").read_text(encoding = "utf-8")++ argv_assignment = source.find('sys.argv[0] = "unsloth"')+ package_import = source.find("import unsloth_cli")+ assert argv_assignment != -1, "__main__.py no longer rewrites argv[0]"+ assert package_import != -1, "__main__.py no longer imports the package"+ assert argv_assignment < package_import, (+ "argv[0] must be rewritten before the package is imported, or a direct "+ "`python path/to/__main__.py` run misses the console-script gate"+ )+ # `-m` imports the package to locate this module, so __init__ has already run+ # with argv[0] == "-m" and its gate cannot fire; __main__ has to say so.+ assert "_prepare_entry_point()" in source+ # click reads __main__.__package__ rather than argv[0] and would otherwise+ # print `Usage: python -m unsloth_cli` in every usage and error string.+ assert 'prog_name = "unsloth"' in source+ # The generated console script is `sys.exit(app())`. Typer raises SystemExit+ # itself today, so both spellings agree, but a returned value has to become+ # the exit status here too or they stop agreeing the moment one exists.+ assert "sys.exit(unsloth_cli.app(" in source+++@requires_this_checkout_installed+def test_the_advertised_module_route_ignores_a_shadowing_directory(tmp_path):+ """`-m` resolves the package before __main__.py runs, so -I is load bearing.++ A shell sitting in a directory that has an `unsloth_cli` folder is not exotic:+ it is anyone standing in an unsloth checkout. Without -I that copy wins and the+ printed recovery command drives the wrong install, which nothing inside+ __main__.py can detect or undo.+ """+ shadow = tmp_path / "unsloth_cli"+ shadow.mkdir()+ (shadow / "__init__.py").write_text("app = None\n", encoding = "utf-8")+ (shadow / "__main__.py").write_text("print('SHADOWED')\n", encoding = "utf-8")++ plain = subprocess.run(+ [sys.executable, "-m", "unsloth_cli", "--version"],+ capture_output = True,+ timeout = 120,+ cwd = tmp_path,+ )+ assert (+ b"SHADOWED" in plain.stdout+ ), "the shadowing fixture did not take effect, so the case below proves nothing"++ isolated = _run([sys.executable, "-X", "utf8", "-I", "-m", "unsloth_cli", "--version"])+ assert isolated.returncode == 0, isolated.stderr.decode("utf-8", "replace")+ assert isolated.stdout.startswith(b"unsloth "), isolated.stdout+++def test_every_advertised_module_route_is_isolated():+ """Runs everywhere: the commands we print must not lose their -I.++ Source-contract, because they live in hint text rather than in code we can call,+ and a copy that drops the flag reintroduces the shadowing silently.++ Only the three that name the MANAGED interpreter. -I implies -s, so it hides a+ `pip install --user` install from itself; __main__.py's docstring documents that+ case and offers the -c bootstrap instead, so it is not held to this rule.+ """+ advertised = {+ "studio/backend/routes/auth.py",+ "studio/backend/run.py",+ "install.ps1",+ }+ for name in sorted(advertised):+ source = (_REPO_ROOT / name).read_text(encoding = "utf-8")+ for line in source.splitlines():+ if "-m unsloth_cli" not in line:+ continue+ # click prints its own `Usage: python -m unsloth_cli` when prog_name is+ # missing; that is the symptom being described, not a command we offer.+ if "Usage:" in line:+ continue+ assert "-I -m unsloth_cli" in line, f"{name}: unisolated module route: {line.strip()}"+++def test_the_module_docstring_documents_the_user_site_exception():+ """-I implies -s, so the advertised form cannot see a --user install.++ Measured: with the package in the user site, `python -m unsloth_cli` runs and+ `python -I -m unsloth_cli` reports "No module named unsloth_cli". Anyone hitting+ that has a launcher under %APPDATA% -- exactly the user-writable location a+ default AppLocker policy denies -- so it is the population this route exists for.+ """+ source = (_REPO_PACKAGE / "__main__.py").read_text(encoding = "utf-8")+ assert "pip install --user" in source+ assert "-I implies -s" in source+ # The escape hatch it points at has to be the real one.+ assert (+ "sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]"+ in source+ )+++@requires_console_script+@requires_this_checkout_installed+def test_safe_path_leaves_an_explicit_pythonpath_alone(tmp_path):+ """Under -P / PYTHONSAFEPATH there is no implicit entry to strip.++ Python then puts the first PYTHONPATH entry at sys.path[0], and the console+ script honours it. A filter that removed index 0 regardless would import a+ different package than the console script for the same environment, which is+ the one thing this change is not allowed to do. Measured before the guard+ existed: the console script loaded the shadow, the trampoline did not.+ """+ shadow = tmp_path / "shadow"+ (shadow / "unsloth_cli").mkdir(parents = True)+ (shadow / "unsloth_cli" / "__init__.py").write_text(+ "raise SystemExit('SHADOWED')\n", encoding = "utf-8"+ )+ env = dict(os.environ)+ env["PYTHONSAFEPATH"] = "1"+ env["PYTHONPATH"] = str(shadow)++ reference = _run(_console_argv("--version"), env = env)+ trampoline = _run(_trampoline_argv("--version"), env = env)++ assert trampoline.returncode == reference.returncode+ assert trampoline.stdout == reference.stdout+ assert trampoline.stderr == reference.stderr+++@requires_console_script+@requires_this_checkout_installed+def test_the_working_directory_is_still_stripped_without_safe_path(tmp_path):+ """The other half: the guard must not disarm the filter it guards."""+ shadow = tmp_path / "shadow"+ (shadow / "unsloth_cli").mkdir(parents = True)+ (shadow / "unsloth_cli" / "__init__.py").write_text(+ "raise SystemExit('SHADOWED')\n", encoding = "utf-8"+ )+ env = dict(os.environ)+ env.pop("PYTHONSAFEPATH", None)+ env.pop("PYTHONPATH", None)++ result = subprocess.run(+ _trampoline_argv("--version"),+ capture_output = True,+ timeout = 120,+ env = env,+ cwd = shadow,+ )+ assert result.returncode == 0, result.stderr.decode("utf-8", "replace")+ assert result.stdout.startswith(b"unsloth "), result.stdout+++def test_the_stream_reconfigure_happens_once_per_process(monkeypatch):+ """The console script reaches it twice; the streams must only move once.++ Off Windows the guard inside cannot short-circuit, because encoding = None+ deliberately keeps the caller's encoding, so the second call reconfigured a+ C-locale console again and flushed it again. Harmless, but it is a difference+ from what the console script did before this file grew a second entry route.+ """+ import unsloth_cli++ calls = []++ class _Stream:+ encoding = "ascii"++ def reconfigure(self, **kwargs):+ calls.append(kwargs)++ monkeypatch.setattr(unsloth_cli, "_streams_reconfigured", False)+ monkeypatch.setattr(unsloth_cli._sys, "stdout", _Stream())+ monkeypatch.setattr(unsloth_cli._sys, "stderr", _Stream())++ unsloth_cli._reconfigure_entry_point_streams()+ unsloth_cli._reconfigure_entry_point_streams()+ unsloth_cli._reconfigure_entry_point_streams()++ assert len(calls) == 2, f"expected one reconfigure per stream, got {calls}"diff --git a/tests/python/test_windows_installer_concurrency_guard.py b/tests/python/test_windows_installer_concurrency_guard.pyindex 7dee41767a0..9ed35eebc0e 100644--- a/tests/python/test_windows_installer_concurrency_guard.py+++ b/tests/python/test_windows_installer_concurrency_guard.py@@ -48,6 +48,13 @@ def _mutex_helpers(source: str) -> str:return "\n".join(_extract(rf" function {name} \{{.*?\n \}}\n", source)for name in (+ # Test-StudioPathEqual reports an unresolvable identity through this,+ # and these scripts run under -ErrorActionPreference Stop, so leaving it+ # out made the CATCH path throw CommandNotFound and every test that+ # reaches it fail for a reason that has nothing to do with what it+ # measures. Extracted rather than stubbed: it is self-contained, and a+ # stub would keep passing if the real call ever went wrong.+ "Write-StudioLine","Enter-StudioNamedMutex","Get-StudioFinalPath","Get-StudioPathHash",@@ -752,7 +759,7 @@ def test_guard_and_mutex_precede_rollback_and_release_after_restore():cwd_venv_move = source.index("Move-Item -LiteralPath $CwdVenv", old_venv_move)restore = source.rindex("Restore-StudioVenvRollback")prompt = source.index("Start Unsloth Studio now?", restore)- autostart = source.index("Start-Process -FilePath $UnslothExe", prompt)+ autostart = source.index("Start-Process -FilePath $VenvPython", prompt)release_runtime = source.rindex("Exit-StudioInstallMutex -Mutex $studioRuntimeMutexes[$i]")release_install = source.rindex("Exit-StudioInstallMutex -Mutex $studioInstallMutex")wait_for_exit = source.rindex("$studioAutoStartProcess.WaitForExit()")@@ -861,7 +868,7 @@ def test_runtime_gate_handoff_covers_tauri_backend_and_installer_autostart():'$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"',save,)- autostart = install_source.index("Start-Process -FilePath $UnslothExe", set_handoff)+ autostart = install_source.index("Start-Process -FilePath $VenvPython", set_handoff)restore = install_source.index("$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = $_runtimeGateHandoff",autostart,@@ -874,7 +881,9 @@ def test_runtime_gate_handoff_covers_tauri_backend_and_installer_autostart():'$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"',setup_save,)- setup_invoke = install_source.index("& $UnslothExe @studioArgs", setup_set)+ setup_invoke = install_source.index(+ "Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs", setup_set+ )setup_restore = install_source.index("$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = $previousSetupRuntimeGateHandoff",setup_invoke,@@ -901,3 +910,39 @@ def test_tauri_start_install_rejects_backend_conflicts_before_spawn():external_guard = body.index("block_external_conflict(&[]).await?")spawn = body.index("install::run_install")assert owned_guard < external_guard < spawn+++ "helpers",+ [_mutex_helpers, _process_helpers],+ ids = ["mutex", "process"],+)+def test_the_extracted_helpers_can_call_everything_they_call(helpers):+ """Every installer function these harnesses reach must be in the harness.++ The scripts above run under -ErrorActionPreference Stop, so a helper that+ calls an installer function nobody extracted dies with CommandNotFound, and+ the test fails for a reason unrelated to what it measures. That is not+ hypothetical: Test-StudioPathEqual reports an unresolvable path identity+ through Write-StudioLine, which was missing, so both+ test_path_identity_failure_is_reported_as_unknown cases failed on Windows+ while passing nowhere they could be noticed.++ Runs on every platform, unlike the scripts themselves, so the harness cannot+ drift out of step again where only a Windows runner would see it.+ """+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ extracted = helpers(source)+ # Every top-level installer function, i.e. everything the harness COULD be+ # missing. A call to a cmdlet or to a function defined inside the scripts is+ # not this test's business.+ installer_functions = set(re.findall(r"^ function ([\w-]+) \{", source, flags = re.M))+ provided = set(re.findall(r"^ function ([\w-]+) \{", extracted, flags = re.M))+ assert provided, "the helper extraction produced nothing"++ called = set(re.findall(r"(?<![\w-])([A-Z][\w]*-[\w-]+)", extracted))+ missing = sorted((called & installer_functions) - provided)+ assert not missing, (+ f"{helpers.__name__} extracts functions that call {missing}, which the "+ "harness never defines; add them to the extraction list"+ )diff --git a/tests/python/test_windows_setup_output_encoding.py b/tests/python/test_windows_setup_output_encoding.pyindex 99e1e051f3c..27bd973fed8 100644--- a/tests/python/test_windows_setup_output_encoding.py+++ b/tests/python/test_windows_setup_output_encoding.py@@ -447,15 +447,21 @@ def test_entry_scripts_bind_a_utf8_writer_when_there_is_no_console(path: Path) -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.+def test_managed_cli_command_uses_the_utf8_switch_not_just_env() -> None:+ """The managed CLI children must force UTF-8 on the command line.- https://docs.python.org/3/using/cmdline.html#cmdoption-I+ Every Windows spawn of the CLI now goes through build_managed_cli_command in+ process.rs, so that is where the switch has to be; update.rs only calls it.+ The env vars alone are not enough: a caller that already exports+ PYTHONIOENCODING wins over the ones set beside the spawn, and the Rust+ readers decode as UTF-8 regardless. -X utf8 is not overridable that way.++ https://docs.python.org/3/using/cmdline.html#cmdoption-X"""- source = (REPO_ROOT / "studio" / "src-tauri" / "src" / "update.rs").read_text(encoding = "utf-8")+ source = (REPO_ROOT / "studio" / "src-tauri" / "src" / "process.rs").read_text(encoding = "utf-8")assert re.search(r'"-X"\s*,\s*"utf8"', source- ), "isolated Python child needs -X utf8, env vars are ignored"+ ), "the managed CLI child needs -X utf8, not just the env vars"@pytest.mark.parametrize(diff --git a/tests/python/test_windows_studio_update_launcher.py b/tests/python/test_windows_studio_update_launcher.pyindex d03aee13478..535bf56bbac 100644--- a/tests/python/test_windows_studio_update_launcher.py+++ b/tests/python/test_windows_studio_update_launcher.py@@ -6,6 +6,8 @@from __future__ import annotationsimport importlib.util+import inspect+import shutilimport subprocessimport sysimport types@@ -87,6 +89,16 @@ def _configure_windows(monkeypatch.setattr(studio, "_windows_hidden_subprocess_kwargs", lambda: {})monkeypatch.setattr(studio, "_refresh_desktop_shortcuts", lambda **_kwargs: None)monkeypatch.setattr(studio, "_fail_if_install_damaged", lambda: None)+ # The runtime gate's process scan is Windows-only, so off Windows it never runs and+ # nothing here noticed it was unstubbed. On a real Windows host it shells out to+ # powershell.exe through the same subprocess.run these tests replace, then reads+ # .stdout off a fake that only carries a returncode, and every test in this file+ # dies before reaching what it meant to assert.+ monkeypatch.setattr(+ studio._studio_runtime_gate,+ "ensure_managed_environment_is_idle",+ lambda *_args, **_kwargs: None,+ )monkeypatch.setattr(studio, "STUDIO_HOME", tmp_path / "studio_home")for name in ("SKIP_STUDIO_BASE",@@ -576,3 +588,641 @@ def test_a_failed_move_aside_warns_that_unsloth_may_not_upgrade(# The backup still succeeded, so this is the move-aside failure alone.assert "could not back up" not in errassert seen["backup"] == ORIGINAL_LAUNCHER+++# ── Application Control (issue #8490) ─────────────────────────────────+#+# Windows can deny the generated, unsigned unsloth.exe while the signed+# python.exe beside it still runs. The launcher --version probe is then+# impossible, and reading that as "the update broke" rolled a perfectly good+# install back on every single update.+++def _blocked_exe_run(interpreter_result, calls = None):+ """subprocess.run where only the launcher is denied by policy."""++ def run(argv, **kwargs):+ if calls is not None:+ calls.append((argv, kwargs))+ if str(argv[0]).endswith("unsloth.exe"):+ error = OSError(13, "An Application Control policy has blocked this file")+ error.winerror = 1260+ raise error+ return interpreter_result(argv, **kwargs)++ return run+++def test_a_policy_blocked_launcher_falls_back_to_the_interpreter(monkeypatch, studio, tmp_path):+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)+ calls = []+ monkeypatch.setattr(+ studio.subprocess,+ "run",+ _blocked_exe_run(lambda argv, **_kwargs: types.SimpleNamespace(returncode = 0), calls),+ )++ _update(studio)++ assert launcher.read_bytes() == ORIGINAL_LAUNCHER+ # A successful update cleans its recovery copies up; a rollback would keep them.+ assert not (scripts / "unsloth.exe.update-backup").exists()+ assert not (scripts / "unsloth.exe.update-stale").exists()++ assert calls[0][0] == [str(launcher), "--version"]+ interpreter_call = calls[1][0]+ # Spelled out rather than imported, so an edit to the constant fails here.+ # -I here and nowhere else in this module: this probe predicts the desktop+ # updater's launch, and build_update_command runs that under+ # Isolation::Isolated with PYTHONHOME/PYTHONPATH cleared. A probe that+ # inherited them could be answered by a foreign checkout on PYTHONPATH and+ # would keep an update the next launch cannot start. -X utf8 precedes -I+ # because -I implies -E, which drops PYTHONUTF8 but cannot touch a+ # command-line -X.+ assert interpreter_call == [+ str(scripts / "python.exe"),+ "-X",+ "utf8",+ "-I",+ "-c",+ "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "+ "sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())",+ "--version",+ ]+ # The launcher probe gets 10s, a process start. This one has to import the whole+ # CLI package first, so it gets the import probe's ceiling instead.+ assert calls[0][1]["timeout"] == 10+ assert calls[1][1]["timeout"] == studio._MANAGED_CLI_IMPORT_PROBE_TIMEOUT+ assert calls[1][1]["timeout"] > calls[0][1]["timeout"]+++def test_a_policy_block_with_a_broken_package_still_fails(monkeypatch, studio, tmp_path):+ """The fallback must not become a blanket "assume it worked"."""+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)+ monkeypatch.setattr(+ studio.subprocess,+ "run",+ _blocked_exe_run(lambda argv, **_kwargs: types.SimpleNamespace(returncode = 3)),+ )++ with pytest.raises(studio.typer.Exit):+ _update(studio)++ assert launcher.read_bytes() == ORIGINAL_LAUNCHER+ assert (scripts / "unsloth.exe.update-backup").exists()+++def test_a_policy_block_with_no_interpreter_reports_the_block(+ monkeypatch, studio, tmp_path, capsys+):+ """Nothing left to ask: say what Windows said rather than inventing a cause."""+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)+ (scripts / "python.exe").unlink()+ monkeypatch.setattr(+ studio, "_run_setup_script", lambda **_kwargs: launcher.write_bytes(b"MZ-new")+ )+ monkeypatch.setattr(+ studio.subprocess,+ "run",+ _blocked_exe_run(lambda argv, **_kwargs: types.SimpleNamespace(returncode = 0)),+ )++ with pytest.raises(studio.typer.Exit):+ _update(studio)++ assert "Application Control policy" in capsys.readouterr().err+++def test_an_ordinary_launcher_oserror_is_still_a_failure(monkeypatch, studio, tmp_path):+ """Parity guard: only 1260 takes the new path, everything else is unchanged."""+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)+ interpreter_calls = []++ def run(argv, **_kwargs):+ if str(argv[0]).endswith("unsloth.exe"):+ error = OSError(13, "Access is denied")+ error.winerror = 5+ raise error+ interpreter_calls.append(argv)+ return types.SimpleNamespace(returncode = 0)++ monkeypatch.setattr(studio.subprocess, "run", run)++ with pytest.raises(studio.typer.Exit):+ _update(studio)++ assert interpreter_calls == [], "a non-policy error must not consult the interpreter"+ assert launcher.read_bytes() == ORIGINAL_LAUNCHER+ assert (scripts / "unsloth.exe.update-backup").exists()+++def test_the_policy_block_helper_only_matches_1260(studio):+ blocked = OSError(13, "blocked")+ blocked.winerror = 1260+ assert studio._is_application_control_block(blocked)++ denied = OSError(13, "denied")+ denied.winerror = 5+ assert not studio._is_application_control_block(denied)++ # POSIX OSError has no winerror at all.+ assert not studio._is_application_control_block(OSError(13, "denied"))+++def test_a_quarantined_away_launcher_falls_back_to_the_interpreter(monkeypatch, studio, tmp_path):+ """Quarantine removes the unsigned stub rather than denying it.++ There is then nothing to run and nothing to put back, and reading that as a+ broken update rolls a good one back exactly as the denial case did. The+ launcher stays gone, which is fine: nothing executes it any more.+ """+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)+ calls = []+ monkeypatch.setattr(studio.subprocess, "run", _successful_version_run(calls))++ _update(studio)++ assert not launcher.exists()+ assert not (scripts / "unsloth.exe.update-backup").exists()+ # Only the interpreter was asked; there was no file to probe.+ assert [call[0][0] for call in calls] == [str(scripts / "python.exe")]+++def test_only_the_updater_probe_isolates_the_interpreter(studio, tmp_path):+ """Isolation is opt-in, and exactly one caller opts in.++ Every other managed invocation has to stay byte-for-byte what the console+ script did, and -I implies -E and -s: PYTHONPATH, PYTHONWARNINGS,+ PYTHONHASHSEED and user site-packages all stop being honoured. That is an+ observable difference on a machine with no policy at all, so the default+ inherits and only the probe standing in for an already-isolated launch asks+ for it. Mirrors only_the_isolated_flavour_carries_the_isolation_flag in+ studio/src-tauri/src/process.rs.+ """+ python = tmp_path / "python.exe"++ inherited = studio._managed_cli_argv(python, "--version")+ assert inherited[:3] == [str(python), "-X", "utf8"]+ assert "-I" not in inherited++ isolated = studio._managed_cli_argv(python, "--version", isolated = True)+ # -X utf8 first: -I implies -E, so PYTHONUTF8 would be discarded, while a+ # command-line -X survives it.+ assert isolated[:4] == [str(python), "-X", "utf8", "-I"]++ # Isolation is the only difference. Same trampoline, same caller arguments,+ # in the same order.+ assert [arg for arg in isolated if arg != "-I"] == inherited+++def test_a_quarantined_away_launcher_with_a_broken_package_still_fails(+ monkeypatch, studio, tmp_path+):+ """Parity guard: absence excuses the launcher, never the update."""+ _configure_windows(monkeypatch, studio, tmp_path, launcher = None)+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)+ monkeypatch.setattr(+ studio.subprocess,+ "run",+ lambda argv, **_kwargs: types.SimpleNamespace(returncode = 3),+ )++ with pytest.raises(studio.typer.Exit):+ _update(studio)+++def test_a_restorable_launcher_is_restored_before_the_interpreter_is_asked(+ monkeypatch, studio, tmp_path+):+ """Absence is only excused once recovery has failed.++ A healthy CLI must not let a launcher that could have been put back stay+ missing, or an ordinary no-op update on an unpoliced machine would quietly+ strip the console script.+ """+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)+ monkeypatch.setattr(studio.subprocess, "run", _successful_version_run())++ _update(studio)++ assert launcher.read_bytes() == ORIGINAL_LAUNCHER+++def test_the_package_answers_for_a_quarantined_console_script(monkeypatch, studio, tmp_path):+ """What `studio run` checks instead of the deleted stub, and only on Windows.++ The layout is the fallback for one specific no-verdict case, a probe that+ timed out, so that is what is simulated here. A probe that could not START+ the interpreter is a different answer and is covered separately: the re-exec+ runs that same interpreter, so the layout cannot excuse it.+ """+ scripts = tmp_path / "Scripts"+ site_packages = tmp_path / "Lib" / "site-packages"+ scripts.mkdir(parents = True)+ site_packages.mkdir(parents = True)+ python = scripts / "python.exe"+ python.write_bytes(b"python")++ def timed_out(*_args, **_kwargs):+ raise subprocess.TimeoutExpired(cmd = "probe", timeout = 60)++ monkeypatch.setattr(studio.subprocess, "run", timed_out)+ monkeypatch.setattr(studio.platform, "system", lambda: "Windows")+ assert not studio._managed_cli_package_present(python)++ (site_packages / "unsloth_cli").mkdir()+ assert studio._managed_cli_package_present(python)++ # An editable install leaves a .pth and no unsloth_cli/ here.+ (site_packages / "unsloth_cli").rmdir()+ (site_packages / "unsloth-2026.8.1.dist-info").mkdir()+ assert studio._managed_cli_package_present(python)++ # POSIX proves a CLI with the console script itself; nothing changes there.+ monkeypatch.setattr(studio.platform, "system", lambda: "Linux")+ assert not studio._managed_cli_package_present(python)++[email protected](scope = "module")+def real_venv(tmp_path_factory):+ """A real, empty interpreter to ask, rather than a file named python.exe.++ Built without pip so site-packages starts genuinely empty; the layout is+ POSIX here, which is the point -- the check must come from the interpreter,+ not from guessing at Lib\\site-packages.+ """+ root = tmp_path_factory.mktemp("managed_cli_probe") / "venv"+ try:+ subprocess.run(+ [sys.executable, "-m", "venv", "--without-pip", str(root)],+ check = True,+ capture_output = True,+ timeout = 300,+ )+ except (OSError, subprocess.SubprocessError) as exc: # pragma: no cover+ pytest.skip(f"could not build a probe venv: {exc}")+ python = root / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")+ assert python.is_file()+ site_packages = next(iter(root.glob("lib/python*/site-packages")), None) or (+ root / "Lib" / "site-packages"+ )+ return python, site_packages+++def test_orphaned_install_metadata_is_not_a_runnable_cli(monkeypatch, studio, real_venv):+ """Metadata is not an importable package, and this gate cannot accept it.++ An interrupted install, or an editable install whose checkout has since+ moved, leaves an ``unsloth-*.dist-info`` behind with nothing to import. This+ check stands in front of the headless-public strip of .bootstrap_password,+ so answering yes here lands exactly the lockout the gate's placement exists+ to prevent: a public Studio with no login page and no recovery credential.+ """+ python, site_packages = real_venv+ windows_layout = python.parent.parent / "Lib" / "site-packages"+ windows_layout.mkdir(parents = True, exist_ok = True)+ (windows_layout / "unsloth-2026.8.1.dist-info").mkdir(exist_ok = True)++ monkeypatch.setattr(studio.platform, "system", lambda: "Windows")+ assert not (site_packages / "unsloth_cli").exists(), "the probe venv must start empty"+ assert not studio._managed_cli_package_present(python)+++def test_an_importable_package_still_answers_for_the_quarantined_stub(+ monkeypatch, studio, real_venv+):+ """The quarantine case this fallback exists for keeps working.++ Same venv as above, now with something the interpreter can actually resolve.+ """+ python, site_packages = real_venv+ package = site_packages / "unsloth_cli"+ package.mkdir(parents = True, exist_ok = True)+ (package / "__init__.py").write_text("app = None\n", encoding = "utf-8")++ monkeypatch.setattr(studio.platform, "system", lambda: "Windows")+ assert studio._managed_cli_package_present(python)++ # And POSIX is untouched: there the console script is what gets exec'd.+ monkeypatch.setattr(studio.platform, "system", lambda: "Linux")+ assert not studio._managed_cli_package_present(python)+++def bare_probe_venv(real_venv):+ """The module venv with any unsloth_cli left by a neighbouring test removed.++ These cases each install their own shape of broken package, so they cannot+ inherit one, and they must not leave one behind either.+ """+ python, site_packages = real_venv+ package = site_packages / "unsloth_cli"+ shutil.rmtree(package, ignore_errors = True)+ yield python, site_packages+ shutil.rmtree(package, ignore_errors = True)+++ "shape, files",+ [+ # An emptied directory. find_spec calls this a namespace package and+ # returns a spec for it, so a spec lookup answers yes to a venv the+ # trampoline's `from unsloth_cli import app` cannot start. This is the+ # shape antivirus leaves when it takes the module files out from under a+ # package it decided it disliked.+ ("an emptied package directory", {}),+ # An interrupted install: the package landed, its dependencies did not.+ (+ "a package whose imports are missing",+ {"__init__.py": "import unsloth_cli_missing_dep\n"},+ ),+ # A partially written __init__ that imports but has no app to hand back.+ ("a package with no app attribute", {"__init__.py": "VERSION = '1'\n"}),+ # An __init__ that raises on import, which no spec lookup ever executes.+ (+ "a package whose import raises",+ {"__init__.py": "raise RuntimeError('half installed')\n"},+ ),+ ],+)+def test_a_package_the_trampoline_cannot_import_is_not_a_runnable_cli(+ monkeypatch, studio, bare_probe_venv, shape, files+):+ """The gate has to fail on everything the launch would fail on.++ It stands in front of the headless-public strip of .bootstrap_password, so a+ yes here that the trampoline then contradicts is a public Studio with no+ login page and no plaintext recovery credential. Locating the package is not+ the question; importing it and getting `app` back is, which is why the probe+ runs that exact import rather than a cheaper find_spec.+ """+ python, site_packages = bare_probe_venv+ package = site_packages / "unsloth_cli"+ package.mkdir(parents = True)+ for name, body in files.items():+ (package / name).write_text(body, encoding = "utf-8")++ monkeypatch.setattr(studio.platform, "system", lambda: "Windows")+ assert not studio._managed_cli_package_present(+ python+ ), f"{shape} must not pass the gate: the trampoline cannot start it"++ # Anti-vacuity: the same venv with a package that does import passes, so the+ # assertion above is about the shape and not about the fixture being broken.+ (package / "__init__.py").write_text("app = None\n", encoding = "utf-8")+ assert studio._managed_cli_package_present(python)+++def test_a_probe_that_cannot_start_the_interpreter_fails_closed(monkeypatch, studio, tmp_path):+ """No verdict is not the same as no problem, and the two causes differ.++ The re-exec this gate stands in front of runs the same interpreter, so an+ interpreter that will not start means the re-exec will not either, and the+ on-disk layout cannot say otherwise. The caller strips .bootstrap_password+ before that re-exec on a headless public launch, so passing here would leave+ a public Studio with no login page and no plaintext recovery credential.+ """+ scripts = tmp_path / "Scripts"+ site_packages = tmp_path / "Lib" / "site-packages"+ scripts.mkdir(parents = True)+ (site_packages / "unsloth_cli").mkdir(parents = True)+ python = scripts / "python.exe"+ python.write_bytes(b"python")+ monkeypatch.setattr(studio.platform, "system", lambda: "Windows")++ # The layout says yes, so any pass below is the fallback and not the layout+ # being empty.+ assert studio._managed_cli_site_packages_layout(python)++ def blocked(*_args, **_kwargs):+ raise OSError(1260, "An Application Control policy has blocked this file")++ monkeypatch.setattr(studio.subprocess, "run", blocked)+ assert not studio._managed_cli_package_present(python)++ # A timeout is the other kind of no verdict, and it keeps the fallback: slow+ # is not broken, a cold venv under an antivirus scan is exactly this, and the+ # re-exec has no timeout of its own to trip over.+ def slow(*_args, **_kwargs):+ raise subprocess.TimeoutExpired(cmd = "probe", timeout = 60)++ monkeypatch.setattr(studio.subprocess, "run", slow)+ assert studio._managed_cli_package_present(python)+++def test_the_interpreter_fallback_waits_as_long_as_the_import_probe(studio):+ """--version through the trampoline is an import, not a process start.++ The launcher's 10 seconds is sized for spawning a built executable. Here the+ same call has to import the whole CLI package, which is the work the import+ probe's ceiling is deliberately generous for, and under the antivirus scan+ that produced the quarantine this path exists to survive, the short ceiling+ would call a healthy update broken and roll it back once per candidate.+ """+ transaction = studio._WindowsLauncherUpdateTransaction+ source = inspect.getsource(transaction._interpreter_health_error)+ assert "_MANAGED_CLI_IMPORT_PROBE_TIMEOUT" in source+ assert "_VERSION_TIMEOUT_SECONDS" not in source+ # And the two are actually different, so the assertion above is not vacuous.+ assert studio._MANAGED_CLI_IMPORT_PROBE_TIMEOUT > transaction._VERSION_TIMEOUT_SECONDS+++def test_a_custom_root_survives_the_launcher_being_quarantined(monkeypatch, studio, tmp_path):+ """The sentinel decides which installation every studio command manages.++ Only install.sh writes share/studio.conf, so on a custom-root Windows+ install the generated unsloth.exe was the only sentinel there was. Quarantine+ deletes it, root inference then falls back to ~/.unsloth/studio, and the CLI+ reads and writes the wrong tree while reporting success. The .cmd shim is+ written by the same installer for the same directory and answers the same+ question.+ """+ root = tmp_path / "custom-root"+ (root / "bin").mkdir(parents = True)+ monkeypatch.setattr(studio.platform, "system", lambda: "Windows")++ assert not studio._looks_like_installer_managed_studio_home(root)++ shim = root / "bin" / "unsloth.cmd"+ shim.write_bytes(+ b"@echo off\r\nrem unsloth-studio-managed-launcher\r\n"+ b'"%~dp0..\\unsloth_studio\\Scripts\\python.exe" -X utf8 -c "from unsloth_cli import app" %*\r\n'+ )+ assert studio._looks_like_installer_managed_studio_home(root)++ # The launcher still answers on its own, so an install that never lost it is+ # unaffected either way.+ shim.unlink()+ (root / "bin" / "unsloth.exe").write_bytes(b"MZ")+ assert studio._looks_like_installer_managed_studio_home(root)+++ "label, body",+ [+ # This decides which tree the CLI manages and the directory is on PATH,+ # so any file of that name would otherwise be enough to redirect a root.+ ("a hand-rolled wrapper", b'@echo off\r\npython -c "from unsloth_cli import app" %*\r\n'),+ ("the marker without the call", b"@echo off\r\nrem unsloth-studio-managed-launcher\r\n"),+ ("an unrelated batch file", b"@echo off\r\necho hello\r\n"),+ ("empty", b""),+ ],+)+def test_only_the_installers_own_cmd_shim_marks_a_root(monkeypatch, studio, tmp_path, label, body):+ root = tmp_path / "root"+ (root / "bin").mkdir(parents = True)+ (root / "bin" / "unsloth.cmd").write_bytes(body)+ monkeypatch.setattr(studio.platform, "system", lambda: "Windows")++ assert not studio._looks_like_installer_managed_studio_home(+ root+ ), f"{label} must not stand in for the installer's own shim"+++def test_an_oversized_cmd_shim_is_not_read_into_memory(monkeypatch, studio, tmp_path):+ """Same 8 KB ceiling Test-UnslothCmdShimFile and the uninstaller apply."""+ root = tmp_path / "root"+ (root / "bin").mkdir(parents = True)+ shim = root / "bin" / "unsloth.cmd"+ shim.write_bytes(+ b"rem unsloth-studio-managed-launcher\r\nfrom unsloth_cli import app\r\n" + b"x" * 9000+ )+ monkeypatch.setattr(studio.platform, "system", lambda: "Windows")++ assert not studio._looks_like_installer_managed_studio_home(root)+++def test_posix_root_inference_is_unchanged(monkeypatch, studio, tmp_path):+ """A .cmd means nothing off Windows, and the console script still answers."""+ root = tmp_path / "root"+ (root / "bin").mkdir(parents = True)+ (root / "bin" / "unsloth.cmd").write_bytes(+ b"rem unsloth-studio-managed-launcher\r\nfrom unsloth_cli import app\r\n"+ )+ monkeypatch.setattr(studio.platform, "system", lambda: "Linux")++ assert not studio._looks_like_installer_managed_studio_home(root)+ (root / "bin" / "unsloth").write_text("#!/bin/sh\n", encoding = "utf-8")+ assert studio._looks_like_installer_managed_studio_home(root)+++def test_the_import_probe_performs_the_trampolines_own_import(studio):+ """A spec lookup here would answer a different question than the launch asks.++ Pinned as a source contract because the two failures it prevents are silent:+ an empty directory and a raising __init__ both resolve as specs, and both+ give the gate a yes the launch immediately contradicts.+ """+ assert "from unsloth_cli import app" in studio._MANAGED_CLI_IMPORT_PROBE+ assert "find_spec" not in studio._MANAGED_CLI_IMPORT_PROBE+++def test_the_import_probe_scrubs_the_cwd_exactly_as_the_trampoline_does(studio):+ """A drift here would let a checkout in the caller's cwd answer for the venv.++ `-c` puts the cwd on sys.path[0]; the trampoline drops it, so a probe that+ did not would report a CLI the launch cannot then import.+ """+ scrub = (+ "import sys, os; sys.path[:1] = [x for x in sys.path[:1] "+ "if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "+ )+ assert studio._WINDOWS_CLI_ENTRYPOINT.startswith(scrub)+ assert studio._MANAGED_CLI_IMPORT_PROBE.startswith(scrub)+++def test_a_candidate_that_vanishes_mid_copy_does_not_stop_the_next_one(+ monkeypatch, studio, tmp_path+):+ """The header check and the copy open the file separately.++ Antivirus taking the first candidate in that gap says nothing about the rest,+ and giving up there turned a recoverable install into a failed update.+ """+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)+ backup = scripts / "unsloth.exe.update-backup"+ legacy = scripts / "unsloth.exe.deleteme"+ backup.write_bytes(b"MZ-backup")+ legacy.write_bytes(ORIGINAL_LAUNCHER)++ real_copy = studio._WindowsLauncherUpdateTransaction._atomic_copy++ def flaky_copy(source, destination):+ if source == backup:+ raise OSError(5, "Access is denied")+ return real_copy(source, destination)++ monkeypatch.setattr(+ studio._WindowsLauncherUpdateTransaction, "_atomic_copy", staticmethod(flaky_copy)+ )+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)+ monkeypatch.setattr(studio.subprocess, "run", _successful_version_run())++ _update(studio)++ assert launcher.read_bytes() == ORIGINAL_LAUNCHER, "the second candidate was never tried"+++def test_every_candidate_failing_is_still_an_error(monkeypatch, studio, tmp_path, capsys):+ """Parity guard: trying them all must not become swallowing them all."""+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)+ (scripts / "unsloth.exe.update-backup").write_bytes(b"MZ-backup")++ def always_fails(source, destination):+ raise OSError(5, "Access is denied")++ monkeypatch.setattr(+ studio._WindowsLauncherUpdateTransaction, "_atomic_copy", staticmethod(always_fails)+ )+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)+ monkeypatch.setattr(studio.subprocess, "run", _successful_version_run())++ with pytest.raises(studio.typer.Exit):+ _update(studio)++ assert "could not recover" in capsys.readouterr().err+++def test_an_unrecoverable_launcher_keeps_its_recovery_copies(monkeypatch, studio, tmp_path):+ """Judged healthy through the interpreter is not the same as repaired.++ When every restore attempt failed, the copies are the only material a later+ run has. Deleting them on the way out of a "successful" update would make the+ next one unrecoverable.+ """+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)+ backup = scripts / "unsloth.exe.update-backup"+ backup.write_bytes(ORIGINAL_LAUNCHER)++ def always_fails(source, destination):+ raise OSError(5, "Access is denied")++ monkeypatch.setattr(+ studio._WindowsLauncherUpdateTransaction, "_atomic_copy", staticmethod(always_fails)+ )+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)+ monkeypatch.setattr(studio.subprocess, "run", _successful_version_run())++ with pytest.raises(studio.typer.Exit):+ _update(studio)++ assert backup.exists(), "the only recovery copy was deleted"+++def test_a_restored_launcher_still_cleans_up(monkeypatch, studio, tmp_path):+ """Parity guard: keeping copies must not become never cleaning up."""+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)+ monkeypatch.setattr(studio.subprocess, "run", _successful_version_run())++ _update(studio)++ assert launcher.read_bytes() == ORIGINAL_LAUNCHER+ assert not (scripts / "unsloth.exe.update-backup").exists()+ assert not (scripts / "unsloth.exe.update-stale").exists()+ assert not (scripts / "unsloth.exe.deleteme").exists()diff --git a/tests/studio/test_application_control_cli_fallback.ps1 b/tests/studio/test_application_control_cli_fallback.ps1new file mode 100644index 00000000000..a61381f60e5--- /dev/null+++ b/tests/studio/test_application_control_cli_fallback.ps1@@ -0,0 +1,638 @@+#!/usr/bin/env pwsh+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# The installer must not depend on the generated unsloth.exe console script (#8490).+#+# On Windows, packaging materializes `unsloth = unsloth_cli:app` as an unsigned launcher .exe.+# AppLocker, WDAC and Smart App Control deny it while the venv's python.exe -- a copy of the+# signed CPython binary -- still runs, so the install died at "running unsloth studio setup"+# with no exit code to report and no diagnostic worth reading.+#+# These checks pin the three things that fix has to get right: the failure is classified off the+# exception (1260), never off $LASTEXITCODE, which no process was created to set; the CLI is+# reached through the interpreter with the trampoline intact as ONE argument; and the .cmd+# companion is byte-stable, so a re-run rewrites nothing.+# Run: pwsh -NoProfile -File tests/studio/test_application_control_cli_fallback.ps1++$ErrorActionPreference = "Stop"+$repo = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path+$install = Join-Path $repo "install.ps1"++# The one canonical spelling, repeated in install.ps1, studio/src-tauri/src/process.rs and+# unsloth_cli/commands/studio.py. Written out here rather than read from any of them, so a+# silent edit on any side fails a check instead of being copied into the expectation. Both+# halves are load bearing; the rationale is on WINDOWS_CLI_ENTRYPOINT in process.rs.+# Written out for the same reason as the trampoline: an edit on either side has to fail a+# check rather than be copied into the expectation. This one gates a recursive delete.+$ShimMarker = "unsloth-studio-managed-launcher"+$Trampoline = "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())"++function Get-FunctionText {+ param([string] $Path, [string] $Name)+ $tokens = $null; $errors = $null+ $ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$tokens, [ref]$errors)+ if ($errors) { $errors | ForEach-Object { $_.ToString() }; throw "$Path has parse errors" }+ $fn = $ast.FindAll({ param($n)+ $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $Name+ }, $true)+ if ($fn.Count -ne 1) { throw "expected exactly one $Name in $Path, found $($fn.Count)" }+ return $fn[0].Extent.Text+}++# Every installer function the extracted ones call has to be in the harness, or a+# code path that reaches it dies with CommandNotFound and the check above it passes+# for the wrong reason. Exactly that shipped twice: Write-StudioLine missing from the+# mutex harness in tests/python, and Test-UnslothCmdShimFile missing from Invoke-Write+# below the moment the writer started asking it.+function Assert-HarnessComplete {+ param([string] $Extracted, [string[]] $Provided, [string] $Label)+ $installerFunctions = @([regex]::Matches(+ (Get-Content -Raw -LiteralPath $install), '(?m)^ function ([\w-]+) \{'+ ) | ForEach-Object { $_.Groups[1].Value })+ $called = @([regex]::Matches($Extracted, '(?<![\w-])([A-Z][\w]*-[\w-]+)') |+ ForEach-Object { $_.Groups[1].Value } | Sort-Object -Unique)+ $missing = @($called | Where-Object { $installerFunctions -contains $_ -and $Provided -notcontains $_ })+ Check "$Label harness defines everything it calls" ($missing.Count -eq 0)+ if ($missing.Count -gt 0) { Write-Host " missing: $($missing -join ', ')" }+}++$failures = 0+function Check($name, $cond) {+ if ($cond) { Write-Host " PASS $name" }+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }+}++$blockFn = Get-FunctionText $install "Test-ApplicationControlBlock"+$cmdlineFn = Get-FunctionText $install "Get-ManagedUnslothCliCommandLine"+$invokeFn = Get-FunctionText $install "Invoke-ManagedUnslothCli"+$relFn = Get-FunctionText $install "Get-RelativeShimPath"+$contentFn = Get-FunctionText $install "Get-UnslothCmdShimContent"+$writeFn = Get-FunctionText $install "Write-UnslothCmdShim"+$probeFn = Get-FunctionText $install "Test-ShimLaunchBlocked"+$shimFileFn = Get-FunctionText $install "Test-UnslothCmdShimFile"+$preferFn = Get-FunctionText $install "Test-UnslothCmdShimPreferred"++# An empty or wrong extraction would make every case below pass vacuously.+Check "extraction kept the policy code" ($blockFn -match '1260')+Check "extraction kept the utf8 pin" ($cmdlineFn -match '-X')+Check "extraction kept the classifier call" ($invokeFn -match 'Test-ApplicationControlBlock')+Check "extraction kept the walk-up" ($relFn -match '\.\.')+Check "extraction kept the dp0 prefix" ($contentFn -match '%~dp0')+Check "extraction kept the compare" ($writeFn -match 'Compare-Object \$existing \$desired')+Check "extraction kept the probe start" ($probeFn -match 'ProcessStartInfo')+Check "extraction kept the content marker" ($shimFileFn -match 'from unsloth_cli import app')+Check "extraction kept the exe test" ($preferFn -match 'ShimExe')++# The whole point of the classifier: the value it must NOT consult.+Check "the classifier never reads LASTEXITCODE" (-not ($blockFn -match 'LASTEXITCODE'))+# ...and the invoker must not treat a missing process as exit code 0.+Check "a blocked launch is not an exit code" ($invokeFn -match '\$script:ManagedUnslothCliExit = \$null')+Check "a non-policy launch failure rethrows" ($invokeFn -match 'if \(-not \(Test-ApplicationControlBlock \$_\)\) \{ throw \}')++# --- Test-ApplicationControlBlock -----------------------------------------------------------+# The real shape: PowerShell wraps the CreateProcess failure, so the 1260 is only reachable by+# walking InnerException. A classifier that inspects only the outer exception sees nothing.+function Invoke-Block {+ param($Record)+ $sb = [scriptblock]::Create(@"+param(`$Record)+$blockFn+Test-ApplicationControlBlock `$Record+"@)+ return (& $sb $Record)+}++function New-Win32 {+ param([int] $Code)+ return (New-Object System.ComponentModel.Win32Exception($Code))+}++function New-Record {+ param([Exception] $Exception)+ return (New-Object System.Management.Automation.ErrorRecord(+ $Exception, "NativeCommandFailed", [System.Management.Automation.ErrorCategory]::ResourceUnavailable, $null))+}++Write-Host "an Application Control block is recognised wherever PowerShell buried it"+Check "bare Win32Exception 1260" (Invoke-Block (New-Win32 1260))+Check "wrapped once" (Invoke-Block (New-Object System.Exception("outer", (New-Win32 1260))))+Check "wrapped twice" (Invoke-Block (New-Object System.Exception("a", (New-Object System.Exception("b", (New-Win32 1260))))))+Check "inside an ErrorRecord" (Invoke-Block (New-Record (New-Object System.Exception("outer", (New-Win32 1260)))))+# Some wrappers keep only the HRESULT form of the same code.+$hresultOnly = New-Object System.Exception("policy")+$hresultOnly.GetType().GetField("_HResult", "Instance,NonPublic").SetValue($hresultOnly, -2147023636)+Check "HRESULT 0x800704EC only" (Invoke-Block $hresultOnly)+Check "HRESULT inside an ErrorRecord" (Invoke-Block (New-Record $hresultOnly))++Write-Host "and nothing else is mistaken for one"+# 5 is ERROR_ACCESS_DENIED, the neighbouring failure Test-AccessDeniedError owns. Reporting a+# permissions problem as a security policy sends the user to the wrong administrator.+Check "access denied is not a policy block" (-not (Invoke-Block (New-Win32 5)))+Check "file not found is not a policy block" (-not (Invoke-Block (New-Win32 2)))+Check "a plain exception" (-not (Invoke-Block (New-Object System.Exception("boom"))))+Check "a plain ErrorRecord" (-not (Invoke-Block (New-Record (New-Object System.Exception("boom")))))+Check "null" (-not (Invoke-Block $null))+# 1260 as an exit code is a program's own choice and says nothing about policy.+Check "an exit code of 1260 is not a block" (-not (Invoke-Block 1260))++# --- Get-ManagedUnslothCliCommandLine -------------------------------------------------------+# Start-Process joins an -ArgumentList array with spaces and quotes NOTHING, so handing it the+# trampoline as an array element gives python eleven arguments instead of one. This builds the+# command line itself.+function Invoke-CommandLine {+ param([string[]] $Arguments = @())+ $sb = [scriptblock]::Create(@"+param(`$Arguments)+`$script:UnslothCmdShimMarker = "$ShimMarker"+`$script:UnslothCliTrampoline = "$Trampoline"+$cmdlineFn+Get-ManagedUnslothCliCommandLine -Arguments `$Arguments+"@)+ return (& $sb $Arguments)+}++$line = Invoke-CommandLine @("studio", "-p", "8888")+Write-Host "the interpreter command line survives Start-Process"+Check "the trampoline is one quoted token" ($line.Contains('"' + $Trampoline + '"'))+Check "-X utf8 leads" ($line.StartsWith("-X utf8 "))+Check "-c follows the utf8 flag" ($line.IndexOf("-X utf8") -lt $line.IndexOf("-c"))+# -I would also discard PYTHONPATH, PYTHONWARNINGS and user site-packages, which the+# console script honours; the trampoline drops the cwd entry by itself instead.+Check "the interpreter is not isolated" (-not ($line -match '(^|\s)-I(\s|$)'))+Check "caller arguments come last" ($line.EndsWith("studio -p 8888"))+Check "no arguments still builds" ((Invoke-CommandLine).Trim().EndsWith('sys.exit(app())"'))+# Start-Process joins the line back with spaces, so an unquoted spaced argument would+# reach the child as several. Only bare subcommands are passed today; the signature is+# what invites the mistake.+$spaced = Invoke-CommandLine @("studio", "run", "--model", "C:\my models\a b.gguf")+Check "a spaced argument is quoted" ($spaced.EndsWith('studio run --model "C:\my models\a b.gguf"'))+Check "and unspaced ones are not" ($spaced -match '\srun\s--model\s')++# --- Invoke-ManagedUnslothCli ---------------------------------------------------------------+# Runs for real against this host's python3 -- the trampoline is swapped for a stub, because the+# thing under test is the plumbing (exit code, argument fidelity, output routing), not unsloth.+$python = (Get-Command python3 -ErrorAction SilentlyContinue)+if (-not $python) { $python = (Get-Command python -ErrorAction SilentlyContinue) }++function Invoke-Managed {+ param([string] $Python, [string] $Trampoline, [string[]] $Arguments = @())+ $sb = [scriptblock]::Create(@"+param(`$Python, `$Trampoline, `$Arguments)+`$script:UnslothCliTrampoline = `$Trampoline+$blockFn+$invokeFn+Invoke-ManagedUnslothCli -Python `$Python -Arguments `$Arguments+[pscustomobject]@{ Exit = `$script:ManagedUnslothCliExit }+"@)+ return (& $sb $Python $Trampoline $Arguments)+}++if ($python) {+ Write-Host "the CLI runs through the interpreter, and its exit code comes back intact"+ # Every argument after -c lands in sys.argv[1:], so this proves the caller's arguments+ # arrive unsplit AND that the exit code is the child's.+ $countArgs = 'import sys; sys.exit(len(sys.argv) - 1)'+ $r = Invoke-Managed $python.Source $countArgs @("studio", "setup", "--verbose")+ Check "argument count reaches the child" ($r[-1].Exit -eq 3)+ $r = Invoke-Managed $python.Source 'import sys; sys.exit(7)' @()+ Check "a nonzero exit is reported" ($r[-1].Exit -eq 7)+ $r = Invoke-Managed $python.Source 'import sys; sys.exit(0)' @()+ Check "a clean exit is reported as 0" ($r[-1].Exit -eq 0)+ # An argument with spaces must stay one argument.+ $r = Invoke-Managed $python.Source 'import sys; sys.exit(0 if sys.argv[1] == "a b c" else 9)' @("a b c")+ Check "a spaced argument stays whole" ($r[-1].Exit -eq 0)+ # The child's stdout must reach the caller's pipeline rather than being swallowed into a+ # return value; that is why the exit code is published in a variable instead.+ $r = Invoke-Managed $python.Source 'print("hello from the child")' @()+ Check "the child's stdout is not swallowed" (($r | Where-Object { "$_" -eq "hello from the child" }).Count -eq 1)+ Check "and the exit code is still separate" ($r[-1].Exit -eq 0)++ Write-Host "a launch failure that is not a policy block is not silently swallowed"+ $threw = $false+ try { Invoke-Managed (Join-Path ([System.IO.Path]::GetTempPath()) "unsloth-no-such-interpreter") 'pass' @() | Out-Null }+ catch { $threw = $true }+ Check "a missing interpreter rethrows" $threw+} else {+ Write-Host " SKIP interpreter checks (no python3 on this host)" -ForegroundColor Yellow+}++# --- Get-RelativeShimPath -------------------------------------------------------------------+function Invoke-Relative {+ param([string] $From, [string] $To)+ $sb = [scriptblock]::Create(@"+param(`$From, `$To)+$relFn+Get-RelativeShimPath -From `$From -To `$To+"@)+ return (& $sb $From $To)+}++Write-Host "the shim reaches the interpreter without naming the install path"+Check "sibling directory" ((Invoke-Relative "C:\Users\me\.unsloth\studio\bin" "C:\Users\me\.unsloth\studio\unsloth_studio\Scripts\python.exe") -eq "..\unsloth_studio\Scripts\python.exe")+Check "legacy .venv layout" ((Invoke-Relative "C:\s\bin" "C:\s\.venv\Scripts\python.exe") -eq "..\.venv\Scripts\python.exe")+Check "trailing separator" ((Invoke-Relative "C:\s\bin\" "C:\s\unsloth_studio\Scripts\python.exe") -eq "..\unsloth_studio\Scripts\python.exe")+Check "spaces in the path" ((Invoke-Relative "C:\Users\Jane Doe\.unsloth\studio\bin" "C:\Users\Jane Doe\.unsloth\studio\unsloth_studio\Scripts\python.exe") -eq "..\unsloth_studio\Scripts\python.exe")+Check "deeper base" ((Invoke-Relative "C:\a\b\c\bin" "C:\a\python.exe") -eq "..\..\..\python.exe")+# A venv on another volume has no relative form; the caller must fall back rather than emit junk.+Check "different volume -> null" ($null -eq (Invoke-Relative "C:\s\bin" "D:\v\Scripts\python.exe"))+Check "empty input -> null" ($null -eq (Invoke-Relative "" "C:\s\python.exe"))+# A descending range counts backwards in PowerShell, so an unguarded tail would answer+# "a\C:" here rather than refusing.+Check "target above the base -> null" ($null -eq (Invoke-Relative "C:\a\b\bin" "C:\a"))+Check "identical paths -> null" ($null -eq (Invoke-Relative "C:\a\bin" "C:\a\bin"))++# --- Get-UnslothCmdShimContent --------------------------------------------------------------+function Invoke-Content {+ param([string] $ShimDir, [string] $PythonPath)+ $sb = [scriptblock]::Create(@"+param(`$ShimDir, `$PythonPath)+`$script:UnslothCmdShimMarker = "$ShimMarker"+`$script:UnslothCliTrampoline = "$Trampoline"+$relFn+$contentFn+Get-UnslothCmdShimContent -ShimDir `$ShimDir -PythonPath `$PythonPath+"@)+ return (& $sb $ShimDir $PythonPath)+}++$shimDir = "C:\Users\Jane Doe\.unsloth\studio\bin"+$shimPy = "C:\Users\Jane Doe\.unsloth\studio\unsloth_studio\Scripts\python.exe"+$body = Invoke-Content $shimDir $shimPy++Write-Host "the .cmd is a pure function of %~dp0"+Check "it starts with echo off" ($body.StartsWith("@echo off`r`n"))+Check "it reaches python via %~dp0" ($body -match '"%~dp0\.\.\\unsloth_studio\\Scripts\\python\.exe"')+# The whole reason for %~dp0: a profile path with a space, a '$' or a bracket never has to be+# escaped, because it is never written down.+Check "the install path is absent" (-not ($body -match 'Jane Doe'))+Check "the trampoline is quoted" ($body.Contains('-X utf8 -c "' + $Trampoline + '" %*'))+Check "the shim is not isolated" (-not ($body -match '\s-I\s'))+# cmd /V:ON, or the machine-wide DelayedExpansion default, eats a '!' out of every+# argument before python sees it unless the scope turns it off.+Check "delayed expansion is off" ($body.Contains("`r`nsetlocal DisableDelayedExpansion`r`n"))+Check "it forwards every argument" ($body -match '%\*')+Check "it propagates the exit code" ($body -match '@exit /b %errorlevel%')+Check "CRLF line endings" (($body -split "`r`n").Count -ge 6 -and -not ($body -match "(?<!`r)`n"))+Check "it is deterministic" ($body -eq (Invoke-Content $shimDir $shimPy))+# Metacharacters that would otherwise reparse: cmd expands %VAR% even inside double quotes,+# so a literal '%' in an absolute fallback has to be doubled.+$crossVolume = Invoke-Content "C:\s\bin" "D:\100%%tools\py\python.exe"+Check "cross-volume falls back absolute" ($crossVolume -match 'D:\\100')+Check "and doubles every percent" ($crossVolume -match '100%%%%tools')+$weird = Invoke-Content "C:\s (x)\bin" "C:\s (x)\unsloth_studio\Scripts\python.exe"+Check "brackets and parens stay out" (-not ($weird -match '\(x\)'))++# --- Write-UnslothCmdShim -------------------------------------------------------------------+# Runs against a real directory: the idempotency contract is about bytes on disk.+function Invoke-Write {+ param([string] $ShimDir, [string] $PythonPath)+ $sb = [scriptblock]::Create(@"+param(`$ShimDir, `$PythonPath)+function substep { param(`$Message, `$Color) Write-Output "SUBSTEP: `$Message" }+`$script:UnslothCmdShimMarker = "$ShimMarker"+`$script:UnslothCliTrampoline = "$Trampoline"+$relFn+$contentFn+$shimFileFn+$writeFn+Write-UnslothCmdShim -ShimDir `$ShimDir -PythonPath `$PythonPath+"@)+ return (& $sb $ShimDir $PythonPath)+}++Assert-HarnessComplete `+ -Extracted ($relFn + "`n" + $contentFn + "`n" + $shimFileFn + "`n" + $writeFn) `+ -Provided @("Get-RelativeShimPath", "Get-UnslothCmdShimContent", "Test-UnslothCmdShimFile",+ "Write-UnslothCmdShim") `+ -Label "the .cmd writer"++$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-shim-" + [guid]::NewGuid().ToString("N").Substring(0, 8))+try {+ $binDir = Join-Path $tmp "bin"+ $null = New-Item -ItemType Directory -Path $binDir -Force+ $pyPath = Join-Path (Join-Path (Join-Path $tmp "unsloth_studio") "Scripts") "python.exe"+ $cmdPath = Join-Path $binDir "unsloth.cmd"++ Invoke-Write $binDir $pyPath | Out-Null+ Write-Host "the .cmd is written once and then left alone"+ Check "the file appears" (Test-Path -LiteralPath $cmdPath -PathType Leaf)+ $firstBytes = [System.IO.File]::ReadAllBytes($cmdPath)+ # cmd.exe reads a UTF-8 BOM as part of the first command, so there must not be one.+ Check "no BOM" (-not ($firstBytes.Length -ge 3 -and $firstBytes[0] -eq 0xEF -and $firstBytes[1] -eq 0xBB -and $firstBytes[2] -eq 0xBF))+ Check "ASCII only" (-not ($firstBytes | Where-Object { $_ -gt 127 }))++ $stampBefore = (Get-Item -LiteralPath $cmdPath).LastWriteTimeUtc+ Start-Sleep -Milliseconds 50+ Invoke-Write $binDir $pyPath | Out-Null+ $stampAfter = (Get-Item -LiteralPath $cmdPath).LastWriteTimeUtc+ # Same bytes means no write at all, not a rewrite that happens to match: a rewrite would+ # move the timestamp and churn the file on every no-op reinstall.+ Check "a re-run rewrites nothing" ($stampBefore -eq $stampAfter)+ Check "the bytes are unchanged" (-not (Compare-Object $firstBytes ([System.IO.File]::ReadAllBytes($cmdPath))))+ # No temp file is left behind either way. Filtered by name rather than by -Filter:+ # "unsloth.cmd.*" keeps 8.3 wildcard semantics and matches bare "unsloth.cmd" too.+ Check "no leftover temp file" (@(Get-ChildItem -LiteralPath $binDir | Where-Object { $_.Name -ne "unsloth.cmd" }).Count -eq 0)++ # A stale shim from an install at a different location must be replaced.+ [System.IO.File]::WriteAllText($cmdPath, "@echo off`r`nrem stale`r`n")+ Invoke-Write $binDir $pyPath | Out-Null+ Check "stale content is replaced" (-not ((Get-Content -Raw -LiteralPath $cmdPath) -match 'stale'))++ # Byte identical except for a leading BOM. ReadAllText strips it before comparing,+ # so a text compare calls this file unchanged and leaves cmd.exe reading the BOM as+ # part of `@echo off` forever.+ $withBom = [byte[]](0xEF, 0xBB, 0xBF) + $firstBytes+ [System.IO.File]::WriteAllBytes($cmdPath, $withBom)+ Invoke-Write $binDir $pyPath | Out-Null+ Check "a BOM-prefixed shim is rewritten" (-not (Compare-Object ([System.IO.File]::ReadAllBytes($cmdPath)) $firstBytes))++ # Case is the other thing -eq ignores. Same reasoning: cmd is case insensitive for+ # commands but the trampoline it carries is Python, where SYS is not sys.+ [System.IO.File]::WriteAllText($cmdPath, ((Get-Content -Raw -LiteralPath $cmdPath).ToUpperInvariant()))+ Invoke-Write $binDir $pyPath | Out-Null+ Check "an upper-cased shim is rewritten" (-not (Compare-Object ([System.IO.File]::ReadAllBytes($cmdPath)) $firstBytes))++ # A run killed between the write and the rename leaves its temp behind, and the next+ # run has a different PID. Nothing else would ever collect it.+ $orphan = Join-Path $binDir "unsloth.cmd.999999.tmp"+ [System.IO.File]::WriteAllText($orphan, "half written")+ Invoke-Write $binDir $pyPath | Out-Null+ Check "an orphaned temp file is swept" (-not (Test-Path -LiteralPath $orphan))+ Check "sweeping did not disturb the shim" (-not (Compare-Object ([System.IO.File]::ReadAllBytes($cmdPath)) $firstBytes))++ # ...but only ours, and only when its owner is gone. A live PID's temp belongs to a+ # concurrent install that is about to rename it.+ $live = Join-Path $binDir "unsloth.cmd.$PID.tmp"+ [System.IO.File]::WriteAllText($live, "in flight")+ $foreignTemp = Join-Path $binDir "something-else.tmp"+ [System.IO.File]::WriteAllText($foreignTemp, "not ours")+ Invoke-Write $binDir $pyPath | Out-Null+ Check "a live PID's temp is left alone" (Test-Path -LiteralPath $live)+ Check "an unrelated temp is left alone" (Test-Path -LiteralPath $foreignTemp)+ Remove-Item -LiteralPath $live, $foreignTemp -Force++ # A directory in the way is reported, not thrown out of the installer.+ $blockedDir = Join-Path $tmp "bin2"+ $null = New-Item -ItemType Directory -Path (Join-Path $blockedDir "unsloth.cmd") -Force+ $out = Invoke-Write $blockedDir $pyPath+ Check "a directory in the way warns" (($out -join "`n") -match 'SUBSTEP: cannot write')+} finally {+ Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue+}++# --- wiring ---------------------------------------------------------------------------------+# Normalised to LF once: on a CRLF checkout every \n-anchored pattern below matches nothing and+# the -not checks pass vacuously.+$installText = (Get-Content -Raw $install) -replace "`r`n", "`n"++Write-Host "nothing the installer drives starts the generated console script"+Check "the setup handoff goes through python" ($installText -match '(?m)^\s*Invoke-ManagedUnslothCli -Python \$VenvPython -Arguments \$studioArgs$')+Check "and reads the published exit code" ($installText -match '\$setupExit = \$script:ManagedUnslothCliExit')+Check "a blocked launch is reported, not printed as an empty exit code" (+ $installText -match '(?s)if \(\$null -eq \$setupExit\) \{\s*return \(Exit-InstallFailure \(Write-ApplicationControlBlocked')+Check "autostart goes through python" ($installText -match 'Start-Process -FilePath \$VenvPython')+Check "the shortcuts launcher takes python" ($installText -match 'New-StudioShortcuts -ManagedPythonPath \$VenvPython')+Check "the generated launcher runs the interpreter" ($installText -match '\$studioPython -replace')+# The executing forms, specifically. `Test-Path $UnslothExe` and the hardlink still name the+# file on purpose: it is still generated, still shimmed, just never started.+Check "no call operator on the exe" (-not ($installText -match '&\s*\$UnslothExe'))+Check "no Start-Process on the exe" (-not ($installText -match 'Start-Process -FilePath \$UnslothExe'))++# A policy DENIES the launcher and leaves it on disk; antivirus QUARANTINES it, deleting it+# out of a venv that still runs. Nothing past this point starts it, so its absence must not+# abort the install for exactly the machines this change is for.+Write-Host "a quarantined launcher does not abort the install"+Check "absence asks the interpreter first" (+ $installText -match '(?s)if \(-not \(Test-Path -LiteralPath \$UnslothExe\)\) \{.*?Invoke-ManagedUnslothCli -Python \$VenvPython -Arguments @\("--version"\)')+Check "and only then gives up" (+ $installText -match '(?s)if \(\$cliImportable\) \{.*?\} else \{.*?Exit-InstallFailure "unsloth CLI was not installed correctly"')+Check "a venv with no interpreter at all still fails" (+ $installText -match '(?s)\$cliImportable = \$false\s*\n\s*if \(Test-Path -LiteralPath \$VenvPython\)')+# Anti-vacuity: the guidance for a genuinely CLI-less wheel has to survive, since that is+# the case this check was written for and the one the fallback must not swallow.+Check "the older-unsloth guidance is still there" (+ $installText -match 'an older unsloth version was installed that does not include the Unsloth CLI')++# Write-UnslothCmdShim warns and leaves an unwritable file alone, so a foreign bin\unsloth.cmd+# can survive a run. Counting it as a launcher would put its directory on PATH and advertise+# someone else's command as the policy-safe way in.+# The bare Test-Path that used to gate this is checked for above, in "PATH accepts either+# launcher". The only surviving occurrence is inside Test-UnslothCmdShimFile's own guard,+# which is where it belongs, so the negative is anchored to the assignment rather than to+# the string appearing anywhere in the file.+Check "PATH counts only our own .cmd" (+ -not ($installText -match '\$ShimUsable = .*Test-Path -LiteralPath \$ShimCmd'))+# ...and it is still installed and still hardlinked, or every unaffected machine regresses.+Check "the exe is still hardlinked" ($installText -match 'New-Item -ItemType HardLink -Path \$ShimExe -Target \$UnslothExe')+Check "the exe existence gate remains" ($installText -match '\$UnslothExe = Join-Path \$VenvDir "Scripts\\unsloth\.exe"')++Write-Host "the launcher and the shortcuts are rewritten only when they change"+# A reinstall and every `unsloth studio update` regenerate both. Rewriting identical bytes+# moves their timestamps, which is the churn the idempotency contract exists to prevent.+# Bytes, including the BOM. ReadAllText decodes the preamble away and PowerShell's -eq+# is case insensitive, so a text compare calls a BOM-less launcher written by an older+# installer unchanged and it never gains the BOM Windows PowerShell 5.1 needs.+Check "launch-studio.ps1 is compared as bytes" (+ $installText -match '(?s)\$launcherUnchanged =\s*\(@\(Compare-Object \$existingLauncher \$desiredLauncher -SyncWindow 0\)\.Count -eq 0\)')+Check "the BOM is part of what is compared" ($installText -match '\$utf8Bom\.GetPreamble\(\) \+ \$utf8Bom\.GetBytes\(\$launcherContent\)')+Check "and skipped when unchanged" ($installText -match '(?s)if \(-not \$launcherUnchanged\) \{\s*\[System\.IO\.File\]::WriteAllBytes\(\$launcherPs1')+Check "the .lnk is saved only when changed" ($installText -match '(?s)if \(-not \$shortcutUnchanged\) \{.*?\$shortcut\.Save\(\)')++Write-Host "the escape hatch reaches installs that only ever run an update"+# `unsloth studio update` drives install.ps1 through -ShortcutsOnly and returns before the+# main shim block, so without this an install made before the .cmd existed never gets one.+Check "-ShortcutsOnly writes the .cmd" ($installText -match '(?s)if \(\$ShortcutsOnly\) \{.*?Write-UnslothCmdShim -ShimDir \$ShortcutShimDir.*?New-StudioShortcuts')+# An installer older than the shim directory never created one, and `unsloth studio+# update` is the only route those installs ever take back into install.ps1. Testing+# only that the write appears in the branch missed that it was conditional on a+# directory that population does not have.+Check "-ShortcutsOnly creates the bin dir first" (+ $installText -match '(?s)if \(\$ShortcutsOnly\) \{.*?\[System\.IO\.Directory\]::CreateDirectory\(\$ShortcutShimDir\).*?Write-UnslothCmdShim -ShimDir \$ShortcutShimDir')+Check "PATH accepts either launcher" ($installText -match '(?s)\$ShimUsable = \(Test-Path -LiteralPath \$ShimExe -PathType Leaf\) -or\s*\(Test-UnslothCmdShimFile -Path \$ShimCmd\)')+Check "and the env-mode export too" ($installText -match "StudioRedirectMode -eq 'env' -and \`$ShimUsable")++Write-Host "the launch instructions are probed, not assumed"+# PATHEXT resolves .EXE before .CMD, so bare `unsloth` picks the blocked file. Printing the+# .cmd unconditionally would change what every unaffected machine sees, so it is gated.+Check "the decline branch probes" ($installText -match 'if \(Test-UnslothCmdShimPreferred -ShimExe \$ShimExe -ShimCmd \$ShimCmd\) \{\n\s*substep "unsloth\.cmd studio -p 8888"')+Check "the manual branch probes" ($installText -match '\$_shimBlocked = Test-UnslothCmdShimPreferred -ShimExe \$ShimExe -ShimCmd \$ShimCmd')+Check "and prints the bare form otherwise" ($installText -match '\$_bareLaunch = if \(\$_shimBlocked\) \{ "unsloth\.cmd studio -p 8888" \} else \{ "unsloth studio -p 8888" \}')++Write-Host "the trampoline is the one the desktop already uses"+# WINDOWS_CLI_ENTRYPOINT lives in process.rs, shared by the backend spawn, the auth+# provisioning, the health probe and the updater. update.rs only calls the builder now.+$processRs = Join-Path $repo "studio/src-tauri/src/process.rs"+$rsText = Get-Content -Raw $processRs+$studioPy = Join-Path $repo "unsloth_cli/commands/studio.py"+# Python splits the literal across source lines to stay inside the line length, so join+# adjacent string literals back before comparing. Matching the raw text instead would fail+# the moment someone rewrapped the constant without changing its value.+$pyText = (Get-Content -Raw $studioPy) -replace '"\s*\r?\n\s*"', ''+# Drift here is silent: two spellings of argv[0] both "work" until one of them stops being+# recognised as the console-script entry point. All three are checked against the literal+# at the top of this file, so editing any one of them alone fails here.+Check "install.ps1 carries the trampoline" ($installText.Contains('$script:UnslothCliTrampoline = "' + $Trampoline + '"'))+Check "process.rs agrees" ($rsText.Contains($Trampoline))+Check "studio.py agrees" ($pyText.Contains($Trampoline))+Check "nothing still isolates with -I" (-not ($installText -match '"-X", "utf8", "-I"'))++Write-Host "a bare unsloth.cmd does not hand an unrelated directory to the uninstaller"+$uninstallText = Get-Content -Raw (Join-Path $repo "scripts/uninstall.ps1")+Check "ownership is content-checked" ($uninstallText -match '_IsUnslothCmdShim \(Join-Path \$Path "bin\\unsloth\.cmd"\)')+Check "and the marker is the trampoline" ($uninstallText -match 'from unsloth_cli import app')+$setupText = Get-Content -Raw (Join-Path $repo "studio/setup.ps1")+Check "setup.ps1 guards the same way" ($setupText -match 'Test-UnslothCmdShimFile \(Join-Path \$StudioHome "bin\\unsloth\.cmd"\)')+Check "install.ps1 guards the same way" ($installText -match 'Test-UnslothCmdShimFile \(Join-Path \$StudioHome "bin\\unsloth\.cmd"\)')++# The predicate itself, run for real: a file with the right name and the wrong contents+# must not qualify, because the callers delete whole directories on the strength of it.+function Invoke-ShimFileCheck {+ param([string] $Path)+ $sb = [scriptblock]::Create(@"+param(`$Path)+$shimFileFn+Test-UnslothCmdShimFile -Path `$Path+"@)+ return (& $sb $Path)+}++$ownTmp = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-own-" + [guid]::NewGuid().ToString("N").Substring(0, 8))+try {+ $null = New-Item -ItemType Directory -Path $ownTmp -Force+ $realShim = Join-Path $ownTmp "unsloth.cmd"+ [System.IO.File]::WriteAllText($realShim, (Invoke-Content "C:\s\bin" "C:\s\unsloth_studio\Scripts\python.exe"))+ Check "our own shim qualifies" (Invoke-ShimFileCheck $realShim)++ $impostor = Join-Path $ownTmp "impostor.cmd"+ [System.IO.File]::WriteAllText($impostor, "@echo off`r`nunsloth %*`r`n")+ Check "someone else's wrapper does not" (-not (Invoke-ShimFileCheck $impostor))++ Check "a missing file does not" (-not (Invoke-ShimFileCheck (Join-Path $ownTmp "absent.cmd")))+ Check "an empty path does not" (-not (Invoke-ShimFileCheck ""))+ $asDir = Join-Path $ownTmp "dir.cmd"+ $null = New-Item -ItemType Directory -Path $asDir -Force+ Check "a directory does not" (-not (Invoke-ShimFileCheck $asDir))+ # Bounded read: a huge file named unsloth.cmd is not our few-hundred-byte shim, and+ # slurping it to find out would be the wrong trade.+ $huge = Join-Path $ownTmp "huge.cmd"+ [System.IO.File]::WriteAllText($huge, ("x" * 9000) + "from unsloth_cli import app")+ Check "an oversized file does not" (-not (Invoke-ShimFileCheck $huge))+} finally {+ Remove-Item -LiteralPath $ownTmp -Recurse -Force -ErrorAction SilentlyContinue+}++# --- Test-ShimLaunchBlocked, chatty launcher ----------------------------------------------+# Both pipes are redirected, so a launcher that fills one blocks writing while the probe+# blocks waiting and neither side moves. Reachable since the trampoline stopped passing -I:+# PYTHONPROFILEIMPORTTIME=1 now reaches the child and produces ~24 KB of stderr against a+# 4 KB pipe buffer. Measured on this runner: undrained, the probe burns its full 20s+# timeout; drained, it returns in tens of milliseconds.+$probeTmp = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-probe-" + [guid]::NewGuid().ToString("N"))+$null = New-Item -ItemType Directory -Path $probeTmp+try {+ $onWindows = $env:OS -eq "Windows_NT"+ $line = "." * 64+ # Has to outrun the pipe buffer to mean anything: Linux defaults to 64 KB, so 26 KB+ # of output would sail through undrained and the timing check below would be vacuous.+ $repeats = 2000+ if ($onWindows) {+ $chatty = Join-Path $probeTmp "chatty.cmd"+ $body = "@echo off`r`n"+ $body += "for /L %%i in (1,1,$repeats) do @echo $line`r`n"+ $body += "for /L %%i in (1,1,$repeats) do @echo $line 1>&2`r`n"+ [System.IO.File]::WriteAllText($chatty, $body, (New-Object System.Text.UTF8Encoding($false)))+ } else {+ $chatty = Join-Path $probeTmp "chatty.sh"+ $body = "#!/bin/sh`n"+ $body += "i=0`n"+ $body += "while [ `$i -lt $repeats ]; do echo '$line'; echo '$line' >&2; i=`$((i+1)); done`n"+ [System.IO.File]::WriteAllText($chatty, $body, (New-Object System.Text.UTF8Encoding($false)))+ & chmod +x $chatty+ }++ $sb = [scriptblock]::Create(@"+param(`$Path)+$blockFn+$probeFn+Test-ShimLaunchBlocked -Path `$Path+"@)+ $sw = [System.Diagnostics.Stopwatch]::StartNew()+ $blocked = & $sb $chatty+ $sw.Stop()++ Write-Host "a launcher that outfills the pipe buffer does not stall the probe"+ Check "extraction kept the drain" ($probeFn -match 'ReadToEndAsync')+ # -1 -lt anything, so an absent drain would pass this on order alone.+ Check "drains before it waits" ($probeFn.IndexOf('ReadToEndAsync') -ge 0 -and+ $probeFn.IndexOf('ReadToEndAsync') -lt $probeFn.IndexOf('WaitForExit'))+ # A launcher that ran is not blocked, whatever it printed.+ Check "a chatty launcher is not blocked" (-not $blocked)+ Check "and it did not hit the timeout" ($sw.ElapsedMilliseconds -lt 10000)+} finally {+ Remove-Item -LiteralPath $probeTmp -Recurse -Force -ErrorAction SilentlyContinue+}++# --- Test-UnslothCmdShimPreferred -----------------------------------------------------------+# Which launcher the printed instructions name. Test-ShimLaunchBlocked answers $false for a+# file that is not there, because nothing refused to start it, so a quarantined or never-created+# .exe used to leave the installer printing a path that does not exist.+$prefTmp = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-pref-" + [guid]::NewGuid().ToString("N"))+$null = New-Item -ItemType Directory -Path $prefTmp+try {+ $prefSb = [scriptblock]::Create(@"+param(`$ShimExe, `$ShimCmd)+$blockFn+$probeFn+$preferFn+Test-UnslothCmdShimPreferred -ShimExe `$ShimExe -ShimCmd `$ShimCmd+"@)+ $exe = Join-Path $prefTmp "unsloth.exe"+ $cmd = Join-Path $prefTmp "unsloth.cmd"++ Write-Host "the instructions name the .cmd only when the .exe cannot serve"+ # Nothing written yet: no .cmd to name.+ Check "no .cmd, no preference" (-not (& $prefSb $exe $cmd))+ [System.IO.File]::WriteAllText($cmd, "@echo off`r`n")+ # This is the regression: the .exe is gone, so naming it prints a dead path.+ Check "quarantined .exe prefers it" (& $prefSb $exe $cmd)+ # A runnable .exe wins, which is what every unaffected machine has.+ Copy-Item -LiteralPath (Get-Command pwsh).Source -Destination $exe -ErrorAction SilentlyContinue+ if (Test-Path -LiteralPath $exe) {+ Check "a runnable .exe keeps it" (-not (& $prefSb $exe $cmd))+ }+} finally {+ Remove-Item -LiteralPath $prefTmp -Recurse -Force -ErrorAction SilentlyContinue+}++# --- the .cmd ownership marker ---------------------------------------------------------------+# _IsStudioRoot accepts a bin\unsloth.cmd as proof that a user-named root is ours, and that+# answer gates a recursive delete. `from unsloth_cli import app` alone is a line anyone could+# have in a hand-rolled wrapper, so the generated shim carries a marker nobody writes by+# accident and every check requires it.+$markerSb = [scriptblock]::Create(@"+param(`$Path)+`$script:UnslothCmdShimMarker = "$ShimMarker"+$shimFileFn+Test-UnslothCmdShimFile -Path `$Path+"@)+$markerTmp = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-marker-" + [guid]::NewGuid().ToString("N"))+$null = New-Item -ItemType Directory -Path $markerTmp+try {+ $ours = Join-Path $markerTmp "ours.cmd"+ [System.IO.File]::WriteAllText($ours, "@echo off`r`nrem unsloth-studio-managed-launcher`r`n... from unsloth_cli import app ...`r`n")+ $theirs = Join-Path $markerTmp "theirs.cmd"+ [System.IO.File]::WriteAllText($theirs, "@echo off`r`npython -c `"from unsloth_cli import app; sys.exit(app())`" %*`r`n")++ Write-Host "only the shim this installer generated proves ownership"+ Check "our shim is recognised" (& $markerSb $ours)+ Check "a hand-rolled wrapper is not" (-not (& $markerSb $theirs))+ Check "the generator emits the marker" ($installText -match 'rem \$script:UnslothCmdShimMarker')+ # The uninstaller gates a recursive delete on the same answer.+ Check "the uninstaller requires it too" ($uninstallText -match 'unsloth-studio-managed-launcher')+} finally {+ Remove-Item -LiteralPath $markerTmp -Recurse -Force -ErrorAction SilentlyContinue+}++Write-Host ""+if ($failures -gt 0) { Write-Host "$failures check(s) failed" -ForegroundColor Red; exit 1 }+Write-Host "All checks passed" -ForegroundColor Greendiff --git a/tests/studio/test_run_windows_entry_point.py b/tests/studio/test_run_windows_entry_point.pyindex 24b2eff8d2f..d204a000d4d 100644--- a/tests/studio/test_run_windows_entry_point.py+++ b/tests/studio/test_run_windows_entry_point.py@@ -1,9 +1,17 @@-"""AST test that `unsloth run` looks for the console script Windows actually ships.+"""AST tests for how `unsloth run` reaches the studio venv's CLI.-The venv's entry point is `unsloth.exe` on Windows, so resolving the bare name made-`studio_bin.is_file()` false on every Windows install and aborted with "Unsloth venv-missing 'unsloth' entry point". Pinned by AST because reaching the assignment at-runtime means standing up a studio venv.+Two separate regressions are pinned here, both needing a real studio venv to reach+at runtime, hence the AST:++1. The venv's entry point is `unsloth.exe` on Windows, so resolving the bare name+ made `studio_bin.is_file()` false on every Windows install and aborted with+ "Unsloth venv missing 'unsloth' entry point". The per-platform name still has to+ be chosen, because on POSIX that file is what proves the venv has a CLI at all.++2. That file must not be what Windows LAUNCHES. It is a generated, unsigned+ executable, and an Application Control policy denies it while the signed+ python.exe beside it still runs, so the respawn goes through the interpreter+ (issue #8490). POSIX keeps exec'ing the script, which is what os.execvp needs."""from __future__ import annotations@@ -11,7 +19,8 @@ from __future__ import annotationsimport astfrom pathlib import Path-_STUDIO = Path(__file__).resolve().parents[2] / "unsloth_cli" / "commands" / "studio.py"+_REPO_ROOT = Path(__file__).resolve().parents[2]+_STUDIO = _REPO_ROOT / "unsloth_cli" / "commands" / "studio.py"def _run_function() -> ast.FunctionDef:@@ -66,3 +75,177 @@ def test_the_windows_branch_is_the_exe():for node in ast.walk(branch.test)if isinstance(node, ast.Constant) and isinstance(node.value, str)}, "the .exe branch must be gated on platform.system() == 'Windows'"+++def _launch_head_value() -> ast.expr:+ for node in ast.walk(_run_function()):+ if not isinstance(node, ast.Assign):+ continue+ for target in node.targets:+ if isinstance(target, ast.Name) and target.id == "launch_head":+ return node.value+ raise AssertionError("`run` never assigns a launch_head")+++def test_windows_respawns_through_the_interpreter_not_the_console_script():+ """The blocked executable must not be argv[0] of the child on Windows."""+ branch = _launch_head_value()+ assert isinstance(+ branch, ast.IfExp+ ), f"expected launch_head to branch per platform, got {ast.dump(branch)}"+ # Windows arm: _managed_cli_argv(studio_python), i.e. the interpreter form.+ assert isinstance(branch.body, ast.Call), ast.dump(branch.body)+ assert isinstance(branch.body.func, ast.Name)+ assert branch.body.func.id == "_managed_cli_argv", (+ "the Windows arm must build the interpreter argv via _managed_cli_argv, got "+ f"{ast.dump(branch.body.func)}"+ )+ assert [arg.id for arg in branch.body.args if isinstance(arg, ast.Name)] == [+ "studio_python"+ ], "the interpreter argv must be built from studio_python"+ # POSIX arm: [str(studio_bin)] -- unchanged, and what os.execvp needs.+ assert isinstance(branch.orelse, ast.List) and len(branch.orelse.elts) == 1+ posix_head = branch.orelse.elts[0]+ assert isinstance(posix_head, ast.Call) and isinstance(posix_head.func, ast.Name)+ assert posix_head.func.id == "str"+ assert isinstance(posix_head.args[0], ast.Name) and posix_head.args[0].id == "studio_bin"+ assert "win32" in {+ node.value+ for node in ast.walk(branch.test)+ if isinstance(node, ast.Constant) and isinstance(node.value, str)+ }, "the interpreter arm must be gated on sys.platform == 'win32'"+++def test_the_trampoline_is_the_one_the_rust_and_powershell_sides_use():+ """One string, three languages. A drift here silently changes argv[0] handling.++ Each side is read from its own file. An earlier version of this test only+ grepped studio.py, so drifting the Rust and PowerShell copies left it green.+ """+ # Spelled out, not imported from any of the three, so editing any single copy+ # fails here instead of quietly agreeing with itself.+ canonical = (+ "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "+ "sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())"+ )++ # Python: via AST, because the constant is written as adjacent literals.+ python_value = None+ for node in ast.walk(ast.parse(_STUDIO.read_text(encoding = "utf-8"))):+ if isinstance(node, ast.Assign) and any(+ isinstance(t, ast.Name) and t.id == "_WINDOWS_CLI_ENTRYPOINT" for t in node.targets+ ):+ python_value = ast.literal_eval(node.value)+ assert (+ python_value == canonical+ ), f"_WINDOWS_CLI_ENTRYPOINT in {_STUDIO.name} has drifted: {python_value!r}"++ rust = (_REPO_ROOT / "studio" / "src-tauri" / "src" / "process.rs").read_text(encoding = "utf-8")+ assert (+ f'"{canonical}"' in rust+ ), "WINDOWS_CLI_ENTRYPOINT in studio/src-tauri/src/process.rs has drifted"++ powershell = (_REPO_ROOT / "install.ps1").read_text(encoding = "utf-8")+ assert (+ f'$script:UnslothCliTrampoline = "{canonical}"' in powershell+ ), "$script:UnslothCliTrampoline in install.ps1 has drifted"+++def test_the_interpreter_argv_carries_no_isolation_flag_by_default():+ """-I implies -E and drops every PYTHON* variable the console script honours.++ The trampoline's own sys.path[:1] filter is what keeps a stray unsloth_cli in+ the working directory from shadowing the managed package, so -I is not needed+ for that either, and paying it would be an observable difference on a machine+ with no policy at all.++ Read off the ternary rather than off the whole file, because the file does+ contain one -I: _interpreter_health_error opts in, since the launch it stands+ in for is itself isolated (build_update_command, Isolation::Isolated). The+ point of this test is that isolation is opt-in and the default is not it.+ """+ argv_builder = None+ for node in ast.walk(ast.parse(_STUDIO.read_text(encoding = "utf-8"))):+ if isinstance(node, ast.FunctionDef) and node.name == "_managed_cli_argv":+ argv_builder = node+ break+ assert argv_builder is not None, "_managed_cli_argv is gone; the argv is built somewhere else"++ ternaries = [node for node in ast.walk(argv_builder) if isinstance(node, ast.IfExp)]+ assert len(ternaries) == 1, "expected exactly one isolated/inherited choice to inspect"+ isolated = ast.literal_eval(ternaries[0].body)+ inherited = ast.literal_eval(ternaries[0].orelse)++ assert inherited == ["-X", "utf8"], "the default argv must stay `-X utf8 -c <trampoline>`"+ # -X utf8 before -I: -I implies -E, which discards PYTHONUTF8 but cannot+ # touch a flag already on the command line.+ assert isolated == ["-X", "utf8", "-I"]+ assert ternaries[0].test.id == "isolated", "the ternary must key off the isolated parameter"++ # And the default really is inherit, so a caller that says nothing gets parity.+ default = argv_builder.args.defaults[-1] if argv_builder.args.defaults else None+ kw_default = argv_builder.args.kw_defaults[-1] if argv_builder.args.kw_defaults else default+ assert ast.literal_eval(kw_default) is False+++def test_only_the_updater_health_probe_asks_for_isolation():+ """One caller, named, so a second one cannot arrive unnoticed.++ Isolation is correct for a probe predicting an already-isolated launch and+ wrong for everything else here, and the difference is invisible until a user+ on an unpoliced machine loses their PYTHONPATH.+ """+ tree = ast.parse(_STUDIO.read_text(encoding = "utf-8"))+ isolated_callers = set()+ for parent in ast.walk(tree):+ if not isinstance(parent, (ast.FunctionDef, ast.AsyncFunctionDef)):+ continue+ for node in ast.walk(parent):+ if (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "_managed_cli_argv"+ and any(+ keyword.arg == "isolated" and keyword.value.value is True+ for keyword in node.keywords+ if isinstance(keyword.value, ast.Constant)+ )+ ):+ isolated_callers.add(parent.name)+ assert isolated_callers == {+ "_interpreter_health_error"+ }, f"unexpected isolated managed CLI callers: {sorted(isolated_callers)}"+++def test_the_windows_existence_gate_accepts_a_quarantined_venv():+ """Quarantine deletes the stub; the install behind it still runs.++ The Windows respawn goes through the interpreter and never touches this file,+ so requiring it here would abort `studio run` on an environment that works,+ which is the whole failure this change exists to remove.+ """+ gate = None+ for node in ast.walk(_run_function()):+ if not isinstance(node, ast.If):+ continue+ called = {+ child.func.attr+ for child in ast.walk(node.test)+ if isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute)+ }+ if "is_file" in called and any(+ isinstance(child, ast.Name) and child.id == "studio_bin"+ for child in ast.walk(node.test)+ ):+ gate = node+ break+ assert gate is not None, "`run` no longer gates on studio_bin.is_file()"+ fallbacks = {+ child.func.id+ for child in ast.walk(gate.test)+ if isinstance(child, ast.Call) and isinstance(child.func, ast.Name)+ }+ assert "_managed_cli_package_present" in fallbacks, (+ "a missing console script must fall back to the installed package, or a "+ "quarantined Windows install cannot start Studio"+ )diff --git a/tests/test_installer_profile_hardening.py b/tests/test_installer_profile_hardening.pyindex 7ac5d885369..a5ab3a045f8 100644--- a/tests/test_installer_profile_hardening.py+++ b/tests/test_installer_profile_hardening.py@@ -126,7 +126,10 @@ def test_profile_hardening_precedes_every_use_it_protects():for marker, what in (("$env:UNSLOTH_NO_TORCH -in @(", "the first unset-env test"),("Invoke-WebRequest", "the first in-process download"),- ("& $UnslothExe @studioArgs", "the setup handoff"),+ (+ "Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs",+ "the setup handoff",+ ),):idx = _locate(code, marker, what)assert strict_idx < idx, f"{what} must be reached with strict mode pinned"@@ -848,7 +851,11 @@ def test_the_handoff_is_published_only_around_the_setup_child():assert "$env:_UNSLOTH_PS_PROXY_DEFAULTS = $previousProxyHandoff" in sourcegate = _locate(source, "$previousSetupRuntimeGateHandoff =", "the runtime-gate handoff")proxy = _locate(source, "$previousProxyHandoff =", "the proxy handoff save")- call = _locate(source, " try {\n & $UnslothExe @studioArgs", "the child invocation")+ call = _locate(+ source,+ " try {\n Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs",+ "the child invocation",+ )assert gate < call and proxy < call, "the handoff must be in place before the child runs"@@ -1580,7 +1587,7 @@ def test_the_proxy_handoff_does_not_outlive_the_installer():# Still dropped explicitly once the child it exists for has run.cleared = "$UnslothProxyHandoffJson = $null"assert cleared in installer- child = installer.index("& $UnslothExe @studioArgs")+ child = installer.index("Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs")assert child < installer.index(cleared, child)diff --git a/tests/test_windows_amd_gpu_scan_fallback.py b/tests/test_windows_amd_gpu_scan_fallback.pyindex 614e9515208..76b80233d76 100644--- a/tests/test_windows_amd_gpu_scan_fallback.py+++ b/tests/test_windows_amd_gpu_scan_fallback.py@@ -231,7 +231,7 @@ def test_gpu_name_list_wraps_the_whole_if_in_an_array():def test_installer_forwards_the_arch_through_a_private_handoff():src = INSTALL_PS1.read_text(encoding = "utf-8")forward = src.index(f"$env:{HANDOFF} = $ROCmGfxArch")- invoke = src.index("& $UnslothExe @studioArgs")+ invoke = src.index("Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs")assert forward < invoke, "the arch must be handed over before setup.ps1 is invoked"@@ -539,7 +539,7 @@ def _run_handoff_lifecycle(tmp_path: Path, *, arch: str | None, inherited: str | None, fails: bool) -> dict:body = _handoff_lifecycle_block().replace(- "& $UnslothExe @studioArgs",+ "Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs","throw 'setup exploded'"if failselse "$script:SeenByChild = $env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF",diff --git a/unsloth_cli/__init__.py b/unsloth_cli/__init__.pyindex 37d854e3385..84dfc2cd594 100644--- a/unsloth_cli/__init__.py+++ b/unsloth_cli/__init__.py@@ -10,12 +10,30 @@ import sys as _sys_entry_base = _os.path.basename(_sys.argv[0]).lower() if _sys.argv else ""_is_entry_point = _entry_base in {"unsloth", "unsloth.exe"}-# Typer renders help via rich, whose box characters cp1252 and cp437 cannot encode,-# so `unsloth --help` dies once stdout is a pipe or a file. Windows gets UTF-8, as-# unsloth/__init__ already does; elsewhere the caller's encoding is kept and only-# the error handler is relaxed, so an explicit PYTHONIOENCODING still picks the-# bytes and only loses unencodable glyphs. Before typer, which binds the stream.-if _is_entry_point:++_streams_reconfigured = False+++def _reconfigure_entry_point_streams():+ """Give the console script streams that can render typer's help.++ Typer renders help via rich, whose box characters cp1252 and cp437 cannot encode,+ so `unsloth --help` dies once stdout is a pipe or a file. Windows gets UTF-8, as+ unsloth/__init__ already does; elsewhere the caller's encoding is kept and only+ the error handler is relaxed, so an explicit PYTHONIOENCODING still picks the+ bytes and only loses unencodable glyphs.++ Called at most once per process. The console script reaches it twice, from+ the import-time gate and again through _prepare_entry_point, and off Windows+ the second call did repeat the work: passing encoding = None keeps the+ caller's encoding, so the "already utf" guard below cannot become true and a+ C-locale console was reconfigured, and flushed, one time more than the+ console script ever did before this file grew a second entry route.+ """+ global _streams_reconfigured+ if _streams_reconfigured:+ return+ _streams_reconfigured = True_to_utf8 = _sys.platform == "win32"for _name in ("stdout", "stderr"):_stream = getattr(_sys, _name, None)@@ -24,7 +42,11 @@ if _is_entry_point:_stream.reconfigure(encoding = "utf-8" if _to_utf8 else None, errors = "replace")except Exception:pass- del _name, _stream, _to_utf8+++# Before typer, which binds the stream.+if _is_entry_point:+ _reconfigure_entry_point_streams()from unsloth_cli._system_dir_guard import check_working_directory as _check_working_directory@@ -56,10 +78,35 @@ from unsloth_cli.commands.studio import ()+_entry_point_prepared = False+++def _prepare_entry_point():+ """Apply the `unsloth` console-script behaviour to this process.++ Split out for `python -m unsloth_cli`, which cannot use the argv[0] check+ above: `-m` imports this package in order to find unsloth_cli/__main__.py,+ so __init__ runs while sys.argv[0] is still "-m" and the gate cannot fire.+ __main__ rewrites argv[0] and calls this instead.++ Idempotent, because the console script reaches it through the gate below+ and only the module entry calls it by hand.+ """+ global _entry_point_prepared+ if _entry_point_prepared:+ return+ _reconfigure_entry_point_streams()+ _expand_attached_np_short()+ # Set last, so a raise leaves the work retryable rather than silently+ # skipped. Neither call can currently raise -- the first swallows everything+ # and the second is pure argv manipulation -- but the ordering costs nothing.+ _entry_point_prepared = True++# Canonicalise `-np<N>` only under the `unsloth` console-script;# third-party scripts that import unsloth_cli keep their argv intact.if _is_entry_point:- _expand_attached_np_short()+ _prepare_entry_point()del _entry_base, _is_entry_pointdiff --git a/unsloth_cli/__main__.py b/unsloth_cli/__main__.pynew file mode 100644index 00000000000..ba95d1a2811--- /dev/null+++ b/unsloth_cli/__main__.py@@ -0,0 +1,55 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""`python -I -m unsloth_cli` -- reach the CLI without the generated console script.++Windows materialises the `unsloth` entry point as a generated, unsigned+`unsloth.exe`. AppLocker, WDAC and Smart App Control deny that executable while+the signed interpreter beside it keeps running, so `unsloth ...` is unusable on+a locked-down machine even though the install is perfectly healthy (issue+https://github.com/unslothai/unsloth/issues/8490). This module is the supported+way in for those users, and for anyone who would rather not depend on a+generated launcher:++ python -X utf8 -I -m unsloth_cli studio -p 8888++Use -I when that `python` is the managed Studio interpreter, which is what every+command Unsloth prints does. `-m` resolves the package before this file runs, so a+shell standing in a directory that has an `unsloth_cli` folder would otherwise run+that copy, and -I drops the working directory from sys.path first.++A `pip install --user` install is the exception: -I implies -s, so it hides the very+user site the package lives in and the command cannot find it at all. There, run the+same bootstrap the internal call sites use, which strips only the working directory:++ python -X utf8 -c "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())" studio -p 8888++Output is identical to the console script, which takes three things:++ * argv[0] is rewritten, so anything reading it sees the name the console+ script would have given it.+ * _prepare_entry_point() applies the rest of the console-script behaviour+ (UTF-8 streams, the `-np<N>` rewrite). The import-time gate in+ unsloth_cli/__init__ cannot do it here, because `-m` imports the package in+ order to locate this module: __init__ has already run, with argv[0] still+ "-m", before the first statement below executes.+ * prog_name is passed explicitly. click ignores argv[0] once it sees a+ __main__ with a __package__ (its _detect_program_name treats that as "python+ -m example") and would print `Usage: python -m unsloth_cli` in every usage+ and error message.+"""++import sys++# Before the import, so a direct `python path/to/unsloth_cli/__main__.py` run+# takes the console-script gate in __init__ rather than needing the call below.+sys.argv[0] = "unsloth"++import unsloth_cli # noqa: E402++unsloth_cli._prepare_entry_point()+# sys.exit, like the generated console script's `sys.exit(app())`. Typer raises+# SystemExit itself in standalone mode, so today both spellings exit the same way,+# but a returned value has to become the exit status here too or the two routes+# stop agreeing the moment one exists.+sys.exit(unsloth_cli.app(prog_name = "unsloth"))diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex 6a4e97e1909..68ad3fd12cd 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -1029,14 +1029,25 @@ def _start_studio_server() -> subprocess.Popen:"""Spawn `unsloth run` for `model`, wait until it is fully ready, and return it."""global _auto_served_server- unsloth = shutil.which("unsloth") or "unsloth"+ # Windows goes through this interpreter, not the launcher on PATH: shutil.which+ # resolves `unsloth` to the denied unsloth.exe, since PATHEXT puts .EXE ahead of+ # the .cmd shim (issue #8490). Without this, a user who reached the CLI through+ # unsloth.cmd would still fail here. sys.executable is the interpreter already+ # running this command, so the child inherits the same environment.+ if sys.platform == "win32":+ # Local import: unsloth_cli.commands.studio imports at package init after+ # this module, so a top-level import would be circular.+ from unsloth_cli.commands.studio import _managed_cli_argv+ launch_head = _managed_cli_argv(Path(sys.executable))+ else:+ launch_head = [shutil.which("unsloth") or "unsloth"]parsed = urlparse(base)# Tools default off = passthrough mode (relay the agent's own tools); --no-cloudflare =# loopback only, no tunnel. Mirrors .github/scripts/serve-unsloth-run.sh. Healing/nudging# travel via the child env below (version-agnostic) rather than new run flags that an# older re-exec'd run could mistake for llama-server args.command = [- unsloth,+ *launch_head,"run","-H",parsed.hostname or "127.0.0.1",diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex cb061920a0e..82347b2399a 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -25,7 +25,7 @@ import urllib.parseimport urllib.requestfrom datetime import datetime, timezonefrom pathlib import Path-from typing import List, Literal, Optional, Sequence+from typing import List, Literal, Optional, Sequence, Tupleimport typerfrom unsloth_cli import _studio_deps, _studio_runtime_gate@@ -46,14 +46,54 @@ def _enable_verbose_access_logs() -> None:# sys.prefix inference (so a direct call to <root>/bin/unsloth resolves after# the installer's env var has expired), then legacy ~/.unsloth/studio.# UNSLOTH_STUDIO_HOME wins when both env vars are set.+# Both halves, and the 8 KB ceiling, are Test-UnslothCmdShimFile's in install.ps1 and+# _IsUnslothCmdShim's in scripts/uninstall.ps1. Bytes, not text: the shim is written+# without a BOM but an edited copy may carry one, and a decode error here would be+# indistinguishable from "not ours".+_CMD_SHIM_MARKERS = (b"unsloth-studio-managed-launcher", b"from unsloth_cli import app")+_CMD_SHIM_MAX_BYTES = 8192++def _looks_like_installer_managed_studio_home(candidate: Path) -> bool:"""Sentinel check (studio.conf or bin shim) so a dev venv namedunsloth_studio is not misidentified as a custom Unsloth root.++ On Windows bin\\unsloth.cmd counts too. Only install.sh writes+ share/studio.conf, so on a custom-root Windows install the generated+ unsloth.exe is the only sentinel there is, and antivirus quarantine deletes+ it -- after which this returns False, the root falls back to+ ~/.unsloth/studio, and every `unsloth studio ...` reads and writes the wrong+ installation. The .cmd is written by the same installer for the same+ directory, so it answers the same question.++ It has to be OUR .cmd: this decides which tree the CLI manages, and the+ directory is on PATH, so any file of that name would otherwise be enough to+ point a custom root at itself. Same marker Test-UnslothCmdShimFile in+ install.ps1 and the uninstaller's recursive-delete guard require."""- shim_name = "unsloth.exe" if platform.system() == "Windows" else "unsloth"- return (candidate / "share" / "studio.conf").is_file() or (- candidate / "bin" / shim_name- ).is_file()+ if (candidate / "share" / "studio.conf").is_file():+ return True+ if platform.system() != "Windows":+ return (candidate / "bin" / "unsloth").is_file()+ if (candidate / "bin" / "unsloth.exe").is_file():+ return True+ return _is_managed_cmd_shim(candidate / "bin" / "unsloth.cmd")+++def _is_managed_cmd_shim(path: Path) -> bool:+ """Whether *path* is the .cmd shim this installer generates.++ Read as bytes and matched on the marker line install.ps1 writes. A hand+ rolled wrapper that happens to invoke the CLI is not this, and must not be+ taken as proof of an installer-managed root.+ """+ try:+ if path.stat().st_size > _CMD_SHIM_MAX_BYTES:+ return False+ body = path.read_bytes()+ except OSError:+ return False+ return all(marker in body for marker in _CMD_SHIM_MARKERS)def _resolve_studio_home() -> tuple[Path, bool]:@@ -173,6 +213,81 @@ def _windows_hidden_subprocess_kwargs() -> dict[str, object]:return kwargs+# Windows materialises the `unsloth` entry point as a generated, unsigned .exe that+# Application Control denies while the signed interpreter beside it still runs, so+# every managed invocation goes through the interpreter (issue #8490).+#+# Byte-identical to WINDOWS_CLI_ENTRYPOINT in studio/src-tauri/src/process.rs and to+# $script:UnslothCliTrampoline in install.ps1, which carries the full rationale for+# both halves and for the deliberate absence of -I.+_WINDOWS_CLI_ENTRYPOINT = (+ "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "+ "sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())"+)++# Asks the managed interpreter whether the trampoline's import would succeed, by+# performing that exact import. The sys.path[0] scrub is+# _WINDOWS_CLI_ENTRYPOINT's, kept a separate literal because a parity test+# literal_evals that constant; the two must agree or the probe answers for a+# different sys.path than the launch uses.+#+# `from unsloth_cli import app` rather than a find_spec, deliberately. find_spec+# locates without executing, which sounds like the lighter question and is the+# wrong one: it answers True for an empty unsloth_cli/ directory (a namespace+# package), for a package whose __init__ raises, and for one whose dependencies+# an interrupted install never fetched. Every one of those is a venv the+# trampoline cannot start, and this probe gates the headless-public strip of+# .bootstrap_password, so a false pass there is a public Studio with no login+# page and no plaintext recovery credential. Paying the import is what makes the+# probe's answer the launch's answer.+_MANAGED_CLI_IMPORT_PROBE = (+ "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "+ "from unsloth_cli import app; sys.exit(0)"+)++# Seconds, and generous: this is a bare interpreter start plus the CLI package+# import, and it can run from cold on a machine whose antivirus is scanning the+# venv it just quarantined a file out of. The caller treats a timeout as "no+# verdict" rather than as a missing package, so overrunning it is not fatal.+_MANAGED_CLI_IMPORT_PROBE_TIMEOUT = 60++# CreateProcess refuses a program blocked by an Application Control policy with+# ERROR_ACCESS_DISABLED_BY_POLICY, which Python surfaces as OSError.winerror.+_ERROR_ACCESS_DISABLED_BY_POLICY = 1260+++def _managed_cli_argv(+ python: Path,+ *args: str,+ isolated: bool = False,+) -> List[str]:+ """argv that runs the managed `unsloth` CLI through *python*.++ -X utf8 rather than PYTHONUTF8 so the encoding holds even for a caller that+ scrubs the environment. -X utf8 precedes -I because -I implies -E, which+ would discard PYTHONUTF8 but cannot touch a command-line -X.++ *isolated* mirrors the Isolation enum in studio/src-tauri/src/process.rs and+ carries the same rule: the default is inherit, because -I implies -E and -s+ and so drops PYTHONPATH, PYTHONWARNINGS, PYTHONHASHSEED and user+ site-packages that the console script honoured, an observable difference on+ machines with no policy at all. Only a caller that must reproduce an+ already-isolated launch asks for it, and today that is the desktop updater's+ health probe, matching build_update_command's Isolation::Isolated.+ """+ flags = ["-X", "utf8", "-I"] if isolated else ["-X", "utf8"]+ return [str(python), *flags, "-c", _WINDOWS_CLI_ENTRYPOINT, *args]+++def _is_application_control_block(error: OSError) -> bool:+ """True when Windows refused to start a program because a policy blocks it.++ Distinct from a missing or corrupt executable: nothing ran, so the failure+ says nothing about the program itself.+ """+ return getattr(error, "winerror", None) == _ERROR_ACCESS_DISABLED_BY_POLICY++@contextlib.contextmanagerdef _studio_runtime_launch_guard(*, inherited: bool = False):guard = _studio_runtime_gate.studio_runtime_launch_guard(@@ -255,6 +370,76 @@ def _studio_venv_python() -> Optional[Path]:return p if p.is_file() else None+def _managed_cli_site_packages_layout(python: Path) -> bool:+ """On-disk hint that the venv holding *python* still carries the CLI.++ Weaker than the import probe below and only used when the probe could not be+ run at all: an empty ``unsloth_cli/`` or an orphaned dist-info left by an+ interrupted install answers yes here without being importable.++ The dist-info is accepted alongside the package directory because an+ editable install of the checkout leaves a .pth and no unsloth_cli/ here.+ """+ site_packages = python.parent.parent / "Lib" / "site-packages"+ if (site_packages / "unsloth_cli").is_dir():+ return True+ return any(site_packages.glob("unsloth-*.dist-info"))+++def _managed_cli_package_present(python: Path) -> bool:+ """Whether the venv holding *python* can still import the package the CLI runs.++ Windows only, and only asked when the console script is gone. The generated+ unsloth.exe is what proves a CLI on POSIX, but on Windows nothing launches it+ any more (issue #8490) and antivirus quarantine deletes the unsigned stub+ while leaving the environment perfectly able to run.++ Asked of the interpreter rather than of site-packages, because the two are+ not the same claim. What Windows launches is the trampoline's+ ``from unsloth_cli import app``, so an orphaned ``unsloth-*.dist-info`` (a+ moved editable checkout, an interrupted install) or an empty ``unsloth_cli/``+ directory is metadata, not a runnable CLI. It matters here specifically:+ this gate stands in front of the headless-public strip of+ .bootstrap_password, so passing a venv that then fails to import is the one+ outcome the gate's placement exists to prevent -- a public Studio with no+ login page and no plaintext recovery credential.++ The probe runs the trampoline's own ``from unsloth_cli import app`` rather+ than a cheaper spec lookup (see _MANAGED_CLI_IMPORT_PROBE for why the cheaper+ one answers a different question), with the same sys.path[0] scrub applied so+ an ``unsloth_cli`` directory in the caller's cwd cannot answer for the venv.+ """+ if platform.system() != "Windows":+ return False+ try:+ probe = subprocess.run(+ [str(python), "-X", "utf8", "-c", _MANAGED_CLI_IMPORT_PROBE],+ capture_output = True,+ timeout = _MANAGED_CLI_IMPORT_PROBE_TIMEOUT,+ # Same as every other managed-interpreter probe here: a non-interactive+ # Windows launch must not flash a console window (issue #8490's sibling).+ **_windows_hidden_subprocess_kwargs(),+ )+ except subprocess.TimeoutExpired:+ # Slow is not broken. A cold venv under an antivirus scan can take longer+ # than the probe waits, and the re-exec this gate stands in front of has+ # no timeout at all, so it would still come up. Fall back to the on-disk+ # layout rather than aborting an install that works -- the failure this+ # whole fallback exists to remove.+ return _managed_cli_site_packages_layout(python)+ except (OSError, subprocess.SubprocessError):+ # No verdict for a different reason: the interpreter would not start at+ # all (missing, or denied by an Application Control policy). The re-exec+ # runs THAT interpreter, so it is going to fail the same way, and the+ # on-disk layout cannot say otherwise. Fail closed, because the caller+ # strips .bootstrap_password on a headless public launch before it+ # re-execs: passing here would leave a public Studio with no login page+ # and no plaintext recovery credential, which is worse than telling the+ # user to re-run setup.+ return False+ return probe.returncode == 0++def _hsa_override_gfx_arch(value: Optional[str]) -> Optional[str]:"""gfx arch named by an HSA_OVERRIDE_GFX_VERSION value, or None if unreadable.@@ -2415,10 +2600,15 @@ def run(# Re-exec via the studio venv's `unsloth` console-script. Windows ships it as# unsloth.exe, so the bare name is never a file there and `unsloth run` aborted# with "venv missing 'unsloth' entry point" on a perfectly good install.+ #+ # On Windows the file is no longer what gets launched (see the launch_head+ # below) and no longer the only thing that proves a CLI: quarantine deletes+ # the stub and leaves the environment able to run, so the installed package+ # answers for it.studio_bin = studio_python.parent / ("unsloth.exe" if platform.system() == "Windows" else "unsloth")- if not studio_bin.is_file():+ if not studio_bin.is_file() and not _managed_cli_package_present(studio_python):typer.echo("Unsloth venv missing 'unsloth' entry point. Re-run: unsloth studio setup")raise typer.Exit(1)# `run` serves the same Unsloth UI (unless --api-only); a public launch must@@ -2471,8 +2661,16 @@ def run()if not in_studio_venv:+ # Windows launches the child through the venv interpreter rather than the+ # console script it just validated: Application Control blocks the+ # generated unsloth.exe on some machines, and the signed python.exe beside+ # it is not blocked. POSIX keeps execing the script directly, which is what+ # the os.execvp below needs anyway.+ launch_head = (+ _managed_cli_argv(studio_python) if sys.platform == "win32" else [str(studio_bin)]+ )args = [- str(studio_bin),+ *launch_head,"studio","run","--model",@@ -3881,6 +4079,15 @@ class _WindowsLauncherUpdateTransaction:"""Keep the managed Windows launcher recoverable during a Python update."""_VERSION_TIMEOUT_SECONDS = 10+ # Sentinel rather than a message: _launcher_health_error matches on identity,+ # so it can never be confused with a real diagnostic that happens to read the+ # same way, and it never reaches a user.+ _POLICY_BLOCKED = "an Application Control policy blocked the launcher"+ # Absence is not corruption. Quarantine takes the unsigned stub and leaves the+ # environment intact, and nothing executes the stub any more, so the CLI can be+ # perfectly healthy without it. Kept apart from the PE-shape failure, which is+ # still a real one.+ _LAUNCHER_ABSENT = "the updated launcher is not on disk"_RESTORE_ATTEMPTS = 3def __init__(self) -> None:@@ -3976,18 +4183,27 @@ class _WindowsLauncherUpdateTransaction:# unusable, and the backup beside it can repair either.if self._is_valid_pe(self.launcher):return+ last_error: Optional[Tuple[Path, OSError]] = Nonefor recovery in (self.backup, self.stale, self.legacy_backup, self.shim):if recovery is not None and self._is_valid_pe(recovery):try:self._atomic_copy(recovery, self.launcher)except OSError as exc:- typer.echo(- f"Error: could not recover {self.launcher} from {recovery}: {exc}",- err = True,- )- typer.echo(f"Manual recovery copy retained at: {recovery}", err = True)- raise typer.Exit(1)+ # Try the next copy. The header check and the copy open the file+ # separately, so antivirus taking a candidate in between is a race+ # this loop can lose without the others being unusable, and giving+ # up on the first one turned a recoverable install into a failure.+ last_error = (recovery, exc)+ continuereturn+ if last_error is not None:+ recovery, exc = last_error+ typer.echo(+ f"Error: could not recover {self.launcher} from {recovery}: {exc}",+ err = True,+ )+ typer.echo(f"Manual recovery copy retained at: {recovery}", err = True)+ raise typer.Exit(1)@staticmethoddef _files_match(left: Path, right: Path) -> bool:@@ -4082,6 +4298,15 @@ class _WindowsLauncherUpdateTransaction:candidate that fails --version must not stop the next one being tried,and a launcher already in place and working must not be replaced by acandidate that is merely PE-shaped.++ Under Application Control that discrimination degrades to the PE-shape+ check, because no candidate can be told apart by running it: every+ --version attempt dies in CreateProcess. That is a real limitation and+ not a hidden one -- a PE-shaped but corrupt copy can be left in place --+ but it is also unavoidable, since the only way to tell a good stub from a+ corrupt one is to start it. It is confined to the case where the launcher+ was missing or truncated, since an intact one never reaches this loop:+ _launcher_health_error asks the interpreter and reports healthy."""if self._launcher_health_error() is None:return True@@ -4093,12 +4318,30 @@ class _WindowsLauncherUpdateTransaction:# one happened to be tried last.if candidates:self._restore_from(candidates[0])- return False-- def _launcher_health_error(self) -> Optional[str]:+ # No copy could be put back and started. A launcher that is simply gone,+ # or one the policy denies, is still not a broken CLI, so ask the+ # interpreter before giving up. Asked only here, after every candidate+ # has been tried, so a launcher that could have been recovered still is.+ return self._recovered_cli_health_error() is None++ def _launcher_runs_error(self) -> Optional[str]:+ """Whether THIS launcher file starts and answers --version.++ Deliberately about the file, not about the CLI: it is the only check that+ can catch a stub that is PE-shaped but corrupt, on every machine. Its+ caller decides what a policy denial means.++ The stub is probed first, and still is on a locked-down machine, which+ costs one denied-launch event per update there. That is a log entry, not+ a failure. Asking the interpreter instead would be quieter but blind: it+ cannot see a corrupt launcher on ANY machine, including the overwhelming+ majority that have no policy at all, which is the strictly worse trade.+ """assert self.launcher is not None+ if not self.launcher.exists():+ return self._LAUNCHER_ABSENTif not self._is_valid_pe(self.launcher):- return "the updated launcher is missing or is not a non-empty PE file"+ return "the updated launcher is not a non-empty PE file"try:result = subprocess.run([str(self.launcher), "--version"],@@ -4110,11 +4353,97 @@ class _WindowsLauncherUpdateTransaction:except subprocess.TimeoutExpired:return f"the updated launcher timed out after {self._VERSION_TIMEOUT_SECONDS} seconds"except OSError as exc:+ if _is_application_control_block(exc):+ return self._POLICY_BLOCKEDreturn f"the updated launcher could not run --version ({exc})"if result.returncode != 0:return f"the updated launcher returned {result.returncode} for --version"return None+ def _launcher_health_error(self) -> Optional[str]:+ """Whether the update left a working CLI -- the question that matters.++ Identical to _launcher_runs_error except when the launcher was denied by+ an Application Control policy. That denial happens before Python starts,+ so it says nothing about the update: the package can be perfectly+ healthy. Ask the signed interpreter beside it instead, or every update on+ such a machine reports failure and rolls a good install back (issue+ #8490). A launcher that fails to start for any other reason is the+ failure it always was.+ """+ error = self._launcher_runs_error()+ if error is self._POLICY_BLOCKED:+ return self._interpreter_health_error(error)+ return error++ def _recovered_cli_health_error(self) -> Optional[str]:+ """_launcher_health_error, once recovering the launcher has been ruled out.++ Absence is the difference. A missing launcher IS worth restoring, so+ _launcher_health_error keeps reporting it and validate_launcher goes on+ to put the previous one back. But quarantine deletes the unsigned stub+ rather than denying it, and no copy survives being restored either, so+ once every candidate has failed, absence says as little about the update+ as a policy denial does: ask the interpreter instead of failing a good+ update and rolling it back (issue #8490).+ """+ error = self._launcher_runs_error()+ if error is self._POLICY_BLOCKED or error is self._LAUNCHER_ABSENT:+ return self._interpreter_health_error(error)+ return error++ def _interpreter_health_error(self, reason: str) -> Optional[str]:+ """Health of the managed CLI when the launcher itself cannot be started.++ Answers the question validate_launcher actually has -- did the update+ leave a working CLI? -- on a machine where --version on the launcher can+ never succeed. Falls back to reporting the original block when there is+ no interpreter to ask.++ Isolated, alone among this module's managed invocations, because the+ launch it is predicting is itself isolated: build_update_command in+ studio/src-tauri/src/update.rs runs the desktop updater under+ Isolation::Isolated and clears PYTHONHOME/PYTHONPATH. Inheriting them+ here would let a foreign checkout on PYTHONPATH answer --version for a+ managed package the update actually broke, and validate_launcher would+ keep an update that the next desktop launch cannot start. -I implies -E,+ so it clears the same two variables the Rust side removes by hand.+ """+ assert self.launcher is not None+ python = self.launcher.parent / "python.exe"+ if not python.is_file():+ blocked = reason is self._POLICY_BLOCKED+ state = "is blocked by an Application Control policy" if blocked else "is missing"+ return (+ f"the updated launcher {state} and there is no managed interpreter "+ f"at {python} to ask instead"+ )+ try:+ result = subprocess.run(+ _managed_cli_argv(python, "--version", isolated = True),+ check = False,+ capture_output = True,+ # The import probe's ceiling, not the launcher's. --version on the+ # launcher is a process start; here it is a bare interpreter start+ # plus the whole CLI package import, which is exactly the work+ # _MANAGED_CLI_IMPORT_PROBE_TIMEOUT is generous for. Under the+ # antivirus scan that produced the quarantine this path exists to+ # survive, the launcher's 10 seconds would call a healthy update+ # broken and roll it back, once per recovery candidate.+ timeout = _MANAGED_CLI_IMPORT_PROBE_TIMEOUT,+ **_windows_hidden_subprocess_kwargs(),+ )+ except subprocess.TimeoutExpired:+ return (+ f"the managed Python CLI timed out after "+ f"{_MANAGED_CLI_IMPORT_PROBE_TIMEOUT} seconds"+ )+ except OSError as exc:+ return f"the managed Python CLI could not run --version ({exc})"+ if result.returncode != 0:+ return f"the managed Python CLI returned {result.returncode} for --version"+ return None+@staticmethoddef _managed_scripts_dir() -> Path:"""Scripts dir of the venv setup actually updates.@@ -4210,6 +4539,14 @@ class _WindowsLauncherUpdateTransaction:typer.echo(f"Manual recovery copy retained at: {self.backup}", err = True)raise typer.Exit(1)self._validated = True+ # Only once the launcher is actually back. A quarantined or locked stub can+ # be judged healthy through the interpreter while every attempt to restore+ # a copy failed, and deleting the copies there would throw away the only+ # material a later run could recover from. They are fixed names, so keeping+ # them costs nothing and the next update that does put a launcher back+ # clears them.+ if not self._is_valid_pe(self.launcher):+ returnfor orphan in (self.stale, self.backup, self.legacy_backup):if orphan is None:continue