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: let LAN access bind only the addresses you choose (#12839)
Danteaf20aca644c2
diff --git a/studio/backend/lan_access.py b/studio/backend/lan_access.pyindex ce62091a05c..f5bef95a3b1 100644--- a/studio/backend/lan_access.py+++ b/studio/backend/lan_access.py@@ -266,8 +266,9 @@ def start_lan_listener(loop,port: int,fallback_ports: tuple[int, ...] = (),+ selected_addresses: Optional[tuple[str, ...]] = None,) -> tuple[str, ...]:- """Serve ``app`` on LAN addresses at the first bindable candidate port."""+ """Serve ``app`` on LAN addresses at the first bindable candidate port; ``selected_addresses=None`` binds all."""global _server, _serve_loop, _sockets, _bound_addresses, _port, _errorwith _lock:@@ -278,6 +279,22 @@ def start_lan_listener(if not candidates:_error = "no_lan_address"raise RuntimeError(_error)+ if selected_addresses is not None:+ # never widened back to the detected set: that would bind the addresses the user excluded+ missing = [address for address in selected_addresses if address not in candidates]+ candidates = [address for address in candidates if address in selected_addresses]+ if not candidates:+ _error = "selected_address_unavailable"+ logger.warning(+ "LAN access found none of the chosen addresses on this machine: %s",+ ", ".join(selected_addresses),+ )+ raise RuntimeError(_error)+ if missing:+ logger.info(+ "LAN access skipped chosen addresses not on this machine: %s",+ ", ".join(missing),+ )sockets: list[socket.socket] = []bound: list[str] = []diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex bac81f1f1da..f1f1147f28b 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -23,6 +23,7 @@ from pydantic import (Field,StrictBool,StrictInt,+ StrictStr,StringConstraints,ValidationError,field_validator,@@ -181,6 +182,8 @@ from utils.current_date_prompt_settings import ()from utils.lan_access_settings import (lan_access_status,+ normalize_lan_access_addresses,+ save_lan_access_addresses,save_lan_access_port,set_lan_access_auto_start,start_lan_access,@@ -3979,6 +3982,22 @@ class LanAccessPortPayload(BaseModel):port: Optional[StrictInt] = Field(ge = 1, le = 65535)+class LanAccessAddressesPayload(BaseModel):+ # required, so a body that forgets the field cannot silently reset the choice to Automatic+ addresses: Optional[list[StrictStr]]++ @field_validator("addresses")+ @classmethod+ def _bindable(cls, value: Optional[list[str]]) -> Optional[list[str]]:+ normalized = normalize_lan_access_addresses(value)+ return list(normalized) if normalized is not None else None+++class LanAccessAddress(BaseModel):+ address: str+ public: bool = False++class LanAccessResponse(BaseModel):state: Literal["off", "online", "error"]urls: list[str] = []@@ -3988,6 +4007,9 @@ class LanAccessResponse(BaseModel):configured_port: Optional[int] = Noneactive_port: Optional[int] = None+ configured_addresses: Optional[list[str]] = None+ available_addresses: list[LanAccessAddress] = []+ configured_public_addresses: list[str] = []managed_by: Optional[Literal["launch", "settings"]] = Nonecan_start: boolcan_stop: bool@@ -4078,6 +4100,25 @@ def update_lan_access_port(return response+@_owner_settings_router.put("/lan-access/addresses", response_model = LanAccessResponse)+def update_lan_access_addresses(+ request: Request,+ payload: LanAccessAddressesPayload,+ current_subject: str = Depends(get_current_subject),+ _ui_session: None = Depends(_require_ui_session),+) -> LanAccessResponse:+ try:+ response = LanAccessResponse(**save_lan_access_addresses(request.app, payload.addresses))+ except RuntimeError as exc:+ raise HTTPException(status_code = 409, detail = str(exc)) from exc+ logger.info(+ "settings.lan_access_addresses_updated subject=%s addresses=%s",+ current_subject,+ ",".join(payload.addresses) if payload.addresses is not None else "automatic",+ )+ return response++@_owner_settings_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_account_chat_settings.py b/studio/backend/tests/test_account_chat_settings.pyindex 6493fc58f3a..1a27497aa61 100644--- a/studio/backend/tests/test_account_chat_settings.py+++ b/studio/backend/tests/test_account_chat_settings.py@@ -382,6 +382,7 @@ OWNER_PATHS = ["/lan-access/stop": ("POST",),"/lan-access/auto-start": ("PUT",),"/lan-access/port": ("PUT",),+ "/lan-access/addresses": ("PUT",),"/preview-sharing": ("GET", "PUT"),"/keyless-api-access": ("GET", "PUT"),"/debug/logs/sources": ("GET",),diff --git a/studio/backend/tests/test_lan_access_settings.py b/studio/backend/tests/test_lan_access_settings.pyindex c8439590b06..0b833eff07d 100644--- a/studio/backend/tests/test_lan_access_settings.py+++ b/studio/backend/tests/test_lan_access_settings.py@@ -30,6 +30,10 @@ import utils.host_policy as host_policy # noqa: E402import utils.lan_access_settings as lan_settings # noqa: E402from storage import studio_db # noqa: E402+# captured before the autouse fixture swaps in the dict stand-in+_REAL_GET_APP_SETTING = studio_db.get_app_setting+_REAL_UPSERT_APP_SETTINGS = studio_db.upsert_app_settings+def _app(**over):state = SimpleNamespace(@@ -122,6 +126,254 @@ def test_saving_a_new_port_policy_clears_the_previous_bind_error():assert status["configured_port"] is None+_DETECTED = ["64.227.100.5", "192.168.1.24", "100.101.102.103"]+++def test_address_persistence_defaults_to_automatic_and_validates(stored_settings):+ assert lan_settings.get_lan_access_addresses() is None++ saved = lan_settings.set_lan_access_addresses(+ [" 100.101.102.103", "192.168.1.24", "100.101.102.103"]+ )+ assert saved == ("100.101.102.103", "192.168.1.24")+ assert lan_settings.get_lan_access_addresses() == saved+ assert stored_settings[lan_settings.LAN_ACCESS_ADDRESSES_KEY] == [+ "100.101.102.103",+ "192.168.1.24",+ ]++ assert lan_settings.set_lan_access_addresses(None) is None+ assert lan_settings.get_lan_access_addresses() is None++ for invalid in (+ [],+ "192.168.1.24",+ [7],+ ["not-an-ip"],+ # leading zeros read as octal by some resolvers, so the literal is ambiguous+ ["192.168.001.024"],+ ["fd00::24"],+ ["127.0.0.1"],+ ["169.254.10.1"],+ ["0.0.0.0"],+ ["224.0.0.1"],+ ["240.0.0.1"],+ [f"10.0.{n // 256}.{n % 256}" for n in range(65)],+ ["10.0.0.7"] * 65,+ ):+ with pytest.raises(ValueError):+ lan_settings.set_lan_access_addresses(invalid)+ with pytest.raises(ValueError):+ routes.LanAccessAddressesPayload(addresses = invalid)++ assert routes.LanAccessAddressesPayload(addresses = None).addresses is None+ with pytest.raises(ValueError):+ routes.LanAccessAddressesPayload()+++def test_a_corrupt_saved_selection_reads_as_automatic_but_refuses_to_start(+ monkeypatch, stored_settings+):+ stored_settings[lan_settings.LAN_ACCESS_ADDRESSES_KEY] = ["192.168.1.24", "nonsense"]+ assert lan_settings.get_lan_access_addresses() is None+ calls = []+ monkeypatch.setattr(+ lan_access, "start_lan_listener", lambda *args: calls.append(args) or ("10.0.0.7",)+ )+ app = _app(lan_access_loop = SimpleNamespace(is_closed = lambda: False, is_running = lambda: True))++ with pytest.raises(RuntimeError, match = "lan_access_addresses_invalid"):+ lan_settings.start_lan_access(app)+ real_get = studio_db.get_app_setting++ def _addresses_unreadable(key, fallback):+ if key == lan_settings.LAN_ACCESS_ADDRESSES_KEY:+ raise OSError("database unavailable")+ return real_get(key, fallback)++ monkeypatch.setattr(studio_db, "get_app_setting", _addresses_unreadable)+ with pytest.raises(RuntimeError, match = "lan_access_addresses_unavailable"):+ lan_settings.start_lan_access(app)+ assert calls == []+++def test_an_undecodable_saved_selection_refuses_to_start(monkeypatch):+ monkeypatch.setattr(studio_db, "get_app_setting", _REAL_GET_APP_SETTING)+ key = lan_settings.LAN_ACCESS_ADDRESSES_KEY+ assert lan_settings._read_lan_access_addresses(strict = True) is None+ _REAL_UPSERT_APP_SETTINGS({key: None})+ assert lan_settings._read_lan_access_addresses(strict = True) is None+ calls = []+ monkeypatch.setattr(+ lan_access, "start_lan_listener", lambda *args: calls.append(args) or ("10.0.0.7",)+ )+ app = _app(lan_access_loop = SimpleNamespace(is_closed = lambda: False, is_running = lambda: True))+ for corrupt in ('["192.168.1.24"', ""):+ conn = studio_db.get_connection()+ try:+ conn.execute("UPDATE app_settings SET value_json = ? WHERE key = ?", (corrupt, key))+ conn.commit()+ finally:+ conn.close()+ assert lan_settings.get_lan_access_addresses() is None+ with pytest.raises(RuntimeError, match = "lan_access_addresses_invalid"):+ lan_settings.start_lan_access(app)+ assert calls == []+++def test_start_hands_the_saved_selection_to_the_listener(monkeypatch, stored_settings):+ calls = []+ monkeypatch.setattr(+ lan_access, "start_lan_listener", lambda *args: calls.append(args) or ("10.0.0.7",)+ )+ app = _app(lan_access_loop = SimpleNamespace(is_closed = lambda: False, is_running = lambda: True))++ lan_settings.start_lan_access(app)+ assert calls[-1][4] is None++ lan_settings.set_lan_access_addresses(["100.101.102.103"])+ lan_settings.start_lan_access(app)+ assert calls[-1][4] == ("100.101.102.103",)+++def test_saving_a_selection_clears_the_previous_error_and_refuses_while_online():+ app = _app()+ lan_access._error = "selected_address_unavailable"++ status = lan_settings.save_lan_access_addresses(app, ["192.168.1.24"])+ assert status["error"] is None+ assert status["configured_addresses"] == ["192.168.1.24"]++ status = lan_settings.save_lan_access_addresses(app, None)+ assert status["configured_addresses"] is None++ with pytest.raises(RuntimeError, match = "lan_access_running"):+ lan_settings.save_lan_access_addresses(+ _app(lan_access_launch_managed = True), ["192.168.1.24"]+ )+ with pytest.raises(RuntimeError, match = "colab"):+ lan_settings.save_lan_access_addresses(_app(lan_access_is_colab = True), ["192.168.1.24"])+ with pytest.raises(ValueError):+ lan_settings.save_lan_access_addresses(_app(lan_access_launch_managed = True), ["nonsense"])+++def test_status_offers_every_detected_address_and_flags_the_public_ones(monkeypatch):+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda _ip_version = 4: list(_DETECTED))+ status = lan_settings.lan_access_status(_app())+ assert status["available_addresses"] == [+ {"address": "64.227.100.5", "public": True},+ {"address": "192.168.1.24", "public": False},+ {"address": "100.101.102.103", "public": False},+ ]+ assert status["configured_addresses"] is None+ response = routes.LanAccessResponse(**status)+ assert [entry.address for entry in response.available_addresses] == _DETECTED+ assert response.available_addresses[0].public is True+ assert (+ lan_settings.lan_access_status(_app(lan_access_launch_managed = True))["available_addresses"]+ == []+ )+++def test_status_flags_saved_public_addresses_even_when_they_are_down(monkeypatch, stored_settings):+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda _ip_version = 4: [])+ stored_settings[lan_settings.LAN_ACCESS_ADDRESSES_KEY] = ["64.227.100.5", "192.168.1.24"]+ status = lan_settings.lan_access_status(_app())+ assert status["configured_public_addresses"] == ["64.227.100.5"]+ assert routes.LanAccessResponse(**status).configured_public_addresses == ["64.227.100.5"]+ stored_settings.pop(lan_settings.LAN_ACCESS_ADDRESSES_KEY)+ assert lan_settings.lan_access_status(_app())["configured_public_addresses"] == []+++def test_status_survives_a_failing_address_detection(monkeypatch):+ def _broken(_ip_version = 4):+ raise RuntimeError("psutil exploded")++ monkeypatch.setattr(lan_access, "detect_lan_addresses", _broken)+ assert lan_settings.lan_access_status(_app())["available_addresses"] == []+++def test_the_addresses_route_validates_saves_and_refuses_while_online():+ from fastapi.testclient import TestClient++ from auth.authentication import authenticated_via_api_key, get_current_subject++ app = FastAPI()+ app.include_router(routes.router, prefix = "/settings")+ app.dependency_overrides[get_current_subject] = lambda: "owner"+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ app.dependency_overrides[routes._require_installation_owner] = lambda: None+ for key, value in vars(_app().state).items():+ setattr(app.state, key, value)++ with TestClient(app) as client:+ for invalid in ({"addresses": ["nonsense"]}, {"addresses": []}, {"addresses": [7]}, {}):+ response = client.put("/settings/lan-access/addresses", json = invalid)+ assert response.status_code == 422, (invalid, response.text)++ response = client.put(+ "/settings/lan-access/addresses", json = {"addresses": ["100.101.102.103"]}+ )+ assert response.status_code == 200, response.text+ assert response.json()["configured_addresses"] == ["100.101.102.103"]+ assert client.get("/settings/lan-access").json()["configured_addresses"] == [+ "100.101.102.103"+ ]++ response = client.put("/settings/lan-access/addresses", json = {"addresses": None})+ assert response.status_code == 200 and response.json()["configured_addresses"] is None++ app.state.lan_access_launch_managed = True+ response = client.put(+ "/settings/lan-access/addresses", json = {"addresses": ["192.168.1.24"]}+ )+ assert response.status_code == 409 and response.json()["detail"] == "lan_access_running"+++def _record_binds(monkeypatch):+ attempted = []++ def _refuse(address, _port):+ attempted.append(address)+ raise OSError("address in use")++ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda: list(_DETECTED))+ monkeypatch.setattr(lan_access, "_bind_listener", _refuse)+ return attempted+++def test_a_selection_binds_only_the_chosen_addresses(monkeypatch):+ attempted = _record_binds(monkeypatch)+ with pytest.raises(RuntimeError, match = "bind_failed"):+ lan_access.start_lan_listener(object(), object(), 8888, (), ("100.101.102.103",))+ assert attempted == ["100.101.102.103"]++ attempted.clear()+ with pytest.raises(RuntimeError, match = "bind_failed"):+ lan_access.start_lan_listener(+ object(), object(), 8888, (), ("10.9.9.9", "100.101.102.103", "192.168.1.24")+ )+ assert attempted == ["192.168.1.24", "100.101.102.103"]+++def test_automatic_still_binds_every_detected_address(monkeypatch):+ attempted = _record_binds(monkeypatch)+ with pytest.raises(RuntimeError, match = "bind_failed"):+ lan_access.start_lan_listener(object(), object(), 8888)+ assert attempted == _DETECTED+++def test_a_selection_with_nothing_detected_fails_closed(monkeypatch):+ attempted = _record_binds(monkeypatch)+ with pytest.raises(RuntimeError, match = "selected_address_unavailable"):+ lan_access.start_lan_listener(object(), object(), 8888, (8889,), ("10.9.9.9",))+ assert (+ attempted == []+ ), "an unavailable selection must never fall back to the detected addresses"+ status = lan_access.lan_listener_status()+ assert status["running"] is False and status["error"] == "selected_address_unavailable"++# ── launch policy ──@@ -1305,7 +1557,8 @@ def test_start_uses_the_saved_port_policy(monkeypatch):monkeypatch.setattr(lan_access,"start_lan_listener",- lambda _app, _loop, port, fallback: calls.append((port, fallback)) or ("10.0.0.7",),+ lambda _app, _loop, port, fallback, _selected: calls.append((port, fallback))+ or ("10.0.0.7",),)lan_settings.start_lan_access(app)@@ -1476,7 +1729,7 @@ def test_management_rejects_api_keys():continueargs = node.args.args + node.args.kwonlyargsgated[node.name] = any(a.arg == "_ui_session" for a in args)- assert len(gated) == 5, f"expected 5 lan-access handlers, found {sorted(gated)}"+ assert len(gated) == 6, f"expected 6 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.pyindex 2da3b98dc23..024d9552583 100644--- a/studio/backend/utils/lan_access_settings.py+++ b/studio/backend/utils/lan_access_settings.py@@ -22,6 +22,10 @@ LAN_ACCESS_PORT_KEY = "lan_access_port"DEFAULT_LAN_ACCESS_PORT = 8888LAST_LAN_ACCESS_PORT = 8908+LAN_ACCESS_ADDRESSES_KEY = "lan_access_addresses"+_MAX_LAN_ACCESS_ADDRESSES = 64+_UNREADABLE = object()+_management_lock = threading.RLock()@@ -232,6 +236,110 @@ def lan_access_port_candidates() -> tuple[int, ...]:return tuple(range(DEFAULT_LAN_ACCESS_PORT, LAST_LAN_ACCESS_PORT + 1))+def normalize_lan_access_addresses(addresses: Any) -> Optional[tuple[str, ...]]:+ """``None`` is Automatic; else a de-duplicated tuple of bindable IPv4 literals, detected right now or not."""+ if addresses is None:+ return None+ if not isinstance(addresses, (list, tuple)):+ raise ValueError("LAN access addresses must be a list of IPv4 addresses.")+ # counted before de-duplicating, so a padded list cannot make validation quadratic+ if len(addresses) > _MAX_LAN_ACCESS_ADDRESSES:+ raise ValueError(f"At most {_MAX_LAN_ACCESS_ADDRESSES} LAN access addresses can be chosen.")+ normalized: list[str] = []+ for value in addresses:+ if not isinstance(value, str):+ raise ValueError("LAN access addresses must be a list of IPv4 addresses.")+ try:+ parsed = ipaddress.IPv4Address(value.strip())+ except ValueError:+ raise ValueError(f"{value!r} is not an IPv4 address.") from None+ if (+ parsed.is_loopback+ or parsed.is_link_local+ or parsed.is_multicast+ or parsed.is_unspecified+ or parsed.is_reserved+ ):+ raise ValueError(f"{value!r} cannot be reached from another device.")+ if str(parsed) not in normalized:+ normalized.append(str(parsed))+ if not normalized:+ raise ValueError("Choose at least one LAN access address, or Automatic.")+ return tuple(normalized)+++def _read_lan_access_addresses(*, strict: bool) -> Optional[tuple[str, ...]]:+ """Strict reads (a start) fail closed: Automatic here would bind the addresses the user excluded."""+ try:+ from storage.studio_db import get_app_setting, get_app_settings+ stored = get_app_setting(LAN_ACCESS_ADDRESSES_KEY, _UNREADABLE)+ # the fallback also answers an undecodable row; only a missing row is Automatic+ if stored is _UNREADABLE and LAN_ACCESS_ADDRESSES_KEY not in get_app_settings(+ [LAN_ACCESS_ADDRESSES_KEY]+ ):+ stored = None+ except Exception as exc:+ if strict:+ raise RuntimeError("lan_access_addresses_unavailable") from exc+ return None+ if stored is _UNREADABLE:+ if strict:+ raise RuntimeError("lan_access_addresses_invalid")+ return None+ try:+ return normalize_lan_access_addresses(stored)+ except ValueError:+ if strict:+ raise RuntimeError("lan_access_addresses_invalid") from None+ return None+++def get_lan_access_addresses() -> Optional[tuple[str, ...]]:+ return _read_lan_access_addresses(strict = False)+++def set_lan_access_addresses(addresses: Any) -> Optional[tuple[str, ...]]:+ normalized = normalize_lan_access_addresses(addresses)+ from storage.studio_db import upsert_app_settings++ upsert_app_settings(+ {LAN_ACCESS_ADDRESSES_KEY: list(normalized) if normalized is not None else None}+ )+ return normalized+++def save_lan_access_addresses(app, addresses: Any) -> dict:+ normalized = normalize_lan_access_addresses(addresses)+ 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_addresses(normalized)+ from lan_access import clear_lan_listener_error++ clear_lan_listener_error()+ return lan_access_status(app)+++def _available_lan_addresses() -> list[dict]:+ """Detected addresses with a public flag; a detection failure offers nothing rather than failing status."""+ try:+ from lan_access import detect_lan_addresses, is_public_address+ return [+ {"address": address, "public": is_public_address(address)}+ for address in detect_lan_addresses()+ ]+ except Exception:+ return []+++def _public_lan_addresses(addresses) -> list[str]:+ from lan_access import is_public_address+ return [address for address in addresses if is_public_address(address)]++def save_lan_access_port(app, port: Optional[int]) -> dict:with _management_lock:status = lan_access_status(app)@@ -386,6 +494,7 @@ def lan_access_status(app) -> dict:running = bool(listener["running"])configured_port = get_lan_access_port()+ configured_addresses = get_lan_access_addresses()if launch_managed:state, urls, managed_by = "online", _launch_urls(app_state), "launch"active_port = getattr(app_state, "lan_access_port", None)@@ -416,6 +525,12 @@ def lan_access_status(app) -> dict:"error": listener["error"],"auto_start": get_lan_access_auto_start(),"configured_port": configured_port,+ "configured_addresses": list(configured_addresses)+ if configured_addresses is not None+ else None,+ "available_addresses": [] if launch_managed else _available_lan_addresses(),+ # a saved address that is down still needs its public warning+ "configured_public_addresses": _public_lan_addresses(configured_addresses or ()),"active_port": active_port,"managed_by": managed_by,"can_start": controllable and not running,@@ -449,11 +564,13 @@ def start_lan_access(app) -> dict:raise RuntimeError(status["block_reason"] or "operation_in_progress")ports = lan_access_port_candidates()+ selected = _read_lan_access_addresses(strict = True)addresses = start_lan_listener(app,_server_loop(app.state),ports[0],ports[1:],+ selected,)logger.info("LAN access started on %s", ", ".join(addresses))return lan_access_status(app)diff --git a/studio/frontend/src/features/settings/api/lan-access-state.ts b/studio/frontend/src/features/settings/api/lan-access-state.tsindex e0ff2c83457..847afea3198 100644--- a/studio/frontend/src/features/settings/api/lan-access-state.ts+++ b/studio/frontend/src/features/settings/api/lan-access-state.ts@@ -4,6 +4,8 @@export type LanAccessState = "off" | "online" | "error";export type LanAccessOwner = "launch" | "settings" | null;export type LanKeylessScope = "off" | "inference" | "full";+export type LanAccessAddress = { address: string; public: boolean };+export type LanAccessAddressChoice = LanAccessAddress & { detected: boolean };export type LanAccessStatus = {state: LanAccessState;@@ -15,6 +17,11 @@ export type LanAccessStatus = {portConfigurationSupported: boolean;configuredPort: number | null;activePort: number | null;+ addressConfigurationSupported: boolean;+ // null is Automatic: every detected address, public ones included+ configuredAddresses: string[] | null;+ availableAddresses: LanAccessAddress[];+ configuredPublicAddresses: string[];managedBy: LanAccessOwner;canStart: boolean;canStop: boolean;@@ -41,6 +48,12 @@ export type ApiLanAccessStatus = {// biome-ignore lint/style/useNamingConvention: API schemaactive_port?: number | null;// biome-ignore lint/style/useNamingConvention: API schema+ configured_addresses?: string[] | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ available_addresses?: LanAccessAddress[] | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ configured_public_addresses?: string[] | null;+ // biome-ignore lint/style/useNamingConvention: API schemamanaged_by?: LanAccessOwner;// biome-ignore lint/style/useNamingConvention: API schemacan_start: boolean;@@ -62,6 +75,17 @@ export type ApiLanAccessStatus = {keyless_tools?: boolean | null;};+function normalizeAddresses(value: unknown): LanAccessAddress[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value.flatMap((entry) =>+ entry && typeof entry.address === "string"+ ? [{ address: entry.address, public: entry.public === true }]+ : [],+ );+}+function normalizeKeylessScope(value: unknown): LanKeylessScope {return value === "inference" || value === "full" ? value : "off";}@@ -84,6 +108,21 @@ export function normalizeLanAccessStatus(: null,activePort:typeof status.active_port === "number" ? status.active_port : null,+ addressConfigurationSupported: Object.hasOwn(+ status,+ "configured_addresses",+ ),+ configuredAddresses: Array.isArray(status.configured_addresses)+ ? status.configured_addresses.filter(+ (address) => typeof address === "string",+ )+ : null,+ availableAddresses: normalizeAddresses(status.available_addresses),+ configuredPublicAddresses: Array.isArray(status.configured_public_addresses)+ ? status.configured_public_addresses.filter(+ (address) => typeof address === "string",+ )+ : [],managedBy: status.managed_by ?? null,canStart: status.can_start,canStop: status.can_stop,@@ -145,6 +184,60 @@ export function lanAccessPortReadOnly(status: LanAccessStatus | null): boolean {);}+export function lanAccessAddressesReadOnly(+ status: LanAccessStatus | null,+): boolean {+ return (+ status === null ||+ !status.addressConfigurationSupported ||+ status.state === "online" ||+ status.blockReason === "colab"+ );+}++export function lanAccessAddressChoices(+ status: LanAccessStatus | null,+ selected: string[],+): LanAccessAddressChoice[] {+ const detected = status?.availableAddresses ?? [];+ // a -H launch skips detection, so an address missing from the list is unknown, not down+ const detectionSkipped = status?.managedBy === "launch";+ const choices: LanAccessAddressChoice[] = detected.map((entry) => ({+ ...entry,+ detected: true,+ }));+ for (const address of [...(status?.configuredAddresses ?? []), ...selected]) {+ if (!choices.some((choice) => choice.address === address)) {+ choices.push({+ address,+ public: status?.configuredPublicAddresses.includes(address) ?? false,+ detected: detectionSkipped,+ });+ }+ }+ return choices;+}++export function defaultLanAccessAddressSelection(+ status: LanAccessStatus | null,+): string[] {+ return (status?.availableAddresses ?? [])+ .filter((entry) => !entry.public)+ .map((entry) => entry.address);+}++export function sameLanAccessAddresses(+ left: string[] | null,+ right: string[] | null,+): boolean {+ if (left === null || right === null) {+ return left === right;+ }+ const a = new Set(left);+ const b = new Set(right);+ return a.size === b.size && [...a].every((address) => b.has(address));+}+export function validLanAccessPort(value: string): boolean {const port = Number(value);return Number.isInteger(port) && port >= 1 && port <= 65535;@@ -214,6 +307,8 @@ export function lanAccessErrorMessage(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 "selected_address_unavailable":+ return "None of the chosen addresses is on this machine right now. Connect that network, or choose another address.";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.tsindex fc29bea55e7..28c809df883 100644--- a/studio/frontend/src/features/settings/api/lan-access.ts+++ b/studio/frontend/src/features/settings/api/lan-access.ts@@ -41,3 +41,10 @@ export const updateLanAccessPort = (port: number | null) =>headers: { "Content-Type": "application/json" },body: JSON.stringify({ port }),});++export const updateLanAccessAddresses = (addresses: string[] | null) =>+ requestLanAccess("/addresses", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ addresses }),+ });diff --git a/studio/frontend/src/features/settings/components/lan-access-section.tsx b/studio/frontend/src/features/settings/components/lan-access-section.tsxindex c3b9a3cd72d..df8d48bd0b2 100644--- a/studio/frontend/src/features/settings/components/lan-access-section.tsx+++ b/studio/frontend/src/features/settings/components/lan-access-section.tsx@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";import {Dialog,DialogContent,@@ -25,19 +26,24 @@ import {loadLanAccess,startLanAccess,stopLanAccess,+ updateLanAccessAddresses,updateLanAccessAutoStart,updateLanAccessPort,} from "@/features/settings/api/lan-access";import {LAN_ACCESS_POLL_MS,type LanAccessStatus,+ defaultLanAccessAddressSelection,keylessLanAccessDescription,+ lanAccessAddressChoices,+ lanAccessAddressesReadOnly,lanAccessAutoStartReadOnly,lanAccessBlockMessage,lanAccessErrorMessage,lanAccessPortReadOnly,lanAccessStopDisconnectsOrigin,lanApiUrls,+ sameLanAccessAddresses,validLanAccessPort,} from "@/features/settings/api/lan-access-state";import { isTauri } from "@/lib/api-base";@@ -50,8 +56,9 @@ import { useCallback, useEffect, useId, useRef, useState } from "react";import QRCode from "react-qr-code";import { SettingsRow } from "./settings-row";-type LanAccessOperation = "start" | "stop" | "auto" | "port";+type LanAccessOperation = "start" | "stop" | "auto" | "port" | "addresses";type PortMode = "automatic" | "custom";+type AddressMode = "automatic" | "chosen";const STATE_LABEL: Record<LanAccessStatus["state"], string> = {off: "Off",@@ -234,12 +241,16 @@ function LanUrlPanel({ status }: { status: LanAccessStatus | null }) {export function LanAccessSection() {const portErrorId = useId();+ const addressErrorId = 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 [addressMode, setAddressMode] = useState<AddressMode>("automatic");+ const [addressDraft, setAddressDraft] = useState<string[]>([]);+ const [addressError, setAddressError] = useState<string | null>(null);const [pollRevision, setPollRevision] = useState(0);const [pollEnabled, setPollEnabled] = useState(true);const mutationEpoch = useRef(0);@@ -258,6 +269,16 @@ export function LanAccessSection() {setPortError(null);}, [status?.configuredPort]);+ // keyed on the saved value, not the array: every poll returns a fresh one, which would wipe the draft+ const configuredAddressesKey = status?.configuredAddresses?.join(",") ?? null;+ // biome-ignore lint/correctness/useExhaustiveDependencies: configuredAddressesKey stands in for status.configuredAddresses+ useEffect(() => {+ const configured = status?.configuredAddresses ?? null;+ setAddressMode(configured === null ? "automatic" : "chosen");+ setAddressDraft(configured ?? []);+ setAddressError(null);+ }, [configuredAddressesKey]);+// biome-ignore lint/correctness/useExhaustiveDependencies: pollRevision intentionally restarts polling after a mutationuseEffect(() => {if (!pollEnabled) {@@ -325,6 +346,9 @@ export function LanAccessSection() {if (operation === "port") {setPortError("Could not save the LAN port.");}+ if (operation === "addresses") {+ setAddressError("Could not save the LAN addresses.");+ }// polling resumes below and reconciles the visible state} finally {setBusy(null);@@ -358,14 +382,40 @@ export function LanAccessSection() {void perform("port", () => updateLanAccessPort(selectedPort));};+ const addressesReadOnly = busy !== null || lanAccessAddressesReadOnly(status);+ const addressChoices = lanAccessAddressChoices(status, addressDraft);+ const addressesEmpty = addressMode === "chosen" && addressDraft.length === 0;+ const addressErrorVisible = addressesEmpty || addressError !== null;+ const selectedAddresses = addressMode === "chosen" ? addressDraft : null;+ const addressesDirty =+ status !== null &&+ !sameLanAccessAddresses(selectedAddresses, status.configuredAddresses);+ const toggleAddress = (address: string, checked: boolean) => {+ setAddressDraft((draft) =>+ checked+ ? [...draft.filter((entry) => entry !== address), address]+ : draft.filter((entry) => entry !== address),+ );+ setAddressError(null);+ };+ const saveAddresses = () => {+ if (addressesEmpty || !addressesDirty) return;+ setAddressError(null);+ void perform("addresses", () =>+ updateLanAccessAddresses(selectedAddresses),+ );+ };+const blockMessage = lanAccessBlockMessage(status, isTauri);const errorMessage = lanAccessErrorMessage(status?.error ?? null,status?.configuredPort ?? null,);const stopAction = status?.state === "online";+ // Start and auto-start bind the saved choice, never an unsaved oneconst actionDisabled =- busy !== null || (stopAction ? !status?.canStop : !status?.canStart);+ busy !== null ||+ (stopAction ? !status?.canStop : !status?.canStart || addressesDirty);const actionLabel =busy === "start"? "Starting…"@@ -495,6 +545,113 @@ export function LanAccessSection() {</div></SettingsRow>) : null}+ {status?.addressConfigurationSupported ? (+ <>+ <SettingsRow+ label="Addresses"+ description="Automatic uses every address this machine has, public ones included. Choose uses only the addresses you tick, such as a Tailscale address. Stop LAN access before changing it, and save before starting."+ below={+ <span+ id={addressErrorId}+ role="status"+ aria-live="polite"+ className="text-xs text-destructive"+ >+ {addressErrorVisible+ ? addressesEmpty+ ? "Tick at least one address, or use Automatic."+ : addressError+ : null}+ </span>+ }+ >+ <div className="flex items-center gap-2">+ <Select+ value={addressMode}+ disabled={addressesReadOnly}+ onValueChange={(value) => {+ const mode = value as AddressMode;+ setAddressMode(mode);+ if (mode === "chosen" && addressDraft.length === 0) {+ setAddressDraft(defaultLanAccessAddressSelection(status));+ }+ setAddressError(null);+ }}+ >+ <SelectTrigger+ size="sm"+ className="w-28"+ aria-label="LAN address mode"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="automatic">Automatic</SelectItem>+ <SelectItem value="chosen">Choose</SelectItem>+ </SelectContent>+ </Select>+ <Button+ type="button"+ size="sm"+ onClick={saveAddresses}+ disabled={+ addressesReadOnly || addressesEmpty || !addressesDirty+ }+ >+ Save+ </Button>+ </div>+ </SettingsRow>+ {addressMode === "chosen" ? (+ <fieldset+ className="flex flex-col gap-2 pb-3"+ aria-describedby={+ addressErrorVisible ? addressErrorId : undefined+ }+ >+ <legend className="sr-only">LAN addresses to use</legend>+ {addressChoices.length === 0 ? (+ <span className="text-xs text-muted-foreground">+ No network address found on this machine.+ </span>+ ) : null}+ {addressChoices.map((choice) => (+ <div+ key={choice.address}+ className="flex items-center gap-2.5"+ >+ <Checkbox+ id={`${addressErrorId}-${choice.address}`}+ checked={addressDraft.includes(choice.address)}+ disabled={addressesReadOnly}+ onCheckedChange={(checked) =>+ toggleAddress(choice.address, checked === true)+ }+ />+ <label+ htmlFor={`${addressErrorId}-${choice.address}`}+ className="flex cursor-pointer flex-wrap items-center gap-x-2.5 text-sm"+ >+ <code className="font-mono text-xs text-foreground">+ {choice.address}+ </code>+ {choice.public ? (+ <span className="text-xs text-destructive">+ Public internet address+ </span>+ ) : null}+ {choice.detected ? null : (+ <span className="text-xs text-muted-foreground">+ Not on this machine right now+ </span>+ )}+ </label>+ </div>+ ))}+ </fieldset>+ ) : null}+ </>+ ) : null}<SettingsRowlabel="Keyless API status"description={keylessLanAccessDescription(status)}@@ -513,7 +670,11 @@ export function LanAccessSection() {><Switchchecked={status?.autoStart ?? false}- disabled={busy !== null || lanAccessAutoStartReadOnly(status)}+ disabled={+ busy !== null ||+ lanAccessAutoStartReadOnly(status) ||+ (addressesDirty && !status?.autoStart)+ }onCheckedChange={setAutoStart}aria-label="Start automatically"/>diff --git a/studio/frontend/tests/lan-access-state.test.ts b/studio/frontend/tests/lan-access-state.test.tsindex 732521d9567..bf162e173c4 100644--- a/studio/frontend/tests/lan-access-state.test.ts+++ b/studio/frontend/tests/lan-access-state.test.ts@@ -8,7 +8,10 @@ import test from "node:test";import {type ApiLanAccessStatus,type LanAccessStatus,+ defaultLanAccessAddressSelection,keylessLanAccessDescription,+ lanAccessAddressChoices,+ lanAccessAddressesReadOnly,lanAccessAutoStartReadOnly,lanAccessBlockMessage,lanAccessErrorMessage,@@ -16,6 +19,7 @@ import {lanAccessStopDisconnectsOrigin,lanApiUrls,normalizeLanAccessStatus,+ sameLanAccessAddresses,validLanAccessPort,} from "../src/features/settings/api/lan-access-state.ts";@@ -24,7 +28,9 @@ import { readSrc } from "./helpers/kit.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 = readSrc("features/settings/components/lan-access-section.tsx");+const SECTION_SOURCE = readSrc(+ "features/settings/components/lan-access-section.tsx",+);function apiStatus(over: Partial<ApiLanAccessStatus> = {}): ApiLanAccessStatus {return {@@ -53,6 +59,13 @@ test("normalize maps every snake_case field onto its camelCase name", () => {configured_port: 43210,active_port: 43210,// biome-ignore lint/style/useNamingConvention: API schema+ configured_addresses: ["100.101.102.103"],+ // biome-ignore lint/style/useNamingConvention: API schema+ available_addresses: [+ { address: "64.227.100.5", public: true },+ { address: "100.101.102.103", public: false },+ ],+ // biome-ignore lint/style/useNamingConvention: API schemamanaged_by: "settings",// biome-ignore lint/style/useNamingConvention: API schemacan_start: false,@@ -80,6 +93,13 @@ test("normalize maps every snake_case field onto its camelCase name", () => {portConfigurationSupported: true,configuredPort: 43210,activePort: 43210,+ addressConfigurationSupported: true,+ configuredAddresses: ["100.101.102.103"],+ availableAddresses: [+ { address: "64.227.100.5", public: true },+ { address: "100.101.102.103", public: false },+ ],+ configuredPublicAddresses: [],managedBy: "settings",canStart: false,canStop: true,@@ -103,6 +123,10 @@ test("normalize defaults the optional fields an older backend may omit", () => {assert.equal(s.activePort, null);assert.equal(s.portConfigurationSupported, false);assert.equal(lanAccessPortReadOnly(s), true);+ assert.equal(s.addressConfigurationSupported, false);+ assert.equal(s.configuredAddresses, null);+ assert.deepEqual(s.availableAddresses, []);+ assert.equal(lanAccessAddressesReadOnly(s), true);assert.equal(s.managedBy, null);assert.equal(s.blockReason, null);assert.equal(s.bindHost, null);@@ -123,10 +147,7 @@ test("an explicit automatic port remains distinct from an old backend", () => {});test("the port form is capability-gated and keeps its live error region mounted", () => {- assert.equal(- SECTION_SOURCE.match(/["'`]Port["'`]/g)?.length,- 1,- );+ assert.equal(SECTION_SOURCE.match(/["'`]Port["'`]/g)?.length, 1);assert.match(SECTION_SOURCE,/\{status\?\.portConfigurationSupported\s*\?\s*\(\s*<SettingsRow\s+label="Port"/,@@ -289,6 +310,140 @@ test("port editing is limited to stopped, non-Colab LAN access", () => {);});+const TAILSCALE = "100.101.102.103";+const WIFI = "192.168.1.24";+const PUBLIC_IP = "64.227.100.5";++function withAddresses(+ configured: string[] | null,+ over: Partial<ApiLanAccessStatus> = {},+): LanAccessStatus {+ return normalizeLanAccessStatus(+ apiStatus({+ // biome-ignore lint/style/useNamingConvention: API schema+ configured_addresses: configured,+ // biome-ignore lint/style/useNamingConvention: API schema+ available_addresses: [+ { address: PUBLIC_IP, public: true },+ { address: WIFI, public: false },+ { address: TAILSCALE, public: false },+ ],+ ...over,+ }),+ );+}++test("an explicit automatic selection remains distinct from an old backend", () => {+ const s = withAddresses(null);+ assert.equal(s.addressConfigurationSupported, true);+ assert.equal(s.configuredAddresses, null);+ assert.equal(lanAccessAddressesReadOnly(s), false);+});++test("address editing is limited to stopped, non-Colab LAN access", () => {+ assert.equal(lanAccessAddressesReadOnly(null), true);+ assert.equal(+ lanAccessAddressesReadOnly(withAddresses(null, { state: "online" })),+ true,+ );+ assert.equal(+ lanAccessAddressesReadOnly(withAddresses(null, { block_reason: "colab" })),+ true,+ );+});++test("malformed address entries are dropped instead of rendered", () => {+ const s = normalizeLanAccessStatus(+ apiStatus({+ // biome-ignore lint/style/useNamingConvention: API schema+ configured_addresses: [WIFI, 7 as unknown as string],+ // biome-ignore lint/style/useNamingConvention: API schema+ available_addresses: [+ { address: WIFI, public: false },+ null as unknown as { address: string; public: boolean },+ { address: PUBLIC_IP, public: "yes" as unknown as boolean },+ ],+ }),+ );+ assert.deepEqual(s.configuredAddresses, [WIFI]);+ assert.deepEqual(s.availableAddresses, [+ { address: WIFI, public: false },+ { address: PUBLIC_IP, public: false },+ ]);+});++test("Choose starts from the private addresses, never a public one", () => {+ assert.deepEqual(defaultLanAccessAddressSelection(withAddresses(null)), [+ WIFI,+ TAILSCALE,+ ]);+ assert.deepEqual(defaultLanAccessAddressSelection(null), []);+});++test("a saved address that is not up right now is still offered", () => {+ const s = withAddresses(["10.9.9.9", TAILSCALE]);+ assert.deepEqual(lanAccessAddressChoices(s, [TAILSCALE]), [+ { address: PUBLIC_IP, public: true, detected: true },+ { address: WIFI, public: false, detected: true },+ { address: TAILSCALE, public: false, detected: true },+ { address: "10.9.9.9", public: false, detected: false },+ ]);+});++test("a launch-managed status never reports saved addresses as down", () => {+ const s = withAddresses([WIFI], {+ // biome-ignore lint/style/useNamingConvention: API schema+ managed_by: "launch",+ // biome-ignore lint/style/useNamingConvention: API schema+ available_addresses: [],+ });+ assert.deepEqual(lanAccessAddressChoices(s, [WIFI]), [+ { address: WIFI, public: false, detected: true },+ ]);+});++test("a saved public address that is down keeps its public warning", () => {+ const s = withAddresses(["203.0.114.7"], {+ // biome-ignore lint/style/useNamingConvention: API schema+ configured_public_addresses: ["203.0.114.7"],+ });+ assert.deepEqual(lanAccessAddressChoices(s, []).at(-1), {+ address: "203.0.114.7",+ public: true,+ detected: false,+ });+ assert.deepEqual(withAddresses(null).configuredPublicAddresses, []);+});++test("address selections compare as sets, with Automatic distinct from any list", () => {+ assert.equal(sameLanAccessAddresses(null, null), true);+ assert.equal(+ sameLanAccessAddresses([WIFI, TAILSCALE], [TAILSCALE, WIFI]),+ true,+ );+ assert.equal(sameLanAccessAddresses([WIFI], [WIFI, TAILSCALE]), false);+ assert.equal(sameLanAccessAddresses(null, [WIFI]), false);+ assert.equal(sameLanAccessAddresses([], null), false);+});++test("an unavailable selection explains itself", () => {+ assert.match(+ lanAccessErrorMessage("selected_address_unavailable") ?? "",+ /None of the chosen addresses/,+ );+});++test("the address form is capability-gated and keeps its live error region mounted", () => {+ assert.match(+ SECTION_SOURCE,+ /\{status\?\.addressConfigurationSupported\s*\?\s*\(\s*<>\s*<SettingsRow\s+label="Addresses"/,+ );+ assert.match(+ SECTION_SOURCE,+ /below=\{\s*<span\s+id=\{addressErrorId\}\s+role="status"\s+aria-live="polite"/,+ );+});+test("custom LAN ports accept only whole ports in range", () => {for (const value of ["1", "8888", "43210", "65535"]) {assert.equal(validLanAccessPort(value), true, value);@@ -463,7 +618,6 @@ 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);