Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Add configurable LAN access port (#10082)

Wasim Yousef Saidf569eea1172c
diff --git a/studio/backend/lan_access.py b/studio/backend/lan_access.py
index 233ad4d8bd2..11bb319f65e 100644
--- a/studio/backend/lan_access.py
+++ b/studio/backend/lan_access.py
@@ -276,13 +276,13 @@ def _wait_until(predicate, timeout: float) -> bool:
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.
- """
+def start_lan_listener(
+ app,
+ loop,
+ port: int,
+ fallback_ports: tuple[int, ...] = (),
+) -> tuple[str, ...]:
+ """Serve ``app`` on LAN addresses at the first bindable candidate port."""
global _server, _serve_loop, _sockets, _bound_addresses, _port, _error
with _lock:
@@ -297,16 +297,26 @@ def start_lan_listener(app, loop, port: int) -> tuple[str, ...]:
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)
+ attempted: list[str] = []
+ for candidate_port in (port, *fallback_ports):
+ sockets = []
+ bound = []
+ failures = []
+ for address in candidates:
+ try:
+ sockets.append(_bind_listener(address, candidate_port))
+ except OSError as exc:
+ failures.append(f"{address}:{candidate_port} ({exc})")
+ continue
+ bound.append(address)
+ if sockets:
+ port = candidate_port
+ break
+ attempted.extend(failures)
+
if not sockets:
_error = "bind_failed"
- logger.warning("LAN access could not bind port %s: %s", port, "; ".join(failures))
+ logger.warning("LAN access could not bind: %s", "; ".join(attempted))
raise RuntimeError(_error)
if failures:
logger.info("LAN access skipped unbindable addresses: %s", "; ".join(failures))
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 230424f2121..a3197ffa14a 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -11,7 +11,15 @@ from typing import Any, Literal, Optional, get_args
from urllib.parse import unquote, urlsplit
from fastapi import APIRouter, Depends, Header, HTTPException, Request
-from pydantic import BaseModel, ConfigDict, Field, StrictBool, ValidationError, field_validator
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ StrictBool,
+ StrictInt,
+ ValidationError,
+ field_validator,
+)
from auth.authentication import (
authenticated_via_api_key,
@@ -127,6 +135,7 @@ from utils.current_date_prompt_settings import (
)
from utils.lan_access_settings import (
lan_access_status,
+ save_lan_access_port,
set_lan_access_auto_start,
start_lan_access,
stop_lan_access,
@@ -2996,12 +3005,19 @@ class LanAccessAutoStartPayload(BaseModel):
enabled: StrictBool
+class LanAccessPortPayload(BaseModel):
+ port: Optional[StrictInt] = Field(ge = 1, le = 65535)
+
+
class LanAccessResponse(BaseModel):
state: Literal["off", "online", "error"]
urls: list[str] = []
public_urls: list[str] = []
error: Optional[str] = None
auto_start: bool
+
+ configured_port: Optional[int] = None
+ active_port: Optional[int] = None
managed_by: Optional[Literal["launch", "settings"]] = None
can_start: bool
can_stop: bool
@@ -3073,6 +3089,25 @@ def update_lan_access_auto_start(
return _lan_access_response(request)
[email protected]("/lan-access/port", response_model = LanAccessResponse)
+def update_lan_access_port(
+ request: Request,
+ payload: LanAccessPortPayload,
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session),
+) -> LanAccessResponse:
+ try:
+ response = LanAccessResponse(**save_lan_access_port(request.app, payload.port))
+ except RuntimeError as exc:
+ raise HTTPException(status_code = 409, detail = str(exc)) from exc
+ logger.info(
+ "settings.lan_access_port_updated subject=%s port=%s",
+ current_subject,
+ payload.port if payload.port is not None else "automatic",
+ )
+ return response
+
+
@router.get("/preview-sharing", response_model = PreviewSharingResponse)
def get_preview_sharing(
current_subject: str = Depends(get_current_subject),
diff --git a/studio/backend/tests/test_lan_access_settings.py b/studio/backend/tests/test_lan_access_settings.py
index 47d1ecfcbae..4e3fbc22efb 100644
--- a/studio/backend/tests/test_lan_access_settings.py
+++ b/studio/backend/tests/test_lan_access_settings.py
@@ -86,6 +86,42 @@ def test_auto_start_persistence_is_strict_and_fail_closed(monkeypatch, stored_se
assert lan_settings.get_lan_access_auto_start() is False
+def test_port_persistence_defaults_to_automatic_and_validates(stored_settings):
+ assert lan_settings.get_lan_access_port() is None
+ assert lan_settings.lan_access_port_candidates() == tuple(range(8888, 8909))
+
+ assert lan_settings.set_lan_access_port(43210) == 43210
+ assert lan_settings.get_lan_access_port() == 43210
+ assert lan_settings.lan_access_port_candidates() == (43210,)
+
+ for invalid in (0, 65536, True, "8888"):
+ with pytest.raises((ValueError, TypeError)):
+ lan_settings.set_lan_access_port(invalid)
+ with pytest.raises(ValueError):
+ routes.LanAccessPortPayload(port = invalid)
+
+ stored_settings[lan_settings.LAN_ACCESS_PORT_KEY] = "broken"
+ assert lan_settings.get_lan_access_port() is None
+ assert routes.LanAccessPortPayload(port = None).port is None
+
+ with pytest.raises(ValueError):
+ routes.LanAccessPortPayload()
+
+
+def test_saving_a_new_port_policy_clears_the_previous_bind_error():
+ app = _app()
+ lan_access._error = "bind_failed"
+
+ status = lan_settings.save_lan_access_port(app, 43210)
+ assert status["error"] is None
+ assert status["configured_port"] == 43210
+
+ lan_access._error = "bind_failed"
+ status = lan_settings.save_lan_access_port(app, None)
+ assert status["error"] is None
+ assert status["configured_port"] is None
+
+
# ── launch policy ──
@@ -911,15 +947,23 @@ def test_a_start_with_no_usable_address_fails_without_leaving_state(monkeypatch)
assert lan_access.lan_listener_status()["error"] is None
-def test_a_port_already_taken_on_every_address_fails_closed(monkeypatch):
+def test_automatic_tries_each_port_and_exact_does_not_fall_back(monkeypatch):
monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda: ["10.0.0.7"])
+ attempted = []
- def _refuse(*_args, **_kwargs):
+ def _refuse(_address, port):
+ attempted.append(port)
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)
+ lan_access.start_lan_listener(object(), object(), 8888, (8889, 8890))
+ assert attempted == [8888, 8889, 8890]
+
+ attempted.clear()
+ with pytest.raises(RuntimeError, match = "bind_failed"):
+ lan_access.start_lan_listener(object(), object(), 43210)
+ assert attempted == [43210]
assert lan_access.lan_listener_status()["running"] is False
@@ -1136,6 +1180,7 @@ def test_stop_releases_the_sockets_itself_when_the_serving_loop_is_gone(monkeypa
def _configured(live_server):
+ lan_settings.set_lan_access_port(live_server.port)
"""The live app carrying the launch policy run.py would have published on it."""
lan_settings.configure_lan_access(
live_server.app.state,
@@ -1253,9 +1298,100 @@ def test_start_refuses_while_a_block_is_in_force():
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_uses_the_saved_port_policy(monkeypatch):
+ calls = []
+ loop = SimpleNamespace(is_closed = lambda: False, is_running = lambda: True)
+ app = _app(lan_access_loop = loop)
+ monkeypatch.setattr(
+ lan_access,
+ "start_lan_listener",
+ lambda _app, _loop, port, fallback: calls.append((port, fallback)) or ("10.0.0.7",),
+ )
+
+ lan_settings.start_lan_access(app)
+ assert calls == [(8888, tuple(range(8889, 8909)))]
+
+ lan_settings.set_lan_access_port(43210)
+ lan_settings.start_lan_access(app)
+ assert calls[-1] == (43210, ())
+
+
+ "stored,reason",
+ [
+ (43210, "lan_access_port_unavailable"),
+ ("broken", "lan_access_port_invalid"),
+ ],
+)
+def test_start_refuses_when_the_saved_port_policy_is_unusable(
+ monkeypatch, stored_settings, stored, reason
+):
+ stored_settings[lan_settings.LAN_ACCESS_PORT_KEY] = stored
+ loop = SimpleNamespace(is_closed = lambda: False, is_running = lambda: True)
+ app = _app(lan_access_loop = loop)
+ calls = []
+ monkeypatch.setattr(
+ lan_access,
+ "start_lan_listener",
+ lambda *_args: calls.append(_args) or ("10.0.0.7",),
+ )
+ if stored == 43210:
+ monkeypatch.setattr(
+ studio_db,
+ "get_app_setting",
+ lambda *_args: (_ for _ in ()).throw(OSError("database unavailable")),
+ )
+
+ with pytest.raises(RuntimeError, match = reason):
+ lan_settings.start_lan_access(app)
+ assert calls == []
+
+
+def test_start_and_port_save_are_serialized(monkeypatch):
+ entered = threading.Event()
+ release = threading.Event()
+ running = False
+ loop = SimpleNamespace(is_closed = lambda: False, is_running = lambda: True)
+ app = _app(lan_access_loop = loop)
+
+ def status(_app):
+ return {
+ "state": "online" if running else "off",
+ "can_start": not running,
+ "block_reason": None,
+ }
+
+ def start_listener(*_args):
+ nonlocal running
+ entered.set()
+ assert release.wait(timeout = 2)
+ running = True
+ return ("10.0.0.7",)
+
+ monkeypatch.setattr(lan_settings, "lan_access_status", status)
+ monkeypatch.setattr(lan_access, "start_lan_listener", start_listener)
+
+ start_thread = threading.Thread(target = lan_settings.start_lan_access, args = (app,))
+ start_thread.start()
+ assert entered.wait(timeout = 2)
+
+ save_errors = []
+
+ def save():
+ try:
+ lan_settings.save_lan_access_port(app, 43210)
+ except RuntimeError as exc:
+ save_errors.append(str(exc))
+
+ save_thread = threading.Thread(target = save)
+ save_thread.start()
+ time.sleep(0.05)
+ assert save_thread.is_alive(), "port save did not wait for the in-flight start"
+
+ release.set()
+ start_thread.join(timeout = 2)
+ save_thread.join(timeout = 2)
+ assert save_errors == ["lan_access_running"]
def test_start_refuses_once_the_server_loop_is_gone(monkeypatch):
@@ -1299,6 +1435,23 @@ def test_colab_auto_start_setting_is_read_only(monkeypatch):
assert exc.value.status_code == 409
+def test_port_update_route_rejects_running_and_colab_lan_access(monkeypatch):
+ for reason in ("lan_access_running", "colab"):
+ monkeypatch.setattr(
+ routes,
+ "save_lan_access_port",
+ lambda *_args, reason = reason: (_ for _ in ()).throw(RuntimeError(reason)),
+ )
+ with pytest.raises(HTTPException) as exc:
+ routes.update_lan_access_port(
+ SimpleNamespace(app = _app()),
+ routes.LanAccessPortPayload(port = 43210),
+ "admin",
+ None,
+ )
+ assert exc.value.status_code == 409 and exc.value.detail == reason
+
+
def test_a_blocked_start_answers_409_rather_than_500(monkeypatch):
monkeypatch.setattr(
routes, "start_lan_access", lambda _app: (_ for _ in ()).throw(RuntimeError("colab"))
@@ -1323,7 +1476,7 @@ def test_management_rejects_api_keys():
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 len(gated) == 5, f"expected 5 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)}"
diff --git a/studio/backend/utils/lan_access_settings.py b/studio/backend/utils/lan_access_settings.py
index d0b78afbf1d..7d73bda20dd 100644
--- a/studio/backend/utils/lan_access_settings.py
+++ b/studio/backend/utils/lan_access_settings.py
@@ -12,6 +12,8 @@ from __future__ import annotations
import ipaddress
import socket
+
+import threading
from typing import Any, Optional
from loggers import get_logger
@@ -21,6 +23,13 @@ logger = get_logger(__name__)
LAN_ACCESS_AUTO_START_KEY = "lan_access_auto_start"
DEFAULT_LAN_ACCESS_AUTO_START = False
+LAN_ACCESS_PORT_KEY = "lan_access_port"
+DEFAULT_LAN_ACCESS_PORT = 8888
+LAST_LAN_ACCESS_PORT = 8908
+
+
+_management_lock = threading.RLock()
+
_PRIVATE_LAN_NETWORKS = (
ipaddress.ip_network("10.0.0.0/8"),
ipaddress.ip_network("172.16.0.0/12"),
@@ -193,6 +202,60 @@ def set_lan_access_auto_start(enabled: bool) -> bool:
return enabled
+def _valid_port(value: Any) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool) and 1 <= value <= 65535
+
+
+def _read_lan_access_port(*, strict: bool) -> Optional[int]:
+ try:
+ from storage.studio_db import get_app_setting
+ stored = get_app_setting(LAN_ACCESS_PORT_KEY, None)
+ except Exception as exc:
+ if strict:
+ raise RuntimeError("lan_access_port_unavailable") from exc
+ return None
+ if stored is None or _valid_port(stored):
+ return stored
+ if strict:
+ raise RuntimeError("lan_access_port_invalid")
+ return None
+
+
+def get_lan_access_port() -> Optional[int]:
+ """The valid saved port, or ``None`` for Automatic/status fallback."""
+ return _read_lan_access_port(strict = False)
+
+
+def set_lan_access_port(port: Optional[int]) -> Optional[int]:
+ if port is not None and not _valid_port(port):
+ raise ValueError("LAN access port must be between 1 and 65535.")
+ from storage.studio_db import upsert_app_settings
+
+ upsert_app_settings({LAN_ACCESS_PORT_KEY: port})
+ return port
+
+
+def lan_access_port_candidates() -> tuple[int, ...]:
+ custom = _read_lan_access_port(strict = True)
+ if custom is not None:
+ return (custom,)
+ return tuple(range(DEFAULT_LAN_ACCESS_PORT, LAST_LAN_ACCESS_PORT + 1))
+
+
+def save_lan_access_port(app, port: Optional[int]) -> dict:
+ with _management_lock:
+ status = lan_access_status(app)
+ if bool(getattr(app.state, "lan_access_is_colab", False)):
+ raise RuntimeError("colab")
+ if status["state"] == "online":
+ raise RuntimeError("lan_access_running")
+ set_lan_access_port(port)
+ from lan_access import clear_lan_listener_error
+
+ clear_lan_listener_error()
+ return lan_access_status(app)
+
+
def _admin_password_ready() -> bool:
try:
from auth.storage import DEFAULT_ADMIN_USERNAME, requires_password_change
@@ -345,17 +408,20 @@ def lan_access_status(app) -> dict:
block_reason = "admin_password_change_required"
running = bool(listener["running"])
+ configured_port = get_lan_access_port()
if launch_managed:
state, urls, managed_by = "online", _launch_urls(app_state), "launch"
+ active_port = getattr(app_state, "lan_access_port", None)
elif running:
state, urls, managed_by = (
"online",
_listener_urls(listener["addresses"], listener["port"]),
"settings",
)
+ active_port = listener["port"]
else:
state = "error" if listener["error"] else "off"
- urls, managed_by = [], None
+ urls, managed_by, active_port = [], None, None
controllable = block_reason is None
try:
@@ -372,6 +438,8 @@ def lan_access_status(app) -> dict:
),
"error": listener["error"],
"auto_start": get_lan_access_auto_start(),
+ "configured_port": configured_port,
+ "active_port": active_port,
"managed_by": managed_by,
"can_start": controllable and not running,
"can_stop": controllable and running,
@@ -396,20 +464,22 @@ def _server_loop(app_state):
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)
+ with _management_lock:
+ 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")
+
+ ports = lan_access_port_candidates()
+ addresses = start_lan_listener(
+ app,
+ _server_loop(app.state),
+ ports[0],
+ ports[1:],
+ )
+ logger.info("LAN access started on %s", ", ".join(addresses))
+ return lan_access_status(app)
def stop_lan_access(app) -> dict:
diff --git a/studio/frontend/src/features/settings/api/lan-access-state.ts b/studio/frontend/src/features/settings/api/lan-access-state.ts
index a332913d1ee..23871411399 100644
--- a/studio/frontend/src/features/settings/api/lan-access-state.ts
+++ b/studio/frontend/src/features/settings/api/lan-access-state.ts
@@ -11,6 +11,10 @@ export type LanAccessStatus = {
publicUrls: string[];
error: string | null;
autoStart: boolean;
+
+ portConfigurationSupported: boolean;
+ configuredPort: number | null;
+ activePort: number | null;
managedBy: LanAccessOwner;
canStart: boolean;
canStop: boolean;
@@ -31,6 +35,11 @@ export type ApiLanAccessStatus = {
error?: string | null;
// biome-ignore lint/style/useNamingConvention: API schema
auto_start: boolean;
+
+ // biome-ignore lint/style/useNamingConvention: API schema
+ configured_port?: number | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ active_port?: number | null;
// biome-ignore lint/style/useNamingConvention: API schema
managed_by?: LanAccessOwner;
// biome-ignore lint/style/useNamingConvention: API schema
@@ -67,6 +76,14 @@ export function normalizeLanAccessStatus(
publicUrls: Array.isArray(status.public_urls) ? status.public_urls : [],
error: status.error ?? null,
autoStart: status.auto_start,
+
+ portConfigurationSupported: Object.hasOwn(status, "configured_port"),
+ configuredPort:
+ typeof status.configured_port === "number"
+ ? status.configured_port
+ : null,
+ activePort:
+ typeof status.active_port === "number" ? status.active_port : null,
managedBy: status.managed_by ?? null,
canStart: status.can_start,
canStop: status.can_stop,
@@ -114,6 +131,20 @@ export function lanAccessAutoStartReadOnly(
return status === null || status.blockReason === "colab";
}
+export function lanAccessPortReadOnly(status: LanAccessStatus | null): boolean {
+ return (
+ status === null ||
+ !status.portConfigurationSupported ||
+ status.state === "online" ||
+ status.blockReason === "colab"
+ );
+}
+
+export function validLanAccessPort(value: string): boolean {
+ const port = Number(value);
+ return Number.isInteger(port) && port >= 1 && port <= 65535;
+}
+
export function lanAccessStopDisconnectsOrigin(
urls: string[],
browserOrigin: string,
@@ -167,12 +198,17 @@ export function lanAccessBlockMessage(
}
}
-export function lanAccessErrorMessage(error: string | null): string | null {
+export function lanAccessErrorMessage(
+ error: string | null,
+ configuredPort: number | null = 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.";
+ return configuredPort === null
+ ? "Could not open any automatic LAN port from 8888 to 8908."
+ : `Port ${configuredPort} is unavailable. Stop the app using it or choose another custom port.`;
case "listener_start_failed":
return "The network listener did not start. Check the logs for details.";
case "stop_timed_out":
diff --git a/studio/frontend/src/features/settings/api/lan-access.ts b/studio/frontend/src/features/settings/api/lan-access.ts
index 893529ccd24..fc29bea55e7 100644
--- a/studio/frontend/src/features/settings/api/lan-access.ts
+++ b/studio/frontend/src/features/settings/api/lan-access.ts
@@ -34,3 +34,10 @@ export const updateLanAccessAutoStart = (enabled: boolean) =>
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ enabled }),
});
+
+export const updateLanAccessPort = (port: number | null) =>
+ requestLanAccess("/port", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ port }),
+ });
diff --git a/studio/frontend/src/features/settings/components/lan-access-section.tsx b/studio/frontend/src/features/settings/components/lan-access-section.tsx
index d3ec946a5e2..611175703d5 100644
--- a/studio/frontend/src/features/settings/components/lan-access-section.tsx
+++ b/studio/frontend/src/features/settings/components/lan-access-section.tsx
@@ -10,12 +10,22 @@ import {
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
+
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import {
loadLanAccess,
startLanAccess,
stopLanAccess,
updateLanAccessAutoStart,
+ updateLanAccessPort,
} from "@/features/settings/api/lan-access";
import {
LAN_ACCESS_POLL_MS,
@@ -24,7 +34,9 @@ import {
lanAccessAutoStartReadOnly,
lanAccessBlockMessage,
lanAccessErrorMessage,
+ lanAccessPortReadOnly,
lanAccessStopDisconnectsOrigin,
+ validLanAccessPort,
} from "@/features/settings/api/lan-access-state";
import { isTauri } from "@/lib/api-base";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
@@ -32,11 +44,12 @@ 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 { useCallback, useEffect, useId, useRef, useState } from "react";
import QRCode from "react-qr-code";
import { SettingsRow } from "./settings-row";
-type LanAccessOperation = "start" | "stop" | "auto";
+type LanAccessOperation = "start" | "stop" | "auto" | "port";
+type PortMode = "automatic" | "custom";
const STATE_LABEL: Record<LanAccessStatus["state"], string> = {
off: "Off",
@@ -218,8 +231,13 @@ function LanUrlPanel({ status }: { status: LanAccessStatus | null }) {
}
export function LanAccessSection() {
+ const portErrorId = useId();
const [status, setStatus] = useState<LanAccessStatus | null>(null);
const [busy, setBusy] = useState<LanAccessOperation | null>(null);
+
+ const [portMode, setPortMode] = useState<PortMode>("automatic");
+ const [portDraft, setPortDraft] = useState("8888");
+ const [portError, setPortError] = useState<string | null>(null);
const [pollRevision, setPollRevision] = useState(0);
const [pollEnabled, setPollEnabled] = useState(true);
const mutationEpoch = useRef(0);
@@ -230,6 +248,13 @@ export function LanAccessSection() {
setStatus(next);
}, []);
+ useEffect(() => {
+ const configured = status?.configuredPort;
+ setPortMode(configured == null ? "automatic" : "custom");
+ setPortDraft(String(configured ?? 8888));
+ setPortError(null);
+ }, [status?.configuredPort]);
+
// biome-ignore lint/correctness/useExhaustiveDependencies: pollRevision intentionally restarts polling after a mutation
useEffect(() => {
if (!pollEnabled) {
@@ -294,6 +319,9 @@ export function LanAccessSection() {
selfStopDisconnectExpected.current = true;
}
} catch {
+ if (operation === "port") {
+ setPortError("Could not save the LAN port.");
+ }
// polling resumes below and reconciles the visible state
} finally {
setBusy(null);
@@ -316,8 +344,22 @@ export function LanAccessSection() {
const setAutoStart = (enabled: boolean) =>
perform("auto", () => updateLanAccessAutoStart(enabled));
+ const portInvalid = portMode === "custom" && !validLanAccessPort(portDraft);
+ const portErrorVisible = portInvalid || portError !== null;
+ const selectedPort =
+ portMode === "custom" && !portInvalid ? Number(portDraft) : null;
+ const portDirty = status !== null && selectedPort !== status.configuredPort;
+ const savePort = () => {
+ if (portInvalid || !portDirty) return;
+ setPortError(null);
+ void perform("port", () => updateLanAccessPort(selectedPort));
+ };
+
const blockMessage = lanAccessBlockMessage(status, isTauri);
- const errorMessage = lanAccessErrorMessage(status?.error ?? null);
+ const errorMessage = lanAccessErrorMessage(
+ status?.error ?? null,
+ status?.configuredPort ?? null,
+ );
const stopAction = status?.state === "online";
const actionDisabled =
busy !== null || (stopAction ? !status?.canStop : !status?.canStart);
@@ -375,6 +417,79 @@ export function LanAccessSection() {
<LanUrlPanel status={status} />
<div className="border-t border-border/60 px-4 py-1">
+ {status?.portConfigurationSupported ? (
+ <SettingsRow
+ label="Port"
+ description="Automatic tries 8888, then 8889–8908. Custom uses only the selected port. Stop LAN access before changing it."
+ >
+ <div className="flex flex-col items-end gap-1.5">
+ <div className="flex items-center gap-2">
+ <Select
+ value={portMode}
+ disabled={busy !== null || lanAccessPortReadOnly(status)}
+ onValueChange={(value) => {
+ setPortMode(value as PortMode);
+ setPortError(null);
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ className="w-28"
+ aria-label="LAN port mode"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="automatic">Automatic</SelectItem>
+ <SelectItem value="custom">Custom</SelectItem>
+ </SelectContent>
+ </Select>
+ {portMode === "custom" ? (
+ <Input
+ type="number"
+ min={1}
+ max={65535}
+ value={portDraft}
+ disabled={busy !== null || lanAccessPortReadOnly(status)}
+ aria-label="Custom LAN port"
+ aria-invalid={portInvalid}
+ aria-describedby={portErrorVisible ? portErrorId : undefined}
+ className="h-8 w-24"
+ onChange={(event) => {
+ setPortDraft(event.target.value);
+ setPortError(null);
+ }}
+ />
+ ) : null}
+ <Button
+ type="button"
+ size="sm"
+ onClick={savePort}
+ disabled={
+ busy !== null ||
+ lanAccessPortReadOnly(status) ||
+ portInvalid ||
+ !portDirty
+ }
+ >
+ Save
+ </Button>
+ </div>
+ <span
+ id={portErrorId}
+ role="status"
+ aria-live="polite"
+ className="text-xs text-destructive"
+ >
+ {portErrorVisible
+ ? portInvalid
+ ? "Enter a port from 1 to 65535."
+ : portError
+ : null}
+ </span>
+ </div>
+ </SettingsRow>
+ ) : null}
<SettingsRow
label="Keyless API status"
description={keylessLanAccessDescription(status)}
diff --git a/studio/frontend/tests/lan-access-state.test.ts b/studio/frontend/tests/lan-access-state.test.ts
index 60bffe6416d..3037126b83c 100644
--- a/studio/frontend/tests/lan-access-state.test.ts
+++ b/studio/frontend/tests/lan-access-state.test.ts
@@ -2,9 +2,10 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
import test from "node:test";
-// lan-access-section.tsx pulls in hugeicons, so only its pure helpers are tested here
+// lan-access-section.tsx pulls in hugeicons, so runtime tests stay on pure helpers.
import {
type ApiLanAccessStatus,
type LanAccessStatus,
@@ -12,13 +13,22 @@ import {
lanAccessAutoStartReadOnly,
lanAccessBlockMessage,
lanAccessErrorMessage,
+ lanAccessPortReadOnly,
lanAccessStopDisconnectsOrigin,
normalizeLanAccessStatus,
+ validLanAccessPort,
} 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";
+const SECTION_SOURCE = readFileSync(
+ new URL(
+ "../src/features/settings/components/lan-access-section.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+);
function apiStatus(over: Partial<ApiLanAccessStatus> = {}): ApiLanAccessStatus {
return {
@@ -43,6 +53,9 @@ test("normalize maps every snake_case field onto its camelCase name", () => {
error: null,
// biome-ignore lint/style/useNamingConvention: API schema
auto_start: true,
+
+ configured_port: 43210,
+ active_port: 43210,
// biome-ignore lint/style/useNamingConvention: API schema
managed_by: "settings",
// biome-ignore lint/style/useNamingConvention: API schema
@@ -67,6 +80,10 @@ test("normalize maps every snake_case field onto its camelCase name", () => {
publicUrls: [],
error: null,
autoStart: true,
+
+ portConfigurationSupported: true,
+ configuredPort: 43210,
+ activePort: 43210,
managedBy: "settings",
canStart: false,
canStop: true,
@@ -85,6 +102,11 @@ test("normalize defaults the optional fields an older backend may omit", () => {
assert.deepEqual(s.urls, []);
assert.deepEqual(s.publicUrls, []);
assert.equal(s.error, null);
+
+ assert.equal(s.configuredPort, null);
+ assert.equal(s.activePort, null);
+ assert.equal(s.portConfigurationSupported, false);
+ assert.equal(lanAccessPortReadOnly(s), true);
assert.equal(s.managedBy, null);
assert.equal(s.blockReason, null);
assert.equal(s.bindHost, null);
@@ -95,6 +117,38 @@ test("normalize defaults the optional fields an older backend may omit", () => {
assert.equal(s.keylessTools, false);
});
+test("an explicit automatic port remains distinct from an old backend", () => {
+ const s = normalizeLanAccessStatus(
+ apiStatus({ configured_port: null, active_port: null }),
+ );
+ assert.equal(s.portConfigurationSupported, true);
+ assert.equal(s.configuredPort, null);
+ assert.equal(lanAccessPortReadOnly(s), false);
+});
+
+test("the port form is capability-gated and keeps its live error region mounted", () => {
+ assert.equal(
+ SECTION_SOURCE.match(/["'`]Port["'`]/g)?.length,
+ 1,
+ );
+ assert.match(
+ SECTION_SOURCE,
+ /\{status\?\.portConfigurationSupported\s*\?\s*\(\s*<SettingsRow\s+label="Port"/,
+ );
+ assert.match(
+ SECTION_SOURCE,
+ /aria-describedby=\{portErrorVisible\s*\?\s*portErrorId\s*:\s*undefined\}/,
+ );
+ assert.match(
+ SECTION_SOURCE,
+ /<\/div>\s*<span\s+id=\{portErrorId\}\s+role="status"\s+aria-live="polite"[\s\S]*?>[\s\S]*?\{portErrorVisible\s*\?\s*portInvalid/,
+ );
+ assert.doesNotMatch(
+ SECTION_SOURCE,
+ /\{portErrorVisible\s*\?\s*\(\s*<span\s+id=\{portErrorId\}/,
+ );
+});
+
test("keyless state and messaging preserve every security boundary", () => {
const unknown = normalizeLanAccessStatus(
apiStatus({ keyless_scope: "unknown", keyless_tools: true }),
@@ -202,6 +256,41 @@ test("auto-start is read-only with no status, or under Colab", () => {
);
});
+test("port editing is limited to stopped, non-Colab LAN access", () => {
+ assert.equal(lanAccessPortReadOnly(null), true);
+ assert.equal(
+ lanAccessPortReadOnly(
+ normalizeLanAccessStatus(
+ apiStatus({ state: "online", configured_port: null }),
+ ),
+ ),
+ true,
+ );
+ assert.equal(
+ lanAccessPortReadOnly(
+ normalizeLanAccessStatus(
+ apiStatus({ block_reason: "colab", configured_port: null }),
+ ),
+ ),
+ true,
+ );
+ assert.equal(
+ lanAccessPortReadOnly(
+ normalizeLanAccessStatus(apiStatus({ configured_port: null })),
+ ),
+ false,
+ );
+});
+
+test("custom LAN ports accept only whole ports in range", () => {
+ for (const value of ["1", "8888", "43210", "65535"]) {
+ assert.equal(validLanAccessPort(value), true, value);
+ }
+ for (const value of ["", "0", "1.5", "65536", "nope"]) {
+ assert.equal(validLanAccessPort(value), false, value);
+ }
+});
+
// ── lanAccessStopDisconnectsOrigin ──
// a false negative here leaves the page polling an origin its own stop just killed
@@ -367,6 +456,14 @@ test("every listener failure the backend can raise has a message", () => {
}
});
+
+test("bind failures distinguish automatic from an occupied custom port", () => {
+ assert.ok(lanAccessErrorMessage("bind_failed")?.includes("8888 to 8908"));
+ const custom = lanAccessErrorMessage("bind_failed", 43210);
+ assert.ok(custom?.includes("43210"));
+ assert.ok(custom?.includes("choose another"));
+});
+
test("no error means no message, and an unknown one still says something", () => {
assert.equal(lanAccessErrorMessage(null), null);
assert.ok(lanAccessErrorMessage("something_new")?.length);