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
use the bundled icon first, and retry the cloudflared download (#10680)
Nilay332e258cdff4
diff --git a/.github/workflows/wheel-smoke.yml b/.github/workflows/wheel-smoke.ymlindex 015d1b152e4..5f98e0bde60 100644--- a/.github/workflows/wheel-smoke.yml+++ b/.github/workflows/wheel-smoke.yml@@ -110,6 +110,11 @@ jobs:"no frontend public": not any("studio/frontend/public/" in s for s in n),"no frontend src": not any("studio/frontend/src/" in s for s in n),"frontend dist shipped": any(s.endswith("studio/frontend/dist/index.html") for s in n),+ # The installers read these out of site-packages before falling back to GitHub.+ "shortcut icons shipped": all(+ any(s.endswith(f"studio/frontend/dist/{f}") for s in n)+ for f in ("rounded-512.png", "unsloth.ico")+ ),"no node_modules": not any("studio/frontend/node_modules/" in s for s in n),"no bun.lock": not any(s.endswith("studio/frontend/bun.lock") for s in n),}diff --git a/install.ps1 b/install.ps1index 27ae9f907d7..727c85d7b3e 100644--- a/install.ps1+++ b/install.ps1@@ -2997,6 +2997,13 @@ exit 1if ($PSScriptRoot -and $PSScriptRoot.Trim()) {$bundledIcon = Join-Path $PSScriptRoot "studio\frontend\public\unsloth.ico"}+ # The packaged .ico (studio\frontend\dist) serves irm|iex installs with no $PSScriptRoot.+ $packagedIcon = $null+ try {+ $venvRoot = Split-Path -Parent (Split-Path -Parent $ManagedPythonPath)+ $packagedIconCandidate = Join-Path $venvRoot "Lib\site-packages\studio\frontend\dist\unsloth.ico"+ if (Test-Path -LiteralPath $packagedIconCandidate) { $packagedIcon = $packagedIconCandidate }+ } catch {}$iconUrl = "https://raw.githubusercontent.com/unslothai/unsloth/main/studio/frontend/public/unsloth.ico"if (-not (Test-Path -LiteralPath $appDir)) {@@ -3338,6 +3345,12 @@ exit 0} catch {Write-StudioLine "[DEBUG] Error copying bundled icon: $($_.Exception.Message)" -ForegroundColor DarkGray}+ } elseif ($packagedIcon) {+ try {+ Copy-Item -LiteralPath $packagedIcon -Destination $iconPath -Force+ } catch {+ Write-StudioLine "[DEBUG] Error copying packaged icon: $($_.Exception.Message)" -ForegroundColor DarkGray+ }} elseif (-not (Test-Path -LiteralPath $iconPath)) {try {Invoke-WebRequest -Uri $iconUrl -OutFile $iconPath -UseBasicParsingdiff --git a/install.sh b/install.shindex 26a7ac3b926..d4d586efb41 100755--- a/install.sh+++ b/install.sh@@ -2169,6 +2169,15 @@ STUB_EOFfi_css_lnk_name_ps=$(printf '%s' "$_css_lnk_name" | sed "s/'/''/g")+ # The generated script prefers this to its download.+ _css_wsl_ico_win=""+ for _sp in "$_css_venv_dir"/lib/python*/site-packages/studio/frontend/dist; do+ if [ -f "$_sp/unsloth.ico" ] && command -v wslpath >/dev/null 2>&1; then+ _css_wsl_ico_win=$(wslpath -w "$_sp/unsloth.ico" 2>/dev/null) || _css_wsl_ico_win=""+ fi+ done+ _css_wsl_ico_win_ps=$(printf '%s' "$_css_wsl_ico_win" | sed "s/'/''/g")+# Create shortcuts via a temp PowerShell script to avoid escaping issues_css_ps1_tmp=$(mktemp /tmp/unsloth-shortcut-XXXXXX.ps1 2>/dev/null) || trueif [ -n "$_css_ps1_tmp" ]; then@@ -2184,6 +2193,13 @@ if (-not \$targetExe) { exit 1 }if (Test-Path -LiteralPath \$iconPath) {try { \$preIconHash = (Get-FileHash -LiteralPath \$iconPath -Algorithm SHA256).Hash } catch {}}+\$packagedIcon = '$_css_wsl_ico_win_ps'+if (-not (Test-Path -LiteralPath \$iconPath) -and \$packagedIcon -and (Test-Path -LiteralPath \$packagedIcon)) {+ try {+ New-Item -ItemType Directory -Force -Path \$iconDir | Out-Null+ Copy-Item -LiteralPath \$packagedIcon -Destination \$iconPath -Force -ErrorAction Stop+ } catch {}+}if (-not (Test-Path -LiteralPath \$iconPath)) {try {New-Item -ItemType Directory -Force -Path \$iconDir | Out-Nulldiff --git a/studio/backend/cloudflare_tunnel.py b/studio/backend/cloudflare_tunnel.pyindex 3aae0c44ae5..6efa299ed73 100644--- a/studio/backend/cloudflare_tunnel.py+++ b/studio/backend/cloudflare_tunnel.py@@ -11,6 +11,7 @@ domain. Best-effort throughout: any failure collapses to "no URL" and Unsloth kefrom __future__ import annotations+import loggingimport osimport platformimport re@@ -154,33 +155,105 @@ def find_cloudflared() -> Optional[str]:return None-def _download(url: str, dest: Path) -> bool:- """Download url to dest via urllib (temp file + atomic rename). Best-effort -> bool."""+_DOWNLOAD_ATTEMPTS = 3+_COPY_CHUNK = 1 << 16+++def _download(+ url: str,+ dest: Path,+ *,+ attempts: int = _DOWNLOAD_ATTEMPTS,+ timeout: float = _DOWNLOAD_TIMEOUT,+) -> bool:+ """Download url to dest via urllib (temp file + atomic rename), retried. Best-effort -> bool.++ Attempts share one budget rather than each getting `timeout`, so a failing download+ costs about what the single attempt before it did, and the terminal cases below skip the+ pauses: run.py starts the launch tunnel inline, where one of them delays the banner.+ """+ import socket+ import sslimport tempfile+ import urllib.errorimport urllib.request- tmp_path: Optional[Path] = None- try:- dest.parent.mkdir(parents = True, exist_ok = True)- with tempfile.NamedTemporaryFile(- prefix = dest.name + ".tmp-", dir = dest.parent, delete = False- ) as handle:- tmp_path = Path(handle.name)- # GitHub's CDN 403s the default Python-urllib User-Agent.- req = urllib.request.Request(url, headers = {"User-Agent": "unsloth-studio"})- with urllib.request.urlopen(req, timeout = _DOWNLOAD_TIMEOUT) as response:- shutil.copyfileobj(response, handle)- if tmp_path.stat().st_size == 0:- raise RuntimeError("empty download")- os.replace(tmp_path, dest)- return True- except Exception:- if tmp_path is not None:- try:- tmp_path.unlink(missing_ok = True)- except Exception:- pass- return False+ deadline = time.monotonic() + timeout+ last_error: Optional[BaseException] = None+ for attempt in range(1, attempts + 1):+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ break+ tmp_path: Optional[Path] = None+ # Set where the failure is known to be the transfer, because nothing else separates+ # it from the local filesystem: ENOSPC from a full disk and ENETUNREACH from a dropped+ # link both arrive as a bare OSError. Identity, so a close mid-unwind stays local.+ transfer_exc: Optional[BaseException] = None+ try:+ dest.parent.mkdir(parents = True, exist_ok = True)+ with tempfile.NamedTemporaryFile(+ prefix = dest.name + ".tmp-", dir = dest.parent, delete = False+ ) as handle:+ tmp_path = Path(handle.name)+ # GitHub's CDN 403s the default Python-urllib User-Agent.+ req = urllib.request.Request(url, headers = {"User-Agent": "unsloth-studio"})+ try:+ response = urllib.request.urlopen(req, timeout = remaining)+ except Exception as exc:+ transfer_exc = exc+ raise+ with response:+ while True:+ try:+ chunk = response.read(_COPY_CHUNK)+ except Exception as exc:+ transfer_exc = exc+ raise+ if not chunk:+ break+ handle.write(chunk)+ if tmp_path.stat().st_size == 0:+ transfer_exc = RuntimeError("empty download")+ raise transfer_exc+ os.replace(tmp_path, dest)+ return True+ except Exception as exc:+ last_error = exc+ if tmp_path is not None:+ try:+ tmp_path.unlink(missing_ok = True)+ except Exception:+ pass+ reason = getattr(exc, "reason", None)+ resolver = exc if isinstance(exc, socket.gaierror) else reason+ terminal = (+ exc is not transfer_exc+ or isinstance(exc, TimeoutError)+ or isinstance(reason, TimeoutError)+ # A verdict on the peer; its SSLError siblings are transfers that failed.+ or isinstance(exc, ssl.SSLCertVerificationError)+ or isinstance(reason, ssl.SSLCertVerificationError)+ # EAI_AGAIN is the resolver asking to be tried again; the rest are answers.+ or (isinstance(resolver, socket.gaierror) and resolver.errno != socket.EAI_AGAIN)+ or (+ isinstance(exc, urllib.error.HTTPError)+ and 400 <= exc.code < 500+ and exc.code not in (408, 429)+ )+ )+ if terminal or attempt >= attempts:+ break+ pause = 1.5 * attempt+ if time.monotonic() + pause >= deadline:+ break+ time.sleep(pause)+ logging.getLogger(__name__).warning(+ "could not download cloudflared from %s (%s); install cloudflared on PATH "+ "to use a public tunnel",+ url,+ last_error,+ )+ return Falsedef _extract_tgz_member(tgz_path: Path, dest: Path) -> bool:diff --git a/studio/backend/tests/test_cloudflare_tunnel.py b/studio/backend/tests/test_cloudflare_tunnel.pyindex b69eb943236..48ac13fd266 100644--- a/studio/backend/tests/test_cloudflare_tunnel.py+++ b/studio/backend/tests/test_cloudflare_tunnel.py@@ -9,11 +9,14 @@ checked by AST so we never import its heavy deps (uvicorn/structlog)."""import ast+import errnoimport importlib.utilimport ioimport os+import sslimport sysimport tarfile+import tempfileimport threading as _real_threadingimport typesfrom pathlib import Path@@ -1548,3 +1551,409 @@ def test_cloudflare_line_failed_does_not_claim_local_only_when_publicly_reachablassert "requested but failed to start" in outassert "reachable from the public internet" in outassert "local network only" not in out+++def test_download_retries_a_transient_failure(monkeypatch, tmp_path):+ import urllib.error+ import urllib.request++ attempts = []++ class _Resp:+ _sent = False++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ def read(self, n = -1):+ if self._sent:+ return b""+ self._sent = True+ return b"payload"++ def flaky_urlopen(req, timeout = None):+ attempts.append(req.full_url)+ if len(attempts) < 3:+ raise urllib.error.URLError("connection reset")+ return _Resp()++ monkeypatch.setattr(urllib.request, "urlopen", flaky_urlopen)+ monkeypatch.setattr(ct.time, "sleep", lambda s: None)+ dest = tmp_path / "cloudflared"+ assert ct._download("https://github.com/cloudflare/cloudflared/x", dest) is True+ assert len(attempts) == 3+ assert dest.read_bytes() == b"payload"+++def test_download_gives_up_and_says_so(monkeypatch, tmp_path, caplog):+ import logging+ import urllib.error+ import urllib.request++ def refused(req, timeout = None):+ raise urllib.error.HTTPError(req.full_url, 503, "unavailable", None, None)++ monkeypatch.setattr(urllib.request, "urlopen", refused)+ monkeypatch.setattr(ct.time, "sleep", lambda s: None)+ dest = tmp_path / "cloudflared"+ with caplog.at_level(logging.WARNING, logger = ct.__name__):+ assert ct._download("https://github.com/cloudflare/cloudflared/x", dest) is False+ assert not dest.exists() and not list(tmp_path.glob("cloudflared.tmp-*"))+ assert "could not download cloudflared" in caplog.text+++def test_download_does_not_retry_a_timeout(monkeypatch, tmp_path):+ import urllib.error+ import urllib.request++ attempts = []++ def slow(req, timeout = None):+ attempts.append(req.full_url)+ raise urllib.error.URLError(TimeoutError("timed out"))++ monkeypatch.setattr(urllib.request, "urlopen", slow)+ monkeypatch.setattr(ct.time, "sleep", lambda s: None)+ assert ct._download("https://github.com/cloudflare/cloudflared/x", tmp_path / "cf") is False+ assert len(attempts) == 1+++def test_download_does_not_retry_a_permanent_4xx(monkeypatch, tmp_path):+ """A 404 for this platform's asset is the same 404 on the next attempt. Retrying+ it three times with pauses only delays the launch banner for nothing."""+ import urllib.error+ import urllib.request++ calls = []+ slept = []++ def missing(req, timeout = None):+ calls.append(timeout)+ raise urllib.error.HTTPError(req.full_url, 404, "Not Found", None, None)++ monkeypatch.setattr(urllib.request, "urlopen", missing)+ monkeypatch.setattr(ct.time, "sleep", slept.append)+ assert ct._download("https://github.com/cloudflare/cloudflared/x", tmp_path / "cf") is False+ assert len(calls) == 1+ assert slept == []+++def test_download_still_retries_a_5xx(monkeypatch, tmp_path):+ import io+ import urllib.error+ import urllib.request++ calls = []++ def flaky(req, timeout = None):+ calls.append(timeout)+ if len(calls) == 1:+ raise urllib.error.HTTPError(req.full_url, 503, "Unavailable", None, None)+ return io.BytesIO(b"cloudflared-bytes")++ monkeypatch.setattr(urllib.request, "urlopen", flaky)+ monkeypatch.setattr(ct.time, "sleep", lambda s: None)+ dest = tmp_path / "cf"+ assert ct._download("https://github.com/cloudflare/cloudflared/x", dest) is True+ assert dest.read_bytes() == b"cloudflared-bytes"+ assert len(calls) == 2+++def test_download_retries_a_429(monkeypatch, tmp_path):+ import io+ import urllib.error+ import urllib.request++ calls = []++ def throttled(req, timeout = None):+ calls.append(timeout)+ if len(calls) == 1:+ raise urllib.error.HTTPError(req.full_url, 429, "Too Many Requests", None, None)+ return io.BytesIO(b"cloudflared-bytes")++ monkeypatch.setattr(urllib.request, "urlopen", throttled)+ monkeypatch.setattr(ct.time, "sleep", lambda s: None)+ dest = tmp_path / "cf"+ assert ct._download("https://github.com/cloudflare/cloudflared/x", dest) is True+ assert dest.read_bytes() == b"cloudflared-bytes"+ assert len(calls) == 2+++def test_download_does_not_retry_an_unresolvable_host(monkeypatch, tmp_path):+ import socket+ import urllib.error+ import urllib.request++ calls = []+ slept = []++ def offline(req, timeout = None):+ calls.append(timeout)+ raise urllib.error.URLError(+ socket.gaierror(socket.EAI_NONAME, "nodename nor servname provided")+ )++ monkeypatch.setattr(urllib.request, "urlopen", offline)+ monkeypatch.setattr(ct.time, "sleep", slept.append)+ assert ct._download("https://github.com/cloudflare/cloudflared/x", tmp_path / "cf") is False+ assert len(calls) == 1+ assert slept == []+++def test_download_retries_a_temporary_resolver_failure(monkeypatch, tmp_path):+ import io+ import socket+ import urllib.error+ import urllib.request++ calls = []++ def resolving(req, timeout = None):+ calls.append(timeout)+ if len(calls) == 1:+ raise urllib.error.URLError(+ socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")+ )+ return io.BytesIO(b"cloudflared-bytes")++ monkeypatch.setattr(urllib.request, "urlopen", resolving)+ monkeypatch.setattr(ct.time, "sleep", lambda s: None)+ dest = tmp_path / "cf"+ assert ct._download("https://github.com/cloudflare/cloudflared/x", dest) is True+ assert dest.read_bytes() == b"cloudflared-bytes"+ assert len(calls) == 2+++def test_download_does_not_retry_a_chain_it_cannot_verify(monkeypatch, tmp_path):+ """A stale CA bundle, a wrong clock and a TLS-intercepting proxy are configuration, not+ a transfer that can go better."""+ import urllib.error+ import urllib.request++ calls = []+ slept = []++ def unverifiable(req, timeout = None):+ calls.append(timeout)+ raise urllib.error.URLError(+ ssl.SSLCertVerificationError(+ 1, "[SSL: CERTIFICATE_VERIFY_FAILED] self-signed certificate"+ )+ )++ monkeypatch.setattr(urllib.request, "urlopen", unverifiable)+ monkeypatch.setattr(ct.time, "sleep", slept.append)+ assert ct._download("https://github.com/cloudflare/cloudflared/x", tmp_path / "cf") is False+ assert len(calls) == 1+ assert slept == []+++def test_download_retries_a_tls_stream_that_broke_mid_body(monkeypatch, tmp_path):+ """A bad record after some bytes is a transfer that died partway, so the half already+ written must not be published."""+ import io+ import urllib.request++ calls = []++ class Truncated(io.BytesIO):+ def read(self, size = -1):+ if not self.tell():+ return super().read(size)+ raise ssl.SSLError(1, "[SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC] bad record mac")++ def flaky(req, timeout = None):+ calls.append(timeout)+ return Truncated(b"half-a-") if len(calls) == 1 else io.BytesIO(b"cloudflared-bytes")++ monkeypatch.setattr(urllib.request, "urlopen", flaky)+ monkeypatch.setattr(ct.time, "sleep", lambda s: None)+ dest = tmp_path / "cf"+ assert ct._download("https://github.com/cloudflare/cloudflared/x", dest) is True+ assert dest.read_bytes() == b"cloudflared-bytes"+ assert len(calls) == 2+ assert list(tmp_path.glob("cf.tmp-*")) == []+++def test_download_does_not_retry_an_unwritable_cache(monkeypatch, tmp_path):+ import tempfile+ import urllib.request++ slept = []+ opened = []+ monkeypatch.setattr(ct.time, "sleep", slept.append)+ monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **k: opened.append(1))++ # Raised rather than chmod'd: a read-only directory still accepts writes on Windows.+ def denied(*a, **k):+ raise PermissionError(13, "Permission denied")++ monkeypatch.setattr(tempfile, "NamedTemporaryFile", denied)+ assert ct._download("https://github.com/cloudflare/cloudflared/x", tmp_path / "cf") is False+ assert slept == []+ assert opened == []++[email protected]("fails_on", ["write", "close", "publish"])+def test_download_does_not_retry_a_disk_that_fills_mid_transfer(monkeypatch, tmp_path, fails_on):+ """The temporary file is buffered, so a full volume surfaces at the write, at the close+ that flushes it, or at the rename. None of the three gains space on a retry."""+ import io+ import pathlib+ import urllib.request++ calls = []+ slept = []++ def responding(req, timeout = None):+ calls.append(timeout)+ return io.BytesIO(b"cloudflared-bytes")++ class _FullDisk:+ name = str(tmp_path / "cf.tmp-full")++ def __enter__(self):+ # Without it a bypassed failure hits FileNotFoundError in stat(), which passes+ # the same assertions as the failure under test.+ pathlib.Path(self.name).write_bytes(b"cloudflared-bytes")+ return self++ def __exit__(self, *a):+ self.close()+ return False++ def _no_space(self):+ raise OSError(errno.ENOSPC, "No space left on device")++ def write(self, data):+ if fails_on == "write":+ self._no_space()++ def close(self):+ if fails_on == "close":+ self._no_space()++ monkeypatch.setattr(urllib.request, "urlopen", responding)+ monkeypatch.setattr(ct.time, "sleep", slept.append)+ monkeypatch.setattr(tempfile, "NamedTemporaryFile", lambda **k: _FullDisk())+ if fails_on == "publish":++ def full_rename(src, dst):+ raise OSError(errno.ENOSPC, "No space left on device")++ monkeypatch.setattr(ct.os, "replace", full_rename)+ assert ct._download("https://github.com/cloudflare/cloudflared/x", tmp_path / "cf") is False+ assert len(calls) == 1+ assert slept == []+++def test_download_retries_an_empty_body(monkeypatch, tmp_path):+ import io+ import urllib.request++ calls = []++ def truncated(req, timeout = None):+ calls.append(timeout)+ return io.BytesIO(b"" if len(calls) == 1 else b"cloudflared-bytes")++ monkeypatch.setattr(urllib.request, "urlopen", truncated)+ monkeypatch.setattr(ct.time, "sleep", lambda s: None)+ dest = tmp_path / "cf"+ assert ct._download("https://github.com/cloudflare/cloudflared/x", dest) is True+ assert dest.read_bytes() == b"cloudflared-bytes"+ assert len(calls) == 2+++def test_download_does_not_retry_when_a_reset_unwinds_into_a_full_disk(monkeypatch, tmp_path):+ """The caller sees the full disk the reset unwound into, and it is just as full next+ time. Identity picks the error that replaced the transfer's."""+ import pathlib+ import tempfile+ import urllib.request++ calls = []+ slept = []++ class _Reset:+ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ def read(self, n = -1):+ raise ConnectionResetError(errno.ECONNRESET, "Connection reset by peer")++ class _FullOnClose:+ name = str(tmp_path / "cf.tmp-reset")++ def __enter__(self):+ pathlib.Path(self.name).write_bytes(b"partial")+ return self++ def __exit__(self, *a):+ raise OSError(errno.ENOSPC, "No space left on device")++ def write(self, data):+ pass++ def responding(req, timeout = None):+ calls.append(timeout)+ return _Reset()++ monkeypatch.setattr(urllib.request, "urlopen", responding)+ monkeypatch.setattr(ct.time, "sleep", slept.append)+ monkeypatch.setattr(tempfile, "NamedTemporaryFile", lambda **k: _FullOnClose())+ assert ct._download("https://github.com/cloudflare/cloudflared/x", tmp_path / "cf") is False+ assert len(calls) == 1+ assert slept == []+++def test_download_retries_share_one_deadline(monkeypatch, tmp_path):+ """A transfer that stalls for most of the budget and then resets gets what is left,+ not a fresh budget. Three fresh budgets would hold the launch banner for minutes."""+ import urllib.request++ clock = [1000.0]+ monkeypatch.setattr(ct.time, "monotonic", lambda: clock[0])+ monkeypatch.setattr(ct.time, "sleep", lambda s: clock.__setitem__(0, clock[0] + s))+ timeouts = []++ def stalls_then_resets(req, timeout = None):+ timeouts.append(timeout)+ clock[0] += 59.0 # the body trickled for almost the whole budget+ raise ConnectionResetError("peer reset")++ monkeypatch.setattr(urllib.request, "urlopen", stalls_then_resets)+ assert (+ ct._download("https://github.com/cloudflare/cloudflared/x", tmp_path / "cf", timeout = 60)+ is False+ )+ # 1s left is less than the 1.5s pause, so there is no second attempt.+ assert timeouts == [60.0]+++def test_download_later_attempts_get_only_the_remaining_time(monkeypatch, tmp_path):+ import urllib.request++ clock = [1000.0]+ monkeypatch.setattr(ct.time, "monotonic", lambda: clock[0])+ monkeypatch.setattr(ct.time, "sleep", lambda s: clock.__setitem__(0, clock[0] + s))+ timeouts = []++ def quick_resets(req, timeout = None):+ timeouts.append(round(timeout, 1))+ clock[0] += 10.0+ raise ConnectionResetError("peer reset")++ monkeypatch.setattr(urllib.request, "urlopen", quick_resets)+ assert (+ ct._download("https://github.com/cloudflare/cloudflared/x", tmp_path / "cf", timeout = 60)+ is False+ )+ assert timeouts == [60.0, 48.5, 35.5]diff --git a/studio/backend/tests/test_transformers_version_optional_tiktoken.py b/studio/backend/tests/test_transformers_version_optional_tiktoken.pyindex a19bac7dc7c..39902e1dce7 100644--- a/studio/backend/tests/test_transformers_version_optional_tiktoken.py+++ b/studio/backend/tests/test_transformers_version_optional_tiktoken.py@@ -1024,6 +1024,8 @@ def test_a_failed_first_install_leaves_nothing_the_offline_guard_would_keep(tmp_assert tv._sidecar_has_content(str(root2)) is False(root2 / "keep.txt").write_text("", encoding = "utf-8")assert tv._sidecar_has_content(str(root2)) is True++def test_an_unlockable_filesystem_is_not_waited_out(tmp_path, monkeypatch) -> None:"""A mount that cannot lock answers at once. Retrying it spent the whole 120 secondbound asleep inside a model activation, to arrive at the same answer."""diff --git a/tests/test_installer_shortcut_icons.py b/tests/test_installer_shortcut_icons.pyindex fde6797e29d..294764a3495 100644--- a/tests/test_installer_shortcut_icons.py+++ b/tests/test_installer_shortcut_icons.py@@ -11,6 +11,7 @@ import textwrapfrom pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwshREPO_ROOT = Path(__file__).resolve().parents[1]INSTALL_SH = REPO_ROOT / "install.sh"@@ -126,3 +127,198 @@ def test_macos_prebuilt_copy_failure_runs_generated_icns_fallback(tmp_path):)assert result.returncode == 0, result.stderrassert (resources / "AppIcon.icns").read_text() == "generated"+++INSTALL_PS1 = REPO_ROOT / "install.ps1"+++def _wsl_packaged_icon_block() -> str:+ source = INSTALL_SH.read_text(encoding = "utf-8")+ start = source.index(' _css_wsl_ico_win=""')+ end = source.index(" # Create shortcuts via a temp PowerShell script", start)+ return textwrap.dedent(source[start:end])++[email protected](shutil.which("bash") is None, reason = "bash is unavailable")+def test_wsl_shortcut_reads_the_packaged_ico_out_of_site_packages(tmp_path):+ """A WSL install that found the .ico in site-packages must hand the shortcut script a+ Windows path."""+ dist = (+ tmp_path / "venv" / "lib" / "python3.12" / "site-packages" / "studio" / "frontend" / "dist"+ )+ dist.mkdir(parents = True)+ (dist / "unsloth.ico").write_bytes(b"\x00\x00\x01\x00icon")+ fake_bin = tmp_path / "bin"+ fake_bin.mkdir()+ (fake_bin / "wslpath").write_text("#!/bin/sh\nprintf 'C:\\\\wsl\\\\%s' \"${2##*/}\"\n")+ (fake_bin / "wslpath").chmod(0o755)++ script = "\n".join(+ [+ f"_css_venv_dir={shlex.quote(str(tmp_path / 'venv'))}",+ _wsl_packaged_icon_block(),+ 'printf "%s" "$_css_wsl_ico_win_ps"',+ ]+ )+ result = subprocess.run(+ ["bash", "-c", script],+ env = {"PATH": f"{fake_bin}:/usr/bin:/bin"},+ check = True,+ capture_output = True,+ text = True,+ )+ assert result.stdout == "C:\\wsl\\unsloth.ico"++[email protected](shutil.which("bash") is None, reason = "bash is unavailable")[email protected]("ships_icon", [True, False])+def test_wsl_shortcut_falls_back_when_the_ico_cannot_be_translated(tmp_path, ships_icon):+ dist = (+ tmp_path / "venv" / "lib" / "python3.12" / "site-packages" / "studio" / "frontend" / "dist"+ )+ dist.mkdir(parents = True)+ if ships_icon:+ (dist / "unsloth.ico").write_bytes(b"\x00\x00\x01\x00icon")+ fake_bin = tmp_path / "bin"+ fake_bin.mkdir()+ (fake_bin / "wslpath").write_text("#!/bin/sh\nprintf 'wslpath: cannot translate'\nexit 1\n")+ (fake_bin / "wslpath").chmod(0o755)++ script = "\n".join(+ [+ f"_css_venv_dir={shlex.quote(str(tmp_path / 'venv'))}",+ _wsl_packaged_icon_block(),+ 'printf "%s" "$_css_wsl_ico_win_ps"',+ ]+ )+ result = subprocess.run(+ ["bash", "-c", script],+ env = {"PATH": f"{fake_bin}:/usr/bin:/bin"},+ check = True,+ capture_output = True,+ text = True,+ )+ assert result.stdout == ""++[email protected](shutil.which("pwsh") is None, reason = "pwsh is unavailable")+def test_windows_shortcut_prefers_the_packaged_icon_over_the_download(tmp_path):+ """An irm|iex install has no $PSScriptRoot and so no $bundledIcon, which is where the+ packaged .ico has to win."""+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ start = source.index(" $hasValidIcon = $false")+ end = source.index(" if (Test-Path -LiteralPath $iconPath) {", start)+ block = textwrap.dedent(source[start:end])++ packaged = tmp_path / "packaged.ico"+ packaged.write_bytes(b"\x00\x00\x01\x00packaged")+ icon_path = tmp_path / "unsloth.ico"++ def run(packaged_icon: str) -> str:+ icon_path.unlink(missing_ok = True)+ script = "\n".join(+ [+ "function Write-StudioLine { }",+ "function Invoke-WebRequest { Write-Output 'DOWNLOADED' }",+ "$bundledIcon = $null",+ f"$packagedIcon = {packaged_icon}",+ f"$iconPath = '{icon_path}'",+ "$iconUrl = 'https://example.invalid/unsloth.ico'",+ block,+ ]+ )+ # run_pwsh, not subprocess.run: a pwsh killed at startup never read $packagedIcon,+ # and check = True would report that as the precedence being wrong.+ return run_pwsh(+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],+ check = True,+ capture_output = True,+ text = True,+ ).stdout++ assert "DOWNLOADED" not in run(f"'{packaged}'")+ assert icon_path.read_bytes() == b"\x00\x00\x01\x00packaged"+ assert "DOWNLOADED" in run("$null")++[email protected](shutil.which("pwsh") is None, reason = "pwsh is unavailable")+def test_windows_packaged_icon_is_found_next_to_the_managed_python(tmp_path):+ """Resolve one level too few or too many and nothing is found, so the icon is downloaded."""+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ start = source.index(" $packagedIcon = $null")+ end = source.index(' $iconUrl = "https://raw.githubusercontent.com', start)+ block = textwrap.dedent(source[start:end])++ venv = tmp_path / "venv"+ (venv / "Scripts").mkdir(parents = True)+ (venv / "Scripts" / "python.exe").write_text("")+ icon = venv / "Lib" / "site-packages" / "studio" / "frontend" / "dist" / "unsloth.ico"+ icon.parent.mkdir(parents = True)+ icon.write_bytes(b"\x00\x00\x01\x00packaged")++ script = "\n".join(+ [+ f"$ManagedPythonPath = '{venv / 'Scripts' / 'python.exe'}'",+ block,+ "Write-Output $packagedIcon",+ ]+ )+ found = run_pwsh(+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],+ check = True,+ capture_output = True,+ text = True,+ ).stdout.strip()+ assert found.startswith(str(venv))+ assert found.endswith("unsloth.ico")+++ shutil.which("pwsh") is None or shutil.which("bash") is None,+ reason = "pwsh and bash are both required",+)+def test_wsl_shortcut_script_copies_the_packaged_ico_instead_of_downloading(tmp_path):+ """The half of the WSL path that runs under Windows, piped through bash because+ install.sh writes it in an unquoted heredoc: a `$` that lost its backslash expands to+ nothing and strips the path off Copy-Item, which no later check would catch."""+ source = INSTALL_SH.read_text(encoding = "utf-8")+ start = source.index("\\$packagedIcon = '$_css_wsl_ico_win_ps'")+ end = source.index("\\$hasIcon = \\$false", start)+ packaged = tmp_path / "packaged.ico"+ packaged.write_bytes(b"\x00\x00\x01\x00packaged")+ icon_dir = tmp_path / "Unsloth Studio"+ block = subprocess.run(+ [+ "bash",+ "-c",+ "\n".join(+ [+ f"_css_wsl_ico_win_ps={shlex.quote(str(packaged))}",+ "cat << WSLPS1_EOF",+ source[start:end],+ "WSLPS1_EOF",+ ]+ ),+ ],+ env = {"PATH": "/usr/bin:/bin"},+ check = True,+ capture_output = True,+ text = True,+ ).stdout++ script = "\n".join(+ [+ "function Invoke-WebRequest { Write-Output 'DOWNLOADED' }",+ f"$iconDir = '{icon_dir}'",+ f"$iconPath = '{icon_dir / 'unsloth.ico'}'",+ block,+ ]+ )+ result = run_pwsh(+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],+ check = True,+ capture_output = True,+ text = True,+ )+ assert "DOWNLOADED" not in result.stdout+ assert (icon_dir / "unsloth.ico").read_bytes() == b"\x00\x00\x01\x00packaged"