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.

Studio settings: fix API, Connections, Remote access and LAN issues (#14596)

Michael Hana29487c52238
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index ad7e28b15ae..346672af9f1 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -7673,8 +7673,17 @@ class ExternalProviderClient:
async def _models_payload(self, timeout: Any) -> tuple[Any, list[dict[str, Any]]]:
response = await _client().get(
f"{self.base_url}/models",
- # Anthropic pages 20 models by default; 1000 is its documented maximum.
- params = {"limit": 1000} if self.provider_type == "anthropic" else None,
+ # Anthropic pages 20 models and native Gemini 50 by default; both cap a page at 1000. A Gemini
+ # connection through a proxy gets no native parameter it may reject.
+ params = (
+ {"limit": 1000}
+ if self.provider_type == "anthropic"
+ else {"pageSize": 1000}
+ if self.provider_type == "gemini"
+ and (urlparse(self.base_url).hostname or "").lower()
+ == "generativelanguage.googleapis.com"
+ else None
+ ),
headers = self._auth_headers(),
timeout = timeout,
)
diff --git a/studio/backend/lan_access.py b/studio/backend/lan_access.py
index 37e501a26bb..fe72ffea461 100644
--- a/studio/backend/lan_access.py
+++ b/studio/backend/lan_access.py
@@ -21,8 +21,10 @@ from __future__ import annotations
import asyncio
import functools
+import errno
import ipaddress
import platform
+import re
import socket
import subprocess
import sys
@@ -156,8 +158,13 @@ def _wsl_networking_mode() -> Optional[str]:
def _is_host_only_interface(name: str) -> bool:
- """True for Windows Hyper-V switches that do not face the physical LAN."""
+ """True for virtual switches (Hyper-V, Docker, libvirt, VirtualBox, VMware) that do not face the physical LAN."""
normalized = name.strip().casefold()
+ # br-<12 hex> is a Docker network; a plain br0 is often the host's real LAN bridge, so it stays.
+ if normalized.startswith(("docker0", "virbr", "vboxnet", "vmnet")) or re.fullmatch(
+ r"br-[0-9a-f]{12}", normalized
+ ):
+ return True
if not normalized.startswith("vethernet ("):
return False
return any(
@@ -212,8 +219,19 @@ def is_public_address(address: str) -> bool:
return False
+def _already_served(address: str, port: int) -> bool:
+ try:
+ with socket.create_connection((address, port), timeout = 0.2):
+ return True
+ except OSError:
+ return False
+
+
def _bind_listener(address: str, port: int) -> socket.socket:
"""A listening socket on exactly ``address:port``."""
+ if sys.platform == "darwin" and _already_served(address, port):
+ # BSD SO_REUSEADDR binds under another app's 0.0.0.0 listener and steals its LAN traffic.
+ raise OSError(errno.EADDRINUSE, f"{address}:{port} is already served")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# skipped on Windows, where SO_REUSEADDR lets a socket take over a live listener
diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.py
index 5f32f469e54..a08596496be 100644
--- a/studio/backend/loggers/handlers.py
+++ b/studio/backend/loggers/handlers.py
@@ -95,6 +95,8 @@ _DEDUP_MAP_MAX = 4096
_NATIVE_PATH_LEASE_RE = re.compile(
r"(?i)(\b(?:native_path_lease|nativePathLease)[\"']?\s*[:=]\s*[\"']?)[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"
)
+# Scheme capped at 32 chars: unbounded, every log string is scanned quadratically ("a." * 50000 took seconds).
+_URL_CREDENTIAL_RE = re.compile(r"(?i)\b([a-z][a-z0-9+.-]{0,31}://)[^/\s@'\"]+@")
_EXCLUDED_PATHS = {
"/api/train/status",
"/api/train/metrics",
@@ -366,7 +368,7 @@ def filter_sensitive_data(logger, method_name, event_dict):
except Exception:
pass
value = _NATIVE_PATH_LEASE_RE.sub(r"\1<redacted native path lease>", value)
- return value
+ return _URL_CREDENTIAL_RE.sub(r"\1<redacted>@", value) if "://" in value else value
elif isinstance(value, dict):
return {
k: "<redacted native path lease>"
@@ -376,6 +378,10 @@ def filter_sensitive_data(logger, method_name, event_dict):
}
elif isinstance(value, list):
return [filter_value(item) for item in value]
+ elif type(value) is tuple:
+ return tuple(filter_value(item) for item in value)
+ elif isinstance(value, BaseException) and _URL_CREDENTIAL_RE.search(str(value)):
+ return filter_value(str(value))
return value
return {
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 89fa48efaf1..9da8ebb23ce 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -4070,6 +4070,7 @@ class KeylessApiAccessResponse(BaseModel):
scope: Literal["off", "inference", "full"]
tools: bool
exposure: Optional[Literal["colab", "public_url", "private_lan", "network"]] = None
+ suspended_by_accounts: bool = False
class McpAccessPayload(BaseModel):
@@ -4532,6 +4533,7 @@ def _keyless_api_access_response(request: Request) -> KeylessApiAccessResponse:
scope = scope,
tools = tools,
exposure = access_exposure(request.app.state),
+ suspended_by_accounts = policy.installation_has_managed_accounts(),
)
diff --git a/studio/backend/tests/test_keyless_api_access.py b/studio/backend/tests/test_keyless_api_access.py
index 9fd6abb7d2b..ad4a3b6e85e 100644
--- a/studio/backend/tests/test_keyless_api_access.py
+++ b/studio/backend/tests/test_keyless_api_access.py
@@ -1200,4 +1200,18 @@ def test_the_keyless_load_probe_waits_out_a_settings_refresh(monkeypatch):
finally:
refresher.join()
assert held_back is False
+
+
+def test_settings_report_keyless_suspended_while_a_managed_account_exists(monkeypatch):
+ from auth import policy
+ from routes import settings as settings_routes
+
+ seed_user()
+ set_keyless_api_access("inference")
+ request = SimpleNamespace(app = SimpleNamespace(state = app_state()))
+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: False)
+ assert settings_routes._keyless_api_access_response(request).suspended_by_accounts is False
+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)
+ response = settings_routes._keyless_api_access_response(request)
+ assert (response.scope, response.suspended_by_accounts) == ("inference", True)
# fmt: on
diff --git a/studio/backend/tests/test_lan_access_settings.py b/studio/backend/tests/test_lan_access_settings.py
index 06ab99316f5..0216b19d98e 100644
--- a/studio/backend/tests/test_lan_access_settings.py
+++ b/studio/backend/tests/test_lan_access_settings.py
@@ -28,6 +28,7 @@ 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
+import utils.paths.file_manager as file_manager # noqa: E402
from storage import studio_db # noqa: E402
# captured before the autouse fixture swaps in the dict stand-in
@@ -702,6 +703,7 @@ def test_a_wildcard_launch_refreshes_lan_addresses_instead_of_showing_the_public
):
"""The status refreshes every LAN address instead of relying on server_url's
single direct base, and never leaks an obsolete public-address value."""
+ monkeypatch.setattr(file_manager, "_in_container", lambda: False)
monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda _ip_version = 4: ["192.168.1.24"])
state = _app(
lan_access_launch_managed = True,
@@ -716,6 +718,78 @@ def test_a_wildcard_launch_refreshes_lan_addresses_instead_of_showing_the_public
assert lan_settings.lan_access_status(state)["urls"] == ["http://10.0.0.7:8888"]
+def test_a_wildcard_launch_in_a_container_advertises_no_bridge_address(monkeypatch):
+ monkeypatch.setattr(file_manager, "_in_container", lambda: True)
+ monkeypatch.setattr(lan_settings, "_veth_addresses", lambda: {"172.17.0.2"})
+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda _ip_version = 4: ["172.17.0.2"])
+ state = _app(lan_access_launch_managed = True, lan_access_wildcard_bind = True)
+ assert lan_settings.lan_access_status(state)["urls"] == []
+
+ # --network host sees the host's own NICs, no veth, even on a 172.16/12 office LAN.
+ monkeypatch.setattr(lan_settings, "_veth_addresses", lambda: set())
+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda _ip_version = 4: ["172.20.1.5"])
+ assert lan_settings.lan_access_status(state)["urls"] == ["http://172.20.1.5:8888"]
+
+
+def test_veth_addresses_reads_the_peer_link_from_sysfs(monkeypatch, tmp_path):
+ entry = lambda address: SimpleNamespace(address = address)
+ monkeypatch.setitem(
+ sys.modules,
+ "psutil",
+ SimpleNamespace(
+ net_if_addrs = lambda: {
+ "eth0": [entry("172.17.0.2")],
+ "enp3s0": [entry("172.20.1.5")],
+ "enp3s0.100": [entry("172.21.0.5")],
+ }
+ ),
+ )
+ # eth0's peer (index 12) is the host-side veth, outside this namespace; a NIC and its VLAN link to index 2.
+ for name, (iflink, ifindex) in {
+ "eth0": ("12", "11"),
+ "enp3s0": ("2", "2"),
+ "enp3s0.100": ("2", "3"),
+ }.items():
+ (tmp_path / name).mkdir()
+ (tmp_path / name / "iflink").write_text(iflink + "\n")
+ (tmp_path / name / "ifindex").write_text(ifindex + "\n")
+ assert lan_settings._veth_addresses(str(tmp_path)) == {"172.17.0.2"}
+
+
+def test_lan_status_reports_keyless_off_while_a_managed_account_exists(monkeypatch):
+ import auth.policy as policy
+ import utils.keyless_api_access as keyless
+
+ monkeypatch.setattr(keyless, "get_keyless_api_access_settings", lambda: ("inference", True))
+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)
+ status = lan_settings.lan_access_status(_app())
+ assert (status["keyless_scope"], status["keyless_tools"]) == ("off", False)
+
+
+ ("name", "host_only"),
+ [
+ ("docker0", True),
+ ("br-0123456789ab", True),
+ ("virbr0", True),
+ ("vboxnet0", True),
+ ("vmnet8", True),
+ ("br0", False),
+ ("en0", False),
+ ("eth0", False),
+ ],
+)
+def test_virtual_switches_are_not_offered_as_lan_addresses(name, host_only):
+ assert lan_access._is_host_only_interface(name) is host_only
+
+
[email protected](sys.platform != "darwin", reason = "BSD SO_REUSEADDR semantics")
+def test_lan_bind_does_not_take_a_port_another_app_serves(monkeypatch):
+ monkeypatch.setattr(lan_access, "_already_served", lambda address, port: True)
+ with pytest.raises(OSError):
+ lan_access._bind_listener("127.0.0.1", 0)
+
+
def test_listener_urls_bracket_ipv6_literals():
assert lan_settings._listener_urls(["192.168.1.24", "fd00::24"], 8888) == [
"http://192.168.1.24:8888",
diff --git a/studio/backend/tests/test_log_filter_no_truncation.py b/studio/backend/tests/test_log_filter_no_truncation.py
index a3fa469cd7b..3e6e286ab75 100644
--- a/studio/backend/tests/test_log_filter_no_truncation.py
+++ b/studio/backend/tests/test_log_filter_no_truncation.py
@@ -81,3 +81,23 @@ class TestNativePathLeaseRedactionStillWorks:
def test_nested_native_path_lease_key_redacted(self):
out = _run({"event": "load", "payload": {"nativePathLease": "AAAAAA.BBBBBB"}})
assert out["payload"]["nativePathLease"] == "<redacted native path lease>"
+
+ def test_url_credentials_redacted_in_strings_args_and_exceptions(self):
+ url = "http://bob:[email protected]:9/v1/models"
+ out = _run(
+ {
+ "event": f"Failed to list models: {url}",
+ "positional_args": ("custom", url),
+ "exc": ValueError(f"Client error for url '{url}'"),
+ }
+ )
+ assert "hunter2" not in repr(out)
+ assert "http://<redacted>@127.0.0.1:9/v1/models" in out["event"]
+
+ def test_url_credential_scan_stays_linear_on_long_unbroken_text(self):
+ import time
+
+ start = time.perf_counter()
+ out = _run({"event": "a." * 50000 + " s3://key:secret@bucket/k"})
+ assert time.perf_counter() - start < 1.0
+ assert out["event"].endswith(" s3://<redacted>@bucket/k")
diff --git a/studio/backend/tests/test_provider_connection_checks.py b/studio/backend/tests/test_provider_connection_checks.py
index 4a5cf5d0a93..2f44edad29f 100644
--- a/studio/backend/tests/test_provider_connection_checks.py
+++ b/studio/backend/tests/test_provider_connection_checks.py
@@ -97,6 +97,17 @@ def test_anthropic_lists_past_the_default_page(mock_http):
assert "limit" not in mock_http[-1].url.params
+def test_gemini_lists_past_the_default_page(mock_http):
+ base = "https://generativelanguage.googleapis.com/v1beta"
+ _run(ExternalProviderClient("gemini", base, "AIza").list_models())
+ assert mock_http[-1].url.params["pageSize"] == "1000"
+
+
+def test_gemini_through_a_proxy_gets_no_native_page_size(mock_http):
+ _run(ExternalProviderClient("gemini", "https://litellm.example/v1", "sk").list_models())
+ assert "pageSize" not in mock_http[-1].url.params
+
+
@pytest.mark.parametrize(
"status,expected",
[
diff --git a/studio/backend/utils/lan_access_settings.py b/studio/backend/utils/lan_access_settings.py
index 36d523445fd..bc02b214c25 100644
--- a/studio/backend/utils/lan_access_settings.py
+++ b/studio/backend/utils/lan_access_settings.py
@@ -6,6 +6,7 @@
from __future__ import annotations
import ipaddress
+import os
import socket
import threading
@@ -389,16 +390,59 @@ def configure_lan_access(
app_state.lan_access_ready = False
+_CONTAINER_NETWORKS = (ipaddress.ip_network("172.16.0.0/12"), ipaddress.ip_network("10.88.0.0/16"))
+
+
+def _container_network_address(address: str) -> bool:
+ try:
+ ip = ipaddress.ip_address(address)
+ except ValueError:
+ return False
+ return any(ip in network for network in _CONTAINER_NETWORKS if ip.version == network.version)
+
+
+def _veth_addresses(sysfs: str = "/sys/class/net") -> set[str]:
+ """Addresses on a link whose peer (iflink) is outside this namespace: a bridged container's veth. A NIC or VLAN
+ links to an index visible here, so host networking keeps a 172.16/12 LAN (kernel ABI sysfs-class-net)."""
+
+ def read(name: str, attr: str) -> str:
+ with open(f"{sysfs}/{name}/{attr}") as handle:
+ return handle.read().strip()
+
+ try:
+ import psutil
+ interfaces = psutil.net_if_addrs()
+ indexes = {read(name, "ifindex") for name in os.listdir(sysfs)}
+ except Exception:
+ return set()
+ addresses = set()
+ for name, entries in interfaces.items():
+ try:
+ if read(name, "iflink") in indexes:
+ continue
+ except OSError:
+ continue
+ addresses.update(entry.address.split("%", 1)[0] for entry in entries)
+ return addresses
+
+
def _launch_urls(app_state) -> list[str]:
"""Where a launch-managed bind answers on this network. A wildcard launch cannot rely only on ``server_url``: run.py gives that direct base one LAN-reachable address, while Settings must show every currently reachable address in each family the launch serves."""
if getattr(app_state, "lan_access_wildcard_bind", False):
from lan_access import detect_lan_addresses
+ from utils.paths.file_manager import _in_container
addresses = []
for ip_version in getattr(app_state, "lan_access_wildcard_ip_versions", ()) or (4,):
for address in detect_lan_addresses(ip_version):
if address not in addresses:
addresses.append(address)
+ if _in_container():
+ # A bridged container's own IP reaches nothing outside it; host networking's addresses stay.
+ bridged = _veth_addresses()
+ addresses = [
+ a for a in addresses if not (a in bridged and _container_network_address(a))
+ ]
return _listener_urls(
addresses,
getattr(app_state, "lan_access_port", None),
@@ -528,7 +572,13 @@ def lan_access_status(app) -> dict:
controllable = block_reason is None
try:
from utils.keyless_api_access import get_keyless_api_access_settings
+
keyless_scope, keyless_tools = get_keyless_api_access_settings()
+ from auth.policy import installation_has_managed_accounts
+
+ # Effective, not saved: one managed account turns keyless admission off install-wide.
+ if installation_has_managed_accounts():
+ keyless_scope, keyless_tools = "off", False
except Exception:
keyless_scope, keyless_tools = "off", False
return {
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 524c70486cc..3e75b03b1c2 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -379,8 +379,10 @@ export const BUDGET = {
// merged at c2f75c4, Node 24, 98 chunks). Raised by that, on top of the above.
// #14592 + #14601 (system polling, floating panels) merged with main at 0c001fceb: 6,907,598 B raw /
// 2,080,708 B transfer (Node 26, 98 chunks). Raised to that plus about 200 B.
- transferBytes: 2_080_908,
- rawBytes: 6_907_798,
+ // Settings API / Remote / LAN strings (#14596) merged with main at 870f37741: 6,907,886 B raw / 2,080,818 B
+ // transfer (Node 26, 98 chunks). Raised to that plus about 200 B.
+ transferBytes: 2_081_018,
+ rawBytes: 6_908_086,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/features/settings/api/api-keys.ts b/studio/frontend/src/features/settings/api/api-keys.ts
index 5bf3f2825b9..ce3746fcbe7 100644
--- a/studio/frontend/src/features/settings/api/api-keys.ts
+++ b/studio/frontend/src/features/settings/api/api-keys.ts
@@ -13,6 +13,20 @@ export interface ApiKey {
is_active: boolean;
}
+/** a refused create or revoke, carrying the server's own reason when it gave one */
+export class ApiKeyActionError extends Error {}
+
+async function actionError(res: Response): Promise<ApiKeyActionError> {
+ try {
+ const body = (await res.json()) as { detail?: unknown };
+ return new ApiKeyActionError(
+ typeof body.detail === "string" ? body.detail : "",
+ );
+ } catch {
+ return new ApiKeyActionError("");
+ }
+}
+
export async function fetchApiKeys(): Promise<ApiKey[]> {
const res = await authFetch("/api/auth/api-keys");
if (!res.ok) throw new Error("Failed to load API access");
@@ -29,7 +43,7 @@ export async function createApiKey(
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, expires_in_days: expiresInDays }),
});
- if (!res.ok) throw new Error("Failed to create access token");
+ if (!res.ok) throw await actionError(res);
return res.json();
}
@@ -37,5 +51,5 @@ export async function revokeApiKey(keyId: number): Promise<void> {
const res = await authFetch(`/api/auth/api-keys/${keyId}`, {
method: "DELETE",
});
- if (!res.ok) throw new Error("Failed to revoke access token");
+ if (!res.ok) throw await actionError(res);
}
diff --git a/studio/frontend/src/features/settings/api/keyless-api-access.ts b/studio/frontend/src/features/settings/api/keyless-api-access.ts
index a7d43867ffd..6ddb23f50f8 100644
--- a/studio/frontend/src/features/settings/api/keyless-api-access.ts
+++ b/studio/frontend/src/features/settings/api/keyless-api-access.ts
@@ -15,12 +15,16 @@ export type KeylessApiAccessSettings = {
scope: KeylessApiAccessScope;
tools: boolean;
exposure: KeylessApiAccessExposure | null;
+ /** a managed account turns keyless off install-wide, whatever scope is saved */
+ suspendedByAccounts: boolean;
};
type ApiKeylessApiAccessSettings = {
scope: KeylessApiAccessScope;
tools: boolean;
exposure?: KeylessApiAccessExposure | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ suspended_by_accounts?: boolean | null;
};
function fromApi(
@@ -30,6 +34,7 @@ function fromApi(
scope: settings.scope,
tools: settings.tools,
exposure: settings.exposure ?? null,
+ suspendedByAccounts: settings.suspended_by_accounts === true,
};
}
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 847afea3198..57a7d762048 100644
--- a/studio/frontend/src/features/settings/api/lan-access-state.ts
+++ b/studio/frontend/src/features/settings/api/lan-access-state.ts
@@ -142,6 +142,26 @@ export function lanApiUrls(status: LanAccessStatus): string[] {
return status.managedBy === "settings" ? status.urls : [];
}
+// A listener keeps the address it bound after Wi-Fi changes or DHCP renews, while detection is fresh.
+export function staleLanUrls(status: LanAccessStatus): string[] {
+ if (
+ status.managedBy !== "settings" ||
+ status.availableAddresses.length === 0
+ ) {
+ return [];
+ }
+ const present = new Set(
+ status.availableAddresses.map((entry) => entry.address),
+ );
+ return status.urls.filter((url) => {
+ try {
+ return !present.has(new URL(url).hostname.replace(/^\[|\]$/g, ""));
+ } catch {
+ return false;
+ }
+ });
+}
+
export function keylessLanAccessDescription(
status: LanAccessStatus | null,
): string {
diff --git a/studio/frontend/src/features/settings/api/remote-access-state.ts b/studio/frontend/src/features/settings/api/remote-access-state.ts
index 7bed619ea05..4d2422e183d 100644
--- a/studio/frontend/src/features/settings/api/remote-access-state.ts
+++ b/studio/frontend/src/features/settings/api/remote-access-state.ts
@@ -128,6 +128,30 @@ export function remoteAccessSelfStopPoll(
return { expectingDisconnect: true, apply: next.state !== "stopping" };
}
+export function remoteAccessErrorMessage(
+ error: string | null | undefined,
+): string | null {
+ switch (error) {
+ case null:
+ case undefined:
+ return null;
+ case "cloudflared is unavailable":
+ return "Couldn't download cloudflared. Check your internet connection, or install cloudflared yourself (for example brew install cloudflared) and try again.";
+ case "cloudflared did not produce a URL":
+ return "Cloudflare didn't issue a URL. Check your connection and try again in a minute.";
+ case "cloudflared did not register a connection":
+ return "Cloudflare couldn't connect. A firewall or VPN may be blocking it.";
+ case "Cloudflare URL was not reachable":
+ return "The URL was created but didn't respond. Try again.";
+ case "cloudflared exited":
+ return "The Cloudflare tunnel stopped unexpectedly. Start it again.";
+ case "cloudflared could not be stopped":
+ return "The previous Cloudflare tunnel could not be stopped. Stop it before starting a new one.";
+ default:
+ return error;
+ }
+}
+
export function remoteAccessBlockMessage(
reason: string | null,
isDesktop: boolean,
@@ -140,7 +164,7 @@ export function remoteAccessBlockMessage(
? "Set a remote password before exposing this server."
: "Change the administrator password before exposing this server. In the desktop app, run unsloth studio reset-password.";
case "explicitly_disabled":
- return "This launch used --no-cloudflare. Restart without it to enable remote access.";
+ return "This launch turned the Cloudflare tunnel off (--no-cloudflare, which unsloth start also sets). Relaunch with unsloth studio to use remote access.";
case "launch_managed":
return "This tunnel is managed by the launch command.";
case "colab_managed":
diff --git a/studio/frontend/src/features/settings/components/api-key-action-message.ts b/studio/frontend/src/features/settings/components/api-key-action-message.ts
new file mode 100644
index 00000000000..3c24e45a70a
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/api-key-action-message.ts
@@ -0,0 +1,11 @@
+// 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 { ApiKeyActionError } from "../api/api-keys";
+
+/** The translated failure, plus the server's reason (e.g. a reserved name) when it gave one. */
+export function apiKeyActionMessage(failure: string, cause: unknown): string {
+ return cause instanceof ApiKeyActionError && cause.message
+ ? `${failure} ${cause.message}`
+ : failure;
+}
diff --git a/studio/frontend/src/features/settings/components/api-key-row.tsx b/studio/frontend/src/features/settings/components/api-key-row.tsx
index 46243ba3309..e87e547a653 100644
--- a/studio/frontend/src/features/settings/components/api-key-row.tsx
+++ b/studio/frontend/src/features/settings/components/api-key-row.tsx
@@ -11,6 +11,7 @@ import {
import { type Locale, formatRelativeTime, useLocale, useT } from "@/i18n";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { toast } from "@/lib/toast";
+import { cn } from "@/lib/utils";
import {
Copy01Icon,
Delete02Icon,
@@ -21,13 +22,21 @@ import type { ApiKey } from "../api/api-keys";
type SettingsT = ReturnType<typeof useT>;
-function relative(iso: string | null, t: SettingsT, locale: Locale): string {
+export function relative(
+ iso: string | null,
+ t: SettingsT,
+ locale: Locale,
+): string {
if (!iso) return t("settings.apiKeys.relativeNever");
const diff = Date.now() - new Date(iso).getTime();
const days = Math.floor(diff / 86400000);
if (days < 1) {
const hours = Math.floor(diff / 3600000);
- if (hours < 1) return t("settings.apiKeys.relativeJustNow");
+ if (hours < 1) {
+ const minutes = Math.floor(diff / 60000);
+ if (minutes < 1) return t("settings.apiKeys.relativeJustNow");
+ return formatRelativeTime(locale, -minutes, "minute");
+ }
return formatRelativeTime(locale, -hours, "hour");
}
if (days < 30) return formatRelativeTime(locale, -days, "day");
@@ -39,13 +48,21 @@ function relative(iso: string | null, t: SettingsT, locale: Locale): string {
return formatRelativeTime(locale, -years, "year");
}
-function expiresText(iso: string | null, t: SettingsT, locale: Locale): string {
+export function isExpired(iso: string | null): boolean {
+ return iso !== null && new Date(iso).getTime() <= Date.now();
+}
+
+export function expiresText(
+ iso: string | null,
+ t: SettingsT,
+ locale: Locale,
+): string {
if (!iso) return t("settings.apiKeys.relativeNever");
const diff = new Date(iso).getTime() - Date.now();
if (diff < 0) return t("settings.apiKeys.expired");
- const days = Math.floor(diff / 86400000);
- if (days < 1) return t("settings.apiKeys.today");
- return formatRelativeTime(locale, days, "day");
+ if (diff < 86400000) return t("settings.apiKeys.today");
+ // ceil: a fresh 7-day token still has 7 days, not "6 days" from 6.99
+ return formatRelativeTime(locale, Math.ceil(diff / 86400000), "day");
}
export function ApiKeyRow({
@@ -59,15 +76,22 @@ export function ApiKeyRow({
const locale = useLocale();
// The ellipsis is display only; a copied prefix must not carry it.
const prefix = `sk-unsloth-${apiKey.key_prefix}`;
+ const expired = isExpired(apiKey.expires_at);
return (
<div className="group flex items-center gap-3 border-b border-border/60 px-1 py-3 last:border-b-0 transition-colors hover:bg-accent/40">
<span
- className="size-1.5 shrink-0 rounded-full bg-emerald-500"
+ className={cn(
+ "size-1.5 shrink-0 rounded-full",
+ expired ? "bg-muted-foreground/40" : "bg-emerald-500",
+ )}
aria-hidden="true"
/>
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<div className="flex min-w-0 items-center justify-between gap-3">
- <span className="truncate text-sm font-medium text-foreground" title={apiKey.name}>
+ <span
+ className="truncate text-sm font-medium text-foreground"
+ title={apiKey.name}
+ >
{apiKey.name}
</span>
<code className="shrink-0 font-mono text-ui-11 text-muted-foreground">
@@ -88,14 +112,16 @@ export function ApiKeyRow({
</span>
<span>·</span>
<span>
- {t("settings.apiKeys.expires", {
- value: expiresText(apiKey.expires_at, t, locale),
- })}
+ {expired
+ ? t("settings.apiKeys.expiredStatus")
+ : t("settings.apiKeys.expires", {
+ value: expiresText(apiKey.expires_at, t, locale),
+ })}
</span>
</div>
</div>
<DropdownMenu>
- <DropdownMenuTrigger asChild>
+ <DropdownMenuTrigger asChild={true}>
<Button
variant="ghost"
size="sm"
diff --git a/studio/frontend/src/features/settings/components/audio-api-examples.tsx b/studio/frontend/src/features/settings/components/audio-api-examples.tsx
index 59980664952..43eeb13171f 100644
--- a/studio/frontend/src/features/settings/components/audio-api-examples.tsx
+++ b/studio/frontend/src/features/settings/components/audio-api-examples.tsx
@@ -5,6 +5,7 @@ import { SegmentedPill } from "@/components/segmented-control";
import { usePlatformStore } from "@/config/env";
import { useT } from "@/i18n";
import type { TranslationKey } from "@/i18n";
+import { isTauri } from "@/lib/api-base";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { Tick02Icon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
@@ -206,7 +207,11 @@ export function AudioApiExamples({
const origin = typeof window !== "undefined" ? window.location.origin : "";
const base =
- useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin);
+ useTunnel && cloudflareUrl
+ ? cloudflareUrl
+ : isTauri
+ ? (serverUrl ?? origin)
+ : origin;
const key = audioApiKey(apiKey, {
base,
tunnel: useTunnel && !!cloudflareUrl,
diff --git a/studio/frontend/src/features/settings/components/create-key-form.tsx b/studio/frontend/src/features/settings/components/create-key-form.tsx
index 08205392ede..c83c81da12c 100644
--- a/studio/frontend/src/features/settings/components/create-key-form.tsx
+++ b/studio/frontend/src/features/settings/components/create-key-form.tsx
@@ -8,6 +8,7 @@ import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { useId, useState } from "react";
import { createApiKey } from "../api/api-keys";
+import { apiKeyActionMessage } from "./api-key-action-message";
const EXPIRY_PRESETS = [
{ label: "Never", value: null as number | null },
@@ -21,7 +22,8 @@ export function CreateKeyForm({
onError,
}: {
onCreated: (rawKey: string) => void;
- onError: (message: string) => void;
+ /** null clears an earlier failure */
+ onError: (message: string | null) => void;
}) {
const t = useT();
const pillId = useId();
@@ -33,14 +35,13 @@ export function CreateKeyForm({
e.preventDefault();
if (!name.trim() || loading) return;
setLoading(true);
+ onError(null);
try {
const result = await createApiKey(name.trim(), expiry);
onCreated(result.key);
setName("");
- } catch {
- // api-keys.ts throws English Error messages; use the translated one so
- // zh-CN users don't see English bleed through from internal exceptions.
- onError(t("settings.apiKeys.createError"));
+ } catch (cause) {
+ onError(apiKeyActionMessage(t("settings.apiKeys.createError"), cause));
} finally {
setLoading(false);
}
diff --git a/studio/frontend/src/features/settings/components/keyless-api-access-section.tsx b/studio/frontend/src/features/settings/components/keyless-api-access-section.tsx
index 1ade65d0e7b..be5536f3925 100644
--- a/studio/frontend/src/features/settings/components/keyless-api-access-section.tsx
+++ b/studio/frontend/src/features/settings/components/keyless-api-access-section.tsx
@@ -21,7 +21,7 @@ import {
import { cn } from "@/lib/utils";
import { LaptopIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { SettingsRow } from "./settings-row";
type PendingGrant = Exclude<KeylessApiAccessScope, "off"> | "tools";
@@ -83,6 +83,16 @@ export function KeylessApiAccessSection({
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [pending, setPending] = useState<PendingGrant | null>(null);
+ // the examples follow what the server admits, not the saved choice
+ const notify = useCallback(
+ (next: KeylessApiAccessSettings) =>
+ onSettingsChange?.({
+ scope: next.suspendedByAccounts ? "off" : next.scope,
+ tools: next.tools,
+ exposure: next.exposure,
+ }),
+ [onSettingsChange],
+ );
// biome-ignore lint/correctness/useExhaustiveDependencies: cloudflareUrl is a trigger, not an input -- exposure is recomputed by the backend when a tunnel appears or goes away
useEffect(() => {
@@ -92,11 +102,7 @@ export function KeylessApiAccessSection({
if (!cancelled) {
setSettings(next);
setError(null);
- onSettingsChange?.({
- scope: next.scope,
- tools: next.tools,
- exposure: next.exposure,
- });
+ notify(next);
}
})
.catch((cause: unknown) => {
@@ -111,7 +117,7 @@ export function KeylessApiAccessSection({
return () => {
cancelled = true;
};
- }, [cloudflareUrl, onSettingsChange]);
+ }, [cloudflareUrl, notify]);
const save = async (next: KeylessApiAccessScope, tools?: boolean) => {
setSaving(true);
@@ -119,11 +125,7 @@ export function KeylessApiAccessSection({
try {
const saved = await updateKeylessApiAccess(next, tools);
setSettings(saved);
- onSettingsChange?.({
- scope: saved.scope,
- tools: saved.tools,
- exposure: saved.exposure,
- });
+ notify(saved);
} catch (cause: unknown) {
setError(
cause instanceof Error
@@ -142,11 +144,7 @@ export function KeylessApiAccessSection({
try {
const refreshed = await loadKeylessApiAccess();
setSettings(refreshed);
- onSettingsChange?.({
- scope: refreshed.scope,
- tools: refreshed.tools,
- exposure: refreshed.exposure,
- });
+ notify(refreshed);
} catch {
// keep the exposure already on screen; the dialog still states the scope
} finally {
@@ -210,6 +208,12 @@ export function KeylessApiAccessSection({
</div>
</div>
+ {settings?.suspendedByAccounts ? (
+ <p className="border-t border-border/60 px-4 py-2.5 text-xs leading-snug text-muted-foreground">
+ Off while this install has other accounts: every request needs a key.
+ </p>
+ ) : null}
+
{error ? (
<p className="border-t border-border/60 px-4 py-2.5 text-xs leading-snug text-destructive">
{error}
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 e58a1749647..bdca316eb2a 100644
--- a/studio/frontend/src/features/settings/components/lan-access-section.tsx
+++ b/studio/frontend/src/features/settings/components/lan-access-section.tsx
@@ -43,6 +43,7 @@ import {
lanAccessPortReadOnly,
lanAccessStopDisconnectsOrigin,
sameLanAccessAddresses,
+ staleLanUrls,
validLanAccessPort,
} from "@/features/settings/api/lan-access-state";
import { isTauri } from "@/lib/api-base";
@@ -203,6 +204,13 @@ function LanUrlPanel({ status }: { status: LanAccessStatus | null }) {
return null;
}
const single = status.urls.length === 1;
+ const stale = new Set(staleLanUrls(status));
+ const keylessInference =
+ // "full" stays localhost-only, so only "inference" reaches LAN callers.
+ status.keylessScope === "inference" && status.keylessLanEligible;
+ const keylessNote = keylessInference
+ ? "Anyone on this network can use the inference API without a key. "
+ : "";
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">
@@ -214,26 +222,41 @@ function LanUrlPanel({ status }: { status: LanAccessStatus | null }) {
) : null}
</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>
- {single ? null : <LanUrlActions url={url} copyLabel="Copy" />}
+ <div key={url} className="flex flex-col gap-1">
+ <div 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>
+ {single ? null : <LanUrlActions url={url} copyLabel="Copy" />}
+ </div>
+ {stale.has(url) ? (
+ <span className="text-xs text-destructive leading-snug">
+ This address is no longer on this computer, so nothing reaches it.
+ Stop and start LAN access to use the current one.
+ </span>
+ ) : null}
</div>
))}
{status.publicUrls.length > 0 ? (
<span className="text-xs text-destructive leading-snug">
+ {keylessNote}
{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">
+ {keylessNote}
{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>
)}
+ <span className="text-xs text-muted-foreground leading-snug">
+ Can't connect from another device? Allow Unsloth through this computer's
+ firewall, and check both devices are on the same network (guest Wi-Fi
+ often keeps devices apart).
+ </span>
</div>
);
}
diff --git a/studio/frontend/src/features/settings/components/mcp-access-section.tsx b/studio/frontend/src/features/settings/components/mcp-access-section.tsx
index 18ee34b6147..a4e2493fa8f 100644
--- a/studio/frontend/src/features/settings/components/mcp-access-section.tsx
+++ b/studio/frontend/src/features/settings/components/mcp-access-section.tsx
@@ -12,6 +12,7 @@ import {
import { Switch } from "@/components/ui/switch";
import { usePlatformStore } from "@/config/env";
import { translate, useT } from "@/i18n";
+import { isTauri } from "@/lib/api-base";
import { cn } from "@/lib/utils";
import { McpServerIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -40,10 +41,7 @@ import {
hasMcpSnippet,
} from "./mcp-agent-snippet";
import { SettingsRow } from "./settings-row";
-import {
- readUseTunnelPref,
- subscribeUseTunnelPref,
-} from "./tunnel-preference";
+import { readUseTunnelPref, subscribeUseTunnelPref } from "./tunnel-preference";
const ENV_FORCE = "UNSLOTH_STUDIO_ENABLE_MCP";
const MCP_AGENTS = SUPPORTED_AGENTS.filter((agent) => hasMcpSnippet(agent.id));
@@ -133,7 +131,11 @@ export function McpAccessSection({
// match the server address shown by the API examples.
const origin = typeof window !== "undefined" ? window.location.origin : "";
const base =
- useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin);
+ useTunnel && cloudflareUrl
+ ? cloudflareUrl
+ : isTauri
+ ? (serverUrl ?? origin)
+ : origin;
const snippet = settings?.enabled
? (buildMcpSnippet(agent, base, os, apiKey) ??
buildMcpSnippet(agent, settings.url, os, apiKey))
diff --git a/studio/frontend/src/features/settings/components/media-api-examples.tsx b/studio/frontend/src/features/settings/components/media-api-examples.tsx
index 0fb8a1a96b3..f8bad552f88 100644
--- a/studio/frontend/src/features/settings/components/media-api-examples.tsx
+++ b/studio/frontend/src/features/settings/components/media-api-examples.tsx
@@ -3,6 +3,7 @@
import { usePlatformStore } from "@/config/env";
import { useT } from "@/i18n";
+import { isTauri } from "@/lib/api-base";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { Tick02Icon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
@@ -128,7 +129,11 @@ export function MediaApiExamples({
const origin = typeof window !== "undefined" ? window.location.origin : "";
const base =
- useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin);
+ useTunnel && cloudflareUrl
+ ? cloudflareUrl
+ : isTauri
+ ? (serverUrl ?? origin)
+ : origin;
const key = audioApiKey(apiKey, {
base,
tunnel: useTunnel && !!cloudflareUrl,
diff --git a/studio/frontend/src/features/settings/components/remote-access-section.tsx b/studio/frontend/src/features/settings/components/remote-access-section.tsx
index f711ba8b227..1556cfae5fa 100644
--- a/studio/frontend/src/features/settings/components/remote-access-section.tsx
+++ b/studio/frontend/src/features/settings/components/remote-access-section.tsx
@@ -1,7 +1,6 @@
// 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 { useLoginMode } from "@/features/auth/account-session";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -13,6 +12,7 @@ import {
} from "@/components/ui/dialog";
import { Switch } from "@/components/ui/switch";
import { usePlatformStore } from "@/config/env";
+import { useLoginMode } from "@/features/auth/account-session";
import {
loadRemoteAccess,
startRemoteAccess,
@@ -23,6 +23,7 @@ import {
type RemoteAccessStatus,
remoteAccessAutoStartReadOnly,
remoteAccessBlockMessage,
+ remoteAccessErrorMessage,
remoteAccessPollDelay,
remoteAccessSelfStopPoll,
remoteAccessStopDisconnectsOrigin,
@@ -33,8 +34,8 @@ import { Tick02Icon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
import {
Copy01Icon,
- QrCodeIcon,
HomeWifiIcon,
+ QrCodeIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useCallback, useEffect, useRef, useState } from "react";
@@ -173,6 +174,7 @@ function StatusMessage({
}
function RemoteUrlPanel({ url }: { url: string | null }) {
+ const multi = useLoginMode() === "multi";
if (!url) {
return null;
}
@@ -189,7 +191,13 @@ function RemoteUrlPanel({ url }: { url: string | null }) {
{url}
</code>
<span className="text-xs text-muted-foreground leading-snug">
- Anyone with this URL and the remote password can sign in.
+ {multi
+ ? "Anyone with this URL reaches the sign-in page, and every account and API key works here. Signing in as the owner gives full control, including running code on this computer through tools."
+ : "Anyone with this URL reaches the sign-in page. Signing in gives full control, including running code on this computer through tools. API keys also work here."}
+ </span>
+ <span className="text-xs text-muted-foreground leading-snug">
+ While remote access is on, MCP servers that run local commands are
+ paused.
</span>
</div>
);
@@ -382,7 +390,7 @@ export function RemoteAccessSection() {
</div>
<p className="text-xs text-muted-foreground leading-relaxed">
Use Unsloth and its APIs from other devices through a secure,
- temporary Cloudflare URL.
+ temporary public Cloudflare URL.
</p>
</div>
</div>
@@ -399,9 +407,10 @@ export function RemoteAccessSection() {
</div>
<StatusMessage
- message={blockMessage ?? status?.error}
- destructive={!blockMessage}
+ message={remoteAccessErrorMessage(status?.error)}
+ destructive={true}
/>
+ <StatusMessage message={blockMessage} />
<RemoteUrlPanel url={status?.url ?? null} />
<div className="border-t border-border/60 px-4 py-1">
diff --git a/studio/frontend/src/features/settings/components/remote-lan-summary.tsx b/studio/frontend/src/features/settings/components/remote-lan-summary.tsx
index b9dbb74b7d9..6050528e538 100644
--- a/studio/frontend/src/features/settings/components/remote-lan-summary.tsx
+++ b/studio/frontend/src/features/settings/components/remote-lan-summary.tsx
@@ -17,6 +17,7 @@ import {
type RemoteAccessStatus,
loadRemoteAccess,
} from "../api/remote-access";
+import { remoteAccessPollDelay } from "../api/remote-access-state";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
type AccessState = "off" | "starting" | "online" | "stopping" | "error";
@@ -82,15 +83,30 @@ export function RemoteLanSummary() {
useEffect(() => {
let cancelled = false;
- loadRemoteAccess()
- .then((next) => {
- if (cancelled) return;
- setRemote(next);
- usePlatformStore.setState({ cloudflareUrl: next.url });
- })
- .catch(() => {
- if (!cancelled) setRemoteFailed(true);
- });
+ let timer: number | undefined;
+ let settling = false;
+ // Re-read only mid-transition: a Start left on another tab would otherwise read "Starting" forever.
+ // A failed read while settling retries too, or the last transitional state would stick.
+ const readRemote = () => {
+ loadRemoteAccess()
+ .then((next) => {
+ if (cancelled) return;
+ setRemote(next);
+ usePlatformStore.setState({ cloudflareUrl: next.url });
+ settling = next.state === "starting" || next.state === "stopping";
+ if (settling) {
+ timer = window.setTimeout(readRemote, remoteAccessPollDelay(next));
+ }
+ })
+ .catch(() => {
+ if (cancelled) return;
+ setRemoteFailed(true);
+ if (settling) {
+ timer = window.setTimeout(readRemote, remoteAccessPollDelay(null));
+ }
+ });
+ };
+ readRemote();
loadLanAccess()
.then((next) => {
if (cancelled) return;
@@ -102,6 +118,7 @@ export function RemoteLanSummary() {
});
return () => {
cancelled = true;
+ window.clearTimeout(timer);
};
}, []);
diff --git a/studio/frontend/src/features/settings/components/usage-examples.tsx b/studio/frontend/src/features/settings/components/usage-examples.tsx
index 8d0ee5d9f68..18b8e62d898 100644
--- a/studio/frontend/src/features/settings/components/usage-examples.tsx
+++ b/studio/frontend/src/features/settings/components/usage-examples.tsx
@@ -34,7 +34,6 @@ import {
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import {
- useCallback,
useEffect,
useId,
useMemo,
@@ -536,6 +535,15 @@ function canUseLocalAgentDetection(base: string): boolean {
}
}
+function isLoopbackUrl(url: string | null | undefined): boolean {
+ if (!url) return false;
+ try {
+ return isLoopbackHost(normalizeHost(new URL(url).hostname));
+ } catch {
+ return false;
+ }
+}
+
const SHIKI_THEMES = [unslothLightTheme, unslothDarkTheme] as [
typeof unslothLightTheme,
typeof unslothDarkTheme,
@@ -642,9 +650,15 @@ export function UsageExamples({
// A manual pick is kept only until the model's GGUF-ness changes under it.
const clickedUnderGgufRef = useRef<boolean | null>(null);
const origin = typeof window !== "undefined" ? window.location.origin : "";
+ // server_url is the bind address, which an SSH forward or reverse proxy does not expose.
const base =
- useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin);
+ useTunnel && cloudflareUrl
+ ? cloudflareUrl
+ : isTauri
+ ? (serverUrl ?? origin)
+ : origin;
const localAgentDetection = canUseLocalAgentDetection(base);
+ const loopbackBind = isLoopbackUrl(serverUrl);
// isServedByLlamaCpp owns which store fields count; a context length is not among them,
// since MLX reports one too.
const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
@@ -905,9 +919,9 @@ export function UsageExamples({
/>
<span className="text-ui-11 font-medium text-foreground">
{t("settings.apiKeys.secureHttps")}
- {/* Only when not launched with --secure: the raw 0.0.0.0 port is
- still globally reachable, so point the user at --secure. */}
- {secure ? null : (
+ {/* Only for a network bind not launched with --secure: its raw port stays
+ reachable. A loopback bind (the default, and Desktop) exposes nothing. */}
+ {secure || loopbackBind ? null : (
<Tooltip>
<TooltipTrigger asChild={true}>
{/* Inline on the baseline, like a glyph after the label. */}
@@ -996,9 +1010,7 @@ export function UsageExamples({
: "text-muted-foreground hover:text-foreground",
)}
>
- {os === "unix" && (
- <SegmentedPill group={`${pillId}-os`} />
- )}
+ {os === "unix" && <SegmentedPill group={`${pillId}-os`} />}
{t("settings.apiKeys.osUnix")}
</button>
<button
@@ -1015,9 +1027,7 @@ export function UsageExamples({
: "text-muted-foreground hover:text-foreground",
)}
>
- {os === "windows" && (
- <SegmentedPill group={`${pillId}-os`} />
- )}
+ {os === "windows" && <SegmentedPill group={`${pillId}-os`} />}
{t("settings.apiKeys.osWindows")}
</button>
</div>
@@ -1121,15 +1131,15 @@ export function UsageExamples({
{t("settings.agents.vscodeNote")}
</span>
)}
- <span className="text-ui-11 leading-snug text-muted-foreground">
- {detectedAgents.length > 0
- ? t("settings.apiKeys.codingAgentsDetectedHint", {
- agents: detectedAgents
- .map((id) => AGENT_LABELS[id] ?? id)
- .join(", "),
- })
- : t("settings.apiKeys.codingAgentsSwap")}
- </span>
+ {detectedAgents.length > 0 ? (
+ <span className="text-ui-11 leading-snug text-muted-foreground">
+ {t("settings.apiKeys.codingAgentsDetectedHint", {
+ agents: detectedAgents
+ .map((id) => AGENT_LABELS[id] ?? id)
+ .join(", "),
+ })}
+ </span>
+ ) : null}
</div>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-border px-3 py-2 text-ui-11 text-muted-foreground">
<span>{t("settings.apiKeys.setupDocs")}</span>
diff --git a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
index b568f92c4d7..54eb24bb29a 100644
--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
@@ -1,7 +1,6 @@
// 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 { useIsAccountOwner } from "@/features/auth";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -11,6 +10,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { useIsAccountOwner } from "@/features/auth";
import { translate, useT } from "@/i18n";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useCallback, useEffect, useState } from "react";
@@ -19,6 +19,7 @@ import type {
KeylessApiAccessExposure,
KeylessApiAccessScope,
} from "../api/keyless-api-access";
+import { apiKeyActionMessage } from "../components/api-key-action-message";
import { ApiKeyRow } from "../components/api-key-row";
import { AudioApiExamples } from "../components/audio-api-examples";
import { MediaApiExamples } from "../components/media-api-examples";
@@ -31,10 +32,7 @@ import { ModelAliasesSection } from "../components/model-aliases-section";
import { ModelAutoSwitchSection } from "../components/model-auto-switch-section";
import { MonitorLink } from "../components/monitor-link";
import { RemoteLanSummary } from "../components/remote-lan-summary";
-import {
- UsageExamples,
- useApiTunnelPref,
-} from "../components/usage-examples";
+import { UsageExamples, useApiTunnelPref } from "../components/usage-examples";
export function ApiKeysTab() {
const t = useT();
@@ -42,6 +40,7 @@ export function ApiKeysTab() {
const [keys, setKeys] = useState<ApiKey[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
+ const [actionError, setActionError] = useState<string | null>(null);
const [revokeTarget, setRevokeTarget] = useState<ApiKey | null>(null);
const [revoking, setRevoking] = useState(false);
const [revealed, setRevealed] = useState<string | null>(null);
@@ -96,12 +95,16 @@ export function ApiKeysTab() {
const confirmRevoke = async () => {
if (!revokeTarget) return;
setRevoking(true);
+ setActionError(null);
try {
await revokeApiKey(revokeTarget.id);
await load();
setRevokeTarget(null);
- } catch {
- setError(translate("settings.apiKeys.revokeError"));
+ } catch (cause) {
+ setActionError(
+ apiKeyActionMessage(translate("settings.apiKeys.revokeError"), cause),
+ );
+ setRevokeTarget(null);
} finally {
setRevoking(false);
}
@@ -151,7 +154,7 @@ export function ApiKeysTab() {
setRevealed(raw);
void load();
}}
- onError={setError}
+ onError={setActionError}
/>
</motion.div>
)}
@@ -161,6 +164,11 @@ export function ApiKeysTab() {
<h2 className="settings-heading mb-2 text-sm font-semibold">
{t("settings.apiKeys.accessTokens")}
</h2>
+ {actionError ? (
+ <div className="mb-2 rounded-md border border-destructive/20 bg-destructive/5 p-3 text-xs text-destructive">
+ {actionError}
+ </div>
+ ) : null}
{error ? (
<div className="rounded-md border border-destructive/20 bg-destructive/5 p-3 text-xs text-destructive">
{error}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 2932e1a82df..81f7cef59b0 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -3121,6 +3121,7 @@ export const ar = {
relativeNever: "لا يوجد",
relativeJustNow: "للتوّ",
expired: "منتهي الصلاحية",
+ expiredStatus: "منتهي الصلاحية",
today: "اليوم",
created: "أُنشئ {value}",
used: "آخر استخدام: {value}",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 681dab2c6b7..b9dbfe3a4fe 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -3168,6 +3168,7 @@ export const de = {
relativeNever: "nie",
relativeJustNow: "gerade eben",
expired: "abgelaufen",
+ expiredStatus: "Abgelaufen",
today: "heute",
created: "Erstellt {value}",
used: "Verwendet {value}",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index e3149dabb28..5b743f62694 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -3134,7 +3134,7 @@ export const en = {
},
apiKeys: {
title: "API",
- description: "Access Unsloth via the OpenAI-compatible API.",
+ description: "Access Unsloth via the OpenAI- and Anthropic-compatible API.",
readDocs: "Read the API docs",
noAccess: "No API access yet.",
accessTokens: "Access tokens",
@@ -3179,6 +3179,7 @@ export const en = {
relativeNever: "never",
relativeJustNow: "just now",
expired: "expired",
+ expiredStatus: "Expired",
today: "today",
created: "Created {value}",
used: "Used {value}",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 257de694ea4..afb6ceb4527 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -3161,6 +3161,7 @@ export const es = {
relativeNever: "nunca",
relativeJustNow: "justo ahora",
expired: "caducado",
+ expiredStatus: "Caducado",
today: "hoy",
created: "Creado {value}",
used: "Usado {value}",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 28a0daad574..88725dee20c 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -3169,6 +3169,7 @@ export const fr = {
relativeNever: "jamais",
relativeJustNow: "à l'instant",
expired: "expiré",
+ expiredStatus: "Expiré",
today: "aujourd'hui",
created: "Créé {value}",
used: "Utilisé {value}",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index b74df8ed1f1..1f920f21ced 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -3241,6 +3241,7 @@ export const he = {
relativeNever: "אף פעם",
relativeJustNow: "זה עתה",
expired: "פג תוקף",
+ expiredStatus: "פג תוקף",
today: "היום",
created: "נוצר {value}",
used: "שימוש אחרון {value}",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index f0dd35ea66d..d85f7e355ab 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -3130,6 +3130,7 @@ export const hi = {
relativeNever: "कभी नहीं",
relativeJustNow: "अभी",
expired: "समाप्त",
+ expiredStatus: "समाप्त",
today: "आज",
created: "बनाया गया: {value}",
used: "उपयोग किया गया: {value}",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 58eaf276d0f..38932252d20 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -3074,6 +3074,7 @@ export const it = {
relativeNever: "mai",
relativeJustNow: "proprio ora",
expired: "scaduta",
+ expiredStatus: "Scaduta",
today: "oggi",
created: "Creato {value}",
used: "Ultimo utilizzo: {value}",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 626851fecd0..37213c8a1f6 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -3094,6 +3094,7 @@ export const ja = {
relativeNever: "なし",
relativeJustNow: "たった今",
expired: "期限切れ",
+ expiredStatus: "期限切れ",
today: "今日",
created: "作成日時 {value}",
used: "使用日時 {value}",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index d8baa62d5e5..1ff4ea31cee 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -3109,6 +3109,7 @@ export const ko = {
relativeNever: "없음",
relativeJustNow: "방금",
expired: "만료됨",
+ expiredStatus: "만료됨",
today: "오늘",
created: "생성: {value}",
used: "마지막 사용: {value}",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 6b1989ca1b8..eb480f05dc5 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -3140,6 +3140,7 @@ export const ptBR = {
relativeNever: "nunca",
relativeJustNow: "agora mesmo",
expired: "expirado",
+ expiredStatus: "Expirado",
today: "hoje",
created: "Criado {value}",
used: "Usado {value}",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 9ad9d80576b..b883a6543f8 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -3137,6 +3137,7 @@ export const ru = {
relativeNever: "никогда",
relativeJustNow: "только что",
expired: "истёк",
+ expiredStatus: "Истёк",
today: "сегодня",
created: "Создан {value}",
used: "Использование: {value}",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 079e425e3aa..8dc41933afe 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -3342,6 +3342,7 @@ export const sv = {
relativeNever: "aldrig",
relativeJustNow: "just nu",
expired: "har löpt ut",
+ expiredStatus: "Har löpt ut",
today: "i dag",
created: "Skapad {value}",
used: "Senast använd {value}",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 9de352c7461..faa93a0f681 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -3067,6 +3067,7 @@ export const zhCN = {
relativeNever: "从未",
relativeJustNow: "刚刚",
expired: "已过期",
+ expiredStatus: "已过期",
today: "今天",
created: "创建于 {value}",
used: "上次使用:{value}",
diff --git a/studio/frontend/tests/api-keys-tab-accuracy.test.ts b/studio/frontend/tests/api-keys-tab-accuracy.test.ts
new file mode 100644
index 00000000000..a878d5e0815
--- /dev/null
+++ b/studio/frontend/tests/api-keys-tab-accuracy.test.ts
@@ -0,0 +1,65 @@
+// 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";
+
+import { en } from "../src/i18n/locales/en.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const TAB = readSrc("features/settings/tabs/api-keys-tab.tsx");
+const FORM = readSrc("features/settings/components/create-key-form.tsx");
+const KEYS_API = readSrc("features/settings/api/api-keys.ts");
+const ROW = readSrc("features/settings/components/api-key-row.tsx");
+const EXAMPLES = readSrc("features/settings/components/usage-examples.tsx");
+const AUDIO = readSrc("features/settings/components/audio-api-examples.tsx");
+const MEDIA = readSrc("features/settings/components/media-api-examples.tsx");
+const KEYLESS_API = readSrc("features/settings/api/keyless-api-access.ts");
+const KEYLESS = readSrc(
+ "features/settings/components/keyless-api-access-section.tsx",
+);
+
+test("a failed create or revoke keeps the token list and says why", () => {
+ assert.match(TAB, /onError=\{setActionError\}/);
+ assert.match(TAB, /\{actionError \? \([\s\S]*?\{error \? \(/);
+ assert.match(
+ KEYS_API,
+ /typeof body\.detail === "string" \? body\.detail : ""/,
+ );
+ assert.equal(KEYS_API.match(/throw await actionError\(res\)/g)?.length, 2);
+ assert.match(FORM, /onError\(null\);/);
+});
+
+test("token rows say Expired, count whole days and show minutes", () => {
+ assert.match(ROW, /t\("settings\.apiKeys\.expiredStatus"\)/);
+ assert.equal(en.settings.apiKeys.expiredStatus, "Expired");
+ assert.match(ROW, /expired \? "bg-muted-foreground\/40" : "bg-emerald-500"/);
+ assert.match(ROW, /Math\.ceil\(diff \/ 86400000\)/);
+ assert.match(ROW, /formatRelativeTime\(locale, -minutes, "minute"\)/);
+});
+
+test("browser examples use the address the browser reached", () => {
+ for (const source of [EXAMPLES, AUDIO, MEDIA]) {
+ assert.match(
+ source,
+ /useTunnel && cloudflareUrl\s*\?\s*cloudflareUrl\s*:\s*isTauri\s*\?\s*\(serverUrl \?\? origin\)\s*:\s*origin/,
+ );
+ }
+});
+
+test("the raw-port warning is not shown for a loopback bind", () => {
+ assert.match(EXAMPLES, /const loopbackBind = isLoopbackUrl\(serverUrl\);/);
+ assert.match(EXAMPLES, /\{secure \|\| loopbackBind \? null : \(/);
+});
+
+test("keyless suspended by managed accounts reads as off for the examples", () => {
+ assert.match(
+ KEYLESS_API,
+ /suspendedByAccounts: settings\.suspended_by_accounts === true/,
+ );
+ assert.match(
+ KEYLESS,
+ /scope: next\.suspendedByAccounts \? "off" : next\.scope/,
+ );
+ assert.match(KEYLESS, /Off while this install has other accounts/);
+});
diff --git a/studio/frontend/tests/api-settings-tab.test.ts b/studio/frontend/tests/api-settings-tab.test.ts
index c3e70e6ac36..d50db3266a8 100644
--- a/studio/frontend/tests/api-settings-tab.test.ts
+++ b/studio/frontend/tests/api-settings-tab.test.ts
@@ -13,7 +13,11 @@ const LAN_API = readSrc("features/settings/api/lan-access.ts");
test("the API tab shows Remote & LAN as a status line, not a second set of polling panels", () => {
assert.doesNotMatch(TAB, /<RemoteAccessSection|<LanAccessSection/);
assert.match(TAB, /<RemoteLanSummary \/>/);
- assert.doesNotMatch(SUMMARY, /setInterval|setTimeout/);
+ assert.doesNotMatch(SUMMARY, /setInterval/);
+ assert.match(
+ SUMMARY,
+ /settling = next\.state === "starting" \|\| next\.state === "stopping";\s*if \(settling\) \{\s*timer = window\.setTimeout/,
+ );
assert.match(SUMMARY, /setActiveTab\("remote-lan"\)/);
});
@@ -55,6 +59,22 @@ test("LAN URLs publish only when they change", () => {
test("the API page marks one served row as the primary, found by checkpoint first", () => {
const page = readSrc("features/api-monitor/api-monitor-page.tsx");
assert.match(page, /active: index === activeIndex,/);
- assert.match(page, /\(model\.checkpoint \?\? model\.id\) === residentCheckpoint/);
+ assert.match(
+ page,
+ /\(model\.checkpoint \?\? model\.id\) === residentCheckpoint/,
+ );
assert.match(page, /\(model\.active && !canEditSettings\)/);
});
+
+test("a failed read while remote access is settling retries instead of sticking", () => {
+ assert.match(
+ SUMMARY,
+ /\.catch\(\(\) => \{[\s\S]*?if \(settling\) \{\s*timer = window\.setTimeout\(readRemote/,
+ );
+});
+
+test("the keyless note shows beside a public address too, since LAN callers stay keyless", () => {
+ const lan = readSrc("features/settings/components/lan-access-section.tsx");
+ assert.doesNotMatch(lan, /keylessLanEligible &&\s*status\.publicUrls\.length === 0/);
+ assert.equal(lan.match(/\{keylessNote\}/g)?.length, 2);
+});
diff --git a/studio/frontend/tests/lan-access-state.test.ts b/studio/frontend/tests/lan-access-state.test.ts
index aacd0d342be..f44f511b2b3 100644
--- a/studio/frontend/tests/lan-access-state.test.ts
+++ b/studio/frontend/tests/lan-access-state.test.ts
@@ -20,6 +20,7 @@ import {
lanApiUrls,
normalizeLanAccessStatus,
sameLanAccessAddresses,
+ staleLanUrls,
validLanAccessPort,
} from "../src/features/settings/api/lan-access-state.ts";
@@ -618,3 +619,22 @@ test("no error means no message, and an unknown one still says something", () =>
assert.equal(lanAccessErrorMessage(null), null);
assert.ok(lanAccessErrorMessage("something_new")?.length);
});
+
+test("a settings listener flags addresses no longer on this machine", () => {
+ const s = normalizeLanAccessStatus(
+ apiStatus({
+ state: "online",
+ urls: [LAN, SECOND, "http://[fd00::5]:8888"],
+ // biome-ignore lint/style/useNamingConvention: API schema
+ managed_by: "settings",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ available_addresses: [
+ { address: "10.0.0.7", public: false },
+ { address: "fd00::5", public: false },
+ ],
+ }),
+ );
+ assert.deepEqual(staleLanUrls(s), [LAN]);
+ assert.deepEqual(staleLanUrls({ ...s, managedBy: "launch" }), []);
+ assert.deepEqual(staleLanUrls({ ...s, availableAddresses: [] }), []);
+});
diff --git a/studio/frontend/tests/mcp-access-section.test.ts b/studio/frontend/tests/mcp-access-section.test.ts
index d85346eaff3..3b033a459b8 100644
--- a/studio/frontend/tests/mcp-access-section.test.ts
+++ b/studio/frontend/tests/mcp-access-section.test.ts
@@ -101,7 +101,7 @@ test("the setup snippet shows only while on, targets the usage examples' address
assert.match(SECTION, /buildMcpSnippet\(agent, settings\.url, os, apiKey\)/);
assert.match(
SECTION,
- /useTunnel && cloudflareUrl\s*\?\s*cloudflareUrl\s*:\s*\(serverUrl \?\? origin\)/,
+ /useTunnel && cloudflareUrl\s*\?\s*cloudflareUrl\s*:\s*isTauri\s*\?\s*\(serverUrl \?\? origin\)\s*:\s*origin/,
);
// tunnel preference changes must notify this section immediately.
assert.match(
diff --git a/studio/frontend/tests/remote-access-state.test.ts b/studio/frontend/tests/remote-access-state.test.ts
index 5375e68e535..f65a6ec9758 100644
--- a/studio/frontend/tests/remote-access-state.test.ts
+++ b/studio/frontend/tests/remote-access-state.test.ts
@@ -10,6 +10,7 @@ import {
normalizeRemoteAccessStatus,
remoteAccessAutoStartReadOnly,
remoteAccessBlockMessage,
+ remoteAccessErrorMessage,
remoteAccessPollDelay,
remoteAccessSelfStopPoll,
remoteAccessStopDisconnectsOrigin,
@@ -335,3 +336,23 @@ test("a self-origin stop settles on off, not a permanent stopping", () => {
assert.equal(shown.state, "off");
assert.equal(expecting, true);
});
+
+test("every connector error the backend reports gets a next step", () => {
+ // Mirrors the allowlist in utils/remote_access_settings.py.
+ for (const error of [
+ "cloudflared is unavailable",
+ "cloudflared did not produce a URL",
+ "Cloudflare URL was not reachable",
+ "cloudflared did not register a connection",
+ "cloudflared exited",
+ "cloudflared could not be stopped",
+ ]) {
+ const message = remoteAccessErrorMessage(error);
+ assert.ok(message && message !== error, error);
+ }
+ assert.equal(remoteAccessErrorMessage(null), null);
+ assert.equal(
+ remoteAccessErrorMessage("Cloudflare tunnel failed"),
+ "Cloudflare tunnel failed",
+ );
+});
diff --git a/studio/frontend/vite.config.ts b/studio/frontend/vite.config.ts
index 80e93d351b8..bb594614b1f 100644
--- a/studio/frontend/vite.config.ts
+++ b/studio/frontend/vite.config.ts
@@ -54,6 +54,11 @@ export default defineConfig({
target: "http://127.0.0.1:8888",
changeOrigin: true,
},
+ // MCP setup snippets use the page's origin.
+ "/mcp": {
+ target: "http://127.0.0.1:8888",
+ changeOrigin: true,
+ },
"/seed/inspect": {
target: "http://127.0.0.1:8004",
changeOrigin: true,
diff --git a/tests/studio/test_usage_examples_model_source_contract.py b/tests/studio/test_usage_examples_model_source_contract.py
index aaabebafc69..6633ea5d12e 100644
--- a/tests/studio/test_usage_examples_model_source_contract.py
+++ b/tests/studio/test_usage_examples_model_source_contract.py
@@ -225,7 +225,8 @@ def test_keyless_examples_match_transport_tool_and_full_scope_policy():
assert "!(useTunnel && cloudflareUrl)" in src
assert 'keylessBase && !apiKey && keylessScope === "inference"' in src
section = KEYLESS_SECTION_TSX.read_text(encoding = "utf-8")
- assert "[cloudflareUrl, onSettingsChange]" in section
+ assert "[cloudflareUrl, notify]" in section
+ assert "[onSettingsChange]" in section
assert "delete" in section[section.find(" full: {") : section.find(" tools: {")]
assert "disabled on localhost" in section
assert "read the files and settings in Unsloth" not in section