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: add settings-managed LAN access (#8951)
Maheswar Kumarea687ef520ae
diff --git a/README.md b/README.mdindex 6091ff224ad..b86a0c9ec4b 100644--- a/README.md+++ b/README.md@@ -198,7 +198,7 @@ Re-running the current installer replaces a previously selected bundle when the```bashunsloth studio -p 8888```-For LAN or cloud access, add `-H 0.0.0.0` (raw port only; add `--cloudflare` for a public URL). By default, Unsloth is accessible only locally.+For LAN or cloud access, add `-H 0.0.0.0` (raw port only; add `--cloudflare` for a public URL), or turn it on later in Settings > API keys > LAN access. By default, Unsloth is accessible only locally.To reach Unsloth over HTTPS, use `unsloth studio --secure`. Unsloth stays bound to localhost and is reached only through a free Cloudflare tunnel, which publishes it at a public `https://*.trycloudflare.com` URL (it fails closed if the tunnel can't start, so the raw port is never exposed). This makes Unsloth reachable from the internet, so anyone with the link and API key can use it and run code: keep your API key private (see Remote access below).@@ -337,6 +337,8 @@ unsloth studio --secure -p 8888```bashunsloth studio -H 0.0.0.0 -p 8888```+- Settings > API keys > **LAN access**: put Unsloth on the local network from the UI, without relaunching. It adds a listener on this machine's own addresses at the same port and shows each `http://<address>:<port>`, with a QR code to open the first on a phone; Stop returns it to loopback only, and **Start automatically** turns it on at every launch. Blocked until the admin password has been changed.+The Cloudflare tunnel is **off by default**: `-H 0.0.0.0` exposes the raw port only, not a public internet URL. Pair the wildcard bind with `--cloudflare` (`unsloth studio -H 0.0.0.0 --cloudflare`) to also publish a public `https://*.trycloudflare.com` link, or prefer `--secure` (above), which keeps the raw port private. `--cloudflare` has no effect on a loopback bind.On a wildcard bind Unsloth works out the address to share by asking `ifconfig.me` for the public IP, then asks `check-host.net` whether that port is reachable so it can tell you if a firewall is in the way. Both contact a third party. Set `UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK=1` to skip them; the banner then shows the LAN address and no reachability line.diff --git a/studio/backend/lan_access.py b/studio/backend/lan_access.pynew file mode 100644index 00000000000..2a13710da15--- /dev/null+++ b/studio/backend/lan_access.py@@ -0,0 +1,475 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Runtime LAN listener for Unsloth Studio.++Studio binds 127.0.0.1 by default, so a phone or laptop on the same network+cannot reach it without relaunching with ``-H 0.0.0.0``. This module adds a+second uvicorn listener over the already-running app, on the machine's own+network addresses and the same port, and takes it away again -- no restart, and+the loopback socket keeps serving the desktop app throughout.++The listener binds each detected address explicitly rather than the wildcard:+``0.0.0.0`` collides with the loopback socket that already holds the port. It+runs on the primary server's event loop with ``lifespan="off"``, so the app's+startup and shutdown handlers stay owned by the primary server and never fire+twice.++IPv4 only. Every consumer of this (URLs in the UI, the QR code, the frontend+gate) works off the addresses reported here, and a link-local IPv6 URL is not+something a phone can be handed.+"""++from __future__ import annotations++import asyncio+import ipaddress+import platform+import socket+import subprocess+import sys+import threading+import time+from typing import Any, Optional++import uvicorn++from loggers import get_logger+from utils.host_policy import set_lan_connector_active++logger = get_logger(__name__)++# local socket work either way, so exceeding these means the event loop is wedged+_START_TIMEOUT = 10.0+# kept under the ~5s Windows console-close budget run.py's shutdown path works to+_STOP_TIMEOUT = 3.0++# a LAN request already accepted can run for minutes, and it stays a remote caller+# for all of them; on expiry the trust flag is left active rather than downgraded+_DRAIN_TIMEOUT = 300.0++# uvicorn's own default, so a burst queues on the LAN socket as it does on loopback+_LISTEN_BACKLOG = 2048++_lock = threading.RLock()+_server: Any = None+_serve_loop: Any = None+_sockets: tuple[socket.socket, ...] = ()+_port: Optional[int] = None+_error: Optional[str] = None+# stopped listeners whose accepted requests are still running; they remain remote+# callers, so the trust flag stays up until every one of them has drained+_pending_drains = 0+# rebound whole, never mutated: request_on_lan_listener reads it without the lock+_bound_addresses: tuple[str, ...] = ()+++def detect_lan_addresses() -> list[str]:+ """The machine's own reachable IPv4 addresses, default route first.++ Loopback, link-local (169.254/16) and multicast are dropped: none of them is+ an address another device on the network can open. A public address is kept+ -- a cloud VM binding its own public IP is the same operation as a laptop+ binding its Wi-Fi address, and the caller decides whether that is wanted.+ """+ # WSL's NAT-side address belongs to a private Hyper-V network, not the+ # physical LAN. A second device cannot open it directly. Mirrored mode is+ # different: WSL participates in the host's network and its addresses can be+ # reached subject to the host firewall.+ if _wsl_networking_mode() not in (None, "mirrored"):+ return []++ addresses: list[str] = []++ def _add(candidate: str) -> None:+ try:+ parsed = ipaddress.ip_address(candidate)+ except ValueError:+ return+ if parsed.version != 4:+ return+ if parsed.is_loopback or parsed.is_link_local or parsed.is_multicast:+ return+ if parsed.is_unspecified or parsed.is_reserved:+ return+ if candidate not in addresses:+ addresses.append(candidate)++ # a UDP connect only fixes the local end of the socket; nothing is sent to 8.8.8.8+ probe = None+ try:+ probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ probe.connect(("8.8.8.8", 80))+ _add(probe.getsockname()[0])+ except OSError:+ pass+ finally:+ if probe is not None:+ probe.close()++ # every other adapter that is up: the route to 8.8.8.8 picks one source address, and+ # an isolated LAN has no route at all, so neither it nor the hostname enumerates them+ for address in _interface_addresses():+ _add(address)+ return addresses+++def _wsl_networking_mode() -> Optional[str]:+ """The active WSL networking mode, or ``None`` outside WSL.++ An older WSL without ``wslinfo`` is treated as unknown and therefore not+ advertised. Older releases use NAT, so failing closed avoids handing a phone+ an address that only the Windows host can route to.+ """+ if sys.platform != "linux" or "microsoft" not in platform.release().casefold():+ return None+ try:+ result = subprocess.run(+ ["wslinfo", "--networking-mode"],+ capture_output = True,+ check = False,+ text = True,+ timeout = 1,+ )+ except (OSError, subprocess.SubprocessError):+ return "unknown"+ mode = result.stdout.strip().casefold()+ return mode or "unknown"+++def _is_host_only_interface(name: str) -> bool:+ """True for Windows Hyper-V switches that do not face the physical LAN."""+ normalized = name.strip().casefold()+ if not normalized.startswith("vethernet ("):+ return False+ return any(+ marker in normalized+ for marker in ("default switch", "wsl", "hyper-v firewall", "host-only")+ )+++def _interface_addresses() -> list[str]:+ """IPv4 addresses on every interface that is up.++ Falls back to resolving the hostname where psutil is unavailable. That+ fallback is not an enumeration: a Linux host mapping its name to 127.0.1.1+ reports nothing, which is why it is the last resort rather than the source.+ """+ try:+ import psutil+ except ImportError:+ try:+ return [+ info[4][0]+ for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET)+ ]+ except OSError:+ return []+ try:+ stats = psutil.net_if_stats()+ addresses = []+ for name, entries in psutil.net_if_addrs().items():+ if _is_host_only_interface(name):+ continue+ interface = stats.get(name)+ if interface is not None and not interface.isup:+ continue+ addresses.extend(e.address for e in entries if e.family == socket.AF_INET)+ return addresses+ except Exception:+ return []+++def is_public_address(address: str) -> bool:+ """True when ``address`` is routable from the internet, not just this network.++ A VPS or dedicated box usually carries its public IPv4 straight on the NIC, so+ the addresses this module binds are not always the LAN addresses the name+ implies. Callers surface that rather than refusing it: a public-IP campus or+ office network is a legitimate place to serve, and only the operator knows+ which one they are on.+ """+ try:+ return ipaddress.ip_address(address).is_global+ except ValueError:+ return False+++def _bind_listener(address: str, port: int) -> socket.socket:+ """A listening socket on exactly ``address:port``."""+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ # skipped on Windows, where SO_REUSEADDR lets a socket take over a live listener+ if sys.platform != "win32":+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ sock.bind((address, port))+ sock.listen(_LISTEN_BACKLOG)+ sock.set_inheritable(False)+ except BaseException:+ sock.close()+ raise+ return sock+++def _listener_config(app, host: str, port: int):+ from utils.uvicorn_h11_shutdown import uvicorn_http_protocol+ return uvicorn.Config(+ app,+ host = host,+ port = port,+ # a second lifespan would re-fire the app's startup handlers+ lifespan = "off",+ # uvicorn.Config applies log_config eagerly, resetting run.py's startup log rewrite+ log_config = None,+ access_log = False,+ server_header = False,+ http = uvicorn_http_protocol(),+ )+++def _running_on_event_loop() -> bool:+ """True when the caller is already inside a running event loop."""+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ return False+ return True+++def _wait_until(predicate, timeout: float) -> bool:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return True+ time.sleep(0.01)+ return predicate()+++def start_lan_listener(app, loop, port: int) -> tuple[str, ...]:+ """Serve ``app`` on every detected LAN address at ``port``. Idempotent.++ Returns the bound addresses. Raises ``RuntimeError`` with a machine-readable+ reason (``no_lan_address``, ``bind_failed``, ``listener_start_failed``) when+ the listener could not be brought up.+ """+ global _server, _serve_loop, _sockets, _bound_addresses, _port, _error++ with _lock:+ if _server is not None:+ return _bound_addresses++ candidates = detect_lan_addresses()+ if not candidates:+ _error = "no_lan_address"+ raise RuntimeError(_error)++ sockets: list[socket.socket] = []+ bound: list[str] = []+ failures: list[str] = []+ for address in candidates:+ try:+ sockets.append(_bind_listener(address, port))+ except OSError as exc:+ failures.append(f"{address} ({exc})")+ continue+ bound.append(address)+ if not sockets:+ _error = "bind_failed"+ logger.warning("LAN access could not bind port %s: %s", port, "; ".join(failures))+ raise RuntimeError(_error)+ if failures:+ logger.info("LAN access skipped unbindable addresses: %s", "; ".join(failures))++ server = uvicorn.Server(_listener_config(app, bound[0], port))+ # published before the socket can accept: a request served in between would+ # still read the loopback-only trust defaults+ set_lan_connector_active(True)+ serving = server.serve(sockets = sockets)+ try:+ future = asyncio.run_coroutine_threadsafe(serving, loop)+ except RuntimeError as exc:+ # the loop can close between _server_loop validating it and this call+ serving.close()+ _fail_start(sockets, port, exc)+ raise RuntimeError(_error) from exc+ started = _wait_until(lambda: server.started or future.done(), _START_TIMEOUT)+ if not started or not server.started:+ server.should_exit = True+ cause = future.exception(timeout = 0) if future.done() else None+ future.cancel()+ _fail_start(sockets, port, cause if cause is not None else "timed out")+ raise RuntimeError(_error)++ _server, _serve_loop, _sockets = server, loop, tuple(sockets)+ _bound_addresses, _port, _error = tuple(bound), port, None++ logger.info("LAN access listening on %s", ", ".join(f"{a}:{port}" for a in bound))+ return _bound_addresses+++def _sync_lan_trust() -> None:+ """Publish the beyond-loopback flag from the authoritative state.++ Derived rather than assigned by callers: a repeated stop, or a start racing a+ stop in another worker thread, otherwise cleared a flag that a live listener+ or a still-draining one owned. The caller holds ``_lock``.+ """+ set_lan_connector_active(_server is not None or _pending_drains > 0)+++def _release_listener_state() -> None:+ """Drop the listener references. The caller holds ``_lock``."""+ global _server, _serve_loop, _sockets, _port++ _server = _serve_loop = None+ _sockets = ()+ _port = None+ _sync_lan_trust()+++def _fail_start(sockets, port: int, cause) -> None:+ """Undo a start that never came up. The caller holds ``_lock``."""+ global _error++ _close_sockets(sockets)+ _sync_lan_trust()+ _error = "listener_start_failed"+ logger.warning("LAN access listener did not start on port %s: %s", port, cause)+++def _arm_drain_watcher(server) -> None:+ """Own the trust flag until ``server``'s accepted requests end. Caller holds ``_lock``."""+ global _pending_drains++ _pending_drains += 1+ threading.Thread(+ target = _clear_trust_after_drain,+ args = (server,),+ name = "lan-access-drain",+ daemon = True,+ ).start()+++def _clear_trust_after_drain(server) -> None:+ """Hold the beyond-loopback flag until the stopped listener's requests finish.++ Closing the listening sockets stops new connections, but uvicorn then drains+ the accepted ones, and a request that started on the LAN is still a remote+ caller for its whole life.+ """+ global _pending_drains++ state = getattr(server, "server_state", None)+ deadline = time.monotonic() + _DRAIN_TIMEOUT+ while state is not None and state.connections and time.monotonic() < deadline:+ time.sleep(0.05)+ with _lock:+ if state is not None and state.connections:+ # ownership is never given up: a request that never ended is still remote+ logger.warning("LAN access kept the trust flag on: connections did not drain")+ return+ _pending_drains -= 1+ _sync_lan_trust()+++def _close_sockets(sockets) -> None:+ for sock in sockets:+ try:+ sock.close()+ except OSError:+ pass+++def stop_lan_listener() -> bool:+ """Release the LAN sockets and take the listener down. Idempotent.++ Returns whether the port is confirmed released. A False means the sockets may+ still be accepting, so the caller must keep treating the host as reachable.++ Waits for the sockets, not for ``serve()`` to return: uvicorn closes the+ sockets passed to it at the top of its shutdown and only then drains+ in-flight responses, so waiting on the serve task would make a Stop pressed+ from a LAN device wait out its own response.+ """+ global _server, _serve_loop, _sockets, _bound_addresses, _port, _error++ # a start holds _lock while waiting for this loop to run serve(), so a stop that+ # arrives on the loop itself must not block on it or the two wait each other out+ if not _lock.acquire(blocking = not _running_on_event_loop()):+ logger.info("LAN access stop deferred: a listener change is in flight")+ return False+ # held across the wait so a start cannot begin rebinding sockets still closing+ try:+ server, loop, sockets = _server, _serve_loop, _sockets+ port = _port+ # closed before the wait so a request landing mid-teardown already reads as off+ _bound_addresses = ()++ if server is None:+ _release_listener_state()+ return True+ server.should_exit = True+ if _running_on_event_loop():+ # /api/shutdown tears down from a task on this very loop; waiting would deadlock.+ # ownership is kept because uvicorn cannot close the sockets until the loop is+ # free again, and _graceful_shutdown blocks it for seconds stopping subprocesses+ logger.info("LAN access stopping")+ return True+ if loop is None or loop.is_closed() or not loop.is_running():+ # nothing is left to run uvicorn's shutdown, so release the sockets here+ _close_sockets(sockets)+ _release_listener_state()+ logger.info("LAN access stopped with its server loop")+ return True+ if _wait_until(lambda: all(sock.fileno() == -1 for sock in sockets), _STOP_TIMEOUT):+ # armed before the release so the flag is never briefly unowned+ _arm_drain_watcher(server)+ _release_listener_state()+ logger.info("LAN access stopped")+ return True+ # ownership is kept so a retry waits on these same sockets, and so a second+ # stop cannot report success while the port may still be accepting+ _error = "stop_timed_out"+ logger.warning("LAN access did not release port %s within %ss", port, _STOP_TIMEOUT)+ return False+ finally:+ _lock.release()+++def lan_listener_status() -> dict:+ """Runtime view of the listener: whether it serves, where, and why not."""+ with _lock:+ return {+ "running": _server is not None,+ "addresses": list(_bound_addresses),+ "port": _port,+ "error": _error,+ }+++def clear_lan_listener_error() -> None:+ """Drop a recorded failure so a retry starts from a clean status."""+ global _error+ with _lock:+ _error = None+++def request_on_lan_listener(scope) -> bool:+ """True when this request arrived on a LAN listener socket, not on loopback.++ ``scope["server"]`` is the accepting socket's own address, so it identifies+ the listener a connection came in on without trusting any client header.+ """+ addresses = _bound_addresses+ if not addresses:+ return False+ server = scope.get("server")+ return bool(server) and server[0] in addresses+++def close_lan_listener_lifecycle() -> None:+ """Shutdown hook: never raise, whatever state the listener is in."""+ try:+ stop_lan_listener()+ except Exception as exc:+ logger.warning("Error stopping the LAN listener: %s", exc)diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 354680b8024..49abd0fae82 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -2283,13 +2283,24 @@ def _is_live_cloudflare_frontend_request(scope, app_state) -> bool:return bool(expected_host) and request_host == expected_host+def _is_remote_frontend_request(scope, app_state) -> bool:+ """True for a request the desktop backend may answer with its packaged web UI.++ Two ways in, both identified by the connection itself rather than a client+ header the caller controls: Cloudflare's own edge, or one of the sockets the+ runtime LAN listener bound (Settings > LAN access).+ """+ from lan_access import request_on_lan_listener+ return _is_live_cloudflare_frontend_request(scope, app_state) or request_on_lan_listener(scope)++class _TunnelOnlyFrontend:def __init__(self, frontend_app, app_state):self.frontend_app = frontend_appself.app_state = app_stateasync def __call__(self, scope, receive, send):- if scope["type"] != "http" or _is_live_cloudflare_frontend_request(scope, self.app_state):+ if scope["type"] != "http" or _is_remote_frontend_request(scope, self.app_state):await self.frontend_app(scope, receive, send)returnawait Response(status_code = 404)(scope, receive, send)@@ -2301,7 +2312,11 @@ def setup_frontend(*,tunnel_only: bool = False,):- """Mount frontend static files (optional)"""+ """Mount frontend static files (optional).++ ``tunnel_only`` restricts the mount to remote callers: the Cloudflare edge, or+ a socket the runtime LAN listener bound. See :func:`_is_remote_frontend_request`.+ """if not build_path.exists():return False@@ -2317,7 +2332,7 @@ def setup_frontend(app.mount("/assets", assets_app, name = "assets")def _frontend_request_allowed(request: Request) -> bool:- return not tunnel_only or _is_live_cloudflare_frontend_request(request.scope, app.state)+ return not tunnel_only or _is_remote_frontend_request(request.scope, app.state)def _build_index_response(request: Request) -> Response:content = (build_path / "index.html").read_bytes()diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 3c8e730d31c..d19374fdb59 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -95,6 +95,12 @@ from utils.preview_sharing_settings import (get_preview_sharing_enabled,set_preview_sharing_enabled,)+from utils.lan_access_settings import (+ lan_access_status,+ set_lan_access_auto_start,+ start_lan_access,+ stop_lan_access,+)from utils.remote_access_settings import (DEFAULT_REMOTE_ACCESS_AUTO_START,remote_access_status,@@ -1801,6 +1807,82 @@ def update_remote_access_auto_start(return _remote_access_response(request)+class LanAccessAutoStartPayload(BaseModel):+ enabled: StrictBool+++class LanAccessResponse(BaseModel):+ state: Literal["off", "online", "error"]+ urls: list[str] = []+ public_urls: list[str] = []+ error: Optional[str] = None+ auto_start: bool+ managed_by: Optional[Literal["launch", "settings"]] = None+ can_start: bool+ can_stop: bool+ block_reason: Optional[str] = None+ serves_web_ui: bool = True+++def _lan_access_response(request: Request) -> LanAccessResponse:+ return LanAccessResponse(**lan_access_status(request.app))++[email protected]("/lan-access", response_model = LanAccessResponse)+def get_lan_access(+ request: Request,+ current_subject: str = Depends(get_current_subject),+ _ui_session: None = Depends(_require_ui_session),+) -> LanAccessResponse:+ return _lan_access_response(request)++[email protected]("/lan-access/start", response_model = LanAccessResponse)+def start_lan_access_route(+ request: Request,+ current_subject: str = Depends(get_current_subject),+ _ui_session: None = Depends(_require_ui_session),+) -> LanAccessResponse:+ try:+ response = LanAccessResponse(**start_lan_access(request.app))+ except RuntimeError as exc:+ raise HTTPException(status_code = 409, detail = str(exc)) from exc+ logger.info("settings.lan_access_start_requested subject=%s", current_subject)+ return response++[email protected]("/lan-access/stop", response_model = LanAccessResponse)+def stop_lan_access_route(+ request: Request,+ current_subject: str = Depends(get_current_subject),+ _ui_session: None = Depends(_require_ui_session),+) -> LanAccessResponse:+ try:+ response = LanAccessResponse(**stop_lan_access(request.app))+ except RuntimeError as exc:+ raise HTTPException(status_code = 409, detail = str(exc)) from exc+ logger.info("settings.lan_access_stop_requested subject=%s", current_subject)+ return response++[email protected]("/lan-access/auto-start", response_model = LanAccessResponse)+def update_lan_access_auto_start(+ request: Request,+ payload: LanAccessAutoStartPayload,+ current_subject: str = Depends(get_current_subject),+ _ui_session: None = Depends(_require_ui_session),+) -> LanAccessResponse:+ if bool(getattr(request.app.state, "lan_access_is_colab", False)):+ raise HTTPException(status_code = 409, detail = "colab")+ set_lan_access_auto_start(payload.enabled)+ logger.info(+ "settings.lan_access_auto_start_updated subject=%s enabled=%s",+ current_subject,+ payload.enabled,+ )+ return _lan_access_response(request)++@router.get("/preview-sharing", response_model = PreviewSharingResponse)def get_preview_sharing(current_subject: str = Depends(get_current_subject),diff --git a/studio/backend/run.py b/studio/backend/run.pyindex 760b4d3e077..b65c1fecfdd 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -585,9 +585,14 @@ def _emit_startup_output(display_host: str,secure: bool = False,enable_tools: "Optional[bool]" = None,+ lan_addresses: "tuple[str, ...]" = (),) -> None:"""Print the access banner, post-startup warnings, the tool-policy notice,- then a single stop hint. Extracted from ``_run`` so the wiring is testable."""+ then a single stop hint. Extracted from ``_run`` so the wiring is testable.++ ``lan_addresses`` are the addresses a persisted Settings > LAN access+ auto-start has already bound. A loopback launch carrying them is network+ reachable, so both the banner and the tool-policy notice must say so."""if secure:_emit_secure_startup_output(port, enable_tools)return@@ -598,13 +603,14 @@ def _emit_startup_output(bind_host = host,display_host = display_host,include_stop_hint = False,+ lan_addresses = lan_addresses,)if localhost_mismatch_url:_print_localhost_ipv6_mismatch_warning(localhost_mismatch_url, port)elif wildcard_bind:_verify_global_reachability(display_host, port)_print_cloudflare_line(loopback_host = _loopback_bind_host_for(host))- _emit_tool_policy_notice(host, False, enable_tools)+ _emit_tool_policy_notice(lan_addresses[0] if lan_addresses else host, False, enable_tools)print_studio_stop_hint()@@ -1481,6 +1487,13 @@ def _graceful_shutdown(server = None):"""logger.info("Graceful shutdown initiated -- cleaning up subprocesses...")+ # 0. Drop the LAN listener first: it shares the loop uvicorn is about to stop.+ try:+ from lan_access import close_lan_listener_lifecycle+ close_lan_listener_lifecycle()+ except Exception as e:+ logger.warning("Error stopping the LAN listener: %s", e)+# 1. Shut down uvicorn (releases the listening socket).if server is not None:server.should_exit = True@@ -2388,12 +2401,12 @@ def run_server(desktop_owned = _desktop_owner() is not None,)- # A desktop-owned API-only backend mounts the packaged SPA behind a- # Cloudflare-only request gate so Remote access can serve the WebUI without- # changing the direct local API-only surface.+ # desktop api-only serves its packaged SPA to remote callers only: tunnel or LAN, not loopback+ _frontend_mounted = Falseif frontend_path and _serve_frontend:chosen, attempted = _resolve_frontend_path(Path(frontend_path))if chosen is not None and setup_frontend(app, chosen, tunnel_only = _tunnel_only_frontend):+ _frontend_mounted = Trueif not silent:# Resolve so logs show an absolute path for support.try:@@ -2405,7 +2418,8 @@ def run_server(# Remote access serves nothing; the local API the desktop asked for# still comes up. The tunnel gate already 404s every other request.logger.warning(- "No frontend build found, so Remote access will not serve the web UI. Tried: %s",+ "No frontend build found, so Remote and LAN access will not serve the web UI. "+ "Tried: %s",", ".join(str(p) for p in attempted) or "(none)",)else:@@ -2532,6 +2546,17 @@ def run_server(launch_managed = _launch_tunnel_managed,)+ from utils.lan_access_settings import configure_lan_access++ configure_lan_access(+ app.state,+ port = port,+ bind_host = host,+ secure = secure,+ is_colab = _IS_COLAB,+ frontend_served = _serve_frontend and _frontend_mounted,+ )+# Expose a shutdown callable before the server accepts requests so# /api/shutdown is ready as soon as readiness publishes.def _trigger_shutdown():@@ -2583,6 +2608,8 @@ def run_server(def _run():loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)+ # settings > LAN access adds its listener to this loop from a request thread+ app.state.lan_access_loop = looptry:loop.run_until_complete(_server.serve())except BaseException as exc:@@ -2600,6 +2627,11 @@ def run_server(# which is why the marker goes here rather than in _remove_pid_file._remove_startup_marker()_remove_pid_file()+ # the loop is closed above, so this is what an embedded host that calls+ # run_server again needs to stop seeing the previous listener as live+ from lan_access import close_lan_listener_lifecycle as _close_lan_listener++ _close_lan_listener()thread = Thread(target = _run, daemon = True)_server_thread = thread@@ -2630,6 +2662,7 @@ def run_server(app.state.server_port = portapp.state.server_url = f"http://{_url_host(_display_host_for_bind(host))}:{port}"app.state.remote_access_port = port+ app.state.lan_access_port = port_write_pid_file(port, host)import atexit@@ -2665,6 +2698,7 @@ def run_server(set_studio_tunnel_runtime_callback(set_remote_connector_active)set_studio_tunnel_url_callback(lambda url: _publish_cloudflare_url(app.state, url))app.state.remote_access_ready = True+ app.state.lan_access_ready = True# 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@@ -2737,8 +2771,22 @@ def run_server(if maybe_auto_start_remote_access(app.state):logger.info("Remote access auto-start scheduled")+ from lan_access import close_lan_listener_lifecycle, lan_listener_status+ from utils.lan_access_settings import maybe_auto_start_lan_access++ atexit.register(close_lan_listener_lifecycle)+ if maybe_auto_start_lan_access(app):+ logger.info("LAN access auto-started")+if not silent:- _emit_startup_output(host, port, display_host, secure = secure, enable_tools = enable_tools)+ _emit_startup_output(+ host,+ port,+ display_host,+ secure = secure,+ enable_tools = enable_tools,+ lan_addresses = tuple(lan_listener_status()["addresses"]),+ )return appdiff --git a/studio/backend/startup_banner.py b/studio/backend/startup_banner.pyindex 9ec7a4f91c7..fc38b10eb01 100644--- a/studio/backend/startup_banner.py+++ b/studio/backend/startup_banner.py@@ -78,10 +78,16 @@ def print_studio_access_banner(bind_host: str,display_host: str,include_stop_hint: bool = True,+ lan_addresses: "tuple[str, ...]" = (),) -> None:"""Pretty-print URLs once the server is listening. Set``include_stop_hint=False`` to omit the trailing stop block; pair with- :func:`print_studio_stop_hint` after inserting your own content."""+ :func:`print_studio_stop_hint` after inserting your own content.++ ``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.+ """use_color = stdout_supports_color()dim = "\033[38;5;245m"title = "\033[38;5;150m"@@ -160,22 +166,33 @@ def print_studio_access_banner()if loopback_bind and not listen_all:- lines.extend(- [- "",- style(- " Reachable on this machine only (bound to 127.0.0.1).",- secondary,- ),- style(- f" To expose it, stop and relaunch with: unsloth studio -H 0.0.0.0 -p {port}",- secondary,- ),- style(- " Only on trusted networks -- anyone who reaches this machine can use Unsloth.",- secondary,- ),- ]+ if lan_addresses:+ lines.append("")+ lines.append(+ style(" LAN access is on -- also reachable on your network at:", secondary)+ )+ lines.extend(style(f" http://{a}:{port}", secondary) for a in lan_addresses)+ lines.append(style(" Turn it off in Settings > API keys > LAN access.", secondary))+ else:+ lines.extend(+ [+ "",+ style(+ " Reachable on this machine only (bound to 127.0.0.1).",+ secondary,+ ),+ style(+ " To expose it, turn on Settings > API keys > LAN access, or "+ f"relaunch with: unsloth studio -H 0.0.0.0 -p {port}",+ secondary,+ ),+ ]+ )+ lines.append(+ style(+ " Only on trusted networks -- anyone who reaches this machine can use Unsloth.",+ secondary,+ ))if include_stop_hint:diff --git a/studio/backend/tests/test_lan_access_settings.py b/studio/backend/tests/test_lan_access_settings.pynew file mode 100644index 00000000000..b95d372dd56--- /dev/null+++ b/studio/backend/tests/test_lan_access_settings.py@@ -0,0 +1,1002 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import ast+import asyncio+import json+import socket+import sys+import threading+import time+import urllib.error+import urllib.request+from pathlib import Path+from types import SimpleNamespace++import pytest++# module scope, not the fixture: postponed annotations resolve against module globals+from fastapi import FastAPI, HTTPException, Request++_BACKEND = Path(__file__).resolve().parents[1]+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++import lan_access # noqa: E402+import routes.settings as routes # noqa: E402+import utils.host_policy as host_policy # noqa: E402+import utils.lan_access_settings as lan_settings # noqa: E402+from storage import studio_db # noqa: E402+++def _app(**over):+ state = SimpleNamespace(+ lan_access_port = 8888,+ lan_access_ready = True,+ lan_access_is_colab = False,+ lan_access_launch_managed = False,+ lan_access_wildcard_bind = False,+ lan_access_secure_launch = False,+ lan_access_frontend_served = True,+ lan_access_loop = None,+ server_url = "http://192.168.1.24:8888",+ )+ for key, value in over.items():+ setattr(state, key, value)+ return SimpleNamespace(state = state)++[email protected](autouse = True)+def stored_settings(monkeypatch):+ """Keep every test off the real listener state, password store and database."""+ stored: dict = {}+ monkeypatch.setattr(lan_settings, "_admin_password_ready", lambda: True)+ monkeypatch.setattr(+ studio_db, "get_app_setting", lambda key, fallback: stored.get(key, fallback)+ )+ monkeypatch.setattr(studio_db, "upsert_app_settings", stored.update)+ yield stored+ lan_access.stop_lan_listener()+ lan_access.clear_lan_listener_error()+ # drain watchers are daemon threads that outlive their test, so the shared+ # counter has to be reset or a later decrement lands on the next test's state+ lan_access._pending_drains = 0+ host_policy._reset_loopback_default_state()+++# ── persisted preference ──+++def test_auto_start_persistence_is_strict_and_fail_closed(monkeypatch, stored_settings):+ assert lan_settings.get_lan_access_auto_start() is False+ stored_settings[lan_settings.LAN_ACCESS_AUTO_START_KEY] = "yes"+ assert lan_settings.get_lan_access_auto_start() is False+ assert lan_settings.set_lan_access_auto_start(True) is True+ assert lan_settings.get_lan_access_auto_start() is True+ with pytest.raises(ValueError):+ routes.LanAccessAutoStartPayload(enabled = "true")+ with pytest.raises(ValueError):+ lan_settings.set_lan_access_auto_start("true")+ monkeypatch.setattr(+ studio_db, "get_app_setting", lambda *args: (_ for _ in ()).throw(OSError())+ )+ assert lan_settings.get_lan_access_auto_start() is False+++# ── launch policy ──+++ "bind_host,launch_managed",+ [+ ("127.0.0.1", False),+ ("localhost", False),+ ("::1", False),+ ("0.0.0.0", True),+ ("::", True),+ ("192.168.1.24", True),+ ],+)+def test_configure_reads_launch_ownership_from_the_bind_host(bind_host, launch_managed):+ state = SimpleNamespace()+ lan_settings.configure_lan_access(+ state,+ port = 8888,+ bind_host = bind_host,+ secure = False,+ is_colab = False,+ frontend_served = True,+ )+ assert state.lan_access_launch_managed is launch_managed+ assert state.lan_access_ready is False+++# ── status ──+++def test_a_loopback_launch_offers_a_startable_off_state():+ status = lan_settings.lan_access_status(_app())+ assert status["state"] == "off"+ assert status["block_reason"] is None+ assert status["can_start"] is True and status["can_stop"] is False+ assert status["urls"] == []+++ "state_over,expected_block",+ [+ ({"lan_access_ready": False}, "server_starting"),+ ({"lan_access_is_colab": True}, "colab"),+ ({"lan_access_launch_managed": True}, "launch_managed"),+ ({"lan_access_secure_launch": True}, "secure_launch"),+ ],+)+def test_every_block_reason_closes_both_controls(state_over, expected_block):+ status = lan_settings.lan_access_status(_app(**state_over))+ assert status["block_reason"] == expected_block+ assert status["can_start"] is False and status["can_stop"] is False+++def test_a_pending_admin_password_blocks_exposing_the_server(monkeypatch):+ monkeypatch.setattr(lan_settings, "_admin_password_ready", lambda: False)+ status = lan_settings.lan_access_status(_app())+ assert status["block_reason"] == "admin_password_change_required"+ assert status["can_start"] is False+++def test_a_specific_host_launch_reports_the_address_it_was_given():+ status = lan_settings.lan_access_status(_app(lan_access_launch_managed = True))+ assert status["state"] == "online" and status["managed_by"] == "launch"+ assert status["urls"] == ["http://192.168.1.24:8888"]+ assert status["can_stop"] is False+++def test_a_wildcard_launch_shows_lan_addresses_not_the_public_sharing_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."""+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda: ["192.168.1.24"])+ state = _app(+ lan_access_launch_managed = True,+ lan_access_wildcard_bind = True,+ server_url = "http://203.0.113.9:8888",+ )+ status = lan_settings.lan_access_status(state)+ assert status["urls"] == ["http://192.168.1.24:8888"]+ assert status["public_urls"] == []++ # detection is not repeated on every poll+ monkeypatch.setattr(+ lan_access, "detect_lan_addresses", lambda: pytest.fail("re-detected on a poll")+ )+ assert lan_settings.lan_access_status(state)["urls"] == ["http://192.168.1.24:8888"]+++def test_a_publicly_routable_bind_is_flagged_so_the_ui_can_warn(monkeypatch):+ """A VPS carries its public IPv4 on the NIC, so "LAN access" can reach the+ internet. Binding it is the operator's call; hiding it is not."""+ monkeypatch.setattr(+ lan_access,+ "lan_listener_status",+ lambda: {+ "running": True,+ "addresses": ["192.168.1.24", "64.227.100.5"],+ "port": 8888,+ "error": None,+ },+ )+ status = lan_settings.lan_access_status(_app())+ assert status["urls"] == ["http://192.168.1.24:8888", "http://64.227.100.5:8888"]+ assert status["public_urls"] == ["http://64.227.100.5:8888"]+++ "address,public",+ [+ ("192.168.1.24", False),+ ("10.0.0.7", False),+ ("172.16.3.9", False),+ # CGNAT, which is where a Tailscale address lands+ ("100.64.1.1", False),+ ("64.227.100.5", True),+ ("8.8.8.8", True),+ ("not-an-ip", False),+ ],+)+def test_public_address_classification(address, public):+ assert lan_access.is_public_address(address) is public+++def test_a_private_bind_carries_no_public_warning(monkeypatch):+ monkeypatch.setattr(+ lan_access,+ "lan_listener_status",+ lambda: {"running": True, "addresses": ["192.168.1.24"], "port": 8888, "error": None},+ )+ assert lan_settings.lan_access_status(_app())["public_urls"] == []+++def test_api_only_launches_advertise_that_the_web_ui_is_not_served():+ assert lan_settings.lan_access_status(_app())["serves_web_ui"] is True+ served = lan_settings.lan_access_status(_app(lan_access_frontend_served = False))+ assert served["serves_web_ui"] is False+++def test_a_failed_start_is_reported_as_an_error_state(monkeypatch):+ monkeypatch.setattr(+ lan_access,+ "lan_listener_status",+ lambda: {"running": False, "addresses": [], "port": None, "error": "no_lan_address"},+ )+ status = lan_settings.lan_access_status(_app())+ assert status["state"] == "error" and status["error"] == "no_lan_address"+ # the failure is retryable: nothing about it blocks a second attempt+ assert status["can_start"] is True+++# ── address detection ──+++def test_detection_drops_addresses_no_other_device_can_open(monkeypatch):+ monkeypatch.setattr(+ lan_access,+ "_interface_addresses",+ lambda: [+ "127.0.0.1",+ "169.254.10.1",+ "224.0.0.1",+ "0.0.0.0",+ "not-an-ip",+ "10.0.0.7",+ "10.0.0.7",+ ],+ )+ addresses = lan_access.detect_lan_addresses()+ assert "10.0.0.7" in addresses+ assert addresses.count("10.0.0.7") == 1+ for rejected in ("127.0.0.1", "169.254.10.1", "224.0.0.1", "0.0.0.0", "not-an-ip"):+ assert rejected not in addresses++[email protected]_network+def test_the_default_route_address_leads_so_it_becomes_the_shown_url(monkeypatch):+ routed = _require_lan_address()+ monkeypatch.setattr(lan_access, "_interface_addresses", lambda: ["203.0.113.9"])+ assert lan_access.detect_lan_addresses() == [routed, "203.0.113.9"]+++def test_detection_survives_a_host_that_resolves_to_nothing(monkeypatch):+ """The hostname fallback only runs without psutil, and a Linux host mapping its+ name to 127.0.1.1 is exactly why it cannot be the source of truth."""++ def _boom(*_args, **_kwargs):+ raise OSError("no such host")++ monkeypatch.setitem(sys.modules, "psutil", None)+ monkeypatch.setattr(lan_access.socket, "getaddrinfo", _boom)+ # under the suite's outbound-network guard the UDP probe is refused too, so+ # a failed lookup must contribute nothing rather than raise+ assert lan_access.detect_lan_addresses() == []++[email protected]_network+def test_detection_enumerates_interfaces_rather_than_the_default_route(monkeypatch):+ """An isolated LAN has no route to 8.8.8.8 and a multihomed host has more than+ one interface, so neither the probe nor the hostname finds every address."""+ routed = _require_lan_address()+ assert routed in lan_access._interface_addresses()++ # with the probe unavailable, enumeration alone still finds the address+ def _no_route(*_args, **_kwargs):+ raise OSError("network is unreachable")++ monkeypatch.setattr(lan_access.socket.socket, "connect", _no_route)+ assert routed in lan_access.detect_lan_addresses()+++def test_interface_enumeration_skips_adapters_that_are_down(monkeypatch):+ import types++ fake = types.SimpleNamespace(+ net_if_stats = lambda: {+ "en0": types.SimpleNamespace(isup = True),+ "en1": types.SimpleNamespace(isup = False),+ },+ net_if_addrs = lambda: {+ "en0": [types.SimpleNamespace(family = socket.AF_INET, address = "10.0.0.7")],+ "en1": [types.SimpleNamespace(family = socket.AF_INET, address = "10.9.9.9")],+ "en2": [types.SimpleNamespace(family = socket.AF_INET6, address = "fe80::1")],+ },+ )+ monkeypatch.setitem(sys.modules, "psutil", fake)+ assert lan_access._interface_addresses() == ["10.0.0.7"]+++def test_interface_enumeration_skips_windows_host_only_switches(monkeypatch):+ import types++ fake = types.SimpleNamespace(+ net_if_stats = lambda: {+ name: types.SimpleNamespace(isup = True)+ for name in (+ "Wi-Fi",+ "vEthernet (Default Switch)",+ "vEthernet (WSL (Hyper-V firewall))",+ "vEthernet (External LAN)",+ )+ },+ net_if_addrs = lambda: {+ "Wi-Fi": [+ types.SimpleNamespace(family = socket.AF_INET, address = "192.168.1.20")+ ],+ "vEthernet (Default Switch)": [+ types.SimpleNamespace(family = socket.AF_INET, address = "172.31.32.1")+ ],+ "vEthernet (WSL (Hyper-V firewall))": [+ types.SimpleNamespace(family = socket.AF_INET, address = "172.25.32.1")+ ],+ # An external Hyper-V switch can replace the physical adapter and is+ # reachable from the LAN, so do not reject every vEthernet interface.+ "vEthernet (External LAN)": [+ types.SimpleNamespace(family = socket.AF_INET, address = "192.168.1.21")+ ],+ },+ )+ monkeypatch.setitem(sys.modules, "psutil", fake)+ assert lan_access._interface_addresses() == ["192.168.1.20", "192.168.1.21"]+++def test_wsl_nat_address_is_not_advertised(monkeypatch):+ monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: "nat")+ monkeypatch.setattr(lan_access, "_interface_addresses", lambda: ["172.25.35.232"])+ assert lan_access.detect_lan_addresses() == []+++def test_wsl_unknown_networking_mode_fails_closed(monkeypatch):+ monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: "unknown")+ monkeypatch.setattr(lan_access, "_interface_addresses", lambda: ["172.25.35.232"])+ assert lan_access.detect_lan_addresses() == []+++def test_wsl_mirrored_networking_keeps_reachable_addresses(monkeypatch):+ monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: "mirrored")+ monkeypatch.setattr(lan_access, "_interface_addresses", lambda: ["192.168.1.20"])+ assert lan_access.detect_lan_addresses() == ["192.168.1.20"]+++# ── live listener ──+++def _free_port() -> int:+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ return probe.getsockname()[1]+++def _get(url: str) -> int:+ with urllib.request.urlopen(url, timeout = 5) as response:+ return response.status+++def _free_port_is_bindable(port: int) -> bool:+ """True when the LAN address can still take ``port``, so nothing leaked a socket."""+ try:+ _bind_listener_probe = lan_access._bind_listener(_require_lan_address(), port)+ except OSError:+ return False+ _bind_listener_probe.close()+ return True+++def _wait_for_trust(expected: bool, timeout: float = 5.0) -> bool:+ """The flag clears on a drain thread once the stopped listener's requests end."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if host_policy.remote_connector_active() is expected:+ return True+ time.sleep(0.02)+ return host_policy.remote_connector_active() is expected+++def _require_lan_address() -> str:+ """The address these tests bind, or a skip on a host with no network address."""+ addresses = lan_access.detect_lan_addresses()+ if not addresses:+ pytest.skip("this host has no LAN address to bind")+ return addresses[0]+++def _refused(url: str) -> bool:+ try:+ _get(url)+ except (urllib.error.URLError, OSError):+ return True+ return False+++def live_server():+ """A loopback uvicorn server on its own loop, the shape run.py starts."""+ import uvicorn++ app = FastAPI()++ @app.get("/where")+ def where(request: Request):+ return {"lan": lan_access.request_on_lan_listener(request.scope)}++ @app.post("/stop-lan")+ def stop_lan():+ started = time.monotonic()+ lan_access.stop_lan_listener()+ return {"seconds": time.monotonic() - started}++ port = _free_port()+ server = uvicorn.Server(uvicorn.Config(app, host = "127.0.0.1", port = port, log_level = "warning"))+ box = {}++ def _run():+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)+ box["loop"] = loop+ loop.run_until_complete(server.serve())++ thread = threading.Thread(target = _run, daemon = True)+ thread.start()+ deadline = time.monotonic() + 10+ while not server.started and time.monotonic() < deadline:+ time.sleep(0.02)+ assert server.started, "primary server never bound"+ yield SimpleNamespace(app = app, loop = box["loop"], port = port)+ lan_access.stop_lan_listener()+ server.should_exit = True+ thread.join(timeout = 10)++[email protected]_network+def test_the_listener_adds_and_removes_network_reach_without_a_restart(live_server):+ address = _require_lan_address()+ lan_url = f"http://{address}:{live_server.port}/where"+ local_url = f"http://127.0.0.1:{live_server.port}/where"++ assert _get(local_url) == 200+ assert _refused(lan_url), "the port was already on the network before starting"++ bound = lan_access.start_lan_listener(live_server.app, live_server.loop, live_server.port)+ assert address in bound+ assert _get(lan_url) == 200+ assert _get(local_url) == 200, "loopback must keep serving while the LAN listener runs"+ assert lan_access.lan_listener_status()["running"] is True++ # a second start is a no-op rather than a second bind on the same address+ again = lan_access.start_lan_listener(live_server.app, live_server.loop, live_server.port)+ assert again == bound++ lan_access.stop_lan_listener()+ assert _refused(lan_url), "the LAN socket outlived stop"+ assert _get(local_url) == 200+ assert lan_access.lan_listener_status() == {+ "running": False,+ "addresses": [],+ "port": None,+ "error": None,+ }++ # the same address rebinds, so a stop does not strand the port until restart+ lan_access.start_lan_listener(live_server.app, live_server.loop, live_server.port)+ assert _get(lan_url) == 200++[email protected]_network+def test_only_traffic_on_a_lan_socket_is_reported_as_lan(live_server):+ address = _require_lan_address()+ lan_access.start_lan_listener(live_server.app, live_server.loop, live_server.port)++ def _lan_flag(host: str) -> bool:+ with urllib.request.urlopen(+ f"http://{host}:{live_server.port}/where", timeout = 5+ ) as response:+ return json.loads(response.read())["lan"]++ assert _lan_flag(address) is True+ assert _lan_flag("127.0.0.1") is False, "loopback traffic must never read as LAN"+++def test_a_start_with_no_usable_address_fails_without_leaving_state(monkeypatch):+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda: [])+ with pytest.raises(RuntimeError, match = "no_lan_address"):+ lan_access.start_lan_listener(object(), object(), 8888)+ status = lan_access.lan_listener_status()+ assert status["running"] is False and status["error"] == "no_lan_address"+ lan_access.clear_lan_listener_error()+ assert lan_access.lan_listener_status()["error"] is None+++def test_a_port_already_taken_on_every_address_fails_closed(monkeypatch):+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda: ["10.0.0.7"])++ def _refuse(*_args, **_kwargs):+ raise OSError("address in use")++ monkeypatch.setattr(lan_access, "_bind_listener", _refuse)+ with pytest.raises(RuntimeError, match = "bind_failed"):+ lan_access.start_lan_listener(object(), object(), 8888)+ assert lan_access.lan_listener_status()["running"] is False++[email protected]_network+def test_an_unbindable_address_does_not_sink_the_ones_that_work(live_server, monkeypatch):+ address = _require_lan_address()+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda: [address, "10.255.255.254"])+ bound = lan_access.start_lan_listener(live_server.app, live_server.loop, live_server.port)+ assert bound == (address,)+ assert _get(f"http://{address}:{live_server.port}/where") == 200++[email protected]_network+def test_stop_from_inside_the_event_loop_does_not_wait_on_itself(live_server):+ """/api/shutdown tears down from a task on the serving loop; blocking there deadlocks."""+ lan_access.start_lan_listener(live_server.app, live_server.loop, live_server.port)++ async def _stop_from_loop():+ started = time.monotonic()+ lan_access.stop_lan_listener()+ return time.monotonic() - started++ elapsed = asyncio.run_coroutine_threadsafe(_stop_from_loop(), live_server.loop).result(+ timeout = 5+ )+ assert elapsed < lan_access._STOP_TIMEOUT+ # the gate closes at once, but ownership and the trust flag stay until uvicorn+ # closes the sockets, which it cannot do while _graceful_shutdown holds the loop+ assert lan_access._bound_addresses == ()+ assert lan_access.lan_listener_status()["running"] is True+ assert host_policy.remote_connector_active() is True++[email protected]_network+def test_a_listener_that_fails_to_serve_gives_up_without_waiting_it_out(live_server, monkeypatch):+ _require_lan_address()++ class _Broken:+ started = False+ should_exit = False++ async def serve(self, sockets = None):+ raise RuntimeError("listener exploded")++ monkeypatch.setattr(lan_access.uvicorn, "Server", lambda _config: _Broken())+ started = time.monotonic()+ with pytest.raises(RuntimeError, match = "listener_start_failed"):+ lan_access.start_lan_listener(live_server.app, live_server.loop, live_server.port)+ assert time.monotonic() - started < lan_access._START_TIMEOUT+ status = lan_access.lan_listener_status()+ assert status["running"] is False and status["error"] == "listener_start_failed"+ # the sockets it opened were released, so the port is free again+ assert _free_port_is_bindable(live_server.port)++[email protected]_network+def test_a_stop_from_a_lan_client_does_not_wait_out_its_own_response(live_server):+ """Settings > Stop pressed on the phone. uvicorn closes the listening sockets at+ the top of its shutdown and only then drains in-flight responses, so a stop that+ waited for serve() to return would be waiting for the very response it is."""+ address = _require_lan_address()+ lan_access.start_lan_listener(live_server.app, live_server.loop, live_server.port)++ request = urllib.request.Request(f"http://{address}:{live_server.port}/stop-lan", method = "POST")+ started = time.monotonic()+ with urllib.request.urlopen(request, timeout = 30) as response:+ handler_seconds = json.loads(response.read())["seconds"]+ assert handler_seconds < lan_access._STOP_TIMEOUT, "the stop waited out its own response"+ assert time.monotonic() - started < lan_access._STOP_TIMEOUT+ assert lan_access.lan_listener_status()["running"] is False+ assert _refused(f"http://{address}:{live_server.port}/where")+++def test_a_stop_that_cannot_confirm_the_port_keeps_the_host_marked_reachable(monkeypatch):+ """The sockets may still be accepting, so the loopback-only trust gates must+ not reopen just because the teardown wait ran out."""++ class _Server:+ should_exit = False++ lingering = socket.socket()+ lingering.bind(("127.0.0.1", 0))+ loop = asyncio.new_event_loop()+ running = threading.Event()++ def _spin():+ loop.call_soon(running.set)+ loop.run_forever()++ thread = threading.Thread(target = _spin, daemon = True)+ thread.start()+ assert running.wait(5)+ monkeypatch.setattr(lan_access, "_STOP_TIMEOUT", 0.2)+ monkeypatch.setattr(lan_access, "_server", _Server())+ monkeypatch.setattr(lan_access, "_serve_loop", loop)+ monkeypatch.setattr(lan_access, "_sockets", (lingering,))+ monkeypatch.setattr(lan_access, "_bound_addresses", ("10.0.0.7",))+ host_policy.set_lan_connector_active(True)++ try:+ app = _app()+ status = lan_settings.stop_lan_access(app)+ assert status["error"] == "stop_timed_out"+ assert host_policy.remote_connector_active() is True+ # ownership is retained, so the stop stays offered and a retry re-waits+ assert status["can_stop"] is True+ assert lan_access.lan_listener_status()["running"] is True++ # a second stop must not report success while the port may still accept+ retried = lan_settings.stop_lan_access(app)+ assert retried["error"] == "stop_timed_out"+ assert host_policy.remote_connector_active() is True++ # once the socket really closes, the retry settles and clears the error+ lingering.close()+ settled = lan_settings.stop_lan_access(app)+ assert settled["state"] == "off" and settled["error"] is None+ assert _wait_for_trust(False)+ finally:+ loop.call_soon_threadsafe(loop.stop)+ thread.join(timeout = 5)+ loop.close()+ lingering.close()+ host_policy.set_lan_connector_active(False)++[email protected]_network+def test_a_schedule_that_cannot_reach_the_loop_releases_the_bound_sockets(live_server, monkeypatch):+ """The loop can close between _server_loop validating it and the schedule call;+ the sockets are bound by then, so that path has to run the start cleanup too."""+ _require_lan_address()++ def _closed(*_args, **_kwargs):+ raise RuntimeError("Event loop is closed")++ monkeypatch.setattr(lan_access.asyncio, "run_coroutine_threadsafe", _closed)+ with pytest.raises(RuntimeError, match = "listener_start_failed"):+ lan_access.start_lan_listener(live_server.app, live_server.loop, live_server.port)++ status = lan_access.lan_listener_status()+ assert status["running"] is False and status["error"] == "listener_start_failed"+ assert host_policy.remote_connector_active() is False, "trust left on with no listener"+ # the port is free, so a later start is not locked out by the leaked sockets+ assert _free_port_is_bindable(live_server.port)++[email protected]_network+def test_a_stop_on_the_serving_loop_never_blocks_on_a_start_holding_the_lock(live_server):+ """A start holds _lock while waiting for this loop to run serve(). /api/shutdown+ reaches stop_lan_listener from that same loop, so blocking on the lock would+ leave the two waiting each other out for the whole start timeout."""+ _require_lan_address()+ holding = threading.Event()+ release = threading.Event()++ def _hold():+ with lan_access._lock:+ holding.set()+ release.wait(10)++ holder = threading.Thread(target = _hold, daemon = True)+ holder.start()+ assert holding.wait(5)+ try:++ async def _stop_from_loop():+ started = time.monotonic()+ return lan_access.stop_lan_listener(), time.monotonic() - started++ stopped, elapsed = asyncio.run_coroutine_threadsafe(+ _stop_from_loop(), live_server.loop+ ).result(timeout = 10)+ assert elapsed < 1, "the loop-side stop waited on the lock"+ assert stopped is False, "an unconfirmed stop must not report success"+ finally:+ release.set()+ holder.join(timeout = 10)+++def test_the_server_thread_releases_the_listener_once_its_loop_ends():+ """An embedded host calls run_server again in-process, and a stale _server would+ report the old addresses as online and skip binding a new listener."""+ source = (_BACKEND / "run.py").read_text(encoding = "utf-8")+ run_body = source[+ source.index(" def _run():") : source.index(" thread = Thread(target = _run")+ ]+ assert "loop.close()" in run_body+ assert "_close_lan_listener()" in run_body+++def test_stop_releases_the_sockets_itself_when_the_serving_loop_is_gone(monkeypatch):+ """An abnormal exit leaves nobody to run uvicorn's shutdown, so stop must close them."""++ class _Server:+ should_exit = False++ stranded = socket.socket()+ stranded.bind(("127.0.0.1", 0))+ dead = asyncio.new_event_loop()+ dead.close()+ monkeypatch.setattr(lan_access, "_server", _Server())+ monkeypatch.setattr(lan_access, "_serve_loop", dead)+ monkeypatch.setattr(lan_access, "_sockets", (stranded,))+ monkeypatch.setattr(lan_access, "_bound_addresses", ("10.0.0.7",))++ started = time.monotonic()+ lan_access.stop_lan_listener()+ assert time.monotonic() - started < 1+ assert stranded.fileno() == -1, "the socket outlived the loop that owned it"+ assert lan_access.lan_listener_status()["running"] is False+++# ── settings orchestration ──+++def _configured(live_server):+ """The live app carrying the launch policy run.py would have published on it."""+ lan_settings.configure_lan_access(+ live_server.app.state,+ port = live_server.port,+ bind_host = "127.0.0.1",+ secure = False,+ is_colab = False,+ frontend_served = True,+ )+ live_server.app.state.lan_access_ready = True+ live_server.app.state.lan_access_loop = live_server.loop+ return live_server.app++[email protected]_network+def test_start_and_stop_track_the_beyond_loopback_trust_flag(live_server):+ app = _configured(live_server)+ assert host_policy.remote_connector_active() is False++ status = lan_settings.start_lan_access(app)+ assert status["state"] == "online" and status["managed_by"] == "settings"+ assert status["urls"] and status["urls"][0].endswith(f":{live_server.port}")+ assert status["can_stop"] is True and status["can_start"] is False+ assert host_policy.remote_connector_active() is True++ # a repeated start is answered with the running listener, not a second bind+ assert lan_settings.start_lan_access(app)["urls"] == status["urls"]++ stopped = lan_settings.stop_lan_access(app)+ assert stopped["state"] == "off" and stopped["managed_by"] is None+ assert stopped["can_start"] is True+ assert _wait_for_trust(False)++[email protected]_network+def test_auto_start_brings_the_listener_up_at_boot(live_server, stored_settings):+ stored_settings[lan_settings.LAN_ACCESS_AUTO_START_KEY] = True+ app = _configured(live_server)+ assert lan_settings.maybe_auto_start_lan_access(app) is True+ assert lan_settings.lan_access_status(app)["state"] == "online"+ # stopping now must not silently clear the preference+ lan_settings.stop_lan_access(app)+ assert lan_settings.get_lan_access_auto_start() is True+++def test_trust_outlives_the_sockets_until_accepted_requests_drain(monkeypatch):+ """Stop closes the listening sockets, but uvicorn then drains the connections it+ already accepted, and a request that arrived on the LAN stays a remote caller."""+ connections = {object()}+ server = SimpleNamespace(server_state = SimpleNamespace(connections = connections))+ monkeypatch.setattr(lan_access, "_DRAIN_TIMEOUT", 5.0)++ with lan_access._lock:+ lan_access._arm_drain_watcher(server)+ lan_access._sync_lan_trust()+ time.sleep(0.2)+ assert host_policy.remote_connector_active() is True, "cleared while a request ran"++ connections.clear()+ assert _wait_for_trust(False)+++def test_a_repeated_stop_does_not_clear_trust_a_pending_drain_still_owns(monkeypatch):+ """The second stop finds no server and would otherwise release the flag out from+ under requests the first stop left draining."""+ connections = {object()}+ server = SimpleNamespace(server_state = SimpleNamespace(connections = connections))+ monkeypatch.setattr(lan_access, "_DRAIN_TIMEOUT", 5.0)++ with lan_access._lock:+ lan_access._arm_drain_watcher(server)+ lan_access._sync_lan_trust()+ assert host_policy.remote_connector_active() is True++ # the idempotent stop path: no server, but a drain still owns the flag+ assert lan_access.stop_lan_listener() is True+ assert host_policy.remote_connector_active() is True++ connections.clear()+ assert _wait_for_trust(False)+++def test_a_drain_that_finishes_after_a_restart_leaves_the_new_listener_trusted(monkeypatch):+ server = SimpleNamespace(server_state = SimpleNamespace(connections = set()))+ monkeypatch.setattr(lan_access, "_server", SimpleNamespace(should_exit = False))+ host_policy.set_lan_connector_active(True)+ lan_access._clear_trust_after_drain(server)+ assert host_policy.remote_connector_active() is True+ host_policy.set_lan_connector_active(False)+++def test_the_trust_flag_moves_with_the_listener_under_one_lock():+ """A start and a stop can run in separate FastAPI worker threads, so the flag+ cannot be published by the callers: it has to change where the state does."""+ settings_source = (_BACKEND / "utils" / "lan_access_settings.py").read_text(encoding = "utf-8")+ assert "set_lan_connector_active" not in settings_source++ listener_source = (_BACKEND / "lan_access.py").read_text(encoding = "utf-8")+ tree = ast.parse(listener_source)+ holders = set()+ for node in ast.walk(tree):+ if not isinstance(node, ast.FunctionDef):+ continue+ body = ast.unparse(node)+ if "set_lan_connector_active" in body:+ holders.add(node.name)+ # only the two helpers that run under _lock may touch it+ assert holders == {"start_lan_listener", "_sync_lan_trust"}, holders+++def test_start_refuses_while_a_block_is_in_force():+ with pytest.raises(RuntimeError, match = "server_starting"):+ lan_settings.start_lan_access(_app(lan_access_ready = False))+ with pytest.raises(RuntimeError, match = "launch_managed"):+ lan_settings.stop_lan_access(_app(lan_access_launch_managed = True))+++def test_start_refuses_a_port_the_server_never_published():+ with pytest.raises(RuntimeError, match = "server_port_unavailable"):+ lan_settings.start_lan_access(_app(lan_access_port = None))+++def test_start_refuses_once_the_server_loop_is_gone(monkeypatch):+ monkeypatch.setattr(+ lan_access, "start_lan_listener", lambda *_: pytest.fail("bound without a live loop")+ )+ with pytest.raises(RuntimeError, match = "server_not_running"):+ lan_settings.start_lan_access(_app(lan_access_loop = None))+ # a loop that exists but is no longer serving would never run the listener either+ idle = asyncio.new_event_loop()+ try:+ with pytest.raises(RuntimeError, match = "server_not_running"):+ lan_settings.start_lan_access(_app(lan_access_loop = idle))+ finally:+ idle.close()+ with pytest.raises(RuntimeError, match = "server_not_running"):+ lan_settings.start_lan_access(_app(lan_access_loop = idle))+++def test_auto_start_stays_quiet_when_the_launch_forbids_it(stored_settings):+ stored_settings[lan_settings.LAN_ACCESS_AUTO_START_KEY] = True+ assert lan_settings.maybe_auto_start_lan_access(_app(lan_access_is_colab = True)) is False+++def test_auto_start_is_skipped_entirely_when_the_preference_is_off(monkeypatch):+ monkeypatch.setattr(+ lan_settings, "start_lan_access", lambda _app: pytest.fail("started despite the preference")+ )+ assert lan_settings.maybe_auto_start_lan_access(_app()) is False+++# ── routes and wiring ──+++def test_colab_auto_start_setting_is_read_only(monkeypatch):+ monkeypatch.setattr(routes, "set_lan_access_auto_start", lambda *_: pytest.fail("persisted"))+ request = SimpleNamespace(app = _app(lan_access_is_colab = True))+ payload = routes.LanAccessAutoStartPayload(enabled = True)+ with pytest.raises(HTTPException) as exc:+ routes.update_lan_access_auto_start(request, payload, "admin", None)+ assert exc.value.status_code == 409+++def test_a_blocked_start_answers_409_rather_than_500(monkeypatch):+ monkeypatch.setattr(+ routes, "start_lan_access", lambda _app: (_ for _ in ()).throw(RuntimeError("colab"))+ )+ with pytest.raises(HTTPException) as exc:+ routes.start_lan_access_route(SimpleNamespace(app = _app()), "admin", None)+ assert exc.value.status_code == 409 and exc.value.detail == "colab"+++def test_management_rejects_api_keys():+ with pytest.raises(HTTPException) as exc:+ routes._require_ui_session(True)+ assert exc.value.status_code == 403+ # every /lan-access handler must carry the UI-session gate+ tree = ast.parse(Path(routes.__file__).read_text(encoding = "utf-8"))+ gated = {}+ for node in ast.walk(tree):+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ continue+ routed = [ast.unparse(d) for d in node.decorator_list if "router." in ast.unparse(d)]+ if not any("'/lan-access" in d for d in routed):+ continue+ args = node.args.args + node.args.kwonlyargs+ gated[node.name] = any(a.arg == "_ui_session" for a in args)+ assert len(gated) == 4, f"expected 4 lan-access handlers, found {sorted(gated)}"+ assert all(+ gated.values()+ ), f"ungated lan-access handlers: {sorted(k for k, v in gated.items() if not v)}"+++def test_the_desktop_frontend_gate_admits_the_lan_listener():+ """A desktop backend mounts its SPA behind a remote-only gate; LAN must open it."""+ import main++ scope = {"type": "http", "headers": [], "server": ("10.0.0.7", 8888)}+ state = SimpleNamespace(cloudflare_url = None)+ assert main._is_remote_frontend_request(scope, state) is False+ original = lan_access._bound_addresses+ lan_access._bound_addresses = ("10.0.0.7",)+ try:+ assert main._is_remote_frontend_request(scope, state) is True+ loopback = {"type": "http", "headers": [], "server": ("127.0.0.1", 8888)}+ assert main._is_remote_frontend_request(loopback, state) is False+ finally:+ lan_access._bound_addresses = original+++def test_the_desktop_assets_mount_admits_the_lan_listener():+ """The SPA is mounted twice on a desktop api-only launch: /assets through+ _TunnelOnlyFrontend, and the routes through _frontend_request_allowed."""+ import main++ served = []++ async def _spa(_scope, _receive, send):+ served.append(True)+ await send({"type": "http.response.start", "status": 200, "headers": []})+ await send({"type": "http.response.body", "body": b""})++ async def _drive(scope):+ statuses = []++ async def _send(message):+ if message["type"] == "http.response.start":+ statuses.append(message["status"])++ await main._TunnelOnlyFrontend(_spa, SimpleNamespace(cloudflare_url = None))(+ scope, None, _send+ )+ return statuses[0]++ lan = {"type": "http", "headers": [], "server": ("10.0.0.7", 8888)}+ loopback = {"type": "http", "headers": [], "server": ("127.0.0.1", 8888)}+ assert asyncio.run(_drive(lan)) == 404++ original = lan_access._bound_addresses+ lan_access._bound_addresses = ("10.0.0.7",)+ try:+ assert asyncio.run(_drive(lan)) == 200+ assert asyncio.run(_drive(loopback)) == 404, "loopback keeps the api-only surface"+ finally:+ lan_access._bound_addresses = original+ assert served++ # the SPA routes share the decision through a closure the mount does not expose+ source = (_BACKEND / "main.py").read_text(encoding = "utf-8")+ assert "return not tunnel_only or _is_remote_frontend_request(request.scope, app.state)" in (+ source+ )+++def test_run_py_wires_the_listener_into_the_server_lifecycle():+ source = (_BACKEND / "run.py").read_text(encoding = "utf-8")+ # without the loop the settings route has nothing to schedule the listener on+ assert "app.state.lan_access_loop = loop" in source+ assert "close_lan_listener_lifecycle" in source+ # readiness is what unblocks the whole feature, and it has to land before auto-start+ ready = source.index("app.state.lan_access_ready = True")+ assert ready < source.index("maybe_auto_start_lan_access(app)")diff --git a/studio/backend/utils/host_policy.py b/studio/backend/utils/host_policy.pyindex 5ee41691f72..0c6d40adce2 100644--- a/studio/backend/utils/host_policy.py+++ b/studio/backend/utils/host_policy.py@@ -28,6 +28,7 @@ _LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"})# public bind, so we only ever take back a value we set ourselves._auto_enabled = False_remote_connector_active = False+_lan_connector_active = Falsedef is_external_host(host: str) -> bool:@@ -99,12 +100,20 @@ def set_remote_connector_active(active: bool) -> None:_remote_connector_active = bool(active)+def set_lan_connector_active(active: bool) -> None:+ """Publish whether a runtime LAN listener is serving beyond loopback."""+ global _lan_connector_active+ _lan_connector_active = bool(active)++def remote_connector_active() -> bool:- return _remote_connector_active+ """True while any connector can carry a request from beyond loopback."""+ return _remote_connector_active or _lan_connector_activedef _reset_loopback_default_state() -> None:"""Test hook: forget runtime trust state applied earlier in this process."""- global _auto_enabled, _remote_connector_active+ global _auto_enabled, _remote_connector_active, _lan_connector_active_auto_enabled = False_remote_connector_active = False+ _lan_connector_active = Falsediff --git a/studio/backend/utils/lan_access_settings.py b/studio/backend/utils/lan_access_settings.pynew file mode 100644index 00000000000..e19b75ef198--- /dev/null+++ b/studio/backend/utils/lan_access_settings.py@@ -0,0 +1,211 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Persisted policy and launch policy for Settings > LAN access.++The listener itself lives in ``lan_access``; this decides whether the current+launch may own one, whether the user is allowed to turn it on, and remembers the+answer across restarts.+"""++from __future__ import annotations++from typing import Any, Optional++from loggers import get_logger++logger = get_logger(__name__)++LAN_ACCESS_AUTO_START_KEY = "lan_access_auto_start"+DEFAULT_LAN_ACCESS_AUTO_START = False+++def _coerce_bool(value: Any) -> Optional[bool]:+ return value if isinstance(value, bool) else None+++def get_lan_access_auto_start() -> bool:+ """Read the preference, failing closed on missing, invalid, or unreadable data."""+ try:+ from storage.studio_db import get_app_setting+ stored = get_app_setting(LAN_ACCESS_AUTO_START_KEY, None)+ except Exception:+ return False+ parsed = _coerce_bool(stored)+ return parsed if parsed is not None else DEFAULT_LAN_ACCESS_AUTO_START+++def set_lan_access_auto_start(enabled: bool) -> bool:+ if not isinstance(enabled, bool):+ raise ValueError("LAN access auto-start must be true or false.")+ from storage.studio_db import upsert_app_settings++ upsert_app_settings({LAN_ACCESS_AUTO_START_KEY: enabled})+ return enabled+++def _admin_password_ready() -> bool:+ try:+ from auth.storage import DEFAULT_ADMIN_USERNAME, requires_password_change+ return not requires_password_change(DEFAULT_ADMIN_USERNAME)+ except Exception:+ return False+++def configure_lan_access(+ app_state, *, port: int, bind_host: str, secure: bool, is_colab: bool, frontend_served: bool+) -> None:+ """Publish immutable launch policy used by every settings request."""+ from utils.host_policy import is_external_host++ app_state.lan_access_port = port+ app_state.lan_access_wildcard_bind = bind_host in ("0.0.0.0", "::")+ app_state.lan_access_launch_managed = app_state.lan_access_wildcard_bind or is_external_host(+ bind_host+ )+ # --secure forces the loopback bind precisely so the raw port is never exposed+ app_state.lan_access_secure_launch = bool(secure)+ app_state.lan_access_is_colab = bool(is_colab)+ app_state.lan_access_frontend_served = bool(frontend_served)+ app_state.lan_access_ready = False+++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.+ """+ if getattr(app_state, "lan_access_wildcard_bind", False):+ cached = getattr(app_state, "lan_access_wildcard_urls", None)+ if cached is None:+ from lan_access import detect_lan_addresses+ cached = _listener_urls(+ detect_lan_addresses(), getattr(app_state, "lan_access_port", None)+ )+ app_state.lan_access_wildcard_urls = cached+ return list(cached)+ url = getattr(app_state, "server_url", None)+ return [url] if url else []+++def _listener_urls(addresses, port: Optional[int]) -> list[str]:+ if not port:+ return []+ return [f"http://{address}:{port}" for address in addresses]+++def _public_urls(urls: list[str]) -> list[str]:+ """The subset reachable from the internet rather than only this network."""+ from urllib.parse import urlparse++ from lan_access import is_public_address++ return [url for url in urls if is_public_address(urlparse(url).hostname or "")]+++def lan_access_status(app) -> dict:+ """Everything Settings > LAN access renders, resolved for the current launch."""+ from lan_access import lan_listener_status++ app_state = app.state+ listener = lan_listener_status()+ ready = bool(getattr(app_state, "lan_access_ready", False))+ is_colab = bool(getattr(app_state, "lan_access_is_colab", False))+ launch_managed = bool(getattr(app_state, "lan_access_launch_managed", False))+ frontend_served = bool(getattr(app_state, "lan_access_frontend_served", False))++ block_reason = None+ if not ready:+ block_reason = "server_starting"+ elif is_colab:+ block_reason = "colab"+ elif launch_managed:+ block_reason = "launch_managed"+ elif bool(getattr(app_state, "lan_access_secure_launch", False)):+ block_reason = "secure_launch"+ elif not _admin_password_ready():+ block_reason = "admin_password_change_required"++ running = bool(listener["running"])+ if launch_managed:+ state, urls, managed_by = "online", _launch_urls(app_state), "launch"+ elif running:+ state, urls, managed_by = (+ "online",+ _listener_urls(listener["addresses"], listener["port"]),+ "settings",+ )+ else:+ state = "error" if listener["error"] else "off"+ urls, managed_by = [], None++ controllable = block_reason is None+ return {+ "state": state,+ "urls": urls,+ "public_urls": _public_urls(urls),+ "error": listener["error"],+ "auto_start": get_lan_access_auto_start(),+ "managed_by": managed_by,+ "can_start": controllable and not running,+ "can_stop": controllable and running,+ "block_reason": block_reason,+ "serves_web_ui": frontend_served,+ }+++def _server_loop(app_state):+ """The loop the primary server serves on, or a refusal if it is not serving."""+ loop = getattr(app_state, "lan_access_loop", None)+ if loop is None or loop.is_closed() or not loop.is_running():+ raise RuntimeError("server_not_running")+ return loop+++def start_lan_access(app) -> dict:+ """Bring the LAN listener up for this launch. Repeated requests are idempotent."""+ from lan_access import start_lan_listener++ status = lan_access_status(app)+ if status["state"] == "online":+ return status+ if not status["can_start"]:+ raise RuntimeError(status["block_reason"] or "operation_in_progress")++ port = getattr(app.state, "lan_access_port", None)+ if not isinstance(port, int) or port <= 0:+ raise RuntimeError("server_port_unavailable")++ addresses = start_lan_listener(app, _server_loop(app.state), port)+ logger.info("LAN access started on %s", ", ".join(addresses))+ return lan_access_status(app)+++def stop_lan_access(app) -> dict:+ """Take the LAN listener down without changing the auto-start preference."""+ from lan_access import clear_lan_listener_error, stop_lan_listener++ status = lan_access_status(app)+ if status["managed_by"] == "launch":+ raise RuntimeError("launch_managed")+ # a stop that could not confirm the port is closed leaves the host reachable+ # a stop that could not confirm the port is closed leaves the host reachable,+ # and lan_access keeps the trust flag with the listener state it describes+ if stop_lan_listener():+ clear_lan_listener_error()+ return lan_access_status(app)+++def maybe_auto_start_lan_access(app) -> bool:+ """Start the listener at boot when the persisted preference allows it."""+ if not get_lan_access_auto_start():+ return False+ try:+ start_lan_access(app)+ except Exception as exc:+ # an optional preference must never take the whole server down with it+ logger.info("LAN access auto-start skipped: %s", exc)+ return False+ return Truediff --git a/studio/frontend/src/features/settings/api/lan-access-state.ts b/studio/frontend/src/features/settings/api/lan-access-state.tsnew file mode 100644index 00000000000..800bb57c5ed--- /dev/null+++ b/studio/frontend/src/features/settings/api/lan-access-state.ts@@ -0,0 +1,124 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export type LanAccessState = "off" | "online" | "error";+export type LanAccessOwner = "launch" | "settings" | null;++export type LanAccessStatus = {+ state: LanAccessState;+ urls: string[];+ publicUrls: string[];+ error: string | null;+ autoStart: boolean;+ managedBy: LanAccessOwner;+ canStart: boolean;+ canStop: boolean;+ blockReason: string | null;+ servesWebUi: boolean;+};++export type ApiLanAccessStatus = {+ state: LanAccessState;+ urls?: string[] | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ public_urls?: string[] | null;+ error?: string | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_start: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ managed_by?: LanAccessOwner;+ // biome-ignore lint/style/useNamingConvention: API schema+ can_start: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ can_stop: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ block_reason?: string | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ serves_web_ui?: boolean;+};++export function normalizeLanAccessStatus(+ status: ApiLanAccessStatus,+): LanAccessStatus {+ return {+ state: status.state,+ urls: Array.isArray(status.urls) ? status.urls : [],+ publicUrls: Array.isArray(status.public_urls) ? status.public_urls : [],+ error: status.error ?? null,+ autoStart: status.auto_start,+ managedBy: status.managed_by ?? null,+ canStart: status.can_start,+ canStop: status.can_stop,+ blockReason: status.block_reason ?? null,+ // absent on a backend that predates the field, where the web UI is served+ servesWebUi: status.serves_web_ui !== false,+ };+}++// start and stop are synchronous socket work, so there is no transition to chase+export const LAN_ACCESS_POLL_MS = 5000;++export function lanAccessAutoStartReadOnly(+ status: LanAccessStatus | null,+): boolean {+ return status === null || status.blockReason === "colab";+}++export function lanAccessStopDisconnectsOrigin(+ urls: string[],+ browserOrigin: string,+): boolean {+ let origin: string;+ try {+ origin = new URL(browserOrigin).origin;+ } catch {+ return false;+ }+ return urls.some((url) => {+ try {+ return new URL(url).origin === origin;+ } catch {+ return false;+ }+ });+}++export function lanAccessBlockMessage(+ reason: string | null,+ isDesktop: boolean,+): string | null {+ switch (reason) {+ case "server_starting":+ return "Unsloth is still starting.";+ case "admin_password_change_required":+ return isDesktop+ ? "Set a remote password before putting this server on the network."+ : "Change the administrator password before putting this server on the network. In the desktop app, run unsloth studio reset-password.";+ case "launch_managed":+ return "This launch already binds every network interface (-H 0.0.0.0), so Unsloth is on the network already.";+ case "secure_launch":+ return "This launch used --secure, which serves only through the Cloudflare link and keeps the raw port closed. Relaunch without --secure to use LAN access.";+ case "colab":+ return "LAN access is managed by the Colab runtime, which has no local network to join.";+ default:+ return null;+ }+}++export function lanAccessErrorMessage(error: string | null): string | null {+ switch (error) {+ case "no_lan_address":+ return "No network address found. Connect this machine to Wi-Fi or a wired network, then try again.";+ case "bind_failed":+ return "Could not open Unsloth's port on this machine's network addresses.";+ case "listener_start_failed":+ return "The network listener did not start. Check the logs for details.";+ case "stop_timed_out":+ return "LAN access could not confirm the port closed. Check the logs, then try again.";+ case null:+ case undefined:+ return null;+ default:+ return "LAN access failed to start.";+ }+}diff --git a/studio/frontend/src/features/settings/api/lan-access.ts b/studio/frontend/src/features/settings/api/lan-access.tsnew file mode 100644index 00000000000..893529ccd24--- /dev/null+++ b/studio/frontend/src/features/settings/api/lan-access.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";+import {+ type LanAccessStatus,+ normalizeLanAccessStatus,+} from "./lan-access-state";++export type { LanAccessStatus } from "./lan-access-state";++async function requestLanAccess(+ path = "",+ init?: RequestInit,+): Promise<LanAccessStatus> {+ const response = await authFetch(`/api/settings/lan-access${path}`, init);+ if (!response.ok) {+ throw new Error(+ await readFastApiError(response, "LAN access request failed"),+ );+ }+ return normalizeLanAccessStatus(await response.json());+}++export const loadLanAccess = () => requestLanAccess();+export const startLanAccess = () =>+ requestLanAccess("/start", { method: "POST" });+export const stopLanAccess = () =>+ requestLanAccess("/stop", { method: "POST" });+export const updateLanAccessAutoStart = (enabled: boolean) =>+ requestLanAccess("/auto-start", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ enabled }),+ });diff --git a/studio/frontend/src/features/settings/components/lan-access-section.tsx b/studio/frontend/src/features/settings/components/lan-access-section.tsxnew file mode 100644index 00000000000..db0af7769e1--- /dev/null+++ b/studio/frontend/src/features/settings/components/lan-access-section.tsx@@ -0,0 +1,376 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { Switch } from "@/components/ui/switch";+import {+ loadLanAccess,+ startLanAccess,+ stopLanAccess,+ updateLanAccessAutoStart,+} from "@/features/settings/api/lan-access";+import {+ LAN_ACCESS_POLL_MS,+ type LanAccessStatus,+ lanAccessAutoStartReadOnly,+ lanAccessBlockMessage,+ lanAccessErrorMessage,+ lanAccessStopDisconnectsOrigin,+} from "@/features/settings/api/lan-access-state";+import { isTauri } from "@/lib/api-base";+import { copyToClipboard } from "@/lib/copy-to-clipboard";+import { Tick02Icon } from "@/lib/tick-icon";+import { cn } from "@/lib/utils";+import { Copy01Icon, QrCodeIcon, Wifi01Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { useCallback, useEffect, useRef, useState } from "react";+import QRCode from "react-qr-code";+import { SettingsRow } from "./settings-row";++type LanAccessOperation = "start" | "stop" | "auto";++const STATE_LABEL: Record<LanAccessStatus["state"], string> = {+ off: "Off",+ online: "Online",+ error: "Error",+};++const OWNER_LABEL: Record<+ Exclude<LanAccessStatus["managedBy"], null>,+ string+> = {+ launch: "Launch managed",+ settings: "Settings managed",+};++function stateDotClass(state?: LanAccessStatus["state"]): string {+ if (state === "online") {+ return "bg-emerald-500";+ }+ return state === "error" ? "bg-red-500" : "bg-muted-foreground";+}++function AccessStatus({ status }: { status: LanAccessStatus | null }) {+ const owner = status?.managedBy ? OWNER_LABEL[status.managedBy] : null;+ return (+ <output+ className="flex items-center gap-1.5 text-xs text-muted-foreground"+ aria-live="polite"+ >+ <span+ className={cn("size-2 rounded-full", stateDotClass(status?.state))}+ />+ {status ? STATE_LABEL[status.state] : "Unavailable"}+ {owner ? ` · ${owner}` : ""}+ </output>+ );+}++function CopyLanUrlButton({ url }: { url: string }) {+ const [copied, setCopied] = useState(false);+ const copyTimer = useRef<number | null>(null);+ useEffect(() => {+ return () => {+ if (copyTimer.current !== null) {+ window.clearTimeout(copyTimer.current);+ }+ };+ }, []);+ return (+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="gap-1.5"+ aria-label={`Copy ${url}`}+ onClick={async () => {+ if (!(await copyToClipboard(url))) {+ return;+ }+ setCopied(true);+ if (copyTimer.current !== null) {+ window.clearTimeout(copyTimer.current);+ }+ copyTimer.current = window.setTimeout(() => setCopied(false), 1800);+ }}+ >+ <HugeiconsIcon+ icon={copied ? Tick02Icon : Copy01Icon}+ className="size-3.5"+ />+ {copied ? "Copied" : "Copy"}+ </Button>+ );+}++function LanUrlQrButton({ url }: { url: string }) {+ return (+ <Dialog>+ <DialogTrigger asChild={true}>+ <Button type="button" size="sm" variant="outline" className="gap-1.5">+ <HugeiconsIcon icon={QrCodeIcon} className="size-3.5" />+ QR+ </Button>+ </DialogTrigger>+ <DialogContent className="sm:max-w-xs">+ <DialogHeader>+ <DialogTitle>Open on your phone</DialogTitle>+ <DialogDescription>+ Scan from a device on the same network to open this address.+ </DialogDescription>+ </DialogHeader>+ <div className="mx-auto mt-2 rounded-md bg-white p-3">+ <QRCode value={url} size={192} />+ </div>+ <code className="block break-all text-center font-mono text-xs text-muted-foreground">+ {url}+ </code>+ </DialogContent>+ </Dialog>+ );+}++function StatusMessage({+ message,+ destructive,+}: {+ message?: string | null;+ destructive?: boolean;+}) {+ if (!message) {+ return null;+ }+ return (+ <p+ className={cn(+ "border-t border-border/60 px-4 py-2.5 text-xs leading-snug",+ destructive ? "text-destructive" : "text-muted-foreground",+ )}+ >+ {message}+ </p>+ );+}++function LanUrlPanel({ status }: { status: LanAccessStatus | null }) {+ if (!status || status.urls.length === 0) {+ return null;+ }+ const [primary] = status.urls;+ return (+ <div className="flex flex-col gap-1.5 border-t border-border/60 p-4">+ <div className="flex items-center justify-between gap-3">+ <span className="text-sm font-medium text-foreground">+ {status.urls.length > 1 ? "Network addresses" : "Network address"}+ </span>+ <LanUrlQrButton url={primary} />+ </div>+ {status.urls.map((url) => (+ <div key={url} className="flex items-center gap-2">+ <code className="block w-full min-w-0 break-all rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground">+ {url}+ </code>+ <CopyLanUrlButton url={url} />+ </div>+ ))}+ {status.publicUrls.length > 0 ? (+ <span className="text-xs text-destructive leading-snug">+ {status.publicUrls[0]} is a public internet address, so this reaches+ beyond your local network. Anyone who has the password or an API key+ can sign in and run code on this machine.+ </span>+ ) : (+ <span className="text-xs text-muted-foreground leading-snug">+ {status.servesWebUi+ ? "Anyone on this network who has the password or an API key can sign in and run code on this machine."+ : "This launch serves the API only, so devices on the network can call the API but not open the web UI."}+ </span>+ )}+ </div>+ );+}++export function LanAccessSection() {+ const [status, setStatus] = useState<LanAccessStatus | null>(null);+ const [busy, setBusy] = useState<LanAccessOperation | null>(null);+ const [pollRevision, setPollRevision] = useState(0);+ const [pollEnabled, setPollEnabled] = useState(true);+ const mutationEpoch = useRef(0);+ const pollSuppressed = useRef(false);+ const selfStopDisconnectExpected = useRef(false);++ const applyStatus = useCallback((next: LanAccessStatus) => {+ setStatus(next);+ }, []);++ // biome-ignore lint/correctness/useExhaustiveDependencies: pollRevision intentionally restarts polling after a mutation+ useEffect(() => {+ if (!pollEnabled) {+ return;+ }+ let stopped = false;+ let timer: number | null = null;+ const schedule = () => {+ if (!stopped && !pollSuppressed.current) {+ timer = window.setTimeout(poll, LAN_ACCESS_POLL_MS);+ }+ };+ const poll = () => {+ if (pollSuppressed.current) {+ return;+ }+ const epoch = mutationEpoch.current;+ loadLanAccess()+ .then((next) => {+ if (+ !stopped &&+ !pollSuppressed.current &&+ mutationEpoch.current === epoch+ ) {+ selfStopDisconnectExpected.current = false;+ applyStatus(next);+ }+ schedule();+ })+ .catch(() => {+ if (mutationEpoch.current !== epoch) {+ return;+ }+ // a stop from a LAN address kills this page's own origin, so stop polling+ if (selfStopDisconnectExpected.current) {+ setPollEnabled(false);+ return;+ }+ schedule();+ });+ };+ poll();+ return () => {+ stopped = true;+ if (timer !== null) {+ window.clearTimeout(timer);+ }+ };+ }, [applyStatus, pollEnabled, pollRevision]);++ const perform = async (+ operation: LanAccessOperation,+ request: () => Promise<LanAccessStatus>,+ pausePollingAfterSuccess = false,+ ) => {+ mutationEpoch.current += 1;+ pollSuppressed.current = true;+ setBusy(operation);+ try {+ applyStatus(await request());+ if (pausePollingAfterSuccess) {+ selfStopDisconnectExpected.current = true;+ }+ } catch {+ // polling resumes below and reconciles the visible state+ } finally {+ setBusy(null);+ pollSuppressed.current = false;+ setPollEnabled(true);+ setPollRevision((revision) => revision + 1);+ }+ };++ const start = () => perform("start", startLanAccess);+ const stop = () =>+ perform(+ "stop",+ stopLanAccess,+ lanAccessStopDisconnectsOrigin(+ status?.urls ?? [],+ typeof window === "undefined" ? "" : window.location.origin,+ ),+ );+ const setAutoStart = (enabled: boolean) =>+ perform("auto", () => updateLanAccessAutoStart(enabled));++ const blockMessage = lanAccessBlockMessage(+ status?.blockReason ?? null,+ isTauri,+ );+ const errorMessage = lanAccessErrorMessage(status?.error ?? null);+ const stopAction = status?.state === "online";+ const actionDisabled =+ busy !== null || (stopAction ? !status?.canStop : !status?.canStart);+ const actionLabel =+ busy === "start"+ ? "Starting…"+ : busy === "stop"+ ? "Stopping…"+ : stopAction+ ? "Stop"+ : "Start";++ return (+ <section+ data-settings-label="LAN access"+ className="overflow-hidden rounded-lg border border-border/70"+ >+ <div className="flex items-center justify-between gap-4 bg-muted/30 p-4">+ <div className="flex min-w-0 items-start gap-3">+ <div className="flex size-8 shrink-0 items-center justify-center rounded-md border border-border/70 bg-muted/40">+ <HugeiconsIcon+ icon={Wifi01Icon}+ className="size-4 text-foreground"+ />+ </div>+ <div className="flex min-w-0 flex-col gap-0.5">+ <div className="flex flex-wrap items-center gap-2">+ <h2 className="text-base font-semibold font-heading text-foreground">+ LAN access+ </h2>+ <AccessStatus status={status} />+ </div>+ <p className="text-xs text-muted-foreground leading-relaxed">+ Use Unsloth and its APIs from other devices on your Wi-Fi or wired+ network.+ </p>+ </div>+ </div>+ <Button+ type="button"+ size="sm"+ variant={stopAction ? "outline" : "default"}+ className="min-w-20 shrink-0"+ onClick={stopAction ? stop : start}+ disabled={actionDisabled}+ >+ {actionLabel}+ </Button>+ </div>++ <StatusMessage+ message={blockMessage ?? errorMessage}+ destructive={!blockMessage}+ />+ <LanUrlPanel status={status} />++ <div className="border-t border-border/60 px-4 py-1">+ <SettingsRow+ label="Start automatically"+ description="Put Unsloth on the network each time it starts. Stopping LAN access now won’t turn this off."+ >+ <Switch+ checked={status?.autoStart ?? false}+ disabled={busy !== null || lanAccessAutoStartReadOnly(status)}+ onCheckedChange={setAutoStart}+ aria-label="Start automatically"+ />+ </SettingsRow>+ </div>+ </section>+ );+}diff --git a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsxindex ea45e41741f..7588f1c1aed 100644--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx@@ -19,6 +19,7 @@ import { ApiKeyRow } from "../components/api-key-row";import { CreateKeyForm } from "../components/create-key-form";import { ModelAutoSwitchSection } from "../components/model-auto-switch-section";import { KeyRevealCard } from "../components/key-reveal-card";+import { LanAccessSection } from "../components/lan-access-section";import { RemoteAccessSection } from "../components/remote-access-section";import { UsageExamples } from "../components/usage-examples";@@ -175,6 +176,8 @@ export function ApiKeysTab() {<RemoteAccessSection />+ <LanAccessSection />+<ModelAutoSwitchSection /><UsageExamples apiKey={revealed} />diff --git a/studio/frontend/tests/lan-access-state.test.ts b/studio/frontend/tests/lan-access-state.test.tsnew file mode 100644index 00000000000..725bbfda29f--- /dev/null+++ b/studio/frontend/tests/lan-access-state.test.ts@@ -0,0 +1,241 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++// lan-access-section.tsx pulls in hugeicons, so only its pure helpers are tested here+import {+ type ApiLanAccessStatus,+ lanAccessAutoStartReadOnly,+ lanAccessBlockMessage,+ lanAccessErrorMessage,+ lanAccessStopDisconnectsOrigin,+ normalizeLanAccessStatus,+} from "../src/features/settings/api/lan-access-state.ts";++const LAN = "http://192.168.1.24:8888";+const SECOND = "http://10.0.0.7:8888";+const PUBLIC = "http://64.227.100.5:8888";++function apiStatus(over: Partial<ApiLanAccessStatus> = {}): ApiLanAccessStatus {+ return {+ state: "off",+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_start: false,+ // biome-ignore lint/style/useNamingConvention: API schema+ can_start: true,+ // biome-ignore lint/style/useNamingConvention: API schema+ can_stop: false,+ ...over,+ };+}++// ── normalizeLanAccessStatus ──++test("normalize maps every snake_case field onto its camelCase name", () => {+ const s = normalizeLanAccessStatus(+ apiStatus({+ state: "online",+ urls: [LAN, SECOND],+ error: null,+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_start: true,+ // biome-ignore lint/style/useNamingConvention: API schema+ managed_by: "settings",+ // biome-ignore lint/style/useNamingConvention: API schema+ can_start: false,+ // biome-ignore lint/style/useNamingConvention: API schema+ can_stop: true,+ // biome-ignore lint/style/useNamingConvention: API schema+ block_reason: null,+ // biome-ignore lint/style/useNamingConvention: API schema+ serves_web_ui: true,+ }),+ );+ assert.deepEqual(s, {+ state: "online",+ urls: [LAN, SECOND],+ publicUrls: [],+ error: null,+ autoStart: true,+ managedBy: "settings",+ canStart: false,+ canStop: true,+ blockReason: null,+ servesWebUi: true,+ });+});++test("normalize defaults the optional fields an older backend may omit", () => {+ const s = normalizeLanAccessStatus(apiStatus());+ assert.deepEqual(s.urls, []);+ assert.deepEqual(s.publicUrls, []);+ assert.equal(s.error, null);+ assert.equal(s.managedBy, null);+ assert.equal(s.blockReason, null);+ assert.equal(s.servesWebUi, true);+});++test("urls survives a null or non-array payload without throwing", () => {+ for (const urls of [null, undefined, "nope" as never]) {+ const s = normalizeLanAccessStatus(apiStatus({ urls }));+ assert.deepEqual(s.urls, []);+ assert.deepEqual(s.publicUrls, []);+ }+});++test("a public address is carried through so the section can warn about it", () => {+ const s = normalizeLanAccessStatus(+ // biome-ignore lint/style/useNamingConvention: API schema+ apiStatus({ urls: [PUBLIC, LAN], public_urls: [PUBLIC] }),+ );+ assert.deepEqual(s.publicUrls, [PUBLIC]);+ assert.deepEqual(s.urls, [PUBLIC, LAN]);+});++test("servesWebUi is only false for an explicit false", () => {+ for (const raw of [undefined, null, true]) {+ assert.equal(+ // biome-ignore lint/style/useNamingConvention: API schema+ normalizeLanAccessStatus(apiStatus({ serves_web_ui: raw as never }))+ .servesWebUi,+ true,+ );+ }+ assert.equal(+ // biome-ignore lint/style/useNamingConvention: API schema+ normalizeLanAccessStatus(apiStatus({ serves_web_ui: false })).servesWebUi,+ false,+ );+});++// ── lanAccessAutoStartReadOnly ──++test("auto-start is read-only with no status, or under Colab", () => {+ assert.equal(lanAccessAutoStartReadOnly(null), true);+ assert.equal(+ lanAccessAutoStartReadOnly(+ // biome-ignore lint/style/useNamingConvention: API schema+ normalizeLanAccessStatus(apiStatus({ block_reason: "colab" })),+ ),+ true,+ );+ // a launch-managed bind still lets the preference be set for next time+ assert.equal(+ lanAccessAutoStartReadOnly(+ // biome-ignore lint/style/useNamingConvention: API schema+ normalizeLanAccessStatus(apiStatus({ block_reason: "launch_managed" })),+ ),+ false,+ );+ assert.equal(+ lanAccessAutoStartReadOnly(normalizeLanAccessStatus(apiStatus())),+ false,+ );+});++// ── lanAccessStopDisconnectsOrigin ──+// a false negative here leaves the page polling an origin its own stop just killed++test("stop-disconnects matches any of the bound addresses", () => {+ assert.equal(lanAccessStopDisconnectsOrigin([LAN, SECOND], SECOND), true);+ assert.equal(lanAccessStopDisconnectsOrigin([LAN], LAN), true);+});++test("stop-disconnects normalizes trailing slashes on both sides", () => {+ assert.equal(lanAccessStopDisconnectsOrigin([`${LAN}/`], LAN), true);+ assert.equal(lanAccessStopDisconnectsOrigin([LAN], `${LAN}/`), true);+ assert.equal(lanAccessStopDisconnectsOrigin([`${LAN}///`], `${LAN}/`), true);+});++test("stop-disconnects normalizes default HTTP and HTTPS ports", () => {+ assert.equal(+ lanAccessStopDisconnectsOrigin(+ ["http://192.168.1.24:80"],+ "http://192.168.1.24",+ ),+ true,+ );+ assert.equal(+ lanAccessStopDisconnectsOrigin(+ ["https://192.168.1.24:443"],+ "https://192.168.1.24",+ ),+ true,+ );+});++test("stop-disconnects is false for a loopback browser or another address", () => {+ assert.equal(+ lanAccessStopDisconnectsOrigin([LAN], "http://127.0.0.1:8888"),+ false,+ );+ assert.equal(lanAccessStopDisconnectsOrigin([LAN], SECOND), false);+ assert.equal(lanAccessStopDisconnectsOrigin([], LAN), false);+ assert.equal(lanAccessStopDisconnectsOrigin([], ""), false);+ assert.equal(lanAccessStopDisconnectsOrigin(["not a URL"], LAN), false);+});++test("stop-disconnects does not treat a different port as the same origin", () => {+ assert.equal(+ lanAccessStopDisconnectsOrigin([LAN], "http://192.168.1.24:9999"),+ false,+ );+});++// ── lanAccessBlockMessage ──++test("every block reason the backend can emit has a message", () => {+ // mirrors the block_reason chain in utils/lan_access_settings.py+ const reasons = [+ "server_starting",+ "colab",+ "launch_managed",+ "secure_launch",+ "admin_password_change_required",+ ];+ for (const reason of reasons) {+ for (const isDesktop of [true, false]) {+ const msg = lanAccessBlockMessage(reason, isDesktop);+ assert.ok(+ msg && msg.length > 0,+ `no message for ${reason} (desktop=${isDesktop})`,+ );+ }+ }+});++test("the pending-password message is desktop-aware", () => {+ const desktop = lanAccessBlockMessage("admin_password_change_required", true);+ const web = lanAccessBlockMessage("admin_password_change_required", false);+ assert.notEqual(desktop, web);+ assert.ok(!desktop?.includes("reset-password"));+ assert.ok(web?.includes("reset-password"));+});++test("an unknown or absent reason yields no message", () => {+ assert.equal(lanAccessBlockMessage(null, false), null);+ assert.equal(lanAccessBlockMessage("something_new", false), null);+ assert.equal(lanAccessBlockMessage("", true), null);+});++// ── lanAccessErrorMessage ──++test("every listener failure the backend can raise has a message", () => {+ // mirrors the RuntimeError reasons in lan_access.start_lan_listener+ for (const error of [+ "no_lan_address",+ "bind_failed",+ "listener_start_failed",+ "stop_timed_out",+ ]) {+ const msg = lanAccessErrorMessage(error);+ assert.ok(msg && msg.length > 0, `no message for ${error}`);+ }+});++test("no error means no message, and an unknown one still says something", () => {+ assert.equal(lanAccessErrorMessage(null), null);+ assert.ok(lanAccessErrorMessage("something_new")?.length);+});