Skip to content

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.

studio: explicit Cloudflare tunnel notice and public-exposure warning at startup (#6515)

Daniel Hanb72a8c42636a
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 6f36f0928a6..ccd0113972f 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -253,12 +253,13 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
local_url_c = "\033[38;5;108;1m" if use_color else "" # matches banner's URL color
reset = "\033[0m" if use_color else ""
- url = f"http://{display_host}:{port}"
+ url = f"http://{_url_host(display_host)}:{port}"
# Private/loopback/link-local addresses aren't globally routable.
try:
addr = ipaddress.ip_address(display_host)
if addr.is_loopback or addr.is_private or addr.is_link_local:
+ _public_reachable = False
print(
f"{dim} Note: {display_host} is a private/LAN address -- "
f"reachable on this network only, not from the public internet."
@@ -380,6 +381,20 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
pass
+def _display_host_for_bind(host: str) -> str:
+ return _resolve_external_ip() if host in ("0.0.0.0", "::") else host
+
+
+def _loopback_bind_host_for(host: str) -> str:
+ return "::1" if host == "::" else "127.0.0.1"
+
+
+def _url_host(host: str) -> str:
+ return (
+ f"[{host}]" if ":" in host and not (host.startswith("[") and host.endswith("]")) else host
+ )
+
+
def _tool_policy_notice(host: str, secure: bool, enable_tools: "Optional[bool]") -> str:
"""One-line tool-policy summary for the plain-server startup banner, so a
network-reachable launch is never silent about code execution."""
@@ -416,7 +431,7 @@ def _emit_secure_startup_output(port: int, enable_tools: "Optional[bool]" = None
print("")
print("πŸ¦₯ Unsloth Studio is running (secure)")
print("─" * 52)
- _print_cloudflare_line()
+ _print_cloudflare_line(secure = True)
print(f" On this machine only: http://127.0.0.1:{port}/")
print("─" * 52)
_emit_tool_policy_notice("127.0.0.1", True, enable_tools)
@@ -447,30 +462,108 @@ def _emit_startup_output(
_print_localhost_ipv6_mismatch_warning(localhost_mismatch_url, port)
elif wildcard_bind:
_verify_global_reachability(display_host, port)
- _print_cloudflare_line()
+ _print_cloudflare_line(loopback_host = _loopback_bind_host_for(host))
_emit_tool_policy_notice(host, False, enable_tools)
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. When the public
- reachability probe just failed (``_public_reachable is False``) but the tunnel
- is up, reword to point the user at the Cloudflare link as the way in.
- """
- if not _cloudflare_url:
- return
+def _print_cloudflare_line(secure: bool = False, loopback_host: str = "127.0.0.1") -> None:
+ """Print Cloudflare tunnel state for startup banners."""
from startup_banner import stdout_supports_color
accent = "\033[38;5;150;1m"
+ warn = "\033[38;5;215;1m"
reset = "\033[0m"
- if _public_reachable is False:
- line = f" Use the secure link access via Cloudflare instead: {_cloudflare_url}"
- else:
- line = f" Secure link access via Cloudflare: {_cloudflare_url}"
- print(f"{accent}{line}{reset}" if stdout_supports_color() else line)
+ color = stdout_supports_color()
+
+ def _emit(text: str, style: str = "") -> None:
+ print(f"{style}{text}{reset}" if (color and style) else text)
+
+ if _cloudflare_url:
+ if _public_reachable is False:
+ _emit(f" Use the secure link access via Cloudflare instead: {_cloudflare_url}", accent)
+ else:
+ _emit(f" Secure link access via Cloudflare: {_cloudflare_url}", accent)
+ if not secure:
+ if _public_reachable is True:
+ _emit(
+ " Cloudflare tunnel: ON. This Cloudflare URL is PUBLIC, and the "
+ "raw port is also publicly reachable. --no-cloudflare disables "
+ f"only the Cloudflare URL; bind {loopback_host} or close firewall "
+ "access to keep Studio private.",
+ warn,
+ )
+ else:
+ _emit(
+ " Cloudflare tunnel: ON. This is a PUBLIC internet URL: anyone "
+ "who has it can reach this Studio. Relaunch with --no-cloudflare "
+ f"to disable the Cloudflare URL; bind {loopback_host} or close "
+ "firewall access to keep Studio private.",
+ warn,
+ )
+ return
+ if _cloudflare_requested:
+ if _public_reachable is True:
+ _emit(
+ " Cloudflare tunnel: requested but failed to start. The raw port is "
+ "still reachable from the public internet (see the reachability check "
+ "above): anyone who can reach it can access this Studio.",
+ warn,
+ )
+ elif _public_reachable is False:
+ _emit(
+ " Cloudflare tunnel: requested but failed to start. Studio is reachable "
+ "on your local network only (no public link).",
+ warn,
+ )
+ else:
+ _emit(
+ " Cloudflare tunnel: requested but failed to start. There is no "
+ "Cloudflare public link. Raw port reachability was not verified; "
+ f"bind {loopback_host} or close firewall access to keep Studio private.",
+ warn,
+ )
+ elif _cloudflare_flag:
+ if _public_reachable is True:
+ _emit(
+ " Cloudflare tunnel: OFF for this mode. The raw port is still "
+ "reachable from the public internet (see the reachability check above): "
+ "anyone who can reach it can access this Studio.",
+ warn,
+ )
+ elif _public_reachable is False:
+ _emit(
+ " Cloudflare tunnel: OFF for this mode. Studio is reachable on your "
+ "local network only (no public link)."
+ )
+ else:
+ _emit(
+ " Cloudflare tunnel: OFF for this mode. There is no Cloudflare public "
+ "link. Raw port reachability was not verified; "
+ f"bind {loopback_host} or close firewall access to keep Studio private.",
+ warn,
+ )
+ elif not _cloudflare_flag:
+ if _public_reachable is True:
+ _emit(
+ " Cloudflare tunnel: OFF (--no-cloudflare). The raw port is still "
+ "reachable from the public internet (see the reachability check above): "
+ "--no-cloudflare disables only the Cloudflare link, not the public bind.",
+ warn,
+ )
+ elif _public_reachable is False:
+ _emit(
+ " Cloudflare tunnel: OFF (--no-cloudflare). Studio is reachable on your "
+ "local network only. Omit --no-cloudflare to expose a public "
+ "Cloudflare HTTPS link."
+ )
+ else:
+ _emit(
+ " Cloudflare tunnel: OFF (--no-cloudflare). There is no Cloudflare "
+ "public link. Raw port reachability was not verified; "
+ f"bind {loopback_host} or close firewall access to keep Studio private.",
+ warn,
+ )
def _get_pid_on_port(port: int) -> "tuple[int, str] | None":
@@ -697,7 +790,7 @@ _server_thread = 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);
+# trycloudflare.com URL for wildcard 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
@@ -707,6 +800,9 @@ _cloudflare_url = None
# not decide (timeout, blocked, private address).
_public_reachable = None
+_cloudflare_requested = False
+_cloudflare_flag = True
+
_DEFAULT_FRONTEND_PATH = Path(__file__).resolve().parent.parent / "frontend" / "dist"
@@ -880,12 +976,12 @@ def _cloudflare_tunnel_should_start(
) -> bool:
"""Whether to start the Cloudflare tunnel. --secure exposes only the tunnel
(loopback bind), so it tunnels even api-only (headless secure API serving);
- otherwise tunnel only a 0.0.0.0 bind, never api-only (Tauri) or Colab."""
+ otherwise tunnel wildcard binds, never api-only (Tauri) or Colab."""
if is_colab or not cloudflare:
return False
if secure:
return True
- return host == "0.0.0.0" and not api_only
+ return host in ("0.0.0.0", "::") and not api_only
def _apply_cli_tool_policy(enable_tools: "Optional[bool]") -> None:
@@ -1072,7 +1168,7 @@ def run_server(
)
# Resolve once; shared by the log rewrite and banner.
- display_host = _resolve_external_ip() if host == "0.0.0.0" else host
+ display_host = _display_host_for_bind(host)
_install_uvicorn_startup_log_rewrite(host, display_host)
logger.info(
@@ -1117,13 +1213,10 @@ def run_server(
# backend, not whatever a proxy/tunnel exposed. For ephemeral binds (port==0)
# leave it unset so handlers fall back to the request scope / base_url.
app.state.server_port = port if port and port > 0 else None
- # Direct (non-tunnel) base for the API panel; resolve 0.0.0.0 to the LAN IP.
+ # Direct (non-tunnel) base for the API panel; resolve wildcard binds to the LAN IP.
if port and port > 0:
- _direct_host = _resolve_external_ip() if host in ("0.0.0.0", "::") else host
- # Bracket IPv6 literals so the URL is valid (http://[2405:...]:port).
- if ":" in _direct_host and not _direct_host.startswith("["):
- _direct_host = f"[{_direct_host}]"
- app.state.server_url = f"http://{_direct_host}:{port}"
+ _direct_host = _display_host_for_bind(host)
+ app.state.server_url = f"http://{_url_host(_direct_host)}:{port}"
else:
app.state.server_url = None
app.state.secure = secure
@@ -1192,11 +1285,12 @@ def run_server(
if api_only and emit_tauri_port:
print(f"TAURI_PORT={port}", flush = True)
- # Free trycloudflare.com tunnel for 0.0.0.0 binds (the raw ip:port is often
+ # Free trycloudflare.com tunnel for wildcard 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
+ global _cloudflare_url, _cloudflare_requested, _cloudflare_flag
_cloudflare_url = None
+ _cloudflare_flag = cloudflare
app.state.cloudflare_url = None
_cloudflare_enabled = _cloudflare_tunnel_should_start(
cloudflare = cloudflare,
@@ -1205,6 +1299,7 @@ def run_server(
api_only = api_only,
is_colab = _IS_COLAB,
)
+ _cloudflare_requested = _cloudflare_enabled
if _cloudflare_enabled:
try: # best-effort: any failure must not block startup
from cloudflare_tunnel import start_studio_tunnel, stop_studio_tunnel
@@ -1309,8 +1404,10 @@ def _build_arg_parser():
"--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)",
+ help = "Auto-create a free Cloudflare HTTPS tunnel for non-api-only wildcard "
+ "binds (0.0.0.0 or ::), exposing Studio on a PUBLIC internet URL (default on). "
+ "Pass --no-cloudflare to disable that Cloudflare URL; it does not change a "
+ "public wildcard bind. --api-only keeps it off unless paired with --secure.",
)
parser.add_argument(
"--secure",
diff --git a/studio/backend/tests/test_cloudflare_tunnel.py b/studio/backend/tests/test_cloudflare_tunnel.py
index 8042240b643..7904c70a7be 100644
--- a/studio/backend/tests/test_cloudflare_tunnel.py
+++ b/studio/backend/tests/test_cloudflare_tunnel.py
@@ -11,6 +11,7 @@ checked by AST so we never import its heavy deps (uvicorn/structlog).
import ast
import importlib.util
import io
+import os
import sys
import tarfile
import types
@@ -136,7 +137,9 @@ def test_ensure_downloads_and_chmods_when_missing(monkeypatch, tmp_path):
path = ct.ensure_cloudflared()
assert path == str(cached)
assert cached.exists()
- assert cached.stat().st_mode & 0o111 # executable bit set
+ # Host OS, not monkeypatched ct.sys.platform.
+ if os.name != "nt":
+ assert cached.stat().st_mode & 0o111
def test_ensure_returns_none_on_download_failure(monkeypatch, tmp_path):
@@ -238,7 +241,8 @@ def test_ensure_macos_extracts_tgz_and_chmods(monkeypatch, tmp_path):
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
+ if os.name != "nt":
+ assert cached.stat().st_mode & 0o111
assert not cached.with_suffix(".tgz").exists() # temp archive cleaned up
@@ -696,6 +700,28 @@ def test_argparse_cloudflare_default_true():
assert _argparse_default(_RUN_PY.read_text(), "--cloudflare") is True
+def test_verify_global_reachability_marks_private_address_unreachable():
+ src = _RUN_PY.read_text()
+ tree = ast.parse(src)
+ func_src = next(
+ ast.get_source_segment(src, n)
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name == "_verify_global_reachability"
+ )
+ captured = []
+ ns = {
+ "_public_reachable": None,
+ "_stdout_color_ok": lambda: False,
+ "_url_host": lambda host: host,
+ "print": lambda *a, **k: captured.append(" ".join(str(x) for x in a)),
+ }
+ exec(compile(func_src, "<verify_global_reachability>", "exec"), ns)
+ ns["_verify_global_reachability"]("192.168.1.10", 8888)
+
+ assert ns["_public_reachable"] is False
+ assert "private/LAN address" in "\n".join(captured)
+
+
def test_run_server_registers_tunnel_atexit_backstop():
# An abnormal exit (exception after startup -> sys.exit) bypasses
# _graceful_shutdown; an atexit backstop must still stop the tunnel.
@@ -703,16 +729,18 @@ def test_run_server_registers_tunnel_atexit_backstop():
assert "atexit.register(stop_studio_tunnel)" in src
-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 source
-
-
-def _run_print_cloudflare_line(monkeypatch, *, cloudflare_url, public_reachable):
- """Exec the real _print_cloudflare_line source in isolation (run.py has heavy
- deps), with the two module globals injected and startup_banner stubbed."""
+def _run_print_cloudflare_line(
+ monkeypatch,
+ *,
+ cloudflare_url,
+ public_reachable,
+ cloudflare_requested = False,
+ cloudflare_flag = True,
+ secure = False,
+ loopback_host = "127.0.0.1",
+ color = False,
+):
+ """Exec _print_cloudflare_line without importing run.py's heavy deps."""
src = _RUN_PY.read_text()
tree = ast.parse(src)
func_src = next(
@@ -721,16 +749,18 @@ def _run_print_cloudflare_line(monkeypatch, *, cloudflare_url, public_reachable)
if isinstance(n, ast.FunctionDef) and n.name == "_print_cloudflare_line"
)
stub = types.ModuleType("startup_banner")
- stub.stdout_supports_color = lambda: False
+ stub.stdout_supports_color = lambda: color
monkeypatch.setitem(sys.modules, "startup_banner", stub)
captured: list[str] = []
ns = {
"_cloudflare_url": cloudflare_url,
"_public_reachable": public_reachable,
+ "_cloudflare_requested": cloudflare_requested,
+ "_cloudflare_flag": cloudflare_flag,
"print": lambda *a, **k: captured.append(" ".join(str(x) for x in a)),
}
exec(compile(func_src, "<print_cloudflare_line>", "exec"), ns)
- ns["_print_cloudflare_line"]()
+ ns["_print_cloudflare_line"](secure = secure, loopback_host = loopback_host)
return "\n".join(captured)
@@ -750,7 +780,6 @@ def test_cloudflare_line_default_wording_when_reachable(monkeypatch):
def test_cloudflare_line_default_wording_when_unknown(monkeypatch):
- # Probe did not run / could not decide -> keep the existing wording.
out = _run_print_cloudflare_line(
monkeypatch, cloudflare_url = "https://x.trycloudflare.com", public_reachable = None
)
@@ -758,6 +787,136 @@ def test_cloudflare_line_default_wording_when_unknown(monkeypatch):
assert "Use the secure link" not in out
-def test_cloudflare_line_prints_nothing_without_tunnel(monkeypatch):
+def test_cloudflare_line_states_inactive_when_enabled_but_not_requested(monkeypatch):
out = _run_print_cloudflare_line(monkeypatch, cloudflare_url = None, public_reachable = False)
- assert out == ""
+ assert "Cloudflare tunnel: OFF for this mode" in out
+ assert "local network only" in out
+
+
+def test_cloudflare_line_warns_when_public_url_up(monkeypatch):
+ out = _run_print_cloudflare_line(
+ monkeypatch,
+ cloudflare_url = "https://x.trycloudflare.com",
+ public_reachable = True,
+ cloudflare_requested = True,
+ )
+ assert "Secure link access via Cloudflare: https://x.trycloudflare.com" in out
+ assert "Cloudflare tunnel: ON" in out
+ assert "PUBLIC" in out
+ assert "--no-cloudflare" in out
+ assert "raw port is also publicly reachable" in out
+ assert "local network only" not in out
+
+
+def test_cloudflare_line_secure_mode_suppresses_public_warning(monkeypatch):
+ out = _run_print_cloudflare_line(
+ monkeypatch,
+ cloudflare_url = "https://x.trycloudflare.com",
+ public_reachable = True,
+ cloudflare_requested = True,
+ secure = True,
+ )
+ assert "Secure link access via Cloudflare: https://x.trycloudflare.com" in out
+ assert "Cloudflare tunnel: ON" not in out
+
+
+def test_cloudflare_line_states_disabled_when_off(monkeypatch):
+ out = _run_print_cloudflare_line(
+ monkeypatch,
+ cloudflare_url = None,
+ public_reachable = False,
+ cloudflare_requested = False,
+ cloudflare_flag = False,
+ )
+ assert "Cloudflare tunnel: OFF" in out
+ assert "local network only" in out
+
+
+def test_cloudflare_line_states_failed_when_requested_but_no_url(monkeypatch):
+ out = _run_print_cloudflare_line(
+ monkeypatch,
+ cloudflare_url = None,
+ public_reachable = False,
+ cloudflare_requested = True,
+ cloudflare_flag = True,
+ )
+ assert "requested but failed to start" in out
+ assert "local network only" in out
+
+
+def test_cloudflare_line_off_does_not_claim_local_only_when_unknown(monkeypatch):
+ out = _run_print_cloudflare_line(
+ monkeypatch,
+ cloudflare_url = None,
+ public_reachable = None,
+ cloudflare_requested = False,
+ cloudflare_flag = False,
+ )
+ assert "Cloudflare tunnel: OFF" in out
+ assert "Raw port reachability was not verified" in out
+ assert "local network only" not in out
+
+
+def test_cloudflare_line_failed_does_not_claim_local_only_when_unknown(monkeypatch):
+ out = _run_print_cloudflare_line(
+ monkeypatch,
+ cloudflare_url = None,
+ public_reachable = None,
+ cloudflare_requested = True,
+ cloudflare_flag = True,
+ )
+ assert "requested but failed to start" in out
+ assert "Raw port reachability was not verified" in out
+ assert "local network only" not in out
+
+
+ "cloudflare_requested,cloudflare_flag,expected",
+ [
+ (True, True, "requested but failed to start"),
+ (False, True, "Cloudflare tunnel: OFF for this mode"),
+ (False, False, "Cloudflare tunnel: OFF"),
+ ],
+)
+def test_cloudflare_line_unknown_warns_with_loopback_host(
+ monkeypatch, cloudflare_requested, cloudflare_flag, expected
+):
+ out = _run_print_cloudflare_line(
+ monkeypatch,
+ cloudflare_url = None,
+ public_reachable = None,
+ cloudflare_requested = cloudflare_requested,
+ cloudflare_flag = cloudflare_flag,
+ loopback_host = "::1",
+ color = True,
+ )
+ assert expected in out
+ assert "bind ::1" in out
+ assert "bind 127.0.0.1" not in out
+ assert "\033[38;5;215;1m" in out
+
+
+def test_cloudflare_line_off_does_not_claim_local_only_when_publicly_reachable(monkeypatch):
+ out = _run_print_cloudflare_line(
+ monkeypatch,
+ cloudflare_url = None,
+ public_reachable = True,
+ cloudflare_requested = False,
+ cloudflare_flag = False,
+ )
+ assert "Cloudflare tunnel: OFF" in out
+ assert "reachable from the public internet" in out
+ assert "local network only" not in out
+
+
+def test_cloudflare_line_failed_does_not_claim_local_only_when_publicly_reachable(monkeypatch):
+ out = _run_print_cloudflare_line(
+ monkeypatch,
+ cloudflare_url = None,
+ public_reachable = True,
+ cloudflare_requested = True,
+ cloudflare_flag = True,
+ )
+ assert "requested but failed to start" in out
+ assert "reachable from the public internet" in out
+ assert "local network only" not in out
diff --git a/studio/backend/tests/test_secure_tunnel_gate.py b/studio/backend/tests/test_secure_tunnel_gate.py
index bf9836e8f31..1f7608a4fc6 100644
--- a/studio/backend/tests/test_secure_tunnel_gate.py
+++ b/studio/backend/tests/test_secure_tunnel_gate.py
@@ -21,8 +21,9 @@ from run import _cloudflare_tunnel_should_start as should_start # noqa: E402
@pytest.mark.parametrize(
"cloudflare,host,secure,api_only,is_colab,expected",
[
- # Non-secure: historical 0.0.0.0-only behaviour preserved.
+ # Non-secure wildcard binds tunnel by default.
(True, "0.0.0.0", False, False, False, True),
+ (True, "::", False, False, False, True),
(True, "127.0.0.1", False, False, False, False),
(True, "localhost", False, False, False, False),
# --secure tunnels a loopback bind too.
@@ -30,13 +31,16 @@ from run import _cloudflare_tunnel_should_start as should_start # noqa: E402
(True, "0.0.0.0", True, False, False, True),
# --no-cloudflare always wins.
(False, "0.0.0.0", False, False, False, False),
+ (False, "::", False, False, False, False),
(False, "127.0.0.1", True, False, False, False),
# Non-secure api-only never tunnels (Tauri).
(True, "0.0.0.0", False, True, False, False),
+ (True, "::", False, True, False, False),
# --secure tunnels even api-only (headless secure API server).
(True, "127.0.0.1", True, True, False, True),
# Colab never tunnels, even --secure.
(True, "0.0.0.0", False, False, True, False),
+ (True, "::", False, False, True, False),
(True, "127.0.0.1", True, False, True, False),
(True, "127.0.0.1", True, True, True, False),
],
@@ -132,7 +136,7 @@ def test_startup_output_emits_tool_notice_on_network_bind(capsys, monkeypatch):
import run
monkeypatch.setattr(run, "_verify_global_reachability", lambda *a, **k: None)
- monkeypatch.setattr(run, "_print_cloudflare_line", lambda: None)
+ monkeypatch.setattr(run, "_print_cloudflare_line", lambda *a, **k: None)
monkeypatch.setattr(run, "_localhost_ipv6_mismatch_url", lambda *a, **k: None)
run._emit_startup_output("0.0.0.0", 8000, "0.0.0.0", secure = False, enable_tools = None)
diff --git a/tests/studio/install/test_selection_logic.py b/tests/studio/install/test_selection_logic.py
index f65c7a895c9..464aa9a5786 100644
--- a/tests/studio/install/test_selection_logic.py
+++ b/tests/studio/install/test_selection_logic.py
@@ -82,6 +82,7 @@ def load_studio_run_module(monkeypatch):
startup_banner = types.ModuleType("startup_banner")
startup_banner.print_studio_access_banner = lambda **k: None
startup_banner.print_studio_stop_hint = lambda: None
+ startup_banner.stdout_supports_color = lambda: False
monkeypatch.setitem(sys.modules, "startup_banner", startup_banner)
paths = types.ModuleType("utils.paths")
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 5975e7e355a..7a5080bd100 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -161,6 +161,34 @@ def _stream_for_subprocess(stream):
return stream
+def _display_host_for_bind(run_mod, host: str) -> str:
+ return run_mod._resolve_external_ip() if host in ("0.0.0.0", "::") else host
+
+
+def _loopback_bind_host_for(host: str) -> str:
+ return "::1" if host == "::" else "127.0.0.1"
+
+
+def _url_host(host: str) -> str:
+ return (
+ f"[{host}]" if ":" in host and not (host.startswith("[") and host.endswith("]")) else host
+ )
+
+
+def _emit_run_cloudflare_notice(
+ run_mod, host: str, display_host: str, actual_port: int, secure: bool
+) -> None:
+ from unsloth_cli._tool_policy import is_external_host
+
+ if not is_external_host(host):
+ return
+ run_mod._verify_global_reachability(display_host, actual_port)
+ run_mod._print_cloudflare_line(
+ secure = secure,
+ loopback_host = _loopback_bind_host_for(host),
+ )
+
+
def _studio_venv_python() -> Optional[Path]:
"""Return the studio venv Python binary, or None if not set up."""
if platform.system() == "Windows":
@@ -688,7 +716,10 @@ def studio_default(
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).",
+ help = "Auto-create a free Cloudflare HTTPS tunnel for non-api-only wildcard "
+ "binds (0.0.0.0 or ::), exposing Studio on a PUBLIC internet URL (default on). "
+ "Pass --no-cloudflare to disable that Cloudflare URL; it does not change a "
+ "public wildcard bind. --api-only keeps it off unless paired with --secure.",
),
secure: bool = typer.Option(
False,
@@ -876,8 +907,8 @@ def studio_default(
run_server = run_mod.run_server
if not silent:
- display_host = run_mod._resolve_external_ip() if host == "0.0.0.0" else host
- typer.echo(f"Starting Unsloth Studio on http://{display_host}:{port}")
+ display_host = _display_host_for_bind(run_mod, host)
+ typer.echo(f"Starting Unsloth Studio on http://{_url_host(display_host)}:{port}")
run_kwargs = dict(
host = host,
@@ -1078,7 +1109,10 @@ def 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).",
+ help = "Auto-create a free Cloudflare HTTPS tunnel for non-api-only wildcard "
+ "binds (0.0.0.0 or ::), exposing Studio on a PUBLIC internet URL (default on). "
+ "Pass --no-cloudflare to disable that Cloudflare URL; it does not change a "
+ "public wildcard bind. --api-only keeps it off unless paired with --secure.",
),
secure: bool = typer.Option(
False,
@@ -1336,10 +1370,10 @@ def run(
context_length_line = _format_context_length_line(result)
# 6. Print banner.
- display_host = run_mod._resolve_external_ip() if host == "0.0.0.0" else host
- base_url = f"http://{display_host}:{actual_port}"
+ display_host = _display_host_for_bind(run_mod, host)
+ base_url = f"http://{_url_host(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 or --secure).
+ # run_server started the tunnel during the silent run above (wildcard or --secure).
_cf_url = getattr(app.state, "cloudflare_url", None)
# --secure: examples must use the public tunnel URL, not the loopback address.
if secure and _cf_url:
@@ -1376,8 +1410,7 @@ def run(
typer.echo(f" On this machine only: {base_url}")
else:
typer.echo(f" Unsloth Studio running at {base_url}")
- if _cf_url:
- typer.echo(f" Secure link access via Cloudflare: {_cf_url}")
+ _emit_run_cloudflare_notice(run_mod, host, display_host, actual_port, secure)
typer.echo(f" Model loaded: {loaded_model}{display_variant}")
if context_length_line:
typer.echo(context_length_line)
@@ -1417,8 +1450,7 @@ def run(
typer.echo(f"Local: {base_url}")
else:
typer.echo(f"URL: {base_url}")
- if _cf_url:
- typer.echo(f"Secure link access via Cloudflare: {_cf_url}")
+ _emit_run_cloudflare_notice(run_mod, host, display_host, actual_port, secure)
if context_length_line:
typer.echo(context_length_line.strip())
typer.echo(f"API Key: {api_key}")
diff --git a/unsloth_cli/tests/test_studio_cloudflare_flag.py b/unsloth_cli/tests/test_studio_cloudflare_flag.py
index 905512976ee..c09ac8b9985 100644
--- a/unsloth_cli/tests/test_studio_cloudflare_flag.py
+++ b/unsloth_cli/tests/test_studio_cloudflare_flag.py
@@ -233,6 +233,121 @@ def test_run_in_venv_passes_cloudflare_to_run_server(monkeypatch, user_flag, exp
assert captured.get("cloudflare") is expected, captured
+def test_run_display_host_and_url_helpers_cover_ipv6_wildcard():
+ import types
+
+ studio_mod = _studio()
+ run_mod = types.SimpleNamespace(_resolve_external_ip = lambda: "198.51.100.7")
+
+ assert studio_mod._display_host_for_bind(run_mod, "0.0.0.0") == "198.51.100.7"
+ assert studio_mod._display_host_for_bind(run_mod, "::") == "198.51.100.7"
+ assert studio_mod._url_host("2001:db8::7") == "[2001:db8::7]"
+ assert studio_mod._url_host("127.0.0.1") == "127.0.0.1"
+
+
+def test_run_cloudflare_notice_uses_external_host_policy():
+ import types
+
+ studio_mod = _studio()
+ calls = []
+ run_mod = types.SimpleNamespace(
+ _verify_global_reachability = lambda host, port: calls.append(("verify", host, port)),
+ _print_cloudflare_line = lambda **kw: calls.append(("print", kw)),
+ )
+
+ studio_mod._emit_run_cloudflare_notice(run_mod, "0.0.0.0", "198.51.100.7", 8888, False)
+ assert calls == [
+ ("verify", "198.51.100.7", 8888),
+ ("print", {"secure": False, "loopback_host": "127.0.0.1"}),
+ ]
+
+ calls.clear()
+ studio_mod._emit_run_cloudflare_notice(run_mod, "::", "198.51.100.7", 8888, False)
+ assert calls == [
+ ("verify", "198.51.100.7", 8888),
+ ("print", {"secure": False, "loopback_host": "::1"}),
+ ]
+
+ calls.clear()
+ studio_mod._emit_run_cloudflare_notice(run_mod, "127.0.0.1", "127.0.0.1", 8888, False)
+ assert calls == []
+
+
+def test_run_silent_emits_cloudflare_notice_for_external_bind(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 _Done(SystemExit):
+ pass
+
+ class _ShutdownEvent:
+ def is_set(self):
+ raise _Done(0)
+
+ def wait(self, timeout = None):
+ return None
+
+ class _App:
+ class state:
+ server_port = 8888
+ cloudflare_url = "https://x.trycloudflare.com"
+
+ calls = []
+ backend = types.ModuleType("studio.backend.run")
+ backend.run_server = lambda **_kwargs: _App()
+ backend._resolve_external_ip = lambda: "198.51.100.7"
+ backend._verify_global_reachability = lambda host, port: calls.append(("verify", host, port))
+ backend._print_cloudflare_line = lambda **kw: calls.append(("print", kw))
+ backend._server = object()
+ backend._shutdown_event = _ShutdownEvent()
+ backend._graceful_shutdown = lambda server: calls.append(("shutdown", server))
+ monkeypatch.setitem(sys.modules, "studio.backend.run", backend)
+ monkeypatch.setattr(studio_mod, "_RUN_MODULE", backend)
+
+ state_mod = types.ModuleType("state")
+ tp_mod = types.ModuleType("state.tool_policy")
+ tp_mod.set_tool_policy = lambda *a, **k: None
+ state_mod.tool_policy = tp_mod
+ monkeypatch.setitem(sys.modules, "state", state_mod)
+ monkeypatch.setitem(sys.modules, "state.tool_policy", tp_mod)
+
+ monkeypatch.setattr(studio_mod, "_wait_for_server", lambda *a, **k: True)
+ monkeypatch.setattr(studio_mod, "_create_api_key_inprocess", lambda name: "sk-test")
+ monkeypatch.setattr(
+ studio_mod,
+ "_load_model_via_http",
+ lambda **_kwargs: {"model": "unsloth/Qwen3-1.7B-GGUF", "context_length": 4096},
+ )
+
+ 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 + ["--silent", "-H", "0.0.0.0"],
+ catch_exceptions = True,
+ )
+
+ assert result.exit_code == 0, result.output
+ assert ("verify", "198.51.100.7", 8888) in calls
+ assert ("print", {"secure": False, "loopback_host": "127.0.0.1"}) in calls
+
+
# ── parent-level --no-cloudflare with a subcommand is rejected ───────