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: harden the launcher-refresh installer fetch (#8542)
Daniel Han18dbedb8890c
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 5b6e983367c..cb061920a0e 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -6,6 +6,7 @@ import functoolsimport importlib.utilimport hashlibimport hmac+import http.clientimport jsonimport osimport platform@@ -20,6 +21,7 @@ import tempfileimport timeimport typesimport urllib.error+import urllib.parseimport urllib.requestfrom datetime import datetime, timezonefrom pathlib import Path@@ -3402,8 +3404,144 @@ def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = Noneraise typer.Exit(returncode)+# The refresh re-runs the installer with --shortcuts-only, fetched rather than shipped+# so a launcher fix reaches users without waiting for a release._INSTALLER_URL_BASH = "https://unsloth.ai/install.sh"_INSTALLER_URL_PWSH = "https://unsloth.ai/install.ps1"+# unsloth.ai 301s to raw.githubusercontent.com, so both are in the chain. Anywhere+# else, or plain http, is refused rather than followed.+_INSTALLER_FETCH_HOSTS = frozenset({"unsloth.ai", "raw.githubusercontent.com"})+_INSTALLER_FETCH_TIMEOUT = 30+# install.sh is ~250KB; the cap just stops an unbounded body from being buffered.+_INSTALLER_MAX_BYTES = 8 * 1024 * 1024+# The flag this code passes, so an installer without it cannot serve the request.+# Internal names would be tighter but can be renamed in a perfectly good installer,+# and a false negative here skips every wheel-based refresh until new Python ships.+_INSTALLER_MARKERS = {+ "install.sh": (b"--shortcuts-only",),+ "install.ps1": (b"--shortcuts-only",),+}+++def _is_allowed_installer_url(url: str) -> bool:+ """https on a known host. Applied to the first request and to every redirect."""+ split = urllib.parse.urlsplit(url)+ return split.scheme == "https" and split.hostname in _INSTALLER_FETCH_HOSTS+++class _InstallerRedirectHandler(urllib.request.HTTPRedirectHandler):+ """Keep the installer fetch on the unsloth.ai -> raw.githubusercontent chain."""++ def redirect_request(self, req, fp, code, msg, headers, newurl):+ if not _is_allowed_installer_url(newurl):+ raise urllib.error.URLError(f"refused installer redirect to {newurl}")+ return super().redirect_request(req, fp, code, msg, headers, newurl)+++def _build_installer_opener() -> urllib.request.OpenerDirector:+ """A private opener, so the redirect chain can be checked before it is followed.++ urlopen() would instead use whatever install_opener() put in place. Carrying those+ handlers over was tried and abandoned: OpenerDirector.add_handler() assigns+ handler.parent, so sharing them repoints the installed opener at this one and+ breaks every later urlopen() in the process, and copying them does not help either+ because the default HTTPSHandler here already answers first. Proxy environment+ variables and the system trust store still work, since build_opener() sets up both.+ The residue is a machine whose proxy auth or CA lives in a programmatically+ installed opener: its refresh is skipped, which the update survives, rather than+ silently pulling the installer through an unchecked path.+ """+ return urllib.request.build_opener(_InstallerRedirectHandler)+++def _looks_like_installer(body: Optional[bytes], installer_name: str) -> bool:+ """Cheap shape check before a fetched installer is executed.++ Not a trust check -- the hosts above are trusted. It stops a captive-portal page or+ an HTTP error body from being piped into bash when something in between answers.+ """+ if not body or len(body) < 512:+ return False+ head = body.lstrip()[:256].lower()+ # `<#` opens PowerShell comment-based help, which is a perfectly ordinary way for+ # install.ps1 to start, so match the actual markup rather than any leading "<".+ if not head.startswith(b"<#") and (+ head.startswith((b"<!doctype", b"<html", b"<head", b"<?xml", b"<body"))+ or b"<html" in head+ or b"<!doctype" in head+ ):+ return False+ return all(marker in body for marker in _INSTALLER_MARKERS[installer_name])+++def _fetch_installer(installer_name: str, *, verbose: bool = False) -> Optional[bytes]:+ """Fetch install.sh / install.ps1, or None if nothing usable came back."""+ url = _INSTALLER_URL_PWSH if installer_name == "install.ps1" else _INSTALLER_URL_BASH+ if not _is_allowed_installer_url(url):+ typer.echo(f" refresh-launcher refusing to fetch {installer_name} from {url}")+ return None+ try:+ opener = _build_installer_opener()+ request = urllib.request.Request(url, headers = {"User-Agent": "unsloth-studio-update"})+ with opener.open(request, timeout = _INSTALLER_FETCH_TIMEOUT) as response:+ body = response.read(_INSTALLER_MAX_BYTES + 1)+ # read(amt) does not check Content-Length; only a further read() does,+ # raising IncompleteRead. Without it a transfer cut off mid-file still+ # carries the markers and would be piped into bash half-written.+ if len(body) <= _INSTALLER_MAX_BYTES:+ body += response.read()+ except (+ urllib.error.URLError,+ # IncompleteRead / a malformed proxy response raises at the HTTP framing layer,+ # which is neither URLError nor OSError, so it would abort an already-done update.+ http.client.HTTPException,+ TimeoutError,+ OSError,+ ValueError,+ ) as exc:+ typer.echo(f" refresh-launcher skipped: could not fetch {url} ({exc})")+ return None++ if len(body) > _INSTALLER_MAX_BYTES:+ typer.echo(f" refresh-launcher skipped: oversized {installer_name} response")+ return None+ if not _looks_like_installer(body, installer_name):+ typer.echo(f" refresh-launcher skipped: response is not {installer_name}")+ return None+ if verbose:+ typer.echo(f" refresh-launcher fetched {url} ({len(body)} bytes)")+ return body+++def _installer_script_candidates(installer_name: str) -> List[Path]:+ """Source-tree installers, which outrank the network because `update --local` is+ testing its own installer, so fetching over the top of it would be wrong."""+ candidates: List[Path] = []+ local_repo = (os.environ.get("STUDIO_LOCAL_REPO") or "").strip()+ if local_repo:+ candidates.append(Path(local_repo).expanduser() / installer_name)+ # Clone or editable install: _PACKAGE_ROOT is the repo root.+ root = _PACKAGE_ROOT / installer_name+ if root not in candidates:+ candidates.append(root)+ return candidates+++def _installers_on_disk(candidates: Sequence[Path]) -> List[Path]:+ """Every candidate that exists, not just the first.++ The pre-refactor loop probed and launched in one pass, so a candidate that could+ not be launched left the next one to try before the network was reached. Returning+ only the first match would quietly drop that second chance.+ """+ found: List[Path] = []+ for candidate in candidates:+ try:+ if candidate.is_file():+ found.append(candidate)+ except OSError:+ continue+ return founddef _refresh_desktop_shortcuts(*, verbose: bool = False) -> None:@@ -3414,145 +3552,124 @@ def _refresh_desktop_shortcuts(*, verbose: bool = False) -> None:is_windows = platform.system() == "Windows"installer_name = "install.ps1" if is_windows else "install.sh"- installer_url = _INSTALLER_URL_PWSH if is_windows else _INSTALLER_URL_BASH-- # Prefer local checkout, fall back to package dir, then network fetch.- local_repo = (os.environ.get("STUDIO_LOCAL_REPO") or "").strip()- candidates: list[Path] = []- if local_repo:- candidates.append(Path(local_repo) / installer_name)- candidates.append(_PACKAGE_ROOT / installer_name)args = ["--shortcuts-only"]if verbose:args.append("--verbose")+ checkouts = _installers_on_disk(_installer_script_candidates(installer_name))+if is_windows:- ps_argv: list[str] = ["powershell.exe"]+ ps_argv: List[str] = ["powershell.exe"]# -NoProfile unconditionally, as in _run_setup_script above: gating it on the hidden# branch left the visible console path, where a profile is exactly what IS loaded.ps_argv.append("-NoProfile")if _should_hide_windows_subprocesses():ps_argv.extend(["-NoLogo", "-NonInteractive", "-WindowStyle", "Hidden"])- for script in candidates:- try:- if script.is_file():- quoted = str(script).replace("'", "''")- argv = list(ps_argv)- argv.extend(- [- "-ExecutionPolicy",- "Bypass",- "-Command",- f"& '{quoted}' {' '.join(args)} *>&1",- ]- )- result = subprocess.run(- argv,- env = env,- check = False,- **_windows_hidden_subprocess_kwargs(),- )- if result.returncode != 0:- typer.echo(f" refresh-launcher install.ps1 exited {result.returncode}")- return- except OSError:- continue-- # PyPI installs lack install.ps1: fetch + pipe to powershell stdin.- try:- request = urllib.request.Request(- installer_url, headers = {"User-Agent": "unsloth-studio-update"}- )- with urllib.request.urlopen(request, timeout = 30) as response:- installer = response.read().decode("utf-8", errors = "replace")- except (urllib.error.URLError, TimeoutError, OSError) as exc:- typer.echo(f" refresh-launcher skipped: could not fetch {installer_url} ({exc})")+ # Stops at the first candidate that launched; only an unlaunchable one moves on.+ if any(_run_installer_ps1(script, args, ps_argv, env) for script in checkouts):return+ fetched = _fetch_installer(installer_name, verbose = verbose)+ if fetched is not None:+ _run_fetched_installer_ps1(fetched, args, ps_argv, env)+ return- # install.ps1 auto-invokes `Install-UnslothStudio @args` at EOF; over- # stdin `$args` is empty so that triggers the full installer flow- # (deps, venv, prompts) before our shortcuts-only call. Strip it.- installer = re.sub(- r"(?m)^[ \t]*Install-UnslothStudio[ \t]+@args[ \t]*\r?\n?",- "",- installer,- )- # stdin-piped scripts have empty $args, so call Install-UnslothStudio explicitly.- marker_args = " ".join(args)- wrapper = installer + f"\nInstall-UnslothStudio {marker_args}\n"-- # Write to a UTF-8 BOM tempfile and use -File rather than -Command -.- # `powershell.exe -Command -` reads stdin via [Console]::InputEncoding- # (CP1252/OEM on most Windows boxes), which mangles box-drawing chars- # in install.ps1. -File reads the BOM and decodes correctly. The- # prefix gives AV/EDR engines (and grep'ing users) a clear identity.- ps1_fd, ps1_path = tempfile.mkstemp(- prefix = "unsloth-studio-refresh-",- suffix = ".ps1",- )- try:- with os.fdopen(ps1_fd, "wb") as fh:- fh.write(b"\xef\xbb\xbf" + wrapper.encode("utf-8"))- argv = list(ps_argv)- argv.extend(["-ExecutionPolicy", "Bypass", "-File", ps1_path])- try:- result = subprocess.run(- argv,- env = env,- check = False,- **_windows_hidden_subprocess_kwargs(),- )- if result.returncode != 0:- typer.echo(- f" refresh-launcher fetched install.ps1 exited {result.returncode}"- )- except OSError as exc:- typer.echo(f" refresh-launcher skipped: powershell exec failed ({exc})")- finally:- try:- os.unlink(ps1_path)- except OSError:- pass+ if any(_run_installer_bash(script, args, env) for script in checkouts):return+ fetched = _fetch_installer(installer_name, verbose = verbose)+ if fetched is not None:+ _run_fetched_installer_bash(fetched, args, env)- for script in candidates:- try:- if script.is_file():- result = subprocess.run(- ["bash", str(script), *args],- env = env,- check = False,- )- if result.returncode != 0:- typer.echo(f" refresh-launcher install.sh exited {result.returncode}")- return- except OSError:- continue- # PyPI installs lack install.sh: fetch upstream.+def _run_installer_bash(script: Path, args: Sequence[str], env: dict) -> bool:+ """False when the interpreter could not be launched, so the caller can fall back.++ The pre-refactor candidate loop caught that OSError and carried on to the next+ candidate and then to the network, silently. Returning False keeps a machine that+ cannot spawn bash for the checkout on exactly that path instead of ending the+ refresh early.+ """try:- request = urllib.request.Request(- installer_url, headers = {"User-Agent": "unsloth-studio-update"}- )- with urllib.request.urlopen(request, timeout = 30) as response:- installer = response.read()- except (urllib.error.URLError, TimeoutError, OSError) as exc:- typer.echo(f" refresh-launcher skipped: could not fetch {installer_url} ({exc})")- return+ result = subprocess.run(["bash", str(script), *args], env = env, check = False)+ except OSError:+ return False+ if result.returncode != 0:+ typer.echo(f" refresh-launcher {script.name} exited {result.returncode}")+ return True++def _run_fetched_installer_bash(installer: bytes, args: Sequence[str], env: dict) -> None:try:- result = subprocess.run(- ["bash", "-s", "--", *args],- input = installer,- env = env,- check = False,- )- if result.returncode != 0:- typer.echo(f" refresh-launcher fetched install.sh exited {result.returncode}")+ result = subprocess.run(["bash", "-s", "--", *args], input = installer, env = env, check = False)except OSError as exc:typer.echo(f" refresh-launcher skipped: bash exec failed ({exc})")+ return+ if result.returncode != 0:+ typer.echo(f" refresh-launcher fetched install.sh exited {result.returncode}")+++def _run_installer_ps1(+ script: Path, args: Sequence[str], ps_argv: Sequence[str], env: dict+) -> bool:+ """False when powershell.exe could not be launched. See _run_installer_bash."""+ quoted = str(script).replace("'", "''")+ argv = list(ps_argv)+ argv.extend(["-ExecutionPolicy", "Bypass", "-Command", f"& '{quoted}' {' '.join(args)} *>&1"])+ try:+ result = subprocess.run(argv, env = env, check = False, **_windows_hidden_subprocess_kwargs())+ except OSError:+ return False+ if result.returncode != 0:+ typer.echo(f" refresh-launcher {script.name} exited {result.returncode}")+ return True+++def _run_fetched_installer_ps1(+ installer: bytes, args: Sequence[str], ps_argv: Sequence[str], env: dict+) -> None:+ """Run a fetched install.ps1 from a tempfile.++ -File rather than `-Command -`: stdin is decoded with [Console]::InputEncoding+ (CP1252/OEM on most Windows boxes), which mangles install.ps1's box-drawing chars,+ while -File honours the BOM written below. The args go after the path so the+ installer's own `Install-UnslothStudio @args` at EOF receives them, which is why+ this no longer rewrites that line. The prefix gives AV/EDR engines (and anyone+ grepping temp) a clear identity.++ Creating and writing that file is its own failure mode: a full disk, a read-only or+ missing %TEMP%, or AV holding the handle. Those raise OSError, and the refresh runs+ after the package update has already succeeded, so they are reported and skipped+ rather than allowed to abort the command.+ """+ try:+ ps1_fd, ps1_path = tempfile.mkstemp(prefix = "unsloth-studio-refresh-", suffix = ".ps1")+ except OSError as exc:+ typer.echo(f" refresh-launcher skipped: could not create a temp script ({exc})")+ return+ try:+ try:+ with os.fdopen(ps1_fd, "wb") as fh:+ fh.write(b"\xef\xbb\xbf" + installer)+ except OSError as exc:+ typer.echo(f" refresh-launcher skipped: could not write the temp script ({exc})")+ return+ argv = list(ps_argv)+ argv.extend(["-ExecutionPolicy", "Bypass", "-File", ps1_path, *args])+ try:+ result = subprocess.run(+ argv, env = env, check = False, **_windows_hidden_subprocess_kwargs()+ )+ except OSError as exc:+ typer.echo(f" refresh-launcher skipped: powershell exec failed ({exc})")+ return+ if result.returncode != 0:+ typer.echo(f" refresh-launcher fetched install.ps1 exited {result.returncode}")+ finally:+ try:+ os.unlink(ps1_path)+ except OSError:+ pass@studio_app.command(hidden = True)diff --git a/unsloth_cli/tests/test_studio_refresh_shortcuts_installer_source.py b/unsloth_cli/tests/test_studio_refresh_shortcuts_installer_source.pynew file mode 100644index 00000000000..931739142bc--- /dev/null+++ b/unsloth_cli/tests/test_studio_refresh_shortcuts_installer_source.py@@ -0,0 +1,454 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The launcher refresh fetches install.sh / install.ps1 from unsloth.ai and runs it.++`unsloth studio update` re-runs the installer with --shortcuts-only. Fetching, rather+than shipping a copy in the wheel, is deliberate: a launcher fix then reaches users+without waiting for a release. unsloth.ai and the unslothai/unsloth repo it redirects to+are trusted, so what is left to get right is everything around the fetch, namely that a+transport error cannot abort an update that already succeeded, that a response which is+not an installer is not piped into bash, and that a source checkout still outranks the+network so `update --local` tests its own installer.+"""++from __future__ import annotations++import os+import sys+import tempfile+from pathlib import Path++import pytest++_REPO_ROOT = Path(__file__).resolve().parents[2]+if str(_REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(_REPO_ROOT))++_SH = b"#!/bin/sh\ncreate_studio_shortcuts() { :; }\n--shortcuts-only\n" + b"# pad\n" * 200+++def _studio():+ from unsloth_cli.commands import studio as _studio_mod+ return _studio_mod+++class _Result:+ returncode = 0+++def _posix(monkeypatch, tmp_path):+ """POSIX refresh with no checkout in sight, the shape of a wheel install. The tests run+ from a clone, so _PACKAGE_ROOT would otherwise short-circuit every fetch.+ """+ studio = _studio()+ monkeypatch.setattr(studio.platform, "system", lambda: "Linux")+ monkeypatch.setattr(studio, "_PACKAGE_ROOT", tmp_path / "no-checkout-here")+ monkeypatch.delenv("STUDIO_LOCAL_REPO", raising = False)+ return studio+++# ── where the installer comes from ─────────────────────────────────────────────────+++def test_the_installer_is_fetched_from_unsloth_ai():+ studio = _studio()+ assert studio._INSTALLER_URL_BASH == "https://unsloth.ai/install.sh"+ assert studio._INSTALLER_URL_PWSH == "https://unsloth.ai/install.ps1"+++def test_the_redirect_chain_is_allowed_and_nothing_else():+ """unsloth.ai 301s to raw.githubusercontent, so both are in the chain."""+ studio = _studio()+ for good in (+ "https://unsloth.ai/install.sh",+ "https://raw.githubusercontent.com/unslothai/unsloth/main/install.sh",+ ):+ assert studio._is_allowed_installer_url(good), good+ for bad in (+ "https://evil.example/install.sh",+ "http://unsloth.ai/install.sh",+ "https://unsloth.ai.evil.example/install.sh",+ ):+ assert not studio._is_allowed_installer_url(bad), bad+++def test_a_redirect_off_the_chain_is_refused():+ import urllib.error++ studio = _studio()+ handler = studio._InstallerRedirectHandler()+ try:+ handler.redirect_request(None, None, 302, "Found", {}, "https://evil.example/x.sh")+ except urllib.error.URLError:+ return+ raise AssertionError("followed a redirect off the allowed chain")+++def test_a_checkout_outranks_the_network(monkeypatch, tmp_path):+ """`update --local` is testing its own installer, so no fetch may happen."""+ studio = _posix(monkeypatch, tmp_path)+ checkout = tmp_path / "install.sh"+ checkout.write_bytes(_SH)+ monkeypatch.setenv("STUDIO_LOCAL_REPO", str(tmp_path))+ monkeypatch.setattr(+ studio,+ "_fetch_installer",+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("checkout must not fetch")),+ )+ runs = []+ monkeypatch.setattr(studio.subprocess, "run", lambda argv, **kw: runs.append(argv) or _Result())+ studio._refresh_desktop_shortcuts()+ assert runs == [["bash", str(checkout), "--shortcuts-only"]]+++def test_a_wheel_install_fetches_and_pipes_to_bash(monkeypatch, tmp_path):+ studio = _posix(monkeypatch, tmp_path)+ monkeypatch.setattr(studio, "_fetch_installer", lambda *a, **k: b"FETCHED")+ runs = []+ monkeypatch.setattr(+ studio.subprocess,+ "run",+ lambda argv, **kw: runs.append((argv, kw.get("input"))) or _Result(),+ )+ studio._refresh_desktop_shortcuts()+ assert runs == [(["bash", "-s", "--", "--shortcuts-only"], b"FETCHED")]+++# ── what a bad response must not do ────────────────────────────────────────────────+++def test_a_failed_fetch_skips_instead_of_executing(monkeypatch, tmp_path, capsys):+ studio = _posix(monkeypatch, tmp_path)+ monkeypatch.setattr(studio, "_fetch_installer", lambda *a, **k: None)+ monkeypatch.setattr(+ studio.subprocess,+ "run",+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("nothing to execute")),+ )+ studio._refresh_desktop_shortcuts()+ assert capsys.readouterr().out == ""+++def test_non_installer_responses_are_not_executed():+ """A captive portal or an error body must never be piped into bash."""+ studio = _studio()+ for body in (+ None,+ b"",+ b"<!DOCTYPE html><html><body>Sign in to WiFi</body></html>" + b"x" * 4000,+ b" <html>" + b"x" * 4000,+ b"rm -rf ~" + b"\n" * 4000,+ _SH[:200],+ ):+ assert not studio._looks_like_installer(body, "install.sh")+ assert studio._looks_like_installer(_SH, "install.sh")+++def test_http_framing_errors_are_fetch_failures_not_crashes(monkeypatch, tmp_path):+ """IncompleteRead is neither URLError nor OSError, and must not abort the update."""+ import http.client++ studio = _posix(monkeypatch, tmp_path)+ assert not issubclass(http.client.IncompleteRead, (OSError, ValueError))+ for exc in (+ http.client.IncompleteRead(b"half"),+ http.client.BadStatusLine("nonsense"),+ http.client.LineTooLong("header line"),+ ):++ class _Opener:+ def open(self, *a, **k):+ raise exc++ monkeypatch.setattr(studio.urllib.request, "build_opener", lambda *a, **k: _Opener())+ assert studio._fetch_installer("install.sh") is None, exc+++def test_oversized_and_html_responses_return_none(monkeypatch, tmp_path):+ studio = _posix(monkeypatch, tmp_path)++ class _Response:+ def __init__(self, body):+ self._body = body++ def read(self, n = None):+ return self._body[:n] if n else self._body++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ for body in (+ b"x" * (studio._INSTALLER_MAX_BYTES + 1),+ b"<html>not an installer</html>" + b"x" * 4000,+ ):++ class _Opener:+ def open(self, *a, **k):+ return _Response(body)++ monkeypatch.setattr(studio.urllib.request, "build_opener", lambda *a, **k: _Opener())+ assert studio._fetch_installer("install.sh") is None+++def test_a_truncated_body_is_never_executed(monkeypatch, tmp_path):+ """read(amt) does not check Content-Length, so a cut-off transfer must be caught.++ The markers sit early in install.sh, so a body truncated a third of the way in+ still satisfies _looks_like_installer. Without the follow-up read() that forces+ http.client to compare against the declared length, that half-written script+ would be piped into bash.+ """+ import http.client++ studio = _posix(monkeypatch, tmp_path)+ full = _SH + b"create_studio_shortcuts --shortcuts-only\n" + b"# tail\n" * 500+ short = full[: len(full) // 3]+ assert studio._looks_like_installer(+ short, "install.sh"+ ), "the truncated prefix still looks valid"++ class _Response:+ def __init__(self):+ self.calls = 0++ def read(self, n = None):+ self.calls += 1+ if self.calls == 1:+ return short+ # What http.client raises when the body is shorter than Content-Length.+ raise http.client.IncompleteRead(b"", len(full) - len(short))++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ class _Opener:+ def open(self, *a, **k):+ return _Response()++ monkeypatch.setattr(studio.urllib.request, "build_opener", lambda *a, **k: _Opener())+ assert studio._fetch_installer("install.sh") is None+++def test_a_complete_body_survives_the_completeness_check(monkeypatch, tmp_path):+ """The follow-up read() must not break the normal case: b"" means we have it all."""+ studio = _posix(monkeypatch, tmp_path)++ class _Response:+ def __init__(self):+ self.calls = 0++ def read(self, n = None):+ self.calls += 1+ return _SH if self.calls == 1 else b""++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ class _Opener:+ def open(self, *a, **k):+ return _Response()++ monkeypatch.setattr(studio.urllib.request, "build_opener", lambda *a, **k: _Opener())+ assert studio._fetch_installer("install.sh") == _SH+++def test_a_windows_tempfile_failure_skips_instead_of_aborting(monkeypatch, tmp_path):+ """The refresh runs after the package update has already succeeded.++ A full disk, a read-only %TEMP% or AV holding the handle raises OSError while+ creating or writing the script. That must not surface as a traceback from a+ command whose real work is done.+ """+ studio = _studio()+ # Captured BEFORE any patching: studio.tempfile is the tempfile module itself, so+ # patching through it replaces the global.+ real_mkstemp = tempfile.mkstemp+ calls = []++ def _boom_mkstemp(*a, **k):+ raise OSError(28, "No space left on device")++ monkeypatch.setattr(studio.tempfile, "mkstemp", _boom_mkstemp)+ monkeypatch.setattr(+ studio.subprocess,+ "run",+ lambda *a, **k: calls.append(a) or (_ for _ in ()).throw(AssertionError("must not run")),+ )+ studio._run_fetched_installer_ps1(b"x", ["--shortcuts-only"], ["powershell.exe"], {})+ assert calls == []++ # And a write that fails after the file exists still cleans up and skips.+ made = {}++ def _ok_mkstemp(*a, **k):+ fd, path = real_mkstemp(dir = tmp_path)+ made["path"] = path+ made["fd"] = fd+ return fd, path++ class _BadHandle:+ """Stands in for the real handle, and owns the descriptor like one.++ Windows refuses to unlink a file that still has an open descriptor, so a+ handle that leaked the fd would make the cleanup below fail there for a+ reason that has nothing to do with the code under test.+ """++ def __init__(self, fd):+ self._fd = fd++ def __enter__(self):+ return self++ def __exit__(self, *a):+ os.close(self._fd)+ return False++ def write(self, _data):+ raise OSError(5, "Input/output error")++ monkeypatch.setattr(studio.tempfile, "mkstemp", _ok_mkstemp)+ monkeypatch.setattr(studio.os, "fdopen", lambda fd, *a, **k: _BadHandle(fd))+ studio._run_fetched_installer_ps1(b"x", ["--shortcuts-only"], ["powershell.exe"], {})+ assert not Path(made["path"]).exists(), "the temp script must not be left behind"+ # Asserted directly so the descriptor leak is caught on Linux too, rather than+ # only surfacing as an unlink failure on Windows.+ with pytest.raises(OSError):+ os.fstat(made["fd"])+++def test_a_powershell_help_block_is_not_mistaken_for_html():+ """`<#` opens comment-based help. Rejecting it would kill every refresh silently."""+ studio = _studio()+ ps1 = (+ b"<#\n.SYNOPSIS\nUnsloth Studio installer\n#>\n"+ b"function Install-UnslothStudio { }\n--shortcuts-only\n" + b"# pad\n" * 200+ )+ assert studio._looks_like_installer(ps1, "install.ps1")+++def test_real_html_is_still_rejected():+ studio = _studio()+ for body in (+ b"<!DOCTYPE html><html><body>proxy error</body></html>" + b"--shortcuts-only\n" * 200,+ b"<html><head><title>502</title></head></html>" + b"--shortcuts-only\n" * 200,+ b"<?xml version='1.0'?><error/>" + b"--shortcuts-only\n" * 200,+ ):+ assert not studio._looks_like_installer(body, "install.sh"), body[:30]+++def test_markers_do_not_pin_internal_function_names():+ """A renamed internal helper must not disable refreshes for everyone."""+ studio = _studio()+ renamed = b"#!/bin/sh\nmake_studio_launchers() { :; }\n--shortcuts-only\n" + b"# pad\n" * 200+ assert studio._looks_like_installer(renamed, "install.sh")+ for markers in studio._INSTALLER_MARKERS.values():+ assert markers == (b"--shortcuts-only",)+++def test_a_local_installer_that_cannot_be_launched_falls_back_to_the_network(monkeypatch, tmp_path):+ """Pre-refactor the candidate loop caught the exec OSError and carried on.++ A machine that cannot spawn bash for the checkout must still reach the fetch, or a+ refactor that only reorganised the code would have stopped refreshing launchers.+ """+ studio = _studio()+ checkout = tmp_path / "checkout"+ checkout.mkdir()+ (checkout / "install.sh").write_text("#!/bin/sh\n")+ monkeypatch.setenv("STUDIO_LOCAL_REPO", str(checkout))+ # The tests run from a clone, so _PACKAGE_ROOT would otherwise supply a second+ # usable installer and the network would never be the fallback under test.+ monkeypatch.setattr(studio, "_PACKAGE_ROOT", tmp_path / "no-checkout-here")+ monkeypatch.setattr(studio.platform, "system", lambda: "Linux")++ seen = []++ def _run(argv, **kwargs):+ seen.append(list(argv))+ if str(checkout / "install.sh") in argv:+ raise OSError(8, "Exec format error")++ class _R:+ returncode = 0++ return _R()++ monkeypatch.setattr(studio.subprocess, "run", _run)+ monkeypatch.setattr(studio, "_fetch_installer", lambda *a, **k: _SH)+ studio._refresh_desktop_shortcuts()++ assert len(seen) == 2, seen+ assert str(checkout / "install.sh") in seen[0]+ assert seen[1][:3] == ["bash", "-s", "--"], seen[1]+++def test_building_the_opener_never_mutates_global_urllib(monkeypatch):+ """A private opener is needed to check redirects, but it must stay private.++ OpenerDirector.add_handler() assigns handler.parent, so an earlier attempt to carry+ the site-installed handlers over repointed that opener's own handlers at ours and+ broke every later urlopen() in the process.+ """+ studio = _studio()+ import urllib.request++ site = urllib.request.ProxyHandler({"https": "http://proxy.example:3128"})+ installed = urllib.request.build_opener(site)+ monkeypatch.setattr(urllib.request, "_opener", installed, raising = False)++ opener = studio._build_installer_opener()+ assert any(+ isinstance(h, studio._InstallerRedirectHandler) for h in opener.handlers+ ), "redirect validation was lost"+ assert site.parent is installed, "the installed opener's handler was hijacked"+ assert urllib.request._opener is installed+++def test_a_second_on_disk_installer_is_tried_before_the_network(monkeypatch, tmp_path):+ """The old loop probed and launched in one pass, so an unlaunchable candidate left+ the next one to try. Selecting only the first match would drop that second chance+ and reach for the network while a usable installer sat on disk."""+ studio = _studio()+ local = tmp_path / "local"+ pkg = tmp_path / "pkg"+ for d in (local, pkg):+ d.mkdir()+ (d / "install.sh").write_text("#!/bin/sh\n")+ monkeypatch.setenv("STUDIO_LOCAL_REPO", str(local))+ monkeypatch.setattr(studio, "_PACKAGE_ROOT", pkg)+ monkeypatch.setattr(studio.platform, "system", lambda: "Linux")++ seen = []++ def _run(argv, **kwargs):+ seen.append(list(argv))+ if str(local / "install.sh") in argv:+ raise OSError(11, "Resource temporarily unavailable")++ class _R:+ returncode = 0++ return _R()++ monkeypatch.setattr(studio.subprocess, "run", _run)+ monkeypatch.setattr(+ studio,+ "_fetch_installer",+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("a usable installer was on disk")),+ )+ studio._refresh_desktop_shortcuts()++ assert len(seen) == 2, seen+ assert str(local / "install.sh") in seen[0]+ assert str(pkg / "install.sh") in seen[1]