Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix: warn when localhost resolves to ::1 but Studio is bound only to 127.0.0.1 (#5994)
Matt Van Horn5cdbfef3902a
diff --git a/studio/backend/run.py b/studio/backend/run.pyindex f401bc2ec1d..7e84c41075a 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -157,6 +157,56 @@ def _working_local_url(port: int) -> "str | None":return None+def _localhost_ipv6_mismatch_url(bind_host: str, port: int) -> "str | None":+ """Return the IPv4 loopback URL when localhost will not reach 127.0.0.1.++ Local Studio intentionally binds to 127.0.0.1. On hosts where localhost+ resolves to IPv6 only (::1), a browser pointed at http://localhost:<port>+ fails -- or worse, reaches a different process listening on ::1 -- even+ though http://127.0.0.1:<port> works. Return the IPv4 URL so the caller can+ tell the user which address to open.+ """+ import socket++ if bind_host != "127.0.0.1" or not port or port <= 0:+ return None++ ipv4_url = f"http://127.0.0.1:{port}"++ # Only warn once Studio is confirmed answering on the IPv4 loopback.+ if _working_local_url(port) != ipv4_url:+ return None++ try:+ addr_info = socket.getaddrinfo(+ "localhost", port, socket.AF_UNSPEC, socket.SOCK_STREAM+ )+ except Exception:+ return None++ if not addr_info:+ return None++ has_ipv4_loopback = False+ has_ipv6_loopback = False+ for family, _, _, _, sockaddr in addr_info:+ if family == socket.AF_INET and sockaddr and sockaddr[0] == "127.0.0.1":+ has_ipv4_loopback = True+ elif family == socket.AF_INET6 and sockaddr:+ host = sockaddr[0].split("%", 1)[0]+ if host == "::1":+ has_ipv6_loopback = True++ # A successful connection to ::1 is NOT evidence that Studio is reachable+ # there: Studio binds 127.0.0.1 only, so anything answering on ::1 is a+ # different process -- which is exactly when the user must be steered to+ # 127.0.0.1. Dual-stack localhost is fine (browsers fall back to 127.0.0.1+ # when ::1 refuses), so only the IPv6-only case strands the user.+ if has_ipv6_loopback and not has_ipv4_loopback:+ return ipv4_url+ return None++def _stdout_color_ok() -> bool:"""Whether to emit ANSI color codes on stdout. Mirrors startup_banner."""if os.environ.get("NO_COLOR", "").strip():@@ -169,6 +219,20 @@ def _stdout_color_ok() -> bool:return False+def _print_localhost_ipv6_mismatch_warning(local_url: str, port: int) -> None:+ """Warn that localhost points at ::1 while Studio is bound to 127.0.0.1."""+ use_color = _stdout_color_ok()+ warn_c = "\033[38;5;215;1m" if use_color else ""+ reset = "\033[0m" if use_color else ""++ print(+ f"{warn_c} Warning: localhost resolves to IPv6 (::1), but Unsloth "+ f"Studio is listening on 127.0.0.1 only. Open {local_url} instead of "+ f"http://localhost:{port}.{reset}",+ flush = True,+ )++def _verify_global_reachability(display_host: str, port: int) -> None:"""Probe check-host.net to confirm display_host:port is reachable from thepublic internet. Synchronous so the caller can render output between the@@ -334,6 +398,33 @@ def _verify_global_reachability(display_host: str, port: int) -> None:pass+def _emit_startup_output(host: str, port: int, display_host: str) -> None:+ """Print the access banner plus any post-startup warnings.++ Extracted from ``_run`` so the banner/warning wiring is unit-testable. The+ ``localhost``-to-::1 mismatch warning and the wildcard reachability check+ are mutually exclusive (the mismatch helper returns None for any non+ 127.0.0.1 bind, and wildcard binds are never 127.0.0.1), so the trailing+ stop hint is emitted exactly once.+ """+ wildcard_bind = host in ("0.0.0.0", "::")+ localhost_mismatch_url = _localhost_ipv6_mismatch_url(host, port)+ # For wildcard binds, run the reachability check between the URL section+ # and the stop hint so the stop hint stays last on screen.+ print_studio_access_banner(+ port = port,+ bind_host = host,+ display_host = display_host,+ include_stop_hint = not wildcard_bind and not localhost_mismatch_url,+ )+ if localhost_mismatch_url:+ _print_localhost_ipv6_mismatch_warning(localhost_mismatch_url, port)+ print_studio_stop_hint()+ elif wildcard_bind:+ _verify_global_reachability(display_host, port)+ print_studio_stop_hint()++def _get_pid_on_port(port: int) -> "tuple[int, str] | None":"""Return (pid, process_name) of the process listening on *port*, or None.@@ -823,18 +914,7 @@ def run_server(print(f"TAURI_PORT={port}", flush = True)if not silent:- wildcard_bind = host in ("0.0.0.0", "::")- # For wildcard binds, run the reachability check between the URL- # section and the stop hint so the stop hint stays last on screen.- print_studio_access_banner(- port = port,- bind_host = host,- display_host = display_host,- include_stop_hint = not wildcard_bind,- )- if wildcard_bind:- _verify_global_reachability(display_host, port)- print_studio_stop_hint()+ _emit_startup_output(host, port, display_host)return appdiff --git a/tests/studio/install/test_selection_logic.py b/tests/studio/install/test_selection_logic.pyindex 2a940390185..f1c3130a773 100644--- a/tests/studio/install/test_selection_logic.py+++ b/tests/studio/install/test_selection_logic.py@@ -11,7 +11,9 @@ No GPU, no network, no torch required -- all I/O is monkeypatched."""import importlib.util+import socketimport sys+import typesfrom pathlib import Pathimport pytest@@ -19,6 +21,7 @@ import pytestPACKAGE_ROOT = Path(__file__).resolve().parents[3]MODULE_PATH = PACKAGE_ROOT / "studio" / "install_llama_prebuilt.py"+RUN_MODULE_PATH = PACKAGE_ROOT / "studio" / "backend" / "run.py"SPEC = importlib.util.spec_from_file_location("studio_install_llama_prebuilt", MODULE_PATH)@@ -91,6 +94,39 @@ resolve_simple_install_release_plans = ()+def load_studio_run_module(monkeypatch):+ logger = types.SimpleNamespace(+ debug = lambda *a, **k: None,+ info = lambda *a, **k: None,+ warning = lambda *a, **k: None,+ )+ loggers = types.ModuleType("loggers")+ loggers.get_logger = lambda name: logger+ monkeypatch.setitem(sys.modules, "loggers", loggers)++ startup_banner = types.ModuleType("startup_banner")+ startup_banner.print_studio_access_banner = lambda **k: None+ startup_banner.print_studio_stop_hint = lambda: None+ monkeypatch.setitem(sys.modules, "startup_banner", startup_banner)++ paths = types.ModuleType("utils.paths")+ paths.__path__ = []+ storage_roots = types.ModuleType("utils.paths.storage_roots")+ storage_roots.studio_root = lambda: PACKAGE_ROOT / ".studio-test-root"+ paths.storage_roots = storage_roots+ monkeypatch.setitem(sys.modules, "utils.paths", paths)+ monkeypatch.setitem(sys.modules, "utils.paths.storage_roots", storage_roots)+ monkeypatch.syspath_prepend(str(RUN_MODULE_PATH.parent))++ spec = importlib.util.spec_from_file_location(+ "studio_backend_run_warning_test", RUN_MODULE_PATH+ )+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module++# ---------------------------------------------------------------------------# Helper factories# ---------------------------------------------------------------------------@@ -255,6 +291,198 @@ def mock_windows_runtime(monkeypatch, lines):)+# ===========================================================================+# Studio run.py localhost warning+# ===========================================================================+++class TestStudioLocalhostIpv6Warning:+ def _prepare_loopback(self, run_module, monkeypatch):+ # Studio is confirmed answering on the IPv4 loopback.+ monkeypatch.setattr(+ run_module,+ "_working_local_url",+ lambda port: f"http://127.0.0.1:{port}",+ )++ def _set_getaddrinfo(self, monkeypatch, entries):+ monkeypatch.setattr(socket, "getaddrinfo", lambda *a, **k: entries)++ @staticmethod+ def _ipv4(port = 8888):+ return (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port))++ @staticmethod+ def _ipv6(port = 8888):+ return (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::1", port, 0, 0))++ # -- _localhost_ipv6_mismatch_url ------------------------------------++ def test_ipv4_localhost_does_not_warn(self, monkeypatch):+ run_module = load_studio_run_module(monkeypatch)+ self._prepare_loopback(run_module, monkeypatch)+ self._set_getaddrinfo(monkeypatch, [self._ipv4()])++ assert run_module._localhost_ipv6_mismatch_url("127.0.0.1", 8888) is None++ def test_dual_stack_localhost_does_not_warn(self, monkeypatch):+ # localhost -> both ::1 and 127.0.0.1: browsers fall back to IPv4 when+ # ::1 refuses, so the URL is reachable and no warning is needed.+ run_module = load_studio_run_module(monkeypatch)+ self._prepare_loopback(run_module, monkeypatch)+ self._set_getaddrinfo(monkeypatch, [self._ipv6(), self._ipv4()])++ assert run_module._localhost_ipv6_mismatch_url("127.0.0.1", 8888) is None++ def test_ipv6_only_localhost_returns_ipv4_url(self, monkeypatch, capsys):+ run_module = load_studio_run_module(monkeypatch)+ self._prepare_loopback(run_module, monkeypatch)+ self._set_getaddrinfo(monkeypatch, [self._ipv6()])+ monkeypatch.setattr(run_module, "_stdout_color_ok", lambda: False)++ local_url = run_module._localhost_ipv6_mismatch_url("127.0.0.1", 8888)+ assert local_url == "http://127.0.0.1:8888"++ run_module._print_localhost_ipv6_mismatch_warning(local_url, 8888)+ captured = capsys.readouterr()+ assert "localhost resolves to IPv6 (::1)" in captured.out+ assert "http://127.0.0.1:8888" in captured.out+ assert "http://localhost:8888" in captured.out++ def test_ipv6_listener_does_not_suppress_warning(self, monkeypatch):+ # Regression for the Codex review: a process answering on ::1 is NOT+ # Studio (Studio binds 127.0.0.1 only), so the warning must still fire+ # -- that is exactly when http://localhost would open the wrong service.+ run_module = load_studio_run_module(monkeypatch)+ self._prepare_loopback(run_module, monkeypatch)+ self._set_getaddrinfo(monkeypatch, [self._ipv6()])+ # Even with something listening on ::1, the result is unchanged.+ monkeypatch.setattr(+ run_module,+ "_local_port_open",+ lambda host, port, timeout = 1.0: True,+ )++ assert (+ run_module._localhost_ipv6_mismatch_url("127.0.0.1", 8888)+ == "http://127.0.0.1:8888"+ )++ @pytest.mark.parametrize("host", ["0.0.0.0", "::"])+ def test_network_bind_suppresses_warning(self, monkeypatch, host):+ run_module = load_studio_run_module(monkeypatch)+ self._prepare_loopback(run_module, monkeypatch)+ self._set_getaddrinfo(monkeypatch, [self._ipv6()])++ assert run_module._localhost_ipv6_mismatch_url(host, 8888) is None++ @pytest.mark.parametrize("port", [0, -1])+ def test_non_positive_port_returns_none(self, monkeypatch, port):+ run_module = load_studio_run_module(monkeypatch)+ self._prepare_loopback(run_module, monkeypatch)++ assert run_module._localhost_ipv6_mismatch_url("127.0.0.1", port) is None++ def test_ipv4_not_answering_suppresses_warning(self, monkeypatch):+ # Studio not confirmed on 127.0.0.1 -> do not warn.+ run_module = load_studio_run_module(monkeypatch)+ monkeypatch.setattr(run_module, "_working_local_url", lambda port: None)+ self._set_getaddrinfo(monkeypatch, [self._ipv6()])++ assert run_module._localhost_ipv6_mismatch_url("127.0.0.1", 8888) is None++ def test_empty_resolver_result_suppresses_warning(self, monkeypatch):+ run_module = load_studio_run_module(monkeypatch)+ self._prepare_loopback(run_module, monkeypatch)+ self._set_getaddrinfo(monkeypatch, [])++ assert run_module._localhost_ipv6_mismatch_url("127.0.0.1", 8888) is None++ def test_resolver_error_suppresses_warning(self, monkeypatch):+ run_module = load_studio_run_module(monkeypatch)+ self._prepare_loopback(run_module, monkeypatch)++ def _raise(*_a, **_k):+ raise socket.gaierror("resolver unavailable")++ monkeypatch.setattr(socket, "getaddrinfo", _raise)++ assert run_module._localhost_ipv6_mismatch_url("127.0.0.1", 8888) is None++ # -- _emit_startup_output (banner / warning wiring) ------------------++ def _wire_recorders(self, run_module, monkeypatch):+ calls = {"banner": [], "warning": [], "stop_hint": 0, "reachability": []}+ monkeypatch.setattr(+ run_module,+ "print_studio_access_banner",+ lambda **kwargs: calls["banner"].append(kwargs),+ )+ monkeypatch.setattr(+ run_module,+ "_print_localhost_ipv6_mismatch_warning",+ lambda local_url, port: calls["warning"].append((local_url, port)),+ )+ monkeypatch.setattr(+ run_module,+ "print_studio_stop_hint",+ lambda: calls.__setitem__("stop_hint", calls["stop_hint"] + 1),+ )+ monkeypatch.setattr(+ run_module,+ "_verify_global_reachability",+ lambda display_host, port: calls["reachability"].append(+ (display_host, port)+ ),+ )+ return calls++ def test_emit_startup_output_wires_mismatch_warning(self, monkeypatch):+ run_module = load_studio_run_module(monkeypatch)+ calls = self._wire_recorders(run_module, monkeypatch)+ monkeypatch.setattr(+ run_module,+ "_localhost_ipv6_mismatch_url",+ lambda host, port: "http://127.0.0.1:8888",+ )++ run_module._emit_startup_output("127.0.0.1", 8888, "127.0.0.1")++ assert calls["banner"][0]["include_stop_hint"] is False+ assert calls["warning"] == [("http://127.0.0.1:8888", 8888)]+ assert calls["stop_hint"] == 1+ assert calls["reachability"] == []++ def test_emit_startup_output_plain_localhost(self, monkeypatch):+ run_module = load_studio_run_module(monkeypatch)+ calls = self._wire_recorders(run_module, monkeypatch)+ monkeypatch.setattr(+ run_module, "_localhost_ipv6_mismatch_url", lambda host, port: None+ )++ run_module._emit_startup_output("127.0.0.1", 8888, "127.0.0.1")++ assert calls["banner"][0]["include_stop_hint"] is True+ assert calls["warning"] == []+ assert calls["stop_hint"] == 0+ assert calls["reachability"] == []++ @pytest.mark.parametrize("host", ["0.0.0.0", "::"])+ def test_emit_startup_output_wildcard_runs_reachability(self, monkeypatch, host):+ run_module = load_studio_run_module(monkeypatch)+ calls = self._wire_recorders(run_module, monkeypatch)+ monkeypatch.setattr(+ run_module, "_localhost_ipv6_mismatch_url", lambda h, port: None+ )++ run_module._emit_startup_output(host, 8888, "203.0.113.5")++ assert calls["banner"][0]["include_stop_hint"] is False+ assert calls["warning"] == []+ assert calls["reachability"] == [("203.0.113.5", 8888)]+ assert calls["stop_hint"] == 1++# ===========================================================================# A. normalize_compute_cap# ===========================================================================