Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: update managed Node to 24.22.1, apply new pins on every update path, and keep the pin current (#15423)
oobabooga4c37b87ca558
diff --git a/.github/workflows/node-pins-update.yml b/.github/workflows/node-pins-update.ymlnew file mode 100644index 00000000000..7bacb92c6d0--- /dev/null+++ b/.github/workflows/node-pins-update.yml@@ -0,0 +1,109 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+#+# Opens one PR on ci/node-pins when the pinned Node LTS line has a newer release (security+# releases included). A new LTS major stays a reviewed change (studio/NODE_RUNTIME.md).+# PRs opened with GITHUB_TOKEN start no CI: close and reopen.++name: Node pin update++on:+ schedule:+ - cron: '17 8 * * *' # 08:17 UTC daily, off the cron rush+ workflow_dispatch:++concurrency:+ group: ${{ github.workflow }}+ cancel-in-progress: false++permissions:+ contents: read++jobs:+ update-pins:+ name: pin the newest Node release of the pinned LTS line+ if: github.repository == 'unslothai/unsloth'+ runs-on: ubuntu-latest+ timeout-minutes: 15+ permissions:+ contents: write+ pull-requests: write+ env:+ BRANCH: ci/node-pins+ PINS: studio/node_prebuilt_pins.json+ steps:+ - name: Harden runner (egress block)+ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2+ with:+ egress-policy: block+ disable-sudo: true+ allowed-endpoints: >+ api.github.com:443+ github.com:443+ nodejs.org:443+ raw.githubusercontent.com:443++ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ # A manual run from another branch must not base the update PR on it.+ ref: ${{ github.event.repository.default_branch || 'main' }}+ persist-credentials: false++ - name: Move the pin to the newest release of its LTS line+ id: update+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: |+ # An unset shell is `bash -e` without pipefail: tee would hide the updater's exit code.+ set -euo pipefail+ python3 scripts/update_node_pins.py --write | tee "$RUNNER_TEMP/changes.txt"+ if git diff --quiet -- "$PINS"; then+ echo "changed=false" >> "$GITHUB_OUTPUT"+ else+ echo "changed=true" >> "$GITHUB_OUTPUT"+ fi++ - name: Open or refresh the pin update pull request+ if: steps.update.outputs.changed == 'true'+ env:+ GH_TOKEN: ${{ github.token }}+ REPO: ${{ github.repository }}+ BASE: ${{ github.event.repository.default_branch || 'main' }}+ run: |+ set -euo pipefail+ remote="https://x-access-token:${GH_TOKEN}@github.com/${REPO}.git"+ push=true+ if git fetch --quiet --depth 1 "$remote" "refs/heads/${BRANCH}" 2>/dev/null \+ && git diff --quiet FETCH_HEAD -- "$PINS"; then+ echo "${BRANCH} already pins these releases."+ push=false+ fi+ number="$(gh pr list --repo "$REPO" --head "$BRANCH" --state open --json number --jq '.[0].number // empty')"+ # Re-open the PR when an earlier run pushed but failed to create it.+ if [ "$push" = false ] && [ -n "$number" ]; then+ exit 0+ fi+ title="Studio: update managed Node ($(paste -sd ';' "$RUNNER_TEMP/changes.txt" | sed 's/;/, /g'))"+ {+ echo "The scheduled pin check found a newer release of the pinned Node LTS line:"+ echo+ sed 's/^/- /' "$RUNNER_TEMP/changes.txt"+ echo+ echo "SHASUMS256.txt was verified against the Node release keys, and all six archives were"+ echo "downloaded and hashed against it. Managed Node installs move to it on their next Studio update."+ echo+ echo "Before merging: read the release notes, then close and reopen this PR to run CI"+ echo "(the Node installer, Node selection and setup rerun tests)."+ } > "$RUNNER_TEMP/body.md"+ git config user.name "github-actions[bot]"+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"+ if [ "$push" = true ]; then+ git checkout -B "$BRANCH"+ git commit --quiet -m "$title" -- "$PINS"+ git push --force "$remote" "HEAD:refs/heads/${BRANCH}"+ fi+ if [ -n "$number" ]; then+ gh pr edit "$number" --repo "$REPO" --title "$title" --body-file "$RUNNER_TEMP/body.md"+ else+ gh pr create --repo "$REPO" --base "$BASE" --head "$BRANCH" --title "$title" --body-file "$RUNNER_TEMP/body.md"+ fidiff --git a/docker/unsloth_studio_update.sh b/docker/unsloth_studio_update.shindex bb180c6f99e..6cd63eb6a18 100755--- a/docker/unsloth_studio_update.sh+++ b/docker/unsloth_studio_update.sh@@ -496,6 +496,22 @@ if ! studio_tree_ok; thenlog "If a new dependency is missing, re-run with --with-deps."exit 1fi+# Move the image's managed Node (never a user's) to the new pin; failure keeps the old Node.+refresh_managed_node() {+ local node_dir="$STUDIO_HOME/node" installer out+ [ "${UNSLOTH_SKIP_NODE_INSTALL:-0}" = "1" ] && return 0+ [ -f "$node_dir/UNSLOTH_NODE_PREBUILT_INFO.json" ] || return 0+ installer="$( (cd / && "$PY" -c 'import os, studio; print(os.path.join(os.path.dirname(studio.__file__), "install_node_prebuilt.py"))') 2>/dev/null)" || return 0+ [ -f "$installer" ] || return 0+ # The installer exits 0 when it keeps a usable old Node after a failed download (as setup.sh reads it).+ if out="$( (cd / && "$PY" "$installer" --install-dir "$node_dir") 2>&1)" \+ && ! printf '%s\n' "$out" | grep -Fq "keeping existing isolated Node"; then+ log "managed Node matches the new pin"+ else+ log "WARNING: could not move the managed Node to the new pin; keeping the current one"+ fi+}+refresh_managed_node# The previous tree stays until the restarted service proves it can serve. The record# is unlinked first: a kill before that leaves a full recovery for the next run, after# it only scratch. Signals held off, so the exit trap cannot restore over the commit.diff --git a/scripts/update_node_pins.py b/scripts/update_node_pins.pynew file mode 100644index 00000000000..ef1869f70c4--- /dev/null+++ b/scripts/update_node_pins.py@@ -0,0 +1,184 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Move studio/node_prebuilt_pins.json to the newest Node LTS release of the pinned major.++Moving to a new LTS major stays a reviewed change (studio/NODE_RUNTIME.md); this only takes+patch and minor releases within the pinned line, security releases included.++SHASUMS256.txt must carry a valid detached signature (SHASUMS256.txt.sig) from a Node release key (github.com/nodejs/release-keys),+and every archive is downloaded and hashed against it before the pins change.++Exit codes: 0 = current (or updated with --write); 1 = --check found a newer release; 2 = error.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+import shutil+import subprocess+import sys+import tempfile+import urllib.request+from pathlib import Path+from typing import Callable, Optional++PINS_PATH = Path(__file__).resolve().parents[1] / "studio" / "node_prebuilt_pins.json"+_DIST = "https://nodejs.org/dist"+_KEYRING = "https://raw.githubusercontent.com/nodejs/release-keys/HEAD/gpg/pubring.kbx"+_TIMEOUT_S = 60+_CHUNK = 1 << 20+++def archive_names(version: str) -> list[str]:+ return [+ f"node-v{version}-linux-x64.tar.gz",+ f"node-v{version}-linux-arm64.tar.gz",+ f"node-v{version}-darwin-x64.tar.gz",+ f"node-v{version}-darwin-arm64.tar.gz",+ f"node-v{version}-win-x64.zip",+ f"node-v{version}-win-arm64.zip",+ ]+++def version_key(version: str) -> tuple[int, ...]:+ parts = version.lstrip("v").split(".")+ if len(parts) != 3 or not all(part.isdigit() for part in parts):+ raise ValueError(f"{version!r} is not a Node release version.")+ return tuple(int(part) for part in parts)+++def _get(url: str) -> bytes:+ request = urllib.request.Request(url, headers = {"User-Agent": "unsloth-pins-updater"})+ with urllib.request.urlopen(request, timeout = _TIMEOUT_S) as response:+ return response.read()+++def hash_url(url: str) -> str:+ digest = hashlib.sha256()+ request = urllib.request.Request(url, headers = {"User-Agent": "unsloth-pins-updater"})+ with urllib.request.urlopen(request, timeout = _TIMEOUT_S) as response:+ while chunk := response.read(_CHUNK):+ digest.update(chunk)+ return digest.hexdigest()+++def verify_signature(shasums: bytes, signature: bytes, keyring: bytes) -> None:+ """Raise unless `signature` is a good signature over `shasums` by a key in `keyring`."""+ gpg = shutil.which("gpg")+ if not gpg:+ raise RuntimeError(+ "gpg is required to verify SHASUMS256.txt; refusing to pin unverified digests."+ )+ with tempfile.TemporaryDirectory() as home:+ paths = {+ name: os.path.join(home, name)+ for name in ("pubring.kbx", "SHASUMS256.txt", "SHASUMS256.txt.sig")+ }+ for name, data in (+ ("pubring.kbx", keyring),+ ("SHASUMS256.txt", shasums),+ ("SHASUMS256.txt.sig", signature),+ ):+ with open(paths[name], "wb") as handle:+ handle.write(data)+ result = subprocess.run(+ [+ gpg,+ "--homedir",+ home,+ "--no-default-keyring",+ "--keyring",+ paths["pubring.kbx"],+ "--status-fd",+ "1",+ "--verify",+ paths["SHASUMS256.txt.sig"],+ paths["SHASUMS256.txt"],+ ],+ capture_output = True,+ text = True,+ timeout = _TIMEOUT_S,+ )+ if result.returncode != 0 or "[GNUPG:] VALIDSIG" not in result.stdout:+ raise RuntimeError("SHASUMS256.txt is not signed by a Node release key.")+++def newest_in_line(index: list[dict], major: int) -> Optional[str]:+ """The newest LTS release of `major` in nodejs.org's dist index."""+ best = None+ for release in index:+ version = str(release.get("version", "")).lstrip("v")+ try:+ key = version_key(version)+ except ValueError:+ continue+ if key[0] == major and release.get("lts") and (best is None or key > version_key(best)):+ best = version+ return best+++def update_pins(+ pins: dict,+ fetch: Optional[Callable[[str], bytes]] = None,+ hasher: Optional[Callable[[str], str]] = None,+ verifier: Optional[Callable[[bytes, bytes, bytes], None]] = None,+) -> tuple[dict, list[str]]:+ fetch, hasher, verifier = fetch or _get, hasher or hash_url, verifier or verify_signature+ pinned = str(pins["default_version"])+ target = newest_in_line(json.loads(fetch(f"{_DIST}/index.json")), version_key(pinned)[0])+ if target is None or version_key(target) <= version_key(pinned):+ return pins, []+ shasums = fetch(f"{_DIST}/v{target}/SHASUMS256.txt")+ verifier(shasums, fetch(f"{_DIST}/v{target}/SHASUMS256.txt.sig"), fetch(_KEYRING))+ published = {}+ for line in shasums.decode("utf-8").splitlines():+ fields = line.split()+ if len(fields) == 2:+ published[fields[1]] = fields[0]+ digests = {}+ for name in archive_names(target):+ expected = published.get(name)+ if not expected:+ raise RuntimeError(f"SHASUMS256.txt for v{target} lists no {name}.")+ actual = hasher(f"{_DIST}/v{target}/{name}")+ if actual != expected:+ raise RuntimeError(+ f"{name} hashed to {actual}, but the signed SHASUMS256.txt lists {expected}."+ )+ digests[name] = expected+ result = json.loads(json.dumps(pins))+ result["default_version"] = target+ result["versions"] = {target: digests}+ return result, [f"node: {pinned} -> {target}"]+++def main(argv: Optional[list[str]] = None) -> int:+ parser = argparse.ArgumentParser(description = __doc__.splitlines()[0])+ parser.add_argument("--pins", type = Path, default = PINS_PATH)+ mode = parser.add_mutually_exclusive_group()+ mode.add_argument("--check", action = "store_true", help = "Exit 1 if a newer release exists.")+ mode.add_argument("--write", action = "store_true", help = "Rewrite the pins file.")+ args = parser.parse_args(argv)+ try:+ pins = json.loads(args.pins.read_text(encoding = "utf-8"))+ new_pins, changes = update_pins(pins)+ except Exception as exc: # noqa: BLE001 -- one line for the CI log, exit 2+ print(f"error: {exc}", file = sys.stderr)+ return 2+ for line in changes or ["Node pin is current."]:+ print(line)+ if changes and args.write:+ # Replace atomically so an interrupted run never leaves a truncated pins file.+ tmp = args.pins.with_name(args.pins.name + ".tmp")+ tmp.write_text(json.dumps(new_pins, indent = 2) + "\n", encoding = "utf-8")+ os.replace(tmp, args.pins)+ return 1 if changes and args.check else 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/studio/NODE_RUNTIME.md b/studio/NODE_RUNTIME.mdnew file mode 100644index 00000000000..cd675e089a2--- /dev/null+++ b/studio/NODE_RUNTIME.md@@ -0,0 +1,58 @@+# Managed Node updates++Studio pins one exact release of a supported Node LTS major in+`node_prebuilt_pins.json`. Setup verifies downloaded archives against the six+committed SHA-256 digests. The default does not query Node's release index.++Review the pin monthly. Take security releases promptly, and take an earlier+update when a confirmed compatibility or reliability fix needs it. Routine+patches and minor releases can be grouped into the monthly update. Move to a new+LTS major after compatibility testing and before the current major reaches+end of life. Freezing an LTS version until the next major would miss security+fixes within that line.++This is a maintainer release policy, not a timer on the user's machine. A new+pin reaches managed installations through Studio setup or update. An unchanged,+verified installation downloads nothing. Setup checks the new pin even when+its managed Node is already on PATH, and reruns once if the package update+changes only the pin. A usable old installation is retained with a warning if+replacement fails; a successful Studio update alone does not prove Node was+replaced.++A compatible external Node/npm remains user-managed and is used read-only.+`UNSLOTH_SKIP_NODE_INSTALL=1` disables automatic Node installation and updates.+The Docker `unsloth-studio-update` helper also moves the image's managed Node+(`$STUDIO_HOME/node`) to the new package's pin once the updated Studio passes its+checks; an unchanged pin downloads nothing, and a failed download keeps the+current Node without failing the update.++## Updating the pin++Dependabot cannot update this file: it is not a package manifest, and the digests have to be+checked against Node's signed checksums. Instead `.github/workflows/node-pins-update.yml` runs+`scripts/update_node_pins.py` daily. When the pinned LTS line has a newer release (security+releases included), it verifies `SHASUMS256.txt` against the Node release keys, downloads and+hashes all six archives, and opens or refreshes one PR on `ci/node-pins`. It never moves to a+new LTS major; that stays the manual review below. Run it locally with+`python scripts/update_node_pins.py --check` (exit 1 when a newer release exists) or `--write`.++For a manual update or a new major:++1. Check the [Node release schedule](https://github.com/nodejs/Release#release-schedule)+ and the selected release's notes, including security fixes.+2. Fetch its `SHASUMS256.txt` and signature from `https://nodejs.org/dist/v<version>/`.+ Verify the signature with the [Node release keys](https://github.com/nodejs/release-keys).+3. Update `default_version` and all six archive digests together: Linux and macOS+ x64/ARM64 `.tar.gz` files and Windows x64/ARM64 `.zip` files. Download the+ archives and verify their digests before committing the pins.+4. Run the Node installer/runtime tests, both platforms' Node selection tests,+ and setup rerun tests. Check an upgrade from the previous pin, a second run+ with no download, and frontend/OXC compatibility with the new runtime.++## Windows reputation warnings++Keeping Node patched addresses known Node vulnerabilities. It does not guarantee+that Windows accepts every executable. [Microsoft Defender SmartScreen](https://learn.microsoft.com/en-us/windows/security/operating-system-security/virus-and-threat-protection/microsoft-defender-smartscreen/)+checks reputation and signatures. Diagnose the actual flagged file and warning+before attributing it to Node. Do not disable Windows protections or remove+download security metadata as part of a Node update.diff --git a/studio/node_prebuilt_pins.json b/studio/node_prebuilt_pins.jsonindex d279c043161..5be19a0b854 100644--- a/studio/node_prebuilt_pins.json+++ b/studio/node_prebuilt_pins.json@@ -1,15 +1,15 @@{"schema_version": 1,- "comment": "Trust anchor for install_node_prebuilt.py: sha256 frozen from the official nodejs.org SHASUMS256.txt. To bump: update default_version and every per-asset digest from the new SHASUMS256.txt.",- "default_version": "24.18.0",+ "comment": "Trust anchor for install_node_prebuilt.py: sha256 frozen from the official nodejs.org SHASUMS256.txt. Review the supported LTS pin monthly and expedite security fixes. See NODE_RUNTIME.md for the update policy and verification steps.",+ "default_version": "24.22.1","versions": {- "24.18.0": {- "node-v24.18.0-linux-x64.tar.gz": "783130984963db7ba9cbd01089eaf2c2efb055c7c1693c943174b967b3050cb8",- "node-v24.18.0-linux-arm64.tar.gz": "6b4484c2190274175df9aa8f28e2d758a819cb1c1fe6ab481e2f95b463ab8508",- "node-v24.18.0-darwin-x64.tar.gz": "dfd0dbd3e721503434df7b7205e719f61b3a3a31b2bcf9729b8b91fea240f080",- "node-v24.18.0-darwin-arm64.tar.gz": "e1a97e14c99c803e96c7339403282ea05a499c32f8d83defe9ef5ec66f979ed1",- "node-v24.18.0-win-x64.zip": "0ae68406b42d7725661da979b1403ec9926da205c6770827f33aac9d8f26e821",- "node-v24.18.0-win-arm64.zip": "f274669adb93b1fd0fbf8f21fd078609e9dcc84333d4f2718d2dde3f9a161a01"+ "24.22.1": {+ "node-v24.22.1-linux-x64.tar.gz": "eb6728e77c576a35162c122c45ccadf224d89ff00abc8dae46cc2897c6002d7c",+ "node-v24.22.1-linux-arm64.tar.gz": "33c37be234ba8bee041961047b19160f4d7d0f164e8e246f78bdd10feff148b3",+ "node-v24.22.1-darwin-x64.tar.gz": "d132557e7ee2b85af08b0c8c34338e65c6430f2238d01f727728ef42dc83b035",+ "node-v24.22.1-darwin-arm64.tar.gz": "89c682593d76cd44233fa53b1563264e7de9cbb189cad169135c5b4fadfbc0a7",+ "node-v24.22.1-win-x64.zip": "d2046d28c2c3dcd211ac5145c0bf30e2047ef9dfb306693c8c6e2eccd8b95fa5",+ "node-v24.22.1-win-arm64.zip": "a0c807319fede24c4a0d8f84564c82a619bd313b16b10c007c383c2609e99171"}}}diff --git a/studio/setup.ps1 b/studio/setup.ps1index 469d5879d95..03d2fcea243 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -31,6 +31,10 @@ $PackageDir = Split-Path -Parent $ScriptDir$script:SetupSelfPath = $MyInvocation.MyCommand.Path$script:SetupSelfAtStart = $nulltry { $script:SetupSelfAtStart = [Convert]::ToBase64String([System.IO.File]::ReadAllBytes($script:SetupSelfPath)) } catch { }+# Node is provisioned before the dependency pass can install a newer pin.+$script:SetupNodePinsPath = Join-Path $ScriptDir 'node_prebuilt_pins.json'+$script:SetupNodePinsAtStart = $null+try { $script:SetupNodePinsAtStart = [Convert]::ToBase64String([System.IO.File]::ReadAllBytes($script:SetupNodePinsPath)) } catch { }$script:SetupArgs = @($args)$script:SetupStartEnv = $nulltry { $script:SetupStartEnv = [System.Environment]::GetEnvironmentVariables() } catch { }@@ -329,7 +333,10 @@ function Complete-FrontendBuildBackground {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 }- return ($now -cne $script:SetupSelfAtStart)+ if ($now -cne $script:SetupSelfAtStart) { return $true }+ $nowPins = $null+ try { $nowPins = [Convert]::ToBase64String([System.IO.File]::ReadAllBytes($script:SetupNodePinsPath)) } catch { }+ return ($nowPins -cne $script:SetupNodePinsAtStart)}function Restore-SetupStartEnvironment {@@ -5093,8 +5100,11 @@ function Get-NodeDecision {param([string]$NodeVersion, # `node -v` output, e.g. v22.17.1 (or empty)[string]$NpmVersion, # `npm -v` output, e.g. 10.9.2 (or empty)- [string]$SkipInstall # "1" => never auto-install+ [string]$SkipInstall, # "1" => never auto-install+ [bool]$ManagedOnPath = $false)+ # An inherited managed Node must go through the pin check, even when compatible.+ if ($ManagedOnPath -and $SkipInstall -ne "1") { return "bundled" }$node = ($NodeVersion -replace '^v', '').Trim()$npm = "$NpmVersion".Trim()if ($node -match '^\d+\.\d+' -and $npm -match '^\d+') {@@ -5111,6 +5121,15 @@ function Get-NodeDecision {}+function Test-ManagedNodeOnPath {+ # Only installer metadata marks it managed (wherever NodeDir is); a bare path match may be a user's link.+ $command = Get-Command node -ErrorAction SilentlyContinue+ if (-not $command -or -not $command.Path) { return $false }+ $parent = Split-Path -Parent $command.Path+ return (Test-Path -LiteralPath (Join-Path $parent "UNSLOTH_NODE_PREBUILT_INFO.json") -PathType Leaf)+}++function Test-PackagedFrontend {param([string]$LocalInstall, [string]$IndexPath, [string]$ProjectFilePath)# PyPI installs (mode 0) use the release-built dist: wheel mtimes are not build order.@@ -5127,6 +5146,7 @@ $NodeDir = $null$SysNodeVersion = ""$SysNpmVersion = ""$NodeSource = $null+$NodeOnPathIsManaged = $falseif (-not $IsPipInstall) {$_masterRoot = Get-MasterRootOverride@@ -5167,7 +5187,9 @@ if (-not $IsPipInstall) {# Under Stop a bare `node -v` throws past 2>$null.$SysNodeVersion = try { if (Get-Command node -ErrorAction SilentlyContinue) { (node -v 2>$null) } else { "" } } catch { "" }$SysNpmVersion = try { if (Get-Command npm -ErrorAction SilentlyContinue) { (npm -v 2>$null) } else { "" } } catch { "" }- $NodeSource = Get-NodeDecision -NodeVersion "$SysNodeVersion" -NpmVersion "$SysNpmVersion" -SkipInstall "$($env:UNSLOTH_SKIP_NODE_INSTALL)"+ $NodeOnPathIsManaged = Test-ManagedNodeOnPath+ $NodeSource = Get-NodeDecision -NodeVersion "$SysNodeVersion" -NpmVersion "$SysNpmVersion" `+ -SkipInstall "$($env:UNSLOTH_SKIP_NODE_INSTALL)" -ManagedOnPath $NodeOnPathIsManaged}if ($IsPipInstall) {@@ -5177,6 +5199,8 @@ if ($IsPipInstall) {} else {if ($NodeSource -eq "system") {substep "Node $SysNodeVersion and npm $SysNpmVersion already meet requirements (system)."+ } elseif ($NodeSource -eq "bundled" -and $NodeOnPathIsManaged) {+ substep "Checking the isolated Node against the configured version (system Node/npm left untouched)."} elseif ($NodeSource -eq "bundled") {substep "Node='$SysNodeVersion' npm='$SysNpmVersion' unsuitable; will use an isolated Node (system left untouched)."} else {@@ -8510,7 +8534,7 @@ if ($stackExit -ne 0) {# 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"+ step "setup" "the update changed setup or its Node pin; finishing with the new version"$_setupRerunArgs = $script:SetupArgsRestore-SetupStartEnvironmentRemove-Item Env:UNSLOTH_STUDIO_FULL_DEPS -ErrorAction SilentlyContinuediff --git a/studio/setup.sh b/studio/setup.shindex 2a1d601436e..fc6fd25ec50 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -8,6 +8,9 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"# The deps pass can replace this file while bash reads the old one (_setup_rerun_if_replaced)._SETUP_SELF="$SCRIPT_DIR/$(basename -- "${BASH_SOURCE[0]}")"_SETUP_SELF_SUM=$(cksum < "$_SETUP_SELF" 2>/dev/null || true)+# Node is provisioned before the dependency pass can install a newer pin.+_SETUP_NODE_PINS="$SCRIPT_DIR/node_prebuilt_pins.json"+_SETUP_NODE_PINS_SUM=$(cksum 2>/dev/null < "$_SETUP_NODE_PINS" || true)_SETUP_ARGV=("$@")_SETUP_START_PWD=$PWD# Bash caches PATH entries across cd, so anchor relative entries before the first directory change.@@ -2063,6 +2066,11 @@ decide_node_source() {_dns_node="${1#v}"_dns_npm="$2"_dns_skip="$3"+ # A managed Node inherited on PATH still needs the pin check on every setup.+ if [ "${4:-0}" = 1 ] && [ "$_dns_skip" != 1 ]; then+ echo bundled+ return 0+ ficase "$_dns_node" in ''|*[!0-9.]*) _dns_node='' ;; esaccase "$_dns_npm" in ''|*[!0-9.]*) _dns_npm='' ;; esacif [ -n "$_dns_node" ] && [ -n "$_dns_npm" ]; then@@ -2122,7 +2130,16 @@ if [ -n "$_SYS_NODE_VER" ]; then_probe_system_node_tool npm_SYS_NPM_VER="$_PROBED_VER"fi-NODE_SOURCE="$(decide_node_source "$_SYS_NODE_VER" "$_SYS_NPM_VER" "${UNSLOTH_SKIP_NODE_INSTALL:-0}")"+# Only installer metadata marks a PATH Node managed (wherever NODE_DIR is); a bare path match may be a user's link.+_NODE_ON_PATH_IS_MANAGED=0+_node_on_path="$(command -v node || true)"+if [ -n "$_node_on_path" ]; then+ _node_on_path_root="$(cd "$(dirname "$_node_on_path")/.." 2>/dev/null && pwd -P)" || _node_on_path_root=""+ if [ -n "$_node_on_path_root" ] && [ -f "$_node_on_path_root/UNSLOTH_NODE_PREBUILT_INFO.json" ]; then+ _NODE_ON_PATH_IS_MANAGED=1+ fi+fi+NODE_SOURCE="$(decide_node_source "$_SYS_NODE_VER" "$_SYS_NPM_VER" "${UNSLOTH_SKIP_NODE_INSTALL:-0}" "$_NODE_ON_PATH_IS_MANAGED")"_FRONTEND_SKIP=falseif [ "$NODE_SOURCE" = system ]; then@@ -2391,14 +2408,15 @@ _setup_rerun_if_replaced() {if [ "${UNSLOTH_SETUP_RERUN:-}" = 1 ] || [ -z "$_SETUP_SELF_SUM" ]; thenreturn 0fi- local _now+ local _now _now_pins_now=$(cksum < "$_SETUP_SELF" 2>/dev/null) || return 0- if [ -z "$_now" ] || [ "$_now" = "$_SETUP_SELF_SUM" ]; then+ _now_pins=$(cksum 2>/dev/null < "$_SETUP_NODE_PINS" || true)+ if [ -z "$_now" ] || { [ "$_now" = "$_SETUP_SELF_SUM" ] && [ "$_now_pins" = "$_SETUP_NODE_PINS_SUM" ]; }; thenreturn 0fi# 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"+ step "setup" "the update changed setup or its Node pin; finishing with the new version"export UNSLOTH_SETUP_RERUN=1unset UNSLOTH_STUDIO_FULL_DEPScd "$_SETUP_START_PWD" 2>/dev/null || :diff --git a/tests/python/test_docker_update_helpers.py b/tests/python/test_docker_update_helpers.pyindex f2b3a77626c..b3973cf5bc1 100644--- a/tests/python/test_docker_update_helpers.py+++ b/tests/python/test_docker_update_helpers.py@@ -1121,3 +1121,55 @@ def test_a_failed_studio_update_puts_the_previous_install_back(tmp_path: Path):assert res.returncode != 0, "a broken update must not report success"assert "previous install was restored" in res.stdout, res.stdoutassert "not restarted" in res.stdout, res.stdout+++def _managed_node(+ tmp_path: Path,+ env,+ installer_exit: int = 0,+ kept: bool = False,+) -> None:+ """The image's managed Node (installer metadata) and a recording installer in the package."""+ (Path(env["UNSLOTH_STUDIO_HOME"]) / "node" / "UNSLOTH_NODE_PREBUILT_INFO.json").write_text("{}")+ (tmp_path / "site" / "studio" / "install_node_prebuilt.py").write_text(+ "import os, sys\n"+ "with open(os.environ['STUB_LOG'], 'a') as f:\n"+ " f.write('STUB-NODE ' + ' '.join(sys.argv[1:]) + '\\n')\n"+ + ("print('Node download failed (x); keeping existing isolated Node')\n" if kept else "")+ + f"sys.exit({installer_exit})\n"+ )+++def test_studio_update_moves_the_managed_node_to_the_new_pin(tmp_path: Path):+ env = _studio_env(tmp_path)+ _managed_node(tmp_path, env)+ res = _run(STUDIO_UPDATE, [], env)+ assert res.returncode == 0, res.stderr + res.stdout+ node_dir = Path(env["UNSLOTH_STUDIO_HOME"]) / "node"+ assert f"STUB-NODE --install-dir {node_dir}" in _calls(env), _calls(env)+ assert "STUB-SUPERVISORCTL restart studio" in _calls(env), _calls(env)++[email protected]("installer_exit, kept", [(1, False), (0, True)])+def test_studio_update_keeps_the_current_node_when_the_new_pin_cannot_install(+ tmp_path: Path, installer_exit: int, kept: bool+):+ env = _studio_env(tmp_path)+ _managed_node(tmp_path, env, installer_exit = installer_exit, kept = kept)+ res = _run(STUDIO_UPDATE, [], env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert "keeping the current one" in res.stdout, res.stdout+ assert "matches the new pin" not in res.stdout, res.stdout+ assert "STUB-SUPERVISORCTL restart studio" in _calls(env), _calls(env)++[email protected]("skip", ["0", "1"])+def test_studio_update_leaves_a_node_it_does_not_manage(tmp_path: Path, skip: str):+ env = _studio_env(tmp_path)+ _managed_node(tmp_path, env)+ env["UNSLOTH_SKIP_NODE_INSTALL"] = skip+ if skip == "0":+ (Path(env["UNSLOTH_STUDIO_HOME"]) / "node" / "UNSLOTH_NODE_PREBUILT_INFO.json").unlink()+ res = _run(STUDIO_UPDATE, [], env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert "STUB-NODE" not in _calls(env), _calls(env)diff --git a/tests/sh/test_node_decision.sh b/tests/sh/test_node_decision.shindex 91a845c89ec..e01ce4fcb36 100644--- a/tests/sh/test_node_decision.sh+++ b/tests/sh/test_node_decision.sh@@ -19,7 +19,7 @@ fiassert_decision() {_label="$1"; _node="$2"; _npm="$3"; _skip="$4"; _expected="$5"- _actual="$(decide_node_source "$_node" "$_npm" "$_skip")"+ _actual="$(decide_node_source "$_node" "$_npm" "$_skip" "${6:-0}")"if [ "$_actual" = "$_expected" ]; thenecho " PASS: $_label (node='$_node' npm='$_npm' skip='$_skip' -> $_actual)"PASS=$((PASS + 1))@@ -47,6 +47,10 @@ assert_decision "npm10 + skip" "v22.17.1" "10.9.2" "1" skipassert_decision "missing + skip" "" "" "1" skip# The skip flag does NOT override an already-good system.assert_decision "good system + skip" "v22.17.1" "11.13.0" "1" system+assert_decision "managed on PATH" "v24.17.0" "11.13.0" "0" bundled 1+assert_decision "managed + skip" "v24.17.0" "11.13.0" "1" system 1+assert_decision "broken managed" "" "" "0" bundled 1+assert_decision "broken managed + skip" "" "" "1" skip 1rm -f "$_FUNC_FILE"echo ""diff --git a/tests/sh/test_node_managed_marker.sh b/tests/sh/test_node_managed_marker.shnew file mode 100755index 00000000000..ee0bc58b5f0--- /dev/null+++ b/tests/sh/test_node_managed_marker.sh@@ -0,0 +1,50 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: AGPL-3.0-only+# Installer metadata beside the PATH Node routes it through the pin check when NODE_DIR differs.+set -euo pipefail++HERE="$(cd "$(dirname "$0")" && pwd)"+SETUP_SH="${SETUP_SH:-$HERE/../../studio/setup.sh}"+WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT+source "$HERE/_harness.sh"++sed -n '/^decide_node_source()/,/^}/p' "$SETUP_SH" > "$WORK/decision"+sed -n '/^_probe_system_node_tool node$/,/^_FRONTEND_SKIP=false$/p' "$SETUP_SH" > "$WORK/selection"+for part in decision selection; do+ [ -s "$WORK/$part" ] || { echo "Cannot extract $part from setup.sh"; exit 1; }+done++for who in live external; do+ mkdir -p "$WORK/$who/node/bin"+ printf '#!/bin/sh\necho v24.18.0\n' > "$WORK/$who/node/bin/node"+ printf '#!/bin/sh\necho 11.0.0\n' > "$WORK/$who/node/bin/npm"+ chmod +x "$WORK/$who/node/bin/node" "$WORK/$who/node/bin/npm"+done+echo '{"version": "24.18.0"}' > "$WORK/live/node/UNSLOTH_NODE_PREBUILT_INFO.json"++source_for() { # node dir on PATH, NODE_DIR, UNSLOTH_SKIP_NODE_INSTALL+ PATH="$1/bin:$PATH" UNSLOTH_SKIP_NODE_INSTALL="$3" bash -c "+ set -euo pipefail+ step() { :; }; substep() { :; }+ _probe_system_node_tool() { _PROBED_VER=\$(\"\$1\" -v); }+ $(cat "$WORK/decision")+ NODE_DIR='$2'+ $(cat "$WORK/selection")+ echo \"\$NODE_SOURCE\""+}++assert_eq 'staged update: the live managed Node gets the pin check' bundled \+ "$(source_for "$WORK/live/node" "$WORK/stage/node" 0)"+assert_eq 'staged update: a compatible external Node stays read-only' system \+ "$(source_for "$WORK/external/node" "$WORK/stage/node" 0)"+assert_eq 'staged update: the skip flag still keeps the managed Node' system \+ "$(source_for "$WORK/live/node" "$WORK/stage/node" 1)"+assert_eq 'same dir: the managed Node gets the pin check' bundled \+ "$(source_for "$WORK/live/node" "$WORK/live/node" 0)"+# A user's own Node linked in at the managed location has no installer metadata: never replaced.+ln -s "$WORK/external/node" "$WORK/linked"+assert_eq 'a user Node linked in at NODE_DIR stays read-only' system \+ "$(source_for "$WORK/linked" "$WORK/linked" 0)"++summarydiff --git a/tests/sh/test_node_pin_update.sh b/tests/sh/test_node_pin_update.shnew file mode 100755index 00000000000..a511bf7b022--- /dev/null+++ b/tests/sh/test_node_pin_update.sh@@ -0,0 +1,98 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: AGPL-3.0-only+# Exercise the real setup selection and re-exec across a pin-only package update.+set -euo pipefail++HERE="$(cd "$(dirname "$0")" && pwd)"+SETUP_SH="${SETUP_SH:-$HERE/../../studio/setup.sh}"+WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT+source "$HERE/_harness.sh"++sed -n '/^_SETUP_SELF=/,/^_SETUP_START_PWD=/p' "$SETUP_SH" > "$WORK/start"+sed -n '/^decide_node_source()/,/^}/p' "$SETUP_SH" > "$WORK/decision"+sed -n '/^_probe_system_node_tool node$/,/^_FRONTEND_SKIP=false$/p' "$SETUP_SH" > "$WORK/selection"+sed -n '/^_setup_rerun_if_replaced()/,/^}/p' "$SETUP_SH" > "$WORK/rerun"+for part in start decision selection rerun; do+ [ -s "$WORK/$part" ] || { echo "Cannot extract $part from setup.sh"; exit 1; }+done++{+ cat <<'EOF'+#!/usr/bin/env bash+set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+EOF+ cat "$WORK/start" "$WORK/decision" "$WORK/rerun"+ cat <<'EOF'+NODE_DIR="$SCRIPT_DIR/node"+step() { echo "RERUN"; }+substep() { :; }+_frontend_bg_join() { :; }+_probe_system_node_tool() { _PROBED_VER=$("$1" -v); }+EOF+ cat "$WORK/selection"+ cat <<'EOF'+echo "SOURCE $NODE_SOURCE"+# Stand-in for archive I/O: record replacements, not just installer invocations.+# The installer itself is covered by test_install_node_prebuilt_logic.py.+if [ "$NODE_SOURCE" = bundled ]; then+ if ! cmp -s "$SCRIPT_DIR/node_prebuilt_pins.json" "$NODE_DIR/installed-pin"; then+ cp "$SCRIPT_DIR/node_prebuilt_pins.json" "$NODE_DIR/installed-pin"+ echo "DOWNLOAD $(cat "$NODE_DIR/installed-pin")"+ fi+fi+# Simulate uv replacing the manifest while setup.sh stays byte-identical.+if [ "${UNSLOTH_SETUP_RERUN:-}" != 1 ]; then+ cp "$SCRIPT_DIR/next-pin" "$SCRIPT_DIR/node_prebuilt_pins.json"+fi+_setup_rerun_if_replaced+EOF+} > "$WORK/template.sh"++run_case() {+ local name=$1 target=$2 source=$3 skip=$4+ local root="$WORK/$name"+ mkdir -p "$root/node/bin" "$root/external/bin"+ cp "$WORK/template.sh" "$root/setup.sh"+ printf '%s\n' old > "$root/node_prebuilt_pins.json"+ printf '%s\n' old > "$root/node/installed-pin"+ echo '{}' > "$root/node/UNSLOTH_NODE_PREBUILT_INFO.json" # the installer always writes it+ printf '%s\n' "$target" > "$root/next-pin"+ for bin in "$root/node/bin" "$root/external/bin"; do+ printf '#!/bin/sh\necho v24.18.0\n' > "$bin/node"+ printf '#!/bin/sh\necho 11.0.0\n' > "$bin/npm"+ chmod +x "$bin/node" "$bin/npm"+ done+ local bin="$root/$source/bin"+ if [ "$source" = alias ]; then+ ln -s "$root/node" "$root/alias"+ fi+ OUT=$(env -u UNSLOTH_SETUP_RERUN PATH="$bin:$PATH" \+ UNSLOTH_SKIP_NODE_INSTALL="$skip" bash "$root/setup.sh")+ INSTALLED=$(cat "$root/node/installed-pin")+}++run_case managed new node 0+assert_eq 'managed Node gets the new pin on the first update' new "$INSTALLED"+assert_eq 'a pin-only change reruns setup once' 1 "$(printf '%s\n' "$OUT" | grep -c '^RERUN' || true)"+assert_eq 'only the new archive is downloaded' 1 "$(printf '%s\n' "$OUT" | grep -c '^DOWNLOAD new' || true)"++run_case unchanged old node 0+assert_eq 'unchanged pin keeps Node' old "$INSTALLED"+assert_eq 'unchanged pin never downloads' 0 "$(printf '%s\n' "$OUT" | grep -c '^DOWNLOAD' || true)"+assert_eq 'unchanged setup and pin do not rerun' 0 "$(printf '%s\n' "$OUT" | grep -c '^RERUN' || true)"++run_case symlink new alias 0+assert_eq 'managed Node through a directory symlink gets the new pin' new "$INSTALLED"++run_case external new external 0+assert_eq 'compatible external Node does not replace the managed cache' old "$INSTALLED"+assert_eq 'external runtime remains the source in both passes' 2 "$(printf '%s\n' "$OUT" | grep -c '^SOURCE system' || true)"+assert_eq 'external Node causes no managed download' 0 "$(printf '%s\n' "$OUT" | grep -c '^DOWNLOAD' || true)"++run_case opted_out new node 1+assert_eq 'skip flag keeps the old managed runtime' old "$INSTALLED"+assert_eq 'skip flag prevents downloads in both passes' 0 "$(printf '%s\n' "$OUT" | grep -c '^DOWNLOAD' || true)"++summarydiff --git a/tests/sh/test_setup_rerun_after_replace.sh b/tests/sh/test_setup_rerun_after_replace.shindex 04c902e1629..1aa7812e210 100755--- a/tests/sh/test_setup_rerun_after_replace.sh+++ b/tests/sh/test_setup_rerun_after_replace.sh@@ -94,7 +94,7 @@ run_setup() {OUT=$(cd "$WORK/launch dir" && env "$@" "$_interp" "$WORK/pkg/setup.sh" --local "a b" 2>&1) || RC=$?}count() { printf '%s\n' "$OUT" | grep -cF -- "$1" || true; }-HANDOFF="STEP setup: the update replaced this setup script; finishing with the new version"+HANDOFF="STEP setup: the update changed setup or its Node pin; finishing with the new version"INTERPRETERS=(bash)if [ "$(uname -s)" = Darwin ] && [ -x /bin/bash ]; thendiff --git a/tests/studio/install/test_install_node_prebuilt_logic.py b/tests/studio/install/test_install_node_prebuilt_logic.pyindex 8d4548a124c..83d1eee3ccf 100644--- a/tests/studio/install/test_install_node_prebuilt_logic.py+++ b/tests/studio/install/test_install_node_prebuilt_logic.py@@ -344,7 +344,6 @@ def test_install_prebuilt_short_circuits_when_version_matches(tmp_path: Path, mopin = M.pinned_sha256(M.load_pins(), version, asset)M.write_metadata(install_dir, version = version, asset = asset, sha256 = pin)monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))- monkeypatch.setattr(M, "fetch_json", lambda url: INDEX)monkeypatch.setattr(M, "installed_node_version", lambda d, h: version)monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)@@ -354,7 +353,7 @@ def test_install_prebuilt_short_circuits_when_version_matches(tmp_path: Path, momonkeypatch.setattr(M, "download_file", boom)monkeypatch.setattr(M, "download_bytes", boom)- rc = M.install_prebuilt(install_dir, channel = "lts", min_major = 24, force = False)+ rc = M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False)assert rc == M.EXIT_SUCCESS@@ -376,7 +375,6 @@ def test_a_matching_install_beside_a_running_installer_still_exits_0(tmp_path: Passert "node_version_checked" not in M.load_metadata(install_dir)monkeypatch.setattr(M, "detect_host", lambda: host)- monkeypatch.setattr(M, "fetch_json", lambda url: INDEX)monkeypatch.setattr(M, "installed_node_version", lambda d, h: version)monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)@@ -394,7 +392,7 @@ def test_a_matching_install_beside_a_running_installer_still_exits_0(tmp_path: Pmonkeypatch.setattr(M, "RECORD_LOCK_TIMEOUT_SECONDS", 0)monkeypatch.setattr(M, "INSTALL_LOCK_TIMEOUT_SECONDS", 0)- assert M.install_prebuilt(install_dir, channel = "lts", min_major = 24, force = False) == (+ assert M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False) == (M.EXIT_SUCCESS)assert "node_version_checked" not in M.load_metadata(install_dir)@@ -495,21 +493,19 @@ def test_install_prebuilt_keeps_existing_when_download_fails(tmp_path: Path, moninstall_dir.mkdir()M.write_metadata(install_dir, version = "24.9.0", asset = "x", sha256 = "y")monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))- monkeypatch.setattr(M, "fetch_json", lambda url: INDEX)monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.9.0")monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)monkeypatch.setattr(M, "download_file_verified", _offline)- rc = M.install_prebuilt(install_dir, channel = "lts", min_major = 24, force = False)+ rc = M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False)assert rc == M.EXIT_SUCCESSdef test_install_prebuilt_reraises_download_failure_without_existing(tmp_path: Path, monkeypatch):install_dir = tmp_path / "node"monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))- monkeypatch.setattr(M, "fetch_json", lambda url: INDEX)monkeypatch.setattr(M, "download_file_verified", _offline)with pytest.raises(OSError):- M.install_prebuilt(install_dir, channel = "lts", min_major = 24, force = False)+ M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False)def _swap_stays_denied(diff --git a/tests/studio/install/test_update_node_pins.py b/tests/studio/install/test_update_node_pins.pynew file mode 100644index 00000000000..bac0076e104--- /dev/null+++ b/tests/studio/install/test_update_node_pins.py@@ -0,0 +1,97 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""scripts/update_node_pins.py: stays on the pinned LTS major, verifies before it pins."""++from __future__ import annotations++import importlib.util+import json+from pathlib import Path++import pytest++REPO = Path(__file__).resolve().parents[3]+_spec = importlib.util.spec_from_file_location(+ "update_node_pins", REPO / "scripts" / "update_node_pins.py"+)+U = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(U)++PINS = {+ "schema_version": 1,+ "comment": "c",+ "default_version": "24.18.0",+ "versions": {"24.18.0": {}},+}+++def _index(*releases):+ return json.dumps([{"version": v, "lts": lts} for v, lts in releases]).encode()+++def _fake(+ index,+ target = "24.22.1",+ wrong = None,+):+ shasums = "".join(+ f"{'0' * 63}{i} {name}\n" for i, name in enumerate(U.archive_names(target))+ ).encode()++ def fetch(url):+ if url.endswith("/index.json"):+ return index+ if url.endswith("SHASUMS256.txt"):+ return shasums+ return b"sig-or-keyring"++ def hasher(url):+ name = url.rsplit("/", 1)[1]+ digest = dict(line.split()[::-1] for line in shasums.decode().splitlines())[name]+ return "f" * 64 if name == wrong else digest++ return fetch, hasher+++def test_takes_the_newest_lts_release_of_the_pinned_major():+ fetch, hasher = _fake(+ _index(+ ("v26.12.1", False),+ ("v24.22.1", "Krypton"),+ ("v24.20.0", "Krypton"),+ ("v22.23.4", "Jod"),+ )+ )+ pins, changes = U.update_pins(PINS, fetch, hasher, lambda *a: None)+ assert changes == ["node: 24.18.0 -> 24.22.1"]+ assert pins["default_version"] == "24.22.1"+ assert sorted(pins["versions"]["24.22.1"]) == sorted(U.archive_names("24.22.1"))+ assert pins["comment"] == "c"+++def test_a_newer_major_or_a_non_lts_release_is_left_for_review():+ fetch, hasher = _fake(_index(("v26.12.1", False), ("v24.18.0", "Krypton"), ("v28.0.0", "Next")))+ assert U.update_pins(PINS, fetch, hasher, lambda *a: None) == (PINS, [])+++def test_a_bad_signature_changes_nothing():+ fetch, hasher = _fake(_index(("v24.22.1", "Krypton")))++ def refuse(*_):+ raise RuntimeError("SHASUMS256.txt is not signed by a Node release key.")++ with pytest.raises(RuntimeError, match = "not signed"):+ U.update_pins(PINS, fetch, hasher, refuse)+++def test_an_archive_that_does_not_match_the_signed_digest_is_refused():+ fetch, hasher = _fake(_index(("v24.22.1", "Krypton")), wrong = "node-v24.22.1-win-arm64.zip")+ with pytest.raises(RuntimeError, match = "win-arm64"):+ U.update_pins(PINS, fetch, hasher, lambda *a: None)+++def test_the_committed_pins_name_all_six_archives():+ pins = json.loads((REPO / "studio" / "node_prebuilt_pins.json").read_text(encoding = "utf-8"))+ version = pins["default_version"]+ assert sorted(pins["versions"][version]) == sorted(U.archive_names(version))diff --git a/tests/studio/test_node_decision.ps1 b/tests/studio/test_node_decision.ps1index fd5b666e684..a60367b99e1 100644--- a/tests/studio/test_node_decision.ps1+++ b/tests/studio/test_node_decision.ps1@@ -71,6 +71,43 @@ 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) {')diff --git a/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1 b/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1index 817d0f14bfa..6aacbc79286 100644--- a/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1+++ b/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1@@ -120,6 +120,9 @@ if ($env:MODE -eq 'identical') {Remove-Item -LiteralPath $script:SetupSelfPath[System.IO.File]::WriteAllBytes($script:SetupSelfPath, $same)}+if ($env:MODE -eq 'pin-only') {+ [System.IO.File]::WriteAllText((Join-Path $ScriptDir 'node_prebuilt_pins.json'), 'new pin')+}if ($env:FAIL_DEPS -eq '1') { Exit-SetupFailure -Message "Python dependency installation failed (exit code 2)" -Code 2 }'@$newDeps = @'@@ -193,6 +196,7 @@ Write-StudioLine "__TAG__: done"foreach ($name in @('new.ps1', 'third.ps1')) { Copy-Item -LiteralPath (Join-Path $script:Templates $name) -Destination $dir }$setup = Join-Path $dir 'setup.ps1'Copy-Item -LiteralPath (Join-Path $script:Templates $Start) -Destination $setup+ [System.IO.File]::WriteAllText((Join-Path $dir 'node_prebuilt_pins.json'), 'old pin')$psi = New-Object System.Diagnostics.ProcessStartInfo$psi.FileName = $HostPath@@ -455,6 +459,14 @@ Describe 'finishing with the setup script the update installed (<HostName>)' -FoGet-Count $r '[TAURI:ERROR] Python dependency installation failed' | Should -Be 1}+ It 'a pin-only package change reruns the byte-identical setup once' {+ $r = Invoke-Setup -HostPath $HostPath -Env @{ MODE = 'pin-only' }+ $r.Rc | Should -Be 0 -Because $r.Text+ Get-Count $r $script:Handoff | Should -Be 1+ Get-Count $r ' OLD banner ' | Should -Be 2+ Get-Count $r 'OLD: done' | Should -Be 1+ }+It 'A4: hands off once even when the new copy is replaced again' {$r = Invoke-Setup -HostPath $HostPath -Env @{ MODE = 'replace'; MODE_NEW = 'third' }$r.Rc | Should -Be 0 -Because $r.Text