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: add --secure Cloudflare-only mode and revamp API usage examples (#6300)

Daniel Han40c8ad78b94e
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py
index fa5b9855131..ee6678d9b9e 100644
--- a/studio/backend/auth/storage.py
+++ b/studio/backend/auth/storage.py
@@ -4,9 +4,11 @@
"""SQLite storage for auth data (user credentials + JWT secret)."""
import hashlib
+import hmac
import os
import secrets
import sqlite3
+import threading
from datetime import datetime, timezone
from typing import Optional, Tuple
@@ -236,6 +238,29 @@ def _pbkdf2_desktop_secret(raw_secret: str) -> str:
return _pbkdf2_api_key(raw_secret)
+# Memoize the deterministic raw-key -> PBKDF2-hash derivation so the 100k-round
+# KDF runs once per key instead of on every authenticated request. Keyed by a
+# salted HMAC of the key (not the key itself); revocation/expiry are still
+# enforced by the SQLite read on every call, so a cache hit only skips the KDF.
+# Only keys present in the DB are cached, so unknown-key spam can't grow it.
+_api_key_hash_cache: dict[str, str] = {}
+_API_KEY_HASH_CACHE_MAX = 4096
+_api_key_hash_cache_lock = threading.Lock()
+
+
+def _api_key_cache_id(raw_key: str) -> str:
+ """Cache id for a raw key: salted HMAC-SHA256 (not the key itself)."""
+ return hmac.new(
+ _get_or_create_api_key_pbkdf2_salt(), raw_key.encode("utf-8"), hashlib.sha256
+ ).hexdigest()
+
+
+def _reset_api_key_hash_cache() -> None:
+ """Drop memoized derivations (tests / salt change)."""
+ with _api_key_hash_cache_lock:
+ _api_key_hash_cache.clear()
+
+
def is_initialized() -> bool:
"""Check if auth is ready for login (at least one user exists in DB)."""
conn = get_connection()
@@ -704,7 +729,9 @@ def validate_api_key(raw_key: str) -> Optional[str]:
Also updates ``last_used_at`` on success.
"""
- key_hash = _pbkdf2_api_key(raw_key)
+ cache_id = _api_key_cache_id(raw_key)
+ cached_hash = _api_key_hash_cache.get(cache_id)
+ key_hash = cached_hash if cached_hash is not None else _pbkdf2_api_key(raw_key)
conn = get_connection()
try:
cur = conn.execute(
@@ -714,6 +741,12 @@ def validate_api_key(raw_key: str) -> Optional[str]:
row = cur.fetchone()
if row is None:
return None
+ # Real key: memoize so later requests skip the KDF. Bounded; clear on overflow.
+ if cached_hash is None:
+ with _api_key_hash_cache_lock:
+ if len(_api_key_hash_cache) >= _API_KEY_HASH_CACHE_MAX:
+ _api_key_hash_cache.clear()
+ _api_key_hash_cache[cache_id] = key_hash
if not row["is_active"]:
return None
if row["expires_at"] is not None:
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 064e2617534..2022074c08b 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -873,6 +873,10 @@ async def health_check(request: Request):
"version": UNSLOTH_VERSION,
"studio_version": STUDIO_VERSION,
"device_type": device_type,
+ # API-screen fields (authed-only; they fingerprint how the host is exposed).
+ "cloudflare_url": getattr(request.app.state, "cloudflare_url", None),
+ "server_url": getattr(request.app.state, "server_url", None),
+ "secure": bool(getattr(request.app.state, "secure", False)),
}
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 18e96f11c40..a9d1f1db264 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -395,7 +395,23 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
pass
-def _emit_startup_output(host: str, port: int, display_host: str) -> None:
+def _emit_secure_startup_output(port: int) -> None:
+ """Secure-mode banner: only the Cloudflare link (loopback has no public raw URL)."""
+ print("")
+ print("๐Ÿฆฅ Unsloth Studio is running (secure)")
+ print("โ”€" * 52)
+ _print_cloudflare_line()
+ print(f" On this machine only: http://127.0.0.1:{port}/")
+ print("โ”€" * 52)
+ print_studio_stop_hint()
+
+
+def _emit_startup_output(
+ host: str,
+ port: int,
+ display_host: str,
+ secure: bool = False,
+) -> None:
"""Print the access banner plus any post-startup warnings.
Extracted from ``_run`` so the banner/warning wiring is testable. The
@@ -404,6 +420,9 @@ def _emit_startup_output(host: str, port: int, display_host: str) -> None:
non-127.0.0.1 bind, and wildcard binds are never 127.0.0.1), so the
trailing stop hint is emitted exactly once.
"""
+ if secure:
+ _emit_secure_startup_output(port)
+ return
wildcard_bind = host in ("0.0.0.0", "::")
localhost_mismatch_url = _localhost_ipv6_mismatch_url(host, port)
# For wildcard binds, run the reachability check between the URL
@@ -811,6 +830,25 @@ def _setup_server_disk_logging():
return log_path
+def _cloudflare_tunnel_should_start(
+ *, cloudflare: bool, host: str, secure: bool, api_only: bool, is_colab: bool
+) -> bool:
+ """Whether to start the Cloudflare tunnel. --secure tunnels a loopback bind too;
+ non-secure keeps the 0.0.0.0-only rule. Colab/api-only never tunnel."""
+ return cloudflare and (host == "0.0.0.0" or secure) and not api_only and not is_colab
+
+
+def _apply_default_tool_policy(host: str, secure: bool) -> None:
+ """Force server-side tools off on network-reachable launches (0.0.0.0 or --secure)
+ so a public endpoint can't run code via a client's `enable_tools`. `unsloth studio
+ run` installs its own resolved policy and bypasses this."""
+ if not (secure or host == "0.0.0.0"):
+ return
+ from state.tool_policy import set_tool_policy
+
+ set_tool_policy(False)
+
+
def run_server(
host: str = "127.0.0.1",
port: int = 8888,
@@ -819,6 +857,7 @@ def run_server(
api_only: bool = False,
llama_parallel_slots: int = 1,
cloudflare: bool = True,
+ secure: bool = False,
):
"""
Start the FastAPI server.
@@ -837,6 +876,18 @@ def run_server(
"""
global _server, _shutdown_event
+ # --secure exposes only the Cloudflare link: force a loopback bind so the raw
+ # port is never public (even with -H 0.0.0.0), and reject the contradictory combo.
+ if secure and not cloudflare:
+ raise SystemExit(
+ "A secure Cloudflare link is not allowed, use --not-secure which provides a 0.0.0.0 link"
+ )
+ if secure:
+ host = "127.0.0.1"
+
+ # `unsloth studio run` overrides this afterward with its resolved policy.
+ _apply_default_tool_policy(host, secure)
+
# Windows cp1252 can't encode emoji; reconfigure stdout to UTF-8.
if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"):
try:
@@ -975,6 +1026,13 @@ def run_server(
# backend, not whatever a proxy/tunnel exposed. For ephemeral binds (port==0)
# leave it unset so handlers fall back to the request scope / base_url.
app.state.server_port = port if port and port > 0 else None
+ # Direct (non-tunnel) base for the API panel; resolve 0.0.0.0 to the LAN IP.
+ if port and port > 0:
+ _direct_host = _resolve_external_ip() if host == "0.0.0.0" else host
+ app.state.server_url = f"http://{_direct_host}:{port}"
+ else:
+ app.state.server_url = None
+ app.state.secure = secure
app.state.llama_parallel_slots = llama_parallel_slots
# Expose a shutdown callable before the server accepts requests so
@@ -1036,7 +1094,13 @@ def run_server(
global _cloudflare_url
_cloudflare_url = None
app.state.cloudflare_url = None
- _cloudflare_enabled = cloudflare and host == "0.0.0.0" and not api_only and not _IS_COLAB
+ _cloudflare_enabled = _cloudflare_tunnel_should_start(
+ cloudflare = cloudflare,
+ host = host,
+ secure = secure,
+ api_only = api_only,
+ is_colab = _IS_COLAB,
+ )
if _cloudflare_enabled:
try: # best-effort: any failure must not block startup
from cloudflare_tunnel import start_studio_tunnel, stop_studio_tunnel
@@ -1049,8 +1113,19 @@ def run_server(
except Exception as e:
logger.debug("Cloudflare tunnel skipped: %s", e)
+ # --secure fails closed: no tunnel means no public link, so exit rather than
+ # silently fall back to a raw port.
+ if secure and not _cloudflare_url:
+ print(
+ "A secure Cloudflare link is not allowed, use --not-secure which provides a 0.0.0.0 link",
+ file = sys.stderr,
+ flush = True,
+ )
+ _graceful_shutdown(_server)
+ sys.exit(1)
+
if not silent:
- _emit_startup_output(host, port, display_host)
+ _emit_startup_output(host, port, display_host, secure = secure)
return app
@@ -1094,6 +1169,14 @@ if __name__ == "__main__":
help = "Auto-create a free Cloudflare HTTPS tunnel when bound to 0.0.0.0 "
"(default on; --no-cloudflare to disable)",
)
+ parser.add_argument(
+ "--secure",
+ action = argparse.BooleanOptionalAction,
+ default = False,
+ help = "Expose ONLY a Cloudflare HTTPS link: bind localhost and fail closed "
+ "if the tunnel can't start. Without it, --not-secure also serves the raw "
+ "0.0.0.0 port, which is reachable from anywhere on the network",
+ )
# Mirror unsloth_cli/commands/studio.py's _PARALLEL_*. Default 1 is for direct
# backend launches; `unsloth studio run` always passes its own value (4).
_PARALLEL_MIN = 1
@@ -1113,6 +1196,10 @@ if __name__ == "__main__":
args = parser.parse_args()
if not _PARALLEL_MIN <= args.parallel <= _PARALLEL_MAX:
parser.error(f"--parallel must be between {_PARALLEL_MIN} and {_PARALLEL_MAX}")
+ if args.secure and not args.cloudflare:
+ parser.error(
+ "--secure requires the Cloudflare tunnel; do not combine it with --no-cloudflare"
+ )
kwargs = dict(
host = args.host,
@@ -1121,6 +1208,7 @@ if __name__ == "__main__":
api_only = args.api_only,
llama_parallel_slots = args.parallel,
cloudflare = args.cloudflare,
+ secure = args.secure,
)
if args.frontend is not None:
kwargs["frontend_path"] = Path(args.frontend)
diff --git a/studio/backend/tests/test_api_key_expiry.py b/studio/backend/tests/test_api_key_expiry.py
new file mode 100644
index 00000000000..0dacb4c61e8
--- /dev/null
+++ b/studio/backend/tests/test_api_key_expiry.py
@@ -0,0 +1,198 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Expiry enforcement for API keys (tz-aware ``expires_at``) and JWT access
+tokens (``exp`` claim). Both must surface as 401 on protected routes."""
+
+from __future__ import annotations
+
+import asyncio
+import secrets
+from datetime import datetime, timedelta, timezone
+
+import pytest
+from fastapi import HTTPException
+from fastapi.security import HTTPAuthorizationCredentials
+
+from auth import storage
+from auth.authentication import create_access_token, get_current_subject
+
+
[email protected](autouse = True)
+def isolated_auth_db(tmp_path, monkeypatch):
+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")
+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")
+ monkeypatch.setattr(storage, "_bootstrap_password", None)
+ monkeypatch.setattr(storage, "_api_key_pbkdf2_salt_cache", None)
+ storage._reset_api_key_hash_cache()
+ yield
+ storage._reset_api_key_hash_cache()
+
+
+def seed_user():
+ storage.create_initial_user(
+ username = storage.DEFAULT_ADMIN_USERNAME,
+ password = "human-password-123",
+ jwt_secret = secrets.token_urlsafe(64),
+ )
+
+
+def iso_from_now(**delta):
+ return (datetime.now(timezone.utc) + timedelta(**delta)).isoformat()
+
+
+def make_key(expires_at):
+ raw, _row = storage.create_api_key(
+ username = storage.DEFAULT_ADMIN_USERNAME,
+ name = "test",
+ expires_at = expires_at,
+ )
+ return raw
+
+
+def subject_of(token):
+ """Run the real FastAPI auth dependency against a bearer token."""
+ credentials = HTTPAuthorizationCredentials(scheme = "Bearer", credentials = token)
+ return asyncio.run(get_current_subject(credentials))
+
+
+# --- validate_api_key (storage layer) ---------------------------------------
+
+
+def test_unexpired_key_validates():
+ seed_user()
+ assert (
+ storage.validate_api_key(make_key(iso_from_now(days = 1))) == storage.DEFAULT_ADMIN_USERNAME
+ )
+
+
+def test_never_expiring_key_validates():
+ seed_user()
+ assert storage.validate_api_key(make_key(None)) == storage.DEFAULT_ADMIN_USERNAME
+
+
+def test_expired_key_rejected():
+ seed_user()
+ assert storage.validate_api_key(make_key(iso_from_now(seconds = -1))) is None
+
+
+def test_key_expiring_far_in_past_rejected():
+ seed_user()
+ assert storage.validate_api_key(make_key(iso_from_now(days = -30))) is None
+
+
+def test_revoked_key_rejected():
+ seed_user()
+ raw, row = storage.create_api_key(
+ username = storage.DEFAULT_ADMIN_USERNAME,
+ name = "doomed",
+ expires_at = iso_from_now(days = 1),
+ )
+ storage.revoke_api_key(storage.DEFAULT_ADMIN_USERNAME, int(row["id"]))
+ assert storage.validate_api_key(raw) is None
+
+
+def test_unknown_key_rejected():
+ seed_user()
+ assert storage.validate_api_key(storage.API_KEY_PREFIX + secrets.token_hex(16)) is None
+
+
+# --- get_current_subject (route dependency) ---------------------------------
+
+
+def test_dependency_accepts_unexpired_key():
+ seed_user()
+ assert subject_of(make_key(iso_from_now(days = 1))) == storage.DEFAULT_ADMIN_USERNAME
+
+
+def test_dependency_rejects_expired_key_as_401():
+ seed_user()
+ with pytest.raises(HTTPException) as exc:
+ subject_of(make_key(iso_from_now(seconds = -1)))
+ assert exc.value.status_code == 401
+ assert exc.value.detail == "Invalid or expired API key"
+
+
+# --- JWT access-token expiry ------------------------------------------------
+
+
+def test_dependency_accepts_unexpired_jwt():
+ seed_user()
+ token = create_access_token(storage.DEFAULT_ADMIN_USERNAME, timedelta(minutes = 5))
+ assert subject_of(token) == storage.DEFAULT_ADMIN_USERNAME
+
+
+def test_dependency_rejects_expired_jwt_as_401():
+ seed_user()
+ token = create_access_token(storage.DEFAULT_ADMIN_USERNAME, timedelta(seconds = -1))
+ with pytest.raises(HTTPException) as exc:
+ subject_of(token)
+ assert exc.value.status_code == 401
+ assert exc.value.detail == "Invalid or expired token"
+
+
+# --- derivation cache: speeds repeats without bypassing checks --------------
+
+
+def test_cache_skips_pbkdf2_on_repeat(monkeypatch):
+ seed_user()
+ raw = make_key(iso_from_now(days = 1))
+ assert storage.validate_api_key(raw) == storage.DEFAULT_ADMIN_USERNAME # warms cache
+
+ calls = {"n": 0}
+ real = storage._pbkdf2_api_key
+
+ def counting(key):
+ calls["n"] += 1
+ return real(key)
+
+ monkeypatch.setattr(storage, "_pbkdf2_api_key", counting)
+ assert storage.validate_api_key(raw) == storage.DEFAULT_ADMIN_USERNAME
+ assert storage.validate_api_key(raw) == storage.DEFAULT_ADMIN_USERNAME
+ assert calls["n"] == 0 # served from cache, KDF not re-run
+
+
+def test_cache_does_not_bypass_revocation():
+ seed_user()
+ raw, row = storage.create_api_key(
+ username = storage.DEFAULT_ADMIN_USERNAME,
+ name = "revoke-after-cache",
+ expires_at = iso_from_now(days = 1),
+ )
+ assert storage.validate_api_key(raw) == storage.DEFAULT_ADMIN_USERNAME # cached
+ storage.revoke_api_key(storage.DEFAULT_ADMIN_USERNAME, int(row["id"]))
+ assert storage.validate_api_key(raw) is None # cache hit still re-checks is_active
+
+
+def test_cache_does_not_bypass_expiry():
+ seed_user()
+ # Expires between the two calls: the first warms the cache, the second is still rejected.
+ near = (datetime.now(timezone.utc) + timedelta(milliseconds = 600)).isoformat()
+ raw = make_key(near)
+ assert storage.validate_api_key(raw) == storage.DEFAULT_ADMIN_USERNAME
+ import time
+
+ time.sleep(0.8)
+ assert storage.validate_api_key(raw) is None
+
+
+def test_unknown_key_not_cached():
+ seed_user()
+ bogus = storage.API_KEY_PREFIX + secrets.token_hex(16)
+ assert storage.validate_api_key(bogus) is None
+ cache_id = storage._api_key_cache_id(bogus)
+ assert cache_id not in storage._api_key_hash_cache # spam can't grow the cache
+
+
+def test_create_api_key_route_stores_tz_aware_expiry():
+ from datetime import datetime as _dt
+
+ seed_user()
+ raw, row = storage.create_api_key(
+ username = storage.DEFAULT_ADMIN_USERNAME,
+ name = "route",
+ expires_at = iso_from_now(days = 30),
+ )
+ parsed = _dt.fromisoformat(row["expires_at"])
+ assert parsed.tzinfo is not None # tz-aware: comparison in validate_api_key won't raise
+ assert storage.validate_api_key(raw) == storage.DEFAULT_ADMIN_USERNAME
diff --git a/studio/backend/tests/test_secure_tunnel_gate.py b/studio/backend/tests/test_secure_tunnel_gate.py
new file mode 100644
index 00000000000..6d9b6be892b
--- /dev/null
+++ b/studio/backend/tests/test_secure_tunnel_gate.py
@@ -0,0 +1,95 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Cloudflare tunnel start gate, incl. --secure on loopback. Imports run.py
+directly, so run under the Studio venv."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND = Path(__file__).resolve().parents[1]
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+from run import _cloudflare_tunnel_should_start as should_start # noqa: E402
+
+
+ "cloudflare,host,secure,api_only,is_colab,expected",
+ [
+ # Non-secure: historical 0.0.0.0-only behaviour preserved.
+ (True, "0.0.0.0", False, False, False, True),
+ (True, "127.0.0.1", False, False, False, False),
+ (True, "localhost", False, False, False, False),
+ # --secure tunnels a loopback bind too.
+ (True, "127.0.0.1", True, False, False, True),
+ (True, "0.0.0.0", True, False, False, True),
+ # --no-cloudflare always wins.
+ (False, "0.0.0.0", False, False, False, False),
+ (False, "127.0.0.1", True, False, False, False),
+ # api-only and Colab never tunnel.
+ (True, "0.0.0.0", False, True, False, False),
+ (True, "127.0.0.1", True, True, False, False),
+ (True, "0.0.0.0", False, False, True, False),
+ (True, "127.0.0.1", True, False, True, False),
+ ],
+)
+def test_cloudflare_gate(cloudflare, host, secure, api_only, is_colab, expected):
+ assert (
+ should_start(
+ cloudflare = cloudflare,
+ host = host,
+ secure = secure,
+ api_only = api_only,
+ is_colab = is_colab,
+ )
+ is expected
+ )
+
+
+def test_run_server_accepts_secure_kwarg():
+ import inspect
+
+ import run
+
+ assert "secure" in inspect.signature(run.run_server).parameters
+ assert inspect.signature(run.run_server).parameters["secure"].default is False
+
+
+def test_plain_network_launch_forces_tools_off():
+ # Network-reachable launches (0.0.0.0 or --secure) must force server-side tools off.
+ import run
+ from state.tool_policy import get_tool_policy, reset_tool_policy
+
+ reset_tool_policy()
+ run._apply_default_tool_policy("127.0.0.1", False)
+ assert get_tool_policy() is None # loopback: untouched (per-request honored)
+
+ run._apply_default_tool_policy("0.0.0.0", False)
+ assert get_tool_policy() is False # network bind: forced off
+
+ reset_tool_policy()
+ run._apply_default_tool_policy("127.0.0.1", True) # --secure (public tunnel)
+ assert get_tool_policy() is False
+ reset_tool_policy()
+
+
+def test_run_server_rejects_secure_without_cloudflare():
+ # Direct backend callers (not just the CLI) must reject the contradictory combo.
+ import run
+ with pytest.raises(SystemExit) as exc:
+ run.run_server(secure = True, cloudflare = False)
+ assert "A secure Cloudflare link is not allowed" in str(exc.value)
+
+
+def test_failclosed_message_present_in_source():
+ # The exact, user-facing fail-closed message must not drift.
+ src = (_BACKEND / "run.py").read_text(encoding = "utf-8")
+ assert (
+ "A secure Cloudflare link is not allowed, use --not-secure which provides a 0.0.0.0 link"
+ in src
+ )
diff --git a/studio/frontend/src/config/env.ts b/studio/frontend/src/config/env.ts
index 61ab111d45c..60f9e876f98 100644
--- a/studio/frontend/src/config/env.ts
+++ b/studio/frontend/src/config/env.ts
@@ -18,6 +18,11 @@ export type DeviceType = "mac" | "windows" | "linux" | string;
interface PlatformState {
deviceType: DeviceType;
chatOnly: boolean;
+ // From /api/health (authed): live tunnel URL, direct (non-tunnel) base, and
+ // whether the server was launched with --secure.
+ cloudflareUrl: string | null;
+ serverUrl: string | null;
+ secure: boolean;
fetched: boolean;
isChatOnly: () => boolean;
}
@@ -37,13 +42,19 @@ const localDeviceType = detectLocalPlatform();
export const usePlatformStore = create<PlatformState>()((_, get) => ({
deviceType: localDeviceType,
chatOnly: localDeviceType === "mac",
+ cloudflareUrl: null,
+ serverUrl: null,
+ secure: false,
fetched: false,
isChatOnly: () => get().chatOnly,
}));
-export async function fetchDeviceType(): Promise<DeviceType> {
+// `force` re-reads /api/health even if cached, to pick up a late-arriving tunnel URL.
+export async function fetchDeviceType(options?: {
+ force?: boolean;
+}): Promise<DeviceType> {
const { fetched } = usePlatformStore.getState();
- if (fetched) return usePlatformStore.getState().deviceType;
+ if (fetched && !options?.force) return usePlatformStore.getState().deviceType;
try {
// /api/health only reports the server's device_type to authed callers.
@@ -57,7 +68,13 @@ export async function fetchDeviceType(): Promise<DeviceType> {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
});
if (res.ok) {
- const data = (await res.json()) as { device_type?: string; chat_only?: boolean };
+ const data = (await res.json()) as {
+ device_type?: string;
+ chat_only?: boolean;
+ cloudflare_url?: string | null;
+ server_url?: string | null;
+ secure?: boolean;
+ };
const deviceType = data.device_type ?? detectLocalPlatform();
const chatOnly = data.chat_only ?? false;
// Cache only a server-reported platform. Unauthenticated responses fall
@@ -66,6 +83,9 @@ export async function fetchDeviceType(): Promise<DeviceType> {
usePlatformStore.setState({
deviceType,
chatOnly,
+ cloudflareUrl: data.cloudflare_url ?? null,
+ serverUrl: data.server_url ?? null,
+ secure: data.secure ?? false,
fetched: data.device_type !== undefined,
});
return deviceType;
diff --git a/studio/frontend/src/features/settings/components/usage-examples.tsx b/studio/frontend/src/features/settings/components/usage-examples.tsx
index 2fd387062fb..874c9fa930b 100644
--- a/studio/frontend/src/features/settings/components/usage-examples.tsx
+++ b/studio/frontend/src/features/settings/components/usage-examples.tsx
@@ -1,25 +1,85 @@
// 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 { createCodePlugin } from "@/components/assistant-ui/code-plugin";
+import {
+ unslothDarkTheme,
+ unslothLightTheme,
+} from "@/components/assistant-ui/code-themes";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { fetchDeviceType, usePlatformStore } from "@/config/env";
+import { useChatRuntimeStore } from "@/features/chat";
+import { useT } from "@/i18n";
+import type { TranslationKey } from "@/i18n";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { Tick02Icon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
-import { copyToClipboard } from "@/lib/copy-to-clipboard";
-import { useT } from "@/i18n";
import {
ArrowUpRight01Icon,
Copy01Icon,
+ InformationCircleIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
+import { Streamdown } from "streamdown";
-type Lang = "curl" | "python" | "tools";
+// API call type; OS axis applies to curl only (Python is OS-identical).
+type ExampleType =
+ | "curl"
+ | "python"
+ | "curlTools"
+ | "pythonTools"
+ | "curlAdvanced"
+ | "pythonAdvanced";
+type Os = "unix" | "windows";
+// plain = bare call; tools = server-side tools; advanced = sampling + thinking + tools.
+type Variant = "plain" | "tools" | "advanced";
-const TABS: { id: Lang; label: string }[] = [
+const TYPE_TABS: { id: ExampleType; label: string }[] = [
{ id: "curl", label: "curl" },
{ id: "python", label: "Python" },
- { id: "tools", label: "Tools" },
+ { id: "curlTools", label: "curl + tools" },
+ { id: "pythonTools", label: "Python + tools" },
+ { id: "curlAdvanced", label: "curl + advanced" },
+ { id: "pythonAdvanced", label: "Python + advanced" },
];
+const TYPE_LABEL_KEY: Partial<Record<ExampleType, TranslationKey>> = {
+ curlTools: "settings.apiKeys.exampleCurlTools",
+ pythonTools: "settings.apiKeys.examplePythonTools",
+ curlAdvanced: "settings.apiKeys.exampleCurlAdvanced",
+ pythonAdvanced: "settings.apiKeys.examplePythonAdvanced",
+};
+
+const OS_AWARE: Record<ExampleType, boolean> = {
+ curl: true,
+ python: false,
+ curlTools: true,
+ pythonTools: false,
+ curlAdvanced: true,
+ pythonAdvanced: false,
+};
+
+const CURL_TYPES = new Set<ExampleType>(["curl", "curlTools", "curlAdvanced"]);
+
+const PROMPT = "Can Unsloth Studio do API calling?";
+// web_search + python + terminal are the reliable built-in tools.
+const TOOLS = ["web_search", "python", "terminal"];
+// Sampling/thinking knobs for the "+ advanced" examples.
+const ADV = {
+ temperature: 0.7,
+ top_p: 0.8,
+ top_k: 20,
+ min_p: 0.05,
+ repetition_penalty: 1.1,
+ max_tokens: 1024,
+} as const;
+
const DOC_LINKS = [
{
label: "Claude Code",
@@ -43,53 +103,276 @@ const DOC_LINKS = [
},
];
-function buildSnippets(base: string) {
- return {
- curl: `curl ${base}/v1/chat/completions \\
- -H "Authorization: Bearer sk-unsloth-YOUR_KEY" \\
+// JSON-encode; also a valid Python literal, so odd model names never break output.
+const j = (s: string): string => JSON.stringify(s);
+// Embed in a POSIX single-quoted string: close, escaped quote, reopen.
+const shSingle = (s: string): string => s.replace(/'/g, "'\\''");
+// Embed in a PowerShell single-quoted string: '' is a literal quote.
+const psSingle = (s: string): string => s.replace(/'/g, "''");
+const toolsJson = TOOLS.map(j).join(", ");
+
+// Shared body fields (after model/messages, before stream) per variant.
+function bodyExtraLines(variant: Variant, indent: string): string[] {
+ const lines: string[] = [];
+ if (variant === "advanced") {
+ lines.push(`${indent}"temperature": ${ADV.temperature},`);
+ lines.push(`${indent}"top_p": ${ADV.top_p},`);
+ lines.push(`${indent}"top_k": ${ADV.top_k},`);
+ lines.push(`${indent}"min_p": ${ADV.min_p},`);
+ lines.push(`${indent}"repetition_penalty": ${ADV.repetition_penalty},`);
+ lines.push(`${indent}"max_tokens": ${ADV.max_tokens},`);
+ lines.push(`${indent}"enable_thinking": true,`);
+ }
+ if (variant !== "plain") {
+ lines.push(`${indent}"enable_tools": true,`);
+ lines.push(`${indent}"enabled_tools": [${toolsJson}],`);
+ }
+ return lines;
+}
+
+function curlBodyPretty(model: string, variant: Variant): string {
+ const lines = [
+ ` "model": ${j(model)},`,
+ ` "messages": [{"role": "user", "content": ${j(PROMPT)}}],`,
+ ...bodyExtraLines(variant, " "),
+ ` "stream": true`,
+ ];
+ return `{\n${lines.join("\n")}\n }`;
+}
+
+// One-line JSON for the Windows body file (PowerShell mangles inline quotes to curl.exe).
+function winBody(model: string, variant: Variant): string {
+ const body: Record<string, unknown> = {
+ model,
+ messages: [{ role: "user", content: PROMPT }],
+ };
+ if (variant === "advanced") {
+ body.temperature = ADV.temperature;
+ body.top_p = ADV.top_p;
+ body.top_k = ADV.top_k;
+ body.min_p = ADV.min_p;
+ body.repetition_penalty = ADV.repetition_penalty;
+ body.max_tokens = ADV.max_tokens;
+ body.enable_thinking = true;
+ }
+ if (variant !== "plain") {
+ body.enable_tools = true;
+ body.enabled_tools = TOOLS;
+ }
+ body.stream = true;
+ return JSON.stringify(body);
+}
+
+function curlUnix(
+ base: string,
+ key: string,
+ model: string,
+ variant: Variant,
+): string {
+ return `curl ${base}/v1/chat/completions \\
+ -H "Authorization: Bearer ${key}" \\
-H "Content-Type: application/json" \\
- -d '{
- "messages": [{"role": "user", "content": "Hello"}],
- "stream": true
- }'`,
- python: `from openai import OpenAI
+ -d '${shSingle(curlBodyPretty(model, variant))}'`;
+}
+
+// Windows PowerShell: curl aliases to Invoke-WebRequest, so use curl.exe + body file.
+function curlWindows(
+ base: string,
+ key: string,
+ model: string,
+ variant: Variant,
+): string {
+ return `$body = '${psSingle(winBody(model, variant))}'
+Set-Content -Path body.json -Value $body -Encoding ascii
+curl.exe ${base}/v1/chat/completions \`
+ -H "Authorization: Bearer ${key}" \`
+ -H "Content-Type: application/json" \`
+ -d "@body.json"`;
+}
+
+function pythonSnippet(
+ base: string,
+ key: string,
+ model: string,
+ variant: Variant,
+): string {
+ // Standard OpenAI args are named; Unsloth extensions go through extra_body.
+ const named =
+ variant === "advanced"
+ ? `
+ temperature=${ADV.temperature},
+ top_p=${ADV.top_p},
+ max_tokens=${ADV.max_tokens},`
+ : "";
+ const extra: string[] = [];
+ if (variant === "advanced") {
+ extra.push(` "top_k": ${ADV.top_k},`);
+ extra.push(` "min_p": ${ADV.min_p},`);
+ extra.push(` "repetition_penalty": ${ADV.repetition_penalty},`);
+ extra.push(` "enable_thinking": True,`);
+ }
+ if (variant !== "plain") {
+ extra.push(` "enable_tools": True,`);
+ extra.push(` "enabled_tools": [${toolsJson}],`);
+ }
+ const extraBody = extra.length
+ ? `
+ extra_body={
+${extra.join("\n")}
+ },`
+ : "";
+ // With tools, some chunks are tool-lifecycle events with no choices; guard it.
+ const loop =
+ variant !== "plain"
+ ? `for chunk in response:
+ if chunk.choices:
+ print(chunk.choices[0].delta.content or "", end="")`
+ : `for chunk in response:
+ print(chunk.choices[0].delta.content or "", end="")`;
+ return `from openai import OpenAI
client = OpenAI(
- base_url="${base}/v1",
- api_key="sk-unsloth-YOUR_KEY",
+ base_url=${j(`${base}/v1`)},
+ api_key=${j(key)},
)
response = client.chat.completions.create(
- model="current",
- messages=[{"role": "user", "content": "Hello"}],
+ model=${j(model)},
+ messages=[{"role": "user", "content": ${j(PROMPT)}}],${named}${extraBody}
stream=True,
)
-for chunk in response:
- print(chunk.choices[0].delta.content or "", end="")`,
- tools: `curl ${base}/v1/chat/completions \\
- -H "Authorization: Bearer sk-unsloth-YOUR_KEY" \\
- -H "Content-Type: application/json" \\
- -d '{
- "messages": [{"role": "user", "content": "Search Python 3.13 features"}],
- "enable_tools": true,
- "enabled_tools": ["web_search", "python"],
- "stream": true
- }'`,
+${loop}`;
+}
+
+function buildSnippets(
+ base: string,
+ key: string,
+ model: string,
+ os: Os,
+): Record<ExampleType, string> {
+ const curl = os === "windows" ? curlWindows : curlUnix;
+ return {
+ curl: curl(base, key, model, "plain"),
+ python: pythonSnippet(base, key, model, "plain"),
+ curlTools: curl(base, key, model, "tools"),
+ pythonTools: pythonSnippet(base, key, model, "tools"),
+ curlAdvanced: curl(base, key, model, "advanced"),
+ pythonAdvanced: pythonSnippet(base, key, model, "advanced"),
};
}
-export function UsageExamples() {
+const KEY_PLACEHOLDER = "sk-unsloth-YOUR_KEY";
+const MODEL_FALLBACK = "unsloth/gemma-4-E4B-it-GGUF:UD-Q5_K_XL";
+
+// Default ON: when a tunnel exists, examples should show the public base_url.
+const USE_TUNNEL_KEY = "unsloth_api_use_tunnel";
+
+function readUseTunnelPref(): boolean {
+ if (typeof window === "undefined") return true;
+ try {
+ return window.localStorage.getItem(USE_TUNNEL_KEY) !== "false";
+ } catch {
+ return true;
+ }
+}
+
+function writeUseTunnelPref(value: boolean): void {
+ if (typeof window === "undefined") return;
+ try {
+ window.localStorage.setItem(USE_TUNNEL_KEY, value ? "true" : "false");
+ } catch {
+ // Non-fatal: the toggle still applies for this session.
+ }
+}
+
+// Active local checkpoint as repo[:variant]; external/none falls back to a default.
+function useLoadedModelName(): string {
+ const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
+ const ggufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
+ return useMemo(() => {
+ if (!checkpoint || checkpoint.startsWith("external::")) {
+ return MODEL_FALLBACK;
+ }
+ if (ggufVariant && !checkpoint.includes(":")) {
+ return `${checkpoint}:${ggufVariant}`;
+ }
+ return checkpoint;
+ }, [checkpoint, ggufVariant]);
+}
+
+// shiki highlighting via the app's shared code plugin + themes (same as chat).
+const SHIKI_THEMES = [unslothLightTheme, unslothDarkTheme] as [
+ typeof unslothLightTheme,
+ typeof unslothDarkTheme,
+];
+const codePlugin = createCodePlugin({ themes: SHIKI_THEMES });
+
+function HighlightedCode({
+ code,
+ language,
+}: {
+ code: string;
+ language: string;
+}) {
+ // Fence so Streamdown's shiki plugin highlights it (no markdown inside a fence).
+ const markdown = useMemo(
+ () => `\`\`\`${language}\n${code}\n\`\`\``,
+ [code, language],
+ );
+ return (
+ <div className="max-w-full overflow-x-auto p-3 pr-16 text-[11px] leading-relaxed [&_pre]:!m-0 [&_pre]:!whitespace-pre-wrap [&_pre]:!break-words [&_pre]:!border-0 [&_pre]:!bg-transparent [&_pre]:!p-0 [&_[data-streamdown=code-block]]:!my-0 [&_[data-streamdown=code-block]]:!border-0 [&_[data-streamdown=code-block]]:!bg-transparent [&_[data-streamdown=code-block]]:!p-0">
+ <Streamdown
+ mode="static"
+ plugins={{ code: codePlugin }}
+ controls={{ code: false }}
+ shikiTheme={SHIKI_THEMES}
+ >
+ {markdown}
+ </Streamdown>
+ </div>
+ );
+}
+
+export function UsageExamples({ apiKey }: { apiKey?: string | null }) {
const t = useT();
- const [lang, setLang] = useState<Lang>("curl");
+ const deviceType = usePlatformStore((s) => s.deviceType);
+ const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
+ const serverUrl = usePlatformStore((s) => s.serverUrl);
+ const secure = usePlatformStore((s) => s.secure);
+ const [lang, setLang] = useState<ExampleType>("curl");
+ const [os, setOs] = useState<Os>(
+ deviceType === "windows" ? "windows" : "unix",
+ );
const [copied, setCopied] = useState(false);
+ const [copiedUrl, setCopiedUrl] = useState(false);
+ const [useTunnel, setUseTunnel] = useState<boolean>(readUseTunnelPref);
+
+ // Tunnel may start after the first /api/health read; refresh so it surfaces here.
+ useEffect(() => {
+ void fetchDeviceType({ force: true });
+ }, []);
+
+ const model = useLoadedModelName();
+ // Real key while revealed (before "Done"); otherwise a placeholder.
+ const key = apiKey || KEY_PLACEHOLDER;
+ // Toggle on + tunnel up: public tunnel URL. Off: backend direct host:port
+ // (origin is only a last-resort fallback).
+ const origin = typeof window !== "undefined" ? window.location.origin : "";
+ const base =
+ useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin);
+
const snippets = useMemo(
- () =>
- buildSnippets(
- typeof window !== "undefined" ? window.location.origin : "",
- ),
- [],
+ () => buildSnippets(base, key, model, os),
+ [base, key, model, os],
);
+ const osAware = OS_AWARE[lang];
+ const shikiLang = CURL_TYPES.has(lang)
+ ? os === "windows"
+ ? "powershell"
+ : "bash"
+ : "python";
+
const handleCopy = async () => {
if (await copyToClipboard(snippets[lang])) {
setCopied(true);
@@ -97,16 +380,86 @@ export function UsageExamples() {
}
};
+ const handleToggleTunnel = (next: boolean) => {
+ setUseTunnel(next);
+ writeUseTunnelPref(next);
+ };
+
+ const handleCopyUrl = async () => {
+ if (cloudflareUrl && (await copyToClipboard(cloudflareUrl))) {
+ setCopiedUrl(true);
+ setTimeout(() => setCopiedUrl(false), 1800);
+ }
+ };
+
return (
<section className="flex min-w-0 max-w-full flex-col">
<h2 className="mb-2 text-sm font-semibold text-foreground">
{t("settings.apiKeys.usageExamples")}
</h2>
<div className="min-w-0 max-w-full overflow-hidden rounded-lg border border-border bg-muted/20">
+ {cloudflareUrl ? (
+ <div className="flex min-w-0 items-center justify-between gap-2 border-b border-border px-2 py-1.5">
+ <div className="flex shrink-0 items-center gap-1.5">
+ <Switch
+ size="sm"
+ checked={useTunnel}
+ onCheckedChange={handleToggleTunnel}
+ aria-label={t("settings.apiKeys.secureHttps")}
+ />
+ <span className="text-[11px] font-medium text-foreground">
+ {t("settings.apiKeys.secureHttps")}
+ </span>
+ {/* Only when not launched with --secure: the raw 0.0.0.0 port is
+ still globally reachable, so point the user at --secure. */}
+ {!secure ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ className="flex items-center rounded text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={t("settings.apiKeys.secureHttpsHint")}
+ >
+ <HugeiconsIcon
+ icon={InformationCircleIcon}
+ className="size-3.5"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-[260px] text-[11px] leading-snug">
+ {t("settings.apiKeys.secureHttpsHint")}
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
+ </div>
+ {/* Always rendered (dimmed when off) so toggling never changes the
+ row height and shifts the code block below. */}
+ <button
+ type="button"
+ onClick={handleCopyUrl}
+ className={cn(
+ "flex min-w-0 items-center gap-1 rounded px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ !useTunnel && "opacity-50",
+ )}
+ title={cloudflareUrl}
+ aria-label={t("settings.apiKeys.copyTunnelUrl")}
+ >
+ <span className="truncate font-mono">{cloudflareUrl}</span>
+ <HugeiconsIcon
+ icon={copiedUrl ? Tick02Icon : Copy01Icon}
+ className={cn(
+ "size-3.5 shrink-0",
+ copiedUrl && "text-emerald-600",
+ )}
+ />
+ </button>
+ </div>
+ ) : null}
<div className="flex min-w-0 items-center justify-between gap-2 border-b border-border px-2 py-1.5">
- <div className="flex min-w-0 items-center gap-0.5">
- {TABS.map((tab) => {
+ <div className="flex min-w-0 flex-wrap items-center gap-0.5">
+ {TYPE_TABS.map((tab) => {
const active = lang === tab.id;
+ const labelKey = TYPE_LABEL_KEY[tab.id];
return (
<button
key={tab.id}
@@ -120,17 +473,47 @@ export function UsageExamples() {
: "text-muted-foreground hover:text-foreground",
)}
>
- {tab.id === "tools"
- ? t("settings.apiKeys.usageTools")
- : tab.label}
+ {labelKey ? t(labelKey) : tab.label}
</button>
);
})}
</div>
+ </div>
+ {osAware ? (
+ <div className="flex min-w-0 items-center gap-0.5 border-b border-border px-2 py-1.5">
+ <button
+ type="button"
+ onClick={() => setOs("unix")}
+ aria-pressed={os === "unix"}
+ className={cn(
+ "rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ os === "unix"
+ ? "bg-foreground/[0.08] text-foreground dark:bg-white/[0.12]"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {t("settings.apiKeys.osUnix")}
+ </button>
+ <button
+ type="button"
+ onClick={() => setOs("windows")}
+ aria-pressed={os === "windows"}
+ className={cn(
+ "rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ os === "windows"
+ ? "bg-foreground/[0.08] text-foreground dark:bg-white/[0.12]"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {t("settings.apiKeys.osWindows")}
+ </button>
+ </div>
+ ) : null}
+ <div className="relative min-w-0">
<button
type="button"
onClick={handleCopy}
- className="flex items-center gap-1 rounded px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ className="absolute right-2 top-2 z-10 flex items-center gap-1 rounded border border-border bg-background/80 px-1.5 py-1 text-[11px] text-muted-foreground backdrop-blur transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label={t("settings.apiKeys.copySnippet")}
>
<HugeiconsIcon
@@ -139,10 +522,15 @@ export function UsageExamples() {
/>
{copied ? t("settings.apiKeys.copied") : t("settings.apiKeys.copy")}
</button>
+ {/* key on the snippet so Streamdown remounts and re-highlights when
+ only a substring (e.g. the base URL) changes; its block memo
+ otherwise keeps the stale render. */}
+ <HighlightedCode
+ key={snippets[lang]}
+ code={snippets[lang]}
+ language={shikiLang}
+ />
</div>
- <pre className="max-w-full overflow-x-auto whitespace-pre-wrap break-words p-3 font-mono text-[11px] leading-relaxed text-foreground">
- {snippets[lang]}
- </pre>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-border px-3 py-2 text-[11px] text-muted-foreground">
<span>{t("settings.apiKeys.setupDocs")}</span>
{DOC_LINKS.map((link) => (
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 d490d6b23a5..64f3ef66214 100644
--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
@@ -166,7 +166,7 @@ export function ApiKeysTab() {
)}
</section>
- <UsageExamples />
+ <UsageExamples apiKey={revealed} />
<Dialog open={revokeTarget !== null} onOpenChange={(o) => !o && setRevokeTarget(null)}>
<DialogContent className="max-w-md">
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 41964d9475a..8998322ced8 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -288,6 +288,16 @@ export const en = {
copyNow: "Copy now - this won't be shown again.",
usageExamples: "Usage examples",
usageTools: "Tools",
+ exampleCurlTools: "curl + tools",
+ examplePythonTools: "Python + tools",
+ exampleCurlAdvanced: "curl + advanced",
+ examplePythonAdvanced: "Python + advanced",
+ osUnix: "Linux / macOS / WSL",
+ osWindows: "Windows",
+ secureHttps: "Secure HTTPS",
+ secureHttpsHint:
+ "The 0.0.0.0 port is still reachable globally. For full security, launch Unsloth Studio with --secure to expose only this HTTPS link.",
+ copyTunnelUrl: "Copy tunnel URL",
copySnippet: "Copy snippet",
copy: "Copy",
copied: "Copied",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index e7e377564e3..9141a4c104c 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -261,6 +261,16 @@ export const zhCN = {
copyNow: "็Žฐๅœจๅคๅˆถ - ไน‹ๅŽไธไผšๅ†ๆฌกๆ˜พ็คบใ€‚",
usageExamples: "ไฝฟ็”จ็คบไพ‹",
usageTools: "ๅทฅๅ…ท",
+ exampleCurlTools: "curl + ๅทฅๅ…ท",
+ examplePythonTools: "Python + ๅทฅๅ…ท",
+ exampleCurlAdvanced: "curl + ้ซ˜็บง",
+ examplePythonAdvanced: "Python + ้ซ˜็บง",
+ osUnix: "Linux / macOS / WSL",
+ osWindows: "Windows",
+ secureHttps: "ๅฎ‰ๅ…จ HTTPS",
+ secureHttpsHint:
+ "0.0.0.0 ็ซฏๅฃไปๅฏ่ขซๅ…จ็ฝ‘่ฎฟ้—ฎใ€‚ๅฆ‚้œ€ๅฎŒๅ…จๅฎ‰ๅ…จ๏ผŒ่ฏทไฝฟ็”จ --secure ๅฏๅŠจ Unsloth Studio๏ผŒไป…ๆšด้œฒๆญค HTTPS ้“พๆŽฅใ€‚",
+ copyTunnelUrl: "ๅคๅˆถ้šง้“้“พๆŽฅ",
copySnippet: "ๅคๅˆถไปฃ็ ็‰‡ๆฎต",
copy: "ๅคๅˆถ",
copied: "ๅทฒๅคๅˆถ",
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 400625363cf..69df81acad8 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -661,6 +661,13 @@ def studio_default(
"--cloudflare/--no-cloudflare",
help = "Auto-create a free Cloudflare HTTPS tunnel when bound to 0.0.0.0 (default on).",
),
+ secure: bool = typer.Option(
+ False,
+ "--secure/--not-secure",
+ help = "Expose ONLY a Cloudflare HTTPS link: bind localhost and fail closed "
+ "if the tunnel can't start. Without it, --not-secure also serves the raw "
+ "0.0.0.0 port, which is reachable from anywhere on the network.",
+ ),
):
"""Launch the Unsloth Studio server."""
# Runs before every subcommand (run/setup/update/...).
@@ -688,8 +695,29 @@ def studio_default(
err = True,
)
raise typer.Exit(2)
+ # Same for --secure: it would not reach the subcommand.
+ if secure:
+ typer.echo(
+ f"Error: --secure on `unsloth studio` applies to the "
+ f"plain-server path only. For `unsloth studio "
+ f"{ctx.invoked_subcommand}`, put it after the subcommand: "
+ f"`unsloth studio {ctx.invoked_subcommand} --secure ...`",
+ err = True,
+ )
+ raise typer.Exit(2)
return
+ # --secure requires the tunnel; force a loopback bind.
+ if secure:
+ if not cloudflare:
+ typer.echo(
+ "Error: --secure requires the Cloudflare tunnel; do not combine it "
+ "with --no-cloudflare.",
+ err = True,
+ )
+ raise typer.Exit(2)
+ host = "127.0.0.1"
+
# Use the studio venv if it exists and we aren't already in it.
studio_venv_dir = STUDIO_HOME / "unsloth_studio"
in_studio_venv = sys.prefix.startswith(str(studio_venv_dir))
@@ -724,6 +752,7 @@ def studio_default(
args.append("--api-only")
# Forward the explicit polarity (matches run.py's BooleanOptionalAction).
args.append("--cloudflare" if cloudflare else "--no-cloudflare")
+ args.append("--secure" if secure else "--not-secure")
# On Windows os.execvp keeps the parent alive, so Ctrl+C
# would orphan the child; use Popen+wait instead.
if sys.platform == "win32":
@@ -766,6 +795,7 @@ def studio_default(
api_only = api_only,
llama_parallel_slots = parallel,
cloudflare = cloudflare,
+ secure = secure,
)
if frontend is not None:
run_kwargs["frontend_path"] = frontend
@@ -943,6 +973,13 @@ def run(
"--cloudflare/--no-cloudflare",
help = "Auto-create a free Cloudflare HTTPS tunnel when bound to 0.0.0.0 (default on).",
),
+ secure: bool = typer.Option(
+ False,
+ "--secure/--not-secure",
+ help = "Expose ONLY a Cloudflare HTTPS link: bind localhost and fail closed "
+ "if the tunnel can't start. Without it, --not-secure also serves the raw "
+ "0.0.0.0 port, which is reachable from anywhere on the network.",
+ ),
tensor_parallel: bool = typer.Option(
False,
"--tensor-parallel/--no-tensor-parallel",
@@ -1011,12 +1048,27 @@ def run(
model = parsed_repo
gguf_variant = gguf_variant or embedded_variant
+ # --secure requires the tunnel; force a loopback bind so the raw port is never public.
+ if secure:
+ if not cloudflare:
+ typer.echo(
+ "Error: --secure requires the Cloudflare tunnel; do not combine it "
+ "with --no-cloudflare.",
+ err = True,
+ )
+ raise typer.Exit(2)
+ host = "127.0.0.1"
+
+ # Gate tools on the *public* exposure: --secure is public via the tunnel, so
+ # tools default off even though the bind is loopback.
+ tool_policy_host = "0.0.0.0" if secure else host
+
# Resolve tool policy here so the re-exec'd child inherits a
# concrete decision and never re-prompts.
from unsloth_cli._tool_policy import is_external_host, resolve_tool_policy
enable_tools = resolve_tool_policy(
- host = host,
+ host = tool_policy_host,
flag = enable_tools,
yes = yes,
silent = silent,
@@ -1065,15 +1117,15 @@ def run(
args.append("--enable-tools")
else:
args.append("--disable-tools")
- # Forward --yes if the parent already cleared the network-bind
- # prompt, else the child re-prompts.
- if yes or (enable_tools and is_external_host(host)):
+ # Forward --yes if the parent already cleared the network-bind prompt.
+ if yes or (enable_tools and is_external_host(tool_policy_host)):
args.append("--yes")
# Typer claims --parallel outside ctx.args; without this the
# child reverts to its default and silently drops the value.
args.extend(["--parallel", str(parallel)])
# Forward the explicit polarity (same rationale as --load-in-4bit above).
args.append("--cloudflare" if cloudflare else "--no-cloudflare")
+ args.append("--secure" if secure else "--not-secure")
args.append("--tensor-parallel" if tensor_parallel else "--no-tensor-parallel")
# llama-server pass-through extras โ†’ child ctx.args โ†’ load payload.
if extra_llama_args:
@@ -1106,6 +1158,7 @@ def run(
silent = True,
llama_parallel_slots = parallel,
cloudflare = cloudflare,
+ secure = secure,
)
if frontend is not None:
run_kwargs["frontend_path"] = frontend
@@ -1157,22 +1210,26 @@ def run(
display_host = run_mod._resolve_external_ip() if host == "0.0.0.0" else host
base_url = f"http://{display_host}:{actual_port}"
sdk_base_url = f"{base_url}/v1"
- # run_server started the tunnel during the silent run above (0.0.0.0 only).
+ # run_server started the tunnel during the silent run above (0.0.0.0 or --secure).
_cf_url = getattr(app.state, "cloudflare_url", None)
+ # --secure: examples must use the public tunnel URL, not the loopback address.
+ if secure and _cf_url:
+ sdk_base_url = f"{_cf_url}/v1"
# Orange so the tool-policy notice stands out; printed under
# --silent / --yes too so the policy is never invisible.
_tool_notice_fg = (217, 119, 87)
- _is_external = is_external_host(host)
+ _is_external = is_external_host(tool_policy_host)
+ _exposure = "the public Cloudflare tunnel" if secure else host
if _is_external and enable_tools:
_tool_notice = (
- f"Server-side tools are ENABLED on {host} (network-reachable). "
+ f"Server-side tools are ENABLED on {_exposure} (network-reachable). "
f"Anyone with the API key can run code on this machine. "
f"Do not share the API key."
)
elif _is_external:
_tool_notice = (
- f"Server-side tools are disabled by default on {host} "
+ f"Server-side tools are disabled by default on {_exposure} "
f"(network-reachable). Pass --enable-tools to turn on "
f"(you will be warned about API-key risk)."
)
@@ -1187,9 +1244,13 @@ def run(
if not silent:
typer.echo("")
typer.echo("=" * 56)
- typer.echo(f" Unsloth Studio running at {base_url}")
- if _cf_url:
- typer.echo(f" Secure link access via Cloudflare: {_cf_url}")
+ if secure and _cf_url:
+ typer.echo(f" Unsloth Studio running (secure) at {_cf_url}")
+ typer.echo(f" On this machine only: {base_url}")
+ else:
+ typer.echo(f" Unsloth Studio running at {base_url}")
+ if _cf_url:
+ typer.echo(f" Secure link access via Cloudflare: {_cf_url}")
typer.echo(f" Model loaded: {loaded_model}{display_variant}")
if context_length_line:
typer.echo(context_length_line)
@@ -1224,9 +1285,13 @@ def run(
typer.echo("")
else:
# Silent still prints URL + API key + tool-status policy.
- typer.echo(f"URL: {base_url}")
- if _cf_url:
- typer.echo(f"Secure link access via Cloudflare: {_cf_url}")
+ if secure and _cf_url:
+ typer.echo(f"URL: {_cf_url}")
+ typer.echo(f"Local: {base_url}")
+ else:
+ typer.echo(f"URL: {base_url}")
+ if _cf_url:
+ typer.echo(f"Secure link access via Cloudflare: {_cf_url}")
if context_length_line:
typer.echo(context_length_line.strip())
typer.echo(f"API Key: {api_key}")
diff --git a/unsloth_cli/tests/test_studio_secure_flag.py b/unsloth_cli/tests/test_studio_secure_flag.py
new file mode 100644
index 00000000000..2c6f1ebf9eb
--- /dev/null
+++ b/unsloth_cli/tests/test_studio_secure_flag.py
@@ -0,0 +1,294 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for the `--secure/--not-secure` Studio flag: option registration,
+re-exec/run_server forwarding, the forced 127.0.0.1 bind, and rejection
+alongside --no-cloudflare or before a subcommand. Modeled on
+test_studio_cloudflare_flag.py."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+if str(_REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(_REPO_ROOT))
+
+
+def _studio():
+ from unsloth_cli.commands import studio as _studio_mod
+ return _studio_mod
+
+
+_BASE = ["--model", "unsloth/Qwen3-1.7B-GGUF"]
+
+
+# โ”€โ”€ option registration โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+
+def test_run_exposes_secure_option_default_off():
+ import inspect
+
+ opt = inspect.signature(_studio().run).parameters["secure"].default
+ decls = set(getattr(opt, "param_decls", []) or [])
+ assert "--secure/--not-secure" in decls
+ assert getattr(opt, "default", None) is False
+
+
+def test_studio_default_exposes_secure_option_default_off():
+ import inspect
+
+ opt = inspect.signature(_studio().studio_default).parameters["secure"].default
+ decls = set(getattr(opt, "param_decls", []) or [])
+ assert "--secure/--not-secure" in decls
+ assert getattr(opt, "default", None) is False
+
+
+# โ”€โ”€ re-exec capture plumbing (mirrors test_studio_cloudflare_flag.py) โ”€
+
+
+class _ExecCaptured(SystemExit):
+ def __init__(self, argv):
+ super().__init__(0)
+ self.argv = list(argv)
+
+
+def _install_run_reexec_capture(monkeypatch):
+ studio_mod = _studio()
+ captured = []
+ monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")
+ fake_venv = Path("/fake/studio/venv/unsloth_studio")
+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_venv / "bin" / "python")
+ fake_bin = fake_venv / "bin" / "unsloth"
+ real_is_file = Path.is_file
+ monkeypatch.setattr(
+ Path,
+ "is_file",
+ lambda self: True if str(self) == str(fake_bin) else real_is_file(self),
+ )
+ from unsloth_cli import _tool_policy as _tp_mod
+
+ monkeypatch.setattr(
+ _tp_mod,
+ "resolve_tool_policy",
+ lambda host, flag, yes, silent: False if flag is None else bool(flag),
+ )
+ monkeypatch.setattr(sys, "platform", "linux")
+
+ def fake_execvp(file, argv):
+ captured.append(list(argv))
+ raise _ExecCaptured(argv)
+
+ monkeypatch.setattr(studio_mod.os, "execvp", fake_execvp)
+ return captured
+
+
+def _invoke_run(monkeypatch, args):
+ import typer as _typer
+
+ captured = _install_run_reexec_capture(monkeypatch)
+ app = _typer.Typer()
+ app.command(
+ context_settings = {"allow_extra_args": True, "ignore_unknown_options": True},
+ )(_studio().run)
+ CliRunner().invoke(app, args, catch_exceptions = True)
+ return captured
+
+
+def _invoke_studio_default(monkeypatch, args):
+ import typer as _typer
+
+ studio_mod = _studio()
+ captured = []
+ monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")
+ monkeypatch.setattr(studio_mod, "_ensure_studio_env_exported", lambda: None)
+ fake_venv = Path("/fake/studio/venv/unsloth_studio")
+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_venv / "bin" / "python")
+ monkeypatch.setattr(studio_mod, "_find_run_py", lambda: Path("/fake/studio/run.py"))
+ monkeypatch.setattr(studio_mod, "_find_frontend_dist", lambda: None)
+ monkeypatch.setattr(sys, "platform", "linux")
+
+ def fake_execvp(file, argv):
+ captured.append(list(argv))
+ raise _ExecCaptured(argv)
+
+ monkeypatch.setattr(studio_mod.os, "execvp", fake_execvp)
+ app = _typer.Typer()
+ app.command()(studio_mod.studio_default)
+ CliRunner().invoke(app, args, catch_exceptions = True)
+ return captured
+
+
+# โ”€โ”€ re-exec forwarding โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+
+ "user_flag,expected,unexpected",
+ [
+ (None, "--not-secure", "--secure"), # default off
+ ("--secure", "--secure", "--not-secure"),
+ ("--not-secure", "--not-secure", "--secure"),
+ ],
+)
+def test_run_reexec_forwards_secure_polarity(monkeypatch, user_flag, expected, unexpected):
+ extras = [user_flag] if user_flag else []
+ captured = _invoke_run(monkeypatch, _BASE + extras)
+ assert len(captured) == 1, captured
+ argv = captured[0]
+ assert expected in argv and unexpected not in argv, argv
+
+
+def test_run_secure_forces_localhost_in_reexec(monkeypatch):
+ # `unsloth studio run -H 0.0.0.0 --secure` must re-exec with --host 127.0.0.1.
+ captured = _invoke_run(monkeypatch, _BASE + ["-H", "0.0.0.0", "--secure"])
+ assert len(captured) == 1, captured
+ argv = captured[0]
+ assert "--secure" in argv
+ assert argv[argv.index("--host") + 1] == "127.0.0.1", argv
+
+
+def test_studio_default_reexec_forwards_secure(monkeypatch):
+ captured = _invoke_studio_default(monkeypatch, ["-H", "0.0.0.0", "--secure"])
+ assert len(captured) == 1, captured
+ argv = captured[0]
+ assert "--secure" in argv
+ # studio_default also forces the loopback bind under --secure.
+ assert argv[argv.index("--host") + 1] == "127.0.0.1", argv
+
+
+# โ”€โ”€ in-venv path forwards secure + forced host into run_server โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+
+class _RunServerCaptured(SystemExit):
+ def __init__(self, kwargs):
+ super().__init__(0)
+ self.kwargs = dict(kwargs)
+
+
+def test_run_in_venv_passes_secure_and_forces_host(monkeypatch):
+ import types
+
+ studio_mod = _studio()
+ fake_venv = Path("/fake/studio/venv/unsloth_studio")
+ monkeypatch.setattr(sys, "prefix", str(fake_venv))
+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", fake_venv.parent)
+
+ from unsloth_cli import _tool_policy as _tp_mod
+
+ monkeypatch.setattr(
+ _tp_mod,
+ "resolve_tool_policy",
+ lambda host, flag, yes, silent: False if flag is None else bool(flag),
+ )
+
+ captured: dict = {}
+
+ def fake_run_server(**kwargs):
+ captured.update(kwargs)
+ raise _RunServerCaptured(kwargs)
+
+ fake_backend_run = sys.modules.setdefault(
+ "studio.backend.run", types.ModuleType("studio.backend.run")
+ )
+ fake_backend_run.run_server = fake_run_server
+ fake_backend_run._resolve_external_ip = lambda: "127.0.0.1"
+ monkeypatch.setattr(studio_mod, "_RUN_MODULE", fake_backend_run)
+
+ import typer as _typer
+
+ app = _typer.Typer()
+ app.command(
+ context_settings = {"allow_extra_args": True, "ignore_unknown_options": True},
+ )(studio_mod.run)
+ CliRunner().invoke(app, _BASE + ["-H", "0.0.0.0", "--secure"], catch_exceptions = True)
+
+ assert captured.get("secure") is True, captured
+ assert captured.get("host") == "127.0.0.1", captured
+
+
+# โ”€โ”€ --secure + --no-cloudflare is rejected โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+
+def test_run_secure_rejects_no_cloudflare(monkeypatch):
+ studio_mod = _studio()
+ import typer as _typer
+
+ app = _typer.Typer()
+ app.command(
+ context_settings = {"allow_extra_args": True, "ignore_unknown_options": True},
+ )(studio_mod.run)
+ result = CliRunner().invoke(app, _BASE + ["--secure", "--no-cloudflare"])
+ assert result.exit_code == 2, result.output
+
+
+def test_studio_default_rejects_secure_with_subcommand():
+ import typer as _typer
+
+ studio_mod = _studio()
+ app = _typer.Typer()
+ app.add_typer(studio_mod.studio_app, name = "studio")
+ result = CliRunner().invoke(app, ["studio", "--secure", "run", "--model", "X"])
+ assert result.exit_code == 2, result.output
+ combined = (result.output or "") + (getattr(result, "stderr", "") or "")
+ assert "--secure" in combined, combined
+
+
+# โ”€โ”€ secure resolves tools against the PUBLIC exposure, not the loopback bind โ”€โ”€
+
+
+def test_run_secure_resolves_tools_against_public_host(monkeypatch):
+ # --secure is public via the tunnel, so tools resolve against 0.0.0.0 (OFF), not loopback (ON).
+ studio_mod = _studio()
+ monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")
+ fake_venv = Path("/fake/studio/venv/unsloth_studio")
+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_venv / "bin" / "python")
+ fake_bin = fake_venv / "bin" / "unsloth"
+ real_is_file = Path.is_file
+ monkeypatch.setattr(
+ Path,
+ "is_file",
+ lambda self: True if str(self) == str(fake_bin) else real_is_file(self),
+ )
+ monkeypatch.setattr(sys, "platform", "linux")
+
+ from unsloth_cli import _tool_policy as _tp_mod
+
+ calls = []
+
+ def rec(host, flag, yes, silent):
+ calls.append(host)
+ return (not _tp_mod.is_external_host(host)) if flag is None else bool(flag)
+
+ monkeypatch.setattr(_tp_mod, "resolve_tool_policy", rec)
+
+ captured = []
+
+ def fake_execvp(file, argv):
+ captured.append(list(argv))
+ raise _ExecCaptured(argv)
+
+ monkeypatch.setattr(studio_mod.os, "execvp", fake_execvp)
+
+ import typer as _typer
+
+ app = _typer.Typer()
+ app.command(
+ context_settings = {"allow_extra_args": True, "ignore_unknown_options": True},
+ )(studio_mod.run)
+ CliRunner().invoke(app, _BASE + ["-H", "0.0.0.0", "--secure"], catch_exceptions = True)
+
+ assert calls and calls[0] == "0.0.0.0", calls
+ assert len(captured) == 1, captured
+ assert "--disable-tools" in captured[0] and "--enable-tools" not in captured[0], captured[0]
+
+
+def test_run_secure_enable_tools_forwards_yes(monkeypatch):
+ # Enabling tools on a secure endpoint forwards --yes so the child doesn't re-prompt.
+ captured = _invoke_run(monkeypatch, _BASE + ["-H", "0.0.0.0", "--secure", "--enable-tools"])
+ assert len(captured) == 1, captured
+ argv = captured[0]
+ assert "--enable-tools" in argv and "--yes" in argv, argv