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.

9.3 KB
Raw Blame
#!/usr/bin/env pwsh
# Unit test for setup.ps1's Get-NodeDecision (system | bundled | skip), AST-extracted;
# also a setup.ps1 parse gate.
# Run: pwsh -NoProfile -File tests/studio/test_node_decision.ps1

$ErrorActionPreference = "Stop"
$setupPath = [System.IO.Path]::Combine($PSScriptRoot, "..", "..", "studio", "setup.ps1")
$setupPath = (Resolve-Path $setupPath).Path
$source = Get-Content -Raw -Path $setupPath

$tokens = $null; $errors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile($setupPath, [ref]$tokens, [ref]$errors)
if ($errors) { $errors | ForEach-Object { $_.ToString() }; throw "setup.ps1 has parse errors" }

$fn = $ast.FindAll({ param($n)
    $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq "Get-NodeDecision"
}, $true)
if ($fn.Count -ne 1) { throw "expected exactly one Get-NodeDecision in setup.ps1, found $($fn.Count)" }
Invoke-Expression $fn[0].Extent.Text


$packagedFn = $ast.FindAll({ param($n)
    $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq "Test-PackagedFrontend"
}, $true)
if ($packagedFn.Count -ne 1) { throw "expected exactly one Test-PackagedFrontend in setup.ps1, found $($packagedFn.Count)" }
Invoke-Expression $packagedFn[0].Extent.Text

$failures = 0
function Check($name, $cond) {
    if ($cond) { Write-Host "  PASS  $name" }
    else { Write-Host "  FAIL  $name" -ForegroundColor Red; $script:failures++ }
}

function D($node, $npm, $skip) { Get-NodeDecision -NodeVersion $node -NpmVersion $npm -SkipInstall $skip }


$packagedRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-packaged-frontend-" + [guid]::NewGuid())
$packagedIndex = Join-Path $packagedRoot "frontend\dist\index.html"
# Only a source checkout has this pyproject.toml.
$packagedProject = Join-Path $packagedRoot "pyproject.toml"
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $packagedIndex) | Out-Null
Set-Content -Path $packagedIndex -Value "<!doctype html>" -Encoding Ascii
try {
    Check "PyPI install uses packaged frontend" (Test-PackagedFrontend -LocalInstall "0" -IndexPath $packagedIndex -ProjectFilePath $packagedProject)
    Check "local install rebuilds frontend" (-not (Test-PackagedFrontend -LocalInstall "1" -IndexPath $packagedIndex -ProjectFilePath $packagedProject))
    Check "unset install mode rebuilds frontend" (-not (Test-PackagedFrontend -LocalInstall "" -IndexPath $packagedIndex -ProjectFilePath $packagedProject))

    # Editable overlay: PyPI mode over a checkout, whose dist is a stale build artifact.
    Set-Content -Path $packagedProject -Value "[project]" -Encoding Ascii
    Check "source checkout in PyPI mode rebuilds frontend" (-not (Test-PackagedFrontend -LocalInstall "0" -IndexPath $packagedIndex -ProjectFilePath $packagedProject))
    Remove-Item -LiteralPath $packagedProject -Force
    Check "packaged layout skips once no source marker remains" (Test-PackagedFrontend -LocalInstall "0" -IndexPath $packagedIndex -ProjectFilePath $packagedProject)

    Remove-Item -LiteralPath $packagedIndex -Force
    Check "missing packaged index rebuilds frontend" (-not (Test-PackagedFrontend -LocalInstall "0" -IndexPath $packagedIndex -ProjectFilePath $packagedProject))
} finally {
    Remove-Item -LiteralPath $packagedRoot -Recurse -Force -ErrorAction SilentlyContinue
}

Write-Host "Get-NodeDecision"
Check "node22 + npm11 -> system"      ((D "v22.17.1" "11.13.0" "0") -eq "system")
Check "node20.19 + npm11 -> system"   ((D "v20.19.0" "11.0.0"  "0") -eq "system")
Check "node24 + npm11 -> system"      ((D "v24.17.0" "11.13.0" "0") -eq "system")
Check "node23 + npm11 -> system"      ((D "v23.5.0"  "11.0.0"  "0") -eq "system")
Check "node22 + npm10 -> bundled"     ((D "v22.17.1" "10.9.2"  "0") -eq "bundled")
Check "node18 -> bundled"             ((D "v18.20.0" "11.0.0"  "0") -eq "bundled")
Check "node22.11 -> bundled"          ((D "v22.11.0" "11.0.0"  "0") -eq "bundled")
Check "node20.18 -> bundled"          ((D "v20.18.0" "11.0.0"  "0") -eq "bundled")
Check "node21 (odd) -> bundled"       ((D "v21.7.0"  "11.0.0"  "0") -eq "bundled")
Check "missing -> bundled"            ((D "" "" "0") -eq "bundled")
Check "npm10 + skip -> skip"          ((D "v22.17.1" "10.9.2"  "1") -eq "skip")
Check "missing + skip -> skip"        ((D "" "" "1") -eq "skip")
Check "good + skip -> system"         ((D "v22.17.1" "11.13.0" "1") -eq "system")
Check "managed on PATH -> bundled" ((Get-NodeDecision -NodeVersion 'v24.18.0' -NpmVersion '11.0.0' -ManagedOnPath $true) -eq 'bundled')
Check "managed + skip -> read-only" ((Get-NodeDecision -NodeVersion 'v24.18.0' -NpmVersion '11.0.0' -ManagedOnPath $true -SkipInstall '1') -eq 'system')
Check "broken managed + skip -> skip" ((Get-NodeDecision -NodeVersion '' -NpmVersion '' -ManagedOnPath $true -SkipInstall '1') -eq 'skip')

foreach ($name in @('Test-ManagedNodeOnPath', 'Get-PathState', 'Test-AccessDeniedError')) {
    $helper = @($ast.FindAll({ param($n)
        $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $name
    }, $true))
    if ($helper.Count -ne 1) { throw "expected one $name" }
    Invoke-Expression $helper[0].Extent.Text
}
$nodeTestRoot = Join-Path ([System.IO.Path]::GetTempPath()) ('unsloth-node-path-' + [guid]::NewGuid())
$managedDir = Join-Path $nodeTestRoot 'managed node'
$externalDir = Join-Path $nodeTestRoot 'external node'
$oldPath = $env:PATH
try {
    $windowsHost = $PSVersionTable.PSEdition -eq 'Desktop' -or $IsWindows
    $nodeName = if ($windowsHost) { 'node.exe' } else { 'node' }
    foreach ($dir in @($managedDir, $externalDir)) {
        New-Item -ItemType Directory -Path $dir -Force | Out-Null
        $exe = Join-Path $dir $nodeName
        [System.IO.File]::WriteAllText($exe, '')
        if (-not $windowsHost) { & chmod +x $exe }
    }
    $env:PATH = $managedDir
    # A user's own Node linked into the managed location carries no installer metadata.
    Check 'unmarked Node, even in the install dir, is not managed' (-not (Test-ManagedNodeOnPath))
    [System.IO.File]::WriteAllText((Join-Path $managedDir 'UNSLOTH_NODE_PREBUILT_INFO.json'), '{}')
    Check 'marked managed command on PATH is recognized' (Test-ManagedNodeOnPath)
    $env:PATH = $externalDir
    Check 'external command is not managed' (-not (Test-ManagedNodeOnPath))
    $env:PATH = $nodeTestRoot
    Check 'missing command is not managed' (-not (Test-ManagedNodeOnPath))
} finally {
    $env:PATH = $oldPath
    Remove-Item -LiteralPath $nodeTestRoot -Recurse -Force
}

$nodeSourceOffset = $source.IndexOf('$NodeSource = Get-NodeDecision')
$skipFrontendBranchOffset = $source.IndexOf('} elseif ($SkipFrontend) {')
$customHomeErrorOffset = $source.IndexOf('UNSLOTH_STUDIO_HOME/STUDIO_HOME=$NodeOverride does not exist')
$nodeParentMkdirOffset = $source.IndexOf('New-Item -ItemType Directory -Force -Path $NodeParent')
$npmPrefixOffset = $source.IndexOf('$env:NPM_CONFIG_PREFIX = $NodeDir')
$nodePathClearOffset = $source.IndexOf('Remove-Item Env:NODE_PATH')
$bundledBranchOffset = $source.IndexOf('} elseif ($NodeSource -eq "bundled") {')
$systemArmOffset = $source.IndexOf('$SysNodeVersion | npm $SysNpmVersion (system)')
$globalBunOffset = $source.IndexOf('npm install -g bun')
Check "NodeSource initialized before SKIP_STUDIO_FRONTEND branch" (
    $nodeSourceOffset -ge 0 -and $skipFrontendBranchOffset -ge 0 -and $nodeSourceOffset -lt $skipFrontendBranchOffset
)
Check "custom Unsloth home validated before Node parent creation" (
    $customHomeErrorOffset -ge 0 -and $nodeParentMkdirOffset -ge 0 -and $customHomeErrorOffset -lt $nodeParentMkdirOffset
)
Check "bundled Node pins npm prefix and clears NODE_PATH" (
    $npmPrefixOffset -ge 0 -and $nodePathClearOffset -ge 0 -and $npmPrefixOffset -lt $nodePathClearOffset
)
# Mirrors tests/sh/test_system_node_readonly.sh: reusing system Node mutates nothing.
Check "npm prefix pin lives in the bundled branch, not the system arm" (
    $bundledBranchOffset -ge 0 -and $systemArmOffset -ge 0 -and
    $bundledBranchOffset -lt $npmPrefixOffset -and $npmPrefixOffset -lt $systemArmOffset
)
Check "global bun install lives in the bundled branch, not the system arm" (
    $bundledBranchOffset -ge 0 -and $systemArmOffset -ge 0 -and
    $bundledBranchOffset -lt $globalBunOffset -and $globalBunOffset -lt $systemArmOffset
)

$bunGate = @($ast.FindAll({ param($n)
    $n -is [System.Management.Automation.Language.IfStatementAst] -and
    $n.Clauses[0].Item1.Extent.Text -match 'Get-Command bun' -and $n.Clauses[0].Item2.Extent.Text -match 'npm install -g bun'
}, $true))
if ($bunGate.Count -ne 1) { throw "expected one bun install gate, found $($bunGate.Count)" }
$bunCond = $bunGate[0].Clauses[0].Item1.Extent.Text
$FrontendDir = Join-Path ([System.IO.Path]::GetTempPath()) ('unsloth-bun-gate-' + [guid]::NewGuid())
New-Item -ItemType Directory -Path $FrontendDir | Out-Null
$oldPath = $env:PATH
try {
    $env:PATH = $FrontendDir
    $NeedFrontendBuild = $true
    Check 'bun fetched for a frontend build without a lockfile' ([bool](Invoke-Expression $bunCond))
    $NeedFrontendBuild = $false
    Check 'bun not fetched when Node serves only OXC (Desktop)' (-not (Invoke-Expression $bunCond))
} finally {
    $env:PATH = $oldPath
    Remove-Item -LiteralPath $FrontendDir -Recurse -Force
}

Write-Host ""
if ($failures -gt 0) { Write-Host "$failures check(s) FAILED" -ForegroundColor Red; exit 1 }
Write-Host "All checks passed" -ForegroundColor Green