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.

fix(studio): stop handing a wildcard bind's public IP to LAN peers (#9912)

Aman Singh5eef8a7b97b4
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 62c617a7b2d..a4c02471eb7 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -176,16 +176,41 @@ def public_check_disabled() -> bool:
return os.environ.get(DISABLE_PUBLIC_CHECK_ENV, "").strip().lower() in {"1", "true", "yes"}
+def _resolve_lan_ip(ip_version: int = 4) -> str:
+ """This machine's own LAN-facing address. No third-party network call.
+
+ Discovery is a UDP route lookup plus the active interfaces; the lookup only
+ fixes the local end of the socket and sends no packet.
+ """
+ from lan_access import detect_lan_addresses
+
+ try:
+ addresses = detect_lan_addresses(ip_version)
+ except Exception:
+ addresses = []
+ if addresses:
+ return addresses[0]
+ return "0.0.0.0" if ip_version == 4 else "::"
+
+
def _resolve_external_ip() -> str:
"""Resolve the machine's external IP address.
Tries, in order:
1. GCE metadata server (instant on Google Cloud VMs)
2. ifconfig.me (anywhere with internet, skipped by UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK)
- 3. LAN IP via UDP socket trick (fallback)
+ 3. The default route's own source address (fallback)
+
+ This is the machine's INTERNET-facing address, used for the reachability
+ probe and the Cloudflare messaging -- not for "another device on your
+ network," which _network_share_host_for_bind answers instead. Step 3 stays
+ a raw route lookup rather than _resolve_lan_ip: that one filters out every
+ address a LAN peer cannot open (WSL's NAT side, link-local), which is the
+ right policy for an address we advertise and the wrong one for a last-resort
+ answer to "where am I".
"""
- import urllib.request
import socket
+ import urllib.request
# 1. GCE metadata server (<10ms on GCE, times out fast elsewhere).
try:
@@ -210,7 +235,8 @@ def _resolve_external_ip() -> str:
except Exception:
pass
- # 3. Fallback: LAN IP via UDP socket trick
+ # 3. Fallback: the source address the default route picks. A UDP connect only
+ # fixes the local end of the socket; nothing is sent to the target.
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
@@ -221,13 +247,20 @@ def _resolve_external_ip() -> str:
return "0.0.0.0"
-def _install_uvicorn_startup_log_rewrite(bind_host: str, display_host: str) -> None:
- """Rewrite Uvicorn's startup log line: swap wildcard bind for the
- externally-reachable address, use our Mac-aware stop hint, and rename the
- prefix to "Unsloth Studio running on"."""
+def _install_uvicorn_startup_log_rewrite(bind_host: str) -> None:
+ """Rewrite Uvicorn's startup log line: swap a wildcard bind for the address
+ this machine answers on, use our Mac-aware stop hint, and rename the prefix
+ to "Unsloth Studio running on".
+
+ The line is a claim about where the server is reachable, so the address is
+ _network_share_host_for_bind's, resolved here rather than passed in so no
+ caller can hand it the internet-facing one (#8868). With no LAN address to
+ name, the guard below leaves uvicorn's raw wildcard.
+ """
import logging
import re
+ display_host = _network_share_host_for_bind(bind_host)
rewrite_host = is_wildcard_host(bind_host) and bool(display_host) and display_host != bind_host
new_suffix = "(To stop: press Ctrl+C -- on macOS, Control+C not Command+C)"
old_suffix_re = re.compile(r"\(Press CTRL\+C to quit\)")
@@ -540,6 +573,26 @@ def _display_host_for_bind(host: str) -> str:
return ipv4_display_host or "::"
+def _network_share_host_for_bind(host: str) -> str:
+ """The address to hand another device on this LAN, or to build the API
+ panel's direct base URL from.
+
+ Deliberately not _display_host_for_bind: that answers "what is this
+ machine's internet-facing address" (right for the reachability probe and the
+ Cloudflare line), and for a wildcard bind that can be a public WAN IP a LAN
+ peer cannot route to (#8868). Only a family the wildcard actually binds is
+ resolved, so an IPv6-only launch is never advertised at an IPv4 address.
+ """
+ wildcard_versions = wildcard_ip_versions(host)
+ if not wildcard_versions:
+ return host
+ for ip_version in wildcard_versions:
+ lan_host = _resolve_lan_ip(ip_version)
+ if not is_wildcard_host(lan_host):
+ return lan_host
+ return host
+
+
def _loopback_bind_host_for(host: str) -> str:
return wildcard_loopback_host(host) or "127.0.0.1"
@@ -553,6 +606,23 @@ def _url_host(host: str) -> str:
)
+def _direct_server_url(host: str, port: int) -> "Optional[str]":
+ """The API panel's direct (non-tunnel) base, or None when this launch has no
+ address worth publishing.
+
+ The frontend prefers any non-null server_url over the origin the client
+ reached, so publishing ``http://0.0.0.0:<port>`` (a wildcard bind with no LAN
+ address: WSL behind NAT, loopback-only) would put an unroutable address in
+ the API examples, the desktop agent command and a copied preview link.
+ """
+ if not port or port <= 0:
+ return None
+ share_host = _network_share_host_for_bind(host)
+ if is_wildcard_host(share_host):
+ return None
+ return f"http://{_url_host(share_host)}:{port}"
+
+
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."""
@@ -623,6 +693,9 @@ def _emit_startup_output(
port = port,
bind_host = host,
display_host = display_host,
+ # The "from another device on your network" line needs the LAN address,
+ # not display_host's possibly-public one (#8868).
+ network_host = _network_share_host_for_bind(host),
include_stop_hint = False,
lan_addresses = lan_addresses,
)
@@ -2621,9 +2694,10 @@ def run_server(
" - reinstall: curl -fsSL https://unsloth.ai/install.sh | sh"
)
- # Resolve once; shared by the log rewrite and banner.
+ # For the banner and the reachability probe; the startup log line resolves
+ # its own, LAN-only, answer.
display_host = _display_host_for_bind(host)
- _install_uvicorn_startup_log_rewrite(host, display_host)
+ _install_uvicorn_startup_log_rewrite(host)
# LoggingMiddleware already logs every unhandled request exception with its full
# traceback as a structured event; without this uvicorn prints the same traceback
# again on stderr and the desktop shell copies it into tauri.log line by line.
@@ -2680,11 +2754,7 @@ def run_server(
app.state.server_port = port if port and port > 0 else None
app.state.server_request_host = None
# Direct (non-tunnel) base for the API panel; resolve wildcard binds to the LAN IP.
- if port and port > 0:
- _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.server_url = _direct_server_url(host, port)
# raw bind address: the keyless exposure warning must tell loopback from a wildcard bind
app.state.bind_host = host
app.state.secure = secure
@@ -2826,7 +2896,7 @@ def run_server(
port = _final_bound_port(_server, port)
app.state.server_port = port
app.state.server_request_host = _bound_request_host(_server)
- app.state.server_url = f"http://{_url_host(_display_host_for_bind(host))}:{port}"
+ app.state.server_url = _direct_server_url(host, port)
app.state.remote_access_port = port
app.state.lan_access_port = port
diff --git a/studio/backend/startup_banner.py b/studio/backend/startup_banner.py
index b8bc8360524..a6c6bc47bdc 100644
--- a/studio/backend/startup_banner.py
+++ b/studio/backend/startup_banner.py
@@ -79,6 +79,7 @@ def print_studio_access_banner(
port: int,
bind_host: str,
display_host: str,
+ network_host: str = "",
include_stop_hint: bool = True,
lan_addresses: "tuple[str, ...]" = (),
) -> None:
@@ -89,6 +90,11 @@ def print_studio_access_banner(
``lan_addresses`` are the addresses a runtime LAN listener (Settings > LAN
access) is already serving on. A loopback launch that carries one is not
reachable on this machine only, so the banner must say where else it answers.
+
+ ``network_host`` is the address printed under "another device on your
+ network", defaulting to ``display_host``. A wildcard-bind caller passes both:
+ ``display_host`` can be a public WAN IP, which is the reachability probe's
+ business and not what a LAN peer can open (#8868).
"""
use_color = stdout_supports_color()
dim = "\033[38;5;245m"
@@ -114,6 +120,12 @@ def print_studio_access_banner(
else:
external_url = f"http://{display_host}:{port}"
+ # Falls back to display_host for a caller with only one address to give.
+ resolved_network_host = network_host or display_host
+ if ":" in resolved_network_host:
+ network_url = f"http://[{resolved_network_host}]:{port}"
+ else:
+ network_url = f"http://{resolved_network_host}:{port}"
# The exact aliases the canned loopback_url is valid for; any other bind (e.g. a specific LAN IP)
# must show its real address, not http://127.0.0.1.
loopback_bind = bind_host in ("127.0.0.1", "localhost", "::1")
@@ -133,18 +145,16 @@ def print_studio_access_banner(
if (listen_all or loopback_bind) and primary_url != alt_local:
lines.append(style(f" (same as {alt_local})", dim))
- if listen_all and display_host not in (
- "127.0.0.1",
- "localhost",
- "::1",
- "0.0.0.0",
- "::",
+ if (
+ listen_all
+ and not is_wildcard_host(resolved_network_host)
+ and resolved_network_host not in ("127.0.0.1", "localhost", "::1")
):
lines.extend(
[
"",
style(" From another device on your network / to share:", dim),
- style(f" {external_url}", secondary),
+ style(f" {network_url}", secondary),
]
)
elif not listen_all and not loopback_bind and external_url != primary_url:
diff --git a/studio/backend/tests/test_lan_access_settings.py b/studio/backend/tests/test_lan_access_settings.py
index 4e3fbc22efb..5d2b660ee6b 100644
--- a/studio/backend/tests/test_lan_access_settings.py
+++ b/studio/backend/tests/test_lan_access_settings.py
@@ -455,8 +455,8 @@ def test_a_specific_host_launch_reports_the_address_it_was_given():
def test_a_wildcard_launch_refreshes_lan_addresses_instead_of_showing_the_public_address(
monkeypatch,
):
- """server_url resolves the public IP for sharing, which behind NAT reaches
- nothing on the LAN and would trip the public-address warning as well."""
+ """The status refreshes every LAN address instead of relying on server_url's
+ single direct base, and never leaks an obsolete public-address value."""
monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda _ip_version = 4: ["192.168.1.24"])
state = _app(
lan_access_launch_managed = True,
diff --git a/studio/backend/tests/test_lan_share_host_resolution.py b/studio/backend/tests/test_lan_share_host_resolution.py
new file mode 100644
index 00000000000..c0583e8ab60
--- /dev/null
+++ b/studio/backend/tests/test_lan_share_host_resolution.py
@@ -0,0 +1,226 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression for #8868: a wildcard bind (``-H 0.0.0.0``) must not hand a
+device on the LAN the machine's public WAN IP.
+
+``_resolve_external_ip()`` (used for the reachability probe and the
+Cloudflare line) can return a public address from ``ifconfig.me`` or the GCE
+metadata server. ``_network_share_host_for_bind()`` is the LAN-only answer --
+no third-party network call -- and is what the "another device on your
+network" banner line and ``app.state.server_url`` must use instead.
+"""
+
+import logging
+import socket
+import urllib.request
+
+import pytest
+
+import lan_access
+import run
+import startup_banner
+from run import _direct_server_url, _network_share_host_for_bind, _resolve_lan_ip
+from startup_banner import print_studio_access_banner
+
+PUBLIC_IP = "104.32.48.18"
+LAN_IP = "192.168.1.50"
+LAN_IPV6 = "fd00::50"
+# What the route lookup reports where detect_lan_addresses declines to advertise
+# anything: WSL's NAT-side address is real and routable from the Windows host,
+# it is just not an address to hand a phone.
+ROUTE_ONLY_IP = "172.29.1.5"
+
+
+class _FakeSocket:
+ """Stand-in for the UDP route lookup: no packet ever leaves the host."""
+
+ def connect(self, addr):
+ pass
+
+ def getsockname(self):
+ return (LAN_IP, 0)
+
+ def close(self):
+ pass
+
+
+def public_and_lan(monkeypatch):
+ """ifconfig.me answers with a public IP; the LAN socket trick answers separately."""
+
+ def _urlopen(req, *args, **kwargs):
+ class _Resp:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def read(self):
+ return PUBLIC_IP.encode()
+
+ url = req if isinstance(req, str) else req.full_url
+ if "metadata.google" in url:
+ raise OSError("not on GCE")
+ return _Resp()
+
+ monkeypatch.setattr(urllib.request, "urlopen", _urlopen)
+ monkeypatch.setattr(socket, "socket", lambda *a, **k: _FakeSocket())
+ monkeypatch.delenv(run.DISABLE_PUBLIC_CHECK_ENV, raising = False)
+
+
+# ── resolution ───────────────────────────────────────────────────────
+
+
+def test_resolve_lan_ip_never_calls_the_network(public_and_lan, monkeypatch):
+ # Only the UDP-socket trick backs this, never urlopen.
+ monkeypatch.setattr(
+ urllib.request,
+ "urlopen",
+ lambda *_args, **_kwargs: pytest.fail("LAN resolution made an HTTP request"),
+ )
+ assert _resolve_lan_ip() == LAN_IP
+
+
+def test_external_ip_prefers_the_public_service(public_and_lan):
+ assert run._resolve_external_ip() == PUBLIC_IP
+
+
+def test_network_share_host_is_lan_not_public(monkeypatch):
+ monkeypatch.setattr(
+ run,
+ "_resolve_lan_ip",
+ lambda ip_version = 4: LAN_IP if ip_version == 4 else LAN_IPV6,
+ )
+ assert _network_share_host_for_bind("0.0.0.0") == LAN_IP
+ assert _network_share_host_for_bind("::") == LAN_IPV6
+ assert _network_share_host_for_bind("::0") == LAN_IPV6
+
+
+def test_network_share_host_is_unchanged_for_a_specific_bind(public_and_lan):
+ # A non-wildcard bind already names its own address; nothing to resolve.
+ assert _network_share_host_for_bind("192.168.1.7") == "192.168.1.7"
+
+
+def test_external_ip_falls_back_to_the_raw_route_address(monkeypatch):
+ """The LAN detector's filtering is right for an address we advertise and wrong
+ as the last resort for "where am I": _resolve_external_ip keeps its own route
+ lookup, so a WSL/NAT host with no public answer still reports a real address."""
+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda _ip_version = 4: [])
+ monkeypatch.setattr(
+ urllib.request,
+ "urlopen",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("offline")),
+ )
+
+ class _RouteSocket(_FakeSocket):
+ def getsockname(self):
+ return (ROUTE_ONLY_IP, 0)
+
+ monkeypatch.setattr(socket, "socket", lambda *a, **k: _RouteSocket())
+ assert run._resolve_external_ip() == ROUTE_ONLY_IP
+ # The sharing resolver still declines, which is the whole point of the split.
+ assert _network_share_host_for_bind("0.0.0.0") == "0.0.0.0"
+
+
+# ── the direct server URL ────────────────────────────────────────────
+
+
+def test_direct_server_url_is_the_lan_address(monkeypatch):
+ monkeypatch.setattr(run, "_resolve_lan_ip", lambda ip_version = 4: LAN_IP)
+ assert _direct_server_url("0.0.0.0", 8888) == f"http://{LAN_IP}:8888"
+
+
+def test_direct_server_url_is_unset_when_no_lan_address_is_detectable(monkeypatch):
+ """Never publish the wildcard: the frontend prefers any non-null server_url
+ over the origin the client actually reached, so http://0.0.0.0:8888 would be
+ what the API panel, the desktop agent command and a copied preview link name."""
+ monkeypatch.setattr(run, "_resolve_lan_ip", lambda ip_version = 4: "0.0.0.0")
+ assert _direct_server_url("0.0.0.0", 8888) is None
+ monkeypatch.setattr(run, "_resolve_lan_ip", lambda ip_version = 6: "::")
+ assert _direct_server_url("::", 8888) is None
+
+
+# ── the uvicorn startup log line ─────────────────────────────────────
+
+
+def uvicorn_log_filters():
+ """The rewrite installs a filter on the uvicorn loggers and never removes it."""
+ loggers = [logging.getLogger(name) for name in ("uvicorn", "uvicorn.error")]
+ saved = [list(log.filters) for log in loggers]
+ yield loggers[1]
+ for log, filters in zip(loggers, saved):
+ log.filters[:] = filters
+
+
+def _rewritten_startup_line(logger, bind_host: str) -> str:
+ record = logger.makeRecord(
+ logger.name,
+ logging.INFO,
+ __file__,
+ 0,
+ "Uvicorn running on %s://%s:%d (Press CTRL+C to quit)",
+ ("http", bind_host, 8888),
+ None,
+ )
+ for log_filter in logger.filters:
+ log_filter.filter(record)
+ return record.getMessage()
+
+
+def test_startup_log_line_names_the_lan_address(uvicorn_log_filters, monkeypatch):
+ """#8868 as reported: the line reads as a claim about where this machine
+ answers, so a wildcard bind must not be rewritten to the public WAN IP."""
+ monkeypatch.setattr(run, "_resolve_lan_ip", lambda ip_version = 4: LAN_IP)
+ run._install_uvicorn_startup_log_rewrite("0.0.0.0")
+ line = _rewritten_startup_line(uvicorn_log_filters, "0.0.0.0")
+ assert f"http://{LAN_IP}:8888" in line
+ assert PUBLIC_IP not in line
+
+
+def test_startup_log_line_keeps_the_wildcard_when_no_lan_address_resolves(
+ uvicorn_log_filters, monkeypatch
+):
+ # The issue's own "expected behavior": say 0.0.0.0 rather than invent an address.
+ monkeypatch.setattr(run, "_resolve_lan_ip", lambda ip_version = 4: "0.0.0.0")
+ run._install_uvicorn_startup_log_rewrite("0.0.0.0")
+ assert "http://0.0.0.0:8888" in _rewritten_startup_line(uvicorn_log_filters, "0.0.0.0")
+
+
+# ── the banner line itself ──────────────────────────────────────────
+
+
+def test_banner_network_line_shows_lan_ip_not_public_ip(capsys):
+ print_studio_access_banner(
+ port = 8888,
+ bind_host = "0.0.0.0",
+ display_host = PUBLIC_IP,
+ network_host = LAN_IP,
+ )
+ out = capsys.readouterr().out
+ assert f"http://{LAN_IP}:8888" in out
+ assert PUBLIC_IP not in out
+
+
+def test_banner_network_line_brackets_ipv6_for_a_wildcard_alias(capsys):
+ print_studio_access_banner(
+ port = 8888,
+ bind_host = "::0",
+ display_host = PUBLIC_IP,
+ network_host = LAN_IPV6,
+ )
+ out = capsys.readouterr().out
+ assert f"http://[{LAN_IPV6}]:8888" in out
+ assert PUBLIC_IP not in out
+
+
+def test_banner_falls_back_to_display_host_when_network_host_is_unset(capsys):
+ # Back-compat for a caller that only ever had one address to give.
+ print_studio_access_banner(
+ port = 8888,
+ bind_host = "0.0.0.0",
+ display_host = "203.0.113.9",
+ )
+ assert "http://203.0.113.9:8888" in capsys.readouterr().out
diff --git a/studio/backend/utils/lan_access_settings.py b/studio/backend/utils/lan_access_settings.py
index 52d4f211406..fed7b14b245 100644
--- a/studio/backend/utils/lan_access_settings.py
+++ b/studio/backend/utils/lan_access_settings.py
@@ -295,9 +295,9 @@ def configure_lan_access(
def _launch_urls(app_state) -> list[str]:
"""Where a launch-managed bind answers on this network.
- A wildcard launch cannot use ``server_url``: run.py builds that from
- ``_display_host_for_bind``, which resolves the machine's public IP for
- sharing, and behind NAT that address reaches nothing on the LAN.
+ A wildcard launch cannot rely only on ``server_url``: run.py gives that
+ direct base one LAN-reachable address, while Settings must show every
+ currently reachable address in each family the launch serves.
"""
if getattr(app_state, "lan_access_wildcard_bind", False):
from lan_access import detect_lan_addresses
diff --git a/tests/studio/test_cli_share_host_lines.py b/tests/studio/test_cli_share_host_lines.py
new file mode 100644
index 00000000000..9ad592f26d8
--- /dev/null
+++ b/tests/studio/test_cli_share_host_lines.py
@@ -0,0 +1,112 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression for #8868: CLI URLs use the LAN host, not the public IP.
+
+The command bodies are checked structurally because they bind, load, and block.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+from unsloth_cli.commands.studio import (
+ _display_host_for_bind,
+ _network_share_host_for_bind,
+ _openable_host_for_bind,
+)
+
+_STUDIO_CLI = Path(__file__).resolve().parents[2] / "unsloth_cli" / "commands" / "studio.py"
+
+PUBLIC_IP = "104.32.48.18"
+LAN_IP = "192.168.1.50"
+
+
+class _RunModule:
+ """Current backend resolver surface."""
+
+ @staticmethod
+ def _display_host_for_bind(host):
+ return PUBLIC_IP if host in ("0.0.0.0", "::") else host
+
+ @staticmethod
+ def _network_share_host_for_bind(host):
+ return LAN_IP if host in ("0.0.0.0", "::") else host
+
+
+class _OlderRunModule:
+ """Compatibility surface for older backends."""
+
+ @staticmethod
+ def _display_host_for_bind(host):
+ return PUBLIC_IP if host in ("0.0.0.0", "::") else host
+
+
+class _NoLanRunModule:
+ """WSL NAT or a loopback-only host: nothing a LAN peer could open."""
+
+ @staticmethod
+ def _display_host_for_bind(host):
+ return PUBLIC_IP if host in ("0.0.0.0", "::") else host
+
+ @staticmethod
+ def _network_share_host_for_bind(host):
+ return host
+
+
+def _function(name: str) -> ast.FunctionDef:
+ tree = ast.parse(_STUDIO_CLI.read_text(encoding = "utf-8"))
+ matches = [
+ node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef) and node.name == name
+ ]
+ assert len(matches) == 1, f"expected exactly one {name}() in studio.py, found {len(matches)}"
+ return matches[0]
+
+
+def _called_names(node: ast.AST) -> list[str]:
+ return [
+ call.func.id
+ for call in ast.walk(node)
+ if isinstance(call, ast.Call) and isinstance(call.func, ast.Name)
+ ]
+
+
+def test_share_host_shim_returns_the_lan_address():
+ assert _network_share_host_for_bind(_RunModule, "0.0.0.0") == LAN_IP
+ assert _display_host_for_bind(_RunModule, "0.0.0.0") == PUBLIC_IP
+
+
+def test_share_host_shim_leaves_a_specific_bind_alone():
+ assert _network_share_host_for_bind(_RunModule, "192.168.1.7") == "192.168.1.7"
+
+
+def test_share_host_shim_keeps_the_only_answer_an_older_run_py_has():
+ assert _network_share_host_for_bind(_OlderRunModule, "0.0.0.0") == PUBLIC_IP
+
+
+def test_openable_host_prefers_the_lan_address():
+ assert _openable_host_for_bind(_RunModule, "0.0.0.0") == LAN_IP
+
+
+def test_openable_host_leaves_a_specific_bind_alone():
+ assert _openable_host_for_bind(_RunModule, "192.168.1.7") == "192.168.1.7"
+
+
+def test_openable_host_falls_back_to_loopback_with_no_lan_address():
+ """A URL to open is never the wildcard: no browser can reach it."""
+ assert _openable_host_for_bind(_NoLanRunModule, "0.0.0.0") == "127.0.0.1"
+ assert _openable_host_for_bind(_NoLanRunModule, "::") == "::1"
+
+
+def test_launch_line_never_resolves_the_internet_facing_address():
+ called = _called_names(_function("studio_default"))
+ assert "_display_host_for_bind" not in called
+ assert "_openable_host_for_bind" in called
+
+
+def test_run_banner_keeps_the_public_address_for_the_reachability_probe_only():
+ called = _called_names(_function("run"))
+ # The remaining call feeds public reachability.
+ assert called.count("_display_host_for_bind") == 1
+ assert "_openable_host_for_bind" in called
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 4df63a54410..6a43088dd01 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -338,11 +338,34 @@ def _display_host_for_bind(run_mod, host: str) -> str:
return run_mod._display_host_for_bind(host)
+def _network_share_host_for_bind(run_mod, host: str) -> str:
+ """Return the LAN-facing host, with a fallback for older backends."""
+ resolver = getattr(run_mod, "_network_share_host_for_bind", None)
+ if resolver is None:
+ return _display_host_for_bind(run_mod, host)
+ return resolver(host)
+
+
def _loopback_bind_host_for(host: str) -> str:
from unsloth_cli._tool_policy import wildcard_loopback_host
return wildcard_loopback_host(host) or "127.0.0.1"
+def _is_wildcard_bind(host: str) -> bool:
+ from unsloth_cli._tool_policy import is_wildcard_host
+ return is_wildcard_host(host)
+
+
+def _openable_host_for_bind(run_mod, host: str) -> str:
+ """The host for a URL we tell the user to open: the LAN address when one
+ resolves, else loopback. A wildcard bind with no LAN address (WSL NAT,
+ loopback-only) must never be printed as-is; no browser can open it."""
+ share_host = _network_share_host_for_bind(run_mod, host)
+ if _is_wildcard_bind(share_host):
+ return _loopback_bind_host_for(host)
+ return share_host
+
+
def _require_bind_host(host: str) -> None:
if isinstance(host, str) and host.strip():
return
@@ -2133,8 +2156,8 @@ def studio_default(
run_server = run_mod.run_server
if not silent:
- display_host = _display_host_for_bind(run_mod, host)
- typer.echo(f"Starting Unsloth Studio on http://{_url_host(display_host)}:{port}")
+ launch_host = _openable_host_for_bind(run_mod, host)
+ typer.echo(f"Starting Unsloth Studio on http://{_url_host(launch_host)}:{port}")
run_kwargs = dict(
host = host,
@@ -2926,8 +2949,10 @@ def run(
context_length_line = _format_context_length_line(result)
# 6. Print banner.
+ # Keep the public host for reachability, but print a LAN or loopback URL.
display_host = _display_host_for_bind(run_mod, host)
- base_url = f"http://{_url_host(display_host)}:{actual_port}"
+ base_host = _openable_host_for_bind(run_mod, host)
+ base_url = f"http://{_url_host(base_host)}:{actual_port}"
sdk_base_url = f"{base_url}/v1"
# run_server started the tunnel during the silent run above (wildcard or --secure).
_cf_url = getattr(app.state, "cloudflare_url", None)