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
Fix Studio launcher repair for missing install id (#6933)
Daniel Han6c25ccc8fd35
diff --git a/install.ps1 b/install.ps1index 025b955259f..0077e0859c1 100644--- a/install.ps1+++ b/install.ps1@@ -5358,6 +5358,35 @@ $studioHomeExport`$ErrorActionPreference = 'Stop'`$timeoutSec = 60`$pollIntervalMs = 1000`$_ExpectedStudioRootId = '$_studioRootId'+`$_StudioInstallIdFile = '$($_studioIdFile -replace "'", "''")'++# A missing or malformed id makes /api/health report "", which the baked id never matches: restore ours no-clobber (the desktop app mints it too), leaving a different valid id or an unreadable file alone.+function Repair-StudioInstallId {+ `$idTmp = `$null+ try {+ if (Test-Path -LiteralPath `$_StudioInstallIdFile -PathType Container) { return }+ if (Test-Path -LiteralPath `$_StudioInstallIdFile -PathType Leaf) {+ `$current = ([System.IO.File]::ReadAllText(`$_StudioInstallIdFile)).Trim()+ if (`$current -cmatch '^[0-9a-f]{64}$') { return }+ }+ [System.IO.Directory]::CreateDirectory((Split-Path -Parent `$_StudioInstallIdFile)) | Out-Null+ `$idTmp = "`$_StudioInstallIdFile.`$([System.IO.Path]::GetRandomFileName()).tmp"+ [System.IO.File]::WriteAllText(`$idTmp, `$_ExpectedStudioRootId)+ try {+ [System.IO.File]::Move(`$idTmp, `$_StudioInstallIdFile)+ } catch [System.IO.IOException] {+ `$incumbent = ''+ try { `$incumbent = ([System.IO.File]::ReadAllText(`$_StudioInstallIdFile)).Trim() } catch { return }+ if (`$incumbent -cnotmatch '^[0-9a-f]{64}$') {+ Move-Item -LiteralPath `$idTmp -Destination `$_StudioInstallIdFile -Force+ }+ }+ } catch {+ } finally {+ if (`$idTmp) { Remove-Item -LiteralPath `$idTmp -Force -ErrorAction SilentlyContinue }+ }+}+Repair-StudioInstallIdfunction Test-StudioHealth {param([Parameter(Mandatory = `$true)][int]`$Port)diff --git a/install.sh b/install.shindex 22b7540ae43..3262e9bed63 100755--- a/install.sh+++ b/install.sh@@ -1677,6 +1677,37 @@ if [ -z "${UNSLOTH_EXE:-}" ] || [ ! -x "${UNSLOTH_EXE:-}" ]; thenexit 1fi+# A missing or malformed id makes /api/health report "", which the baked id never matches: restore ours no-clobber (the desktop app mints it too), leaving a different valid id or an unreadable file alone.+_repair_studio_install_id() (+ LC_ALL=C+ export LC_ALL+ _rid_file=${STUDIO_INSTALL_ID_FILE:-}+ [ -n "$_rid_file" ] && [ -n "$_EXPECTED_STUDIO_ROOT_ID" ] || return 0+ _rid_has_valid() {+ [ -e "$_rid_file" ] || return 1+ [ -f "$_rid_file" ] || return 0+ _rid_cur=$({ cat "$_rid_file"; } 2>/dev/null) || return 0+ _rid_cur=${_rid_cur#"${_rid_cur%%[![:space:]]*}"}+ _rid_cur=${_rid_cur%"${_rid_cur##*[![:space:]]}"}+ case "$_rid_cur" in+ "" | *[!0123456789abcdef]*) return 1 ;;+ esac+ [ "${#_rid_cur}" -eq 64 ]+ }+ _rid_has_valid && return 0+ mkdir -p "$(dirname "$_rid_file")" 2>/dev/null || return 0+ _rid_tmp=$(mktemp "$_rid_file.XXXXXX" 2>/dev/null) || return 0+ if printf '%s' "$_EXPECTED_STUDIO_ROOT_ID" > "$_rid_tmp" 2>/dev/null; then+ if ! ln "$_rid_tmp" "$_rid_file" 2>/dev/null && ! _rid_has_valid; then+ mv -f "$_rid_tmp" "$_rid_file" 2>/dev/null || true+ fi+ chmod 600 "$_rid_file" 2>/dev/null || true+ fi+ rm -f "$_rid_tmp" 2>/dev/null+ return 0+)+_repair_studio_install_id+BASE_PORT=8888MAX_PORT_OFFSET=20TIMEOUT_SEC=60@@ -2039,6 +2070,8 @@ LAUNCHER_EOF_css_quoted_exe=$(printf '%s' "$_css_exe" | sed "s/'/'\\\\''/g"){printf '%s\n' "UNSLOTH_EXE='$_css_quoted_exe'"+ _css_quoted_id_file=$(printf '%s' "$_css_id_file" | sed "s/'/'\\\\''/g")+ printf '%s\n' "STUDIO_INSTALL_ID_FILE='$_css_quoted_id_file'"if [ "$_STUDIO_HOME_REDIRECT" = "env" ]; then# An override resolving to the legacy default shares ~/.unsloth/llama.cpp._css_legacy_studio="$HOME/.unsloth/studio"diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 1bf1be0f993..5195592c9ee 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -286,8 +286,8 @@ _STUDIO_INSTALL_ID_RE = _re.compile(r"^[0-9a-f]{64}$")def _read_studio_install_id() -> str:"""Per-install opaque id at $STUDIO_HOME/share/studio_install_id. Returns "" when absent or not a 64-char- lowercase-hex token; then /api/health emits "" and the launcher accepts any healthy backend. Carries no- install-path info (matters when Unsloth runs -H 0.0.0.0)."""+ lowercase-hex token; a launcher with a baked id rejects "", so it restores a missing id before starting+ Studio. Carries no install-path info (matters when Unsloth runs -H 0.0.0.0)."""try:token = ((_STUDIO_ROOT_RESOLVED / "share" / "studio_install_id")@@ -304,7 +304,7 @@ _STUDIO_ROOT_ID_CACHE: str = _read_studio_install_id()def _studio_root_id() -> str:"""Same-install discriminator for /api/health (cached at import). Empty when no installer token is- present; the launcher treats "" as "accept any healthy backend"."""+ present."""return _STUDIO_ROOT_ID_CACHEdiff --git a/tests/test_studio_install_workspace_guard.py b/tests/test_studio_install_workspace_guard.pyindex 45ffb5b3ebf..48243845630 100644--- a/tests/test_studio_install_workspace_guard.py+++ b/tests/test_studio_install_workspace_guard.py@@ -1477,6 +1477,155 @@ def test_create_studio_shortcuts_end_to_end_never_embeds_a_planted_id(tmp_path):assert not marker.exists(), "the planted id executed as launcher code"+def _generated_sh_launcher(tmp_path):+ """Run the real create_studio_shortcuts; return (studio_home, data_dir, baked id)."""+ home, studio_home, data_dir = tmp_path / "home", tmp_path / "studio", tmp_path / "data"+ for d in (home, studio_home / "share", data_dir, tmp_path / "bin"):+ d.mkdir(parents = True)+ exe = tmp_path / "bin" / "unsloth"+ exe.write_text("#!/bin/sh\nexit 0\n", encoding = "utf-8")+ exe.chmod(0o755)+ script = (+ "set -e\ndownload() { : ; }\nsubstep() { : ; }\n_LOCK_KEY=testkey\n"+ f'STUDIO_HOME="{studio_home}"\nDATA_DIR="{data_dir}"\n_STUDIO_HOME_REDIRECT=default\n'+ + _extract_create_studio_shortcuts()+ + f'\ncreate_studio_shortcuts "{exe}" "linux"\n'+ )+ res = subprocess.run(+ ["sh", "-c", script],+ text = True,+ capture_output = True,+ timeout = 300,+ env = dict(os.environ, HOME = str(home)),+ cwd = str(tmp_path),+ )+ assert res.returncode == 0, res.stderr[-400:]+ baked = re.search(+ r"^_EXPECTED_STUDIO_ROOT_ID='(.*)'$", (data_dir / "launch-studio.sh").read_text(), re.M+ ).group(1)+ return studio_home, data_dir, baked+++def _run_sh_launcher_repair(+ data_dir: Path,+ baked: str,+ conf: Path | None = None,+):+ """The generated launcher's prologue (studio.conf + the repair), under its own set -euo pipefail."""+ launcher = (data_dir / "launch-studio.sh").read_text(encoding = "utf-8")+ start = launcher.index("_repair_studio_install_id() (")+ end = launcher.index("\n_repair_studio_install_id\n", start) + len(+ "\n_repair_studio_install_id\n"+ )+ script = (+ "set -euo pipefail\n"+ f"_EXPECTED_STUDIO_ROOT_ID='{baked}'\n"+ f". '{conf or data_dir / 'studio.conf'}'\n" + launcher[start:end] + "echo REPAIR_DONE\n"+ )+ res = subprocess.run(["bash", "-c", script], text = True, capture_output = True, timeout = 60)+ assert res.returncode == 0 and "REPAIR_DONE" in res.stdout, res.stderr++[email protected](os.name != "posix", reason = "runs the POSIX installer function")+def test_install_sh_launcher_restores_a_missing_or_malformed_install_id(tmp_path):+ """Without the id the backend reports "", which the baked id never matches, so the launcher+ would start a new Studio on every click and never open one."""+ studio_home, data_dir, baked = _generated_sh_launcher(tmp_path)+ id_file = studio_home / "share" / "studio_install_id"+ launcher = (data_dir / "launch-studio.sh").read_text(encoding = "utf-8")+ assert launcher.index("\n_repair_studio_install_id\n") < launcher.index(+ "\n_port=$(_find_healthy_port)"+ )++ id_file.unlink()+ _run_sh_launcher_repair(data_dir, baked)+ assert id_file.read_text() == baked+ assert oct(id_file.stat().st_mode & 0o777) == "0o600"++ for broken in ("", "not-an-id", baked.upper(), baked[:63]):+ id_file.write_text(broken)+ _run_sh_launcher_repair(data_dir, baked)+ assert id_file.read_text() == baked, f"{broken!r} was not repaired"++ other = "cd34" * 16+ id_file.write_text(other + "\n")+ _run_sh_launcher_repair(data_dir, baked)+ assert id_file.read_text() == other + "\n", "a different valid id belongs to someone else"++ id_file.unlink()+ id_file.mkdir()+ _run_sh_launcher_repair(data_dir, baked)+ assert id_file.is_dir() and not any(id_file.iterdir())+ assert [p.name for p in (studio_home / "share").iterdir()] == [+ "studio_install_id"+ ], "temp file left behind"++[email protected](os.name != "posix", reason = "runs the POSIX installer function")+def test_install_sh_launcher_repair_is_a_no_op_without_the_id_path(tmp_path):+ """A studio.conf from an older install names no id file, so there is nothing to repair."""+ studio_home, data_dir, baked = _generated_sh_launcher(tmp_path)+ id_file = studio_home / "share" / "studio_install_id"+ id_file.unlink()+ old_conf = tmp_path / "old.conf"+ old_conf.write_text(+ "".join(+ l + "\n"+ for l in (data_dir / "studio.conf").read_text().splitlines()+ if not l.startswith("STUDIO_INSTALL_ID_FILE=")+ )+ )+ _run_sh_launcher_repair(data_dir, baked, conf = old_conf)+ assert not id_file.exists()+++def _ps1_launcher_repair(id_file: Path, expected: str) -> str:+ """Repair-StudioInstallId from install.ps1's launcher template, rendered as install.ps1 would."""+ src = INSTALL_PS1.read_text(encoding = "utf-8")+ tpl = src[src.index('$launcherContent = @"') :]+ start = tpl.index("function Repair-StudioInstallId {")+ end = tpl.index("\nRepair-StudioInstallId\n", start) + len("\nRepair-StudioInstallId\n")+ body = tpl[start:end].replace("`$", "$")+ quoted = str(id_file).replace("'", "''")+ return (+ "$ErrorActionPreference = 'Stop'\n"+ f"$_ExpectedStudioRootId = '{expected}'\n$_StudioInstallIdFile = '{quoted}'\n"+ + body+ + "'REPAIR_DONE'\n"+ )++[email protected](shutil.which("pwsh") is None, reason = "needs pwsh")+def test_install_ps1_launcher_restores_a_missing_or_malformed_install_id(tmp_path):+ src = INSTALL_PS1.read_text(encoding = "utf-8")+ tpl = src[src.index('$launcherContent = @"') :]+ assert "`$_StudioInstallIdFile = '$($_studioIdFile -replace \"'\", \"''\")'" in tpl+ assert tpl.index("\nRepair-StudioInstallId\n") < tpl.index("function Find-FreeLaunchPort")++ share = tmp_path / "it's share"+ share.mkdir()+ id_file = share / "studio_install_id"+ expected = "ab12" * 16+ script = tmp_path / "repair.ps1"+ script.write_text(_ps1_launcher_repair(id_file, expected), encoding = "utf-8")++ def run():+ res = run_pwsh(["pwsh", "-NoProfile", "-File", str(script)], capture_output = True, text = True)+ assert res.returncode == 0 and "REPAIR_DONE" in res.stdout, res.stderr++ run()+ assert id_file.read_text() == expected+ for broken in ("", "not-an-id", expected.upper()):+ id_file.write_text(broken)+ run()+ assert id_file.read_text() == expected, f"{broken!r} was not repaired"+ other = "cd34" * 16+ id_file.write_text(other)+ run()+ assert id_file.read_text() == other+ assert [p.name for p in share.iterdir()] == ["studio_install_id"], "temp file left behind"++def test_install_sh_never_bakes_a_planted_id_into_the_launcher(tmp_path):"""A pre-planted studio_install_id must be regenerated, not embedded.