Skip to content

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

Guard Windows Studio installs against active runtimes (#7764)

Etherld495a09bf027
diff --git a/install.ps1 b/install.ps1
index 2c1a1c00784..b478aabd96a 100644
--- a/install.ps1
+++ b/install.ps1
@@ -265,20 +265,163 @@ function Install-UnslothStudio {
$envOverrideVar = "STUDIO_HOME"
$envOverride = $env:STUDIO_HOME.Trim()
}
+ $defaultProfile = $null
+ try { $defaultProfile = [Environment]::GetFolderPath("UserProfile") } catch {}
+ $tauriProfile = if ($defaultProfile) { $defaultProfile } else { $env:USERPROFILE }
+
+ function Get-StudioFinalPath {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ $fullPath = [System.IO.Path]::GetFullPath($Path)
+ $fullRoot = [System.IO.Path]::GetPathRoot($fullPath)
+ if (-not $fullRoot -or $fullPath.Length -gt $fullRoot.Length) {
+ $fullPath = $fullPath.TrimEnd('\', '/')
+ }
+ $existingPath = $fullPath
+ $missingSegments = @()
+ while (-not (Test-Path -LiteralPath $existingPath)) {
+ $leaf = [System.IO.Path]::GetFileName($existingPath)
+ $parent = [System.IO.Path]::GetDirectoryName($existingPath)
+ if ([string]::IsNullOrEmpty($leaf) -or [string]::IsNullOrEmpty($parent)) {
+ return $fullPath
+ }
+ $missingSegments = @($leaf) + $missingSegments
+ $existingPath = $parent
+ }
+ if (-not ("UnslothStudioFinalPathV2" -as [type])) {
+ Add-Type -TypeDefinition @'
+using System;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Text;
+using Microsoft.Win32.SafeHandles;
+
+public static class UnslothStudioFinalPathV2
+{
+ private const uint FileShareRead = 0x00000001;
+ private const uint FileShareWrite = 0x00000002;
+ private const uint FileShareDelete = 0x00000004;
+ private const uint OpenExisting = 3;
+ private const uint FileFlagBackupSemantics = 0x02000000;
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateFileW(
+ string fileName,
+ uint desiredAccess,
+ uint shareMode,
+ IntPtr securityAttributes,
+ uint creationDisposition,
+ uint flagsAndAttributes,
+ IntPtr templateFile);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern uint GetFinalPathNameByHandleW(
+ SafeFileHandle file,
+ StringBuilder path,
+ uint pathLength,
+ uint flags);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern IntPtr OpenProcess(
+ uint desiredAccess,
+ bool inheritHandle,
+ int processId);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern bool QueryFullProcessImageNameW(
+ IntPtr process,
+ uint flags,
+ StringBuilder path,
+ ref uint pathLength);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool CloseHandle(IntPtr handle);
+
+ public static string Resolve(string path)
+ {
+ using (SafeFileHandle handle = CreateFileW(
+ path,
+ 0,
+ FileShareRead | FileShareWrite | FileShareDelete,
+ IntPtr.Zero,
+ OpenExisting,
+ FileFlagBackupSemantics,
+ IntPtr.Zero))
+ {
+ if (handle.IsInvalid)
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+
+ StringBuilder buffer = new StringBuilder(512);
+ uint length = GetFinalPathNameByHandleW(
+ handle, buffer, (uint)buffer.Capacity, 0);
+ if (length == 0)
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ if (length >= buffer.Capacity)
+ {
+ buffer = new StringBuilder((int)length + 1);
+ length = GetFinalPathNameByHandleW(
+ handle, buffer, (uint)buffer.Capacity, 0);
+ if (length == 0)
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ }
+ if (length >= buffer.Capacity)
+ throw new InvalidOperationException("Final path exceeded the allocated buffer");
+ return buffer.ToString();
+ }
+ }
+
+ public static string GetProcessImagePath(int processId)
+ {
+ const uint ProcessQueryLimitedInformation = 0x1000;
+ IntPtr process = OpenProcess(ProcessQueryLimitedInformation, false, processId);
+ if (process == IntPtr.Zero)
+ {
+ return null;
+ }
+ try
+ {
+ StringBuilder path = new StringBuilder(32768);
+ uint pathLength = (uint)path.Capacity;
+ return QueryFullProcessImageNameW(process, 0, path, ref pathLength)
+ ? path.ToString()
+ : null;
+ }
+ finally
+ {
+ CloseHandle(process);
+ }
+ }
+}
+'@
+ }
+ $resolved = [UnslothStudioFinalPathV2]::Resolve($existingPath)
+ if ($resolved.StartsWith('\\?\UNC\', [System.StringComparison]::OrdinalIgnoreCase)) {
+ $resolved = '\\' + $resolved.Substring(8)
+ } elseif ($resolved.StartsWith('\\?\', [System.StringComparison]::OrdinalIgnoreCase)) {
+ $resolved = $resolved.Substring(4)
+ }
+ foreach ($segment in $missingSegments) {
+ $resolved = [System.IO.Path]::Combine($resolved, $segment)
+ }
+ $resolvedRoot = [System.IO.Path]::GetPathRoot($resolved)
+ if ($resolvedRoot -and $resolved.Length -le $resolvedRoot.Length) {
+ return $resolvedRoot
+ }
+ return $resolved.TrimEnd('\', '/')
+ }
- # Custom Unsloth roots are not supported with --tauri (desktop app still
- # resolves %USERPROFILE%\.unsloth\studio). Pass through if override == legacy.
+ # Custom Unsloth roots are not supported with --tauri (the desktop app uses
+ # the Windows profile folder). Pass through if the override is that same root.
if ($TauriMode -and $envOverride) {
$_tauriOverride = $envOverride
if ($_tauriOverride -eq "~" -or $_tauriOverride -like "~/*" -or $_tauriOverride -like "~\*") {
$_tauriOverride = (Join-Path $env:USERPROFILE $_tauriOverride.Substring(1).TrimStart('/','\'))
}
try {
- $_tauriOverride = [System.IO.Path]::GetFullPath($_tauriOverride)
+ $_tauriOverride = Get-StudioFinalPath -Path $_tauriOverride
} catch {}
- $_legacyTauriRoot = Join-Path $env:USERPROFILE ".unsloth\studio"
+ $_legacyTauriRoot = Join-Path $tauriProfile ".unsloth\studio"
try {
- $_legacyTauriRoot = [System.IO.Path]::GetFullPath($_legacyTauriRoot)
+ $_legacyTauriRoot = Get-StudioFinalPath -Path $_legacyTauriRoot
} catch {}
# Strip trailing separators so ".../studio\" matches ".../studio".
$_trimSeps = @(
@@ -289,15 +432,13 @@ function Install-UnslothStudio {
$_legacyTauriRoot = $_legacyTauriRoot.TrimEnd($_trimSeps)
if ($_tauriOverride -ne $_legacyTauriRoot) {
Write-Host "ERROR: $envOverrideVar is not supported with --tauri." -ForegroundColor Red
- Write-Host " The desktop app still uses the legacy %USERPROFILE%\.unsloth\studio root." -ForegroundColor Red
+ Write-Host " The desktop app uses the Windows profile .unsloth\studio root." -ForegroundColor Red
Write-Host " Run install.ps1 without --tauri for custom-root shell installs," -ForegroundColor Yellow
Write-Host " or unset the env var for default desktop installs." -ForegroundColor Yellow
throw "$envOverrideVar is not supported with --tauri."
}
}
- $defaultProfile = $null
- try { $defaultProfile = [Environment]::GetFolderPath("UserProfile") } catch {}
# LOCALAPPDATA may be unset in service / CI contexts; Join-Path would abort
# under ErrorActionPreference=Stop without this guard.
@@ -1274,6 +1415,292 @@ exit 0
# without the Store, etc.) the script can proceed without it.
# We defer the hard failure to the Python / uv install branches
# below, where winget is actually invoked.
+ function Enter-StudioNamedMutex {
+ param([Parameter(Mandatory = $true)][string]$Name)
+ $mutex = [System.Threading.Mutex]::new($false, $Name)
+ $acquired = $false
+ try {
+ $acquired = $mutex.WaitOne(0)
+ } catch [System.Threading.AbandonedMutexException] {
+ $acquired = $true
+ }
+ if (-not $acquired) {
+ $mutex.Dispose()
+ return $null
+ }
+ return $mutex
+ }
+
+ function Get-StudioPathHash {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ $canonical = (Get-StudioFinalPath -Path $Path).ToUpperInvariant()
+ $bytes = [System.Text.Encoding]::UTF8.GetBytes($canonical)
+ $sha256 = [System.Security.Cryptography.SHA256]::Create()
+ try {
+ $digest = $sha256.ComputeHash($bytes)
+ } finally {
+ $sha256.Dispose()
+ }
+ $hex = -join ($digest | ForEach-Object { $_.ToString('x2') })
+ return $hex
+ }
+
+ function Test-StudioPathEqual {
+ param(
+ [Parameter(Mandatory = $true)][string]$Left,
+ [Parameter(Mandatory = $true)][string]$Right
+ )
+ try {
+ $leftFull = Get-StudioFinalPath -Path $Left
+ $rightFull = Get-StudioFinalPath -Path $Right
+ } catch {
+ Write-Host "[WARN] Could not resolve Studio path identity; using the runtime lock." -ForegroundColor Yellow
+ return $null
+ }
+ return [string]::Equals(
+ $leftFull, $rightFull, [System.StringComparison]::OrdinalIgnoreCase
+ )
+ }
+
+ function Get-StudioInstallMutexName {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ return "Global\UnslothStudioInstall-$(Get-StudioPathHash -Path $Path)"
+ }
+
+ function Get-StudioRuntimeMutexNameForSid {
+ param([Parameter(Mandatory = $true)][string]$Sid)
+ return "Global\UnslothStudioManagedEnvironment-$Sid"
+ }
+
+ function Get-StudioRuntimePathHash {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ # Byte-for-byte spelling: .NET and Python disagree on Unicode case (ß).
+ $canonical = Get-StudioFinalPath -Path $Path
+ $bytes = [System.Text.Encoding]::UTF8.GetBytes($canonical)
+ $sha256 = [System.Security.Cryptography.SHA256]::Create()
+ try {
+ $digest = $sha256.ComputeHash($bytes)
+ } finally {
+ $sha256.Dispose()
+ }
+ return (-join ($digest | ForEach-Object { $_.ToString('x2') }))
+ }
+
+ function Get-StudioRuntimeMutexNameForPath {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ return "Global\UnslothStudioManagedEnvironmentPath-$(Get-StudioRuntimePathHash -Path $Path)"
+ }
+
+ function Get-StudioCurrentUserSid {
+ $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
+ if ($null -eq $identity) {
+ throw "Could not determine the Windows user for the Studio runtime lock"
+ }
+ try {
+ $sid = if ($identity.User) { $identity.User.Value } else { $null }
+ } finally {
+ $identity.Dispose()
+ }
+ if ([string]::IsNullOrWhiteSpace($sid)) {
+ throw "Could not determine the Windows user SID for the Studio runtime lock"
+ }
+ return $sid
+ }
+
+ function Get-StudioRuntimeMutexName {
+ return (Get-StudioRuntimeMutexNameForSid -Sid (Get-StudioCurrentUserSid))
+ }
+
+ function Get-StudioRuntimeMutexNames {
+ param(
+ [AllowNull()]$TauriRootMatch,
+ [Parameter(Mandatory = $true)][string]$Path
+ )
+ $names = @()
+ # true: Tauri default -> SID lock. false: custom root -> path lock.
+ # null: identity unresolved -> take both and fail closed.
+ if ($TauriRootMatch -ne $false) {
+ $names += Get-StudioRuntimeMutexName
+ }
+ if ($TauriRootMatch -ne $true) {
+ $names += Get-StudioRuntimeMutexNameForPath -Path $Path
+ }
+ return $names
+ }
+
+ function Enter-StudioInstallMutex {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ return (Enter-StudioNamedMutex -Name (Get-StudioInstallMutexName -Path $Path))
+ }
+
+ function Exit-StudioInstallMutex {
+ param([System.Threading.Mutex]$Mutex)
+ if ($null -eq $Mutex) { return }
+ try { $Mutex.ReleaseMutex() } catch {} finally { $Mutex.Dispose() }
+ }
+
+ function Test-StudioProtectedPathMatch {
+ param(
+ [Parameter(Mandatory = $true)][string]$Candidate,
+ [Parameter(Mandatory = $true)][string]$ProtectedPath,
+ [switch]$Exact
+ )
+ $candidateKey = $Candidate.TrimEnd('\', '/')
+ $protectedKey = $ProtectedPath.TrimEnd('\', '/')
+ if ([string]::Equals(
+ $candidateKey, $protectedKey, [System.StringComparison]::OrdinalIgnoreCase
+ )) {
+ return $true
+ }
+ if ($Exact) { return $false }
+ $prefix = $protectedKey + [System.IO.Path]::DirectorySeparatorChar
+ return $candidateKey.StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)
+ }
+
+ function Get-StudioDesktopProcessesForCurrentUser {
+ $currentSid = Get-StudioCurrentUserSid
+ try {
+ $candidates = @(
+ Get-CimInstance -ClassName Win32_Process `
+ -Filter "Name = 'unsloth-studio.exe'" -ErrorAction Stop
+ )
+ } catch {
+ return
+ }
+ foreach ($candidate in $candidates) {
+ try {
+ $owner = Invoke-CimMethod -InputObject $candidate `
+ -MethodName GetOwnerSid -ErrorAction Stop
+ } catch {
+ continue
+ }
+ if ($null -eq $owner -or $owner.ReturnValue -ne 0) { continue }
+ if ([string]::Equals(
+ $owner.Sid, $currentSid, [System.StringComparison]::OrdinalIgnoreCase
+ )) {
+ [pscustomobject]@{
+ ProcessName = [System.IO.Path]::GetFileNameWithoutExtension($candidate.Name)
+ Id = [int]$candidate.ProcessId
+ }
+ }
+ }
+ }
+
+ function Get-RunningStudioVenvProcesses {
+ param(
+ [Parameter(Mandatory = $true)][string]$VenvPath,
+ [switch]$Exact
+ )
+ try {
+ $resolvedPath = (Get-StudioFinalPath -Path $VenvPath).TrimEnd('\', '/')
+ } catch {
+ throw "Could not resolve managed Studio process path '$VenvPath': $($_.Exception.Message)"
+ }
+
+ # Block only confirmed executable identities: a command line or working
+ # directory that merely mentions the path is not proof of an open file.
+ foreach ($process in @(Get-Process -ErrorAction SilentlyContinue)) {
+ $executable = $null
+ try { $executable = [UnslothStudioFinalPathV2]::GetProcessImagePath($process.Id) } catch { continue }
+ if (-not $executable) { continue }
+ try { $executable = Get-StudioFinalPath -Path $executable } catch { continue }
+ if (Test-StudioProtectedPathMatch -Candidate $executable -ProtectedPath $resolvedPath -Exact:$Exact) {
+ [pscustomobject]@{
+ ProcessName = $process.ProcessName
+ Id = $process.Id
+ Path = $executable
+ }
+ }
+ }
+ }
+ try {
+ $studioInstallMutex = Enter-StudioInstallMutex -Path $StudioHome
+ } catch {
+ Write-Host "[ERROR] Could not create the Studio install lock: $($_.Exception.Message)" -ForegroundColor Red
+ return (Exit-InstallFailure "Could not create the Studio install lock")
+ }
+ if ($null -eq $studioInstallMutex) {
+ Write-Host "[ERROR] Another Unsloth Studio install or repair is already running." -ForegroundColor Red
+ Write-Host " Wait for it to finish, then re-run install.ps1." -ForegroundColor Yellow
+ return (Exit-InstallFailure "Another Unsloth Studio install or repair is already running")
+ }
+
+ $studioRuntimeMutexes = @()
+ $tauriManagedStudioHome = if ($tauriProfile) {
+ Join-Path $tauriProfile ".unsloth\studio"
+ } else { $null }
+ $studioTauriRootMatch = if ($tauriManagedStudioHome) {
+ Test-StudioPathEqual -Left $StudioHome -Right $tauriManagedStudioHome
+ } else { $false }
+ $studioUsesTauriManagedRoot = ($studioTauriRootMatch -eq $true)
+ $studioNeedsRuntimeLock = $true
+ $studioUsesLegacyLayout = ($StudioRedirectMode -ne 'env') -or $studioUsesTauriManagedRoot
+ $studioAutoStartProcess = $null
+ try {
+ if ($studioNeedsRuntimeLock) {
+ try {
+ $studioRuntimeMutexNames = @(
+ Get-StudioRuntimeMutexNames -TauriRootMatch $studioTauriRootMatch -Path $StudioHome
+ )
+ foreach ($studioRuntimeMutexName in $studioRuntimeMutexNames) {
+ $mutex = Enter-StudioNamedMutex -Name $studioRuntimeMutexName
+ if ($null -eq $mutex) {
+ Write-Host "[ERROR] Unsloth Studio is starting or installation is already running." -ForegroundColor Red
+ Write-Host " Close Unsloth Studio completely, wait for the other operation, then re-run install.ps1." -ForegroundColor Yellow
+ return (Exit-InstallFailure "The managed Studio environment is busy")
+ }
+ $studioRuntimeMutexes += $mutex
+ }
+ } catch {
+ Write-Host "[ERROR] Could not create the Studio runtime lock: $($_.Exception.Message)" -ForegroundColor Red
+ return (Exit-InstallFailure "Could not create the Studio runtime lock")
+ }
+ }
+
+ $protectedProcessPaths = @(
+ [pscustomobject]@{ Path = $VenvDir; Exact = $false }
+ [pscustomobject]@{ Path = (Join-Path $StudioHome "bin\unsloth.exe"); Exact = $true }
+ )
+ if ($studioUsesLegacyLayout) {
+ $protectedProcessPaths += [pscustomobject]@{
+ Path = (Join-Path $StudioHome ".venv")
+ Exact = $false
+ }
+ $protectedProcessPaths += [pscustomobject]@{
+ Path = (Join-Path $env:USERPROFILE "unsloth_studio")
+ Exact = $false
+ }
+ }
+ $runningVenvProcessesById = @{}
+ foreach ($candidate in $protectedProcessPaths) {
+ foreach ($process in @(
+ Get-RunningStudioVenvProcesses -VenvPath $candidate.Path -Exact:$candidate.Exact
+ )) {
+ $processId = [string]$process.Id
+ if (-not $runningVenvProcessesById.ContainsKey($processId)) {
+ $runningVenvProcessesById[$processId] = $process
+ }
+ }
+ }
+ $runningVenvProcesses = @($runningVenvProcessesById.Values)
+ if ($runningVenvProcesses.Count -gt 0) {
+ $runningSummary = ($runningVenvProcesses | ForEach-Object { "$($_.ProcessName) (PID $($_.Id))" }) -join ", "
+ Write-Host "[ERROR] Unsloth Studio is using the managed Python environment." -ForegroundColor Red
+ Write-Host " Active processes: $runningSummary" -ForegroundColor Yellow
+ Write-Host " Close Unsloth Studio completely, including its tray process, then re-run install.ps1." -ForegroundColor Yellow
+ return (Exit-InstallFailure "The managed Python environment is still in use")
+ }
+
+ if (-not $TauriMode -and $studioUsesLegacyLayout) {
+ $runningDesktopApps = @(Get-StudioDesktopProcessesForCurrentUser)
+ if ($runningDesktopApps.Count -gt 0) {
+ $desktopSummary = ($runningDesktopApps | ForEach-Object { "PID $($_.Id)" }) -join ", "
+ Write-Host "[ERROR] The Unsloth Studio desktop app is still running ($desktopSummary)." -ForegroundColor Red
+ Write-Host " Close the app completely, including its tray process, then re-run install.ps1." -ForegroundColor Yellow
+ return (Exit-InstallFailure "The Unsloth Studio desktop app is still running")
+ }
+ }
+
Write-TauriLog "STEP" "Checking system dependencies"
$script:WingetAvailable = [bool](Get-Command winget -ErrorAction SilentlyContinue)
if ($script:WingetAvailable) {
@@ -2131,12 +2558,12 @@ exit 0
return (Exit-InstallFailure "Could not prepare existing environment for reinstall")
}
} elseif (
- $StudioRedirectMode -ne 'env' `
+ $studioUsesLegacyLayout `
-and (Test-Path -LiteralPath (Join-Path $StudioHome ".venv\Scripts\python.exe"))
) {
# Old layout (~/.unsloth/studio/.venv) exists -- validate before migrating.
- # Skip in env-mode so we don't blow away an unrelated .venv at the
- # workspace root (e.g. user's existing project Python venv).
+ # Skip custom-root env-mode installs so we do not replace an unrelated
+ # project .venv; an override of the managed default root still migrates.
$OldVenv = Join-Path $StudioHome ".venv"
$OldPy = Join-Path $OldVenv "Scripts\python.exe"
substep "found legacy Unsloth environment, validating..."
@@ -2162,12 +2589,11 @@ exit 0
Move-Item -LiteralPath $OldVenv -Destination $invalidVenv -Force -ErrorAction SilentlyContinue
}
} elseif (
- $StudioRedirectMode -ne 'env' `
+ $studioUsesLegacyLayout `
-and (Test-Path -LiteralPath (Join-Path $env:USERPROFILE "unsloth_studio\Scripts\python.exe"))
) {
# CWD-relative venv from old install.ps1 -> migrate to absolute path.
- # Skip in env-mode so we don't relocate the default-install venv into
- # the workspace root.
+ # Skip custom-root env-mode so it is not relocated into a workspace root.
$CwdVenv = Join-Path $env:USERPROFILE "unsloth_studio"
substep "found CWD-relative Unsloth environment, migrating to $VenvDir..."
Move-Item -LiteralPath $CwdVenv -Destination $VenvDir -Force
@@ -3582,6 +4008,11 @@ exit 0
# can trip over an unsupported `python` 3.14 or a Store stub on PATH even
# though the venv is fine). setup.ps1 Test-Path-guards this before use.
$env:UNSLOTH_SETUP_PYTHON = Join-Path $VenvDir "Scripts\python.exe"
+ # Installer already owns the runtime mutex; the child inherits it rather
+ # than deadlocking trying to reacquire it.
+ $previousSetupRuntimeGateHandoff = $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF
+ $hadPreviousSetupRuntimeGateHandoff = ($null -ne $previousSetupRuntimeGateHandoff)
+ $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"
try {
& $UnslothExe @studioArgs
$setupExit = $LASTEXITCODE
@@ -3596,6 +4027,11 @@ exit 0
} else {
Remove-Item Env:UNSLOTH_TAURI_MODE -ErrorAction SilentlyContinue
}
+ if ($hadPreviousSetupRuntimeGateHandoff) {
+ $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = $previousSetupRuntimeGateHandoff
+ } else {
+ Remove-Item Env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF -ErrorAction SilentlyContinue
+ }
Remove-Item Env:UNSLOTH_LOCAL_LLAMA_CPP_DIR -ErrorAction SilentlyContinue
Remove-Item Env:UNSLOTH_INSTALL_ROLLBACK_MANAGED -ErrorAction SilentlyContinue
Remove-Item Env:UNSLOTH_SETUP_PYTHON -ErrorAction SilentlyContinue
@@ -3753,7 +4189,21 @@ exit 0
Write-Host ""
$reply = Read-Host " Start Unsloth Studio now? [Y/n]"
if ([string]::IsNullOrWhiteSpace($reply) -or $reply -match '^[Yy]') {
- & $UnslothExe studio -p 8888
+ # Keep both locks until the process exists: a second installer can
+ # then take them, but its scan sees Studio before it mutates.
+ $_runtimeGateHandoff = $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF
+ try {
+ $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"
+ $studioAutoStartProcess = Start-Process -FilePath $UnslothExe `
+ -ArgumentList @("studio", "-p", "8888") `
+ -NoNewWindow -PassThru
+ } finally {
+ if ($null -eq $_runtimeGateHandoff) {
+ Remove-Item Env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF -ErrorAction SilentlyContinue
+ } else {
+ $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = $_runtimeGateHandoff
+ }
+ }
} else {
step "launch" "to start later, run:"
substep "unsloth studio -p 8888"
@@ -3782,6 +4232,15 @@ exit 0
substep "(add -H 0.0.0.0 --cloudflare for a public Cloudflare HTTPS link, or --secure to keep the raw port private; anyone with the API key can run code)"
Write-Host ""
}
+ } finally {
+ for ($i = $studioRuntimeMutexes.Count - 1; $i -ge 0; $i--) {
+ Exit-StudioInstallMutex -Mutex $studioRuntimeMutexes[$i]
+ }
+ Exit-StudioInstallMutex -Mutex $studioInstallMutex
+ }
+ if ($null -ne $studioAutoStartProcess) {
+ $studioAutoStartProcess.WaitForExit()
+ }
}
Install-UnslothStudio @args
diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.toml
index 8300f69e0a3..c4f8db77aea 100644
--- a/studio/src-tauri/Cargo.toml
+++ b/studio/src-tauri/Cargo.toml
@@ -57,7 +57,7 @@ webkit2gtk-sys = "2.0.2"
[target.'cfg(windows)'.dependencies]
winreg = "0.10"
windows = { version = "0.62.2", features = ["Win32_System_Threading"] }
-windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_Console", "Win32_System_JobObjects", "Win32_System_Threading"] }
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Threading"] }
[build-dependencies]
tauri-build = { version = "2", features = [] }
diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rs
index 4f575b0c0e4..86ca3b81891 100644
--- a/studio/src-tauri/src/commands.rs
+++ b/studio/src-tauri/src/commands.rs
@@ -158,7 +158,9 @@ pub async fn check_install_status() -> bool {
cmd.env_remove("UNSLOTH_STUDIO_HOME");
cmd.env_remove("STUDIO_HOME");
- let mut child = match cmd.spawn() {
+ let mut child = match process::with_studio_runtime_launch_guard(|| {
+ cmd.spawn().map_err(|error| error.to_string())
+ }) {
Ok(c) => c,
Err(e) => {
warn!("Install check: failed to spawn {:?}: {}", bin, e);
@@ -488,8 +490,17 @@ pub fn open_models_dir(window: tauri::WebviewWindow, path: String) -> Result<(),
pub async fn start_install(
app: AppHandle,
state: tauri::State<'_, install::InstallState>,
+ backend_state: tauri::State<'_, BackendState>,
diagnostics: tauri::State<'_, DiagnosticsState>,
) -> Result<(), String> {
+ if has_owned_backend(&backend_state)? {
+ return Err(
+ "The Unsloth backend is still running. Stop it before starting installation."
+ .to_string(),
+ );
+ }
+ block_external_conflict(&[]).await?;
+
let state = state.inner().clone();
let diagnostics_state = diagnostics.inner().clone();
tokio::task::spawn_blocking(move || install::run_install(app, state, diagnostics_state))
diff --git a/studio/src-tauri/src/desktop_auth.rs b/studio/src-tauri/src/desktop_auth.rs
index 32e777d1b6f..c0560300cf9 100644
--- a/studio/src-tauri/src/desktop_auth.rs
+++ b/studio/src-tauri/src/desktop_auth.rs
@@ -240,7 +240,11 @@ async fn provision_desktop_auth() -> Result<(), String> {
cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
}
- let output = tokio::time::timeout(std::time::Duration::from_secs(30), cmd.output())
+ let child = crate::process::with_studio_runtime_launch_guard(|| {
+ cmd.spawn().map_err(|error| error.to_string())
+ })
+ .map_err(|e| format!("Desktop auth provisioning failed: {}", e))?;
+ let output = tokio::time::timeout(std::time::Duration::from_secs(30), child.wait_with_output())
.await
.map_err(|_| "Desktop auth provisioning timed out after 30s".to_string())?
.map_err(|e| format!("Desktop auth provisioning failed: {}", e))?;
diff --git a/studio/src-tauri/src/preflight/managed.rs b/studio/src-tauri/src/preflight/managed.rs
index b43e5936572..532c5040d56 100644
--- a/studio/src-tauri/src/preflight/managed.rs
+++ b/studio/src-tauri/src/preflight/managed.rs
@@ -318,7 +318,9 @@ async fn run_cli_probe(bin: &Path, args: &[&str]) -> bool {
cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
}
- let Ok(mut child) = cmd.spawn() else {
+ let Ok(mut child) = crate::process::with_studio_runtime_launch_guard(|| {
+ cmd.spawn().map_err(|error| error.to_string())
+ }) else {
info!(
"Managed preflight probe {:?} failed to spawn in {}ms",
args,
@@ -362,7 +364,9 @@ async fn probe_cli_capability(bin: &Path) -> Option<DesktopCapability> {
cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
}
- let Ok(mut child) = cmd.spawn() else {
+ let Ok(mut child) = crate::process::with_studio_runtime_launch_guard(|| {
+ cmd.spawn().map_err(|error| error.to_string())
+ }) else {
info!(
"Managed desktop-capabilities probe failed to spawn in {}ms",
started.elapsed().as_millis()
diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rs
index 908f1b4b904..78e62d465c9 100644
--- a/studio/src-tauri/src/process.rs
+++ b/studio/src-tauri/src/process.rs
@@ -12,6 +12,530 @@ use tauri::{AppHandle, Emitter, Manager};
const MAX_LOG_LINES: usize = 1000;
+#[cfg(windows)]
+const STUDIO_MANAGED_RUNTIME_MUTEX_PREFIX: &str = "Global\\UnslothStudioManagedEnvironment-";
+
+#[cfg(windows)]
+pub(crate) const STUDIO_RUNTIME_GATE_HANDOFF_ENV: &str = "_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF";
+
+#[cfg(windows)]
+#[derive(Debug)]
+struct StudioManagedRuntimeLaunchGuard {
+ handle: windows_sys::Win32::Foundation::HANDLE,
+}
+
+#[cfg(windows)]
+impl Drop for StudioManagedRuntimeLaunchGuard {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = windows_sys::Win32::System::Threading::ReleaseMutex(self.handle);
+ let _ = windows_sys::Win32::Foundation::CloseHandle(self.handle);
+ }
+ }
+}
+
+#[cfg(windows)]
+fn acquire_named_studio_runtime_launch_guard(
+ name: &str,
+) -> Result<StudioManagedRuntimeLaunchGuard, String> {
+ const WAIT_OBJECT_0: u32 = 0x0000_0000;
+ const WAIT_ABANDONED: u32 = 0x0000_0080;
+ const WAIT_TIMEOUT: u32 = 0x0000_0102;
+
+ let wide_name: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
+ let handle = unsafe {
+ windows_sys::Win32::System::Threading::CreateMutexW(std::ptr::null(), 0, wide_name.as_ptr())
+ };
+ if handle.is_null() {
+ return Err(format!(
+ "Could not create the Studio runtime lock: {}",
+ std::io::Error::last_os_error()
+ ));
+ }
+
+ let wait = unsafe { windows_sys::Win32::System::Threading::WaitForSingleObject(handle, 0) };
+ match wait {
+ WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(StudioManagedRuntimeLaunchGuard { handle }),
+ WAIT_TIMEOUT => {
+ unsafe {
+ let _ = windows_sys::Win32::Foundation::CloseHandle(handle);
+ }
+ Err(
+ "Unsloth installation is modifying the managed environment. Wait for it to finish, then start the backend again."
+ .to_string(),
+ )
+ }
+ _ => {
+ let error = std::io::Error::last_os_error();
+ unsafe {
+ let _ = windows_sys::Win32::Foundation::CloseHandle(handle);
+ }
+ Err(format!(
+ "Could not acquire the Studio runtime lock: {error}"
+ ))
+ }
+ }
+}
+
+#[cfg(windows)]
+fn studio_runtime_mutex_name_for_sid(sid: &str) -> String {
+ format!("{STUDIO_MANAGED_RUNTIME_MUTEX_PREFIX}{sid}")
+}
+
+#[cfg(windows)]
+fn current_windows_user_sid() -> Result<String, String> {
+ use windows_sys::Win32::Security::{
+ GetSidIdentifierAuthority, GetSidSubAuthority, GetSidSubAuthorityCount,
+ GetTokenInformation, IsValidSid, TokenUser, TOKEN_QUERY, TOKEN_USER,
+ };
+ use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
+
+ let mut token = std::ptr::null_mut();
+ if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
+ return Err(format!(
+ "Could not open the Windows user token for the Studio runtime lock: {}",
+ std::io::Error::last_os_error()
+ ));
+ }
+
+ let result = (|| -> Result<String, String> {
+ let mut required = 0_u32;
+ unsafe {
+ GetTokenInformation(token, TokenUser, std::ptr::null_mut(), 0, &mut required);
+ }
+ if required == 0 {
+ return Err(format!(
+ "Could not size the Windows user SID for the Studio runtime lock: {}",
+ std::io::Error::last_os_error()
+ ));
+ }
+
+ let word_size = std::mem::size_of::<usize>();
+ let mut buffer = vec![0_usize; (required as usize).div_ceil(word_size)];
+ if unsafe {
+ GetTokenInformation(
+ token,
+ TokenUser,
+ buffer.as_mut_ptr().cast(),
+ required,
+ &mut required,
+ )
+ } == 0
+ {
+ return Err(format!(
+ "Could not read the Windows user SID for the Studio runtime lock: {}",
+ std::io::Error::last_os_error()
+ ));
+ }
+
+ let token_user = unsafe { &*(buffer.as_ptr().cast::<TOKEN_USER>()) };
+ let sid = token_user.User.Sid;
+ if sid.is_null() || unsafe { IsValidSid(sid) } == 0 {
+ return Err("Windows returned an invalid user SID for the Studio runtime lock".into());
+ }
+
+ let authority_ptr = unsafe { GetSidIdentifierAuthority(sid) };
+ let count_ptr = unsafe { GetSidSubAuthorityCount(sid) };
+ if authority_ptr.is_null() || count_ptr.is_null() {
+ return Err(
+ "Could not inspect the Windows user SID for the Studio runtime lock".into(),
+ );
+ }
+ let authority = unsafe { (*authority_ptr).Value }
+ .iter()
+ .fold(0_u64, |value, byte| (value << 8) | u64::from(*byte));
+ let revision = unsafe { *sid.cast::<u8>() };
+ let count = unsafe { *count_ptr };
+ let mut sid_text = format!("S-{revision}-{authority}");
+ for index in 0..u32::from(count) {
+ let sub_authority = unsafe { GetSidSubAuthority(sid, index) };
+ if sub_authority.is_null() {
+ return Err(
+ "Could not inspect the Windows user SID for the Studio runtime lock".into(),
+ );
+ }
+ sid_text.push_str(&format!("-{}", unsafe { *sub_authority }));
+ }
+ Ok(sid_text)
+ })();
+
+ unsafe {
+ let _ = windows_sys::Win32::Foundation::CloseHandle(token);
+ }
+ result
+}
+
+#[cfg(windows)]
+fn acquire_studio_runtime_launch_guard() -> Result<StudioManagedRuntimeLaunchGuard, String> {
+ let name = studio_runtime_mutex_name_for_sid(&current_windows_user_sid()?);
+ acquire_named_studio_runtime_launch_guard(&name)
+}
+
+/// Serialize creation of managed-environment children with install/repair.
+///
+/// The guard ends when the sync operation returns. The installer takes the same
+/// mutex then scans for managed processes, so holding it through child creation
+/// closes the race without carrying a thread-owned Win32 mutex across an await.
+#[cfg(windows)]
+fn with_named_studio_runtime_launch_guard<T>(
+ name: &str,
+ operation: impl FnOnce() -> Result<T, String>,
+) -> Result<T, String> {
+ let _runtime_launch_guard = acquire_named_studio_runtime_launch_guard(name)?;
+ operation()
+}
+
+pub(crate) fn with_studio_runtime_launch_guard<T>(
+ operation: impl FnOnce() -> Result<T, String>,
+) -> Result<T, String> {
+ #[cfg(windows)]
+ {
+ let name = studio_runtime_mutex_name_for_sid(&current_windows_user_sid()?);
+ return with_named_studio_runtime_launch_guard(&name, operation);
+ }
+ #[cfg(not(windows))]
+ operation()
+}
+
+#[cfg(windows)]
+fn normalized_existing_windows_path(path: &std::path::Path) -> Result<String, String> {
+ let resolved = std::fs::canonicalize(path)
+ .map_err(|error| format!("Could not resolve managed Studio path {:?}: {error}", path))?;
+ Ok(resolved
+ .to_string_lossy()
+ .trim_end_matches(['\\', '/'])
+ .replace('/', "\\"))
+}
+
+#[cfg(windows)]
+fn windows_ordinal_ignore_case_equal(left: &[u16], right: &[u16]) -> Result<bool, String> {
+ use windows_sys::Win32::Globalization::{CompareStringOrdinal, CSTR_EQUAL};
+
+ let left_length = i32::try_from(left.len())
+ .map_err(|_| "Normalized Studio path exceeds Win32 comparison limits".to_string())?;
+ let right_length = i32::try_from(right.len())
+ .map_err(|_| "Normalized Studio path exceeds Win32 comparison limits".to_string())?;
+ let comparison = unsafe {
+ CompareStringOrdinal(left.as_ptr(), left_length, right.as_ptr(), right_length, 1)
+ };
+ if comparison == 0 {
+ return Err(format!(
+ "Could not compare normalized Studio paths: {}",
+ std::io::Error::last_os_error()
+ ));
+ }
+ Ok(comparison == CSTR_EQUAL)
+}
+
+#[cfg(windows)]
+fn windows_paths_are_equal(left: &str, right: &str) -> Result<bool, String> {
+ let left_wide: Vec<u16> = left.encode_utf16().collect();
+ let right_wide: Vec<u16> = right.encode_utf16().collect();
+ windows_ordinal_ignore_case_equal(&left_wide, &right_wide)
+}
+
+#[cfg(windows)]
+fn windows_path_is_within(candidate: &str, root: &str) -> Result<bool, String> {
+ let candidate_wide: Vec<u16> = candidate.encode_utf16().collect();
+ let root_wide: Vec<u16> = root.encode_utf16().collect();
+ if candidate_wide.len() < root_wide.len() {
+ return Ok(false);
+ }
+
+ let same_root =
+ windows_ordinal_ignore_case_equal(&candidate_wide[..root_wide.len()], &root_wide)?;
+ Ok(same_root
+ && (candidate_wide.len() == root_wide.len()
+ || candidate_wide[root_wide.len()] == u16::from(b'\\')))
+}
+
+#[cfg(windows)]
+fn process_image_path(process_id: u32) -> Option<std::path::PathBuf> {
+ use std::os::windows::ffi::OsStringExt;
+ use windows_sys::Win32::System::Threading::{
+ OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32,
+ PROCESS_QUERY_LIMITED_INFORMATION,
+ };
+
+ let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, process_id) };
+ if process.is_null() {
+ return None;
+ }
+ let mut buffer = vec![0_u16; 32_768];
+ let mut length = buffer.len() as u32;
+ let ok = unsafe {
+ QueryFullProcessImageNameW(
+ process,
+ PROCESS_NAME_WIN32,
+ buffer.as_mut_ptr(),
+ &mut length,
+ )
+ };
+ unsafe {
+ let _ = windows_sys::Win32::Foundation::CloseHandle(process);
+ }
+ if ok == 0 {
+ return None;
+ }
+ Some(std::path::PathBuf::from(std::ffi::OsString::from_wide(
+ &buffer[..length as usize],
+ )))
+}
+
+/// Reject an update when a process image runs from the target venv or the exact
+/// supported Studio shim.
+///
+/// Callers must hold the runtime launch mutex across the whole mutation: this
+/// scan finds older consumers, and the gate blocks new launches after it.
+pub(crate) fn ensure_managed_environment_is_idle(
+ managed_binary: &std::path::Path,
+) -> Result<(), String> {
+ #[cfg(not(windows))]
+ {
+ let _ = managed_binary;
+ return Ok(());
+ }
+
+ #[cfg(windows)]
+ {
+ use windows_sys::Win32::Foundation::{
+ CloseHandle, GetLastError, ERROR_NO_MORE_FILES, INVALID_HANDLE_VALUE,
+ };
+ use windows_sys::Win32::System::Diagnostics::ToolHelp::{
+ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
+ TH32CS_SNAPPROCESS,
+ };
+
+ let venv = managed_binary
+ .parent()
+ .and_then(std::path::Path::parent)
+ .ok_or_else(|| {
+ format!(
+ "Could not determine the managed Studio environment for {:?}",
+ managed_binary
+ )
+ })?;
+ let studio_home = venv.parent().ok_or_else(|| {
+ format!(
+ "Could not determine the managed Studio root for {:?}",
+ managed_binary
+ )
+ })?;
+ let canonical_root = normalized_existing_windows_path(venv)?;
+ let shim = studio_home.join("bin").join("unsloth.exe");
+ let canonical_shim = shim
+ .exists()
+ .then(|| normalized_existing_windows_path(&shim))
+ .transpose()?;
+
+ let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
+ if snapshot == INVALID_HANDLE_VALUE {
+ return Err(format!(
+ "Could not inspect running processes before Studio update: {}",
+ std::io::Error::last_os_error()
+ ));
+ }
+
+ let result = (|| {
+ let mut entry = PROCESSENTRY32W {
+ dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32,
+ ..Default::default()
+ };
+ let mut has_entry = unsafe { Process32FirstW(snapshot, &mut entry) };
+ if has_entry == 0 {
+ let error = unsafe { GetLastError() };
+ if error == ERROR_NO_MORE_FILES {
+ return Ok(());
+ }
+ return Err(format!(
+ "Could not enumerate running processes before Studio update: {}",
+ std::io::Error::from_raw_os_error(error as i32)
+ ));
+ }
+
+ loop {
+ if let Some(image) = process_image_path(entry.th32ProcessID) {
+ if let Ok(image_key) = normalized_existing_windows_path(&image) {
+ let image_is_shim = canonical_shim
+ .as_ref()
+ .map(|shim| windows_paths_are_equal(&image_key, shim))
+ .transpose()?
+ .unwrap_or(false);
+ if windows_path_is_within(&image_key, &canonical_root)? || image_is_shim {
+ let name_length = entry
+ .szExeFile
+ .iter()
+ .position(|character| *character == 0)
+ .unwrap_or(entry.szExeFile.len());
+ let name = String::from_utf16_lossy(&entry.szExeFile[..name_length]);
+ return Err(format!(
+ "The managed Studio environment is in use by {} (PID {}). Stop that process, then retry the update.",
+ name, entry.th32ProcessID
+ ));
+ }
+ }
+ }
+
+ has_entry = unsafe { Process32NextW(snapshot, &mut entry) };
+ if has_entry == 0 {
+ let error = unsafe { GetLastError() };
+ if error == ERROR_NO_MORE_FILES {
+ break;
+ }
+ return Err(format!(
+ "Could not finish enumerating running processes before Studio update: {}",
+ std::io::Error::from_raw_os_error(error as i32)
+ ));
+ }
+ }
+ Ok(())
+ })();
+
+ unsafe {
+ let _ = CloseHandle(snapshot);
+ }
+ result
+ }
+}
+#[cfg(all(test, windows))]
+mod studio_runtime_launch_guard_tests {
+ use super::*;
+
+ #[test]
+ fn blocks_a_second_launcher_until_the_first_releases_the_gate() {
+ let name = format!(
+ "Local\\UnslothStudioRuntimeGateTest-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ );
+ let first = acquire_named_studio_runtime_launch_guard(&name).unwrap();
+ let contender_name = name.clone();
+ let error = std::thread::spawn(move || {
+ acquire_named_studio_runtime_launch_guard(&contender_name)
+ .err()
+ .expect("second launcher unexpectedly acquired the gate")
+ })
+ .join()
+ .unwrap();
+ assert!(error.contains("installation is modifying"));
+ drop(first);
+ acquire_named_studio_runtime_launch_guard(&name).unwrap();
+ }
+
+ #[test]
+ fn guarded_operation_is_skipped_while_busy_and_runs_after_release() {
+ let name = format!(
+ "Local\\UnslothStudioRuntimeGateOperationTest-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ );
+ let first = acquire_named_studio_runtime_launch_guard(&name).unwrap();
+ let invoked = Arc::new(AtomicBool::new(false));
+ let contender_invoked = invoked.clone();
+ let contender_name = name.clone();
+ let error = std::thread::spawn(move || {
+ with_named_studio_runtime_launch_guard(&contender_name, || {
+ contender_invoked.store(true, Ordering::SeqCst);
+ Ok(())
+ })
+ .unwrap_err()
+ })
+ .join()
+ .unwrap();
+ assert!(error.contains("installation is modifying"));
+ assert!(!invoked.load(Ordering::SeqCst));
+
+ drop(first);
+ with_named_studio_runtime_launch_guard(&name, || {
+ invoked.store(true, Ordering::SeqCst);
+ Ok(())
+ })
+ .unwrap();
+ assert!(invoked.load(Ordering::SeqCst));
+ }
+
+ #[test]
+ fn guarded_operation_releases_the_gate_after_an_operation_error() {
+ let name = format!(
+ "Local\\UnslothStudioRuntimeGateErrorTest-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ );
+ let error = with_named_studio_runtime_launch_guard(&name, || {
+ Err::<(), _>("synthetic spawn failure".to_string())
+ })
+ .unwrap_err();
+ assert_eq!(error, "synthetic spawn failure");
+
+ with_named_studio_runtime_launch_guard(&name, || Ok(())).unwrap();
+ }
+
+ #[test]
+ fn managed_environment_scan_finds_a_process_inside_the_target_root() {
+ let current_exe = std::env::current_exe().unwrap();
+ let target_root = current_exe.parent().unwrap();
+ let managed_binary = target_root.join("Scripts").join("unsloth.exe");
+
+ let error = ensure_managed_environment_is_idle(&managed_binary).unwrap_err();
+ assert!(error.contains("managed Studio environment is in use"));
+ }
+
+ #[test]
+ fn windows_path_containment_requires_a_component_boundary() {
+ assert!(windows_path_is_within(
+ r"c:\\users\\pc\\.unsloth\\studio\\unsloth_studio\\scripts\\python.exe",
+ r"c:\\users\\pc\\.unsloth\\studio\\unsloth_studio"
+ )
+ .unwrap());
+ assert!(!windows_path_is_within(
+ r"c:\\users\\pc\\.unsloth\\studio\\unsloth_studio_old\\scripts\\python.exe",
+ r"c:\\users\\pc\\.unsloth\\studio\\unsloth_studio"
+ )
+ .unwrap());
+ }
+
+ #[test]
+ fn windows_path_comparison_uses_ordinal_case_insensitive_semantics() {
+ assert!(windows_paths_are_equal(
+ r"C:\\Users\\PC\\.Unsloth\\Studio",
+ r"c:\\users\\pc\\.unsloth\\studio"
+ )
+ .unwrap());
+
+ let dotted_capital_root = r"C:\\Users\\İ\\.unsloth\\studio";
+ let expanded_lowercase_root = "C:\\\\Users\\\\i\u{307}\\\\.unsloth\\\\studio";
+ assert_eq!(
+ dotted_capital_root.to_lowercase(),
+ expanded_lowercase_root.to_lowercase()
+ );
+ assert!(!windows_paths_are_equal(dotted_capital_root, expanded_lowercase_root).unwrap());
+
+ let unrelated_image = format!("{expanded_lowercase_root}\\\\Scripts\\\\python.exe");
+ assert!(!windows_path_is_within(&unrelated_image, dotted_capital_root).unwrap());
+ }
+
+ #[test]
+ fn runtime_mutex_name_is_global_and_user_scoped() {
+ let first = studio_runtime_mutex_name_for_sid("S-1-5-21-111-222-333-1001");
+ let second = studio_runtime_mutex_name_for_sid("S-1-5-21-111-222-333-1002");
+ assert_eq!(
+ first,
+ "Global\\UnslothStudioManagedEnvironment-S-1-5-21-111-222-333-1001"
+ );
+ assert_ne!(first, second);
+ assert!(current_windows_user_sid().unwrap().starts_with("S-1-"));
+ }
+}
+
#[allow(dead_code)]
pub(crate) enum OwnedBackendHandle {
Spawned {
@@ -556,6 +1080,9 @@ pub fn start_backend(
shutdown: &ShutdownFlag,
diagnostics_state: &DiagnosticsState,
) -> Result<u64, String> {
+ #[cfg(windows)]
+ let _runtime_launch_guard = acquire_studio_runtime_launch_guard()?;
+
let bin = match resolve_backend_binary() {
Ok(bin) => bin,
Err(msg) => {
@@ -578,6 +1105,9 @@ pub fn start_backend(
.stdout(Stdio::piped())
.stderr(Stdio::piped());
+ #[cfg(windows)]
+ cmd.env(STUDIO_RUNTIME_GATE_HANDOFF_ENV, "1");
+
if let Some(native_state) = app.try_state::<crate::native_intents::NativeIntakeState>() {
cmd.env(
crate::native_backend_lease::LEASE_SECRET_ENV,
diff --git a/studio/src-tauri/src/update.rs b/studio/src-tauri/src/update.rs
index 71318427226..bb87b4f741b 100644
--- a/studio/src-tauri/src/update.rs
+++ b/studio/src-tauri/src/update.rs
@@ -97,6 +97,8 @@ fn spawn_update(
// desktop bundle so it skips re-creating CLI launchers/.app/.desktop
// shortcuts (Tauri owns its own bundle entries).
cmd.env("UNSLOTH_TAURI_UPDATE", "1");
+ #[cfg(windows)]
+ cmd.env(crate::process::STUDIO_RUNTIME_GATE_HANDOFF_ENV, "1");
// read_lossy_lines decodes as UTF-8, and here the child is Python itself,
// which otherwise encodes redirected streams with the locale code page.
@@ -285,33 +287,27 @@ fn run_backend_update_with_terminal_events(
};
let _ = app.emit(progress_event, "Starting backend update...");
- let (stdout, stderr) = match spawn_update(&bin, &state) {
- Ok(handles) => handles,
- Err(msg) => {
- diagnostics::finish_attempt(
- &diagnostics,
- &attempt,
- None,
- false,
- Some(format!("spawn_update: {msg}")),
- );
- clear_current_attempt(&state);
- return Err(msg);
- }
- };
- let threads = stream_output(
- &app,
- progress_event,
- diagnostics.clone(),
- attempt.clone(),
- stdout,
- stderr,
- );
+ // Update mutates the managed environment for its whole lifetime. This function
+ // is synchronous, so the thread-owned Win32 mutex never crosses an await.
+ let result = crate::process::with_studio_runtime_launch_guard(|| {
+ crate::process::ensure_managed_environment_is_idle(&bin)?;
+ let (stdout, stderr) =
+ spawn_update(&bin, &state).map_err(|msg| format!("spawn_update: {msg}"))?;
+ let threads = stream_output(
+ &app,
+ progress_event,
+ diagnostics.clone(),
+ attempt.clone(),
+ stdout,
+ stderr,
+ );
- let result = wait_for_exit(&state);
- for handle in threads {
- let _ = handle.join();
- }
+ let result = wait_for_exit(&state);
+ for handle in threads {
+ let _ = handle.join();
+ }
+ result
+ });
match result {
Ok((status, _)) if status.success() => {
diff --git a/tests/python/test_studio_runtime_gate.py b/tests/python/test_studio_runtime_gate.py
new file mode 100644
index 00000000000..afbca8cb142
--- /dev/null
+++ b/tests/python/test_studio_runtime_gate.py
@@ -0,0 +1,429 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+from __future__ import annotations
+
+import ctypes
+import hashlib
+import json
+import os
+import subprocess
+import sys
+import threading
+from ctypes import wintypes
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from unsloth_cli import _studio_runtime_gate as gate
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+STUDIO_COMMAND = REPO_ROOT / "unsloth_cli" / "commands" / "studio.py"
+
+
+def test_runtime_mutex_name_matches_installer_and_tauri():
+ sid = "S-1-5-21-111-222-333-1001"
+ expected = f"Global\\UnslothStudioManagedEnvironment-{sid}"
+ assert gate.runtime_mutex_name_for_sid(sid) == expected
+ install_source = (REPO_ROOT / "install.ps1").read_text(encoding = "utf-8")
+ rust_source = (REPO_ROOT / "studio" / "src-tauri" / "src" / "process.rs").read_text(
+ encoding = "utf-8"
+ )
+ assert '"Global\\UnslothStudioManagedEnvironment-$Sid"' in install_source
+ assert '"Global\\\\UnslothStudioManagedEnvironment-"' in rust_source
+
+
+def test_custom_root_mutex_name_matches_installer_hash(monkeypatch):
+ root = Path(r"C:\\custom\\studio")
+ canonical = r"C:\\custom\\studio"
+ monkeypatch.setattr(gate, "uses_tauri_managed_root", lambda _path: False)
+ monkeypatch.setattr(gate, "_resolved_windows_path", lambda _path: canonical)
+ expected_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
+ assert gate.runtime_mutex_name_for_studio_home(root) == (
+ f"Global\\UnslothStudioManagedEnvironmentPath-{expected_hash}"
+ )
+
+
[email protected](os.name != "nt", reason = "Windows ordinal comparison is required")
+def test_tauri_root_classification_uses_windows_ordinal_case_semantics(monkeypatch):
+ profile = Path(r"C:\Users\Straße")
+ monkeypatch.setattr(gate, "_windows_profile_path", lambda: profile)
+
+ assert gate.uses_tauri_managed_root(Path(r"C:\Users\straße\.unsloth\studio"))
+ assert not gate.uses_tauri_managed_root(Path(r"C:\Users\Strasse\.unsloth\studio"))
+
+
+def test_runtime_gate_handoff_is_one_shot(monkeypatch):
+ monkeypatch.setenv(gate._RUNTIME_GATE_HANDOFF_ENV, "1")
+ assert gate.consume_runtime_gate_handoff() is True
+ assert gate.consume_runtime_gate_handoff() is False
+
+
+def test_terminal_launch_boundaries_use_the_runtime_gate():
+ source = STUDIO_COMMAND.read_text(encoding = "utf-8")
+ assert source.count("with _studio_runtime_launch_guard(") >= 4
+ assert "runtime_gate_child_environment()" in source
+ assert "runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()" in source
+
+
+def test_terminal_update_holds_the_gate_through_environment_mutation():
+ source = STUDIO_COMMAND.read_text(encoding = "utf-8")
+ body = source[source.index("def update(") : source.index("def _release_self_exe_lock_windows")]
+ consume = body.index("_studio_runtime_gate.consume_runtime_gate_handoff()")
+ guard = body.index("with _studio_runtime_launch_guard(", consume)
+ idle_scan = body.index("_studio_runtime_gate.ensure_managed_environment_is_idle", guard)
+ release_self = body.index("_release_self_exe_lock_windows()", idle_scan)
+ setup = body.index("_run_setup_script(", release_self)
+ verify = body.index("_fail_if_install_damaged()", setup)
+ assert consume < guard < idle_scan < release_self < setup < verify
+
+
+def test_terminal_setup_holds_the_gate_through_environment_mutation():
+ source = STUDIO_COMMAND.read_text(encoding = "utf-8")
+ body = source[source.index("def setup(") : source.index("def _fail_if_install_damaged")]
+ consume = body.index("_studio_runtime_gate.consume_runtime_gate_handoff()")
+ guard = body.index("with _studio_runtime_launch_guard(", consume)
+ idle_scan = body.index("_studio_runtime_gate.ensure_managed_environment_is_idle", guard)
+ setup = body.index("_run_setup_script(", idle_scan)
+ assert consume < guard < idle_scan < setup
+
+
+def test_interrupted_windows_setup_kills_tree_before_return(monkeypatch):
+ from unsloth_cli.commands import studio as studio_command
+
+ events = []
+
+ class InterruptedProcess:
+ pid = 4242
+ returncode = None
+
+ def wait(self):
+ events.append("wait")
+ if self.returncode is None and events.count("wait") == 1:
+ raise KeyboardInterrupt
+ self.returncode = -1
+ return self.returncode
+
+ def poll(self):
+ return self.returncode
+
+ def fake_taskkill(argv, **kwargs):
+ events.append(("taskkill", argv, kwargs))
+ return SimpleNamespace(returncode = 0)
+
+ monkeypatch.setattr(studio_command.subprocess, "run", fake_taskkill)
+ monkeypatch.setattr(studio_command, "_windows_hidden_subprocess_kwargs", lambda: {})
+
+ with pytest.raises(KeyboardInterrupt):
+ studio_command._wait_for_windows_setup_process(InterruptedProcess())
+
+ assert events[0] == "wait"
+ assert events[1][0] == "taskkill"
+ assert events[1][1] == ["taskkill", "/PID", "4242", "/T", "/F"]
+ assert events[1][2]["check"] is False
+ assert events[2] == "wait"
+
+
[email protected](os.name != "nt", reason = "Windows ordinal comparison is required")
+def test_windows_path_containment_requires_component_boundaries():
+ root = r"C:\Users\pc\.unsloth\studio\unsloth_studio"
+ assert gate._windows_path_is_within(root + r"\Scripts\python.exe", root)
+ assert not gate._windows_path_is_within(root + "_backup" + r"\python.exe", root)
+
+
[email protected](os.name != "nt", reason = "Windows ordinal comparison is required")
+def test_windows_path_containment_uses_ordinal_case_semantics():
+ root = r"D:\Straße\studio"
+ assert gate._windows_path_is_within(r"D:\straße\studio\python.exe", root)
+ assert not gate._windows_path_is_within(r"D:\Strasse\studio\python.exe", root)
+
+
[email protected](os.name != "nt", reason = "Windows process inspection is required")
+def test_idle_scan_excludes_verified_launcher_and_blocks_another_managed_image(
+ tmp_path, monkeypatch
+):
+ studio_home = tmp_path / "studio"
+ managed_python = studio_home / "unsloth_studio" / "Scripts" / "python.exe"
+ managed_launcher = studio_home / "unsloth_studio" / "Scripts" / "unsloth.exe"
+ managed_python.parent.mkdir(parents = True)
+ managed_python.write_bytes(b"MZ")
+ managed_launcher.write_bytes(b"MZ")
+ current_pid = os.getpid()
+ parent_pid = current_pid + 1_000_000
+ consumer_pid = parent_pid + 1
+ payload = [
+ {
+ "ProcessId": current_pid,
+ "ParentProcessId": parent_pid,
+ "Name": "python.exe",
+ "ExecutablePath": str(managed_python),
+ },
+ {
+ "ProcessId": parent_pid,
+ "ParentProcessId": 0,
+ "Name": "unsloth.exe",
+ "ExecutablePath": str(managed_launcher),
+ },
+ ]
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *args, **kwargs: SimpleNamespace(
+ returncode = 0,
+ stdout = json.dumps(payload),
+ stderr = "",
+ ),
+ )
+ gate.ensure_managed_environment_is_idle(studio_home)
+ payload.append(
+ {
+ "ProcessId": consumer_pid,
+ "ParentProcessId": 0,
+ "Name": "python.exe",
+ "ExecutablePath": str(managed_python),
+ }
+ )
+ with pytest.raises(RuntimeError, match = rf"PID {consumer_pid}"):
+ gate.ensure_managed_environment_is_idle(studio_home)
+
+
[email protected](os.name != "nt", reason = "Windows process inspection is required")
+def test_idle_scan_excludes_the_venv_python_redirector(tmp_path, monkeypatch):
+ # install.ps1 runs `Scripts\unsloth.exe studio setup` and Tauri runs the venv
+ # interpreter, so both arrive through the redirector and would self-block.
+ studio_home = tmp_path / "studio"
+ scripts = studio_home / "unsloth_studio" / "Scripts"
+ managed_python = scripts / "python.exe"
+ managed_launcher = scripts / "unsloth.exe"
+ scripts.mkdir(parents = True)
+ managed_python.write_bytes(b"MZ")
+ managed_launcher.write_bytes(b"MZ")
+ current_pid = os.getpid()
+ redirector_pid = current_pid + 1_075_000
+ launcher_pid = redirector_pid + 1
+ payload = [
+ {
+ "ProcessId": current_pid,
+ "ParentProcessId": redirector_pid,
+ "Name": "python.exe",
+ "ExecutablePath": str(tmp_path / "base" / "python.exe"),
+ },
+ {
+ "ProcessId": redirector_pid,
+ "ParentProcessId": launcher_pid,
+ "Name": "python.exe",
+ "ExecutablePath": str(managed_python),
+ },
+ {
+ "ProcessId": launcher_pid,
+ "ParentProcessId": 0,
+ "Name": "unsloth.exe",
+ "ExecutablePath": str(managed_launcher),
+ },
+ ]
+ monkeypatch.setattr(sys, "executable", str(managed_python))
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *args, **kwargs: SimpleNamespace(
+ returncode = 0,
+ stdout = json.dumps(payload),
+ stderr = "",
+ ),
+ )
+ gate.ensure_managed_environment_is_idle(studio_home)
+
+ # Tauri runs the redirector directly, with no shim above it.
+ payload[2]["ExecutablePath"] = str(tmp_path / "Unsloth" / "unsloth.exe")
+ gate.ensure_managed_environment_is_idle(studio_home)
+
+ # Only the direct parent is the redirector; a managed image above is a consumer.
+ payload[2]["ExecutablePath"] = str(managed_python)
+ with pytest.raises(RuntimeError, match = rf"PID {launcher_pid}"):
+ gate.ensure_managed_environment_is_idle(studio_home)
+
+ # We were not launched through the venv, so nothing above us is a redirector.
+ payload[2]["ExecutablePath"] = str(managed_launcher)
+ monkeypatch.setattr(sys, "executable", str(tmp_path / "base" / "python.exe"))
+ with pytest.raises(RuntimeError, match = rf"PID {redirector_pid}"):
+ gate.ensure_managed_environment_is_idle(studio_home)
+
+
[email protected](os.name != "nt", reason = "Windows process inspection is required")
+def test_idle_scan_does_not_exclude_managed_parent_of_updater(tmp_path, monkeypatch):
+ studio_home = tmp_path / "studio"
+ scripts = studio_home / "unsloth_studio" / "Scripts"
+ managed_python = scripts / "python.exe"
+ managed_launcher = scripts / "unsloth.exe"
+ scripts.mkdir(parents = True)
+ managed_python.write_bytes(b"MZ")
+ managed_launcher.write_bytes(b"MZ")
+ current_pid = os.getpid()
+ launcher_pid = current_pid + 1_050_000
+ managed_parent_pid = launcher_pid + 1
+ payload = [
+ {
+ "ProcessId": current_pid,
+ "ParentProcessId": launcher_pid,
+ "Name": "python.exe",
+ "ExecutablePath": str(managed_python),
+ },
+ {
+ "ProcessId": launcher_pid,
+ "ParentProcessId": managed_parent_pid,
+ "Name": "unsloth.exe",
+ "ExecutablePath": str(managed_launcher),
+ },
+ {
+ "ProcessId": managed_parent_pid,
+ "ParentProcessId": 0,
+ "Name": "python.exe",
+ "ExecutablePath": str(managed_python),
+ },
+ ]
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *args, **kwargs: SimpleNamespace(
+ returncode = 0,
+ stdout = json.dumps(payload),
+ stderr = "",
+ ),
+ )
+
+ with pytest.raises(RuntimeError, match = rf"PID {managed_parent_pid}"):
+ gate.ensure_managed_environment_is_idle(studio_home)
+
+
[email protected](os.name != "nt", reason = "Windows process inspection is required")
+def test_idle_scan_blocks_exact_outer_shim(tmp_path, monkeypatch):
+ studio_home = tmp_path / "studio"
+ outer_shim = studio_home / "bin" / "unsloth.exe"
+ outer_shim.parent.mkdir(parents = True)
+ outer_shim.write_bytes(b"MZ")
+ consumer_pid = os.getpid() + 1_100_000
+ payload = [
+ {
+ "ProcessId": os.getpid(),
+ "ParentProcessId": 0,
+ "Name": "python.exe",
+ "ExecutablePath": str(Path(os.environ["SystemRoot"]) / "System32" / "cmd.exe"),
+ },
+ {
+ "ProcessId": consumer_pid,
+ "ParentProcessId": 0,
+ "Name": "unsloth.exe",
+ "ExecutablePath": str(outer_shim),
+ },
+ ]
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *args, **kwargs: SimpleNamespace(
+ returncode = 0,
+ stdout = json.dumps(payload),
+ stderr = "",
+ ),
+ )
+ with pytest.raises(RuntimeError, match = rf"PID {consumer_pid}"):
+ gate.ensure_managed_environment_is_idle(studio_home)
+
+
[email protected](os.name != "nt", reason = "Windows process inspection is required")
+def test_idle_scan_ignores_command_line_only_path_mentions(tmp_path, monkeypatch):
+ studio_home = tmp_path / "studio"
+ mentioned = studio_home / "unsloth_studio" / "Lib" / "worker.py"
+ payload = [
+ {
+ "ProcessId": os.getpid(),
+ "ParentProcessId": 0,
+ "Name": "python.exe",
+ "ExecutablePath": str(Path(os.environ["SystemRoot"]) / "System32" / "cmd.exe"),
+ "CommandLine": f'python.exe "{mentioned}"',
+ }
+ ]
+ captured = {}
+
+ def fake_run(command, **kwargs):
+ captured["command"] = command
+ return SimpleNamespace(returncode = 0, stdout = json.dumps(payload), stderr = "")
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ gate.ensure_managed_environment_is_idle(studio_home)
+ assert "CommandLine" not in " ".join(captured["command"])
+
+
[email protected](os.name != "nt", reason = "Windows process inspection is required")
+def test_idle_scan_fails_closed_when_process_inventory_fails(tmp_path, monkeypatch):
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *args, **kwargs: SimpleNamespace(
+ returncode = 1,
+ stdout = "",
+ stderr = "access denied",
+ ),
+ )
+ with pytest.raises(RuntimeError, match = "access denied"):
+ gate.ensure_managed_environment_is_idle(tmp_path)
+
+
[email protected](os.name != "nt", reason = "Windows named mutexes are required")
+def test_runtime_gate_blocks_another_thread_and_recovers():
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ kernel32.CreateMutexW.argtypes = [ctypes.c_void_p, wintypes.BOOL, wintypes.LPCWSTR]
+ kernel32.CreateMutexW.restype = wintypes.HANDLE
+ kernel32.ReleaseMutex.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ managed_root = gate._windows_profile_path() / ".unsloth" / "studio"
+ holder = kernel32.CreateMutexW(
+ None,
+ True,
+ gate.runtime_mutex_name_for_sid(gate._current_windows_user_sid()),
+ )
+ assert holder
+ observed: list[str] = []
+
+ def contend() -> None:
+ try:
+ with gate.studio_runtime_launch_guard(managed_root):
+ observed.append("acquired")
+ except gate.StudioRuntimeGateBusy:
+ observed.append("blocked")
+
+ contender = threading.Thread(target = contend)
+ contender.start()
+ contender.join(timeout = 10)
+ assert observed == ["blocked"]
+ assert kernel32.ReleaseMutex(holder)
+ assert kernel32.CloseHandle(holder)
+ with gate.studio_runtime_launch_guard(managed_root) as acquired:
+ assert acquired is True
+
+
[email protected](os.name != "nt", reason = "Windows named mutexes are required")
+def test_custom_root_runtime_gate_blocks_another_thread(tmp_path):
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ kernel32.CreateMutexW.argtypes = [ctypes.c_void_p, wintypes.BOOL, wintypes.LPCWSTR]
+ kernel32.CreateMutexW.restype = wintypes.HANDLE
+ kernel32.ReleaseMutex.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ holder = kernel32.CreateMutexW(None, True, gate.runtime_mutex_name_for_studio_home(tmp_path))
+ assert holder
+ observed: list[str] = []
+
+ def contend() -> None:
+ try:
+ with gate.studio_runtime_launch_guard(tmp_path):
+ observed.append("acquired")
+ except gate.StudioRuntimeGateBusy:
+ observed.append("blocked")
+
+ contender = threading.Thread(target = contend)
+ contender.start()
+ contender.join(timeout = 10)
+ assert observed == ["blocked"]
+ assert kernel32.ReleaseMutex(holder)
+ assert kernel32.CloseHandle(holder)
diff --git a/tests/python/test_windows_installer_concurrency_guard.py b/tests/python/test_windows_installer_concurrency_guard.py
new file mode 100644
index 00000000000..42212ab969a
--- /dev/null
+++ b/tests/python/test_windows_installer_concurrency_guard.py
@@ -0,0 +1,898 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+from __future__ import annotations
+
+import hashlib
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+INSTALL_PS1 = REPO_ROOT / "install.ps1"
+COMMANDS_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "commands.rs"
+PROCESS_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "process.rs"
+PREFLIGHT_MANAGED_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "preflight" / "managed.rs"
+DESKTOP_AUTH_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "desktop_auth.rs"
+UPDATE_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "update.rs"
+STUDIO_COMMAND = REPO_ROOT / "unsloth_cli" / "commands" / "studio.py"
+POWERSHELLS = [shell for shell in ("pwsh", "powershell") if shutil.which(shell)]
+
+
+def _extract(pattern: str, source: str) -> str:
+ match = re.search(pattern, source, flags = re.DOTALL)
+ assert match is not None, f"install.ps1 block not found: {pattern}"
+ return match.group(0)
+
+
+def _run_powershell(shell: str, script: str, env: dict[str, str]) -> str:
+ result = subprocess.run(
+ [shell, "-NoProfile", "-NonInteractive", "-Command", script],
+ check = True,
+ capture_output = True,
+ text = True,
+ env = env,
+ timeout = 30,
+ )
+ return result.stdout.strip()
+
+
+def _mutex_helpers(source: str) -> str:
+ return "\n".join(
+ _extract(rf" function {name} \{{.*?\n \}}\n", source)
+ for name in (
+ "Enter-StudioNamedMutex",
+ "Get-StudioFinalPath",
+ "Get-StudioPathHash",
+ "Get-StudioInstallMutexName",
+ "Test-StudioPathEqual",
+ "Get-StudioRuntimeMutexNameForSid",
+ "Get-StudioRuntimePathHash",
+ "Get-StudioRuntimeMutexNameForPath",
+ "Get-StudioCurrentUserSid",
+ "Get-StudioRuntimeMutexName",
+ "Get-StudioRuntimeMutexNames",
+ "Enter-StudioInstallMutex",
+ "Exit-StudioInstallMutex",
+ )
+ )
+
+
+def _process_helpers(source: str) -> str:
+ return "\n".join(
+ _extract(rf" function {name} \{{.*?\n \}}\n", source)
+ for name in (
+ "Get-StudioFinalPath",
+ "Test-StudioProtectedPathMatch",
+ "Get-RunningStudioVenvProcesses",
+ )
+ )
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_running_venv_process_is_reported(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ detector = _process_helpers(source)
+ scripts = tmp_path / "unsloth_studio" / "Scripts"
+ scripts.mkdir(parents = True)
+ probe = scripts / "guard-probe.exe"
+ shutil.copy2(Path(os.environ["SystemRoot"]) / "System32" / "PING.EXE", probe)
+
+ creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
+ child = subprocess.Popen(
+ [str(probe), "-n", "6", "127.0.0.1"],
+ creationflags = creationflags,
+ )
+ try:
+ script = f"""
+$ErrorActionPreference = "Stop"
+{detector}
+@(Get-RunningStudioVenvProcesses -VenvPath $env:TEST_VENV) |
+ ForEach-Object {{ Write-Output $_.Id }}
+"""
+ env = os.environ.copy()
+ env["TEST_VENV"] = str(scripts.parent)
+ deadline = time.monotonic() + 4
+ observed = []
+ while time.monotonic() < deadline:
+ observed = _run_powershell(shell, script, env).splitlines()
+ if str(child.pid) in observed:
+ break
+ time.sleep(0.1)
+ assert str(child.pid) in observed
+ finally:
+ child.terminate()
+ child.wait(timeout = 10)
+
+
+ os.name != "nt" or sys.maxsize <= 2**32,
+ reason = "A 64-bit Windows test host is required",
+)
+def test_x86_powershell_reports_64_bit_managed_process(tmp_path: Path):
+ x86_shell = (
+ Path(os.environ["SystemRoot"])
+ / "SysWOW64"
+ / "WindowsPowerShell"
+ / "v1.0"
+ / "powershell.exe"
+ )
+ if not x86_shell.is_file():
+ pytest.skip("32-bit Windows PowerShell is unavailable")
+
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ detector = _process_helpers(source)
+ scripts = tmp_path / "unsloth_studio" / "Scripts"
+ scripts.mkdir(parents = True)
+ probe = scripts / "guard-probe.exe"
+ shutil.copy2(Path(os.environ["SystemRoot"]) / "System32" / "PING.EXE", probe)
+ # Long-lived: a 32-bit shell pays a WOW64 start plus an Add-Type compile, so a
+ # short probe can exit before the scan runs.
+ child = subprocess.Popen(
+ [str(probe), "-n", "120", "127.0.0.1"],
+ creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ try:
+ script = f"""
+$ErrorActionPreference = "Stop"
+{detector}
+@(Get-RunningStudioVenvProcesses -VenvPath $env:TEST_VENV) |
+ ForEach-Object {{ Write-Output $_.Id }}
+"""
+ env = os.environ.copy()
+ env["TEST_VENV"] = str(scripts.parent)
+ deadline = time.monotonic() + 30
+ observed = []
+ while time.monotonic() < deadline:
+ observed = _run_powershell(str(x86_shell), script, env).splitlines()
+ if str(child.pid) in observed:
+ break
+ time.sleep(0.5)
+ assert str(child.pid) in observed
+ finally:
+ child.terminate()
+ child.wait(timeout = 10)
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_installer_decision_stops_active_process_and_allows_idle(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ decision_start = source.index(" $protectedProcessPaths = @(")
+ decision_end = source.index(
+ " if (-not $TauriMode -and $studioUsesLegacyLayout)", decision_start
+ )
+ decision = source[decision_start:decision_end]
+
+ studio_home = tmp_path / "studio"
+ venv = studio_home / "unsloth_studio"
+ scripts = venv / "Scripts"
+ scripts.mkdir(parents = True)
+ marker = venv / "must-remain.txt"
+ marker.write_text("untouched", encoding = "utf-8")
+ worker = scripts / "worker.exe"
+ shutil.copy2(Path(os.environ["SystemRoot"]) / "System32" / "PING.EXE", worker)
+ child = subprocess.Popen(
+ [str(worker), "-n", "30", "127.0.0.1"],
+ creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+
+ script = f"""
+$ErrorActionPreference = "Stop"
+{_process_helpers(source)}
+function Exit-InstallFailure {{
+ param([string]$Message)
+ return "blocked"
+}}
+function Invoke-InstallerDecision {{
+ $VenvDir = $env:TEST_VENV
+ $StudioHome = $env:TEST_STUDIO_HOME
+ $studioUsesLegacyLayout = $false
+{decision}
+ return "continued"
+}}
+$result = Invoke-InstallerDecision
+Write-Output ("RESULT:" + $result)
+Write-Output ("MARKER:" + (Get-Content -LiteralPath $env:TEST_MARKER -Raw))
+"""
+ env = os.environ.copy()
+ env["TEST_VENV"] = str(venv)
+ env["TEST_STUDIO_HOME"] = str(studio_home)
+ env["TEST_MARKER"] = str(marker)
+ try:
+ active = [
+ line
+ for line in _run_powershell(shell, script, env).splitlines()
+ if line.startswith(("RESULT:", "MARKER:"))
+ ]
+ assert active == ["RESULT:blocked", "MARKER:untouched"]
+ finally:
+ child.terminate()
+ child.wait(timeout = 10)
+
+ idle = [
+ line
+ for line in _run_powershell(shell, script, env).splitlines()
+ if line.startswith(("RESULT:", "MARKER:"))
+ ]
+ assert idle == ["RESULT:continued", "MARKER:untouched"]
+
+
+def test_installer_ignores_command_line_and_cwd_only_path_mentions():
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ for removed_helper in (
+ "ConvertFrom-StudioWindowsCommandLine",
+ "Test-StudioRawCommandLinePathReference",
+ "Get-StudioProcessWorkingDirectories",
+ "Test-StudioCommandLinePathReference",
+ ):
+ assert removed_helper not in source
+
+ detector = source[
+ source.index(" function Get-RunningStudioVenvProcesses {") : source.index(
+ " function Test-VenvPythonReady {"
+ )
+ ]
+ assert "Get-CimInstance" not in detector
+ assert ".CommandLine" not in detector
+ assert "$process.Path" not in detector
+ assert "[UnslothStudioFinalPathV2]::GetProcessImagePath($process.Id)" in detector
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_versioned_native_helper_loads_after_older_installer_type(shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ final_path_helper = _extract(r" function Get-StudioFinalPath \{.*?\n \}\n", source)
+ script = f"""
+$ErrorActionPreference = "Stop"
+Add-Type -TypeDefinition @'
+public static class UnslothStudioFinalPath
+{{
+ public static string Resolve(string path) {{ return path; }}
+}}
+'@
+{final_path_helper}
+Get-StudioFinalPath -Path $env:SystemRoot | Out-Null
+Write-Output ([bool]("UnslothStudioFinalPathV2" -as [type]))
+Write-Output ([bool]([UnslothStudioFinalPathV2]::GetProcessImagePath($PID)))
+"""
+ assert _run_powershell(shell, script, os.environ.copy()).splitlines() == ["True", "True"]
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_desktop_process_filter_keeps_only_the_current_user_sid(shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ helper = _extract(
+ r" function Get-StudioDesktopProcessesForCurrentUser \{.*?\n \}\n", source
+ )
+ script = f"""
+$ErrorActionPreference = "Stop"
+{helper}
+function Get-StudioCurrentUserSid {{ return "S-1-5-21-current" }}
+function Get-CimInstance {{
+ [CmdletBinding()]
+ param([string]$ClassName, [string]$Filter)
+ @(
+ [pscustomobject]@{{ Name = "unsloth-studio.exe"; ProcessId = 101 }}
+ [pscustomobject]@{{ Name = "unsloth-studio.exe"; ProcessId = 202 }}
+ [pscustomobject]@{{ Name = "unsloth-studio.exe"; ProcessId = 303 }}
+ )
+}}
+function Invoke-CimMethod {{
+ [CmdletBinding()]
+ param($InputObject, [string]$MethodName)
+ if ($InputObject.ProcessId -eq 101) {{
+ return [pscustomobject]@{{ ReturnValue = 0; Sid = "S-1-5-21-current" }}
+ }}
+ if ($InputObject.ProcessId -eq 202) {{
+ return [pscustomobject]@{{ ReturnValue = 0; Sid = "S-1-5-21-other" }}
+ }}
+ throw "owner unavailable"
+}}
+@(Get-StudioDesktopProcessesForCurrentUser) | ForEach-Object {{ Write-Output $_.Id }}
+"""
+ assert _run_powershell(shell, script, os.environ.copy()).splitlines() == ["101"]
+ assert "GetOwnerSid" in helper
+ assert "SessionId" not in helper
+
+ assert "QueryFullProcessImageNameW" in source
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_junction_alias_process_is_reported_for_physical_venv(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ detector = _process_helpers(source)
+ physical = tmp_path / "physical" / "unsloth_studio"
+ scripts = physical / "Scripts"
+ scripts.mkdir(parents = True)
+ alias = tmp_path / "alias"
+ subprocess.run(
+ ["cmd.exe", "/d", "/c", "mklink", "/J", str(alias), str(physical)],
+ check = True,
+ capture_output = True,
+ text = True,
+ )
+ probe = alias / "Scripts" / "guard-probe.exe"
+ shutil.copy2(Path(os.environ["SystemRoot"]) / "System32" / "PING.EXE", probe)
+ child = subprocess.Popen(
+ [str(probe), "-n", "6", "127.0.0.1"],
+ creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ try:
+ script = f"""
+$ErrorActionPreference = "Stop"
+{detector}
+@(Get-RunningStudioVenvProcesses -VenvPath $env:TEST_VENV) |
+ ForEach-Object {{ Write-Output $_.Id }}
+"""
+ env = os.environ.copy()
+ env["TEST_VENV"] = str(physical)
+ assert str(child.pid) in _run_powershell(shell, script, env).splitlines()
+ finally:
+ child.terminate()
+ child.wait(timeout = 10)
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_exact_studio_bin_shim_process_is_reported(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ detector = _process_helpers(source)
+ shim = tmp_path / "studio" / "bin" / "unsloth.exe"
+ shim.parent.mkdir(parents = True)
+ shutil.copy2(Path(os.environ["SystemRoot"]) / "System32" / "PING.EXE", shim)
+ child = subprocess.Popen(
+ [str(shim), "-n", "6", "127.0.0.1"],
+ creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ try:
+ script = f"""
+$ErrorActionPreference = "Stop"
+{detector}
+@(Get-RunningStudioVenvProcesses -VenvPath $env:TEST_SHIM -Exact) |
+ ForEach-Object {{ Write-Output $_.Id }}
+"""
+ env = os.environ.copy()
+ env["TEST_SHIM"] = str(shim)
+ assert str(child.pid) in _run_powershell(shell, script, env).splitlines()
+ finally:
+ child.terminate()
+ child.wait(timeout = 10)
+
+
+def test_installer_scan_protects_the_exact_studio_bin_shim():
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ assert 'Join-Path $StudioHome "bin\\unsloth.exe"' in source
+ assert "[pscustomobject]@{ Path = (Join-Path $StudioHome" in source
+ assert "Exact = $true" in source
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_mutex_names_are_global_and_install_lock_is_path_scoped(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ studio_home = tmp_path / "studio"
+ studio_home.mkdir()
+ script = f"""
+$ErrorActionPreference = "Stop"
+{_mutex_helpers(source)}
+Write-Output (Get-StudioInstallMutexName -Path $env:TEST_STUDIO_HOME)
+Write-Output (Get-StudioRuntimeMutexNameForSid -Sid "S-1-5-21-111-222-333-1001")
+Write-Output (Get-StudioRuntimeMutexNameForSid -Sid "S-1-5-21-111-222-333-1002")
+$currentSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
+Write-Output ((Get-StudioRuntimeMutexName) -eq `
+ (Get-StudioRuntimeMutexNameForSid -Sid $currentSid))
+"""
+ env = os.environ.copy()
+ env["TEST_STUDIO_HOME"] = str(studio_home)
+ canonical = str(studio_home.resolve()).rstrip("\\/").upper()
+ digest = hashlib.sha256(canonical.encode()).hexdigest()
+ assert _run_powershell(shell, script, env).splitlines() == [
+ f"Global\\UnslothStudioInstall-{digest}",
+ "Global\\UnslothStudioManagedEnvironment-S-1-5-21-111-222-333-1001",
+ "Global\\UnslothStudioManagedEnvironment-S-1-5-21-111-222-333-1002",
+ "True",
+ ]
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_tauri_managed_root_path_classification(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ profile = tmp_path / "profile"
+ studio_home = profile / ".unsloth" / "studio"
+ studio_home.mkdir(parents = True)
+ alias = studio_home / ".." / "studio"
+ junction = tmp_path / "profile-alias"
+ junction_result = subprocess.run(
+ [os.environ["COMSPEC"], "/d", "/c", "mklink", "/J", str(junction), str(profile)],
+ capture_output = True,
+ text = True,
+ )
+ if junction_result.returncode != 0:
+ pytest.skip(f"Could not create a directory junction: {junction_result.stderr}")
+ junction_studio = junction / ".unsloth" / "studio"
+ script = f"""
+$ErrorActionPreference = "Stop"
+{_mutex_helpers(source)}
+Write-Output (Test-StudioPathEqual -Left $env:TEST_STUDIO_HOME -Right $env:TEST_ALIAS)
+Write-Output (Test-StudioPathEqual -Left $env:TEST_STUDIO_HOME -Right $env:TEST_CASE_VARIANT)
+Write-Output (Test-StudioPathEqual -Left $env:TEST_STUDIO_HOME -Right $env:TEST_JUNCTION)
+Write-Output (Test-StudioPathEqual -Left $env:TEST_STUDIO_HOME -Right $env:TEST_SIBLING)
+"""
+ env = os.environ.copy()
+ env["TEST_STUDIO_HOME"] = str(studio_home)
+ env["TEST_ALIAS"] = str(alias)
+ env["TEST_CASE_VARIANT"] = str(studio_home).upper()
+ env["TEST_JUNCTION"] = str(junction_studio)
+ env["TEST_SIBLING"] = str(profile / ".unsloth" / "studio-backup")
+ assert _run_powershell(shell, script, env).splitlines() == ["True", "True", "True", "False"]
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_tauri_override_accepts_junction_alias_of_managed_root(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ profile = tmp_path / "profile"
+ studio_home = profile / ".unsloth" / "studio"
+ studio_home.mkdir(parents = True)
+ junction = tmp_path / "profile-alias"
+ junction_result = subprocess.run(
+ [os.environ["COMSPEC"], "/d", "/c", "mklink", "/J", str(junction), str(profile)],
+ capture_output = True,
+ text = True,
+ )
+ if junction_result.returncode != 0:
+ pytest.skip(f"Could not create a directory junction: {junction_result.stderr}")
+
+ validation_start = source.index(" # Custom Unsloth roots are not supported with --tauri")
+ validation_end = source.index(" # LOCALAPPDATA may be unset", validation_start)
+ validation = source[validation_start:validation_end]
+ final_path_helper = _extract(r" function Get-StudioFinalPath \{.*?\n \}\n", source)
+ script = f"""
+$ErrorActionPreference = "Stop"
+{final_path_helper}
+$TauriMode = $true
+$envOverride = $env:TEST_TAURI_OVERRIDE
+$envOverrideVar = "UNSLOTH_STUDIO_HOME"
+$tauriProfile = $env:TEST_TAURI_PROFILE
+{validation}
+Write-Output "accepted"
+"""
+ env = os.environ.copy()
+ env["TEST_TAURI_OVERRIDE"] = str(junction / ".unsloth" / "studio")
+ env["TEST_TAURI_PROFILE"] = str(profile)
+ assert _run_powershell(shell, script, env) == "accepted"
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_missing_root_beneath_junction_uses_the_physical_mutex_identity(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ profile = tmp_path / "profile"
+ profile.mkdir()
+ junction = tmp_path / "profile-alias"
+ junction_result = subprocess.run(
+ [os.environ["COMSPEC"], "/d", "/c", "mklink", "/J", str(junction), str(profile)],
+ capture_output = True,
+ text = True,
+ )
+ if junction_result.returncode != 0:
+ pytest.skip(f"Could not create a directory junction: {junction_result.stderr}")
+
+ script = f"""
+$ErrorActionPreference = "Stop"
+{_mutex_helpers(source)}
+$aliasRoot = $env:TEST_ALIAS_ROOT
+$physicalRoot = $env:TEST_PHYSICAL_ROOT
+$aliasMatch = Test-StudioPathEqual -Left $aliasRoot -Right $physicalRoot
+$physicalMatch = Test-StudioPathEqual -Left $physicalRoot -Right $physicalRoot
+$aliasRuntime = @(Get-StudioRuntimeMutexNames -TauriRootMatch $aliasMatch -Path $aliasRoot)
+$physicalRuntime = @(Get-StudioRuntimeMutexNames -TauriRootMatch $physicalMatch -Path $physicalRoot)
+Write-Output $aliasMatch
+Write-Output ((Get-StudioInstallMutexName -Path $aliasRoot) -eq (Get-StudioInstallMutexName -Path $physicalRoot))
+Write-Output $aliasRuntime.Count
+Write-Output $physicalRuntime.Count
+Write-Output ($aliasRuntime[0] -eq $physicalRuntime[0])
+Write-Output ($aliasRuntime[0].StartsWith("Global\\UnslothStudioManagedEnvironment-"))
+"""
+ env = os.environ.copy()
+ env["TEST_ALIAS_ROOT"] = str(junction / ".unsloth" / "studio")
+ env["TEST_PHYSICAL_ROOT"] = str(profile / ".unsloth" / "studio")
+ assert _run_powershell(shell, script, env).splitlines() == [
+ "True",
+ "True",
+ "1",
+ "1",
+ "True",
+ "True",
+ ]
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_path_identity_failure_is_reported_as_unknown(shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ script = f"""
+$ErrorActionPreference = "Stop"
+{_mutex_helpers(source)}
+function Get-StudioFinalPath {{ throw "identity unavailable" }}
+$match = Test-StudioPathEqual -Left "C:\\one" -Right "C:\\two"
+Write-Output ($null -eq $match)
+"""
+ assert _run_powershell(shell, script, os.environ.copy()).splitlines()[-1] == "True"
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_install_mutex_blocks_before_target_mutation_and_recovers_abandonment(
+ tmp_path: Path, shell: str
+):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ mutex_helpers = _mutex_helpers(source)
+ studio_home = tmp_path / "studio"
+ target = studio_home / "unsloth_studio"
+ target.mkdir(parents = True)
+ marker = target / "healthy.marker"
+ marker.write_text("old", encoding = "utf-8")
+ env = os.environ.copy()
+ env["TEST_STUDIO_HOME"] = str(studio_home)
+ env["TEST_TARGET"] = str(target)
+
+ holder_script = f"""
+$ErrorActionPreference = "Stop"
+{mutex_helpers}
+$mutex = Enter-StudioInstallMutex -Path $env:TEST_STUDIO_HOME
+if ($null -eq $mutex) {{ throw "holder did not acquire mutex" }}
+Write-Output "READY"
+[Console]::ReadLine() | Out-Null
+Exit-StudioInstallMutex -Mutex $mutex
+"""
+ holder = subprocess.Popen(
+ [shell, "-NoProfile", "-NonInteractive", "-Command", holder_script],
+ stdin = subprocess.PIPE,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ text = True,
+ env = env,
+ )
+ try:
+ assert holder.stdout is not None
+ assert holder.stdout.readline().strip() == "READY"
+ contender_script = f"""
+$ErrorActionPreference = "Stop"
+{mutex_helpers}
+$mutex = Enter-StudioInstallMutex -Path $env:TEST_STUDIO_HOME
+if ($null -eq $mutex) {{ Write-Output "BLOCKED"; exit 0 }}
+Move-Item -LiteralPath $env:TEST_TARGET -Destination ($env:TEST_TARGET + ".rollback") -ErrorAction Stop
+Write-Output "MUTATED"
+Exit-StudioInstallMutex -Mutex $mutex
+"""
+ assert _run_powershell(shell, contender_script, env) == "BLOCKED"
+ assert marker.read_text(encoding = "utf-8") == "old"
+ assert not Path(f"{target}.rollback").exists()
+
+ holder.kill()
+ holder.wait(timeout = 10)
+ assert _run_powershell(shell, contender_script, env) == "MUTATED"
+ assert not target.exists()
+ assert (Path(f"{target}.rollback") / marker.name).read_text(encoding = "utf-8") == "old"
+ finally:
+ if holder.poll() is None:
+ holder.kill()
+ holder.wait(timeout = 10)
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_unknown_root_identity_acquires_sid_and_path_mutexes(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ helpers = _mutex_helpers(source)
+ custom_root = tmp_path / "custom-studio"
+ custom_root.mkdir()
+ script = f"""
+$ErrorActionPreference = "Stop"
+{helpers}
+$names = @(
+ Get-StudioRuntimeMutexNames -TauriRootMatch $null -Path $env:TEST_STUDIO_HOME
+)
+$names | ForEach-Object {{ Write-Output $_ }}
+"""
+ env = os.environ.copy()
+ env["TEST_STUDIO_HOME"] = str(custom_root)
+ names = _run_powershell(shell, script, env).splitlines()
+ assert len(names) == 2
+ assert any(name.startswith("Global\\UnslothStudioManagedEnvironment-S-1-") for name in names)
+ assert any(name.startswith("Global\\UnslothStudioManagedEnvironmentPath-") for name in names)
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_unicode_custom_root_mutex_name_matches_python(tmp_path: Path, shell: str):
+ from unsloth_cli import _studio_runtime_gate as gate
+
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ helpers = _mutex_helpers(source)
+ custom_root = tmp_path / "Studio-ß"
+ custom_root.mkdir()
+ script = f"""
+$ErrorActionPreference = "Stop"
+{helpers}
+Write-Output (Get-StudioRuntimeMutexNameForPath -Path $env:TEST_STUDIO_HOME)
+"""
+ env = os.environ.copy()
+ env["TEST_STUDIO_HOME"] = str(custom_root)
+ powershell_name = _run_powershell(shell, script, env)
+ assert powershell_name == gate.runtime_mutex_name_for_studio_home(custom_root)
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_drive_root_identity_and_mutex_names_match_python(shell: str):
+ from unsloth_cli import _studio_runtime_gate as gate
+
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ helpers = _mutex_helpers(source)
+ drive_root = Path(f"{os.environ['SystemDrive']}\\")
+ script = f"""
+$ErrorActionPreference = "Stop"
+{helpers}
+Write-Output (Get-StudioFinalPath -Path $env:TEST_STUDIO_HOME)
+Write-Output (Get-StudioInstallMutexName -Path $env:TEST_STUDIO_HOME)
+Write-Output (Get-StudioRuntimeMutexNameForPath -Path $env:TEST_STUDIO_HOME)
+"""
+ env = os.environ.copy()
+ env["TEST_STUDIO_HOME"] = str(drive_root)
+ final_path, install_name, runtime_name = _run_powershell(shell, script, env).splitlines()
+ canonical = gate._resolved_windows_path(drive_root)
+ install_digest = hashlib.sha256(canonical.upper().encode("utf-8")).hexdigest()
+
+ assert final_path == canonical
+ assert final_path.endswith("\\")
+ assert install_name == f"Global\\UnslothStudioInstall-{install_digest}"
+ runtime_digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
+ expected_runtime = f"Global\\UnslothStudioManagedEnvironmentPath-{runtime_digest}"
+ assert runtime_name == expected_runtime
+
+
[email protected](os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
[email protected]("shell", POWERSHELLS)
+def test_runtime_gate_blocks_a_late_backend_start(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ helper = _extract(r" function Enter-StudioNamedMutex \{.*?\n \}\n", source)
+ release = _extract(r" function Exit-StudioInstallMutex \{.*?\n \}\n", source)
+ mutex_name = f"Global\\UnslothStudioRuntimeGateTest-{os.getpid()}-{tmp_path.name}"
+ env = os.environ.copy()
+ env["TEST_RUNTIME_MUTEX"] = mutex_name
+
+ holder_script = f"""
+$ErrorActionPreference = "Stop"
+{helper}
+{release}
+$mutex = Enter-StudioNamedMutex -Name $env:TEST_RUNTIME_MUTEX
+if ($null -eq $mutex) {{ throw "holder did not acquire mutex" }}
+Write-Output "READY"
+[Console]::ReadLine() | Out-Null
+Exit-StudioInstallMutex -Mutex $mutex
+"""
+ contender_script = f"""
+$ErrorActionPreference = "Stop"
+{helper}
+{release}
+$mutex = Enter-StudioNamedMutex -Name $env:TEST_RUNTIME_MUTEX
+if ($null -eq $mutex) {{ Write-Output "BLOCKED"; exit 0 }}
+Write-Output "ACQUIRED"
+Exit-StudioInstallMutex -Mutex $mutex
+"""
+ holder = subprocess.Popen(
+ [shell, "-NoProfile", "-NonInteractive", "-Command", holder_script],
+ stdin = subprocess.PIPE,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ text = True,
+ env = env,
+ )
+ try:
+ assert holder.stdout is not None
+ assert holder.stdout.readline().strip() == "READY"
+ assert _run_powershell(shell, contender_script, env) == "BLOCKED"
+ holder.kill()
+ holder.wait(timeout = 10)
+ assert _run_powershell(shell, contender_script, env) == "ACQUIRED"
+ finally:
+ if holder.poll() is None:
+ holder.kill()
+ holder.wait(timeout = 10)
+
+
+def test_runtime_path_hash_is_defined_before_custom_root_lock_uses_it():
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ path_hash = source.index(" function Get-StudioRuntimePathHash {")
+ path_mutex = source.index(" function Get-StudioRuntimeMutexNameForPath {")
+ acquire = source.index("$studioRuntimeMutexNames = @(")
+ assert path_hash < path_mutex < acquire
+
+
+def test_guard_and_mutex_precede_rollback_and_release_after_restore():
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ acquire = source.index("$studioInstallMutex = Enter-StudioInstallMutex -Path $StudioHome")
+ root_match = source.index("$studioTauriRootMatch =", acquire)
+ managed_root = source.index("$studioUsesTauriManagedRoot =", root_match)
+ runtime_lock_needed = source.index("$studioNeedsRuntimeLock =", managed_root)
+ legacy_layout = source.index("$studioUsesLegacyLayout =", runtime_lock_needed)
+ runtime_name = source.index("Get-StudioRuntimeMutexName", legacy_layout)
+ legacy_scan = source.index("if ($studioUsesLegacyLayout)", runtime_name)
+ runtime_lock = source.index(
+ "Enter-StudioNamedMutex -Name $studioRuntimeMutexName",
+ runtime_name,
+ )
+ scan_candidates = source.index("$protectedProcessPaths = @(", runtime_lock)
+ legacy_source = source.index('Join-Path $StudioHome ".venv"', scan_candidates)
+ cwd_source = source.index('Join-Path $env:USERPROFILE "unsloth_studio"', legacy_source)
+ runtime_guard = source.index("foreach ($candidate in $protectedProcessPaths)", cwd_source)
+ desktop_guard = source.index("Get-StudioDesktopProcessesForCurrentUser", runtime_guard)
+ dependency_check = source.index('Write-TauriLog "STEP" "Checking system dependencies"')
+ rollback = source.index("Start-StudioVenvRollback -ExistingDir $VenvDir", desktop_guard)
+ old_venv_move = source.index("Move-Item -LiteralPath $OldVenv", rollback)
+ 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)
+ release_runtime = source.rindex("Exit-StudioInstallMutex -Mutex $studioRuntimeMutexes[$i]")
+ release_install = source.rindex("Exit-StudioInstallMutex -Mutex $studioInstallMutex")
+ wait_for_exit = source.rindex("$studioAutoStartProcess.WaitForExit()")
+
+ assert (
+ acquire
+ < root_match
+ < managed_root
+ < runtime_lock_needed
+ < legacy_layout
+ < runtime_name
+ < runtime_lock
+ )
+ assert runtime_lock < scan_candidates < legacy_scan < legacy_source < cwd_source
+ assert cwd_source < runtime_guard < desktop_guard < dependency_check < rollback
+ assert source.count("$studioUsesLegacyLayout `") >= 2
+ assert "if ($studioNeedsRuntimeLock)" in source
+ assert (
+ "$studioUsesLegacyLayout = ($StudioRedirectMode -ne 'env') -or $studioUsesTauriManagedRoot"
+ ) in source
+ assert "-not $TauriMode -and $studioUsesLegacyLayout" in source
+ assert runtime_guard < rollback < old_venv_move < cwd_venv_move
+ assert (
+ rollback < restore < prompt < autostart < release_runtime < release_install < wait_for_exit
+ )
+ assert "if ($StudioRedirectMode -eq 'legacy')" not in source
+ assert "& $UnslothExe studio -p 8888" not in source
+ assert "--clear" not in source[source.index("uv venv $VenvDir") :][:200]
+
+
+def test_tauri_runtime_uses_the_same_gate_before_backend_spawn():
+ install_source = INSTALL_PS1.read_text(encoding = "utf-8")
+ process_source = PROCESS_RS.read_text(encoding = "utf-8")
+
+ assert '"Global\\UnslothStudioManagedEnvironment-$Sid"' in install_source
+ assert '"Global\\\\UnslothStudioManagedEnvironment-"' in process_source
+ assert "Get-StudioRuntimeMutexName" in install_source
+ assert "Get-StudioRuntimeMutexNameForSid" in install_source
+ assert "studio_runtime_mutex_name_for_sid" in process_source
+ assert "current_windows_user_sid()?" in process_source
+ assert "studio_runtime_mutex_name_for_path" not in process_source
+ start = process_source.index("pub fn start_backend(")
+ guard = process_source.index("acquire_studio_runtime_launch_guard()?", start)
+ resolve = process_source.index("resolve_backend_binary()", guard)
+ handoff = process_source.index("STUDIO_RUNTIME_GATE_HANDOFF_ENV", resolve)
+ spawn = process_source.index("cmd.spawn()", handoff)
+ store = process_source.index("proc.owned = Some(", spawn)
+ assert guard < resolve < handoff < spawn < store
+
+
+def test_every_tauri_managed_child_spawn_uses_the_runtime_gate():
+ process_source = PROCESS_RS.read_text(encoding = "utf-8")
+ commands_source = COMMANDS_RS.read_text(encoding = "utf-8")
+ preflight_source = PREFLIGHT_MANAGED_RS.read_text(encoding = "utf-8")
+ desktop_auth_source = DESKTOP_AUTH_RS.read_text(encoding = "utf-8")
+ update_source = UPDATE_RS.read_text(encoding = "utf-8")
+
+ assert "pub(crate) fn with_studio_runtime_launch_guard<T>" in process_source
+
+ install_check = commands_source.index("pub async fn check_install_status()")
+ install_guard = commands_source.index("with_studio_runtime_launch_guard", install_check)
+ install_spawn = commands_source.index("cmd.spawn()", install_guard)
+ assert install_guard < install_spawn
+
+ first_probe = preflight_source.index("async fn run_cli_probe(")
+ first_guard = preflight_source.index("with_studio_runtime_launch_guard", first_probe)
+ first_spawn = preflight_source.index("cmd.spawn()", first_guard)
+ capability_probe = preflight_source.index("async fn probe_cli_capability(", first_spawn)
+ capability_guard = preflight_source.index("with_studio_runtime_launch_guard", capability_probe)
+ capability_spawn = preflight_source.index("cmd.spawn()", capability_guard)
+ assert first_guard < first_spawn < capability_probe < capability_guard < capability_spawn
+
+ provision = desktop_auth_source.index("async fn provision_desktop_auth()")
+ provision_guard = desktop_auth_source.index("with_studio_runtime_launch_guard", provision)
+ provision_spawn = desktop_auth_source.index("cmd.spawn()", provision_guard)
+ provision_wait = desktop_auth_source.index("child.wait_with_output()", provision_spawn)
+ assert provision_guard < provision_spawn < provision_wait
+
+ update_call = update_source.index(
+ "let result = crate::process::with_studio_runtime_launch_guard"
+ )
+ update_scan = update_source.index(
+ "ensure_managed_environment_is_idle(&bin)",
+ update_call,
+ )
+ update_spawn = update_source.index("spawn_update(&bin, &state)", update_scan)
+ update_wait = update_source.index("wait_for_exit(&state)", update_spawn)
+ update_guard_release = update_source.index("\n });", update_wait)
+ assert update_call < update_scan < update_spawn < update_wait < update_guard_release
+
+
+def test_runtime_gate_handoff_covers_tauri_backend_and_installer_autostart():
+ process_source = PROCESS_RS.read_text(encoding = "utf-8")
+ install_source = INSTALL_PS1.read_text(encoding = "utf-8")
+ studio_source = STUDIO_COMMAND.read_text(encoding = "utf-8")
+
+ start = process_source.index("pub fn start_backend(")
+ handoff = process_source.index('cmd.env(STUDIO_RUNTIME_GATE_HANDOFF_ENV, "1")', start)
+ spawn = process_source.index("cmd.spawn()", handoff)
+ assert handoff < spawn
+
+ prompt = install_source.index("Start Unsloth Studio now?")
+ save = install_source.index("$_runtimeGateHandoff =", prompt)
+ set_handoff = install_source.index(
+ '$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"',
+ save,
+ )
+ autostart = install_source.index("Start-Process -FilePath $UnslothExe", set_handoff)
+ restore = install_source.index(
+ "$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = $_runtimeGateHandoff",
+ autostart,
+ )
+ assert save < set_handoff < autostart < restore
+
+ setup_python = install_source.index("$env:UNSLOTH_SETUP_PYTHON =")
+ setup_save = install_source.index("$previousSetupRuntimeGateHandoff =", setup_python)
+ setup_set = install_source.index(
+ '$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"',
+ setup_save,
+ )
+ setup_invoke = install_source.index("& $UnslothExe @studioArgs", setup_set)
+ setup_restore = install_source.index(
+ "$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = $previousSetupRuntimeGateHandoff",
+ setup_invoke,
+ )
+ tauri_remove = install_source.index("Remove-Item Env:UNSLOTH_TAURI_MODE", setup_invoke)
+ assert setup_python < setup_save < setup_set < setup_invoke < tauri_remove < setup_restore
+
+ assert (
+ studio_source.count(
+ "runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()"
+ )
+ == 4
+ )
+ assert studio_source.count("inherited = runtime_gate_handoff") >= 5
+
+
+def test_tauri_start_install_rejects_backend_conflicts_before_spawn():
+ source = COMMANDS_RS.read_text(encoding = "utf-8")
+ start = source.index("pub async fn start_install(")
+ end = source.index("\n}\n", start)
+ body = source[start:end]
+
+ owned_guard = body.index("has_owned_backend(&backend_state)?")
+ external_guard = body.index("block_external_conflict(&[]).await?")
+ spawn = body.index("install::run_install")
+ assert owned_guard < external_guard < spawn
diff --git a/unsloth_cli/_studio_runtime_gate.py b/unsloth_cli/_studio_runtime_gate.py
new file mode 100644
index 00000000000..1327b58433f
--- /dev/null
+++ b/unsloth_cli/_studio_runtime_gate.py
@@ -0,0 +1,356 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Coordinate Windows launches that consume the Tauri-managed Studio environment."""
+
+from __future__ import annotations
+
+import contextlib
+import ctypes
+import hashlib
+import ntpath
+import os
+import sys
+from ctypes import wintypes
+from pathlib import Path
+from typing import Iterator, Mapping
+
+
+_RUNTIME_MUTEX_PREFIX = "Global\\UnslothStudioManagedEnvironment-"
+_PATH_RUNTIME_MUTEX_PREFIX = "Global\\UnslothStudioManagedEnvironmentPath-"
+_RUNTIME_GATE_HANDOFF_ENV = "_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF"
+
+
+class StudioRuntimeGateBusy(RuntimeError):
+ """The managed Studio environment is being installed or repaired."""
+
+
+class _SidAndAttributes(ctypes.Structure):
+ _fields_ = [
+ ("sid", ctypes.c_void_p),
+ ("attributes", wintypes.DWORD),
+ ]
+
+
+class _TokenUser(ctypes.Structure):
+ _fields_ = [("user", _SidAndAttributes)]
+
+
+def runtime_mutex_name_for_sid(sid: str) -> str:
+ return f"{_RUNTIME_MUTEX_PREFIX}{sid}"
+
+
+def _windows_profile_path() -> Path:
+ shell32 = ctypes.WinDLL("shell32", use_last_error = True)
+ get_folder_path = shell32.SHGetFolderPathW
+ get_folder_path.argtypes = [
+ wintypes.HWND,
+ ctypes.c_int,
+ wintypes.HANDLE,
+ wintypes.DWORD,
+ wintypes.LPWSTR,
+ ]
+ get_folder_path.restype = ctypes.c_long
+
+ buffer = ctypes.create_unicode_buffer(32768)
+ result = get_folder_path(None, 0x0028, None, 0, buffer) # CSIDL_PROFILE
+ if result != 0:
+ raise OSError(
+ f"SHGetFolderPathW(CSIDL_PROFILE) failed with HRESULT 0x{result & 0xFFFFFFFF:08x}"
+ )
+ return Path(buffer.value)
+
+
+def _resolved_windows_path(path: Path) -> str:
+ resolved = str(path.resolve(strict = False))
+ if resolved.startswith("\\\\?\\UNC\\"):
+ resolved = "\\\\" + resolved[8:]
+ elif resolved.startswith("\\\\?\\"):
+ resolved = resolved[4:]
+ drive, tail = ntpath.splitdrive(resolved)
+ if drive and tail and not tail.rstrip("\\/"):
+ return drive + "\\"
+ return resolved.rstrip("\\/")
+
+
+def _canonical_windows_path(path: Path) -> str:
+ return _resolved_windows_path(path).replace("/", "\\")
+
+
+def _windows_paths_equal(left: str, right: str) -> bool:
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ compare = kernel32.CompareStringOrdinal
+ compare.argtypes = [
+ wintypes.LPCWSTR,
+ ctypes.c_int,
+ wintypes.LPCWSTR,
+ ctypes.c_int,
+ wintypes.BOOL,
+ ]
+ compare.restype = ctypes.c_int
+ result = compare(left, -1, right, -1, True)
+ if result == 0:
+ raise ctypes.WinError(ctypes.get_last_error())
+ return result == 2 # CSTR_EQUAL
+
+
+def uses_tauri_managed_root(studio_home: Path) -> bool:
+ if sys.platform != "win32":
+ return False
+ managed_root = _windows_profile_path() / ".unsloth" / "studio"
+ return _windows_paths_equal(
+ _resolved_windows_path(studio_home),
+ _resolved_windows_path(managed_root),
+ )
+
+
+def runtime_mutex_name_for_studio_home(studio_home: Path) -> str:
+ if uses_tauri_managed_root(studio_home):
+ return runtime_mutex_name_for_sid(_current_windows_user_sid())
+ canonical = _resolved_windows_path(studio_home)
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
+ return f"{_PATH_RUNTIME_MUTEX_PREFIX}{digest}"
+
+
+def _current_windows_user_sid() -> str:
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ advapi32 = ctypes.WinDLL("advapi32", use_last_error = True)
+
+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.restype = wintypes.BOOL
+ kernel32.LocalFree.argtypes = [ctypes.c_void_p]
+ kernel32.LocalFree.restype = ctypes.c_void_p
+
+ advapi32.OpenProcessToken.argtypes = [
+ wintypes.HANDLE,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.HANDLE),
+ ]
+ advapi32.OpenProcessToken.restype = wintypes.BOOL
+ advapi32.GetTokenInformation.argtypes = [
+ wintypes.HANDLE,
+ ctypes.c_int,
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD),
+ ]
+ advapi32.GetTokenInformation.restype = wintypes.BOOL
+ advapi32.ConvertSidToStringSidW.argtypes = [
+ ctypes.c_void_p,
+ ctypes.POINTER(wintypes.LPWSTR),
+ ]
+ advapi32.ConvertSidToStringSidW.restype = wintypes.BOOL
+
+ token = wintypes.HANDLE()
+ if not advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), 0x0008, ctypes.byref(token)):
+ raise ctypes.WinError(ctypes.get_last_error())
+
+ try:
+ needed = wintypes.DWORD()
+ advapi32.GetTokenInformation(token, 1, None, 0, ctypes.byref(needed)) # TokenUser
+ if not needed.value:
+ raise ctypes.WinError(ctypes.get_last_error())
+
+ token_buffer = ctypes.create_string_buffer(needed.value)
+ if not advapi32.GetTokenInformation(
+ token,
+ 1,
+ token_buffer,
+ needed,
+ ctypes.byref(needed),
+ ):
+ raise ctypes.WinError(ctypes.get_last_error())
+
+ token_user = ctypes.cast(token_buffer, ctypes.POINTER(_TokenUser)).contents
+ sid_text = wintypes.LPWSTR()
+ if not advapi32.ConvertSidToStringSidW(token_user.user.sid, ctypes.byref(sid_text)):
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ return sid_text.value
+ finally:
+ kernel32.LocalFree(ctypes.cast(sid_text, ctypes.c_void_p))
+ finally:
+ kernel32.CloseHandle(token)
+
+
+def studio_runtime_launch_guard(studio_home: Path, *, inherited: bool = False) -> Iterator[bool]:
+ """Hold the shared Windows launch gate through backend admission."""
+
+ if sys.platform != "win32" or inherited:
+ yield False
+ return
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ kernel32.CreateMutexW.argtypes = [
+ ctypes.c_void_p,
+ wintypes.BOOL,
+ wintypes.LPCWSTR,
+ ]
+ kernel32.CreateMutexW.restype = wintypes.HANDLE
+ kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
+ kernel32.WaitForSingleObject.restype = wintypes.DWORD
+ kernel32.ReleaseMutex.argtypes = [wintypes.HANDLE]
+ kernel32.ReleaseMutex.restype = wintypes.BOOL
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.restype = wintypes.BOOL
+
+ name = runtime_mutex_name_for_studio_home(studio_home)
+ handle = kernel32.CreateMutexW(None, False, name)
+ if not handle:
+ raise ctypes.WinError(ctypes.get_last_error())
+
+ wait_result = kernel32.WaitForSingleObject(handle, 0)
+ if wait_result not in (0x00000000, 0x00000080): # WAIT_OBJECT_0, WAIT_ABANDONED
+ kernel32.CloseHandle(handle)
+ if wait_result == 0x00000102: # WAIT_TIMEOUT
+ raise StudioRuntimeGateBusy(name)
+ raise ctypes.WinError(ctypes.get_last_error())
+
+ try:
+ yield True
+ finally:
+ kernel32.ReleaseMutex(handle)
+ kernel32.CloseHandle(handle)
+
+
+def _windows_path_is_within(candidate: str, root: str) -> bool:
+ candidate_key = candidate.rstrip("\\/").replace("/", "\\")
+ root_key = root.rstrip("\\/").replace("/", "\\")
+ if _windows_paths_equal(candidate_key, root_key):
+ return True
+ prefix = root_key + "\\"
+ if len(candidate_key) < len(prefix):
+ return False
+ return _windows_paths_equal(candidate_key[: len(prefix)], prefix)
+
+
+def ensure_managed_environment_is_idle(studio_home: Path) -> None:
+ """Reject a Windows update while a confirmed managed executable is running."""
+
+ if sys.platform != "win32":
+ return
+
+ import json
+ import subprocess
+
+ venv = studio_home / "unsloth_studio"
+ protected_root = _canonical_windows_path(venv)
+ # Not gated on exists(): a shim renamed out of the way mid-update still runs.
+ protected_files = {
+ _canonical_windows_path(candidate)
+ for candidate in (
+ venv / "Scripts" / "unsloth.exe",
+ studio_home / "bin" / "unsloth.exe",
+ )
+ }
+
+ script = (
+ "$ErrorActionPreference='Stop';"
+ "[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false);"
+ "$items=@(Get-CimInstance Win32_Process -ErrorAction Stop|"
+ "Select-Object ProcessId,ParentProcessId,Name,ExecutablePath);"
+ "[Console]::Out.Write(($items|ConvertTo-Json -Compress))"
+ )
+ result = subprocess.run(
+ ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ check = False,
+ )
+ if result.returncode != 0:
+ detail = result.stderr.strip() or f"exit code {result.returncode}"
+ raise RuntimeError(f"Could not inspect running processes before Studio update: {detail}")
+
+ try:
+ payload = json.loads(result.stdout or "[]")
+ except json.JSONDecodeError as error:
+ raise RuntimeError(
+ f"Could not decode the running-process list before Studio update: {error}"
+ ) from error
+ processes = payload if isinstance(payload, list) else [payload]
+ process_by_pid = {
+ int(process.get("ProcessId") or -1): process
+ for process in processes
+ if int(process.get("ProcessId") or -1) > 0
+ }
+
+ # The updater may itself have been entered through the managed console shim,
+ # so exempt verified launcher ancestors only: a managed backend that starts
+ # an update as its child must still block replacement.
+ #
+ # venv\Scripts\python.exe is a redirector (bpo-34977): it starts base Python
+ # as a child and waits, so a venv launch arrives as python.exe -> us. Our
+ # image is then the base interpreter while sys.executable still names the
+ # redirector, which identifies our direct parent as that launcher rather
+ # than a live consumer. Exempt that one hop only; above it must be a shim.
+ excluded_pids = {os.getpid()}
+ descendant_pid = os.getpid()
+ self_executable = (process_by_pid.get(os.getpid()) or {}).get("ExecutablePath")
+ interpreter = _canonical_windows_path(Path(sys.executable)) if sys.executable else ""
+ launcher_redirector = ""
+ if (
+ interpreter
+ and self_executable
+ and _windows_path_is_within(interpreter, protected_root)
+ and not _windows_paths_equal(
+ _canonical_windows_path(Path(str(self_executable))), interpreter
+ )
+ ):
+ launcher_redirector = interpreter
+ for _ in range(16):
+ descendant = process_by_pid.get(descendant_pid)
+ if descendant is None:
+ break
+ parent_pid = int(descendant.get("ParentProcessId") or -1)
+ if parent_pid <= 0 or parent_pid in excluded_pids:
+ break
+ parent = process_by_pid.get(parent_pid)
+ if parent is None:
+ break
+ parent_executable = parent.get("ExecutablePath")
+ if not parent_executable:
+ break
+ parent_image = _canonical_windows_path(Path(str(parent_executable)))
+ is_shim = any(
+ _windows_paths_equal(parent_image, protected_file) for protected_file in protected_files
+ )
+ is_our_redirector = (
+ descendant_pid == os.getpid()
+ and bool(launcher_redirector)
+ and _windows_paths_equal(parent_image, launcher_redirector)
+ )
+ if not (is_shim or is_our_redirector):
+ break
+ excluded_pids.add(parent_pid)
+ descendant_pid = parent_pid
+
+ for process_id, process in process_by_pid.items():
+ if process_id in excluded_pids:
+ continue
+ executable = process.get("ExecutablePath")
+ if not executable:
+ continue
+ image = _canonical_windows_path(Path(str(executable)))
+ if _windows_path_is_within(image, protected_root) or any(
+ _windows_paths_equal(image, protected_file) for protected_file in protected_files
+ ):
+ name = process.get("Name") or "process"
+ raise RuntimeError(
+ "The managed Studio environment is in use by "
+ f"{name} (PID {process_id}). Stop that process, then retry the update."
+ )
+
+
+def consume_runtime_gate_handoff() -> bool:
+ return os.environ.pop(_RUNTIME_GATE_HANDOFF_ENV, None) == "1"
+
+
+def runtime_gate_child_environment(base: Mapping[str, str] | None = None) -> dict[str, str]:
+ child_env = dict(os.environ if base is None else base)
+ child_env[_RUNTIME_GATE_HANDOFF_ENV] = "1"
+ return child_env
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 8fc3700d3d3..8e76c843c96 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import contextlib
import importlib.util
import hashlib
import hmac
@@ -23,7 +24,7 @@ from pathlib import Path
from typing import List, Literal, Optional, Sequence
import typer
-from unsloth_cli import _studio_deps
+from unsloth_cli import _studio_deps, _studio_runtime_gate
from unsloth_cli._inference import SpeculativeType
from unsloth_cli.commands import _password_prompt
@@ -168,6 +169,31 @@ def _windows_hidden_subprocess_kwargs() -> dict[str, object]:
return kwargs
+def _studio_runtime_launch_guard(*, inherited: bool = False):
+ guard = _studio_runtime_gate.studio_runtime_launch_guard(
+ STUDIO_HOME,
+ inherited = inherited,
+ )
+ try:
+ acquired = guard.__enter__()
+ except _studio_runtime_gate.StudioRuntimeGateBusy:
+ typer.echo(
+ "Error: Unsloth installation is modifying the managed environment. "
+ "Wait for it to finish, then try again.",
+ err = True,
+ )
+ raise typer.Exit(1)
+ except OSError as exc:
+ typer.echo(f"Error: could not coordinate the Studio launch: {exc}", err = True)
+ raise typer.Exit(1)
+
+ try:
+ yield acquired
+ finally:
+ guard.__exit__(None, None, None)
+
+
def _stream_for_subprocess(stream):
"""Return *stream* if it has a real OS file descriptor, else None.
@@ -1482,6 +1508,7 @@ def studio_default(
raise typer.Exit(2)
return
+ runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
_preserve_cloudflare_intent(cloudflare, secure)
# --secure requires the tunnel; force a loopback bind.
@@ -1626,12 +1653,13 @@ def studio_default(
# captures nothing -- the same trap noted at the setup.ps1 call below.
# Omitting stdin does not withhold it (subprocess still fills it from
# GetStdHandle); that would need stdin = DEVNULL.
- proc = _sp.Popen(
- args,
- stdout = _stream_for_subprocess(sys.stdout),
- stderr = _stream_for_subprocess(sys.stderr),
- **_windows_hidden_subprocess_kwargs(),
- )
+ with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
+ proc = _sp.Popen(
+ args,
+ stdout = _stream_for_subprocess(sys.stdout),
+ stderr = _stream_for_subprocess(sys.stderr),
+ **_windows_hidden_subprocess_kwargs(),
+ )
try:
rc = proc.wait()
except KeyboardInterrupt:
@@ -1676,7 +1704,8 @@ def studio_default(
# in-process server serves exactly the dist we vouched for.
if resolved_frontend is not None:
run_kwargs["frontend_path"] = resolved_frontend
- run_server(**run_kwargs)
+ with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
+ run_server(**run_kwargs)
try:
if run_mod._shutdown_event is not None:
@@ -2061,6 +2090,7 @@ def run(
# env so an older child ignores it instead of treating it as a llama-server arg.
inherited_start_api_key_marker = _consume_start_api_key_marker_env()
start_api_key_marker = start_api_key_marker or inherited_start_api_key_marker
+ runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
# Back-compat: --not-secure is a deprecated alias for --no-secure.
secure = _resolve_secure(secure, not_secure)
@@ -2317,7 +2347,11 @@ def run(
os.environ[_START_API_KEY_MARKER_ENV] = "1"
try:
if sys.platform == "win32":
- proc = subprocess.Popen(args)
+ with _studio_runtime_launch_guard(inherited = runtime_gate_handoff) as gate_held:
+ popen_kwargs = {}
+ if gate_held:
+ popen_kwargs["env"] = _studio_runtime_gate.runtime_gate_child_environment()
+ proc = subprocess.Popen(args, **popen_kwargs)
try:
rc = proc.wait()
except KeyboardInterrupt:
@@ -2359,7 +2393,8 @@ def run(
# Forward the frontend validated before the gate (in-venv path).
if resolved_frontend is not None:
run_kwargs["frontend_path"] = resolved_frontend
- app = run_server(**run_kwargs)
+ with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
+ app = run_server(**run_kwargs)
actual_port = getattr(app.state, "server_port", port) or port
# Steps 3-5 can abort (health timeout, model-load error, or Ctrl+C during the
@@ -2755,6 +2790,35 @@ def stop():
# ── unsloth studio setup / update ─────────────────────────────────────
+def _wait_for_windows_setup_process(process) -> int:
+ """Reap setup and its descendants before a runtime-gate owner can unwind."""
+
+ try:
+ return process.wait()
+ except BaseException:
+ if process.poll() is not None:
+ raise
+ try:
+ subprocess.run(
+ ["taskkill", "/PID", str(process.pid), "/T", "/F"],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ check = False,
+ **_windows_hidden_subprocess_kwargs(),
+ )
+ except BaseException:
+ # taskkill interrupted or unavailable: hold the gate until setup
+ # exits naturally rather than exposing a live mutator.
+ pass
+ while process.poll() is None:
+ try:
+ process.wait()
+ except KeyboardInterrupt:
+ continue
+ raise
+
+
def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None) -> None:
"""Find and run the studio setup/update script."""
script = _find_setup_script(repo_root)
@@ -2790,13 +2854,13 @@ def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None
]
)
# Explicitly hand std handles to the child so CI tee sees setup.ps1's
- # output. On Windows, subprocess.run defaults to close_fds=True
+ # output. On Windows, subprocess.Popen defaults to close_fds=True
# (bInheritHandles=False); combined with CREATE_NO_WINDOW the child
# has no console and no inherited handles, so Write-Host writes to
# nothing. Passing stdout/stderr makes Python mark the std handles
# inheritable via PROC_THREAD_ATTRIBUTE_HANDLE_LIST. Empty update.log
# on windows-latest CI was the smoking gun (runs 25533694490/25534292239).
- result = subprocess.run(
+ process = subprocess.Popen(
powershell_args,
env = env,
stdin = _stream_for_subprocess(sys.stdin),
@@ -2804,11 +2868,13 @@ def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None
stderr = _stream_for_subprocess(sys.stderr),
**_windows_hidden_subprocess_kwargs(),
)
+ returncode = _wait_for_windows_setup_process(process)
else:
result = subprocess.run(["bash", str(script)], env = env)
+ returncode = result.returncode
- if result.returncode != 0:
- raise typer.Exit(result.returncode)
+ if returncode != 0:
+ raise typer.Exit(returncode)
_INSTALLER_URL_BASH = "https://unsloth.ai/install.sh"
@@ -2971,7 +3037,10 @@ def setup(
),
):
"""Run Unsloth setup (called by install.ps1 / install.sh)."""
- _run_setup_script(verbose = verbose)
+ runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
+ with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
+ _studio_runtime_gate.ensure_managed_environment_is_idle(STUDIO_HOME)
+ _run_setup_script(verbose = verbose)
def _fail_if_install_damaged() -> None:
@@ -3140,21 +3209,24 @@ def update(
else:
os.environ["STUDIO_LOCAL_INSTALL"] = "0"
os.environ.pop("STUDIO_LOCAL_REPO", None)
- _release_self_exe_lock_windows()
- try:
- _run_setup_script(verbose = verbose, repo_root = repo_root)
- except BaseException:
- # Restore unsloth.exe from .deleteme if setup failed before pip
- # produced a replacement; otherwise the user has no CLI for recovery.
- _restore_self_exe_lock_windows()
- raise
- # On Windows clear the .deleteme orphan now that pip wrote a fresh
- # unsloth.exe; on next update os.replace would overwrite it anyway,
- # but leaving a stale binary around invites cross-version restore
- # confusion from _restore_self_exe_lock_windows.
- _cleanup_self_exe_lock_windows()
- if verify:
- _fail_if_install_damaged()
+ runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
+ with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
+ _studio_runtime_gate.ensure_managed_environment_is_idle(STUDIO_HOME)
+ _release_self_exe_lock_windows()
+ try:
+ _run_setup_script(verbose = verbose, repo_root = repo_root)
+ except BaseException:
+ # Restore unsloth.exe from .deleteme if setup failed before pip
+ # produced a replacement; otherwise the user has no CLI for recovery.
+ _restore_self_exe_lock_windows()
+ raise
+ # On Windows clear the .deleteme orphan now that pip wrote a fresh
+ # unsloth.exe; on next update os.replace would overwrite it anyway,
+ # but leaving a stale binary around invites cross-version restore
+ # confusion from _restore_self_exe_lock_windows.
+ _cleanup_self_exe_lock_windows()
+ if verify:
+ _fail_if_install_damaged()
# Tauri desktop owns its own bundle entries; skip CLI launcher refresh
# so a Tauri-initiated update doesn't create duplicate shortcuts.
if os.environ.get("UNSLOTH_TAURI_UPDATE") == "1":
diff --git a/unsloth_cli/tests/test_studio_run_parallel_flag.py b/unsloth_cli/tests/test_studio_run_parallel_flag.py
index dabcef2ed9a..d52c6cfbcf5 100644
--- a/unsloth_cli/tests/test_studio_run_parallel_flag.py
+++ b/unsloth_cli/tests/test_studio_run_parallel_flag.py
@@ -13,6 +13,7 @@ canonicaliser and the legacy `-m` / `-hfr` / `-f` shim.
from __future__ import annotations
+import contextlib
import json
import sys
from io import BytesIO
@@ -178,8 +179,9 @@ def _install_reexec_capture(monkeypatch, *, platform):
monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")
fake_venv = Path("/fake/studio/venv/unsloth_studio")
- fake_python = fake_venv / "bin" / "python"
- fake_bin = fake_venv / "bin" / "unsloth"
+ host_is_windows = sys.platform == "win32"
+ fake_python = fake_venv / ("Scripts/python.exe" if host_is_windows else "bin/python")
+ fake_bin = fake_python.parent / ("unsloth.exe" if host_is_windows else "unsloth")
monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_python)
real_is_file = Path.is_file
@@ -199,6 +201,12 @@ def _install_reexec_capture(monkeypatch, *, platform):
)
monkeypatch.setattr(sys, "platform", platform)
+ # Emulate Windows re-exec without calling Win32 APIs on non-Windows hosts.
+ monkeypatch.setattr(
+ studio_mod,
+ "_studio_runtime_launch_guard",
+ lambda **_kwargs: contextlib.nullcontext(True),
+ )
def capture(kind, argv):
captured.append(