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: auto Cloudflare tunnel for 0.0.0.0 launches (#6204)
Daniel Han1a99980b469c
diff --git a/studio/backend/cloudflare_tunnel.py b/studio/backend/cloudflare_tunnel.pynew file mode 100644index 00000000000..7c088b6e1e2--- /dev/null+++ b/studio/backend/cloudflare_tunnel.py@@ -0,0 +1,302 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Free Cloudflare quick tunnel for Studio's 0.0.0.0 launches.++The raw http://<ip>:<port> is often unreachable (https-vs-http, blocked ports,+closed security groups); a cloudflared quick tunnel gives a free+https://*.trycloudflare.com URL that works anywhere, with no account or domain.++Best-effort throughout: any failure collapses to "no URL" and Studio keeps+running. Stdlib only (back-end imports are lazy) so it is safe to import early.+"""++from __future__ import annotations++import os+import platform+import re+import shutil+import subprocess+import sys+import threading+from pathlib import Path+from typing import Optional, Tuple++# cloudflared logs the quick-tunnel URL; match only the URL so we do not depend+# on the surrounding wording, which Cloudflare may change.+_URL_RE = re.compile(r"https://[A-Za-z0-9-]+\.trycloudflare\.com")++_RELEASE_BASE = "https://github.com/cloudflare/cloudflared/releases/latest/download"++_URL_TIMEOUT = 15.0 # seconds to wait for the public URL before giving up+_DOWNLOAD_TIMEOUT = 60 # urlopen timeout for the one-time binary download+++def _windows_hidden_kwargs() -> dict:+ """Suppress a child console window on Windows; no-op elsewhere."""+ if sys.platform != "win32":+ return {}+ flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)+ return {"creationflags": flags} if flags else {}+++def _asset_name() -> Optional[Tuple[str, bool]]:+ """(release asset filename, is_tgz) for this OS/arch, or None if unsupported."""+ system = platform.system().lower()+ machine = platform.machine().lower()+ is_x64 = machine in ("x86_64", "amd64", "x64")+ is_arm64 = machine in ("aarch64", "arm64")+ is_x86 = machine in ("i386", "i686", "x86")+ if system == "linux":+ if is_x64:+ return ("cloudflared-linux-amd64", False)+ if is_arm64:+ return ("cloudflared-linux-arm64", False)+ elif system == "darwin":+ if is_arm64:+ return ("cloudflared-darwin-arm64.tgz", True)+ if is_x64:+ return ("cloudflared-darwin-amd64.tgz", True)+ elif system == "windows":+ if is_x64:+ return ("cloudflared-windows-amd64.exe", False)+ if is_x86:+ return ("cloudflared-windows-386.exe", False)+ return None+++def _cache_path() -> Optional[Path]:+ """studio_bin_root()/cloudflared(.exe), or None if the studio home is unresolvable."""+ try:+ from utils.paths.storage_roots import studio_bin_root # lazy: backend-only import+ except Exception:+ return None+ name = "cloudflared.exe" if sys.platform == "win32" else "cloudflared"+ return studio_bin_root() / name+++def find_cloudflared() -> Optional[str]:+ """Locate an existing cloudflared: PATH first, then the Studio bin cache."""+ on_path = shutil.which("cloudflared")+ if on_path:+ return on_path+ cached = _cache_path()+ if cached is not None and cached.is_file() and os.access(cached, os.X_OK):+ return str(cached)+ return None+++def _download(url: str, dest: Path) -> bool:+ """Download url to dest via urllib (temp file + atomic rename). Best-effort -> bool."""+ import tempfile+ import 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+++def _extract_tgz_member(tgz_path: Path, dest: Path) -> bool:+ """Extract just the `cloudflared` member from a darwin .tgz to dest.++ Rejects absolute paths and `..` traversal so a hostile archive cannot write+ outside dest. Best-effort -> bool.+ """+ import tarfile+ try:+ with tarfile.open(tgz_path, "r:gz") as tar:+ member = None+ for m in tar.getmembers():+ if not m.isfile() or os.path.basename(m.name) != "cloudflared":+ continue+ if m.name.startswith("/") or ".." in Path(m.name).parts:+ continue+ member = m+ break+ if member is None:+ return False+ src = tar.extractfile(member)+ if src is None:+ return False+ with src, open(dest, "wb") as out:+ shutil.copyfileobj(src, out)+ return True+ except Exception:+ return False+++def ensure_cloudflared() -> Optional[str]:+ """Return a cloudflared path, downloading + caching the binary once if missing."""+ existing = find_cloudflared()+ if existing:+ return existing+ asset = _asset_name()+ cached = _cache_path()+ if asset is None or cached is None:+ return None+ name, is_tgz = asset+ url = f"{_RELEASE_BASE}/{name}"+ try:+ cached.parent.mkdir(parents = True, exist_ok = True)+ if is_tgz:+ tgz = cached.with_suffix(".tgz")+ if not _download(url, tgz) or not _extract_tgz_member(tgz, cached):+ tgz.unlink(missing_ok = True)+ return None+ tgz.unlink(missing_ok = True)+ elif not _download(url, cached):+ return None+ if sys.platform != "win32":+ os.chmod(cached, 0o755)+ return str(cached)+ except Exception:+ return None+++class CloudflareTunnel:+ """A cloudflared quick tunnel to http://localhost:<port>. Best-effort throughout.++ Use localhost (not the wildcard bind) as the tunnel origin so cloudflared's+ upstream stays local-only.+ """++ def __init__(self, port: int, binary: str):+ self.port = port+ self.binary = binary+ self._proc: Optional[subprocess.Popen] = None+ self._lock = threading.Lock()+ self._url_event = threading.Event()+ self.url: Optional[str] = None+ self.error: Optional[str] = None++ def start(self) -> None:+ cmd = [+ self.binary,+ "tunnel",+ "--url",+ f"http://localhost:{self.port}",+ "--no-autoupdate",+ ]+ proc = subprocess.Popen(+ cmd,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ stdin = subprocess.DEVNULL,+ text = True,+ errors = "replace",+ bufsize = 1,+ **_windows_hidden_kwargs(),+ )+ with self._lock:+ self._proc = proc+ threading.Thread(+ target = self._reader, args = (proc,), name = "cloudflared-reader", daemon = True+ ).start()++ def _reader(self, proc: subprocess.Popen) -> None:+ # Drain cloudflared's output, capture the first trycloudflare URL, and+ # keep draining so it never blocks on a full pipe.+ try:+ if proc.stdout is not None:+ for line in proc.stdout:+ if self.url is None:+ match = _URL_RE.search(line)+ if match:+ self.url = match.group(0)+ self._url_event.set()+ except Exception:+ pass+ finally:+ if self.url is None:+ self.error = "cloudflared exited before emitting a tunnel URL"+ self._url_event.set()++ def wait_for_url(self, timeout: float = _URL_TIMEOUT) -> Optional[str]:+ self._url_event.wait(timeout)+ return self.url++ def stop(self) -> None:+ """Terminate the tunnel. Idempotent and safe to call from a signal handler."""+ with self._lock:+ proc, self._proc = self._proc, None+ if proc is None:+ return+ try:+ if proc.poll() is None:+ proc.terminate()+ try:+ proc.wait(timeout = 5)+ except subprocess.TimeoutExpired:+ proc.kill()+ try:+ proc.wait(timeout = 5)+ except Exception:+ pass+ except Exception:+ pass+++# Single serving process per Studio launch, so one module-level tunnel handle is+# enough; the lock guards the start/stop/shutdown races.+_active_tunnel: Optional[CloudflareTunnel] = None+_active_lock = threading.Lock()+++def start_studio_tunnel(port: int, timeout: float = _URL_TIMEOUT) -> Optional[str]:+ """Start a quick tunnel and return its public URL, or None (best-effort).++ On any failure (no binary, no URL within timeout, early crash) the tunnel is+ stopped and None is returned, so the caller prints a hint and continues.+ """+ global _active_tunnel+ binary = ensure_cloudflared()+ if not binary:+ return None+ tunnel = CloudflareTunnel(port, binary)+ # Register before start/wait so a shutdown during the URL wait can stop it.+ with _active_lock:+ prior, _active_tunnel = _active_tunnel, tunnel+ if prior is not None:+ prior.stop()+ try:+ tunnel.start()+ url = tunnel.wait_for_url(timeout)+ except Exception:+ url = None+ if url:+ return url+ # No URL (or crash): drop it unless a concurrent shutdown already replaced it.+ with _active_lock:+ if _active_tunnel is tunnel:+ _active_tunnel = None+ tunnel.stop()+ return None+++def stop_studio_tunnel() -> None:+ """Terminate the active tunnel, if any. Idempotent."""+ global _active_tunnel+ with _active_lock:+ tunnel, _active_tunnel = _active_tunnel, None+ if tunnel is not None:+ tunnel.stop()diff --git a/studio/backend/run.py b/studio/backend/run.pyindex 4619cb849ce..32dfe06a18a 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -414,9 +414,26 @@ def _emit_startup_output(host: str, port: int, display_host: str) -> None:print_studio_stop_hint()elif wildcard_bind:_verify_global_reachability(display_host, port)+ _print_cloudflare_line()print_studio_stop_hint()+def _print_cloudflare_line() -> None:+ """Print the Cloudflare quick-tunnel URL for 0.0.0.0 binds, if one is up.++ Reads the module-level URL set by ``run_server``. Prints nothing when the+ tunnel is disabled or failed -- failures are silently ignored.+ """+ if not _cloudflare_url:+ return+ from startup_banner import stdout_supports_color++ accent = "\033[38;5;150;1m"+ reset = "\033[0m"+ line = f" Secure link access via Cloudflare: {_cloudflare_url}"+ print(f"{accent}{line}{reset}" if stdout_supports_color() else line)++def _get_pid_on_port(port: int) -> "tuple[int, str] | None":"""Return (pid, process_name) listening on *port*, or None.@@ -584,6 +601,13 @@ def _graceful_shutdown(server = None):except Exception as e:logger.warning("Error shutting down llama-server: %s", e)+ # 6. Stop the Cloudflare tunnel (if started).+ try:+ from cloudflare_tunnel import stop_studio_tunnel+ stop_studio_tunnel()+ except Exception as e:+ logger.warning("Error stopping Cloudflare tunnel: %s", e)+logger.info("All subprocesses cleaned up")@@ -594,6 +618,10 @@ _server = None# Shutdown event -- wakes the main loop on signal._shutdown_event = None+# trycloudflare.com URL for 0.0.0.0 binds (set by run_server, read by the banner);+# None when there is no tunnel (loopback, disabled, or a silently-ignored failure).+_cloudflare_url = None+_DEFAULT_FRONTEND_PATH = Path(__file__).resolve().parent.parent / "frontend" / "dist"@@ -769,6 +797,7 @@ def run_server(silent: bool = False,api_only: bool = False,llama_parallel_slots: int = 1,+ cloudflare: bool = True,):"""Start the FastAPI server.@@ -973,6 +1002,21 @@ def run_server(if api_only:print(f"TAURI_PORT={port}", flush = True)+ # Free trycloudflare.com tunnel for 0.0.0.0 binds (the raw ip:port is often+ # unreachable). Started pre-banner and even when silent so the CLI banner can+ # read app.state.cloudflare_url; torn down by _graceful_shutdown.+ global _cloudflare_url+ _cloudflare_url = None+ app.state.cloudflare_url = None+ _cloudflare_enabled = cloudflare and host == "0.0.0.0" and not api_only and not _IS_COLAB+ if _cloudflare_enabled:+ try: # best-effort: any failure must not block startup+ from cloudflare_tunnel import start_studio_tunnel+ _cloudflare_url = start_studio_tunnel(port)+ app.state.cloudflare_url = _cloudflare_url+ except Exception as e:+ logger.debug("Cloudflare tunnel skipped: %s", e)+if not silent:_emit_startup_output(host, port, display_host)@@ -1011,6 +1055,13 @@ if __name__ == "__main__":action = "store_true",help = "API server only, no frontend (for Tauri)",)+ parser.add_argument(+ "--cloudflare",+ action = argparse.BooleanOptionalAction,+ default = True,+ help = "Auto-create a free Cloudflare HTTPS tunnel when bound to 0.0.0.0 "+ "(default on; --no-cloudflare to disable)",+ )# Mirror unsloth_cli/commands/studio.py's _PARALLEL_*. Default 1 is for direct# backend launches; `unsloth studio run` always passes its own value (4)._PARALLEL_MIN = 1@@ -1037,6 +1088,7 @@ if __name__ == "__main__":silent = args.silent,api_only = args.api_only,llama_parallel_slots = args.parallel,+ cloudflare = args.cloudflare,)if args.frontend is not None:kwargs["frontend_path"] = Path(args.frontend)diff --git a/studio/backend/tests/test_cloudflare_tunnel.py b/studio/backend/tests/test_cloudflare_tunnel.pynew file mode 100644index 00000000000..8208f7f83f3--- /dev/null+++ b/studio/backend/tests/test_cloudflare_tunnel.py@@ -0,0 +1,425 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for the Cloudflare quick-tunnel helper and run.py wiring.++cloudflare_tunnel.py is stdlib-only (storage_roots is imported lazily), so it+loads via spec_from_file_location without the studio venv. run.py defaults are+checked by AST so we never import its heavy deps (uvicorn/structlog).+"""++import ast+import importlib.util+import io+import sys+import tarfile+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+_CT_PY = _BACKEND / "cloudflare_tunnel.py"+_RUN_PY = _BACKEND / "run.py"+++def _load_ct():+ spec = importlib.util.spec_from_file_location("cloudflare_tunnel", _CT_PY)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++ct = _load_ct()+++# ── URL parsing ──────────────────────────────────────────────────────+++def test_url_regex_extracts_and_ignores_noise():+ blob = (+ "2026-06-11T10:00:00Z INF Thank you for trying Cloudflare Tunnel.\n"+ "2026-06-11T10:00:01Z INF Requesting new quick Tunnel on trycloudflare.com...\n"+ "2026-06-11T10:00:01Z INF | https://setting-democracy-gathering.trycloudflare.com |\n"+ "2026-06-11T10:00:02Z INF Registered tunnel connection https://not-the-url.example.com\n"+ )+ m = ct._URL_RE.search(blob)+ assert m is not None+ assert m.group(0) == "https://setting-democracy-gathering.trycloudflare.com"+++def test_url_regex_no_match_on_unrelated():+ assert ct._URL_RE.search("INF connecting to https://api.cloudflare.com/v4") is None+++# ── asset mapping ────────────────────────────────────────────────────+++ "system,machine,expected",+ [+ ("Linux", "x86_64", ("cloudflared-linux-amd64", False)),+ ("Linux", "aarch64", ("cloudflared-linux-arm64", False)),+ ("Darwin", "arm64", ("cloudflared-darwin-arm64.tgz", True)),+ ("Darwin", "x86_64", ("cloudflared-darwin-amd64.tgz", True)),+ ("Windows", "AMD64", ("cloudflared-windows-amd64.exe", False)),+ ("Windows", "x86", ("cloudflared-windows-386.exe", False)),+ ("Linux", "mips", None),+ ("Plan9", "x86_64", None),+ ],+)+def test_asset_name(monkeypatch, system, machine, expected):+ monkeypatch.setattr(ct.platform, "system", lambda: system)+ monkeypatch.setattr(ct.platform, "machine", lambda: machine)+ assert ct._asset_name() == expected+++# ── binary discovery ─────────────────────────────────────────────────+++def test_find_cloudflared_prefers_path(monkeypatch):+ monkeypatch.setattr(ct.shutil, "which", lambda name: "/usr/local/bin/cloudflared")+ assert ct.find_cloudflared() == "/usr/local/bin/cloudflared"+++def test_find_cloudflared_falls_back_to_cache(monkeypatch, tmp_path):+ cached = tmp_path / "cloudflared"+ cached.write_text("#!/bin/sh\n")+ cached.chmod(0o755)+ monkeypatch.setattr(ct.shutil, "which", lambda name: None)+ monkeypatch.setattr(ct, "_cache_path", lambda: cached)+ assert ct.find_cloudflared() == str(cached)+++def test_find_cloudflared_none_when_missing(monkeypatch, tmp_path):+ monkeypatch.setattr(ct.shutil, "which", lambda name: None)+ monkeypatch.setattr(ct, "_cache_path", lambda: tmp_path / "absent")+ assert ct.find_cloudflared() is None+++# ── ensure / download ────────────────────────────────────────────────+++def test_ensure_downloads_and_chmods_when_missing(monkeypatch, tmp_path):+ cached = tmp_path / "cloudflared"+ monkeypatch.setattr(ct, "find_cloudflared", lambda: None)+ monkeypatch.setattr(ct, "_asset_name", lambda: ("cloudflared-linux-amd64", False))+ monkeypatch.setattr(ct, "_cache_path", lambda: cached)++ def fake_download(url, dest):+ assert url.endswith("/cloudflared-linux-amd64")+ dest.write_bytes(b"ELF-ish")+ return True++ monkeypatch.setattr(ct, "_download", fake_download)+ monkeypatch.setattr(ct.sys, "platform", "linux")+ path = ct.ensure_cloudflared()+ assert path == str(cached)+ assert cached.exists()+ assert cached.stat().st_mode & 0o111 # executable bit set+++def test_ensure_returns_none_on_download_failure(monkeypatch, tmp_path):+ monkeypatch.setattr(ct, "find_cloudflared", lambda: None)+ monkeypatch.setattr(ct, "_asset_name", lambda: ("cloudflared-linux-amd64", False))+ monkeypatch.setattr(ct, "_cache_path", lambda: tmp_path / "cloudflared")+ monkeypatch.setattr(ct, "_download", lambda url, dest: False)+ assert ct.ensure_cloudflared() is None+++def test_ensure_returns_none_for_unsupported_arch(monkeypatch, tmp_path):+ monkeypatch.setattr(ct, "find_cloudflared", lambda: None)+ monkeypatch.setattr(ct, "_asset_name", lambda: None)+ monkeypatch.setattr(ct, "_cache_path", lambda: tmp_path / "cloudflared")+ assert ct.ensure_cloudflared() is None+++def test_download_sets_user_agent(monkeypatch, tmp_path):+ import urllib.request++ captured = {}++ 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 fake_urlopen(req, timeout = None):+ captured["ua"] = req.get_header("User-agent")+ return _Resp()++ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)+ dest = tmp_path / "cloudflared"+ assert ct._download("https://github.com/cloudflare/cloudflared/x", dest) is True+ assert captured["ua"] == "unsloth-studio" # GitHub CDN 403s the default UA+ assert dest.read_bytes() == b"payload"+++# ── cross-platform: Windows (.exe), macOS (.tgz) ─────────────────────+++def test_cache_path_uses_exe_on_windows(monkeypatch, tmp_path):+ import types++ fake_sr = types.ModuleType("utils.paths.storage_roots")+ fake_sr.studio_bin_root = lambda: tmp_path+ monkeypatch.setitem(sys.modules, "utils.paths.storage_roots", fake_sr)+ monkeypatch.setattr(ct.sys, "platform", "win32")+ assert ct._cache_path() == tmp_path / "cloudflared.exe"+++def test_ensure_windows_downloads_exe(monkeypatch, tmp_path):+ cached = tmp_path / "cloudflared.exe"+ monkeypatch.setattr(ct, "find_cloudflared", lambda: None)+ monkeypatch.setattr(ct, "_asset_name", lambda: ("cloudflared-windows-amd64.exe", False))+ monkeypatch.setattr(ct, "_cache_path", lambda: cached)+ monkeypatch.setattr(ct.sys, "platform", "win32")++ def fake_download(url, dest):+ assert url.endswith("/cloudflared-windows-amd64.exe")+ dest.write_bytes(b"MZ") # PE header magic+ return True++ monkeypatch.setattr(ct, "_download", fake_download)+ # chmod is skipped on Windows; would raise on a path that does not exist yet.+ monkeypatch.setattr(ct.os, "chmod", lambda *a, **k: pytest.fail("chmod called on win32"))+ assert ct.ensure_cloudflared() == str(cached)+ assert cached.read_bytes() == b"MZ"+++def test_ensure_macos_extracts_tgz_and_chmods(monkeypatch, tmp_path):+ cached = tmp_path / "cloudflared"+ monkeypatch.setattr(ct, "find_cloudflared", lambda: None)+ monkeypatch.setattr(ct, "_asset_name", lambda: ("cloudflared-darwin-arm64.tgz", True))+ monkeypatch.setattr(ct, "_cache_path", lambda: cached)+ monkeypatch.setattr(ct.sys, "platform", "darwin")++ def fake_download(url, dest):+ # dest is cached.with_suffix(".tgz"); write a real archive there.+ assert url.endswith("/cloudflared-darwin-arm64.tgz")+ with tarfile.open(dest, "w:gz") as tar:+ data = b"mach-o"+ info = tarfile.TarInfo(name = "cloudflared")+ info.size = len(data)+ tar.addfile(info, io.BytesIO(data))+ return True++ monkeypatch.setattr(ct, "_download", fake_download)+ path = ct.ensure_cloudflared()+ assert path == str(cached)+ assert cached.read_bytes() == b"mach-o"+ assert cached.stat().st_mode & 0o111 # chmod applied on posix+ assert not cached.with_suffix(".tgz").exists() # temp archive cleaned up+++# ── .tgz extraction (darwin) ─────────────────────────────────────────+++def _make_tgz(+ tmp_path,+ member_name,+ data = b"bin",+):+ tgz = tmp_path / "cf.tgz"+ with tarfile.open(tgz, "w:gz") as tar:+ info = tarfile.TarInfo(name = member_name)+ info.size = len(data)+ tar.addfile(info, io.BytesIO(data))+ return tgz+++def test_tgz_extraction_extracts_clean_member(tmp_path):+ tgz = _make_tgz(tmp_path, "cloudflared")+ dest = tmp_path / "out"+ assert ct._extract_tgz_member(tgz, dest) is True+ assert dest.read_bytes() == b"bin"+++def test_tgz_extraction_rejects_traversal(tmp_path):+ tgz = _make_tgz(tmp_path, "../cloudflared")+ dest = tmp_path / "out"+ assert ct._extract_tgz_member(tgz, dest) is False+ assert not dest.exists()+++def test_tgz_extraction_missing_member(tmp_path):+ tgz = _make_tgz(tmp_path, "README")+ dest = tmp_path / "out"+ assert ct._extract_tgz_member(tgz, dest) is False+++# ── tunnel lifecycle ─────────────────────────────────────────────────+++class _FakePopen:+ def __init__(self):+ self.terminated = False+ self.killed = False+ self._alive = True++ def poll(self):+ return None if self._alive else 0++ def terminate(self):+ self.terminated = True+ self._alive = False++ def wait(self, timeout = None):+ if self._alive:+ raise ct.subprocess.TimeoutExpired(cmd = "cloudflared", timeout = timeout)+ return 0++ def kill(self):+ self.killed = True+ self._alive = False+++def test_stop_terminates_process():+ t = ct.CloudflareTunnel(8080, "/bin/cloudflared")+ fake = _FakePopen()+ t._proc = fake+ t.stop()+ assert fake.terminated is True+ assert t._proc is None+ # second stop is a no-op (idempotent)+ t.stop()+++def test_wait_for_url_times_out_without_blocking():+ t = ct.CloudflareTunnel(8080, "/bin/cloudflared")+ assert t.wait_for_url(timeout = 0.05) is None+++def test_start_studio_tunnel_no_binary(monkeypatch):+ monkeypatch.setattr(ct, "ensure_cloudflared", lambda: None)+ assert ct.start_studio_tunnel(8080) is None+++def test_start_studio_tunnel_registers_before_wait(monkeypatch):+ # The tunnel must be visible to stop_studio_tunnel() during the URL wait,+ # else a shutdown in that window orphans cloudflared.+ seen = {}++ class _Stub:+ def __init__(self, port, binary):+ self.url = None++ def start(self):+ pass++ def wait_for_url(self, timeout):+ seen["active_during_wait"] = ct._active_tunnel is self+ self.url = "https://x.trycloudflare.com"+ return self.url++ def stop(self):+ seen["stopped"] = True++ monkeypatch.setattr(ct, "ensure_cloudflared", lambda: "/bin/cloudflared")+ monkeypatch.setattr(ct, "CloudflareTunnel", _Stub)+ try:+ assert ct.start_studio_tunnel(8080) == "https://x.trycloudflare.com"+ assert seen["active_during_wait"] is True+ finally:+ ct.stop_studio_tunnel()+++def test_start_studio_tunnel_clears_and_stops_on_no_url(monkeypatch):+ seen = {}++ class _Stub:+ def __init__(self, port, binary):+ self.url = None++ def start(self):+ pass++ def wait_for_url(self, timeout):+ return None++ def stop(self):+ seen["stopped"] = True++ monkeypatch.setattr(ct, "ensure_cloudflared", lambda: "/bin/cloudflared")+ monkeypatch.setattr(ct, "CloudflareTunnel", _Stub)+ assert ct.start_studio_tunnel(8080) is None+ assert seen.get("stopped") is True+ assert ct._active_tunnel is None+++def test_start_studio_tunnel_returns_url(monkeypatch):+ class _StubTunnel:+ def __init__(self, port, binary):+ self.url = None++ def start(self):+ self.url = "https://stub-xyz.trycloudflare.com"++ def wait_for_url(self, timeout):+ return self.url++ def stop(self):+ pass++ monkeypatch.setattr(ct, "ensure_cloudflared", lambda: "/bin/cloudflared")+ monkeypatch.setattr(ct, "CloudflareTunnel", _StubTunnel)+ try:+ assert ct.start_studio_tunnel(8080) == "https://stub-xyz.trycloudflare.com"+ finally:+ ct.stop_studio_tunnel()+++# ── run.py source-level pins (AST / source, no heavy import) ─────────+++def _func_param_defaults(source, func_name):+ tree = ast.parse(source)+ for node in ast.walk(tree):+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == func_name:+ args = node.args.args+ defaults = node.args.defaults+ offset = len(args) - len(defaults)+ out = {}+ for i, d in enumerate(defaults):+ if isinstance(d, ast.Constant):+ out[args[offset + i].arg] = d.value+ return out+ return {}+++def _argparse_default(source, option):+ tree = ast.parse(source)+ for node in ast.walk(tree):+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):+ if node.func.attr == "add_argument" and node.args:+ a0 = node.args[0]+ if isinstance(a0, ast.Constant) and a0.value == option:+ for kw in node.keywords:+ if kw.arg == "default" and isinstance(kw.value, ast.Constant):+ return kw.value.value+ return None+++def test_run_server_cloudflare_default_true():+ defaults = _func_param_defaults(_RUN_PY.read_text(), "run_server")+ assert defaults.get("cloudflare") is True+++def test_argparse_cloudflare_default_true():+ assert _argparse_default(_RUN_PY.read_text(), "--cloudflare") is True+++def test_run_server_gates_tunnel_on_wildcard():+ # Guard against accidentally widening the trigger beyond 0.0.0.0.+ source = _RUN_PY.read_text()+ assert "_cloudflare_enabled" in source+ assert 'host == "0.0.0.0"' in sourcediff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.pyindex 10597a689b1..2d4f5ac2433 100644--- a/studio/backend/utils/paths/storage_roots.py+++ b/studio/backend/utils/paths/storage_roots.py@@ -60,6 +60,11 @@ def cache_root() -> Path:return studio_root() / "cache"+def studio_bin_root() -> Path:+ """Dir for Studio-managed executables (the `unsloth` shim, downloaded tools like cloudflared)."""+ return studio_root() / "bin"++def assets_root() -> Path:return studio_root() / "assets"diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex b506f764d7a..7493b87eee8 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -597,6 +597,11 @@ def studio_default(f"defaults to {_PARALLEL_DEFAULT_RUN}."),),+ cloudflare: bool = typer.Option(+ True,+ "--cloudflare/--no-cloudflare",+ help = "Auto-create a free Cloudflare HTTPS tunnel when bound to 0.0.0.0 (default on).",+ ),):"""Launch the Unsloth Studio server."""# Runs before every subcommand (run/setup/update/...).@@ -614,6 +619,16 @@ def studio_default(err = True,)raise typer.Exit(2)+ # Same for --no-cloudflare: it would not reach the subcommand.+ if not cloudflare:+ typer.echo(+ f"Error: --no-cloudflare on `unsloth studio` applies to the "+ f"plain-server path only. For `unsloth studio "+ f"{ctx.invoked_subcommand}`, put it after the subcommand: "+ f"`unsloth studio {ctx.invoked_subcommand} --no-cloudflare ...`",+ err = True,+ )+ raise typer.Exit(2)return# Use the studio venv if it exists and we aren't already in it.@@ -648,6 +663,8 @@ def studio_default(args.append("--silent")if api_only:args.append("--api-only")+ # Forward the explicit polarity (matches run.py's BooleanOptionalAction).+ args.append("--cloudflare" if cloudflare else "--no-cloudflare")# On Windows os.execvp keeps the parent alive, so Ctrl+C# would orphan the child; use Popen+wait instead.if sys.platform == "win32":@@ -689,6 +706,7 @@ def studio_default(silent = silent,api_only = api_only,llama_parallel_slots = parallel,+ cloudflare = cloudflare,)if frontend is not None:run_kwargs["frontend_path"] = frontend@@ -861,6 +879,11 @@ def run(f"{_PARALLEL_DEFAULT_RUN} (pre-PR hardcoded value)."),),+ cloudflare: bool = typer.Option(+ True,+ "--cloudflare/--no-cloudflare",+ help = "Auto-create a free Cloudflare HTTPS tunnel when bound to 0.0.0.0 (default on).",+ ),):"""Start Studio, load a model, print an API key -- one-liner server.@@ -980,6 +1003,8 @@ def run(# Typer claims --parallel outside ctx.args; without this the# child reverts to its default and silently drops the value.args.extend(["--parallel", str(parallel)])+ # Forward the explicit polarity (same rationale as --load-in-4bit above).+ args.append("--cloudflare" if cloudflare else "--no-cloudflare")# llama-server pass-through extras → child ctx.args → load payload.if extra_llama_args:args.extend(extra_llama_args)@@ -997,7 +1022,13 @@ def run(# ── 2. Start server (always suppress built-in banner) ─────────────from studio.backend.run import run_server, _resolve_external_ip- run_kwargs = dict(host = host, port = port, silent = True, llama_parallel_slots = parallel)+ run_kwargs = dict(+ host = host,+ port = port,+ silent = True,+ llama_parallel_slots = parallel,+ cloudflare = cloudflare,+ )if frontend is not None:run_kwargs["frontend_path"] = frontendapp = run_server(**run_kwargs)@@ -1011,32 +1042,41 @@ def run(set_tool_policy(enable_tools)- # 3. Wait for server health.- if not silent:- typer.echo("Starting Unsloth Studio...")- if not _wait_for_server(actual_port):- typer.echo("Error: server did not become healthy within 30 seconds.", err = True)- raise typer.Exit(1)+ # Steps 3-5 can abort (health timeout, model-load error, or Ctrl+C during the+ # slow load); tear the server and its children (llama-server, cloudflared) down+ # on any abort so they never orphan.+ from studio.backend.run import _graceful_shutdown, _server- # 4. Create API key in-process.- api_key = _create_api_key_inprocess(api_key_name)-- # 5. Load model via HTTP.- if not silent:- typer.echo(f"Loading model: {model}...")try:- result = _load_model_via_http(- port = actual_port,- api_key = api_key,- model = model,- gguf_variant = gguf_variant,- max_seq_length = max_seq_length,- load_in_4bit = load_in_4bit,- llama_extra_args = extra_llama_args,- )- except RuntimeError as exc:- typer.echo(f"Error: {exc}", err = True)- raise typer.Exit(1)+ # 3. Wait for server health.+ if not silent:+ typer.echo("Starting Unsloth Studio...")+ if not _wait_for_server(actual_port):+ typer.echo("Error: server did not become healthy within 30 seconds.", err = True)+ raise typer.Exit(1)++ # 4. Create API key in-process.+ api_key = _create_api_key_inprocess(api_key_name)++ # 5. Load model via HTTP.+ if not silent:+ typer.echo(f"Loading model: {model}...")+ try:+ result = _load_model_via_http(+ port = actual_port,+ api_key = api_key,+ model = model,+ gguf_variant = gguf_variant,+ max_seq_length = max_seq_length,+ load_in_4bit = load_in_4bit,+ llama_extra_args = extra_llama_args,+ )+ except RuntimeError as exc:+ typer.echo(f"Error: {exc}", err = True)+ raise typer.Exit(1)+ except BaseException:+ _graceful_shutdown(_server)+ raiseloaded_model = result.get("model", model)display_variant = f" ({gguf_variant})" if gguf_variant else ""@@ -1045,6 +1085,8 @@ def run(display_host = _resolve_external_ip() if host == "0.0.0.0" else hostbase_url = f"http://{display_host}:{actual_port}"sdk_base_url = f"{base_url}/v1"+ # run_server started the tunnel during the silent run above (0.0.0.0 only).+ _cf_url = getattr(app.state, "cloudflare_url", None)# Orange so the tool-policy notice stands out; printed under# --silent / --yes too so the policy is never invisible.@@ -1074,6 +1116,8 @@ def run(typer.echo("")typer.echo("=" * 56)typer.echo(f" Unsloth Studio running at {base_url}")+ if _cf_url:+ typer.echo(f" Secure link access via Cloudflare: {_cf_url}")typer.echo(f" Model loaded: {loaded_model}{display_variant}")typer.echo(f" API Key: {api_key}")typer.echo("")@@ -1107,6 +1151,8 @@ def run(else:# Silent still prints URL + API key + tool-status policy.typer.echo(f"URL: {base_url}")+ if _cf_url:+ typer.echo(f"Secure link access via Cloudflare: {_cf_url}")typer.echo(f"API Key: {api_key}")typer.secho(_tool_notice, fg = _tool_notice_fg, bold = True)diff --git a/unsloth_cli/tests/test_studio_cloudflare_flag.py b/unsloth_cli/tests/test_studio_cloudflare_flag.pynew file mode 100644index 00000000000..5c2a039547c--- /dev/null+++ b/unsloth_cli/tests/test_studio_cloudflare_flag.py@@ -0,0 +1,292 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for the `--cloudflare/--no-cloudflare` Studio flag.++Pins the typer Option (default on) on both `unsloth studio` and+`unsloth studio run`, and that the chosen polarity reaches the re-exec'd+child and run_server. Modeled on test_studio_run_parallel_flag.py.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest+from typer.testing import CliRunner+++_REPO_ROOT = Path(__file__).resolve().parents[2]+if str(_REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(_REPO_ROOT))+++def _studio():+ from unsloth_cli.commands import studio as _studio_mod+ return _studio_mod+++_BASE = ["--model", "unsloth/Qwen3-1.7B-GGUF"]+++# ── option registration ──────────────────────────────────────────────+++def test_run_exposes_cloudflare_option_default_on():+ import inspect++ sig = inspect.signature(_studio().run)+ assert "cloudflare" in sig.parameters+ opt = sig.parameters["cloudflare"].default+ decls = set(getattr(opt, "param_decls", []) or [])+ assert "--cloudflare/--no-cloudflare" in decls+ assert getattr(opt, "default", None) is True+++def test_studio_default_exposes_cloudflare_option_default_on():+ import inspect++ sig = inspect.signature(_studio().studio_default)+ assert "cloudflare" in sig.parameters+ opt = sig.parameters["cloudflare"].default+ assert getattr(opt, "default", None) is True+++# ── re-exec forwarding: `unsloth studio run` ─────────────────────────+++class _ExecCaptured(SystemExit):+ def __init__(self, argv):+ super().__init__(0)+ self.argv = list(argv)+++def _install_run_reexec_capture(monkeypatch, *, platform = "linux"):+ studio_mod = _studio()+ captured = []++ monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")+ fake_venv = Path("/fake/studio/venv/unsloth_studio")+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_venv / "bin" / "python")+ fake_bin = fake_venv / "bin" / "unsloth"+ real_is_file = Path.is_file+ monkeypatch.setattr(+ Path,+ "is_file",+ lambda self: True if str(self) == str(fake_bin) else real_is_file(self),+ )+ from unsloth_cli import _tool_policy as _tp_mod++ monkeypatch.setattr(+ _tp_mod,+ "resolve_tool_policy",+ lambda host, flag, yes, silent: False if flag is None else bool(flag),+ )+ monkeypatch.setattr(sys, "platform", platform)++ def fake_execvp(file, argv):+ captured.append(list(argv))+ raise _ExecCaptured(argv)++ monkeypatch.setattr(studio_mod.os, "execvp", fake_execvp)+ return captured+++def _invoke_run(monkeypatch, args):+ import typer as _typer++ studio_mod = _studio()+ captured = _install_run_reexec_capture(monkeypatch)+ app = _typer.Typer()+ app.command(+ context_settings = {"allow_extra_args": True, "ignore_unknown_options": True},+ )(studio_mod.run)+ CliRunner().invoke(app, args, catch_exceptions = True)+ return captured+++ "user_flag,expected,unexpected",+ [+ (None, "--cloudflare", "--no-cloudflare"), # default on+ ("--cloudflare", "--cloudflare", "--no-cloudflare"),+ ("--no-cloudflare", "--no-cloudflare", "--cloudflare"),+ ],+)+def test_run_reexec_forwards_cloudflare_polarity(monkeypatch, user_flag, expected, unexpected):+ extras = [user_flag] if user_flag else []+ captured = _invoke_run(monkeypatch, _BASE + extras)+ assert len(captured) == 1, captured+ argv = captured[0]+ assert expected in argv, f"expected {expected} in child argv; got {argv}"+ assert unexpected not in argv, f"unexpected {unexpected} in child argv; got {argv}"+++# ── re-exec forwarding: plain `unsloth studio` ───────────────────────+++def _invoke_studio_default(+ monkeypatch,+ args,+ *,+ platform = "linux",+):+ import typer as _typer++ studio_mod = _studio()+ captured = []++ monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")+ monkeypatch.setattr(studio_mod, "_ensure_studio_env_exported", lambda: None)+ fake_venv = Path("/fake/studio/venv/unsloth_studio")+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_venv / "bin" / "python")+ monkeypatch.setattr(studio_mod, "_find_run_py", lambda: Path("/fake/studio/run.py"))+ monkeypatch.setattr(studio_mod, "_find_frontend_dist", lambda: None)+ monkeypatch.setattr(sys, "platform", platform)++ def fake_execvp(file, argv):+ captured.append(list(argv))+ raise _ExecCaptured(argv)++ monkeypatch.setattr(studio_mod.os, "execvp", fake_execvp)++ app = _typer.Typer()+ app.command()(studio_mod.studio_default)+ CliRunner().invoke(app, args, catch_exceptions = True)+ return captured+++ "user_flag,expected,unexpected",+ [+ (None, "--cloudflare", "--no-cloudflare"),+ ("--no-cloudflare", "--no-cloudflare", "--cloudflare"),+ ],+)+def test_studio_default_reexec_forwards_cloudflare(monkeypatch, user_flag, expected, unexpected):+ extras = [user_flag] if user_flag else []+ captured = _invoke_studio_default(monkeypatch, ["-H", "0.0.0.0"] + extras)+ assert len(captured) == 1, captured+ argv = captured[0]+ assert expected in argv, f"expected {expected}; got {argv}"+ assert unexpected not in argv, f"unexpected {unexpected}; got {argv}"+++# ── in-venv path forwards cloudflare into run_server ─────────────────+++class _RunServerCaptured(SystemExit):+ def __init__(self, kwargs):+ super().__init__(0)+ self.kwargs = dict(kwargs)++[email protected]("user_flag,expected", [(None, True), ("--no-cloudflare", False)])+def test_run_in_venv_passes_cloudflare_to_run_server(monkeypatch, user_flag, expected):+ import types++ studio_mod = _studio()+ fake_venv = Path("/fake/studio/venv/unsloth_studio")+ monkeypatch.setattr(sys, "prefix", str(fake_venv))+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", fake_venv.parent)++ from unsloth_cli import _tool_policy as _tp_mod++ monkeypatch.setattr(+ _tp_mod,+ "resolve_tool_policy",+ lambda host, flag, yes, silent: False if flag is None else bool(flag),+ )++ captured: dict = {}++ def fake_run_server(**kwargs):+ captured.update(kwargs)+ raise _RunServerCaptured(kwargs)++ fake_backend_run = sys.modules.setdefault(+ "studio.backend.run", types.ModuleType("studio.backend.run")+ )+ fake_backend_run.run_server = fake_run_server+ fake_backend_run._resolve_external_ip = lambda: "127.0.0.1"++ import typer as _typer++ app = _typer.Typer()+ app.command(+ context_settings = {"allow_extra_args": True, "ignore_unknown_options": True},+ )(studio_mod.run)+ extras = [user_flag] if user_flag else []+ CliRunner().invoke(app, _BASE + extras, catch_exceptions = True)++ assert captured.get("cloudflare") is expected, captured+++# ── parent-level --no-cloudflare with a subcommand is rejected ───────+++def test_studio_default_rejects_no_cloudflare_with_subcommand(monkeypatch):+ # `unsloth studio --no-cloudflare run ...` would not reach the subcommand,+ # so it must error (mirrors --parallel) rather than silently still tunnel.+ import typer as _typer++ studio_mod = _studio()+ app = _typer.Typer()+ app.add_typer(studio_mod.studio_app, name = "studio")+ result = CliRunner().invoke(app, ["studio", "--no-cloudflare", "run", "--model", "X"])+ assert result.exit_code == 2, result.output+ combined = (result.output or "") + (getattr(result, "stderr", "") or "")+ assert "--no-cloudflare" in combined, combined+++# ── run() tears the server + tunnel down if startup aborts ───────────+++def test_run_in_venv_shuts_down_on_startup_abort(monkeypatch):+ import types++ studio_mod = _studio()+ fake_venv = Path("/fake/studio/venv/unsloth_studio")+ monkeypatch.setattr(sys, "prefix", str(fake_venv))+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", fake_venv.parent)++ from unsloth_cli import _tool_policy as _tp_mod++ monkeypatch.setattr(+ _tp_mod,+ "resolve_tool_policy",+ lambda host, flag, yes, silent: False if flag is None else bool(flag),+ )++ class _App:+ class state:+ server_port = 8888++ shutdown_calls = []+ backend = sys.modules.setdefault("studio.backend.run", types.ModuleType("studio.backend.run"))+ backend.run_server = lambda **k: _App()+ backend._resolve_external_ip = lambda: "1.2.3.4"+ backend._server = object()+ backend._shutdown_event = None+ backend._graceful_shutdown = lambda server: shutdown_calls.append(server)++ # set_tool_policy is imported as `from state.tool_policy import set_tool_policy`.+ state_mod = sys.modules.setdefault("state", types.ModuleType("state"))+ tp_mod = sys.modules.setdefault("state.tool_policy", types.ModuleType("state.tool_policy"))+ tp_mod.set_tool_policy = lambda *a, **k: None+ state_mod.tool_policy = tp_mod++ # Force the health check to fail so startup aborts after run_server().+ monkeypatch.setattr(studio_mod, "_wait_for_server", lambda *a, **k: False)++ import typer as _typer++ app = _typer.Typer()+ app.command(+ context_settings = {"allow_extra_args": True, "ignore_unknown_options": True},+ )(studio_mod.run)+ result = CliRunner().invoke(app, _BASE + ["-H", "0.0.0.0"], catch_exceptions = True)++ assert result.exit_code == 1, result.output+ assert len(shutdown_calls) == 1, "startup abort must call _graceful_shutdown"