Skip to content

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

Studio setup: build the frontend in the background on source installs (setup.sh and setup.ps1) (#13442)

Daniel Hanf5a45dd7493b
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 866d57c4569..cc3befcda23 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -196,6 +196,8 @@ function Exit-SetupFailure {
)
if (Get-Command Remove-WoaMergedOverrides -CommandType Function -ErrorAction SilentlyContinue) { Remove-WoaMergedOverrides }
if ($Code -eq 0) { $Code = 1 }
+ # A rerun right after this must not find the old frontend build still writing (#8818).
+ if ($script:FrontendBuildProc) { Stop-FrontendBuildBackground }
if (-not $NoTauriMarker -and ((@("1", "true") -contains $env:UNSLOTH_TAURI_MODE) -or
(@("1", "true") -contains $env:UNSLOTH_TAURI_UPDATE))) {
$singleLine = ($Message -replace '[\r\n]+', ' ').Trim()
@@ -205,6 +207,153 @@ function Exit-SetupFailure {
exit $Code
}
+# Frontend build overlapped with the Python and llama.cpp steps (#8818).
+$script:FrontendBuildProc = $null
+$script:FrontendBuildFiles = @()
+$script:FrontendBuildHidden = @()
+
+# Serial for Desktop, staged updates and verbose runs. `tsc -b && vite build` alone peaks near
+# 7 GB, so ask for 4 logical CPUs and 12 GiB usable; a failing probe keeps the serial path.
+function Test-FrontendBuildInBackground {
+ if (@("1", "true") -contains $env:UNSLOTH_STUDIO_SERIAL_SETUP) { return $false }
+ if ($script:UnslothVerbose) { return $false }
+ if (Get-Variable -Name StageRoot -ValueOnly -ErrorAction SilentlyContinue) { return $false }
+ if ((@("1", "true") -contains $env:UNSLOTH_TAURI_MODE) -or (@("1", "true") -contains $env:UNSLOTH_TAURI_UPDATE)) { return $false }
+ try {
+ if ([Environment]::ProcessorCount -lt 4) { return $false }
+ return ([long](Get-UsableMemoryMb -AvailableOnly) -ge 12288)
+ } catch { return $false }
+}
+
+# Start `npm run build` with its output in files and stdin on an empty file (a Ctrl-C must not
+# leave cmd.exe asking "Terminate batch job"). $false when it could not start: build serially.
+function Start-FrontendBuildBackground {
+ param(
+ [string]$WorkingDirectory,
+ [object[]]$HiddenGitignores = @(),
+ [string]$FilePath = $env:ComSpec,
+ [string[]]$ArgumentList = @("/d", "/c", "npm run build")
+ )
+ # cmd.exe finds only npm.cmd / .exe / .bat; a PowerShell-only npm.ps1 keeps the serial path.
+ if ($FilePath -eq $env:ComSpec -and
+ -not (Get-Command npm.cmd, npm.exe, npm.bat -CommandType Application -ErrorAction SilentlyContinue)) { return $false }
+ $files = @()
+ try {
+ foreach ($i in 1..3) { $files += (New-UnslothTemporaryFile).FullName }
+ $proc = Start-Process -FilePath $FilePath -ArgumentList $ArgumentList -WorkingDirectory $WorkingDirectory `
+ -NoNewWindow -PassThru -RedirectStandardOutput $files[0] -RedirectStandardError $files[1] `
+ -RedirectStandardInput $files[2] -ErrorAction Stop
+ # Windows PowerShell only reports ExitCode later if the handle was taken now.
+ $null = $proc.Handle
+ } catch {
+ foreach ($f in $files) { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue }
+ return $false
+ }
+ $script:FrontendBuildProc = $proc
+ $script:FrontendBuildFiles = $files
+ $script:FrontendBuildHidden = @($HiddenGitignores)
+ try { [System.IO.File]::WriteAllText($FrontendBuildMark, "$($proc.Id) $($proc.StartTime.ToFileTimeUtc())") } catch { }
+ return $true
+}
+
+# Wait (up to 10 min, then stop it) for a build a killed setup left running (marker = id + start time).
+function Wait-FrontendBuildOwner {
+ param([int]$TimeoutSeconds = 600)
+ try { $owner = @(([System.IO.File]::ReadAllText($FrontendBuildMark)).Trim() -split ' ') } catch { return }
+ if ($owner.Count -ne 2) { return }
+ $said = $false
+ $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
+ while ($true) {
+ try {
+ $p = Get-Process -Id ([int]$owner[0]) -ErrorAction Stop
+ # Within 1 s: .NET on Linux derives StartTime from boot time and drifts by microseconds.
+ if ([Math]::Abs($p.StartTime.ToFileTimeUtc() - [long]$owner[1]) -gt 10000000) { return }
+ } catch { return }
+ if ((Get-Date) -ge $deadline) { break }
+ if (-not $said) { substep "waiting for an earlier frontend build in this checkout (pid $($owner[0]))..."; $said = $true }
+ Start-Sleep -Seconds 1
+ }
+ # Still alive after that: hung, so stop its tree rather than share node_modules and dist with it.
+ try {
+ $taskkill = if ($env:SystemRoot) { Join-Path $env:SystemRoot "System32\taskkill.exe" } else { $null }
+ if ($taskkill -and (Test-Path -LiteralPath $taskkill)) {
+ & $taskkill /T /F /PID $p.Id *> $null
+ } else {
+ try { $p.Kill($true) } catch { $p.Kill() }
+ }
+ [void]$p.WaitForExit(10000)
+ } catch { }
+}
+
+function Restore-FrontendBuildGitignores {
+ foreach ($gi in $script:FrontendBuildHidden) {
+ Rename-Item -Path "$gi._twbuild" -NewName (Split-Path $gi -Leaf) -Force -ErrorAction SilentlyContinue
+ }
+ $script:FrontendBuildHidden = @()
+}
+
+function Remove-FrontendBuildFiles {
+ foreach ($f in $script:FrontendBuildFiles) { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue }
+ $script:FrontendBuildFiles = @()
+}
+
+# Kill the build's process tree and restore what it hid; the mark stays, so the next run rebuilds.
+function Stop-FrontendBuildBackground {
+ $proc = $script:FrontendBuildProc
+ if (-not $proc) { return }
+ $script:FrontendBuildProc = $null
+ try {
+ if (-not $proc.HasExited) {
+ $taskkill = if ($env:SystemRoot) { Join-Path $env:SystemRoot "System32\taskkill.exe" } else { $null }
+ if ($taskkill -and (Test-Path -LiteralPath $taskkill)) {
+ & $taskkill /T /F /PID $proc.Id *> $null
+ } else {
+ try { $proc.Kill($true) } catch { $proc.Kill() }
+ }
+ [void]$proc.WaitForExit(10000)
+ }
+ } catch { }
+ Restore-FrontendBuildGitignores
+ Remove-FrontendBuildFiles
+}
+
+# CSS check, the "built" line, and clearing the build mark: shared by the serial path and the join.
+function Complete-FrontendBuildOutput {
+ $CssFiles = Get-ChildItem (Join-Path $DistDir "assets") -Filter "*.css" -ErrorAction SilentlyContinue
+ $MaxCssSize = ($CssFiles | Measure-Object -Property Length -Maximum).Maximum
+ if ($MaxCssSize -lt 100000) {
+ step "frontend" "built (warning: CSS may be truncated)" "Yellow"
+ } else {
+ step "frontend" "built"
+ }
+ Remove-Item -LiteralPath $FrontendBuildMark -Force -ErrorAction SilentlyContinue
+}
+
+# Join the background build; with -IfDone, only when it has already exited.
+function Complete-FrontendBuildBackground {
+ param([switch]$IfDone)
+ $proc = $script:FrontendBuildProc
+ if (-not $proc) { return }
+ if ($IfDone -and -not $proc.HasExited) { return }
+ if (-not $proc.HasExited) { substep "waiting for the frontend build..." }
+ $proc.WaitForExit()
+ $buildExit = $proc.ExitCode
+ $script:FrontendBuildProc = $null
+ $output = ""
+ foreach ($f in $script:FrontendBuildFiles[0..1]) {
+ $text = Get-Content -LiteralPath $f -Raw -ErrorAction SilentlyContinue
+ if ($text) { $output += $text }
+ }
+ Restore-FrontendBuildGitignores
+ Remove-FrontendBuildFiles
+ if ($buildExit -ne 0) {
+ if ($output) { Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red }
+ Write-StudioLine "[ERROR] npm run build failed (exit code $buildExit)" -ForegroundColor Red
+ Exit-SetupFailure "Frontend build failed (exit code $buildExit)"
+ }
+ Complete-FrontendBuildOutput
+}
+
function Test-SetupScriptReplaced {
if ($env:UNSLOTH_SETUP_RERUN -eq '1' -or -not $script:SetupSelfAtStart) { return $false }
try { $now = [Convert]::ToBase64String([System.IO.File]::ReadAllBytes($script:SetupSelfPath)) } catch { return $false }
@@ -276,6 +425,8 @@ function Get-SetupHostInterpreterInVenv {
# Detect if running from pip install (no frontend/ dir in studio)
$FrontendDir = Join-Path $ScriptDir "frontend"
+# Build state, not a source input, so the CI dist cache key rightly leaves it out.
+$FrontendBuildMark = Join-Path $FrontendDir ".unsloth-build.local"
$OxcValidatorDir = Join-Path $ScriptDir "backend\core\data_recipe\oxc-validator"
$IsPipInstall = -not (Test-Path $FrontendDir)
@@ -1463,10 +1614,13 @@ function Get-LlamaJobsFor {
# rather than treated as unreadable, since falling back to installed RAM under
# real pressure would hand the machine its full core count at the worst moment.
function Get-UsableMemoryMb {
+ # -AvailableOnly: -1 rather than installed RAM when free memory cannot be read.
+ param([switch]$AvailableOnly)
try {
$avail = (Get-CimInstance Win32_PerfRawData_PerfOS_Memory -ErrorAction Stop).AvailableMBytes
if ($null -ne $avail) { return [long]$avail }
} catch { }
+ if ($AvailableOnly) { return -1 }
try {
$bytes = (Get-CimInstance Win32_ComputerSystem -ErrorAction Stop).TotalPhysicalMemory
if ($bytes -gt 0) { return [long]($bytes / 1MB) }
@@ -5774,11 +5928,14 @@ if ($SkipFrontend) {
Where-Object { $_.Name -ne "bun.lock" -and $_.LastWriteTime -gt $DistTime } |
Select-Object -First 1
}
- if (-not $NewerFile) {
+ if ($NewerFile) {
+ substep "Frontend source changed since last build -- rebuilding..." "Yellow"
+ } elseif (Test-Path -LiteralPath $FrontendBuildMark) {
+ # An earlier build that never finished (killed, failed) left its mark: redo it.
+ substep "Previous frontend build did not finish -- rebuilding..." "Yellow"
+ } else {
$NeedFrontendBuild = $false
step "frontend" "up to date"
- } else {
- substep "Frontend source changed since last build -- rebuilding..." "Yellow"
}
}
@@ -5920,12 +6077,19 @@ if ($NeedNodeForSetup) {
if ($NeedFrontendBuild -and -not $IsPipInstall) {
Write-StudioLine ""
substep "building frontend..."
+ Wait-FrontendBuildOwner
+ # Cleared only once the build succeeds, so one that dies at any point is redone next run.
+ try { [System.IO.File]::WriteAllText($FrontendBuildMark, "$PID") } catch { }
# Tailwind v4's oxide scanner respects parent .gitignore, and a venv's "*" hides the .tsx files.
$HiddenGitignores = @()
$WalkDir = (Get-Item $FrontendDir).Parent.FullName
while ($WalkDir -and $WalkDir -ne [System.IO.Path]::GetPathRoot($WalkDir)) {
$gi = Join-Path $WalkDir ".gitignore"
+ # A build stopped by Ctrl-C or a closed window never put its hidden file back.
+ if (-not (Test-Path -LiteralPath $gi) -and (Test-Path -LiteralPath "$gi._twbuild" -PathType Leaf)) {
+ Rename-Item -LiteralPath "$gi._twbuild" -NewName ".gitignore" -ErrorAction SilentlyContinue
+ }
if (Test-Path $gi) {
$content = Get-Content $gi -Raw -ErrorAction SilentlyContinue
if ($content -and ($content.Trim() -match '^\*$')) {
@@ -5992,29 +6156,28 @@ if ($NeedFrontendBuild -and -not $IsPipInstall) {
}
}
- $buildExit = Invoke-SetupCommand { npm run build }
- if ($buildExit -ne 0) {
+ if ((Test-FrontendBuildInBackground) -and
+ (Start-FrontendBuildBackground -WorkingDirectory $FrontendDir -HiddenGitignores $HiddenGitignores)) {
+ Pop-Location
+ $ErrorActionPreference = $prevEAP_npm
+ } else {
+ $buildExit = Invoke-SetupCommand { npm run build }
+ if ($buildExit -ne 0) {
+ Pop-Location
+ $ErrorActionPreference = $prevEAP_npm
+ foreach ($gi in $HiddenGitignores) { Rename-Item -Path "$gi._twbuild" -NewName (Split-Path $gi -Leaf) -Force -ErrorAction SilentlyContinue }
+ Write-StudioLine "[ERROR] npm run build failed (exit code $buildExit)" -ForegroundColor Red
+ Exit-SetupFailure "Frontend build failed (exit code $buildExit)"
+ }
Pop-Location
$ErrorActionPreference = $prevEAP_npm
- foreach ($gi in $HiddenGitignores) { Rename-Item -Path "$gi._twbuild" -NewName (Split-Path $gi -Leaf) -Force -ErrorAction SilentlyContinue }
- Write-StudioLine "[ERROR] npm run build failed (exit code $buildExit)" -ForegroundColor Red
- Exit-SetupFailure "Frontend build failed (exit code $buildExit)"
- }
- Pop-Location
- $ErrorActionPreference = $prevEAP_npm
- # ── Restore hidden .gitignore files ──
- foreach ($gi in $HiddenGitignores) {
- Rename-Item -Path "$gi._twbuild" -NewName (Split-Path $gi -Leaf) -Force -ErrorAction SilentlyContinue
- }
+ # ── Restore hidden .gitignore files ──
+ foreach ($gi in $HiddenGitignores) {
+ Rename-Item -Path "$gi._twbuild" -NewName (Split-Path $gi -Leaf) -Force -ErrorAction SilentlyContinue
+ }
- # ── Validate CSS output ──
- $CssFiles = Get-ChildItem (Join-Path $DistDir "assets") -Filter "*.css" -ErrorAction SilentlyContinue
- $MaxCssSize = ($CssFiles | Measure-Object -Property Length -Maximum).Maximum
- if ($MaxCssSize -lt 100000) {
- step "frontend" "built (warning: CSS may be truncated)" "Yellow"
- } else {
- step "frontend" "built"
+ Complete-FrontendBuildOutput
}
}
@@ -9420,6 +9583,7 @@ if ($stackExit -ne 0) {
# Phases a release adds below would be skipped by the update installing it. A module scope keeps this
# run's variables from the new copy; it cannot see $PSDefaultParameterValues, so those are passed in.
if (Test-SetupScriptReplaced) {
+ Complete-FrontendBuildBackground
step "setup" "the update replaced this setup script; finishing with the new version"
$_setupRerunArgs = $script:SetupArgs
Restore-SetupStartEnvironment
@@ -9450,6 +9614,7 @@ if (Test-SetupScriptReplaced) {
# Restore ErrorActionPreference (was lowered for pip/python section)
$ErrorActionPreference = $prevEAP
}
+Complete-FrontendBuildBackground -IfDone
# Windows MXC Preview is an optional, pinned prebuilt like the other native
# runtimes. Keep this outside the Python dependency fast path: a missing or
@@ -10404,6 +10569,8 @@ if ($env:AUDIOCPP_SERVER_PATH -or $env:UNSLOTH_AUDIO_CPP_PATH) {
if ($StageRoot -and $NeedLlamaSourceBuild) {
Exit-SetupFailure "Background staging cannot install system build tools for llama.cpp; retry with the foreground updater."
}
+# A CMake build next to `tsc -b && vite build` can exhaust a host the overlap gate admitted.
+if ($NeedLlamaSourceBuild) { Complete-FrontendBuildBackground }
# Asked before Phase 3.5: OpenSSL is a system install too.
$script:LlamaBuildToolsDeclined = $NeedLlamaSourceBuild -and $script:LlamaSourceBuildIsFallback -and (Test-LlamaBuildToolsMissing) -and
@@ -11111,6 +11278,8 @@ if (-not $llamaCppIsLink -and (
Remove-AgentInstructionFiles -Roots @($LlamaCppDir)
}
+Complete-FrontendBuildBackground
+
# ─────────────────────────────────────────────
# Footer
# ─────────────────────────────────────────────
diff --git a/studio/setup.sh b/studio/setup.sh
index 76a922557f9..7babbf18356 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -85,6 +85,8 @@ setup_fail() {
case "${UNSLOTH_TAURI_MODE:-0}" in 1|true) tauri_marker=1 ;; esac
case "${UNSLOTH_TAURI_UPDATE:-0}" in 1|true) tauri_marker=1 ;; esac
if [ "$tauri_marker" -eq 1 ]; then printf '[TAURI:ERROR] %s\n' "$message"; fi
+ # A rerun right after this must not find the old build still writing (#8818).
+ [ -z "${_FRONTEND_BG_PID:-}" ] || _frontend_bg_cancel
exit "$exit_code"
}
@@ -133,6 +135,148 @@ _remove_agent_instruction_files() {
done
}
+# Frontend build overlapped with the Python and llama.cpp steps (#8818).
+_FRONTEND_BG_PID=""
+_FRONTEND_BG_LOG=""
+# Build state, not a source input, so the CI dist cache key rightly leaves it out.
+_FRONTEND_BUILD_MARK="$SCRIPT_DIR/frontend/.unsloth-build.local"
+
+# Serial for Desktop, staged updates and verbose runs. `tsc -b && vite build` alone peaks near
+# 7 GB RSS, so ask for 4 CPUs and 12 GiB usable (cgroup-aware); an unreadable probe = serial.
+_frontend_can_build_in_background() {
+ case "${UNSLOTH_STUDIO_SERIAL_SETUP:-0}" in 1|true) return 1 ;; esac
+ _is_verbose && return 1
+ [ -z "${STAGE_ROOT:-}" ] || return 1
+ case "${UNSLOTH_TAURI_MODE:-0}" in 1|true) return 1 ;; esac
+ case "${UNSLOTH_TAURI_UPDATE:-0}" in 1|true) return 1 ;; esac
+ local _cpus _mb
+ _cpus=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null) || return 1
+ [ "$_cpus" -ge 4 ] 2>/dev/null || return 1
+ # Without MemAvailable the helper falls back to installed RAM, not headroom.
+ [ ! -r /proc/meminfo ] || grep -q '^MemAvailable:' /proc/meminfo || return 1
+ _mb=$(_usable_ram_mb)
+ [ "${_mb:-0}" -ge 12288 ] 2>/dev/null || return 1
+ # A rerun waits for a build still being stopped by the identity in its marker.
+ [ -n "$(_frontend_proc_id "$$")" ]
+}
+
+# Put back an ancestor .gitignore a killed build hid.
+_frontend_build_cleanup() {
+ local _dir="$SCRIPT_DIR/frontend"
+ while [ "$_dir" != "/" ]; do
+ _dir="$(dirname "$_dir")"
+ if [ -f "$_dir/.gitignore._twbuild" ] && [ ! -e "$_dir/.gitignore" ]; then
+ mv "$_dir/.gitignore._twbuild" "$_dir/.gitignore" 2>/dev/null || :
+ fi
+ done
+}
+
+# "<pid> <start time>" of a process, the identity a build marker records.
+_frontend_proc_id() {
+ ps -o pid= -o lstart= -p "$1" 2>/dev/null | sed 's/^ *//'
+}
+
+# Mark set before a build touches the tree, cleared only on success. Wait (up to 10 min, zombies
+# excluded) for a live marked build, then 30 s for its group, and undo what it hid.
+_frontend_build_begin() {
+ local _owner="" _pid _n=0 _self
+ _self=$(exec sh -c 'echo "$PPID"')
+ [ -f "$_FRONTEND_BUILD_MARK" ] && _owner=$(head -c 200 "$_FRONTEND_BUILD_MARK" 2>/dev/null)
+ _pid=${_owner%% *}
+ while [ -n "$_owner" ] && [ "$_pid" != "$_self" ] &&
+ [ "$(head -c 200 "$_FRONTEND_BUILD_MARK" 2>/dev/null)" = "$_owner" ] &&
+ [ "$(_frontend_proc_id "$_pid")" = "$_owner" ] && [ "$_n" -lt "${_FRONTEND_OWNER_POLLS:-600}" ] &&
+ [ "$(ps -o stat= -p "$_pid" 2>/dev/null | cut -c1)" != Z ]; do
+ [ "$_n" -ne 10 ] || substep "waiting for another frontend build in this checkout (pid $_pid)..."
+ sleep 1
+ _n=$((_n + 1))
+ done
+ # Still alive after that: a hung background build (its own group), so stop it, never share the tree.
+ if [ "$_n" -ge "${_FRONTEND_OWNER_POLLS:-600}" ] && [ "$(ps -o pgid= -p "$_pid" 2>/dev/null | tr -d ' ')" = "$_pid" ]; then
+ kill -KILL -- "-$_pid" 2>/dev/null || :
+ fi
+ _n=0
+ while [ -n "$_owner" ] && [ "$_pid" != "$_self" ] && [ "$_n" -lt 30 ] &&
+ [ "$_pid" -gt 1 ] 2>/dev/null && kill -0 -- "-$_pid" 2>/dev/null; do
+ sleep 1
+ _n=$((_n + 1))
+ done
+ _frontend_build_cleanup
+ _frontend_proc_id "$_self" > "$_FRONTEND_BUILD_MARK" 2>/dev/null || :
+}
+
+# TERM, then KILL after 5 s (npm ci ignores TERM; KILL skips its EXIT trap, hence the cleanup).
+# The group's watcher keeps its id from being reused until this KILL.
+_frontend_bg_stop() {
+ local _n=0
+ kill -TERM -- "-$1" 2>/dev/null || return 0
+ while [ "$_n" -lt 5 ] && kill -0 "$1" 2>/dev/null; do
+ sleep 1
+ _n=$((_n + 1))
+ done
+ _frontend_build_cleanup
+ kill -KILL -- "-$1" 2>/dev/null || :
+}
+
+# Own process group; a watcher ignoring HUP/INT/TERM stops it if setup dies (errexit, Ctrl-C).
+_frontend_bg_start() {
+ local _monitor=off
+ case "$-" in *m*) _monitor=on ;; esac
+ _FRONTEND_BG_LOG=$(mktemp)
+ [ "$_monitor" = on ] || set -m
+ (
+ set +m
+ _fbs_leader=$(exec sh -c 'echo "$PPID"')
+ (
+ trap '' HUP INT TERM
+ while kill -0 "$$" 2>/dev/null; do sleep 1; done
+ rm -f "$_FRONTEND_BG_LOG"
+ _frontend_bg_stop "$_fbs_leader"
+ ) </dev/null >/dev/null 2>&1 &
+ trap 'exit 143' TERM
+ _FRONTEND_IN_JOB=1
+ _build_frontend
+ _install_oxc_runtime
+ rm -f "$_FRONTEND_BUILD_MARK"
+ _remove_agent_instruction_files "$SCRIPT_DIR/frontend/node_modules"
+ _remove_agent_instruction_files "$_OXC_DIR/node_modules"
+ ) </dev/null >"$_FRONTEND_BG_LOG" 2>&1 &
+ _FRONTEND_BG_PID=$!
+ [ "$_monitor" = on ] || set +m
+}
+
+_frontend_bg_cancel() {
+ [ -n "${_FRONTEND_BG_PID:-}" ] || return 0
+ local _pid=$_FRONTEND_BG_PID
+ _FRONTEND_BG_PID=""
+ _frontend_bg_stop "$_pid"
+ wait "$_pid" 2>/dev/null || :
+ rm -f "$_FRONTEND_BG_LOG"
+}
+
+_frontend_bg_join() {
+ [ -n "$_FRONTEND_BG_PID" ] || return 0
+ local _pid=$_FRONTEND_BG_PID _rc=0
+ if kill -0 "$_pid" 2>/dev/null; then
+ substep "waiting for the frontend build..."
+ fi
+ wait "$_pid" || _rc=$?
+ _FRONTEND_BG_PID=""
+ # The watcher still holds the group: this takes it and anything the build left running.
+ kill -KILL -- "-$_pid" 2>/dev/null || :
+ [ "$_rc" -eq 0 ] || _frontend_build_cleanup
+ cat "$_FRONTEND_BG_LOG" 2>/dev/null || :
+ rm -f "$_FRONTEND_BG_LOG"
+ [ "$_rc" -eq 0 ] || setup_fail "$_rc" "Frontend build failed (exit code $_rc)"
+}
+
+# Surface a finished build (above all a failed one) at a step boundary, not at the end.
+_frontend_bg_reap() {
+ [ -n "$_FRONTEND_BG_PID" ] || return 0
+ kill -0 "$_FRONTEND_BG_PID" 2>/dev/null && return 0
+ _frontend_bg_join
+}
+
# ── Bounded `--version` probe for binaries setup does not own (uv candidates, the system Node) ──
_SETUP_PROBE_TARGET=""
_SETUP_PROBE_PID=""
@@ -2150,6 +2294,38 @@ _packaged_frontend_available() {
[ -f "$SCRIPT_DIR/frontend/dist/index.html" ]
}
+# ── oxc-validator runtime ──
+_install_oxc_runtime() {
+# Skip when the user opted out of Node (NODE_SOURCE=skip): there is no suitable
+# Node, so do not run npm install against an unsuitable/absent system Node.
+if [ -d "$_OXC_DIR" ] && [ "${NODE_SOURCE:-}" != skip ] && command -v npm &>/dev/null; then
+ cd "$_OXC_DIR"
+ _OXC_INSTALL_LOG=$(mktemp)
+ _CAPTURE_LOG="$_OXC_INSTALL_LOG"
+ # `|| _oxc_install_rc=$?` keeps this off `set -e`'s exit path so the hint branch
+ # below is reachable; it also captures the exact exit code.
+ _oxc_install_rc=0
+ _NPM_INSTALL=install
+ [ -f package-lock.json ] && _NPM_INSTALL=ci
+ run_quiet_no_exit "npm $_NPM_INSTALL (oxc validator runtime)" npm "$_NPM_INSTALL" --no-fund --no-audit --loglevel=error "${_NPM_REGISTRY_ARGS[@]+"${_NPM_REGISTRY_ARGS[@]}"}" || _oxc_install_rc=$?
+ if [ "$_oxc_install_rc" -ne 0 ] && _npm_mirror_retry "npm $_NPM_INSTALL (oxc validator runtime)"; then
+ _oxc_install_rc=0
+ fi
+ _CAPTURE_LOG=""
+ if [ "$_oxc_install_rc" -ne 0 ]; then
+ _suggest_npm_registry "$_OXC_INSTALL_LOG"
+ rm -f "$_OXC_INSTALL_LOG"
+ setup_fail "$_oxc_install_rc" "OXC validator dependency installation failed (exit code $_oxc_install_rc)"
+ fi
+ rm -f "$_OXC_INSTALL_LOG"
+ cd "$SCRIPT_DIR"
+elif [ -d "$_OXC_DIR" ] && [ "${NODE_SOURCE:-}" != skip ]; then
+ # No npm on PATH: skip rather than abort; the backend Node resolver degrades
+ # the validator gracefully. Mirrors setup.ps1's elseif on this block.
+ substep "OXC validator runtime skipped (no npm found); code validation degrades until Node is available" "$C_WARN"
+fi
+}
+
if [ "$_LLAMA_ONLY" != "1" ]; then
# ── Detect whether frontend needs building ──
# Tauri owns its frontend bundle. Standard PyPI installs use the release-built
@@ -2172,6 +2348,8 @@ if [ -d "$SCRIPT_DIR/frontend/dist" ]; then
fi
[ -z "$_changed" ] && _NEED_FRONTEND_BUILD=false
fi
+# An earlier build that never finished (killed, failed) left its mark: redo it.
+[ ! -e "$_FRONTEND_BUILD_MARK" ] || _NEED_FRONTEND_BUILD=true
fi # end packaged/Tauri guard
# OXC validator runtime (below) needs node/npm whenever its dir exists, regardless
@@ -2361,6 +2539,8 @@ fi
# ── Build frontend ──
substep "building frontend..."
+_build_frontend() {
+_frontend_build_begin
cd "$SCRIPT_DIR/frontend"
_HIDDEN_GITIGNORES=()
_dir="$(pwd)"
@@ -2377,7 +2557,7 @@ _restore_gitignores() {
mv "${_gi}._twbuild" "$_gi" 2>/dev/null || true
done
}
-trap _restore_gitignores EXIT
+trap _frontend_build_cleanup EXIT
# package-lock.json always wins (`npm ci`); bun only without one, since bun.lock is gitignored.
# Build always uses npm (Node runtime -- avoids bun runtime issues on some platforms).
@@ -2457,6 +2637,8 @@ run_quiet "npm run build" npm run build
_restore_gitignores
trap - EXIT
+# The background job keeps the mark until the OXC install it runs next is done too.
+[ -n "${_FRONTEND_IN_JOB:-}" ] || rm -f "$_FRONTEND_BUILD_MARK"
_MAX_CSS=$(find "$SCRIPT_DIR/frontend/dist/assets" -name '*.css' -exec wc -c {} + 2>/dev/null | sort -n | tail -1 | awk '{print $1}')
if [ -z "$_MAX_CSS" ]; then
@@ -2468,45 +2650,26 @@ else
fi
cd "$SCRIPT_DIR"
+}
+
+if _frontend_can_build_in_background; then
+ _frontend_bg_start
+ cd "$SCRIPT_DIR"
+else
+ _build_frontend
+fi
fi # end _FRONTEND_SKIP guard (Node available: system or isolated)
fi # end frontend build check
-# ── oxc-validator runtime ──
-# Skip when the user opted out of Node (NODE_SOURCE=skip): there is no suitable
-# Node, so do not run npm install against an unsuitable/absent system Node.
-if [ -d "$_OXC_DIR" ] && [ "${NODE_SOURCE:-}" != skip ] && command -v npm &>/dev/null; then
- cd "$_OXC_DIR"
- _OXC_INSTALL_LOG=$(mktemp)
- _CAPTURE_LOG="$_OXC_INSTALL_LOG"
- # `|| _oxc_install_rc=$?` keeps this off `set -e`'s exit path so the hint branch
- # below is reachable; it also captures the exact exit code.
- _oxc_install_rc=0
- _NPM_INSTALL=install
- [ -f package-lock.json ] && _NPM_INSTALL=ci
- run_quiet_no_exit "npm $_NPM_INSTALL (oxc validator runtime)" npm "$_NPM_INSTALL" --no-fund --no-audit --loglevel=error "${_NPM_REGISTRY_ARGS[@]+"${_NPM_REGISTRY_ARGS[@]}"}" || _oxc_install_rc=$?
- if [ "$_oxc_install_rc" -ne 0 ] && _npm_mirror_retry "npm $_NPM_INSTALL (oxc validator runtime)"; then
- _oxc_install_rc=0
- fi
- _CAPTURE_LOG=""
- if [ "$_oxc_install_rc" -ne 0 ]; then
- _suggest_npm_registry "$_OXC_INSTALL_LOG"
- rm -f "$_OXC_INSTALL_LOG"
- setup_fail "$_oxc_install_rc" "OXC validator dependency installation failed (exit code $_oxc_install_rc)"
- fi
- rm -f "$_OXC_INSTALL_LOG"
- cd "$SCRIPT_DIR"
-elif [ -d "$_OXC_DIR" ] && [ "${NODE_SOURCE:-}" != skip ]; then
- # No npm on PATH: skip rather than abort; the backend Node resolver degrades
- # the validator gracefully. Mirrors setup.ps1's elseif on this block.
- substep "OXC validator runtime skipped (no npm found); code validation degrades until Node is available" "$C_WARN"
+# A background build runs this itself: it shares the npm mirror the build may have switched to.
+if [ -z "$_FRONTEND_BG_PID" ]; then
+ _install_oxc_runtime
+ _remove_agent_instruction_files "$SCRIPT_DIR/frontend/node_modules"
+ _remove_agent_instruction_files "$_OXC_DIR/node_modules"
fi
-_remove_agent_instruction_files \
- "$SCRIPT_DIR/frontend/node_modules" \
- "$_OXC_DIR/node_modules"
-
# ── Python venv + deps ──
[ -d "$REPO_ROOT/.venv" ] && rm -rf "$REPO_ROOT/.venv"
@@ -2571,6 +2734,8 @@ _setup_rerun_if_replaced() {
if [ -z "$_now" ] || [ "$_now" = "$_SETUP_SELF_SUM" ]; then
return 0
fi
+ # exec keeps this PID, so the watcher would not stop a build the new script then repeats.
+ _frontend_bg_join
step "setup" "the update replaced this setup script; finishing with the new version"
export UNSLOTH_SETUP_RERUN=1
unset UNSLOTH_STUDIO_FULL_DEPS
@@ -3635,6 +3800,7 @@ else
step "python" "dependencies up to date"
verbose_substep "python deps check: installed=$_PKG_NAME@${INSTALLED_VER:-unknown} latest=${LATEST_VER:-unknown}"
fi
+_frontend_bg_reap
# ── 6b. Pre-install transformers 5.x into .venv_t5_530/, .venv_t5_550/, and .venv_t5_510/ ──
# Models like GLM-4.7-Flash, Qwen3 MoE need transformers>=5.3.0.
@@ -4447,6 +4613,8 @@ else
substep "Training and GPU inference require an NVIDIA or AMD ROCm GPU."
fi
+_frontend_bg_reap
+
# ── 7. Prefer prebuilt llama.cpp bundles before any source build path ──
# Nest llama.cpp under $STUDIO_HOME only for real env-overrides; legacy
# default keeps ~/.unsloth/llama.cpp so pre-PR builds are still discovered.
@@ -5207,6 +5375,11 @@ if [ "$_NEED_LLAMA_SOURCE_BUILD" = true ] && grep -qi microsoft /proc/version 2>
fi
fi
+# A CMake build next to `tsc -b && vite build` can exhaust a host the overlap gate admitted.
+if [ "$_NEED_LLAMA_SOURCE_BUILD" = true ]; then
+ _frontend_bg_join
+fi
+
# ── 9. Build llama.cpp binaries for GGUF inference + export when prebuilt install fails ──
# Builds at ~/.unsloth/llama.cpp — a single shared location under the user's
# home directory. This is used by both the inference server and the GGUF
@@ -5843,6 +6016,7 @@ else
_WHISPER_BUILD="$SCRIPT_DIR/../scripts/build_whisper_cpp.sh"
if [ "${UNSLOTH_WHISPER_FORCE_COMPILE:-0}" = "1" ] && [ -f "$_WHISPER_BUILD" ] \
&& command -v cmake >/dev/null 2>&1 && command -v git >/dev/null 2>&1; then
+ _frontend_bg_join
substep "whisper.cpp prebuilt unavailable; building from source (UNSLOTH_WHISPER_FORCE_COMPILE=1)..."
# The source build overwrites whisper-server in the managed dir but
# knows nothing about the prebuilt marker; a stale marker would make
@@ -5940,6 +6114,8 @@ _print_llama_gpu_notes() {
fi
}
+_frontend_bg_join
+
# ── Footer ──
if [ "$_LLAMA_ONLY" = "1" ]; then
echo ""
diff --git a/tests/sh/test_setup_frontend_overlap.sh b/tests/sh/test_setup_frontend_overlap.sh
new file mode 100644
index 00000000000..88df5a2a8d4
--- /dev/null
+++ b/tests/sh/test_setup_frontend_overlap.sh
@@ -0,0 +1,361 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+#
+# setup.sh runs the frontend build in the background on a source install (#8818).
+# These run the real helpers (and the real setup_fail) against a stand-in _build_frontend:
+# the join reports the build's output and exit code, a setup that fails or is interrupted
+# first takes the whole build with it, puts back what it hid and leaves the tree marked for
+# a rebuild, a new build waits for one still being stopped, and the gate keeps Desktop,
+# staged updates, verbose, opted-out and small machines serial.
+set -u
+
+ROOT=$(CDPATH= cd -- "$(dirname "$0")/../.." && pwd)
+SETUP_SH="$ROOT/studio/setup.sh"
+. "$ROOT/tests/sh/_harness.sh"
+WORK=$(mktemp -d)
+trap 'rm -rf "$WORK"' EXIT
+
+HELPERS="$WORK/helpers.sh"
+FNS="setup_fail _remove_agent_instruction_files _frontend_can_build_in_background
+ _frontend_build_cleanup _frontend_proc_id _frontend_build_begin _frontend_bg_stop _frontend_bg_start _frontend_bg_cancel
+ _frontend_bg_join _frontend_bg_reap"
+{
+ printf '_FRONTEND_BG_PID=""\n_FRONTEND_BG_LOG=""\n'
+ grep '^_FRONTEND_BUILD_MARK=' "$SETUP_SH"
+ for fn in $FNS; do
+ sed -n "/^$fn() {/,/^}/p" "$SETUP_SH"
+ done
+} > "$HELPERS"
+for fn in $FNS; do
+ grep -q "^$fn() {" "$HELPERS" || { echo "FAIL: $fn not found in setup.sh"; exit 1; }
+done
+
+STUBS='
+set -euo pipefail
+step() { echo "step $*"; }
+substep() { echo "substep $*"; }
+_is_verbose() { [ "${UNSLOTH_VERBOSE:-0}" = "1" ]; }
+_install_oxc_runtime() { echo "oxc-installed"; [ -z "${OXC_FAIL:-}" ] || exit "$OXC_FAIL"; }
+_OXC_DIR="$SCRIPT_DIR/backend/oxc"
+'
+
+FE="$WORK/outer/studio/frontend"
+MARK="$FE/.unsloth-build.local"
+run_case() {
+ # $1 = body appended after the helpers; prints the script output and "rc=N".
+ local out rc=0
+ out=$(SCRIPT_DIR="$WORK/outer/studio" STAGE_ROOT="" bash -c "$STUBS
+. '$HELPERS'
+$1" 2>&1) || rc=$?
+ printf '%s\nrc=%s\n' "$out" "$rc"
+}
+wait_gone() {
+ # Wait up to $2 s for pid $1 to disappear; 0 when it did.
+ local _i=0
+ while kill -0 "$1" 2>/dev/null && [ "$_i" -lt "$(( $2 * 5 ))" ]; do sleep 0.2; _i=$((_i + 1)); done
+ ! kill -0 "$1" 2>/dev/null
+}
+mkdir -p "$FE/node_modules/pkg" "$FE/src"
+
+echo "== join reports a successful build after the parent's own steps =="
+out=$(run_case '
+_build_frontend() { sleep 1; echo "built-line"; }
+_frontend_bg_start
+echo "parent-step"
+_frontend_bg_join
+echo "after-join"')
+assert_contains "build output is replayed" "$out" "built-line"
+assert_eq "parent step runs while the build is still going" "parent-step" \
+ "$(printf '%s\n' "$out" | grep -E '^(parent-step|built-line)$' | head -1)"
+assert_contains "parent continues after a good build" "$out" "after-join"
+assert_contains "exit 0" "$out" "rc=0"
+
+echo "== the OXC runtime installs inside the job, after the build =="
+assert_eq "build line then OXC line" "built-line oxc-installed" \
+ "$(printf '%s\n' "$out" | grep -E '^(built-line|oxc-installed)$' | tr '\n' ' ' | sed 's/ $//')"
+out=$(OXC_FAIL=6 run_case '
+_build_frontend() { echo "built-line"; }
+_frontend_bg_start
+_frontend_bg_join
+echo "not-reached"')
+assert_contains "an OXC failure in the job fails setup with its code" "$out" "rc=6"
+assert_not_contains "setup stops" "$out" "not-reached"
+
+echo "== a failed build fails setup with its exit code =="
+out=$(run_case '
+_build_frontend() { echo "npm error"; exit 7; }
+_frontend_bg_start
+_frontend_bg_join
+echo "not-reached"')
+assert_contains "build output is replayed" "$out" "npm error"
+assert_not_contains "setup stops" "$out" "not-reached"
+assert_contains "exit 7" "$out" "rc=7"
+
+echo "== errexit inside the build still fails it =="
+out=$(run_case '
+_build_frontend() { false; echo "kept-going"; }
+_frontend_bg_start
+_frontend_bg_join')
+assert_not_contains "a failing command stops the build" "$out" "kept-going"
+assert_contains "and fails setup" "$out" "rc=1"
+
+echo "== reap is non-blocking and joins a finished build =="
+out=$(run_case '
+_build_frontend() { sleep 2; echo "late"; }
+_frontend_bg_start
+_frontend_bg_reap
+echo "pid-after-first-reap=${_FRONTEND_BG_PID:+set}"
+sleep 3
+_frontend_bg_reap
+echo "pid-after-second-reap=${_FRONTEND_BG_PID:-empty}"')
+assert_contains "running build is left alone" "$out" "pid-after-first-reap=set"
+assert_contains "finished build is joined" "$out" "pid-after-second-reap=empty"
+assert_contains "and its output shown" "$out" "late"
+
+echo "== reap surfaces a failed build at the next boundary =="
+out=$(run_case '
+_build_frontend() { exit 5; }
+_frontend_bg_start
+sleep 1
+_frontend_bg_reap
+echo "not-reached"')
+assert_contains "exit 5" "$out" "rc=5"
+assert_not_contains "setup stops at the boundary" "$out" "not-reached"
+
+# A build that marks the tree, hides an ancestor .gitignore, writes dist and ignores TERM.
+STUBBORN="_build_frontend() {
+ _frontend_build_begin
+ mv '$WORK/outer/.gitignore' '$WORK/outer/.gitignore._twbuild'
+ mkdir -p '$FE/dist'
+ python3 -c 'import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(300)' &
+ echo \$! > '$WORK/grandchild'
+ wait
+}"
+# Never fall back to pid 0: `kill 0` signals this test's own process group.
+grandchild() { local p; p=$(cat "$WORK/grandchild" 2>/dev/null); case "$p" in ''|*[!0-9]*|0) ;; *) echo "$p" ;; esac; }
+READY="i=0; while [ ! -s '$WORK/grandchild' ] && [ \$i -lt 50 ]; do sleep 0.1; i=\$((i + 1)); done"
+prime() {
+ printf '*\n' > "$WORK/outer/.gitignore"
+ rm -rf "$WORK/outer/.gitignore._twbuild" "$FE/dist" "$WORK/grandchild" "$MARK"
+}
+check_aftermath() {
+ local gc
+ gc=$(grandchild)
+ if [ -z "$gc" ]; then bad "$1: build never started its child"; elif wait_gone "$gc" 10; then ok "$1: TERM-resistant child was killed"; else bad "$1: child $gc still running"; kill -KILL "$gc" 2>/dev/null; fi
+ assert_eq "$1: ancestor .gitignore is back" "*" "$(cat "$WORK/outer/.gitignore" 2>/dev/null)"
+ if [ -e "$MARK" ]; then ok "$1: tree stays marked, so the next run rebuilds"; else bad "$1: build mark gone"; fi
+}
+
+echo "== setup_fail stops the build before it returns =="
+prime
+out=$(run_case "$STUBBORN
+_frontend_bg_start
+$READY
+echo \"log=\$_FRONTEND_BG_LOG\"
+setup_fail 3 boom")
+assert_contains "setup exits with its own code" "$out" "rc=3"
+gc=$(grandchild)
+# A killed child can still be listed for a moment until it is reaped.
+if [ -n "$gc" ] && ! wait_gone "$gc" 2; then bad "build still running when setup_fail returned"; else ok "nothing of the build survives setup_fail"; fi
+log=$(printf '%s\n' "$out" | sed -n 's/^log=//p')
+if [ -n "$log" ] && [ ! -e "$log" ]; then ok "build log removed"; else bad "build log '$log' left behind"; fi
+check_aftermath "setup_fail"
+
+echo "== a setup killed by errexit is cleaned up by the watcher =="
+prime
+out=$(run_case "$STUBBORN
+_frontend_bg_start
+$READY
+false")
+assert_contains "errexit exit code" "$out" "rc=1"
+check_aftermath "errexit"
+
+echo "== Ctrl-C to setup's whole process group =="
+prime
+python3 - "$WORK/outer/studio" "$HELPERS" "$STUBS" "$STUBBORN" <<'PY'
+import os, signal, subprocess, sys, time
+script_dir, helpers, stubs, stubborn = sys.argv[1:]
+body = f"{stubs}\n. '{helpers}'\n{stubborn}\n_frontend_bg_start\nsleep 300\n"
+p = subprocess.Popen(["bash", "-c", body], env=dict(os.environ, SCRIPT_DIR=script_dir, STAGE_ROOT=""),
+ start_new_session=True, stdin=subprocess.DEVNULL)
+time.sleep(1.5)
+os.killpg(p.pid, signal.SIGINT)
+p.wait()
+PY
+check_aftermath "Ctrl-C"
+
+echo "== a build that exits first leaves nothing running after the join =="
+out=$(run_case "
+_build_frontend() {
+ python3 -c 'import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(300)' &
+ echo \$! > '$WORK/grandchild'
+}
+_frontend_bg_start
+sleep 1
+_frontend_bg_join
+sleep 0.5
+if kill -0 \$(cat '$WORK/grandchild') 2>/dev/null; then echo child-alive; else echo child-gone; fi")
+assert_contains "the join itself killed the build's leftover child" "$out" "child-gone"
+gc=$(grandchild); [ -z "$gc" ] || kill -KILL "$gc" 2>/dev/null
+
+echo "== nothing is signalled once the build is joined =="
+python3 -c 'import subprocess as s; print(s.Popen(["sleep", "60"], start_new_session=True, stdout=s.DEVNULL, stderr=s.DEVNULL).pid)' > "$WORK/other"
+other=$(cat "$WORK/other")
+out=$(run_case "
+_build_frontend() { :; }
+_frontend_bg_start
+_frontend_bg_join
+# Pretend the old id now names another group; a later failure must leave it alone.
+_FRONTEND_BG_LOG=/nonexistent
+setup_fail 4 later")
+assert_contains "setup_fail exit" "$out" "rc=4"
+if kill -0 "$other" 2>/dev/null; then ok "unrelated process group left alone"; kill "$other"; else bad "unrelated process group $other was killed"; fi
+
+echo "== a new build waits for one still being stopped, then takes over =="
+prime
+( sleep 3 ) & owner=$!
+ps -o pid= -o lstart= -p "$owner" | sed 's/^ *//' > "$MARK"
+mv "$WORK/outer/.gitignore" "$WORK/outer/.gitignore._twbuild"
+start=$(date +%s)
+out=$(run_case '_frontend_build_begin; echo "self=$$"')
+waited=$(( $(date +%s) - start ))
+if [ "$waited" -ge 2 ]; then ok "waited for the live owner (${waited}s)"; else bad "did not wait for the live owner (${waited}s)"; fi
+assert_eq "hidden .gitignore put back before the new build" "*" "$(cat "$WORK/outer/.gitignore" 2>/dev/null)"
+assert_eq "marker now names the new build" "$(printf '%s\n' "$out" | sed -n 's/^self=//p')" "$(cut -d' ' -f1 "$MARK")"
+wait "$owner" 2>/dev/null
+start=$(date +%s)
+run_case '_frontend_build_begin' >/dev/null
+if [ $(( $(date +%s) - start )) -le 5 ]; then ok "a dead owner is not waited for"; else bad "waited for a dead owner"; fi
+echo "== another live setup building this checkout is never overtaken =="
+prime
+( sleep 16 ) & owner=$!
+ps -o pid= -o lstart= -p "$owner" | sed 's/^ *//' > "$MARK"
+start=$(date +%s)
+# 0.1 s sleeps: a 30-poll cap gives up after 3-9 s (ps is slow on a busy host), before the owner ends.
+out=$(run_case 'sleep() { command sleep 0.1; }; _frontend_build_begin')
+waited=$(( $(date +%s) - start ))
+if [ "$waited" -ge 15 ]; then ok "waited for the live owner to finish (${waited}s)"; else bad "overtook a live owner (${waited}s)"; fi
+assert_contains "says why it is waiting" "$out" "waiting for another frontend build in this checkout"
+wait "$owner" 2>/dev/null
+
+echo "== an owner that finished its build but is still running is not waited for =="
+( sleep 20 ) & owner=$!
+ps -o pid= -o lstart= -p "$owner" | sed 's/^ *//' > "$MARK"
+( sleep 2; rm -f "$MARK" ) &
+start=$(date +%s)
+run_case '_frontend_build_begin' >/dev/null
+waited=$(( $(date +%s) - start ))
+if [ "$waited" -le 10 ]; then ok "stopped waiting once the owner cleared its mark (${waited}s)"; else bad "kept waiting after the mark was cleared (${waited}s)"; fi
+kill "$owner" 2>/dev/null; wait "$owner" 2>/dev/null
+rm -f "$MARK"
+
+echo "== a background build still alive after the wait is stopped, not shared =="
+python3 -c 'import subprocess as s; print(s.Popen(["sleep", "120"], start_new_session=True, stdout=s.DEVNULL, stderr=s.DEVNULL).pid)' > "$WORK/hung"
+hung=$(cat "$WORK/hung")
+ps -o pid= -o lstart= -p "$hung" | sed 's/^ *//' > "$MARK"
+run_case '_FRONTEND_OWNER_POLLS=3; _frontend_build_begin' >/dev/null
+if wait_gone "$hung" 10; then ok "hung build group stopped"; else bad "hung build $hung left running"; kill -KILL "$hung" 2>/dev/null; fi
+rm -f "$MARK"
+
+echo "== a zombie owner nobody reaps is not waited for =="
+python3 -c 'import os, sys, time
+pid = os.fork()
+if pid == 0:
+ os._exit(0)
+print(pid, flush=True)
+sys.stdout.close()
+time.sleep(30)' > "$WORK/zombie" &
+zparent=$!
+i=0; while [ ! -s "$WORK/zombie" ] && [ $i -lt 50 ]; do sleep 0.1; i=$((i + 1)); done
+zpid=$(cat "$WORK/zombie")
+sleep 0.5
+ps -o pid= -o lstart= -p "$zpid" | sed 's/^ *//' > "$MARK"
+start=$(date +%s)
+run_case '_frontend_build_begin' >/dev/null
+waited=$(( $(date +%s) - start ))
+if [ -s "$WORK/zombie" ] && [ "$waited" -le 5 ]; then ok "zombie owner skipped (${waited}s)"; else bad "waited ${waited}s for zombie $zpid"; fi
+kill "$zparent" 2>/dev/null; wait "$zparent" 2>/dev/null
+rm -f "$MARK"
+
+echo "== a new build also waits for a child its stopped owner left in the group =="
+prime
+python3 -c 'import os, subprocess as s
+p = s.Popen(["bash", "-c", "sleep 3 & exit 0"], start_new_session=True)
+p.wait(); print(p.pid)' > "$WORK/leader"
+leader=$(cat "$WORK/leader")
+printf '%s gone\n' "$leader" > "$MARK"
+start=$(date +%s)
+run_case '_frontend_build_begin' >/dev/null
+waited=$(( $(date +%s) - start ))
+if [ "$waited" -ge 2 ]; then ok "waited for the group's leftover child (${waited}s)"; else bad "did not wait for the group's leftover child (${waited}s)"; fi
+rm -f "$MARK"
+
+echo "== a background job keeps the mark until its OXC install is done =="
+CLEAR_MARK=$(grep -F 'rm -f "$_FRONTEND_BUILD_MARK"' "$SETUP_SH" | grep -F '_FRONTEND_IN_JOB' | sed 's/^ *//')
+[ -n "$CLEAR_MARK" ] || bad "setup.sh no longer keeps the mark for the background job"
+rm -f "$MARK"
+out=$(run_case "
+_build_frontend() { _frontend_build_begin; $CLEAR_MARK; }
+_install_oxc_runtime() { if [ -e '$MARK' ]; then echo mark-during-oxc; fi; }
+_frontend_bg_start
+_frontend_bg_join
+if [ -e '$MARK' ]; then echo mark-left; else echo mark-cleared; fi")
+assert_contains "mark still set while OXC installs" "$out" "mark-during-oxc"
+assert_contains "mark cleared once the job finished" "$out" "mark-cleared"
+out=$(run_case "
+_build_frontend() { _frontend_build_begin; $CLEAR_MARK; }
+_build_frontend
+if [ -e '$MARK' ]; then echo mark-left; else echo mark-cleared; fi")
+assert_contains "serial build still clears the mark itself" "$out" "mark-cleared"
+
+echo "== background build cleans agent guide files out of node_modules =="
+touch "$FE/node_modules/pkg/AGENTS.md"
+out=$(run_case '
+_build_frontend() { :; }
+_frontend_bg_start
+_frontend_bg_join')
+if [ -e "$FE/node_modules/pkg/AGENTS.md" ]; then bad "AGENTS.md left in node_modules"; else ok "AGENTS.md removed"; fi
+
+echo "== cleanup never replaces a .gitignore that exists =="
+printf 'mine\n' > "$WORK/outer/.gitignore"
+printf '*\n' > "$WORK/outer/.gitignore._twbuild"
+run_case '_frontend_build_cleanup' >/dev/null
+assert_eq "existing .gitignore kept" "mine" "$(cat "$WORK/outer/.gitignore")"
+rm -f "$WORK/outer/.gitignore._twbuild"
+
+echo "== gate =="
+gate() {
+ SCRIPT_DIR="$WORK/outer/studio" bash -c "$STUBS
+. '$HELPERS'
+nproc() { [ -n \"\${FAKE_CPUS-16}\" ] && echo \"\${FAKE_CPUS-16}\"; }
+sysctl() { return 1; }
+_usable_ram_mb() { printf '%s' \"\${FAKE_MB-65536}\"; }
+if _frontend_can_build_in_background; then echo yes; else echo no; fi" 2>/dev/null
+}
+assert_eq "16 CPUs, 64 GiB usable overlaps" "yes" "$(STAGE_ROOT= gate)"
+assert_eq "4 CPUs, 12 GiB usable overlaps" "yes" "$(FAKE_CPUS=4 FAKE_MB=12288 STAGE_ROOT= gate)"
+assert_eq "2 CPUs stays serial" "no" "$(FAKE_CPUS=2 STAGE_ROOT= gate)"
+assert_eq "unreadable CPU count stays serial" "no" "$(FAKE_CPUS= STAGE_ROOT= gate)"
+assert_eq "8 GiB usable (cgroup or free) stays serial" "no" "$(FAKE_MB=8192 STAGE_ROOT= gate)"
+assert_eq "unreadable memory stays serial" "no" "$(FAKE_MB= STAGE_ROOT= gate)"
+assert_eq "opt-out stays serial" "no" "$(UNSLOTH_STUDIO_SERIAL_SETUP=1 STAGE_ROOT= gate)"
+assert_eq "opt-out (true) stays serial" "no" "$(UNSLOTH_STUDIO_SERIAL_SETUP=true STAGE_ROOT= gate)"
+assert_eq "verbose stays serial" "no" "$(UNSLOTH_VERBOSE=1 STAGE_ROOT= gate)"
+assert_eq "Desktop install stays serial" "no" "$(UNSLOTH_TAURI_MODE=1 STAGE_ROOT= gate)"
+assert_eq "Desktop update stays serial" "no" "$(UNSLOTH_TAURI_UPDATE=true STAGE_ROOT= gate)"
+assert_eq "staged update stays serial" "no" "$(STAGE_ROOT=/tmp/stage gate)"
+[ ! -r /proc/meminfo ] || assert_eq "MemAvailable missing stays serial" "no" "$(SCRIPT_DIR="$WORK/outer/studio" STAGE_ROOT= bash -c "$STUBS
+. '$HELPERS'
+nproc() { echo 16; }
+_usable_ram_mb() { printf 65536; }
+grep() { return 1; }
+if _frontend_can_build_in_background; then echo yes; else echo no; fi" 2>/dev/null)"
+assert_eq "no usable ps stays serial" "no" "$(SCRIPT_DIR="$WORK/outer/studio" STAGE_ROOT= bash -c "$STUBS
+. '$HELPERS'
+nproc() { echo 16; }
+_usable_ram_mb() { printf 65536; }
+ps() { return 1; }
+if _frontend_can_build_in_background; then echo yes; else echo no; fi" 2>/dev/null)"
+
+summary
diff --git a/tests/sh/test_setup_rerun_after_replace.sh b/tests/sh/test_setup_rerun_after_replace.sh
index bfb20f5b0a4..04c902e1629 100755
--- a/tests/sh/test_setup_rerun_after_replace.sh
+++ b/tests/sh/test_setup_rerun_after_replace.sh
@@ -58,6 +58,7 @@ make_variant() {
echo 'step() { printf "STEP %s: %s\n" "$1" "$2"; }'
echo 'substep() { printf "SUB %s\n" "$1"; }'
echo 'C_WARN='
+ echo '_frontend_bg_join() { :; }'
cat "$WORK/func_blk.sh"
cat <<EOF
echo "START $_v pid=\$\$ pwd=\$PWD guard=\${UNSLOTH_SETUP_RERUN:-}"
diff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.py
index 1e9b576b7a0..69b2f46eea1 100644
--- a/tests/studio/install/test_install_llama_prebuilt_logic.py
+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py
@@ -3324,10 +3324,20 @@ def test_setup_scripts_prune_agent_files_without_shipping_a_repo_copy():
setup_sh = (PACKAGE_ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8")
setup_ps1 = (PACKAGE_ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
+ # A background frontend build installs the OXC runtime and prunes both trees itself.
assert (
- "_remove_agent_instruction_files \\\n"
- ' "$SCRIPT_DIR/frontend/node_modules" \\\n'
- ' "$_OXC_DIR/node_modules"'
+ 'if [ -z "$_FRONTEND_BG_PID" ]; then\n'
+ " _install_oxc_runtime\n"
+ ' _remove_agent_instruction_files "$SCRIPT_DIR/frontend/node_modules"\n'
+ ' _remove_agent_instruction_files "$_OXC_DIR/node_modules"\n'
+ "fi\n"
+ ) in setup_sh
+ assert (
+ " _build_frontend\n"
+ " _install_oxc_runtime\n"
+ ' rm -f "$_FRONTEND_BUILD_MARK"\n'
+ ' _remove_agent_instruction_files "$SCRIPT_DIR/frontend/node_modules"\n'
+ ' _remove_agent_instruction_files "$_OXC_DIR/node_modules"'
) in setup_sh
assert '_remove_agent_instruction_files "$SCRIPT_DIR/frontend" "$_OXC_DIR"' not in setup_sh
assert '_remove_agent_instruction_files "$LLAMA_CPP_DIR"' in setup_sh
diff --git a/tests/studio/test_setup_frontend_overlap.ps1 b/tests/studio/test_setup_frontend_overlap.ps1
new file mode 100644
index 00000000000..015cd59d72c
--- /dev/null
+++ b/tests/studio/test_setup_frontend_overlap.ps1
@@ -0,0 +1,197 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+#
+# setup.ps1 runs `npm run build` in the background on a source install (#8818). These run the
+# real helpers (and the real Exit-SetupFailure) in child shells against a stand-in build: the
+# join reports the build's exit code and output, a failure elsewhere kills the build's process
+# tree and puts back what it hid while keeping the build mark, and the gate keeps Desktop,
+# staged updates, verbose, opted-out and small machines serial.
+$ErrorActionPreference = "Stop"
+$script:failures = 0
+function Check($name, $cond) {
+ if ($cond) { Write-Host " PASS $name" }
+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }
+}
+
+$repoRoot = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path
+$setupPath = [System.IO.Path]::Combine($repoRoot, "studio", "setup.ps1")
+. ([System.IO.Path]::Combine($repoRoot, "tests", "studio_setup_ps1", "Get-FunctionSource.ps1"))
+
+$work = Join-Path ([System.IO.Path]::GetTempPath()) ("fe-overlap-" + [guid]::NewGuid().ToString("N"))
+$fe = Join-Path $work "outer/studio/frontend"
+New-Item -ItemType Directory -Force -Path (Join-Path $fe "dist/assets") | Out-Null
+$helpers = Join-Path $work "helpers.ps1"
+$src = @()
+foreach ($fn in @("New-UnslothTemporaryFile", "Exit-SetupFailure", "Test-FrontendBuildInBackground",
+ "Start-FrontendBuildBackground", "Restore-FrontendBuildGitignores",
+ "Remove-FrontendBuildFiles", "Stop-FrontendBuildBackground",
+ "Complete-FrontendBuildOutput", "Complete-FrontendBuildBackground", "Wait-FrontendBuildOwner")) {
+ $body = Get-FunctionSource -Path $setupPath -Name $fn
+ Check "setup.ps1 defines $fn" ($null -ne $body)
+ $src += $body
+}
+$prelude = @'
+$ErrorActionPreference = "Stop"
+$script:UnslothVerbose = $false
+$script:FrontendBuildProc = $null
+$script:FrontendBuildFiles = @()
+$script:FrontendBuildHidden = @()
+function step($a, $b, $c) { Write-Output "step $a $b" }
+function substep($a, $b) { Write-Output "substep $a" }
+function Write-StudioLine($t) { Write-Output "line $t" }
+function Redact-InstallOutput($t) { $t }
+function Get-UsableMemoryMb { if ($env:FAKE_MB -eq "throw") { throw "no probe" }; [long]$env:FAKE_MB }
+'@
+Set-Content -LiteralPath $helpers -Value ($prelude + "`n" + ($src -join "`n")) -Encoding utf8
+# A script-scope trap would turn errors the script tolerates under ErrorActionPreference
+# Continue into fatal ones; a rerun recovers a build left running instead (Wait-FrontendBuildOwner).
+$setupAst = [System.Management.Automation.Language.Parser]::ParseFile($setupPath, [ref]$null, [ref]$null)
+Check "setup.ps1 has no script-scope trap" (-not $setupAst.EndBlock.Traps)
+$pwshExe = (Get-Process -Id $PID).Path
+$mark = Join-Path $fe ".unsloth-build.local"
+
+function Invoke-Case([string]$Body) {
+ $script = Join-Path $work ("case-" + [guid]::NewGuid().ToString("N") + ".ps1")
+ $head = ". '$helpers'`n`$DistDir = '$fe/dist'`n`$FrontendBuildMark = '$mark'`n`$Build = '$pwshExe'`n"
+ Set-Content -LiteralPath $script -Value ($head + $Body) -Encoding utf8
+ $out = & $pwshExe -NoProfile -File $script 2>&1 | Out-String
+ return @{ Out = $out; Code = $LASTEXITCODE }
+}
+function Reset-Tree {
+ Set-Content -LiteralPath (Join-Path $work "outer/.gitignore._twbuild") -Value "*"
+ Remove-Item -LiteralPath (Join-Path $work "outer/.gitignore") -Force -ErrorAction SilentlyContinue
+ Set-Content -LiteralPath $mark -Value "1"
+ Remove-Item -LiteralPath (Join-Path $fe "dist/assets/app.css") -Force -ErrorAction SilentlyContinue
+}
+$hidden = "@('" + (Join-Path $work "outer/.gitignore") + "')"
+
+Write-Host "== a successful background build is joined like the serial one =="
+Reset-Tree
+$r = Invoke-Case @"
+`$ok = Start-FrontendBuildBackground -WorkingDirectory '$fe' -HiddenGitignores $hidden -FilePath `$Build -ArgumentList @('-NoProfile', '-Command', "Start-Sleep 1; Set-Content -LiteralPath '$fe/dist/assets/app.css' -Value ('x' * 200000)")
+Write-Output "started=`$ok"
+Write-Output "parent-step"
+Complete-FrontendBuildBackground
+Write-Output "after-join"
+"@
+Check "build started in the background" ($r.Out -match "started=True")
+Check "join prints the built line" ($r.Out -match "step frontend built")
+Check "join returns and setup continues" ($r.Out -match "after-join" -and $r.Code -eq 0)
+Check "hidden .gitignore restored" (Test-Path -LiteralPath (Join-Path $work "outer/.gitignore"))
+Check "build mark cleared after success" (-not (Test-Path -LiteralPath $mark))
+
+Write-Host "== a failed background build fails setup like the serial one =="
+Reset-Tree
+$r = Invoke-Case @"
+`$null = Start-FrontendBuildBackground -WorkingDirectory '$fe' -HiddenGitignores $hidden -FilePath `$Build -ArgumentList @('-NoProfile', '-Command', "Write-Output 'tsc says boom'; exit 7")
+Complete-FrontendBuildBackground
+Write-Output "not-reached"
+"@
+Check "setup exits 1, as the serial path does" ($r.Code -eq 1)
+Check "the build output is shown" ($r.Out -match "tsc says boom")
+Check "the error names the build exit code" ($r.Out -match "npm run build failed \(exit code 7\)")
+Check "setup stops" ($r.Out -notmatch "not-reached")
+Check "hidden .gitignore restored" (Test-Path -LiteralPath (Join-Path $work "outer/.gitignore"))
+Check "build mark kept, so the next run rebuilds" (Test-Path -LiteralPath $mark)
+
+Write-Host "== -IfDone leaves a running build alone and joins a finished one =="
+Reset-Tree
+$r = Invoke-Case @"
+`$null = Start-FrontendBuildBackground -WorkingDirectory '$fe' -FilePath `$Build -ArgumentList @('-NoProfile', '-Command', "Start-Sleep 2; Set-Content -LiteralPath '$fe/dist/assets/app.css' -Value ('x' * 200000)")
+Complete-FrontendBuildBackground -IfDone
+Write-Output "running-after-first=`$([bool]`$script:FrontendBuildProc)"
+Start-Sleep 4
+Complete-FrontendBuildBackground -IfDone
+Write-Output "running-after-second=`$([bool]`$script:FrontendBuildProc)"
+"@
+Check "running build is left alone" ($r.Out -match "running-after-first=True")
+Check "finished build is joined" ($r.Out -match "running-after-second=False" -and $r.Out -match "step frontend built")
+
+Write-Host "== a failure elsewhere kills the whole build tree before setup exits =="
+Reset-Tree
+$pidFile = Join-Path $work "grandchild.pid"
+Remove-Item -LiteralPath $pidFile -Force -ErrorAction SilentlyContinue
+$sleeper = if ($IsWindows) { "Start-Process -PassThru -NoNewWindow -FilePath ''$pwshExe'' -ArgumentList ''-NoProfile'',''-Command'',''Start-Sleep 300''" } else { "Start-Process -PassThru -FilePath ''sleep'' -ArgumentList ''300''" }
+$r = Invoke-Case @"
+`$null = Start-FrontendBuildBackground -WorkingDirectory '$fe' -HiddenGitignores $hidden -FilePath `$Build -ArgumentList @('-NoProfile', '-Command', '`$p = $sleeper; Set-Content -LiteralPath ''$pidFile'' -Value `$p.Id; Start-Sleep 300')
+Start-Sleep 3
+Exit-SetupFailure "python deps failed" -Code 3
+"@
+Check "setup exits with its own code" ($r.Code -eq 3)
+$gc = if (Test-Path -LiteralPath $pidFile) { [int](Get-Content -LiteralPath $pidFile) } else { 0 }
+$alive = $false
+if ($gc) { $alive = $null -ne (Get-Process -Id $gc -ErrorAction SilentlyContinue | Where-Object { -not $_.HasExited }) }
+Check "the build's child process is gone" ($gc -ne 0 -and -not $alive)
+if ($alive) { Stop-Process -Id $gc -Force -ErrorAction SilentlyContinue }
+Check "hidden .gitignore restored" (Test-Path -LiteralPath (Join-Path $work "outer/.gitignore"))
+Check "build mark kept, so the next run rebuilds" (Test-Path -LiteralPath $mark)
+
+Write-Host "== a build that cannot start leaves no temp files and stays serial =="
+$before = @(Get-ChildItem -LiteralPath ([System.IO.Path]::GetTempPath()) -Filter "tmp*.tmp" -ErrorAction SilentlyContinue).Count
+$r = Invoke-Case "Write-Output (`"started=`" + (Start-FrontendBuildBackground -WorkingDirectory '$fe' -FilePath '$work/no-such-exe'))"
+$after = @(Get-ChildItem -LiteralPath ([System.IO.Path]::GetTempPath()) -Filter "tmp*.tmp" -ErrorAction SilentlyContinue).Count
+Check "start reports failure" ($r.Out -match "started=False")
+Check "no temp files left" ($after -le $before)
+
+if (-not (Get-Command npm.cmd, npm.exe, npm.bat -CommandType Application -ErrorAction SilentlyContinue)) {
+ Write-Host "== no npm launcher cmd.exe can run: stay serial =="
+ $r = Invoke-Case "`$env:ComSpec = '$pwshExe'; Write-Output (`"started=`" + (Start-FrontendBuildBackground -WorkingDirectory '$fe'))"
+ Check "an npm.ps1-only host builds serially" ($r.Out -match "started=False")
+}
+
+Write-Host "== a rerun waits for a build its killed setup left running =="
+$r = Invoke-Case @"
+`$null = Start-FrontendBuildBackground -WorkingDirectory '$fe' -FilePath `$Build -ArgumentList @('-NoProfile', '-Command', 'Start-Sleep 4')
+Write-Output "owner=`$(`$script:FrontendBuildProc.Id)"
+"@
+$ownerId = ([regex]::Match($r.Out, "owner=(\d+)")).Groups[1].Value
+Check "the marker names the build process" ((Get-Content -LiteralPath $mark -Raw).Trim() -like "$ownerId *")
+$sw = [Diagnostics.Stopwatch]::StartNew()
+$r = Invoke-Case "Wait-FrontendBuildOwner"
+Check "waited for the orphaned build" ($sw.Elapsed.TotalSeconds -ge 2)
+Check "says why it waits" ($r.Out -match "waiting for an earlier frontend build")
+$sw.Restart()
+$null = Invoke-Case "Wait-FrontendBuildOwner"
+Check "a finished build is not waited for" ($sw.Elapsed.TotalSeconds -lt 2)
+Set-Content -LiteralPath $mark -Value "$PID 123"
+$sw.Restart()
+$null = Invoke-Case "Wait-FrontendBuildOwner"
+Check "a reused process id is not waited for" ($sw.Elapsed.TotalSeconds -lt 2)
+
+Write-Host "== a build still alive after the wait is stopped, not shared =="
+$r = Invoke-Case @"
+`$null = Start-FrontendBuildBackground -WorkingDirectory '$fe' -FilePath `$Build -ArgumentList @('-NoProfile', '-Command', 'Start-Sleep 120')
+Write-Output "owner=`$(`$script:FrontendBuildProc.Id)"
+"@
+$hungId = [int]([regex]::Match($r.Out, "owner=(\d+)")).Groups[1].Value
+$sw.Restart()
+$null = Invoke-Case "Wait-FrontendBuildOwner -TimeoutSeconds 2"
+$hungAlive = $null -ne (Get-Process -Id $hungId -ErrorAction SilentlyContinue | Where-Object { -not $_.HasExited })
+Check "hung build stopped after the timeout" ($hungId -gt 0 -and -not $hungAlive -and $sw.Elapsed.TotalSeconds -lt 30)
+if ($hungAlive) { Stop-Process -Id $hungId -Force -ErrorAction SilentlyContinue }
+
+Write-Host "== gate =="
+function Gate([hashtable]$Env, [string]$Extra = "") {
+ $saved = @{}
+ foreach ($k in $Env.Keys) { $saved[$k] = [Environment]::GetEnvironmentVariable($k); [Environment]::SetEnvironmentVariable($k, $Env[$k]) }
+ try { $r = Invoke-Case ($Extra + "`nif (Test-FrontendBuildInBackground) { 'gate=yes' } else { 'gate=no' }") }
+ finally { foreach ($k in $saved.Keys) { [Environment]::SetEnvironmentVariable($k, $saved[$k]) } }
+ if ($r.Out -match "gate=yes") { return "yes" } else { return "no" }
+}
+$base = @{ FAKE_MB = "65536"; UNSLOTH_STUDIO_SERIAL_SETUP = $null; UNSLOTH_TAURI_MODE = $null; UNSLOTH_TAURI_UPDATE = $null }
+$big = [Environment]::ProcessorCount -ge 4
+if ($big) { Check "4+ CPUs, 64 GiB usable overlaps" ((Gate $base) -eq "yes") }
+if ($big) { Check "12 GiB usable overlaps" ((Gate ($base + @{}) ) -eq "yes" -and (Gate (@{ FAKE_MB = "12288" })) -eq "yes") }
+Check "8 GiB usable stays serial" ((Gate @{ FAKE_MB = "8192" }) -eq "no")
+Check "a failing memory probe stays serial" ((Gate @{ FAKE_MB = "throw" }) -eq "no")
+Check "an unknown memory reading (-1) stays serial" ((Gate @{ FAKE_MB = "-1" }) -eq "no")
+Check "opt-out stays serial" ((Gate @{ FAKE_MB = "65536"; UNSLOTH_STUDIO_SERIAL_SETUP = "1" }) -eq "no")
+Check "opt-out (true) stays serial" ((Gate @{ FAKE_MB = "65536"; UNSLOTH_STUDIO_SERIAL_SETUP = "true" }) -eq "no")
+Check "Desktop install stays serial" ((Gate @{ FAKE_MB = "65536"; UNSLOTH_TAURI_MODE = "1" }) -eq "no")
+Check "Desktop update stays serial" ((Gate @{ FAKE_MB = "65536"; UNSLOTH_TAURI_UPDATE = "true" }) -eq "no")
+Check "verbose stays serial" ((Gate @{ FAKE_MB = "65536" } '$script:UnslothVerbose = $true') -eq "no")
+Check "staged update stays serial" ((Gate @{ FAKE_MB = "65536" } '$StageRoot = "C:\stage"') -eq "no")
+
+Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue
+if ($script:failures -gt 0) { Write-Host "$($script:failures) check(s) failed" -ForegroundColor Red; exit 1 }
+Write-Host "All checks passed"
diff --git a/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1 b/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1
index 3a431fa3b10..dd60f2798f5 100644
--- a/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1
+++ b/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1
@@ -84,8 +84,10 @@ BeforeAll {
if ($script:RerunBlock -notmatch 'step "setup" "([^"]+)"') { throw "drift: the rerun block lost its handoff step." }
$script:Handoff = $Matches[1]
+ # Complete-FrontendBuildBackground returns at once here: no background build was started.
$functions = foreach ($name in @('Write-StudioLine', 'Remove-WoaMergedOverrides', 'Exit-SetupFailure',
- 'Test-SetupScriptReplaced', 'Restore-SetupStartEnvironment')) {
+ 'Test-SetupScriptReplaced', 'Restore-SetupStartEnvironment',
+ 'Complete-FrontendBuildBackground')) {
$src = Get-FunctionSource -Path $script:SetupPs1 -Name $name
if (-not $src) { throw "drift: $name is gone from setup.ps1." }
$src