Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix(studio): support explicitly selected virtual bridge LAN addresses (#17165)
Alan Huangfa3e02290bd2
diff --git a/studio/backend/lan_access.py b/studio/backend/lan_access.pyindex 6f23b489b4f..1748541e545 100644--- a/studio/backend/lan_access.py+++ b/studio/backend/lan_access.py@@ -71,30 +71,13 @@ def detect_lan_addresses(ip_version: int = 4) -> list[str]:else:raise ValueError("ip_version must be 4 or 6")- addresses: list[str] = []-- def _add(candidate: str) -> None:- candidate = candidate.split("%", 1)[0]- try:- parsed = ipaddress.ip_address(candidate)- except ValueError:- return- if parsed.version != ip_version:- return- if parsed.is_loopback or parsed.is_link_local or parsed.is_multicast:- return- if parsed.is_unspecified or parsed.is_reserved:- return- normalized = str(parsed)- if normalized not in addresses:- addresses.append(normalized)-+ found: list[str] = []# a UDP connect only fixes the local end of the socket; nothing is sent to the targetprobe = Nonetry:probe = socket.socket(socket_family, socket.SOCK_DGRAM)probe.connect(route_probe)- _add(probe.getsockname()[0])+ found.append(probe.getsockname()[0])except OSError:passfinally:@@ -102,8 +85,37 @@ def detect_lan_addresses(ip_version: int = 4) -> list[str]:probe.close()# Route probes and hostname lookup miss other adapters; an isolated LAN has no route at all.- for address in _interface_addresses(ip_version):- _add(address)+ found.extend(_interface_addresses(ip_version))+ return _usable_addresses(found, ip_version)+++def detect_host_only_addresses(ip_version: int = 4, carrier: bool = True) -> list[str]:+ """Addresses on virtual switches (libvirt, Docker, ...) that detection skips: offered for an explicit+ choice, e.g. serving VMs on virbr0 (#17017), never bound by Automatic. ``carrier=False`` adds+ bridges no guest is attached to yet, whose assigned address still binds."""+ if _wsl_networking_mode() not in (None, "mirrored"):+ return []+ return _usable_addresses(+ _interface_addresses(ip_version, host_only = True, carrier = carrier), ip_version+ )+++def _usable_addresses(found, ip_version: int) -> list[str]:+ addresses: list[str] = []+ for candidate in found:+ try:+ parsed = ipaddress.ip_address(candidate.split("%", 1)[0])+ except ValueError:+ continue+ if parsed.version != ip_version:+ continue+ if parsed.is_loopback or parsed.is_link_local or parsed.is_multicast:+ continue+ if parsed.is_unspecified or parsed.is_reserved:+ continue+ normalized = str(parsed)+ if normalized not in addresses:+ addresses.append(normalized)return addresses@@ -152,11 +164,18 @@ def _is_host_only_interface(name: str) -> bool:)-def _interface_addresses(ip_version: int = 4) -> list[str]:- """Without psutil, hostname lookup is a last resort: it misses hosts whose name maps to 127.0.1.1."""+def _interface_addresses(+ ip_version: int = 4,+ host_only: bool = False,+ carrier: bool = True,+) -> list[str]:+ """Up interfaces, or every virtual switch when ``host_only``. Without psutil, hostname lookup is a+ last resort: it misses hosts whose name maps to 127.0.1.1."""try:import psutilexcept ImportError:+ if host_only:+ return []try:return [info[4][0]@@ -173,10 +192,10 @@ def _interface_addresses(ip_version: int = 4) -> list[str]:family = socket.AF_INET if ip_version == 4 else socket.AF_INET6addresses = []for name, entries in psutil.net_if_addrs().items():- if _is_host_only_interface(name):+ if _is_host_only_interface(name) != host_only:continueinterface = stats.get(name)- if interface is not None and not interface.isup:+ if carrier and interface is not None and not interface.isup:continueaddresses.extend(e.address for e in entries if e.family == family)return addresses@@ -278,6 +297,11 @@ def start_lan_listener(return _bound_addressescandidates = detect_lan_addresses()+ if selected_addresses is not None:+ # a saved virbr0 must bind at launch, before any VM has started+ candidates += [+ a for a in detect_host_only_addresses(carrier = False) if a not in candidates+ ]if not candidates:_error = "no_lan_address"raise RuntimeError(_error)diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex c7e9f369e54..3ae30a5b9a1 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -4445,6 +4445,7 @@ class LanAccessAddressesPayload(BaseModel):class LanAccessAddress(BaseModel):address: strpublic: bool = False+ host_only: bool = Falseclass LanAccessResponse(BaseModel):diff --git a/studio/backend/tests/test_lan_access_settings.py b/studio/backend/tests/test_lan_access_settings.pyindex 7482148d7c4..7fd477d62a4 100644--- a/studio/backend/tests/test_lan_access_settings.py+++ b/studio/backend/tests/test_lan_access_settings.py@@ -256,16 +256,26 @@ def test_saving_a_selection_clears_the_previous_error_and_refuses_while_online()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))+ monkeypatch.setattr(+ lan_access,+ "detect_host_only_addresses",+ lambda _ip_version = 4: ["192.168.122.1", "192.168.1.24"],+ )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},+ {"address": "64.227.100.5", "public": True, "host_only": False},+ {"address": "192.168.1.24", "public": False, "host_only": False},+ {"address": "100.101.102.103", "public": False, "host_only": False},+ {"address": "192.168.122.1", "public": False, "host_only": True},]assert status["configured_addresses"] is Noneresponse = routes.LanAccessResponse(**status)- assert [entry.address for entry in response.available_addresses] == _DETECTED+ assert [entry.address for entry in response.available_addresses] == [+ *_DETECTED,+ "192.168.122.1",+ ]assert response.available_addresses[0].public is True+ assert response.available_addresses[-1].host_only is Trueassert (lan_settings.lan_access_status(_app(lan_access_launch_managed = True))["available_addresses"]== []diff --git a/studio/backend/tests/test_lan_bridge_selection.py b/studio/backend/tests/test_lan_bridge_selection.pynew file mode 100644index 00000000000..1dc912e35ea--- /dev/null+++ b/studio/backend/tests/test_lan_bridge_selection.py@@ -0,0 +1,92 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A virtual switch address (libvirt virbr0) can be chosen explicitly but is never bound by Automatic (#17017)."""++import socket+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++_BACKEND = Path(__file__).resolve().parents[1]+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++import lan_access # noqa: E402++_BRIDGE = "192.168.122.1"+_NIC = "192.168.1.24"+++def interfaces(monkeypatch):+ psutil = pytest.importorskip("psutil")+ up = {"eth0": True, "virbr0": True, "virbr1": False}+ addrs = {+ "eth0": [SimpleNamespace(family = socket.AF_INET, address = _NIC)],+ "virbr0": [SimpleNamespace(family = socket.AF_INET, address = _BRIDGE)],+ "virbr1": [SimpleNamespace(family = socket.AF_INET, address = "192.168.100.1")],+ }+ monkeypatch.setattr(psutil, "net_if_addrs", lambda: addrs)+ monkeypatch.setattr(+ psutil, "net_if_stats", lambda: {n: SimpleNamespace(isup = v) for n, v in up.items()}+ )+ monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: None)+ return up+++def binds(monkeypatch):+ attempted = []++ def _bind(address, port):+ attempted.append(address)+ raise OSError("not binding in a unit test")++ monkeypatch.setattr(lan_access, "_bind_listener", _bind)+ return attempted+++def _start(selected):+ with pytest.raises(RuntimeError) as exc:+ lan_access.start_lan_listener(object(), object(), 8888, (), selected)+ return str(exc.value)+++def test_bridge_is_host_only_and_not_detected(interfaces):+ assert _BRIDGE not in lan_access.detect_lan_addresses()+ assert lan_access.detect_host_only_addresses() == [_BRIDGE]+++def test_a_chosen_bridge_address_is_bound(interfaces, binds):+ assert _start((_BRIDGE,)) == "bind_failed"+ assert binds == [_BRIDGE]+++def test_automatic_never_binds_the_bridge(interfaces, binds):+ _start(None)+ assert _NIC in binds and _BRIDGE not in binds+++def test_a_saved_bridge_without_a_guest_yet_still_binds(interfaces, binds):+ assert "192.168.100.1" not in lan_access.detect_host_only_addresses()+ assert _start(("192.168.100.1",)) == "bind_failed"+ assert binds == ["192.168.100.1"]+++def test_a_chosen_address_on_no_interface_is_unavailable(interfaces, binds):+ assert _start(("192.168.200.1",)) == "selected_address_unavailable"+ assert binds == []+++def test_wsl_nat_offers_no_bridge(interfaces, monkeypatch):+ monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: "nat")+ assert lan_access.detect_host_only_addresses() == []+++def test_no_psutil_offers_no_bridge(monkeypatch):+ monkeypatch.setitem(sys.modules, "psutil", None)+ monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: None)+ assert lan_access.detect_host_only_addresses() == []diff --git a/studio/backend/utils/lan_access_settings.py b/studio/backend/utils/lan_access_settings.pyindex 1d704472353..dbe00f232c8 100644--- a/studio/backend/utils/lan_access_settings.py+++ b/studio/backend/utils/lan_access_settings.py@@ -325,12 +325,20 @@ def save_lan_access_addresses(app, addresses: Any) -> dict:def _available_lan_addresses() -> list[dict]:- """Detected addresses with a public flag; a detection failure offers nothing rather than failing status."""+ """Detected addresses, then virtual switch ones flagged ``host_only``; a detection failure offers nothing+ rather than failing status."""try:- from lan_access import detect_lan_addresses, is_public_address+ from lan_access import detect_host_only_addresses, detect_lan_addresses, is_public_address++ detected = detect_lan_addresses()+ host_only = [address for address in detect_host_only_addresses() if address not in detected]return [- {"address": address, "public": is_public_address(address)}- for address in detect_lan_addresses()+ {+ "address": address,+ "public": is_public_address(address),+ "host_only": address in host_only,+ }+ for address in (*detected, *host_only)]except Exception:return []diff --git a/studio/frontend/src/features/settings/api/lan-access-state.ts b/studio/frontend/src/features/settings/api/lan-access-state.tsindex 70af0b12bc4..b89268db459 100644--- a/studio/frontend/src/features/settings/api/lan-access-state.ts+++ b/studio/frontend/src/features/settings/api/lan-access-state.ts@@ -4,7 +4,17 @@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 LanAccessAddress = {+ address: string;+ public: boolean;+ hostOnly?: boolean;+};+type ApiLanAccessAddress = {+ address: string;+ public: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ host_only?: boolean;+};export type LanAccessAddressChoice = LanAccessAddress & { detected: boolean };export type LanAccessStatus = {@@ -50,7 +60,7 @@ export type ApiLanAccessStatus = {// biome-ignore lint/style/useNamingConvention: API schemaconfigured_addresses?: string[] | null;// biome-ignore lint/style/useNamingConvention: API schema- available_addresses?: LanAccessAddress[] | null;+ available_addresses?: ApiLanAccessAddress[] | null;// biome-ignore lint/style/useNamingConvention: API schemaconfigured_public_addresses?: string[] | null;// biome-ignore lint/style/useNamingConvention: API schema@@ -81,7 +91,13 @@ function normalizeAddresses(value: unknown): LanAccessAddress[] {}return value.flatMap((entry) =>entry && typeof entry.address === "string"- ? [{ address: entry.address, public: entry.public === true }]+ ? [+ {+ address: entry.address,+ public: entry.public === true,+ ...(entry.host_only === true ? { hostOnly: true } : {}),+ },+ ]: [],);}@@ -241,7 +257,7 @@ export function defaultLanAccessAddressSelection(status: LanAccessStatus | null,): string[] {return (status?.availableAddresses ?? [])- .filter((entry) => !entry.public)+ .filter((entry) => !(entry.public || entry.hostOnly)).map((entry) => entry.address);}diff --git a/studio/frontend/src/features/settings/components/lan-access-section.tsx b/studio/frontend/src/features/settings/components/lan-access-section.tsxindex c594e9b0efe..68787bb6899 100644--- a/studio/frontend/src/features/settings/components/lan-access-section.tsx+++ b/studio/frontend/src/features/settings/components/lan-access-section.tsx@@ -642,6 +642,11 @@ export function LanAccessSection() {Public internet address</span>) : null}+ {choice.hostOnly ? (+ <span className="text-xs text-muted-foreground">+ Virtual network on this machine+ </span>+ ) : null}{choice.detected ? null : (<span className="text-xs text-muted-foreground">Not on this machine right nowdiff --git a/studio/frontend/tests/lan-access-state.test.ts b/studio/frontend/tests/lan-access-state.test.tsindex f44f511b2b3..b4ce2d48ef2 100644--- a/studio/frontend/tests/lan-access-state.test.ts+++ b/studio/frontend/tests/lan-access-state.test.ts@@ -376,6 +376,24 @@ test("Choose starts from the private addresses, never a public one", () => {assert.deepEqual(defaultLanAccessAddressSelection(null), []);});+test("a virtual switch address is offered flagged but never pre-ticked", () => {+ const s = withAddresses(null, {+ // biome-ignore lint/style/useNamingConvention: API schema+ available_addresses: [+ { address: WIFI, public: false },+ // biome-ignore lint/style/useNamingConvention: API schema+ { address: "192.168.122.1", public: false, host_only: true },+ ],+ });+ assert.deepEqual(lanAccessAddressChoices(s, []).at(-1), {+ address: "192.168.122.1",+ public: false,+ hostOnly: true,+ detected: true,+ });+ assert.deepEqual(defaultLanAccessAddressSelection(s), [WIFI]);+});+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]), [