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.

feat(studio): add settings-managed remote access (#7875)

Long Yixing4a4509c1562f
diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.py
index 2e9520827e1..b5214f6ac16 100644
--- a/studio/backend/auth/authentication.py
+++ b/studio/backend/auth/authentication.py
@@ -186,6 +186,17 @@ async def authenticated_via_api_key(
return bool(credentials and credentials.credentials.startswith(API_KEY_PREFIX))
+async def authenticated_via_desktop_jwt(
+ credentials: HTTPAuthorizationCredentials = Depends(security),
+) -> bool:
+ """True when the caller is the local desktop app, not a browser session or API key.
+
+ Lets routes treat the desktop as an authority of its own: it authenticates
+ with a local secret rather than the account password.
+ """
+ return is_desktop_access_token(credentials.credentials)
+
+
async def get_current_subject_allow_password_change(
credentials: HTTPAuthorizationCredentials = Depends(security),
) -> str:
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py
index 6cf4d44834b..e1b885083b1 100644
--- a/studio/backend/auth/storage.py
+++ b/studio/backend/auth/storage.py
@@ -705,6 +705,7 @@ def update_password(
*,
revoke_refresh_tokens: bool = False,
expect_password_hash: Optional[str] = None,
+ preserve_desktop_secret: bool = False,
) -> Optional[str]:
"""Update password, clear first-login requirement, rotate JWT secret.
@@ -720,6 +721,11 @@ def update_password(
caller verified still being current, so a request that checked the old
password cannot overwrite a reset that landed while it was in flight.
Returns False when the credential moved underneath it.
+
+ ``preserve_desktop_secret`` keeps the local desktop credential valid. It is
+ for a caller that already authenticated as the desktop app: revoking the
+ secret it is currently using would break desktop auto-auth for a change the
+ desktop itself made.
"""
from .hashing import hash_password
@@ -750,7 +756,8 @@ def update_password(
conn.commit()
if cursor.rowcount > 0:
clear_bootstrap_password()
- clear_desktop_secret()
+ if not preserve_desktop_secret:
+ clear_desktop_secret()
return jwt_secret
return None
finally:
diff --git a/studio/backend/cloudflare_tunnel.py b/studio/backend/cloudflare_tunnel.py
index f7967e2faa0..f9d7a0cb813 100644
--- a/studio/backend/cloudflare_tunnel.py
+++ b/studio/backend/cloudflare_tunnel.py
@@ -22,7 +22,7 @@ import sys
import threading
import time
from pathlib import Path
-from typing import Optional, Tuple
+from typing import Callable, Optional, Tuple
# cloudflared logs the quick-tunnel URL; match only the URL so we do not depend
# on the surrounding wording, which Cloudflare may change. The negative lookahead
@@ -56,6 +56,21 @@ _DNS_POLL_DELAY = 2.0
# Retry transient DoH failures, but give up fast when DoH is blocked outright.
_DNS_MAX_DOH_ERRORS = 3
_DOH_URL = "https://cloudflare-dns.com/dns-query?name={host}&type=A"
+# The resolver negative-caches a miss of its own, so a query sent before the
+# record can exist blinds the poll for that cache's lifetime. Hold off first.
+_DNS_INITIAL_GRACE = 3.0
+# A blinded poll cannot recover, so bound its share of the shared deadline.
+_DNS_WAIT_MAX = 20.0
+
+# Cloudflare's edge routes by TLS SNI, so it serves the tunnel as soon as the
+# connection registers -- before the hostname resolves anywhere. Probing there
+# keeps DNS off the startup path entirely.
+_EDGE_HOST = "trycloudflare.com"
+_EDGE_PROBE_RETRY_DELAY = 0.5
+# Bound the wait so the hostname fallback keeps most of the shared deadline.
+_EDGE_WAIT_MAX = 15.0
+# A network that blocks the edge blocks every attempt, so stop spending the wait.
+_EDGE_MAX_UNREACHABLE = 2
def _windows_hidden_kwargs() -> dict:
@@ -76,6 +91,16 @@ def _lifetime_kwargs() -> dict:
return {}
+def _spawn_child(spawn):
+ """Fork on a process-lifetime thread so the PDEATHSIG above means "die with
+ the parent process", not "die when the worker thread that forked me returns"."""
+ try:
+ from utils.process_lifetime import spawn_on_lifetime_thread
+ except Exception:
+ return spawn()
+ return spawn_on_lifetime_thread(spawn)
+
+
def _asset_name() -> Optional[Tuple[str, bool]]:
"""(release asset filename, is_tgz) for this OS/arch, or None if unsupported."""
system = platform.system().lower()
@@ -212,6 +237,10 @@ def _wait_for_dns(host: str, deadline: float) -> None:
import json
import urllib.request
+ now = time.monotonic()
+ deadline = min(deadline, now + _DNS_WAIT_MAX)
+ if deadline > now:
+ time.sleep(min(_DNS_INITIAL_GRACE, deadline - now))
errors = 0
while True:
answered = False
@@ -235,6 +264,85 @@ def _wait_for_dns(host: str, deadline: float) -> None:
time.sleep(min(_DNS_POLL_DELAY, remaining))
+def _edge_addresses() -> list:
+ """Distinct Cloudflare frontends, from a name that resolves before any tunnel exists."""
+ import socket
+
+ addresses = []
+ try:
+ resolved = socket.getaddrinfo(_EDGE_HOST, 443, type = socket.SOCK_STREAM)
+ except Exception:
+ return addresses
+ for info in resolved:
+ address = info[4][0]
+ # macOS reports the A records as IPv4-mapped under AF_INET6. The mapped
+ # and bare forms are one frontend, and probing it twice buys nothing.
+ if address.startswith("::ffff:"):
+ address = address[len("::ffff:") :]
+ if address not in addresses:
+ addresses.append(address)
+ return addresses[:2]
+
+
+def _probe_edge(
+ address: str,
+ host: str,
+ timeout: float = _PUBLIC_PROBE_ATTEMPT_TIMEOUT,
+) -> Optional[bool]:
+ """Ask the edge for the marker as ``host``. None when the edge is unreachable."""
+ import http.client
+ import json
+ import socket
+ import ssl
+
+ request = (
+ f"GET {_PUBLIC_PROBE_PATH} HTTP/1.1\r\nHost: {host}\r\n"
+ "User-Agent: unsloth-studio\r\nConnection: close\r\n\r\n"
+ ).encode()
+ try:
+ with socket.create_connection((address, 443), timeout = timeout) as raw:
+ with ssl.create_default_context().wrap_socket(raw, server_hostname = host) as tls:
+ tls.sendall(request)
+ response = http.client.HTTPResponse(tls, method = "GET")
+ response.begin()
+ body = response.read(4096)
+ except Exception:
+ return None
+ try:
+ return json.loads(body).get("service") == _PUBLIC_PROBE_MARKER
+ except Exception:
+ return False
+
+
+def _verify_through_edge(host: str, deadline: float) -> bool:
+ """Verify at the edge, which selects the tunnel by SNI rather than by address.
+
+ Error 1033 and an intercepting proxy's own page are both answers and are not
+ told apart here, so only the marker ends the wait. Nothing answering at all
+ is this path being blocked, which the hostname may still get through.
+ """
+ addresses = _edge_addresses()
+ if not addresses:
+ return False
+ deadline = min(deadline, time.monotonic() + _EDGE_WAIT_MAX)
+ unreachable = 0
+ while True:
+ for address in addresses:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return False
+ answer = _probe_edge(address, host, min(_PUBLIC_PROBE_ATTEMPT_TIMEOUT, remaining))
+ if answer:
+ return True
+ unreachable = unreachable + 1 if answer is None else 0
+ if unreachable >= _EDGE_MAX_UNREACHABLE:
+ return False
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return False
+ time.sleep(min(_EDGE_PROBE_RETRY_DELAY, remaining))
+
+
def verify_public_url(url: str, timeout: float = _PUBLIC_PROBE_TIMEOUT) -> bool:
import json
import urllib.request
@@ -243,6 +351,10 @@ def verify_public_url(url: str, timeout: float = _PUBLIC_PROBE_TIMEOUT) -> bool:
deadline = time.monotonic() + timeout
host = urlsplit(url).hostname
if host:
+ if _verify_through_edge(host, deadline):
+ return True
+ # The edge never served the tunnel, so fall back to the hostname and pay
+ # the DoH wait that keeps an early OS lookup from caching the miss.
_wait_for_dns(host, deadline)
probe_url = f"{url.rstrip('/')}{_PUBLIC_PROBE_PATH}"
@@ -261,6 +373,13 @@ def verify_public_url(url: str, timeout: float = _PUBLIC_PROBE_TIMEOUT) -> bool:
time.sleep(min(_PUBLIC_PROBE_RETRY_DELAY, remaining))
+def _process_exited(proc: subprocess.Popen) -> bool:
+ try:
+ return proc.poll() is not None
+ except Exception:
+ return False
+
+
class CloudflareTunnel:
"""A cloudflared quick tunnel to http://localhost:<port>. Best-effort throughout.
@@ -287,6 +406,9 @@ class CloudflareTunnel:
self.url: Optional[str] = None
self.ready = False
self.error: Optional[str] = None
+ self.on_exit: Optional[Callable[["CloudflareTunnel"], None]] = None
+ self._reader_exited = False
+ self._runtime_active = False
def start(self) -> None:
cmd = [
@@ -304,18 +426,27 @@ class CloudflareTunnel:
# orphan a process nobody owns, so refuse.
if self._stopped:
return
- proc = subprocess.Popen(
- cmd,
- stdout = subprocess.PIPE,
- stderr = subprocess.STDOUT,
- stdin = subprocess.DEVNULL,
- text = True,
- encoding = "utf-8",
- errors = "replace",
- bufsize = 1,
- **_windows_hidden_kwargs(),
- **_lifetime_kwargs(),
- )
+ _set_studio_tunnel_runtime_active(self, True)
+ try:
+ # PDEATHSIG binds to the forking thread, so spawning from the
+ # settings start worker would kill cloudflared when it returned.
+ proc = _spawn_child(
+ lambda: subprocess.Popen(
+ cmd,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ stdin = subprocess.DEVNULL,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ bufsize = 1,
+ **_windows_hidden_kwargs(),
+ **_lifetime_kwargs(),
+ )
+ )
+ except Exception:
+ _set_studio_tunnel_runtime_active(self, False)
+ raise
self._proc = proc
threading.Thread(
target = self._reader, args = (proc,), name = "cloudflared-reader", daemon = True
@@ -345,8 +476,17 @@ class CloudflareTunnel:
self.error = "cloudflared exited before emitting a tunnel URL"
elif not self.ready:
self.error = "cloudflared exited before the tunnel connection registered"
+ else:
+ self.error = "cloudflared exited"
self._url_event.set()
self._ready_event.set()
+ with self._lock:
+ self._reader_exited = True
+ callback = self.on_exit
+ if _process_exited(proc):
+ _set_studio_tunnel_runtime_active(self, False)
+ if callback is not None:
+ callback(self)
def wait_for_ready(self, timeout: float = _READY_TIMEOUT) -> Optional[str]:
"""Block until the tunnel is actually serving -- the URL has been minted
@@ -357,14 +497,17 @@ class CloudflareTunnel:
self._ready_event.wait(timeout)
return self.url if self.ready else None
- def stop(self) -> None:
- """Terminate the tunnel. Idempotent and safe to call from a signal handler."""
+ def stop(self) -> bool:
+ """Terminate the tunnel and report whether process exit was confirmed."""
with self._lock:
# Mark stopped so a start() racing behind us refuses to spawn.
self._stopped = True
proc, self._proc = self._proc, None
if proc is None:
- return
+ active = _studio_tunnel_runtime_active(self)
+ if active:
+ _retain_studio_tunnel_for_stop(self)
+ return not active
try:
if proc.poll() is None:
proc.terminate()
@@ -378,18 +521,225 @@ class CloudflareTunnel:
pass
except Exception:
pass
+ if _process_exited(proc):
+ _set_studio_tunnel_runtime_active(self, False)
+ return True
+ else:
+ # Preserve both the stop handle and the fail-closed trust state when
+ # termination could not be confirmed. A later stop can retry.
+ with self._lock:
+ if self._proc is None:
+ self._proc = proc
+ _retain_studio_tunnel_for_stop(self)
+ return False
+
+ def is_running(self) -> bool:
+ with self._lock:
+ proc = self._proc
+ try:
+ return proc is not None and proc.poll() is None
+ except Exception:
+ return False
+
+ def set_on_exit(self, callback: Callable[["CloudflareTunnel"], None]) -> None:
+ with self._lock:
+ self.on_exit = callback
+ reader_exited = self._reader_exited
+ if reader_exited:
+ callback(self)
+
+ def _publish_if_running(self, callback: Callable[[], None]) -> bool:
+ with self._lock:
+ try:
+ running = (
+ not self._reader_exited and self._proc is not None and self._proc.poll() is None
+ )
+ except Exception:
+ running = False
+ if running:
+ callback()
+ return running
# Single serving process per Unsloth launch, so one module-level tunnel handle is
# enough; the lock guards the start/stop/shutdown races.
_active_tunnel: Optional[CloudflareTunnel] = None
_active_lock = threading.Lock()
+_start_lock = threading.Lock()
# Latched by stop_studio_tunnel so a shutdown landing *between* a start's retry
# attempts aborts the loop instead of starting a tunnel nobody will ever stop.
_shutdown_requested = False
+_tunnel_generation = 0
+_tunnel_lifecycle = 0
+_accepting_starts = True
+_tunnel_state = "off"
+_tunnel_owner: Optional[str] = None
+_tunnel_url: Optional[str] = None
+_tunnel_error: Optional[str] = None
+_tunnel_port: Optional[int] = None
+_tunnel_url_callback: Optional[Callable[[Optional[str]], None]] = None
+_tunnel_runtime_callback: Optional[Callable[[bool], None]] = None
+_tunnel_runtime_lock = threading.Lock()
+_tunnel_runtime_count = 0
+_tunnels_pending_stop = set()
+_TUNNEL_OWNERS = frozenset({"launch", "settings", "colab"})
+
+
+def _set_studio_tunnel_runtime_active(tunnel: CloudflareTunnel, active: bool) -> None:
+ global _tunnel_runtime_count
+ with _tunnel_runtime_lock:
+ if not active:
+ _tunnels_pending_stop.discard(tunnel)
+ if tunnel._runtime_active == active:
+ return
+ tunnel._runtime_active = active
+ _tunnel_runtime_count += 1 if active else -1
+ if _tunnel_runtime_callback is not None:
+ try:
+ _tunnel_runtime_callback(_tunnel_runtime_count > 0)
+ except Exception:
+ pass
+
+
+def _studio_tunnel_runtime_active(tunnel: CloudflareTunnel) -> bool:
+ with _tunnel_runtime_lock:
+ return tunnel._runtime_active
+
+
+def _retain_studio_tunnel_for_stop(tunnel: CloudflareTunnel) -> None:
+ with _tunnel_runtime_lock:
+ if tunnel._runtime_active:
+ _tunnels_pending_stop.add(tunnel)
+
+
+def _tunnels_pending_stop_snapshot() -> tuple:
+ with _tunnel_runtime_lock:
+ return tuple(_tunnels_pending_stop)
-def start_studio_tunnel(port: int, timeout: float = _READY_TIMEOUT) -> Optional[str]:
+def set_studio_tunnel_runtime_callback(callback: Optional[Callable[[bool], None]]) -> None:
+ global _tunnel_runtime_callback
+ with _tunnel_runtime_lock:
+ _tunnel_runtime_callback = callback
+ if callback is not None:
+ try:
+ callback(_tunnel_runtime_count > 0)
+ except Exception:
+ pass
+
+
+def open_studio_tunnel_lifecycle() -> None:
+ """Open a new backend lifecycle and invalidate workers from any prior one."""
+ global _tunnel_lifecycle, _accepting_starts
+ with _active_lock:
+ _tunnel_lifecycle += 1
+ _accepting_starts = True
+
+
+def capture_studio_tunnel_start_admission() -> Optional[Tuple[int, int]]:
+ """Capture the lifecycle/generation that admitted an asynchronous start."""
+ with _active_lock:
+ if not _accepting_starts:
+ return None
+ return (_tunnel_lifecycle, _tunnel_generation)
+
+
+def get_studio_tunnel_control_token() -> Tuple[int, int]:
+ """Return the current lifecycle/generation for worker bookkeeping."""
+ with _active_lock:
+ return (_tunnel_lifecycle, _tunnel_generation)
+
+
+def _set_tunnel_url_locked(url: Optional[str]) -> None:
+ global _tunnel_url
+ _tunnel_url = url
+ if _tunnel_url_callback is not None:
+ try:
+ _tunnel_url_callback(url)
+ except Exception:
+ pass
+
+
+def set_studio_tunnel_url_callback(callback: Optional[Callable[[Optional[str]], None]]) -> None:
+ global _tunnel_url_callback
+ with _active_lock:
+ _tunnel_url_callback = callback
+ _set_tunnel_url_locked(_tunnel_url)
+
+
+def get_studio_tunnel_status() -> dict:
+ with _active_lock:
+ return {
+ "state": _tunnel_state,
+ "managed_by": _tunnel_owner,
+ "url": _tunnel_url,
+ "error": _tunnel_error,
+ "port": _tunnel_port,
+ "stop_pending": bool(_tunnels_pending_stop_snapshot()),
+ }
+
+
+def _set_failed(generation: int, owner: str, port: int, error: str) -> None:
+ global _tunnel_state, _tunnel_owner, _tunnel_url, _tunnel_error, _tunnel_port
+ with _active_lock:
+ if generation != _tunnel_generation or _shutdown_requested:
+ return
+ _tunnel_state = "error"
+ _tunnel_owner = owner
+ _set_tunnel_url_locked(None)
+ _tunnel_error = error
+ _tunnel_port = port
+
+
+def _active_tunnel_exited(tunnel: CloudflareTunnel) -> None:
+ global _active_tunnel, _tunnel_state, _tunnel_owner
+ global _tunnel_url, _tunnel_error, _tunnel_port
+ with _active_lock:
+ if _active_tunnel is not tunnel:
+ return
+ if _tunnel_state == "stopping":
+ return
+ generation = _tunnel_generation
+ exit_owner, exit_port = _tunnel_owner, _tunnel_port
+ exit_error = tunnel.error or "cloudflared exited"
+ _tunnel_state = "stopping"
+ _set_tunnel_url_locked(None)
+ _tunnel_error = None
+ stopped = tunnel.stop() is not False
+ with _active_lock:
+ stopped = stopped or not _studio_tunnel_runtime_active(tunnel)
+ if not stopped and (_active_tunnel is None or _active_tunnel is tunnel):
+ _active_tunnel = tunnel
+ _tunnel_state = "error"
+ _tunnel_owner = exit_owner
+ _tunnel_error = "cloudflared could not be stopped"
+ _tunnel_port = exit_port
+ elif generation == _tunnel_generation:
+ _active_tunnel = None
+ _tunnel_state = "error"
+ _tunnel_error = exit_error
+ elif stopped and _active_tunnel is tunnel:
+ _active_tunnel = None
+ _tunnel_state = "off"
+ _tunnel_owner = None
+ _tunnel_error = None
+ _tunnel_port = None
+
+
+def _set_online_locked(url: str) -> None:
+ global _tunnel_state, _tunnel_url, _tunnel_error
+ _tunnel_state = "online"
+ _set_tunnel_url_locked(url)
+ _tunnel_error = None
+
+
+def start_studio_tunnel(
+ port: int,
+ timeout: float = _READY_TIMEOUT,
+ *,
+ managed_by: str = "launch",
+ admission: Optional[Tuple[int, int]] = None,
+) -> Optional[str]:
"""Start a quick tunnel and return its public URL once it is actually
serving, or None (best-effort).
@@ -400,66 +750,204 @@ def start_studio_tunnel(port: int, timeout: float = _READY_TIMEOUT) -> Optional[
is blocked on this network), retries once forcing the http2 protocol. On any
failure the tunnel is stopped and None is returned.
"""
- global _active_tunnel, _shutdown_requested
- binary = ensure_cloudflared()
- if not binary:
- return None
+ global _active_tunnel, _shutdown_requested, _tunnel_generation
+ global _tunnel_state, _tunnel_owner, _tunnel_url, _tunnel_error, _tunnel_port
+ if managed_by not in _TUNNEL_OWNERS:
+ raise ValueError(f"Unknown Cloudflare tunnel owner: {managed_by}")
with _active_lock:
- _shutdown_requested = False # fresh session
- # Default protocol first (quic, with cloudflared's own http2 fallback); if a
- # URL appears but no connection registers, quic is likely blocked -> retry
- # once forcing http2.
- for protocol in (None, "http2"):
- # Create + register under the lock, and bail if a stop already landed
- # (e.g. between this and the previous attempt) so we never start a tunnel
- # after shutdown has run.
+ if not _accepting_starts or _tunnel_state == "stopping" or _tunnels_pending_stop_snapshot():
+ return None
+ if admission is not None and admission != (_tunnel_lifecycle, _tunnel_generation):
+ return None
+ requested_generation = _tunnel_generation
+ with _start_lock:
with _active_lock:
- if _shutdown_requested:
- _active_tunnel = None
+ if (
+ _tunnel_state == "online"
+ and _tunnel_owner == managed_by
+ and _tunnel_port == port
+ and _active_tunnel is not None
+ ):
+ return _tunnel_url
+ if (
+ not _accepting_starts
+ or requested_generation != _tunnel_generation
+ or _tunnel_state == "stopping"
+ or _tunnels_pending_stop_snapshot()
+ or (admission is not None and admission != (_tunnel_lifecycle, _tunnel_generation))
+ ):
return None
- tunnel = CloudflareTunnel(port, binary, protocol = protocol)
- prior, _active_tunnel = _active_tunnel, tunnel
- if prior is not None:
- prior.stop()
- registered = False
- try:
- tunnel.start()
- url = tunnel.wait_for_ready(timeout)
- registered = url is not None
- if url and not verify_public_url(url):
- url = None
- except Exception:
- url = None
- if url:
- return url
- saw_url = tunnel.url is not None
- # Not ready: drop it, but only if we are still the active tunnel.
- with _active_lock:
- was_active = _active_tunnel is tunnel
- if was_active:
- _active_tunnel = None
- tunnel.stop()
- # A concurrent shutdown or start took over while we waited; retrying would
- # spawn a tunnel nobody owns (orphaned after shutdown), so bail instead.
- if not was_active:
+ _shutdown_requested = False
+ _tunnel_generation += 1
+ generation = _tunnel_generation
+ prior_at_start, _active_tunnel = _active_tunnel, None
+ _tunnel_state = "starting"
+ _tunnel_owner = managed_by
+ _set_tunnel_url_locked(None)
+ _tunnel_error = None
+ _tunnel_port = port
+ if prior_at_start is not None and prior_at_start.stop() is False:
+ with _active_lock:
+ if generation == _tunnel_generation:
+ _active_tunnel = prior_at_start
+ _tunnel_state = "error"
+ _tunnel_error = "cloudflared could not be stopped"
return None
- # No URL at all is an API/network failure, not a protocol one; forcing
- # http2 will not help, so do not burn another window on it.
- if not saw_url:
- return None
- # probe failure after registering is DNS propagation; http2 would not help
- if registered:
+
+ binary = ensure_cloudflared()
+ if not binary:
+ _set_failed(generation, managed_by, port, "cloudflared is unavailable")
return None
- return None
+
+ for protocol in (None, "http2"):
+ with _active_lock:
+ if _shutdown_requested or generation != _tunnel_generation:
+ _active_tunnel = None
+ return None
+ tunnel = CloudflareTunnel(port, binary, protocol = protocol)
+ prior, _active_tunnel = _active_tunnel, tunnel
+ if prior is not None and prior.stop() is False:
+ with _active_lock:
+ if generation == _tunnel_generation and _active_tunnel is tunnel:
+ _active_tunnel = prior
+ _tunnel_state = "error"
+ _tunnel_error = "cloudflared could not be stopped"
+ return None
+ registered = False
+ try:
+ tunnel.start()
+ url = tunnel.wait_for_ready(timeout)
+ registered = url is not None
+ if url and not verify_public_url(url):
+ url = None
+ except Exception:
+ url = None
+ if url:
+ if hasattr(tunnel, "set_on_exit"):
+ tunnel.set_on_exit(_active_tunnel_exited)
+ else:
+ tunnel.on_exit = _active_tunnel_exited
+ aborted = False
+ with _active_lock:
+ if (
+ generation != _tunnel_generation
+ or _shutdown_requested
+ or _active_tunnel is not tunnel
+ ):
+ # Stop/shutdown landed while coming up. Detach AND tear
+ # down: returning this URL would leave a live public
+ # tunnel no later stop_studio_tunnel() can reach.
+ aborted = True
+ was_active = False
+ if _active_tunnel is tunnel:
+ _active_tunnel = None
+ else:
+ if hasattr(tunnel, "_publish_if_running"):
+ running = tunnel._publish_if_running(lambda: _set_online_locked(url))
+ else:
+ _set_online_locked(url)
+ running = True
+ if running:
+ was_active = True
+ else:
+ _active_tunnel = None
+ _tunnel_state = "error"
+ _set_tunnel_url_locked(None)
+ _tunnel_error = tunnel.error or "cloudflared exited"
+ was_active = False
+ if aborted or not was_active:
+ tunnel.stop()
+ return None
+ if hasattr(tunnel, "is_running") and not tunnel.is_running():
+ _active_tunnel_exited(tunnel)
+ return None
+ return url
+ saw_url = tunnel.url is not None
+ with _active_lock:
+ was_active = _active_tunnel is tunnel
+ if was_active:
+ _tunnel_state = "stopping"
+ stopped = tunnel.stop() is not False
+ with _active_lock:
+ stopped = stopped or not _studio_tunnel_runtime_active(tunnel)
+ if _shutdown_requested and _active_tunnel is tunnel:
+ if stopped:
+ _active_tunnel = None
+ _tunnel_state = "off"
+ _tunnel_owner = None
+ _tunnel_error = None
+ _tunnel_port = None
+ else:
+ _tunnel_state = "error"
+ _tunnel_error = "cloudflared could not be stopped"
+ elif generation == _tunnel_generation and _active_tunnel is tunnel:
+ if stopped:
+ _active_tunnel = None
+ # Attempt 1's teardown parked the state at "stopping".
+ # Leaving it there for the http2 retry makes
+ # stop_studio_tunnel() early-return and stop nothing.
+ if _tunnel_state == "stopping" and protocol is None:
+ _tunnel_state = "starting"
+ else:
+ _active_tunnel = tunnel
+ _tunnel_state = "error"
+ _tunnel_error = "cloudflared could not be stopped"
+ if not was_active:
+ return None
+ if not stopped:
+ return None
+ if not saw_url:
+ _set_failed(generation, managed_by, port, "cloudflared did not produce a URL")
+ return None
+ if registered:
+ _set_failed(generation, managed_by, port, "Cloudflare URL was not reachable")
+ return None
+ _set_failed(generation, managed_by, port, "cloudflared did not register a connection")
+ return None
-def stop_studio_tunnel() -> None:
+def stop_studio_tunnel(*, admission: Optional[Tuple[int, int]] = None) -> None:
"""Terminate the active tunnel, if any. Idempotent."""
- global _active_tunnel, _shutdown_requested
+ global _active_tunnel, _shutdown_requested, _tunnel_generation
+ global _tunnel_state, _tunnel_owner, _tunnel_url, _tunnel_error, _tunnel_port
with _active_lock:
+ if admission is not None and admission != (_tunnel_lifecycle, _tunnel_generation):
+ return
+ if _tunnel_state == "stopping":
+ _shutdown_requested = True
+ _tunnel_generation += 1
+ return
# Latch so an in-flight start_studio_tunnel won't start a fresh tunnel
# (e.g. its http2 retry) after we have already torn down.
_shutdown_requested = True
- tunnel, _active_tunnel = _active_tunnel, None
- if tunnel is not None:
- tunnel.stop()
+ _tunnel_generation += 1
+ stop_generation = _tunnel_generation
+ tunnel = _active_tunnel
+ pending = _tunnels_pending_stop_snapshot()
+ tunnels = list(dict.fromkeys(((tunnel,) if tunnel is not None else ()) + pending))
+ _tunnel_state = "stopping" if tunnels else "off"
+ _set_tunnel_url_locked(None)
+ _tunnel_error = None
+ for candidate in tunnels:
+ candidate.stop()
+ with _active_lock:
+ if stop_generation == _tunnel_generation or _tunnel_state == "stopping":
+ pending = _tunnels_pending_stop_snapshot()
+ if pending:
+ _active_tunnel = pending[0]
+ _tunnel_state = "error"
+ _tunnel_error = "cloudflared could not be stopped"
+ else:
+ _active_tunnel = None
+ _tunnel_state = "off"
+ _tunnel_owner = None
+ _tunnel_port = None
+
+
+def close_studio_tunnel_lifecycle() -> None:
+ """Permanently reject queued starts for this backend lifecycle, then stop."""
+ global _tunnel_lifecycle, _accepting_starts
+ with _active_lock:
+ _accepting_starts = False
+ _tunnel_lifecycle += 1
+ stop_studio_tunnel()
diff --git a/studio/backend/colab.py b/studio/backend/colab.py
index bf4a6a44b5e..e3b93861926 100644
--- a/studio/backend/colab.py
+++ b/studio/backend/colab.py
@@ -381,12 +381,13 @@ def start_cloudflare_tunnel(port: int) -> "str | None":
)
return None
try:
- from cloudflare_tunnel import start_studio_tunnel
+ from cloudflare_tunnel import set_studio_tunnel_url_callback, start_studio_tunnel
except Exception as e:
logger.info(f"Cloudflare tunnel unavailable ({e}); using Colab proxy only.")
return None
try:
- url = start_studio_tunnel(port)
+ set_studio_tunnel_url_callback(_publish_cloudflare_url)
+ url = start_studio_tunnel(port, managed_by = "colab")
except Exception as e:
logger.info(f"Cloudflare tunnel failed to start ({e}); using Colab proxy only.")
return None
@@ -397,14 +398,6 @@ def start_cloudflare_tunnel(port: int) -> "str | None":
def _publish_cloudflare_url(cloudflare_url: "str | None") -> None:
- """Publish a directly-started tunnel URL onto app.state so /api/health advertises it.
-
- run_server sets this only when it opens the tunnel itself (skipped on Colab), so we
- set it here; otherwise the frontend's API examples fall back to an unreachable
- server_url. Best-effort.
- """
- if not cloudflare_url:
- return
try:
from main import app as _studio_app
_studio_app.state.cloudflare_url = cloudflare_url
@@ -419,12 +412,6 @@ def _stop_cloudflare_tunnel() -> None:
stop_studio_tunnel()
except Exception:
pass
- # Stop /api/health advertising a dead tunnel.
- try:
- from main import app as _studio_app
- _studio_app.state.cloudflare_url = None
- except Exception:
- pass
def _is_studio_healthy(port: int, timeout: float = 2.0) -> bool:
@@ -645,7 +632,6 @@ def start(port: int = 8888, *, cloudflare: "bool | None" = None):
try:
colab_login = _finalize_colab_admin_password() if use_cloudflare else None
cf_url = start_cloudflare_tunnel(port) if use_cloudflare else None
- _publish_cloudflare_url(cf_url)
_show_and_embed(
port,
cloudflare_url = cf_url,
@@ -716,7 +702,6 @@ def start(port: int = 8888, *, cloudflare: "bool | None" = None):
try:
colab_login = _finalize_colab_admin_password() if use_cloudflare else None
cf_url = start_cloudflare_tunnel(actual_port) if use_cloudflare else None
- _publish_cloudflare_url(cf_url)
_show_and_embed(
actual_port,
cloudflare_url = cf_url,
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index 98112c6d5bb..488e34e5d09 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -148,9 +148,9 @@ def stdio_mcp_enabled() -> bool:
if os.environ.get("UNSLOTH_STUDIO_ALLOW_STDIO_MCP") != "1":
return False
from state.tool_policy import get_tool_policy
- from utils.host_policy import loopback_default_active
+ from utils.host_policy import loopback_default_active, remote_connector_active
- if loopback_default_active() and get_tool_policy() is False:
+ if loopback_default_active() and (remote_connector_active() or get_tool_policy() is False):
return False
return True
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 1616020e3c8..a298e3a97da 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -368,9 +368,13 @@ def _load_desktop_owner() -> dict[str, str] | None:
_DESKTOP_OWNER = _load_desktop_owner()
-# The Tauri desktop app runs the backend locally, so stdio MCP servers are safe; "0" opts out.
+# The Tauri desktop app runs the backend locally, so stdio MCP servers are safe ("0" opts
+# out). Tracked as an automatic loopback default so publishing a runtime tunnel can suspend
+# it without overriding an explicit operator choice.
if _DESKTOP_OWNER:
- os.environ.setdefault("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")
+ from utils.host_policy import apply_stdio_mcp_loopback_default as _apply_desktop_stdio_default
+ _apply_desktop_stdio_default("127.0.0.1")
+ del _apply_desktop_stdio_default
def _desktop_owner() -> dict[str, str] | None:
@@ -1124,19 +1128,45 @@ async def _recipes_redirect(rest: str = ""):
from utils.host_policy import cors_origins_for_mode # noqa: E402
+
+class RemoteAccessCORSMiddleware(CORSMiddleware):
+ """Allow remote browser origins only while a Cloudflare URL is published."""
+
+ def __init__(self, cors_app, *, remote_access_state, **kwargs):
+ self.remote_access_state = remote_access_state
+ super().__init__(cors_app, **kwargs)
+
+ def is_allowed_origin(self, origin: str) -> bool:
+ return bool(
+ getattr(self.remote_access_state, "cloudflare_url", None)
+ ) or super().is_allowed_origin(origin)
+
+
_cors_origins = cors_origins_for_mode(
api_only = os.environ.get("UNSLOTH_API_ONLY") == "1",
secure = os.environ.get("UNSLOTH_SECURE") == "1",
)
app.add_middleware(
- CORSMiddleware,
+ RemoteAccessCORSMiddleware,
+ remote_access_state = app.state,
allow_origins = _cors_origins,
allow_credentials = True,
allow_methods = ["*"],
allow_headers = ["*"],
+ # is_allowed_origin closes the moment the tunnel URL clears, but a preflight
+ # already cached by the browser does not. Measured in WebKit: with Starlette's
+ # 600s default, a state-changing request still REACHED the server after remote
+ # access was stopped (Chromium/Firefox/Edge re-preflighted). Keep the stale
+ # window short so revocation is nearly as immediate as every other trust
+ # signal here.
+ max_age = 60,
)
+from utils.remote_access_settings import RemoteAccessStopResponseMiddleware # noqa: E402
+
+app.add_middleware(RemoteAccessStopResponseMiddleware)
+
# ============ Register API Routes ============
@@ -1871,7 +1901,37 @@ class _AssetGZipMiddleware(GZipMiddleware):
await super().__call__(scope, receive, send)
-def setup_frontend(app: FastAPI, build_path: Path):
+def _is_live_cloudflare_frontend_request(scope, app_state) -> bool:
+ cloudflare_url = getattr(app_state, "cloudflare_url", None)
+ headers = dict(scope.get("headers", ()))
+ if not cloudflare_url or not headers.get(b"cf-connecting-ip"):
+ return False
+ try:
+ expected_host = urlparse(cloudflare_url).hostname
+ request_host = urlparse(f"//{headers.get(b'host', b'').decode('latin-1')}").hostname
+ except (UnicodeDecodeError, ValueError):
+ return False
+ return bool(expected_host) and request_host == expected_host
+
+
+class _TunnelOnlyFrontend:
+ def __init__(self, frontend_app, app_state):
+ self.frontend_app = frontend_app
+ self.app_state = app_state
+
+ async def __call__(self, scope, receive, send):
+ if scope["type"] != "http" or _is_live_cloudflare_frontend_request(scope, self.app_state):
+ await self.frontend_app(scope, receive, send)
+ return
+ await Response(status_code = 404)(scope, receive, send)
+
+
+def setup_frontend(
+ app: FastAPI,
+ build_path: Path,
+ *,
+ tunnel_only: bool = False,
+):
"""Mount frontend static files (optional)"""
if not build_path.exists():
return False
@@ -1883,8 +1943,13 @@ def setup_frontend(app: FastAPI, build_path: Path):
minimum_size = 1024,
compresslevel = 6,
)
+ if tunnel_only:
+ assets_app = _TunnelOnlyFrontend(assets_app, app.state)
app.mount("/assets", assets_app, name = "assets")
+ def _frontend_request_allowed(request: Request) -> bool:
+ return not tunnel_only or _is_live_cloudflare_frontend_request(request.scope, app.state)
+
def _build_index_response(request: Request) -> Response:
content = (build_path / "index.html").read_bytes()
content = _strip_crossorigin(content)
@@ -1908,6 +1973,8 @@ def setup_frontend(app: FastAPI, build_path: Path):
@app.get("/")
async def serve_root(request: Request):
+ if not _frontend_request_allowed(request):
+ return Response(status_code = 404)
return _build_index_response(request)
@app.get("/{full_path:path}")
@@ -1916,6 +1983,8 @@ def setup_frontend(app: FastAPI, build_path: Path):
# for /v1/* ({"detail": ...} for /api/*). The request path is "/" + full_path.
if full_path in {"api", "v1"} or full_path.startswith(("api/", "v1/")):
raise HTTPException(status_code = 404, detail = "API endpoint not found")
+ if not _frontend_request_allowed(request):
+ return Response(status_code = 404)
file_path = (build_path / full_path).resolve()
diff --git a/studio/backend/models/auth.py b/studio/backend/models/auth.py
index 2283aa709f9..52e01ea0720 100644
--- a/studio/backend/models/auth.py
+++ b/studio/backend/models/auth.py
@@ -43,6 +43,16 @@ class AuthStatusResponse(BaseModel):
)
+class DesktopInitialPasswordRequest(BaseModel):
+ """Set the seeded admin's first real password from the desktop app."""
+
+ new_password: str = Field(
+ ...,
+ min_length = MIN_PASSWORD_LENGTH,
+ description = f"Replacement password (minimum {MIN_PASSWORD_LENGTH} characters)",
+ )
+
+
class ChangePasswordRequest(BaseModel):
"""Change the current user's password, typically on first login."""
diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.py
index fe2f09fcd9d..73e6a78cbb0 100644
--- a/studio/backend/routes/auth.py
+++ b/studio/backend/routes/auth.py
@@ -23,12 +23,14 @@ from models.auth import (
ChangePasswordRequest,
CreateApiKeyRequest,
CreateApiKeyResponse,
+ DesktopInitialPasswordRequest,
DesktopLoginRequest,
RefreshTokenRequest,
)
from models.users import Token
from auth import storage, hashing
from auth.authentication import (
+ authenticated_via_desktop_jwt,
create_access_token,
create_refresh_token,
get_current_credential,
@@ -480,11 +482,81 @@ async def refresh(payload: RefreshTokenRequest) -> Token:
)
[email protected]("/desktop-initial-password", response_model = Token)
+async def set_desktop_initial_password(
+ payload: DesktopInitialPasswordRequest,
+ request: Request,
+ current_subject: str = Depends(get_current_subject_allow_password_change),
+ is_desktop: bool = Depends(authenticated_via_desktop_jwt),
+) -> Token:
+ """Set the first real password from the desktop app, which never sees the seeded one.
+
+ Desktop auth is passwordless, so the desktop user cannot complete the normal
+ flow: it needs the generated bootstrap password that only the terminal ever
+ printed. Remote browser logins do need a real password, so an
+ already-authenticated desktop session may set it while the seeded credential
+ is still in place. Once set, change-password owns every later change.
+ """
+ if not is_desktop:
+ raise HTTPException(
+ status_code = status.HTTP_403_FORBIDDEN,
+ detail = "This action requires the Unsloth desktop app.",
+ )
+
+ record = storage.get_user_and_secret(current_subject)
+ if record is None:
+ raise HTTPException(
+ status_code = status.HTTP_401_UNAUTHORIZED,
+ detail = "User session is invalid",
+ )
+
+ _salt, pwd_hash, _jwt_secret, must_change_password = record
+ if not must_change_password:
+ raise HTTPException(
+ status_code = status.HTTP_409_CONFLICT,
+ detail = "A password is already set. Change it instead.",
+ )
+ if any(ch.isspace() for ch in payload.new_password):
+ raise HTTPException(
+ status_code = status.HTTP_400_BAD_REQUEST,
+ detail = "New password cannot contain spaces",
+ )
+
+ # Conditional on the credential just read: a web password change or a
+ # reset-password landing while this request is in flight must not be
+ # overwritten by a caller that verified no password at all.
+ new_secret = storage.update_password(
+ current_subject,
+ payload.new_password,
+ revoke_refresh_tokens = True,
+ expect_password_hash = pwd_hash,
+ preserve_desktop_secret = True,
+ )
+ if new_secret is None:
+ raise HTTPException(
+ status_code = status.HTTP_409_CONFLICT,
+ detail = "The password changed while this request was in flight. Try again.",
+ )
+ try:
+ request.app.state.bootstrap_password = None
+ except AttributeError:
+ pass
+ access_token = create_access_token(subject = current_subject, desktop = True, secret = new_secret)
+ refresh_token = create_refresh_token(subject = current_subject, desktop = True, secret = new_secret)
+ return Token(
+ access_token = access_token,
+ refresh_token = refresh_token,
+ token_type = "bearer",
+ must_change_password = False,
+ )
+
+
@router.post("/change-password", response_model = Token)
async def change_password(
payload: ChangePasswordRequest,
request: Request,
current_subject: str = Depends(get_current_subject_allow_password_change),
+ is_desktop: bool = Depends(authenticated_via_desktop_jwt),
) -> Token:
"""Allow the authenticated user to replace the default password."""
record = storage.get_user_and_secret(current_subject)
@@ -515,11 +587,15 @@ async def change_password(
# password commit, leaving pre-change tokens able to mint access tokens.
# Conditional on the hash just verified: a reset-password that landed while
# this request was in flight must not be overwritten by it.
+ # The desktop app authenticates with a local secret rather than this
+ # password; revoking that secret would break its auto-auth over a change it
+ # made itself. A browser session still revokes it.
new_secret = storage.update_password(
current_subject,
payload.new_password,
revoke_refresh_tokens = True,
expect_password_hash = pwd_hash,
+ preserve_desktop_secret = is_desktop,
)
if new_secret is None:
raise HTTPException(
@@ -530,8 +606,12 @@ async def change_password(
request.app.state.bootstrap_password = None
except AttributeError:
pass
- access_token = create_access_token(subject = current_subject, secret = new_secret)
- refresh_token = create_refresh_token(subject = current_subject, secret = new_secret)
+ access_token = create_access_token(
+ subject = current_subject, desktop = is_desktop, secret = new_secret
+ )
+ refresh_token = create_refresh_token(
+ subject = current_subject, desktop = is_desktop, secret = new_secret
+ )
return Token(
access_token = access_token,
refresh_token = refresh_token,
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index f8201c79bfb..542710710ee 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -7,10 +7,10 @@ import threading
from typing import Any, Literal, Optional
from urllib.parse import unquote, urlsplit
-from fastapi import APIRouter, Depends, HTTPException
-from pydantic import BaseModel, ConfigDict, Field, field_validator
+from fastapi import APIRouter, Depends, HTTPException, Request
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, field_validator
-from auth.authentication import get_current_subject
+from auth.authentication import authenticated_via_api_key, get_current_subject
from auth.storage import rotate_preview_link_secret
from core.rag.config import default_gguf_repo, effective_gguf_repo
from loggers import get_logger
@@ -62,6 +62,13 @@ from utils.preview_sharing_settings import (
get_preview_sharing_enabled,
set_preview_sharing_enabled,
)
+from utils.remote_access_settings import (
+ DEFAULT_REMOTE_ACCESS_AUTO_START,
+ remote_access_status,
+ set_remote_access_auto_start,
+ start_remote_access,
+ stop_remote_access,
+)
from utils.embedding_model_settings import (
MAX_EMBEDDING_MODEL_LENGTH,
default_embedding_model,
@@ -921,6 +928,98 @@ class PreviewSharingResponse(BaseModel):
default_enabled: bool = DEFAULT_PREVIEW_SHARING_ENABLED
+class RemoteAccessAutoStartPayload(BaseModel):
+ enabled: StrictBool
+
+
+class RemoteAccessResponse(BaseModel):
+ state: Literal["off", "starting", "online", "stopping", "error"]
+ url: Optional[str] = None
+ error: Optional[str] = None
+ auto_start: bool
+ default_auto_start: bool = DEFAULT_REMOTE_ACCESS_AUTO_START
+ available: bool
+ managed_by: Optional[Literal["launch", "settings", "colab"]] = None
+ can_start: bool
+ can_stop: bool
+ block_reason: Optional[str] = None
+ password_pending: bool = False
+ streaming_supported: bool = True
+
+
+def _require_ui_session(via_api_key: bool = Depends(authenticated_via_api_key)) -> None:
+ if via_api_key:
+ raise HTTPException(status_code = 403, detail = "Remote access requires a UI session.")
+
+
+def _remote_access_response(request: Request) -> RemoteAccessResponse:
+ return RemoteAccessResponse(**remote_access_status(request.app.state))
+
+
[email protected]("/remote-access", response_model = RemoteAccessResponse)
+def get_remote_access(
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session),
+) -> RemoteAccessResponse:
+ return _remote_access_response(request)
+
+
[email protected]("/remote-access/start", response_model = RemoteAccessResponse)
+def start_remote_access_route(
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session),
+) -> RemoteAccessResponse:
+ try:
+ response = RemoteAccessResponse(**start_remote_access(request.app.state))
+ except RuntimeError as exc:
+ raise HTTPException(status_code = 409, detail = str(exc)) from exc
+ logger.info("settings.remote_access_start_requested subject=%s", current_subject)
+ return response
+
+
[email protected]("/remote-access/stop", response_model = RemoteAccessResponse)
+def stop_remote_access_route(
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session),
+) -> RemoteAccessResponse:
+ try:
+ status = stop_remote_access(request.app.state)
+ except RuntimeError as exc:
+ raise HTTPException(status_code = 409, detail = str(exc)) from exc
+ status.update(
+ state = "off",
+ url = None,
+ error = None,
+ managed_by = None,
+ can_start = False,
+ can_stop = False,
+ )
+ response = RemoteAccessResponse(**status)
+ logger.info("settings.remote_access_stop_requested subject=%s", current_subject)
+ return response
+
+
[email protected]("/remote-access/auto-start", response_model = RemoteAccessResponse)
+def update_remote_access_auto_start(
+ request: Request,
+ payload: RemoteAccessAutoStartPayload,
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session),
+) -> RemoteAccessResponse:
+ if bool(getattr(request.app.state, "remote_access_is_colab", False)):
+ raise HTTPException(status_code = 409, detail = "colab")
+ set_remote_access_auto_start(payload.enabled)
+ logger.info(
+ "settings.remote_access_auto_start_updated subject=%s enabled=%s",
+ current_subject,
+ payload.enabled,
+ )
+ return _remote_access_response(request)
+
+
@router.get("/preview-sharing", response_model = PreviewSharingResponse)
def get_preview_sharing(
current_subject: str = Depends(get_current_subject),
diff --git a/studio/backend/run.py b/studio/backend/run.py
index c9bfda62dac..ca97404066a 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -1170,8 +1170,8 @@ def _graceful_shutdown(server = None):
# 6. Stop the Cloudflare tunnel (if started).
try:
- from cloudflare_tunnel import stop_studio_tunnel
- stop_studio_tunnel()
+ from cloudflare_tunnel import close_studio_tunnel_lifecycle
+ close_studio_tunnel_lifecycle()
except Exception as e:
logger.warning("Error stopping Cloudflare tunnel: %s", e)
@@ -1227,6 +1227,13 @@ _shutdown_event = None
# None when there is no tunnel (loopback, disabled, or a silently-ignored failure).
_cloudflare_url = None
+
+def _publish_cloudflare_url(app_state, cloudflare_url: "Optional[str]") -> None:
+ global _cloudflare_url
+ _cloudflare_url = cloudflare_url
+ app_state.cloudflare_url = cloudflare_url
+
+
# Public reachability from the last _verify_global_reachability run, read by the
# Cloudflare banner line. True when the public ip:port probe confirmed reachable,
# False when it confirmed NOT reachable, None when the probe did not run or could
@@ -1318,6 +1325,22 @@ def _resolve_frontend_path(frontend_path: Path) -> tuple[Optional[Path], list[Pa
return None, attempted
+def _frontend_serving_mode(*, api_only: bool, desktop_owned: bool) -> tuple[bool, bool]:
+ tunnel_only = api_only and desktop_owned
+ return not api_only or tunnel_only, tunnel_only
+
+
+def _missing_frontend_is_fatal(*, tunnel_only: bool) -> bool:
+ """Whether an unresolvable SPA build must abort startup.
+
+ It must when the web UI is this launch's own surface: a 404 on / is worse
+ than a loud error. It must not for the desktop, which passes --api-only with
+ no --frontend and whose installer skips the frontend build outright; there
+ the SPA only backs the optional remote web UI, so aborting would kill the
+ local API before TAURI_PORT is ever emitted. Degrade to API-only instead."""
+ return not tunnel_only
+
+
class _TeeStream:
"""Mirror writes to the original stream and a session log file.
@@ -1514,6 +1537,39 @@ def _cloudflare_tunnel_should_start(
return host in ("0.0.0.0", "::") and not api_only
+def _final_bound_port(server, requested_port: int) -> int:
+ """Resolve Uvicorn's OS-assigned port after readiness for ``port=0``."""
+ if requested_port > 0:
+ return requested_port
+ for listener in getattr(server, "servers", ()):
+ for sock in getattr(listener, "sockets", ()) or ():
+ address = sock.getsockname()
+ if isinstance(address, tuple) and len(address) >= 2 and int(address[1]) > 0:
+ return int(address[1])
+ raise RuntimeError("Uvicorn did not expose its final bound port")
+
+
+_CLOUDFLARE_INTENT_ENV = "_UNSLOTH_CLOUDFLARE_INTENT"
+
+
+def _consume_cloudflare_intent(cloudflare: "Optional[bool]", secure: bool) -> str:
+ """Resolve user intent without confusing a compatibility flag with opt-out.
+
+ An explicit choice on THIS invocation wins: letting the inherited marker
+ override it would let a stale export, Docker ENV or systemd Environment=
+ re-enable a tunnel the user opted out of.
+ """
+ inherited = os.environ.pop(_CLOUDFLARE_INTENT_ENV, None)
+ if secure or cloudflare is True:
+ return "enabled"
+ if cloudflare is False:
+ # Only "the parent omitted the option" softens this into unselected.
+ return "unset" if inherited == "unset" else "disabled"
+ if inherited in {"unset", "enabled", "disabled"}:
+ return inherited
+ return "unset"
+
+
def _stream_isatty(stream) -> bool:
"""isatty() that treats broken streams as non-interactive.
@@ -1756,7 +1812,8 @@ def run_server(
port: Port to bind to (auto-increments if in use)
frontend_path: Path to frontend build directory (optional)
silent: Suppress startup messages
- api_only: API server only, no frontend (for Tauri desktop app)
+ api_only: API server only, except that a Tauri-owned backend serves its
+ packaged frontend exclusively through a live Cloudflare tunnel
llama_parallel_slots: parallel slots for llama-server (default
_PARALLEL_DEFAULT_PLAIN, matching the CLI entry points)
cloudflare: opt in to the public Cloudflare HTTPS tunnel for a wildcard
@@ -1776,6 +1833,7 @@ def run_server(
boot_started = time.perf_counter()
logger.info("run_server startup begin api_only=%s host=%s port=%s", api_only, host, port)
+ cloudflare_intent = _consume_cloudflare_intent(cloudflare, secure)
# Reap every child if the parent dies abnormally (terminal close, Task
# Manager kill, SIGKILL); must run before any child can spawn.
@@ -1854,7 +1912,7 @@ def run_server(
import_started = time.perf_counter()
- from main import app, setup_frontend, _IS_COLAB
+ from main import app, setup_frontend, _desktop_owner, _IS_COLAB
logger.info(
"Imported FastAPI app in %.1fms",
@@ -1903,11 +1961,17 @@ def run_server(
print("=" * 50)
print("")
- # Setup frontend (skip in api-only). Falls back through alternate locations if
- # the default lacks a built dist; errors loudly rather than 404 on `/`.
- if frontend_path and not api_only:
+ _serve_frontend, _tunnel_only_frontend = _frontend_serving_mode(
+ api_only = api_only,
+ desktop_owned = _desktop_owner() is not None,
+ )
+
+ # A desktop-owned API-only backend mounts the packaged SPA behind a
+ # Cloudflare-only request gate so Remote access can serve the WebUI without
+ # changing the direct local API-only surface.
+ if frontend_path and _serve_frontend:
chosen, attempted = _resolve_frontend_path(Path(frontend_path))
- if chosen is not None and setup_frontend(app, chosen):
+ if chosen is not None and setup_frontend(app, chosen, tunnel_only = _tunnel_only_frontend):
if not silent:
# Resolve so logs show an absolute path for support.
try:
@@ -1915,6 +1979,13 @@ def run_server(
except OSError:
display = chosen
print(f"[OK] Frontend loaded from {display}")
+ elif not _missing_frontend_is_fatal(tunnel_only = _tunnel_only_frontend):
+ # Remote access serves nothing; the local API the desktop asked for
+ # still comes up. The tunnel gate already 404s every other request.
+ logger.warning(
+ "No frontend build found, so Remote access will not serve the web UI. Tried: %s",
+ ", ".join(str(p) for p in attempted) or "(none)",
+ )
else:
home_str = (
os.environ.get("UNSLOTH_STUDIO_HOME")
@@ -1999,6 +2070,27 @@ def run_server(
app.state.secure = secure
app.state.llama_parallel_slots = llama_parallel_slots
+ global _cloudflare_url, _cloudflare_requested, _cloudflare_flag
+ _cloudflare_url = None
+ _cloudflare_flag = cloudflare
+ app.state.cloudflare_url = None
+ from utils.remote_access_settings import configure_remote_access
+
+ _launch_tunnel_managed = _cloudflare_tunnel_should_start(
+ cloudflare = cloudflare,
+ host = host,
+ secure = secure,
+ api_only = api_only,
+ is_colab = _IS_COLAB,
+ )
+ configure_remote_access(
+ app.state,
+ port = port,
+ intent = cloudflare_intent,
+ is_colab = _IS_COLAB,
+ launch_managed = _launch_tunnel_managed,
+ )
+
# Expose a shutdown callable before the server accepts requests so
# /api/shutdown is ready as soon as readiness publishes.
def _trigger_shutdown():
@@ -2017,13 +2109,7 @@ def run_server(
# warn / fail closed headless; see _terminal_password_gate). Runs BEFORE the
# socket binds so a pre-gate listener can't hand out the injected credential.
_pw_proceed, _pw_drop_bootstrap = _terminal_password_gate(
- tunnel_will_start = _cloudflare_tunnel_should_start(
- cloudflare = cloudflare,
- host = host,
- secure = secure,
- api_only = api_only,
- is_colab = _IS_COLAB,
- ),
+ tunnel_will_start = _launch_tunnel_managed,
host = host,
secure = secure,
api_only = api_only,
@@ -2046,6 +2132,10 @@ def run_server(
app.state.suppress_bootstrap_injection = True
app.state.bootstrap_password = None
+ from cloudflare_tunnel import open_studio_tunnel_lifecycle
+
+ open_studio_tunnel_lifecycle()
+
# Run server in a daemon thread with explicit new_event_loop() +
# run_until_complete() (not asyncio.run) so nest_asyncio's patches don't
# interfere when Colab/IPython already runs a loop on the main thread.
@@ -2087,6 +2177,11 @@ def run_server(
(time.perf_counter() - boot_started) * 1000,
)
+ port = _final_bound_port(_server, port)
+ app.state.server_port = port
+ app.state.server_url = f"http://{_url_host(_display_host_for_bind(host))}:{port}"
+ app.state.remote_access_port = port
+
_write_pid_file(port, host)
import atexit
@@ -2112,34 +2207,34 @@ def run_server(
parent_pid = int(owner_pid) if owner_pid.isdigit() else None,
)
+ from cloudflare_tunnel import (
+ set_studio_tunnel_runtime_callback,
+ set_studio_tunnel_url_callback,
+ )
+ from utils.host_policy import set_remote_connector_active
+
+ set_studio_tunnel_runtime_callback(set_remote_connector_active)
+ set_studio_tunnel_url_callback(lambda url: _publish_cloudflare_url(app.state, url))
+ app.state.remote_access_ready = True
+
# Free trycloudflare.com tunnel for wildcard binds (the raw ip:port is often
# unreachable). Started pre-banner and even when silent so the CLI banner can
# read app.state.cloudflare_url; torn down by _graceful_shutdown.
- global _cloudflare_url, _cloudflare_requested, _cloudflare_flag
- _cloudflare_url = None
- _cloudflare_flag = cloudflare
- app.state.cloudflare_url = None
- _cloudflare_enabled = _cloudflare_tunnel_should_start(
- cloudflare = cloudflare,
- host = host,
- secure = secure,
- api_only = api_only,
- is_colab = _IS_COLAB,
- )
+ _cloudflare_enabled = _launch_tunnel_managed
_cloudflare_requested = _cloudflare_enabled
if _cloudflare_enabled:
try: # best-effort: any failure must not block startup
- from cloudflare_tunnel import start_studio_tunnel, stop_studio_tunnel
-
- _cloudflare_url = start_studio_tunnel(port)
- app.state.cloudflare_url = _cloudflare_url
- # Backstop: tear the tunnel down even on an abnormal exit that bypasses
- # _graceful_shutdown (e.g. an exception after startup -> sys.exit). Idempotent.
- atexit.register(stop_studio_tunnel)
+ from cloudflare_tunnel import start_studio_tunnel
+ start_studio_tunnel(port, managed_by = "launch")
except Exception as e:
logger.debug("Cloudflare tunnel skipped: %s", e)
+ # Backstop for both launch- and settings-managed tunnels on abnormal exits.
+ from cloudflare_tunnel import close_studio_tunnel_lifecycle
+
+ atexit.register(close_studio_tunnel_lifecycle)
+
# --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:
@@ -2188,6 +2283,11 @@ def run_server(
except Exception as e: # best-effort: never block startup on the timeout
logger.warning("Bootstrap timeout not armed: %s", e)
+ from utils.remote_access_settings import maybe_auto_start_remote_access
+
+ if maybe_auto_start_remote_access(app.state):
+ logger.info("Remote access auto-start scheduled")
+
if not silent:
_emit_startup_output(host, port, display_host, secure = secure, enable_tools = enable_tools)
diff --git a/studio/backend/tests/test_change_password_policy.py b/studio/backend/tests/test_change_password_policy.py
index fc095760d01..945f18c3a0a 100644
--- a/studio/backend/tests/test_change_password_policy.py
+++ b/studio/backend/tests/test_change_password_policy.py
@@ -43,7 +43,9 @@ def _change(new_password):
current_password = "bootstrap-pw",
new_password = new_password,
)
- return asyncio.run(auth_routes.change_password(payload, None, "unsloth"))
+ # is_desktop explicitly: positionally it would default to the Depends object,
+ # which is truthy, and silently take the preserve-desktop-secret branch.
+ return asyncio.run(auth_routes.change_password(payload, None, "unsloth", False))
def test_rejects_whitespace_only_password(_user):
diff --git a/studio/backend/tests/test_cloudflare_tunnel.py b/studio/backend/tests/test_cloudflare_tunnel.py
index 8d19f09baeb..866e654b8f7 100644
--- a/studio/backend/tests/test_cloudflare_tunnel.py
+++ b/studio/backend/tests/test_cloudflare_tunnel.py
@@ -16,6 +16,7 @@ import sys
import tarfile
import types
from pathlib import Path
+from typing import Optional
import pytest
@@ -319,6 +320,66 @@ def test_stop_terminates_process():
t.stop()
+def test_runtime_callback_covers_process_start_through_stop(monkeypatch):
+ events = []
+ starts_admitted = []
+ ct.set_studio_tunnel_runtime_callback(events.append)
+
+ class _ObservedPopen(_FakePopen):
+ stdout = None
+ block_termination = True
+
+ def terminate(self):
+ assert events[-1] is True
+ if self.block_termination:
+ ct.start_studio_tunnel(8081, managed_by = "settings")
+ raise OSError("termination unavailable")
+ super().terminate()
+
+ fake = _ObservedPopen()
+
+ def fake_popen(*_args, **_kwargs):
+ assert events[-1] is True
+ return fake
+
+ class _NoReaderThread:
+ def __init__(self, **_kwargs):
+ pass
+
+ def start(self):
+ pass
+
+ monkeypatch.setattr(ct.subprocess, "Popen", fake_popen)
+ monkeypatch.setattr(ct.threading, "Thread", _NoReaderThread)
+ monkeypatch.setattr(ct, "ensure_cloudflared", lambda: starts_admitted.append(True))
+ try:
+ tunnel = ct.CloudflareTunnel(8080, "/bin/cloudflared")
+ tunnel.start()
+ assert events[-1] is True
+ ct._active_tunnel = tunnel
+ ct._tunnel_state = "online"
+ ct._tunnel_owner = "settings"
+ ct._tunnel_port = 8080
+ ct._tunnel_state = "stopping"
+ ct._active_tunnel_exited(tunnel)
+ assert ct.get_studio_tunnel_status()["state"] == "stopping"
+ ct._tunnel_state = "online"
+ ct._active_tunnel_exited(tunnel)
+ assert events[-1] is True
+ assert starts_admitted == []
+ assert ct._active_tunnel is tunnel
+ assert ct.get_studio_tunnel_status()["state"] == "error"
+ assert ct.get_studio_tunnel_status()["stop_pending"] is True
+ fake.block_termination = False
+ ct.stop_studio_tunnel()
+ assert events[-1] is False
+ assert ct.get_studio_tunnel_status()["state"] == "off"
+ ct._retain_studio_tunnel_for_stop(tunnel)
+ assert ct._tunnels_pending_stop_snapshot() == ()
+ finally:
+ ct.set_studio_tunnel_runtime_callback(None)
+
+
def test_start_after_stop_does_not_spawn(monkeypatch):
# If stop() lands before start() (a concurrent shutdown in the caller's
# register->start window), start() must NOT spawn a cloudflared process --
@@ -350,6 +411,8 @@ def _fake_proc(text):
def test_reader_captures_url_and_registration():
t = ct.CloudflareTunnel(8080, "/bin/cloudflared")
+ exited = []
+ t.set_on_exit(exited.append)
t._reader(
_fake_proc(
"INF Requesting new quick Tunnel on trycloudflare.com...\n"
@@ -360,7 +423,8 @@ def test_reader_captures_url_and_registration():
assert t.url == "https://words-here-abc.trycloudflare.com"
assert t.ready is True
assert t.wait_for_ready(0) == t.url
- assert t.error is None # a fully-registered tunnel records no error
+ assert t.error == "cloudflared exited"
+ assert exited == [t]
def test_reader_url_without_registration_is_not_ready():
@@ -426,9 +490,10 @@ def _patch_urlopen(monkeypatch, handler):
@pytest.fixture(autouse = True)
-def _stub_dns_wait(monkeypatch, request):
+def _stub_remote_lookups(monkeypatch, request):
if request.node.name.startswith("test_verify_public_url"):
monkeypatch.setattr(ct, "_wait_for_dns", lambda *a, **kw: None)
+ monkeypatch.setattr(ct, "_edge_addresses", list)
def test_wait_for_dns_polls_until_answer(monkeypatch):
@@ -445,6 +510,8 @@ def test_wait_for_dns_polls_until_answer(monkeypatch):
ct._wait_for_dns("words.trycloudflare.com", ct.time.monotonic() + 5)
assert len(calls) == 3
assert "name=words.trycloudflare.com" in calls[0]
+ # The tunnel provider already knows the hostname it just issued; no one else does.
+ assert all("cloudflare-dns.com" in call for call in calls)
def test_wait_for_dns_gives_up_at_deadline(monkeypatch):
@@ -481,6 +548,40 @@ def test_wait_for_dns_bails_on_persistent_doh_errors(monkeypatch):
assert len(calls) == ct._DNS_MAX_DOH_ERRORS
+def test_wait_for_dns_delays_first_query(monkeypatch):
+ order = []
+
+ def handler(req):
+ order.append("query")
+ return _FakeResponse(b'{"Status":0,"Answer":[{"data":"104.16.0.1"}]}')
+
+ _patch_urlopen(monkeypatch, handler)
+ monkeypatch.setattr(ct.time, "sleep", lambda s: order.append(("sleep", s)))
+ ct._wait_for_dns("words.trycloudflare.com", ct.time.monotonic() + 30)
+ # a token hold-off would not outlast the propagation that makes the first query miss
+ assert ct._DNS_INITIAL_GRACE >= 1.0
+ assert order[0] == ("sleep", ct._DNS_INITIAL_GRACE)
+ assert order[1] == "query"
+
+
+def test_wait_for_dns_is_capped_below_the_probe_deadline(monkeypatch):
+ clock = [0.0]
+ calls = []
+
+ def handler(req):
+ calls.append(req.full_url)
+ return _FakeResponse(b'{"Status":3}')
+
+ _patch_urlopen(monkeypatch, handler)
+ monkeypatch.setattr(ct.time, "monotonic", lambda: clock[0])
+ monkeypatch.setattr(ct.time, "sleep", lambda s: clock.__setitem__(0, clock[0] + s))
+ ct._wait_for_dns("words.trycloudflare.com", 300.0)
+ assert calls
+ assert clock[0] <= ct._DNS_WAIT_MAX + ct._DNS_POLL_DELAY
+ # The probe shares one deadline with the wait and needs most of it.
+ assert clock[0] < ct._PUBLIC_PROBE_TIMEOUT / 2
+
+
def test_verify_public_url_accepts_studio_marker(monkeypatch):
seen = {}
@@ -493,7 +594,7 @@ def test_verify_public_url_accepts_studio_marker(monkeypatch):
assert seen["url"] == "https://words.trycloudflare.com/api/health"
-def test_verify_public_url_waits_for_dns_first(monkeypatch):
+def test_verify_public_url_waits_for_dns_before_probing_the_hostname(monkeypatch):
order = []
monkeypatch.setattr(ct, "_wait_for_dns", lambda host, deadline: order.append(("dns", host)))
@@ -552,6 +653,191 @@ def test_verify_public_url_rejects_foreign_responder(monkeypatch):
assert ct.verify_public_url("https://words.trycloudflare.com", timeout = 0.05) is False
+def _fake_edge(
+ monkeypatch,
+ payload: bytes,
+ connect_error: Optional[str] = None,
+) -> dict:
+ """Stand in for the TLS hop so the probe's own parsing is under test."""
+ import socket as socket_module
+ import ssl as ssl_module
+
+ seen: dict = {}
+
+ class _Closeable:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_a):
+ return False
+
+ class _Tls(_Closeable):
+ def sendall(self, data):
+ seen["request"] = data
+
+ def makefile(self, *_a, **_kw):
+ return io.BytesIO(payload)
+
+ class _Context:
+ # A default context verifies the chain and matches it against the SNI
+ # name; the probe dials a bare address, so that match is the only thing
+ # binding the answer to the tunnel.
+ check_hostname = True
+ verify_mode = ssl_module.CERT_REQUIRED
+
+ def wrap_socket(
+ self,
+ _raw,
+ server_hostname = None,
+ ):
+ seen["sni"] = server_hostname
+ seen["verified"] = self.check_hostname and self.verify_mode == ssl_module.CERT_REQUIRED
+ return _Tls()
+
+ def connect(address, timeout = None):
+ seen["timeout"] = timeout
+ if connect_error is not None:
+ raise OSError(connect_error)
+ seen["address"] = address
+ return _Closeable()
+
+ monkeypatch.setattr(socket_module, "create_connection", connect)
+ monkeypatch.setattr(ssl_module, "create_default_context", _Context)
+ return seen
+
+
+def _edge_response(status: bytes, body: bytes) -> bytes:
+ return b"HTTP/1.1 %s\r\nContent-Length: %d\r\n\r\n%s" % (status, len(body), body)
+
+
+def test_edge_probe_selects_the_tunnel_by_sni(monkeypatch):
+ seen = _fake_edge(monkeypatch, _edge_response(b"200 OK", b'{"service":"Unsloth UI Backend"}'))
+ assert ct._probe_edge("104.16.0.1", "words.trycloudflare.com") is True
+ assert seen["address"] == ("104.16.0.1", 443)
+ # Cloudflare picks the tunnel from SNI and the Host header, not the address.
+ assert seen["sni"] == "words.trycloudflare.com"
+ assert seen["verified"] is True
+ assert seen["timeout"] == ct._PUBLIC_PROBE_ATTEMPT_TIMEOUT
+ assert seen["request"].startswith(f"GET {ct._PUBLIC_PROBE_PATH} HTTP/1.1\r\n".encode())
+ assert b"Host: words.trycloudflare.com\r\n" in seen["request"]
+
+
+def test_edge_probe_rejects_the_cloudflare_error_page(monkeypatch):
+ _fake_edge(monkeypatch, _edge_response(b"530 ", b"<html>error 1033</html>"))
+ assert ct._probe_edge("104.16.0.1", "words.trycloudflare.com") is False
+
+
+def test_edge_probe_rejects_a_foreign_responder(monkeypatch):
+ # Well-formed JSON from something that is not this backend, e.g. a proxy.
+ _fake_edge(monkeypatch, _edge_response(b"200 OK", b'{"service":"something else"}'))
+ assert ct._probe_edge("104.16.0.1", "words.trycloudflare.com") is False
+
+
+def test_edge_addresses_keep_one_entry_per_frontend(monkeypatch):
+ import socket as socket_module
+
+ # macOS reports the A records mapped into IPv6; both forms are one frontend.
+ resolved = [
+ (socket_module.AF_INET, 1, 6, "", ("104.16.230.132", 443)),
+ (socket_module.AF_INET6, 1, 6, "", ("::ffff:104.16.230.132", 443, 0, 0)),
+ (socket_module.AF_INET6, 1, 6, "", ("2606:4700::6810:e684", 443, 0, 0)),
+ ]
+ monkeypatch.setattr(socket_module, "getaddrinfo", lambda *_a, **_kw: resolved)
+ assert ct._edge_addresses() == ["104.16.230.132", "2606:4700::6810:e684"]
+
+
+def test_edge_probe_reports_an_unreachable_edge_apart_from_a_wrong_answer(monkeypatch):
+ _fake_edge(monkeypatch, b"", connect_error = "blocked")
+ assert ct._probe_edge("104.16.0.1", "words.trycloudflare.com") is None
+
+
+def test_edge_verification_skips_the_hostname_entirely(monkeypatch):
+ seen = {}
+
+ def probe(
+ address,
+ host,
+ _timeout = None,
+ ):
+ seen["probe"] = (address, host)
+ return True
+
+ def resolve(*_a, **_kw):
+ seen["dns"] = True
+
+ monkeypatch.setattr(ct, "_edge_addresses", lambda: ["104.16.0.1"])
+ monkeypatch.setattr(ct, "_probe_edge", probe)
+ monkeypatch.setattr(ct, "_wait_for_dns", resolve)
+ _patch_urlopen(monkeypatch, lambda req: pytest.fail("probed the hostname"))
+ assert ct.verify_public_url("https://words.trycloudflare.com") is True
+ assert seen["probe"] == ("104.16.0.1", "words.trycloudflare.com")
+ assert "dns" not in seen
+
+
+def test_edge_verification_polls_until_the_tunnel_answers(monkeypatch):
+ # Error 1033 and a proxy's own page answer, so a reply without the marker is
+ # not an unreachable edge and must not count towards giving up.
+ answers = [False, None, False, None, True]
+ monkeypatch.setattr(ct, "_edge_addresses", lambda: ["104.16.0.1"])
+ monkeypatch.setattr(ct, "_probe_edge", lambda *_a: answers.pop(0))
+ monkeypatch.setattr(ct.time, "sleep", lambda _s: None)
+ assert ct._verify_through_edge("words.trycloudflare.com", ct.time.monotonic() + 5) is True
+ assert not answers
+
+
+def test_edge_verification_stops_at_the_deadline_mid_pass(monkeypatch):
+ clock = [0.0]
+ timeouts = []
+
+ def probe(_address, _host, timeout):
+ timeouts.append(timeout)
+ clock[0] += 6.0
+ return False
+
+ monkeypatch.setattr(ct, "_edge_addresses", lambda: ["104.16.0.1", "104.16.0.2"])
+ monkeypatch.setattr(ct, "_probe_edge", probe)
+ monkeypatch.setattr(ct.time, "monotonic", lambda: clock[0])
+ monkeypatch.setattr(ct.time, "sleep", lambda s: clock.__setitem__(0, clock[0] + s))
+ assert ct._verify_through_edge("words.trycloudflare.com", 3.0) is False
+ # One attempt, given only the time the deadline leaves: the second address is
+ # already past it, and a whole pass must not outlive the caller's budget.
+ assert timeouts == [3.0]
+
+
+def test_edge_verification_leaves_the_fallback_room_in_the_deadline(monkeypatch):
+ clock = [0.0]
+ monkeypatch.setattr(ct, "_edge_addresses", lambda: ["104.16.0.1"])
+ monkeypatch.setattr(ct, "_probe_edge", lambda *_a: False)
+ monkeypatch.setattr(ct.time, "monotonic", lambda: clock[0])
+ monkeypatch.setattr(ct.time, "sleep", lambda s: clock.__setitem__(0, clock[0] + s))
+ assert ct._verify_through_edge("words.trycloudflare.com", 300.0) is False
+ assert clock[0] <= ct._EDGE_WAIT_MAX + ct._EDGE_PROBE_RETRY_DELAY
+ # What the cap is for: the hostname fallback still needs its DNS wait and
+ # several attempts of its own out of the one shared deadline.
+ left = ct._PUBLIC_PROBE_TIMEOUT - ct._EDGE_WAIT_MAX - ct._DNS_WAIT_MAX
+ assert left >= 5 * ct._PUBLIC_PROBE_RETRY_DELAY
+
+
+def test_blocked_edge_falls_back_to_the_hostname(monkeypatch):
+ order = []
+
+ def probe(*_a):
+ order.append("edge")
+ return None
+
+ def handler(_req):
+ order.append("hostname")
+ return _FakeResponse(b'{"service":"Unsloth UI Backend"}')
+
+ monkeypatch.setattr(ct, "_edge_addresses", lambda: ["104.16.0.1"])
+ monkeypatch.setattr(ct, "_probe_edge", probe)
+ monkeypatch.setattr(ct, "_wait_for_dns", lambda *_a: order.append("dns"))
+ _patch_urlopen(monkeypatch, handler)
+ monkeypatch.setattr(ct.time, "sleep", lambda _s: None)
+ assert ct.verify_public_url("https://words.trycloudflare.com") is True
+ assert order == ["edge"] * ct._EDGE_MAX_UNREACHABLE + ["dns", "hostname"]
+
+
@pytest.fixture(autouse = True)
def _stub_public_probe(monkeypatch, request):
# start_studio_tunnel tests use fake hostnames; keep them off the network.
@@ -631,6 +917,58 @@ def test_start_studio_tunnel_returns_url_once_probe_passes(monkeypatch):
ct.stop_studio_tunnel()
+def test_tunnel_status_tracks_owner_and_post_ready_exit(monkeypatch):
+ instances = []
+
+ class _Stub:
+ late_exit = False
+
+ def __init__(self, *_args, **_kwargs):
+ self.url = "https://words.trycloudflare.com"
+ self.error = None
+ instances.append(self)
+
+ start = stop = lambda self: None
+ wait_for_ready = lambda self, timeout: self.url
+
+ def set_on_exit(self, callback):
+ self.on_exit = callback
+ if self.late_exit:
+ self.error = "cloudflared exited"
+
+ def _publish_if_running(self, callback):
+ if self.late_exit:
+ return False
+ callback()
+ return True
+
+ monkeypatch.setattr(ct, "ensure_cloudflared", lambda: "/bin/cloudflared")
+ monkeypatch.setattr(ct, "CloudflareTunnel", _Stub)
+ monkeypatch.setattr(ct, "verify_public_url", lambda url, **kw: True)
+ published = []
+ ct.set_studio_tunnel_url_callback(published.append)
+ assert ct.start_studio_tunnel(8087, managed_by = "settings") == instances[0].url
+ status = ct.get_studio_tunnel_status()
+ assert status["state"] == "online"
+ assert status["managed_by"] == "settings"
+ assert status["url"] == instances[0].url
+ assert status["port"] == 8087
+ instances[0].error = "cloudflared exited"
+ instances[0].on_exit(instances[0])
+ status = ct.get_studio_tunnel_status()
+ assert status["state"] == "error"
+ assert status["url"] is None
+ assert status["error"] == "cloudflared exited"
+ assert published[-1] is None
+ ct.stop_studio_tunnel()
+ _Stub.late_exit = True
+ published.clear()
+ assert ct.start_studio_tunnel(8087, managed_by = "settings") is None
+ assert instances[-1].url not in published
+ assert ct.get_studio_tunnel_status()["state"] == "error"
+ ct.set_studio_tunnel_url_callback(None)
+
+
def test_start_studio_tunnel_registers_before_wait(monkeypatch):
# The tunnel must be visible to stop_studio_tunnel() during the readiness
# wait, else a shutdown in that window orphans cloudflared.
@@ -950,7 +1288,7 @@ def test_run_server_registers_tunnel_atexit_backstop():
# An abnormal exit (exception after startup -> sys.exit) bypasses
# _graceful_shutdown; an atexit backstop must still stop the tunnel.
src = _RUN_PY.read_text(encoding = "utf-8")
- assert "atexit.register(stop_studio_tunnel)" in src
+ assert "atexit.register(close_studio_tunnel_lifecycle)" in src
def _run_print_cloudflare_line(
diff --git a/studio/backend/tests/test_colab_embed.py b/studio/backend/tests/test_colab_embed.py
index 83b2a5a82d7..f20368dd0e4 100644
--- a/studio/backend/tests/test_colab_embed.py
+++ b/studio/backend/tests/test_colab_embed.py
@@ -3,6 +3,7 @@
"""Regression coverage for Colab iframe embedding (#7344)."""
+import inspect
import sys
import types
from types import SimpleNamespace
@@ -82,6 +83,28 @@ def test_warn_colab_cloudflare_missing_skips_when_tunnel_ready(monkeypatch, capl
assert "Cloudflare tunnel unavailable" not in caplog.text
+def test_start_cloudflare_tunnel_marks_colab_owner(monkeypatch):
+ calls = []
+ tunnel = types.ModuleType("cloudflare_tunnel")
+ tunnel.set_studio_tunnel_url_callback = lambda callback: calls.append(("callback", callback))
+ tunnel.start_studio_tunnel = lambda port, **kwargs: (
+ calls.append((port, kwargs)) or "https://share.trycloudflare.com"
+ )
+ monkeypatch.setitem(sys.modules, "cloudflare_tunnel", tunnel)
+ monkeypatch.setattr(colab, "_bootstrap_password_pending", lambda: False)
+
+ assert colab.start_cloudflare_tunnel(8891) == "https://share.trycloudflare.com"
+ assert calls == [
+ ("callback", colab._publish_cloudflare_url),
+ (8891, {"managed_by": "colab"}),
+ ]
+
+
+def test_colab_start_does_not_republish_returned_url():
+ assert "_publish_cloudflare_url(cf_url)" not in inspect.getsource(colab.start)
+ assert "cloudflare_url = None" not in inspect.getsource(colab._stop_cloudflare_tunnel)
+
+
def test_is_colab_runtime_uses_backend_colab_detector(monkeypatch):
fake_main = types.ModuleType("main")
fake_main._IS_COLAB = True
diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.py
index c7f459fc5d8..e4a96121d16 100644
--- a/studio/backend/tests/test_desktop_auth.py
+++ b/studio/backend/tests/test_desktop_auth.py
@@ -504,6 +504,87 @@ def test_desktop_session_uses_real_admin_identity_for_api_keys():
assert [row["name"] for row in rows] == ["desktop"]
+def web_bearer(client) -> str:
+ payload = {"username": storage.DEFAULT_ADMIN_USERNAME, "password": "human-password-123"}
+ return client.post("/api/auth/login", json = payload).json()["access_token"]
+
+
+def is_desktop_token(token: str) -> bool:
+ payload = jwt.decode(
+ token, storage.get_jwt_secret(storage.DEFAULT_ADMIN_USERNAME), algorithms = ["HS256"]
+ )
+ return payload.get("desktop") is True
+
+
+def test_desktop_sets_the_remote_password_without_the_seeded_one():
+ seed_user(must_change_password = True)
+ raw = storage.create_desktop_secret()
+ client = auth_client()
+ token = client.post("/api/auth/desktop-login", json = {"secret": raw}).json()["access_token"]
+ headers = {"Authorization": f"Bearer {token}"}
+ body = {"new_password": "remote-password-123"}
+
+ response = client.post("/api/auth/desktop-initial-password", headers = headers, json = body)
+
+ assert response.status_code == 200
+ assert response.json()["must_change_password"] is False
+ assert is_desktop_token(response.json()["access_token"])
+ assert storage.requires_password_change(storage.DEFAULT_ADMIN_USERNAME) is False
+ # Desktop auto-auth survives the change the desktop itself made.
+ assert storage.validate_desktop_secret(raw) == storage.DEFAULT_ADMIN_USERNAME
+ remote_login = client.post(
+ "/api/auth/login",
+ json = {"username": storage.DEFAULT_ADMIN_USERNAME, "password": "remote-password-123"},
+ )
+ assert remote_login.status_code == 200
+ # The seeded credential is gone, so change-password owns every later change.
+ repeat = client.post(
+ "/api/auth/desktop-initial-password",
+ headers = {"Authorization": f"Bearer {response.json()['access_token']}"},
+ json = body,
+ )
+ assert repeat.status_code == 409
+
+
+def test_remote_password_refuses_credentials_that_are_not_the_desktop_app():
+ seed_user(must_change_password = True)
+ client = auth_client()
+ api_key, _row = storage.create_api_key(storage.DEFAULT_ADMIN_USERNAME, "cli")
+
+ for bearer in (web_bearer(client), api_key):
+ response = client.post(
+ "/api/auth/desktop-initial-password",
+ headers = {"Authorization": f"Bearer {bearer}"},
+ json = {"new_password": "remote-password-123"},
+ )
+ # Distinguishable from the pre-existing "Password change required" refusal.
+ assert response.status_code == 403
+ assert response.json()["detail"] == "This action requires the Unsloth desktop app."
+ assert storage.requires_password_change(storage.DEFAULT_ADMIN_USERNAME) is True
+
+
[email protected]("desktop", [True, False])
+def test_change_password_revokes_the_desktop_secret_only_for_browsers(desktop):
+ seed_user(must_change_password = False)
+ raw = storage.create_desktop_secret()
+ client = auth_client()
+ bearer = (
+ client.post("/api/auth/desktop-login", json = {"secret": raw}).json()["access_token"]
+ if desktop
+ else web_bearer(client)
+ )
+
+ response = client.post(
+ "/api/auth/change-password",
+ headers = {"Authorization": f"Bearer {bearer}"},
+ json = {"current_password": "human-password-123", "new_password": "remote-password-123"},
+ )
+
+ assert response.status_code == 200
+ assert is_desktop_token(response.json()["access_token"]) is desktop
+ assert (storage.validate_desktop_secret(raw) == storage.DEFAULT_ADMIN_USERNAME) is desktop
+
+
def test_local_recipe_token_authenticates_as_admin_for_desktop_user(loaded_local_model):
# _inject_local_providers mints an internal sk-unsloth-* API key (not a
# forwarded JWT) that validates as admin whether the session was desktop or web.
diff --git a/studio/backend/tests/test_frontend_resolution.py b/studio/backend/tests/test_frontend_resolution.py
index 7ac2717aaef..447c9c4079b 100644
--- a/studio/backend/tests/test_frontend_resolution.py
+++ b/studio/backend/tests/test_frontend_resolution.py
@@ -13,6 +13,8 @@ import os
import sys
from pathlib import Path
+import pytest
+
_RUN_PY = Path(__file__).resolve().parent.parent / "run.py"
_REPO_STUDIO_DIR = _RUN_PY.parent.parent # studio/
@@ -27,6 +29,8 @@ def _load_helpers_only():
"_DEFAULT_FRONTEND_PATH",
"_iter_frontend_fallback_candidates",
"_resolve_frontend_path",
+ "_frontend_serving_mode",
+ "_missing_frontend_is_fatal",
}
for node in tree.body:
if isinstance(node, (ast.Import, ast.ImportFrom)):
@@ -44,6 +48,13 @@ def _load_helpers_only():
return ns
+def test_frontend_serving_mode_is_tunnel_only_for_desktop_api_only():
+ mode = _load_helpers_only()["_frontend_serving_mode"]
+ assert mode(api_only = False, desktop_owned = False) == (True, False)
+ assert mode(api_only = True, desktop_owned = False) == (False, False)
+ assert mode(api_only = True, desktop_owned = True) == (True, True)
+
+
def test_resolver_returns_none_when_nothing_exists(tmp_path, monkeypatch):
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "no_studio"))
monkeypatch.delenv("STUDIO_HOME", raising = False)
@@ -237,3 +248,64 @@ def test_systemexit_message_contains_actionable_fixes(tmp_path, monkeypatch):
assert "reinstall" in message
assert "installer's binary directly" in message
assert str(installer_bin) in message
+
+
+def _run_frontend_mount(*, tunnel_only, resolves):
+ """Drive run_server's frontend-mount decision without importing uvicorn.
+
+ Slices out the `if frontend_path and _serve_frontend:` statement, so the
+ branch that decides abort-vs-degrade is exercised where it actually lives."""
+ import logging
+
+ tree = ast.parse(_RUN_PY.read_text(encoding = "utf-8"))
+ run_server = next(
+ n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "run_server"
+ )
+ block = next(
+ n
+ for n in run_server.body
+ if isinstance(n, ast.If)
+ and isinstance(n.test, ast.BoolOp)
+ and any(isinstance(v, ast.Name) and v.id == "_serve_frontend" for v in n.test.values)
+ )
+ code = compile(ast.Module(body = [block], type_ignores = []), str(_RUN_PY), "exec")
+ mounted = []
+ ns = {
+ "frontend_path": Path("/nonexistent/studio/frontend/dist"),
+ "_serve_frontend": True,
+ "_tunnel_only_frontend": tunnel_only,
+ "_resolve_frontend_path": lambda p: (Path("/dist"), [p]) if resolves else (None, [p]),
+ "setup_frontend": lambda app, chosen, *, tunnel_only: (
+ mounted.append((chosen, tunnel_only)) or True
+ ),
+ "_missing_frontend_is_fatal": _load_helpers_only()["_missing_frontend_is_fatal"],
+ "app": object(),
+ "silent": True,
+ "logger": logging.getLogger("test_frontend_resolution"),
+ "Path": Path,
+ "os": os,
+ "sys": sys,
+ }
+ exec(code, ns)
+ return mounted
+
+
+def test_missing_frontend_is_fatal_everywhere_but_the_desktop_tunnel_path():
+ fatal = _load_helpers_only()["_missing_frontend_is_fatal"]
+ assert fatal(tunnel_only = False) is True
+ assert fatal(tunnel_only = True) is False
+
+
+def test_desktop_api_only_backend_starts_without_a_packaged_dist():
+ """The desktop spawns `studio --api-only` with no --frontend, and its
+ installer skips the frontend build, so a missing dist must not abort."""
+ assert _run_frontend_mount(tunnel_only = True, resolves = False) == []
+
+
+def test_a_missing_dist_still_aborts_a_web_ui_launch():
+ with pytest.raises(SystemExit, match = "frontend build not found"):
+ _run_frontend_mount(tunnel_only = False, resolves = False)
+
+
+def test_a_desktop_dist_is_still_mounted_behind_the_tunnel_gate():
+ assert _run_frontend_mount(tunnel_only = True, resolves = True) == [(Path("/dist"), True)]
diff --git a/studio/backend/tests/test_mcp_stdio_pr5863.py b/studio/backend/tests/test_mcp_stdio_pr5863.py
index 1cb1211cf21..f80a377428f 100644
--- a/studio/backend/tests/test_mcp_stdio_pr5863.py
+++ b/studio/backend/tests/test_mcp_stdio_pr5863.py
@@ -275,6 +275,21 @@ def test_loopback_default_not_inherited_by_later_public_bind(monkeypatch):
assert mcp_client.stdio_mcp_enabled() is False
+def test_remote_access_suspends_only_automatic_stdio_default(monkeypatch):
+ _disable(monkeypatch)
+ host_policy.apply_stdio_mcp_loopback_default("127.0.0.1")
+ assert mcp_client.stdio_mcp_enabled() is True
+ host_policy.set_remote_connector_active(True)
+ assert mcp_client.stdio_mcp_enabled() is False
+ host_policy.set_remote_connector_active(False)
+ assert mcp_client.stdio_mcp_enabled() is True
+
+ host_policy._reset_loopback_default_state()
+ monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")
+ host_policy.set_remote_connector_active(True)
+ assert mcp_client.stdio_mcp_enabled() is True
+
+
@pytest.mark.parametrize("second_host", ["127.0.0.1", "0.0.0.0"])
def test_force_disable_after_auto_default_in_same_process(monkeypatch, second_host):
# Reuse: a loopback launch auto-enables, then the operator sets =0 before a
diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.py
index c483f7f43a6..50c4fd6d3c4 100644
--- a/studio/backend/tests/test_middleware.py
+++ b/studio/backend/tests/test_middleware.py
@@ -692,6 +692,29 @@ class TestResearchPortMiddleware:
class TestFrontendAssets:
+ def test_desktop_frontend_is_available_only_through_live_tunnel(self, tmp_path, main_module):
+ (tmp_path / "index.html").write_text("<!doctype html><title>remote</title>")
+ assets = tmp_path / "assets"
+ assets.mkdir()
+ (assets / "app.js").write_text("export {};", encoding = "utf-8")
+ app = FastAPI()
+ app.state.cloudflare_url = None
+ assert main_module.setup_frontend(app, tmp_path, tunnel_only = True)
+ client = TestClient(app)
+ remote_client = TestClient(app, base_url = "https://remote.trycloudflare.com")
+ headers = {"CF-Connecting-IP": "198.51.100.7"}
+ assert client.get("/").status_code == 404
+ assert client.get("/assets/app.js").status_code == 404
+ assert remote_client.get("/", headers = headers).status_code == 404
+
+ app.state.cloudflare_url = "https://remote.trycloudflare.com"
+ assert remote_client.get("/", headers = headers).status_code == 200
+ assert remote_client.get("/settings/api", headers = headers).status_code == 200
+ assert remote_client.get("/assets/app.js", headers = headers).status_code == 200
+ assert client.get("/", headers = headers).status_code == 404
+ assert client.get("/settings/api", headers = headers).status_code == 404
+ assert client.get("/").status_code == 404
+
def test_hashed_assets_are_compressed_and_cached(self, tmp_path, main_module):
content = b"export const value = 'responsive';\n" * 200
(tmp_path / "page-abc123.js").write_bytes(content)
diff --git a/studio/backend/tests/test_password_prompt_backstop.py b/studio/backend/tests/test_password_prompt_backstop.py
index 6c225325324..918da101ef1 100644
--- a/studio/backend/tests/test_password_prompt_backstop.py
+++ b/studio/backend/tests/test_password_prompt_backstop.py
@@ -209,14 +209,20 @@ def test_gate_success_applies_route_equivalent_change(monkeypatch):
def test_gate_runs_before_server_bind_in_source():
+ app_state = type("State", (), {})()
+ run._publish_cloudflare_url(app_state, "https://live.trycloudflare.com")
+ assert app_state.cloudflare_url == run._cloudflare_url == "https://live.trycloudflare.com"
+ run._publish_cloudflare_url(app_state, None)
# The gate must run before the uvicorn socket binds: on a wildcard bind
# the served HTML injects the bootstrap credential for first login, so a
# pre-gate listener would hand out the default password mid-prompt.
src = (_BACKEND / "run.py").read_text(encoding = "utf-8")
gate_call = src.index("_pw_proceed, _pw_drop_bootstrap = _terminal_password_gate(")
thread_start = src.index("thread.start()")
- tunnel_start = src.index("_cloudflare_url = start_studio_tunnel(port)")
- assert gate_call < thread_start < tunnel_start
+ tunnel_start = src.index('start_studio_tunnel(port, managed_by = "launch")')
+ callback_bind = src.index("set_studio_tunnel_url_callback(")
+ assert gate_call < thread_start < callback_bind < tunnel_start
+ assert "_cloudflare_url = start_studio_tunnel" not in src
# The fail-closed branch exits before any server exists.
refusal = src[gate_call:thread_start]
assert "sys.exit(1)" in refusal
diff --git a/studio/backend/tests/test_preview_routes.py b/studio/backend/tests/test_preview_routes.py
index 0770ad32fd0..2bd55df328f 100644
--- a/studio/backend/tests/test_preview_routes.py
+++ b/studio/backend/tests/test_preview_routes.py
@@ -118,6 +118,7 @@ def test_page_renders_with_csp(client):
assert "base-uri 'none'" in csp
# Token rides in the query string; keep it out of the Referer header.
assert r.headers.get("referrer-policy") == "no-referrer"
+ assert "messages: msgs,\n stream: true," in r.text
def test_page_escapes_title(tmp_path, monkeypatch, captured):
diff --git a/studio/backend/tests/test_remote_access_settings.py b/studio/backend/tests/test_remote_access_settings.py
new file mode 100644
index 00000000000..48f8cf30bbe
--- /dev/null
+++ b/studio/backend/tests/test_remote_access_settings.py
@@ -0,0 +1,498 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import asyncio
+import sys
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+
+_BACKEND = Path(__file__).resolve().parents[1]
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import cloudflare_tunnel # noqa: E402
+import routes.settings as routes # noqa: E402
+import utils.remote_access_settings as remote_access # noqa: E402
+from storage import studio_db # noqa: E402
+
+
+def _state(
+ intent = "unset",
+ is_colab = False,
+ launch_managed = False,
+):
+ return SimpleNamespace(
+ remote_access_intent = intent,
+ remote_access_is_colab = is_colab,
+ remote_access_launch_managed = launch_managed,
+ remote_access_port = 8888,
+ remote_access_ready = True,
+ )
+
+
+def test_auto_start_persistence_is_strict_and_fail_closed(monkeypatch):
+ stored = {}
+ monkeypatch.setattr(
+ studio_db, "get_app_setting", lambda key, fallback: stored.get(key, fallback)
+ )
+ monkeypatch.setattr(studio_db, "upsert_app_settings", lambda values: stored.update(values))
+ assert remote_access.get_remote_access_auto_start() is False
+ stored[remote_access.REMOTE_ACCESS_AUTO_START_KEY] = "yes"
+ assert remote_access.get_remote_access_auto_start() is False
+ assert remote_access.set_remote_access_auto_start(True) is True
+ assert remote_access.get_remote_access_auto_start() is True
+ with pytest.raises(ValueError):
+ routes.RemoteAccessAutoStartPayload(enabled = "true")
+ monkeypatch.setattr(
+ studio_db, "get_app_setting", lambda *args: (_ for _ in ()).throw(OSError())
+ )
+ assert remote_access.get_remote_access_auto_start() is False
+
+
+ "launch_managed,expected_block,can_start",
+ [(False, None, True), (True, "launch_managed", False)],
+)
+def test_enabled_intent_blocks_only_selected_launch_path(
+ monkeypatch, launch_managed, expected_block, can_start
+):
+ monkeypatch.setattr(remote_access, "_start_worker", None)
+ monkeypatch.setattr(remote_access, "_stop_worker", None)
+ monkeypatch.setattr(remote_access, "get_remote_access_auto_start", lambda: False)
+ monkeypatch.setattr(remote_access, "_admin_password_ready", lambda: True)
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "get_studio_tunnel_status",
+ lambda: {"state": "off", "url": None, "error": None, "managed_by": None},
+ )
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_control_token", lambda: (1, 0))
+
+ state = _state(intent = "enabled", launch_managed = launch_managed)
+ status = remote_access.remote_access_status(state)
+ assert status["block_reason"] == expected_block
+ assert status["can_start"] is can_start
+ assert status["password_pending"] is False
+
+ # A pending password is reported on its own, even where another block hides it.
+ monkeypatch.setattr(remote_access, "_admin_password_ready", lambda: False)
+ pending = remote_access.remote_access_status(state)
+ assert pending["password_pending"] is True
+ assert pending["block_reason"] == (expected_block or "admin_password_change_required")
+
+
+def test_failed_stop_remains_retryable(monkeypatch):
+ monkeypatch.setattr(remote_access, "_start_worker", None)
+ monkeypatch.setattr(remote_access, "_stop_worker", None)
+ monkeypatch.setattr(remote_access, "get_remote_access_auto_start", lambda: False)
+ monkeypatch.setattr(remote_access, "_admin_password_ready", lambda: True)
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "get_studio_tunnel_status",
+ lambda: {
+ "state": "error",
+ "url": None,
+ "error": None,
+ "managed_by": "settings",
+ "stop_pending": True,
+ },
+ )
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_control_token", lambda: (1, 0))
+ status = remote_access.remote_access_status(_state())
+ assert status["can_start"] is False and status["can_stop"] is True
+ source = Path(remote_access.__file__).read_text(encoding = "utf-8")
+ assert 'if get_studio_tunnel_status().get("stop_pending"):' in source
+
+
+def test_only_a_finished_stop_worker_stops_reporting_stopping(monkeypatch):
+ hold = threading.Event()
+ stale_stop = threading.Thread(target = hold.wait, daemon = True)
+ stale_stop.start()
+ monkeypatch.setattr(remote_access, "_stop_worker", stale_stop)
+ monkeypatch.setattr(remote_access, "_stop_worker_admission", (1, 5))
+ monkeypatch.setattr(remote_access, "_start_worker", None)
+ monkeypatch.setattr(remote_access, "get_remote_access_auto_start", lambda: False)
+ monkeypatch.setattr(remote_access, "_admin_password_ready", lambda: True)
+ tunnel_status = {
+ "state": "off",
+ "url": None,
+ "error": None,
+ "managed_by": None,
+ "stop_pending": False,
+ }
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_status", lambda: dict(tunnel_status))
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_control_token", lambda: (1, 6))
+
+ # the teardown advanced the generation past (1, 5), so this stop is done
+ status = remote_access.remote_access_status(_state())
+ assert status["state"] == "off"
+ assert status["can_start"] is True
+
+ new_start = threading.Thread(target = hold.wait, daemon = True)
+ new_start.start()
+ monkeypatch.setattr(remote_access, "_start_worker", new_start)
+ monkeypatch.setattr(remote_access, "_start_worker_admission", (1, 6))
+ assert remote_access.remote_access_status(_state())["state"] == "starting"
+ monkeypatch.setattr(remote_access, "_start_worker", None)
+
+ # a stop admitted at the current generation still owes its teardown
+ monkeypatch.setattr(remote_access, "_stop_worker_admission", (1, 6))
+ assert remote_access.remote_access_status(_state())["state"] == "stopping"
+ monkeypatch.setattr(remote_access, "_stop_worker_admission", (1, 5))
+
+ # so does a torn-down stop whose termination is unconfirmed
+ tunnel_status["stop_pending"] = True
+ assert remote_access.remote_access_status(_state())["state"] == "stopping"
+
+ # and the report stays scoped to a tunnel that is actually off
+ tunnel_status.update(stop_pending = False, state = "online", managed_by = "settings")
+ assert remote_access.remote_access_status(_state())["state"] == "stopping"
+ hold.set()
+
+
+def test_workers_and_stops_are_scoped_to_backend_lifecycle(monkeypatch):
+ remote_access._start_worker = remote_access._stop_worker = None
+ remote_access._start_worker_admission = remote_access._stop_worker_admission = None
+ cloudflare_tunnel.stop_studio_tunnel()
+ cloudflare_tunnel.open_studio_tunnel_lifecycle()
+ entered, reopened, release = (threading.Event() for _ in range(3))
+ attempts = []
+ real_start = cloudflare_tunnel.start_studio_tunnel
+
+ def _delayed(*args, **kwargs):
+ attempts.append(kwargs["admission"])
+ if len(attempts) == 1:
+ entered.set()
+ release.wait(1)
+ return real_start(*args, **kwargs)
+ reopened.set()
+
+ monkeypatch.setattr(cloudflare_tunnel, "start_studio_tunnel", _delayed)
+ monkeypatch.setattr(cloudflare_tunnel, "ensure_cloudflared", lambda: pytest.fail("stale start"))
+ monkeypatch.setattr(remote_access, "get_remote_access_auto_start", lambda: False)
+ monkeypatch.setattr(remote_access, "_admin_password_ready", lambda: True)
+ remote_access._stop_response_admission_open = False
+ assert (
+ remote_access.remote_access_status(_state())
+ and not remote_access._stop_response_admission_open
+ )
+ remote_access.start_remote_access(_state())
+ assert entered.wait(1) and remote_access._stop_response_admission_open
+ old_worker = remote_access._start_worker
+ old_token = attempts[0]
+ cloudflare_tunnel.close_studio_tunnel_lifecycle()
+ cloudflare_tunnel.open_studio_tunnel_lifecycle()
+ monkeypatch.setattr(remote_access, "get_remote_access_auto_start", lambda: True)
+ assert remote_access.maybe_auto_start_remote_access(_state()) and reopened.wait(1)
+ release.set()
+ old_worker.join(1)
+ current = cloudflare_tunnel.get_studio_tunnel_control_token()
+ cloudflare_tunnel.stop_studio_tunnel(admission = old_token)
+ assert len(attempts) == 2 and cloudflare_tunnel.get_studio_tunnel_control_token() == current
+ assert cloudflare_tunnel.get_studio_tunnel_status()["state"] == "off"
+
+
[email protected]("trigger", ["manual", "auto"])
+def test_settings_start_logs_public_url_when_tunnel_is_ready(monkeypatch, trigger):
+ monkeypatch.setattr(remote_access, "_start_worker", None)
+ monkeypatch.setattr(remote_access, "_start_worker_admission", None)
+ ready = threading.Event()
+ messages = []
+ status = {
+ "state": "off",
+ "managed_by": None,
+ "can_start": True,
+ "block_reason": None,
+ }
+
+ def _start(*_args, **_kwargs):
+ ready.set()
+ return "https://example.trycloudflare.com"
+
+ monkeypatch.setattr(remote_access, "get_remote_access_auto_start", lambda: True)
+ monkeypatch.setattr(remote_access, "remote_access_status", lambda _: status)
+ monkeypatch.setattr(cloudflare_tunnel, "capture_studio_tunnel_start_admission", lambda: (1, 1))
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_control_token", lambda: (1, 1))
+ monkeypatch.setattr(cloudflare_tunnel, "start_studio_tunnel", _start)
+ monkeypatch.setattr(
+ remote_access.logger,
+ "info",
+ lambda message, url: messages.append(message % url),
+ )
+
+ if trigger == "auto":
+ assert remote_access.maybe_auto_start_remote_access(_state())
+ else:
+ remote_access.start_remote_access(_state())
+ assert ready.wait(1)
+ remote_access._start_worker.join(1)
+ assert messages == ["Secure link access via Cloudflare: https://example.trycloudflare.com"]
+
+
[email protected]("operation", ["start", "stop"])
+def test_request_cannot_adopt_reopened_lifecycle(monkeypatch, operation):
+ status = (
+ {"state": "off", "managed_by": None, "can_start": True}
+ if operation == "start"
+ else {"state": "online", "managed_by": "settings"}
+ )
+ satisfied = {
+ "state": "online" if operation == "start" else "stopping",
+ "managed_by": "settings",
+ }
+ cloudflare_tunnel.open_studio_tunnel_lifecycle()
+
+ def _status(_state):
+ cloudflare_tunnel.close_studio_tunnel_lifecycle()
+ cloudflare_tunnel.open_studio_tunnel_lifecycle()
+ return {"block_reason": None, **status}
+
+ monkeypatch.setattr(remote_access, "remote_access_status", _status)
+ with pytest.raises(RuntimeError, match = "server_lifecycle_changed"):
+ getattr(remote_access, f"{operation}_remote_access")(_state())
+ monkeypatch.setattr(
+ remote_access,
+ "remote_access_status",
+ lambda _: (cloudflare_tunnel.stop_studio_tunnel(), satisfied)[1],
+ )
+ assert getattr(remote_access, f"{operation}_remote_access")(_state()) == satisfied
+
+
+def test_management_rejects_api_keys():
+ with pytest.raises(HTTPException) as exc:
+ routes._require_ui_session(True)
+ assert exc.value.status_code == 403
+ assert remote_access.remote_access_status(_state())["streaming_supported"] is True
+ source = Path(routes.__file__).read_text(encoding = "utf-8")
+ assert source.count("_ui_session: None = Depends(_require_ui_session)") == 4
+
+
+def test_remote_stop_returns_terminal_state(monkeypatch):
+ def _stop(_state):
+ return {
+ "state": "stopping",
+ "url": None,
+ "error": None,
+ "auto_start": True,
+ "available": True,
+ "managed_by": "settings",
+ "can_start": False,
+ "can_stop": False,
+ "block_reason": None,
+ "streaming_supported": True,
+ }
+
+ monkeypatch.setattr(routes, "stop_remote_access", _stop)
+ request = SimpleNamespace(app = SimpleNamespace(state = _state()))
+ response = routes.stop_remote_access_route(request, "admin", None)
+ assert response.state == "off" and response.managed_by is None
+
+
+def test_stop_response_middleware_holds_lease_through_body(monkeypatch):
+ acquired = threading.Event()
+ released = threading.Event()
+
+ def _acquire():
+ acquired.set()
+ return released.set
+
+ monkeypatch.setattr(remote_access, "acquire_remote_access_stop_response", _acquire)
+
+ async def _app(scope, receive, send):
+ assert acquired.is_set() and not released.is_set()
+ await send({"type": "http.response.start", "status": 200, "headers": []})
+ assert not released.is_set()
+ await send({"type": "http.response.body", "body": b"{}"})
+
+ async def _send(_message):
+ return None
+
+ middleware = remote_access.RemoteAccessStopResponseMiddleware(_app)
+ asyncio.run(
+ middleware(
+ {
+ "type": "http",
+ "method": "POST",
+ "path": "/api/settings/remote-access/stop",
+ },
+ None,
+ _send,
+ )
+ )
+ assert released.is_set()
+ assert "app.add_middleware(RemoteAccessStopResponseMiddleware)" in (
+ _BACKEND / "main.py"
+ ).read_text(encoding = "utf-8")
+
+
+def test_stop_worker_waits_for_every_concurrent_response(monkeypatch):
+ remote_access._start_worker = remote_access._stop_worker = None
+ remote_access._start_worker_admission = remote_access._stop_worker_admission = None
+ remote_access._stop_response_admission_open = True
+ stopped = threading.Event()
+
+ release_first = remote_access.acquire_remote_access_stop_response()
+ release_second = remote_access.acquire_remote_access_stop_response()
+ assert release_first is not None and release_second is not None
+ status = {
+ "state": "online",
+ "managed_by": "settings",
+ "block_reason": None,
+ }
+ monkeypatch.setattr(remote_access, "remote_access_status", lambda _: status)
+ monkeypatch.setattr(cloudflare_tunnel, "capture_studio_tunnel_start_admission", lambda: (1, 1))
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_control_token", lambda: (1, 1))
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "get_studio_tunnel_status",
+ lambda: {"state": "online", "managed_by": "settings"},
+ )
+ monkeypatch.setattr(cloudflare_tunnel, "stop_studio_tunnel", lambda **_: stopped.set())
+
+ remote_access.stop_remote_access(_state())
+ release_first()
+ assert not stopped.wait(0.1)
+ release_second()
+ assert stopped.wait(1)
+ assert remote_access.acquire_remote_access_stop_response() is None
+ remote_access._open_remote_access_stop_response_admission()
+
+
+def test_stop_response_wait_accepts_admission_after_initial_zero(monkeypatch):
+ remote_access._stop_responses_pending = 0
+ remote_access._stop_response_admission_open = True
+ entered_quiet_window, advance_clock, finished = (threading.Event() for _ in range(3))
+ real_monotonic = remote_access.time.monotonic
+ advanced_at = monotonic_calls = 0
+
+ def _monotonic():
+ nonlocal monotonic_calls
+ monotonic_calls += 1
+ if monotonic_calls == 2:
+ entered_quiet_window.set()
+ if advance_clock.is_set():
+ return 0.1 + real_monotonic() - advanced_at
+ return 0.0
+
+ def _wait():
+ remote_access._drain_and_close_remote_access_stop_responses()
+ finished.set()
+
+ monkeypatch.setattr(remote_access.time, "monotonic", _monotonic)
+ waiter = threading.Thread(target = _wait)
+ waiter.start()
+ assert entered_quiet_window.wait(0.5)
+ release = remote_access.acquire_remote_access_stop_response()
+ assert release is not None
+ assert not finished.wait(0.1)
+ advanced_at = real_monotonic()
+ advance_clock.set()
+ release()
+ assert finished.wait(1)
+ assert remote_access.acquire_remote_access_stop_response() is None
+ remote_access._open_remote_access_stop_response_admission()
+ waiter.join()
+
+
+def test_colab_auto_start_setting_is_read_only(monkeypatch):
+ monkeypatch.setattr(routes, "set_remote_access_auto_start", lambda *_: pytest.fail("persisted"))
+ request = SimpleNamespace(app = SimpleNamespace(state = _state(is_colab = True)))
+ payload = routes.RemoteAccessAutoStartPayload(enabled = True)
+ with pytest.raises(HTTPException) as exc:
+ routes.update_remote_access_auto_start(request, payload, "admin", None)
+ assert exc.value.status_code == 409
+
+
+def test_unstoppable_connector_reports_why_start_is_blocked(monkeypatch):
+ # The generic "Cloudflare tunnel failed" hides the one state the user can
+ # act on: a connector whose exit was never confirmed still holds the slot.
+ monkeypatch.setattr(remote_access, "_start_worker", None)
+ monkeypatch.setattr(remote_access, "_stop_worker", None)
+ monkeypatch.setattr(remote_access, "get_remote_access_auto_start", lambda: False)
+ monkeypatch.setattr(remote_access, "_admin_password_ready", lambda: True)
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "get_studio_tunnel_status",
+ lambda: {
+ "state": "error",
+ "url": None,
+ "error": "cloudflared could not be stopped",
+ "managed_by": "settings",
+ "stop_pending": True,
+ },
+ )
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_control_token", lambda: (1, 0))
+ assert remote_access.remote_access_status(_state())["error"] == (
+ "cloudflared could not be stopped"
+ )
+
+
+def test_stop_does_not_wait_forever_on_a_start_that_never_claims_ownership(monkeypatch):
+ # A start worker that stays alive without taking settings ownership (foreign
+ # owner, or bailed on admission) must not defer Stop for the probe deadline.
+ hold = threading.Event()
+ foreign_start = threading.Thread(target = hold.wait, daemon = True)
+ foreign_start.start()
+ monkeypatch.setattr(remote_access, "_start_worker", foreign_start)
+ monkeypatch.setattr(remote_access, "_stop_worker", None)
+ monkeypatch.setattr(remote_access, "_STOP_OWNERSHIP_WAIT", 0.1)
+ monkeypatch.setattr(remote_access, "get_remote_access_auto_start", lambda: False)
+ monkeypatch.setattr(remote_access, "_admin_password_ready", lambda: True)
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "get_studio_tunnel_status",
+ lambda: {
+ "state": "online",
+ "url": "https://live.trycloudflare.com",
+ "error": None,
+ "managed_by": "settings",
+ "stop_pending": False,
+ },
+ )
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_control_token", lambda: (1, 0))
+ monkeypatch.setattr(cloudflare_tunnel, "capture_studio_tunnel_start_admission", lambda: (1, 0))
+ stopped = threading.Event()
+ monkeypatch.setattr(
+ cloudflare_tunnel, "stop_studio_tunnel", lambda **_kw: stopped.set()
+ )
+ try:
+ remote_access.stop_remote_access(_state())
+ assert stopped.wait(5), "stop worker never reached stop_studio_tunnel"
+ finally:
+ hold.set()
+ foreign_start.join(timeout = 5)
+ remote_access._open_remote_access_stop_response_admission()
+
+
+def test_streaming_is_not_advertised_while_a_quick_tunnel_carries_the_traffic(monkeypatch):
+ # Cloudflare documents that Quick Tunnels do not support Server-Sent Events,
+ # and Studio only ever opens Quick Tunnels. Measured against a real tunnel: an
+ # SSE endpoint answers 200 with text/event-stream but delivers zero events.
+ monkeypatch.setattr(remote_access, "_start_worker", None)
+ monkeypatch.setattr(remote_access, "_stop_worker", None)
+ monkeypatch.setattr(remote_access, "get_remote_access_auto_start", lambda: False)
+ monkeypatch.setattr(remote_access, "_admin_password_ready", lambda: True)
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_control_token", lambda: (1, 0))
+
+ def _status(url):
+ return {
+ "state": "online" if url else "off",
+ "url": url,
+ "error": None,
+ "managed_by": "settings" if url else None,
+ "stop_pending": False,
+ }
+
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_status", lambda: _status(None))
+ assert remote_access.remote_access_status(_state())["streaming_supported"] is True
+
+ monkeypatch.setattr(
+ cloudflare_tunnel, "get_studio_tunnel_status",
+ lambda: _status("https://live.trycloudflare.com"),
+ )
+ assert remote_access.remote_access_status(_state())["streaming_supported"] is False
diff --git a/studio/backend/tests/test_secure_tunnel_gate.py b/studio/backend/tests/test_secure_tunnel_gate.py
index b4911340450..f57327d9794 100644
--- a/studio/backend/tests/test_secure_tunnel_gate.py
+++ b/studio/backend/tests/test_secure_tunnel_gate.py
@@ -62,6 +62,29 @@ def test_cloudflare_gate(cloudflare, host, secure, api_only, is_colab, expected)
)
+ "inherited,cloudflare,secure,expected",
+ [
+ ("unset", False, False, "unset"),
+ ("disabled", False, False, "disabled"),
+ (None, False, False, "disabled"),
+ (None, None, False, "unset"),
+ (None, None, True, "enabled"),
+ ],
+)
+def test_cloudflare_intent_preserves_compatibility_provenance(
+ monkeypatch, inherited, cloudflare, secure, expected
+):
+ import run
+
+ if inherited is None:
+ monkeypatch.delenv(run._CLOUDFLARE_INTENT_ENV, raising = False)
+ else:
+ monkeypatch.setenv(run._CLOUDFLARE_INTENT_ENV, inherited)
+ assert run._consume_cloudflare_intent(cloudflare, secure) == expected
+ assert run._CLOUDFLARE_INTENT_ENV not in run.os.environ
+
+
def test_run_server_accepts_secure_kwarg():
import inspect
@@ -71,6 +94,27 @@ def test_run_server_accepts_secure_kwarg():
assert inspect.signature(run.run_server).parameters["secure"].default is False
+def test_final_bound_port_uses_uvicorn_listener_for_ephemeral_bind():
+ from types import SimpleNamespace
+
+ import run
+
+ sock = SimpleNamespace(getsockname = lambda: ("127.0.0.1", 43123))
+ server = SimpleNamespace(servers = [SimpleNamespace(sockets = [sock])])
+ assert run._final_bound_port(server, 0) == 43123
+ assert run._final_bound_port(server, 8888) == 8888
+ source = (_BACKEND / "run.py").read_text(encoding = "utf-8")
+ resolved = source.index("port = _final_bound_port(_server, port)")
+ assert all(
+ resolved < source.index(consumer, resolved)
+ for consumer in (
+ "app.state.remote_access_port",
+ "TAURI_PORT={port}",
+ "start_studio_tunnel(port",
+ )
+ )
+
+
def test_arg_parser_secure_polarity_and_not_secure_alias():
# --secure/--no-secure is the documented flag; --not-secure is a hidden,
# back-compat alias for --no-secure. Last flag wins (BooleanOptionalAction).
@@ -202,11 +246,46 @@ def test_cors_origins_for_mode(api_only, secure, expected):
assert origins == expected
+def test_api_only_cors_tracks_published_public_url():
+ from types import SimpleNamespace
+
+ from starlette.datastructures import Headers
+
+ from main import RemoteAccessCORSMiddleware
+
+ state = SimpleNamespace(cloudflare_url = None)
+ middleware = RemoteAccessCORSMiddleware(
+ lambda *_: None,
+ remote_access_state = state,
+ allow_origins = ["tauri://localhost"],
+ allow_credentials = True,
+ allow_methods = ["*"],
+ allow_headers = ["*"],
+ )
+ request = Headers(
+ {
+ "origin": "https://browser-client.example",
+ "access-control-request-method": "POST",
+ "access-control-request-headers": "authorization,content-type",
+ }
+ )
+ assert middleware.preflight_response(request).status_code == 400
+ state.cloudflare_url = "https://public.trycloudflare.com"
+ response = middleware.preflight_response(request)
+ assert response.status_code == 200
+ assert response.headers["access-control-allow-origin"] == "https://browser-client.example"
+ state.cloudflare_url = None
+ assert middleware.preflight_response(request).status_code == 400
+
+
def test_run_server_exports_secure_env_for_cors():
# run_server must export UNSLOTH_SECURE before importing main so the CORS
# profile can tell remote secure serving from local Tauri use.
src = (_BACKEND / "run.py").read_text(encoding = "utf-8")
assert 'os.environ["UNSLOTH_SECURE"] = "1"' in src
+ assert "set_studio_tunnel_runtime_callback(set_remote_connector_active)" in src
+ main_src = (_BACKEND / "main.py").read_text(encoding = "utf-8")
+ assert "RemoteAccessCORSMiddleware,\n remote_access_state = app.state" in main_src
def test_run_server_emit_tauri_port_defaults_on():
@@ -225,3 +304,36 @@ def test_tauri_port_print_is_gated_in_source():
# The TAURI_PORT line must depend on emit_tauri_port, not api_only alone.
src = (_BACKEND / "run.py").read_text(encoding = "utf-8")
assert "if api_only and emit_tauri_port:" in src
+
+
+def test_cors_preflight_cache_window_is_short():
+ # is_allowed_origin closes the instant the tunnel URL clears, but a preflight
+ # the browser already cached does not. Measured in WebKit: with Starlette's
+ # 600s default a state-changing request still reached the server after Stop.
+ from types import SimpleNamespace
+
+ from starlette.datastructures import Headers
+
+ from main import RemoteAccessCORSMiddleware
+
+ middleware = RemoteAccessCORSMiddleware(
+ lambda *_: None,
+ remote_access_state = SimpleNamespace(cloudflare_url = "https://x.trycloudflare.com"),
+ allow_origins = ["tauri://localhost"],
+ allow_credentials = True,
+ allow_methods = ["*"],
+ allow_headers = ["*"],
+ max_age = 60,
+ )
+ response = middleware.preflight_response(
+ Headers({
+ "origin": "https://browser-client.example",
+ "access-control-request-method": "POST",
+ "access-control-request-headers": "authorization",
+ })
+ )
+ assert response.status_code == 200
+ assert int(response.headers["access-control-max-age"]) <= 60
+
+ main_src = (_BACKEND / "main.py").read_text(encoding = "utf-8")
+ assert "max_age = 60" in main_src, "the mounted middleware must pin max_age"
diff --git a/studio/backend/utils/host_policy.py b/studio/backend/utils/host_policy.py
index 55565bb3386..5ee41691f72 100644
--- a/studio/backend/utils/host_policy.py
+++ b/studio/backend/utils/host_policy.py
@@ -27,6 +27,7 @@ _LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"})
# (embedders, tests) a stale loopback default must not carry into a later
# public bind, so we only ever take back a value we set ourselves.
_auto_enabled = False
+_remote_connector_active = False
def is_external_host(host: str) -> bool:
@@ -58,8 +59,8 @@ def apply_stdio_mcp_loopback_default(host: str, *, is_colab: bool = False) -> No
"""Default stdio MCP servers on when bound to loopback.
A loopback bind is the user's own machine -- the same trust boundary the
- Tauri desktop app relies on (see main.py, which also binds 127.0.0.1 and
- setdefaults this var). Colab is excluded: even its loopback is a hosted VM
+ Tauri desktop app relies on (see main.py, which uses this same helper).
+ Colab is excluded: even its loopback is a hosted VM
reachable through Colab's proxy, so it stays off unless opted in. An explicit
operator value wins: a pre-set `UNSLOTH_STUDIO_ALLOW_STDIO_MCP=0`
force-disables and `=1` opts in, including on a network bind. We only ever
@@ -92,7 +93,18 @@ def loopback_default_active() -> bool:
return _auto_enabled
+def set_remote_connector_active(active: bool) -> None:
+ """Publish whether a connector may carry requests from beyond loopback."""
+ global _remote_connector_active
+ _remote_connector_active = bool(active)
+
+
+def remote_connector_active() -> bool:
+ return _remote_connector_active
+
+
def _reset_loopback_default_state() -> None:
- """Test hook: forget any auto-enable applied earlier in this process."""
- global _auto_enabled
+ """Test hook: forget runtime trust state applied earlier in this process."""
+ global _auto_enabled, _remote_connector_active
_auto_enabled = False
+ _remote_connector_active = False
diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.py
index c52a8221fca..6c48e993940 100644
--- a/studio/backend/utils/process_lifetime.py
+++ b/studio/backend/utils/process_lifetime.py
@@ -32,6 +32,8 @@ _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
_JobObjectExtendedLimitInformation = 9
_lock = threading.Lock()
+_spawner_lock = threading.Lock()
+_spawner: "Optional[_Spawner]" = None
_initialized = False
_win_job_handle: Optional[int] = None # retained for the interpreter's lifetime
_tracked_pids: "dict[int, Optional[str]]" = {} # pid -> identity, reaped by terminate_all
@@ -217,6 +219,98 @@ def compose_preexec(
return _composed
+_fork_reset_installed = False
+
+
+def _reset_after_fork() -> None:
+ """A fork child inherits _spawner_lock in whatever state it was in and a
+ _spawner whose thread does not exist here. Start clean instead of deadlocking."""
+ global _spawner, _spawner_lock
+ _spawner_lock = threading.Lock()
+ _spawner = None
+
+
+def _adopt_fork_reset() -> None:
+ """Register the child-side reset once, lazily. Best-effort like the rest of
+ this module: os.register_at_fork is POSIX-only and absent on Windows."""
+ global _fork_reset_installed
+ if _fork_reset_installed:
+ return
+ _fork_reset_installed = True
+ try:
+ os.register_at_fork(after_in_child = _reset_after_fork)
+ except (AttributeError, RuntimeError): # no fork support; nothing to guard
+ pass
+
+
+def spawn_on_lifetime_thread(spawn: Callable[[], object]) -> object:
+ """Run *spawn* (a Popen call) on a thread that lives as long as the process.
+
+ PR_SET_PDEATHSIG fires when the forking THREAD exits, not the process, so a
+ child spawned from a short-lived worker dies as soon as that worker returns.
+ Forking from one process-lifetime thread restores "die with the parent
+ process". Non-Linux arms no per-thread signal, so it spawns directly.
+ """
+ if not _is_linux():
+ return spawn()
+ global _spawner
+ _adopt_fork_reset()
+ with _spawner_lock:
+ if _spawner is None or not _spawner.usable():
+ candidate = _Spawner()
+ _spawner = candidate if candidate.usable() else None
+ spawner = _spawner
+ # No helper thread available (only when threading.Thread is replaced, as
+ # some tests do): spawn inline, the pre-existing behaviour, rather than block.
+ return spawn() if spawner is None else spawner.run(spawn)
+
+
+class _Spawner:
+ """One daemon thread that forks on behalf of any caller. Daemon is correct:
+ the process dies at interpreter exit, which is when children should die."""
+
+ def __init__(self) -> None:
+ import queue
+
+ self._jobs: "queue.Queue" = queue.Queue()
+ self._ready = threading.Event()
+ self._thread = None
+ try:
+ self._thread = threading.Thread(
+ target = self._run, name = "unsloth-child-spawner", daemon = True
+ )
+ self._thread.start()
+ except Exception: # noqa: BLE001 - fall back to an inline spawn
+ self._thread = None
+
+ def usable(self) -> bool:
+ """True only once the helper has actually begun running."""
+ if self._thread is None:
+ return False
+ return self._ready.wait(5.0) and bool(getattr(self._thread, "is_alive", bool)())
+
+ def _run(self) -> None:
+ self._ready.set()
+ while True:
+ spawn, box, done = self._jobs.get()
+ try:
+ box.append((True, spawn()))
+ except BaseException as exc: # noqa: BLE001 - re-raised in the caller
+ box.append((False, exc))
+ finally:
+ done.set()
+
+ def run(self, spawn: Callable[[], object]) -> object:
+ box: list = []
+ done = threading.Event()
+ self._jobs.put((spawn, box, done))
+ done.wait()
+ ok, value = box[0]
+ if not ok:
+ raise value
+ return value
+
+
def child_popen_kwargs(preexec_fn: Optional[Callable[[], None]] = None) -> dict:
"""Popen kwargs that bind a long-lived child to the parent's lifetime.
diff --git a/studio/backend/utils/remote_access_settings.py b/studio/backend/utils/remote_access_settings.py
new file mode 100644
index 00000000000..7d13f6aad03
--- /dev/null
+++ b/studio/backend/utils/remote_access_settings.py
@@ -0,0 +1,369 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Persisted policy and non-blocking runtime operations for Remote access."""
+
+from __future__ import annotations
+
+import threading
+import time
+from typing import Any, Callable
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+REMOTE_ACCESS_AUTO_START_KEY = "remote_access_auto_start"
+DEFAULT_REMOTE_ACCESS_AUTO_START = False
+# Longest a Stop waits for a live start worker to claim settings ownership.
+_STOP_OWNERSHIP_WAIT = 5.0
+
+_worker_lock = threading.Lock()
+_start_worker: threading.Thread | None = None
+_stop_worker: threading.Thread | None = None
+_start_worker_admission: tuple[int, int] | None = None
+_stop_worker_admission: tuple[int, int] | None = None
+_stop_response_condition = threading.Condition()
+_stop_responses_pending = 0
+_stop_response_admission_open = True
+
+
+class RemoteAccessStopResponseMiddleware:
+ """Lease the connector for every Stop request from ASGI admission through response."""
+
+ def __init__(self, app):
+ self.app = app
+
+ async def __call__(self, scope, receive, send):
+ if not (
+ scope.get("type") == "http"
+ and scope.get("method") == "POST"
+ and scope.get("path") == "/api/settings/remote-access/stop"
+ ):
+ await self.app(scope, receive, send)
+ return
+
+ release = acquire_remote_access_stop_response()
+ if release is None:
+ # Teardown has already linearized. Preserve downstream auth and
+ # idempotent route behavior without admitting new drain work.
+ await self.app(scope, receive, send)
+ return
+
+ async def _send(message):
+ await send(message)
+ if message.get("type") == "http.response.body" and not message.get("more_body", False):
+ release()
+
+ try:
+ await self.app(scope, receive, _send)
+ finally:
+ release()
+
+
+def acquire_remote_access_stop_response() -> Callable[[], None] | None:
+ """Hold connector teardown until this HTTP response has been finalized."""
+ global _stop_responses_pending
+ with _stop_response_condition:
+ if not _stop_response_admission_open:
+ return None
+ _stop_responses_pending += 1
+ _stop_response_condition.notify_all()
+ released = False
+
+ def _release() -> None:
+ nonlocal released
+ global _stop_responses_pending
+ with _stop_response_condition:
+ if released:
+ return
+ released = True
+ _stop_responses_pending -= 1
+ _stop_response_condition.notify_all()
+
+ return _release
+
+
+def _open_remote_access_stop_response_admission() -> None:
+ global _stop_response_admission_open
+ with _stop_response_condition:
+ _stop_response_admission_open = True
+ _stop_response_condition.notify_all()
+
+
+def _drain_and_close_remote_access_stop_responses() -> None:
+ """Drain admitted responses, then close admission at the teardown boundary."""
+ global _stop_response_admission_open
+ deadline = time.monotonic() + 1.0
+ quiet_deadline: float | None = None
+ with _stop_response_condition:
+ while True:
+ now = time.monotonic()
+ if now >= deadline:
+ _stop_response_admission_open = False
+ return
+ if _stop_responses_pending:
+ quiet_deadline = None
+ _stop_response_condition.wait(min(0.05, deadline - now))
+ continue
+ if quiet_deadline is None:
+ quiet_deadline = now + 0.05
+ if now >= quiet_deadline:
+ _stop_response_admission_open = False
+ return
+ _stop_response_condition.wait(min(quiet_deadline - now, deadline - now))
+
+
+def _coerce_bool(value: Any) -> bool | None:
+ return value if isinstance(value, bool) else None
+
+
+def get_remote_access_auto_start() -> bool:
+ """Read the preference, failing closed on missing, invalid, or unreadable data."""
+ try:
+ from storage.studio_db import get_app_setting
+ stored = get_app_setting(REMOTE_ACCESS_AUTO_START_KEY, None)
+ except Exception:
+ return False
+ parsed = _coerce_bool(stored)
+ return parsed if parsed is not None else DEFAULT_REMOTE_ACCESS_AUTO_START
+
+
+def set_remote_access_auto_start(enabled: bool) -> bool:
+ if not isinstance(enabled, bool):
+ raise ValueError("Remote access auto-start must be true or false.")
+ from storage.studio_db import upsert_app_settings
+
+ upsert_app_settings({REMOTE_ACCESS_AUTO_START_KEY: enabled})
+ return enabled
+
+
+def _admin_password_ready() -> bool:
+ try:
+ from auth.storage import DEFAULT_ADMIN_USERNAME, requires_password_change
+ return not requires_password_change(DEFAULT_ADMIN_USERNAME)
+ except Exception:
+ return False
+
+
+def configure_remote_access(
+ app_state, *, port: int, intent: str, is_colab: bool, launch_managed: bool
+) -> None:
+ """Publish immutable launch policy used by every settings request."""
+ app_state.remote_access_port = port
+ app_state.remote_access_intent = intent
+ app_state.remote_access_is_colab = bool(is_colab)
+ app_state.remote_access_launch_managed = bool(launch_managed)
+ app_state.remote_access_ready = False
+
+
+def _worker_alive(worker: threading.Thread | None) -> bool:
+ return worker is not None and worker.is_alive()
+
+
+def _worker_is_current(
+ worker: threading.Thread | None, admission: tuple[int, int] | None, current: tuple[int, int]
+) -> bool:
+ if not _worker_alive(worker) or admission is None or admission[0] != current[0]:
+ return False
+ return current[1] in {admission[1], admission[1] + 1}
+
+
+def remote_access_status(app_state) -> dict:
+ from cloudflare_tunnel import get_studio_tunnel_control_token, get_studio_tunnel_status
+
+ status = get_studio_tunnel_status()
+ current = get_studio_tunnel_control_token()
+ with _worker_lock:
+ starting = _worker_is_current(_start_worker, _start_worker_admission, current)
+ stopping = _worker_is_current(_stop_worker, _stop_worker_admission, current)
+ generation_advanced = stopping and _stop_worker_admission[1] != current[1]
+ # A stop worker outlives its teardown. Only one that advanced the generation
+ # and left the tunnel off with nothing pending has actually performed it.
+ if generation_advanced and status["state"] == "off" and not status.get("stop_pending"):
+ stopping = False
+ if stopping:
+ status.update(state = "stopping", managed_by = "settings", url = None, error = None)
+ elif starting and status["state"] in {"off", "error"}:
+ status.update(state = "starting", managed_by = "settings", url = None, error = None)
+
+ intent = getattr(app_state, "remote_access_intent", "disabled")
+ is_colab = bool(getattr(app_state, "remote_access_is_colab", False))
+ launch_managed = bool(getattr(app_state, "remote_access_launch_managed", False))
+ ready = bool(getattr(app_state, "remote_access_ready", False))
+ owner = status["managed_by"]
+ state = status["state"]
+ stop_pending = bool(status.get("stop_pending"))
+ # Reported on its own too: a higher-precedence block hides the reason, but
+ # the desktop still offers setting the password that is pending.
+ password_pending = not _admin_password_ready()
+ block_reason = None
+ if not ready:
+ block_reason = "server_starting"
+ elif is_colab:
+ block_reason = "colab_managed" if owner == "colab" else "colab"
+ elif intent == "disabled":
+ block_reason = "explicitly_disabled"
+ elif launch_managed:
+ block_reason = "launch_managed"
+ elif password_pending:
+ block_reason = "admin_password_change_required"
+ elif owner in {"launch", "colab"}:
+ block_reason = f"{owner}_managed"
+
+ controllable = block_reason is None
+ can_start = controllable and not stopping and not stop_pending and state in {"off", "error"}
+ can_stop = owner == "settings" and (stop_pending or state in {"starting", "online"})
+ error = status["error"]
+ if error not in {
+ None,
+ "cloudflared is unavailable",
+ "cloudflared did not produce a URL",
+ "Cloudflare URL was not reachable",
+ "cloudflared did not register a connection",
+ "cloudflared exited",
+ # Why Start is blocked: the connector's exit was never confirmed, so it
+ # still holds the runtime slot. The generic text hides the one reason
+ # the user can act on.
+ "cloudflared could not be stopped",
+ }:
+ error = "Cloudflare tunnel failed"
+ return {
+ "state": state,
+ "url": status["url"],
+ "error": error,
+ "auto_start": get_remote_access_auto_start(),
+ "available": ready and not is_colab and intent != "disabled",
+ "managed_by": owner,
+ "can_start": can_start,
+ "can_stop": can_stop,
+ "block_reason": block_reason,
+ "password_pending": password_pending,
+ # Every tunnel Studio opens is a Cloudflare Quick Tunnel, and Cloudflare
+ # documents that those do not support Server-Sent Events. Measured: an
+ # SSE endpoint returns 200 with text/event-stream through the tunnel but
+ # delivers no events. So responses are only streamable while no tunnel
+ # is carrying them.
+ "streaming_supported": status["url"] is None,
+ }
+
+
+def start_remote_access(app_state) -> dict:
+ """Schedule a settings-owned start. Repeated requests are idempotent."""
+ global _start_worker, _start_worker_admission
+ from cloudflare_tunnel import (
+ capture_studio_tunnel_start_admission,
+ get_studio_tunnel_control_token,
+ )
+
+ admission = capture_studio_tunnel_start_admission()
+ if admission is None:
+ raise RuntimeError("server_shutting_down")
+ status = remote_access_status(app_state)
+ current = get_studio_tunnel_control_token()
+ if current[0] != admission[0]:
+ raise RuntimeError("server_lifecycle_changed")
+ if status["managed_by"] == "settings" and status["state"] in {"starting", "online"}:
+ return status
+ if not status["can_start"]:
+ raise RuntimeError(status["block_reason"] or "operation_in_progress")
+
+ port = getattr(app_state, "remote_access_port", None)
+ if not isinstance(port, int) or port <= 0:
+ raise RuntimeError("server_port_unavailable")
+ if get_studio_tunnel_control_token() != admission:
+ raise RuntimeError("server_lifecycle_changed")
+
+ def _start() -> None:
+ from cloudflare_tunnel import start_studio_tunnel
+ url = start_studio_tunnel(port, managed_by = "settings", admission = admission)
+ if url:
+ logger.info("Secure link access via Cloudflare: %s", url)
+
+ _open_remote_access_stop_response_admission()
+ with _worker_lock:
+ if not _worker_is_current(_start_worker, _start_worker_admission, admission):
+ _start_worker = threading.Thread(target = _start, daemon = True)
+ _start_worker_admission = admission
+ _start_worker.start()
+ return remote_access_status(app_state)
+
+
+def stop_remote_access(app_state) -> dict:
+ """Schedule a settings-owned stop without changing the auto-start preference."""
+ global _stop_worker, _stop_worker_admission
+ from cloudflare_tunnel import (
+ capture_studio_tunnel_start_admission,
+ get_studio_tunnel_control_token,
+ )
+
+ admission = capture_studio_tunnel_start_admission()
+ if admission is None:
+ raise RuntimeError("server_shutting_down")
+ status = remote_access_status(app_state)
+ current = get_studio_tunnel_control_token()
+ if current[0] != admission[0]:
+ raise RuntimeError("server_lifecycle_changed")
+ if status["state"] == "off" and status["managed_by"] is None:
+ return status
+ if status["state"] == "stopping" and status["managed_by"] == "settings":
+ return status
+ if status["managed_by"] != "settings":
+ raise RuntimeError(status["block_reason"] or "not_settings_managed")
+
+ if get_studio_tunnel_control_token() != admission:
+ raise RuntimeError("server_lifecycle_changed")
+
+ def _stop() -> None:
+ global _stop_worker_admission
+ from cloudflare_tunnel import get_studio_tunnel_status, stop_studio_tunnel
+
+ # A stop can beat the newly-created start worker to the controller. Wait
+ # until it claims settings ownership, then cancel that generation. Bounded:
+ # a start that never claims it (foreign owner, bailed on admission) must
+ # not defer the user's Stop for the probe deadline.
+ deadline = time.monotonic() + _STOP_OWNERSHIP_WAIT
+ while _worker_alive(_start_worker) and time.monotonic() < deadline:
+ if get_studio_tunnel_status()["managed_by"] == "settings":
+ break
+ time.sleep(0.02)
+ current = get_studio_tunnel_control_token()
+ if current[0] != admission[0]:
+ return
+ if get_studio_tunnel_status()["managed_by"] == "settings":
+ # Every Stop admitted before this teardown decision must finish
+ # traversing cloudflared. Closing admission at the end of the drain
+ # prevents a later request from creating an unobserved lease.
+ _drain_and_close_remote_access_stop_responses()
+ current = get_studio_tunnel_control_token()
+ if current[0] != admission[0] or get_studio_tunnel_status()["managed_by"] != "settings":
+ _open_remote_access_stop_response_admission()
+ return
+ with _worker_lock:
+ if _stop_worker is threading.current_thread():
+ _stop_worker_admission = current
+ try:
+ stop_studio_tunnel(admission = current)
+ if get_studio_tunnel_status().get("stop_pending"):
+ _open_remote_access_stop_response_admission()
+ except Exception:
+ _open_remote_access_stop_response_admission()
+ raise
+
+ with _worker_lock:
+ if not _worker_is_current(_stop_worker, _stop_worker_admission, admission):
+ _stop_worker = threading.Thread(target = _stop, daemon = True)
+ _stop_worker_admission = admission
+ _stop_worker.start()
+ return remote_access_status(app_state)
+
+
+def maybe_auto_start_remote_access(app_state) -> bool:
+ """Schedule persisted auto-start when current launch policy permits it."""
+ if not get_remote_access_auto_start():
+ return False
+ try:
+ start_remote_access(app_state)
+ except RuntimeError:
+ return False
+ return True
diff --git a/studio/frontend/package-lock.json b/studio/frontend/package-lock.json
index ea33b4560cc..4395b644e7c 100644
--- a/studio/frontend/package-lock.json
+++ b/studio/frontend/package-lock.json
@@ -60,6 +60,7 @@
"react-day-picker": "^9.13.2",
"react-dom": "^19.2.4",
"react-pdf": "10.4.1",
+ "react-qr-code": "2.2.0",
"react-resizable-panels": "^4.6.4",
"recharts": "3.7.0",
"shadcn": "^4.2.0",
@@ -13248,6 +13249,23 @@
"node": ">=6"
}
},
+ "node_modules/prop-types": {
+ "version": "15.8.1",
+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
+ "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.4.0",
+ "object-assign": "^4.1.1",
+ "react-is": "^16.13.1"
+ }
+ },
+ "node_modules/prop-types/node_modules/react-is": {
+ "version": "16.13.1",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
+ "license": "MIT"
+ },
"node_modules/property-information": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",
@@ -13281,6 +13299,12 @@
"node": ">=6"
}
},
+ "node_modules/qrcode-generator": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-2.0.4.tgz",
+ "integrity": "sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==",
+ "license": "MIT"
+ },
"node_modules/qs": {
"version": "6.15.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",
@@ -13614,6 +13638,19 @@
}
}
},
+ "node_modules/react-qr-code": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/react-qr-code/-/react-qr-code-2.2.0.tgz",
+ "integrity": "sha512-e5nS0UUN22K3Nf8KBRUzemfdJ6OmnN5w+kbnj1lvJaol9RyVRFeGl05bCkxSN2ZegbLxjjYjX1+mmAoX9+fAhw==",
+ "license": "MIT",
+ "dependencies": {
+ "prop-types": "^15.8.1",
+ "qrcode-generator": "^2.0.4"
+ },
+ "peerDependencies": {
+ "react": "*"
+ }
+ },
"node_modules/react-redux": {
"version": "9.2.0",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
diff --git a/studio/frontend/package.json b/studio/frontend/package.json
index f9cf85a06d5..2d67e30a904 100644
--- a/studio/frontend/package.json
+++ b/studio/frontend/package.json
@@ -72,6 +72,7 @@
"react-day-picker": "^9.13.2",
"react-dom": "^19.2.4",
"react-pdf": "10.4.1",
+ "react-qr-code": "2.2.0",
"react-resizable-panels": "^4.6.4",
"recharts": "3.7.0",
"shadcn": "^4.2.0",
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
index d3cd58019a8..11e2cc932a9 100644
--- a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
+++ b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
@@ -14,7 +14,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
-import { usePlatformStore } from "@/config/env";
+import { fetchDeviceType, usePlatformStore } from "@/config/env";
import { getInferenceStatus, unloadModel } from "@/features/chat/api/chat-api";
import { resolveInferenceCheckpointId } from "@/features/chat/lib/apply-inference-status-to-store";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
@@ -22,6 +22,7 @@ import type { ApiMonitorEntry } from "@/features/chat/types/api";
import { isExternalModelId } from "@/features/chat/external-providers";
import { modelIdsMatch } from "@/features/hub/lib/model-identity";
import { useSettingsDialogStore } from "@/features/settings";
+import { remoteApiOrigin } from "@/features/settings/api/remote-access-state";
import { getApiBase, isTauri } from "@/lib/api-base";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { Tick02Icon } from "@/lib/tick-icon";
@@ -498,9 +499,19 @@ export function ApiMonitorPage(): ReactElement {
requestDetail,
} = useApiMonitor();
const serverUrl = usePlatformStore((s) => s.serverUrl);
+ const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
const [unloading, setUnloading] = useState(false);
const [unloadError, setUnloadError] = useState<string | null>(null);
+ useEffect(() => {
+ const refreshRemoteBase = () => {
+ void fetchDeviceType({ force: true });
+ };
+ refreshRemoteBase();
+ window.addEventListener("focus", refreshRemoteBase);
+ return () => window.removeEventListener("focus", refreshRemoteBase);
+ }, []);
+
// Manual release so VRAM frees without the idle timer. /unload matches on the
// internal id, which the monitor does not carry, so read status. unloadResident owns
// the read/unload/recheck sequence: this page's own feature (an API auto-switch) can
@@ -620,7 +631,8 @@ export function ApiMonitorPage(): ReactElement {
// The desktop webview's origin is tauri://, and the packaged app picks its port
// dynamically. Same source as the Agents tab.
const origin = typeof window === "undefined" ? "" : window.location.origin;
- const baseUrl = `${isTauri ? (serverUrl ?? getApiBase()) : origin}/v1`;
+ const localOrigin = isTauri ? (serverUrl ?? getApiBase()) : origin;
+ const baseUrl = `${remoteApiOrigin(cloudflareUrl, localOrigin)}/v1`;
const serverStatus = data?.status ?? "idle";
// Older backends omit the field; only an explicit `false` means recording is off.
const loggingDisabled = data?.logging_enabled === false;
diff --git a/studio/frontend/src/features/settings/api/remote-access-state.ts b/studio/frontend/src/features/settings/api/remote-access-state.ts
new file mode 100644
index 00000000000..c97cdc99ff4
--- /dev/null
+++ b/studio/frontend/src/features/settings/api/remote-access-state.ts
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type RemoteAccessState =
+ | "off"
+ | "starting"
+ | "online"
+ | "stopping"
+ | "error";
+export type RemoteAccessOwner = "launch" | "settings" | "colab" | null;
+const TRAILING_SLASHES_RE = /\/+$/;
+
+export type RemoteAccessStatus = {
+ state: RemoteAccessState;
+ url: string | null;
+ error: string | null;
+ autoStart: boolean;
+ defaultAutoStart: boolean;
+ available: boolean;
+ managedBy: RemoteAccessOwner;
+ canStart: boolean;
+ canStop: boolean;
+ blockReason: string | null;
+ passwordPending: boolean;
+ streamingSupported: boolean;
+};
+
+export type ApiRemoteAccessStatus = {
+ state: RemoteAccessState;
+ url?: string | null;
+ error?: string | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ auto_start: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ default_auto_start: boolean;
+ available: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ managed_by?: RemoteAccessOwner;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ can_start: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ can_stop: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ block_reason?: string | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ password_pending?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ streaming_supported: boolean;
+};
+
+export function normalizeRemoteAccessStatus(
+ status: ApiRemoteAccessStatus,
+): RemoteAccessStatus {
+ return {
+ state: status.state,
+ url: status.url ?? null,
+ error: status.error ?? null,
+ autoStart: status.auto_start,
+ defaultAutoStart: status.default_auto_start,
+ available: status.available,
+ managedBy: status.managed_by ?? null,
+ canStart: status.can_start,
+ canStop: status.can_stop,
+ blockReason: status.block_reason ?? null,
+ passwordPending: status.password_pending === true,
+ streamingSupported: status.streaming_supported,
+ };
+}
+
+export function remoteAccessPollDelay(
+ status: RemoteAccessStatus | null,
+): number {
+ return status?.state === "starting" || status?.state === "stopping"
+ ? 1000
+ : 5000;
+}
+
+export function remoteApiOrigin(
+ remoteUrl: string | null,
+ localOrigin: string,
+): string {
+ return remoteUrl ?? localOrigin;
+}
+
+export function remoteAccessAutoStartReadOnly(
+ status: RemoteAccessStatus | null,
+): boolean {
+ return (
+ status === null ||
+ status.managedBy === "colab" ||
+ status.blockReason === "colab"
+ );
+}
+
+export function remoteAccessStopDisconnectsOrigin(
+ remoteUrl: string | null,
+ browserOrigin: string,
+): boolean {
+ return (
+ remoteUrl?.replace(TRAILING_SLASHES_RE, "") ===
+ browserOrigin.replace(TRAILING_SLASHES_RE, "")
+ );
+}
+
+// A Stop sent from the tunnel's own origin is answered with a terminal off, then
+// that origin dies. Polls landing during teardown still report "stopping", a state
+// this origin can never see resolve, so they must not overwrite the terminal off.
+// One that can still stop the connector proves teardown was abandoned, so the
+// origin is staying up and polls lead again.
+export function remoteAccessSelfStopPoll(
+ next: RemoteAccessStatus,
+ expectingDisconnect: boolean,
+): { expectingDisconnect: boolean; apply: boolean } {
+ if (!expectingDisconnect || next.canStop) {
+ return { expectingDisconnect: false, apply: true };
+ }
+ return { expectingDisconnect: true, apply: next.state !== "stopping" };
+}
+
+export function remoteAccessBlockMessage(
+ reason: string | null,
+ isDesktop: boolean,
+): string | null {
+ switch (reason) {
+ case "server_starting":
+ return "Unsloth is still starting.";
+ case "admin_password_change_required":
+ return isDesktop
+ ? "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.";
+ case "launch_managed":
+ return "This tunnel is managed by the launch command.";
+ case "colab_managed":
+ return "This tunnel is managed by the Colab runtime.";
+ case "colab":
+ return "Remote access settings are managed by the Colab runtime.";
+ default:
+ return null;
+ }
+}
diff --git a/studio/frontend/src/features/settings/api/remote-access.ts b/studio/frontend/src/features/settings/api/remote-access.ts
new file mode 100644
index 00000000000..0582969e1fd
--- /dev/null
+++ b/studio/frontend/src/features/settings/api/remote-access.ts
@@ -0,0 +1,36 @@
+// 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 { authFetch } from "@/features/auth";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+import {
+ type RemoteAccessStatus,
+ normalizeRemoteAccessStatus,
+} from "./remote-access-state";
+
+export type { RemoteAccessStatus } from "./remote-access-state";
+
+async function requestRemoteAccess(
+ path = "",
+ init?: RequestInit,
+): Promise<RemoteAccessStatus> {
+ const response = await authFetch(`/api/settings/remote-access${path}`, init);
+ if (!response.ok) {
+ throw new Error(
+ await readFastApiError(response, "Remote access request failed"),
+ );
+ }
+ return normalizeRemoteAccessStatus(await response.json());
+}
+
+export const loadRemoteAccess = () => requestRemoteAccess();
+export const startRemoteAccess = () =>
+ requestRemoteAccess("/start", { method: "POST" });
+export const stopRemoteAccess = () =>
+ requestRemoteAccess("/stop", { method: "POST" });
+export const updateRemoteAccessAutoStart = (enabled: boolean) =>
+ requestRemoteAccess("/auto-start", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled }),
+ });
diff --git a/studio/frontend/src/features/settings/components/change-password-dialog.tsx b/studio/frontend/src/features/settings/components/change-password-dialog.tsx
index c88fc48cac2..d2a54230595 100644
--- a/studio/frontend/src/features/settings/components/change-password-dialog.tsx
+++ b/studio/frontend/src/features/settings/components/change-password-dialog.tsx
@@ -39,17 +39,46 @@ function booleanField(payload: Record<string, unknown>, key: string): boolean {
}
function changePasswordBody(
+ initial: boolean,
currentPassword: string,
nextPassword: string,
): string {
return JSON.stringify(
- Object.fromEntries([
- ["current_password", currentPassword],
- ["new_password", nextPassword],
- ]),
+ Object.fromEntries(
+ initial
+ ? [["new_password", nextPassword]]
+ : [
+ ["current_password", currentPassword],
+ ["new_password", nextPassword],
+ ],
+ ),
);
}
+function dialogCopy(t: T, initial: boolean) {
+ return initial
+ ? {
+ trigger: t("settings.general.passwordDialog.setTrigger"),
+ title: t("settings.general.passwordDialog.setTitle"),
+ description: t("settings.general.passwordDialog.setDescription", {
+ minLength: MIN_PASSWORD_LENGTH,
+ }),
+ submit: t("settings.general.passwordDialog.setSubmit"),
+ submitting: t("settings.general.passwordDialog.setting"),
+ done: t("settings.general.passwordDialog.setDone"),
+ }
+ : {
+ trigger: t("settings.general.passwordDialog.trigger"),
+ title: t("settings.general.passwordDialog.title"),
+ description: t("settings.general.passwordDialog.description", {
+ minLength: MIN_PASSWORD_LENGTH,
+ }),
+ submit: t("settings.general.passwordDialog.update"),
+ submitting: t("settings.general.passwordDialog.updating"),
+ done: t("settings.general.passwordDialog.updated"),
+ };
+}
+
function hasStartedTooShortPassword(value: string): boolean {
return value.length > 0 && value.length < MIN_PASSWORD_LENGTH;
}
@@ -64,11 +93,12 @@ function hasReusablePassword(currentPassword: string, nextPassword: string) {
function passwordValidationMessage(
t: T,
+ initial: boolean,
currentPassword: string,
nextPassword: string,
confirmPassword: string,
): string {
- if (currentPassword.length < MIN_PASSWORD_LENGTH) {
+ if (!initial && currentPassword.length < MIN_PASSWORD_LENGTH) {
return t("settings.general.passwordDialog.currentTooShort", {
minLength: MIN_PASSWORD_LENGTH,
});
@@ -104,6 +134,7 @@ async function unauthorizedDetail(response: Response): Promise<string | null> {
}
function postChangePassword(
+ initial: boolean,
currentPassword: string,
nextPassword: string,
): Promise<Response> {
@@ -112,24 +143,40 @@ function postChangePassword(
if (token) {
headers.set("Authorization", `Bearer ${token}`);
}
- return fetch(apiUrl("/api/auth/change-password"), {
- method: "POST",
- headers,
- body: changePasswordBody(currentPassword, nextPassword),
- });
+ return fetch(
+ apiUrl(
+ initial
+ ? "/api/auth/desktop-initial-password"
+ : "/api/auth/change-password",
+ ),
+ {
+ method: "POST",
+ headers,
+ body: changePasswordBody(initial, currentPassword, nextPassword),
+ },
+ );
}
async function requestPasswordChange(
+ initial: boolean,
currentPassword: string,
nextPassword: string,
): Promise<Record<string, unknown>> {
- let response = await postChangePassword(currentPassword, nextPassword);
+ let response = await postChangePassword(
+ initial,
+ currentPassword,
+ nextPassword,
+ );
const detail = await unauthorizedDetail(response);
if (response.status === 401 && detail !== WRONG_CURRENT_PASSWORD_DETAIL) {
// Retry token/session 401s, but never turn the endpoint's
// "wrong current password" validation into a session refresh/logout.
if (await refreshSession()) {
- response = await postChangePassword(currentPassword, nextPassword);
+ response = await postChangePassword(
+ initial,
+ currentPassword,
+ nextPassword,
+ );
}
}
if (!response.ok) {
@@ -146,14 +193,25 @@ async function requestPasswordChange(
* POST /api/auth/change-password endpoint. The forced first-login flow lives at
* /change-password and bounces non-forced users to /login, so day-to-day changes
* need their own self-contained entry point here.
+ *
+ * ``initial`` switches to the desktop route that sets the first password: the
+ * desktop app authenticates with a local secret and never saw the seeded
+ * password, so it has no current password to supply.
*/
-export function ChangePasswordDialog() {
+export function ChangePasswordDialog({
+ initial = false,
+ onDone,
+}: {
+ initial?: boolean;
+ onDone?: () => void;
+}) {
const t = useT();
const [open, setOpen] = useState(false);
const [current, setCurrent] = useState("");
const [next, setNext] = useState("");
const [confirm, setConfirm] = useState("");
const [submitting, setSubmitting] = useState(false);
+ const copy = dialogCopy(t, initial);
const reset = () => {
setCurrent("");
@@ -168,6 +226,7 @@ export function ChangePasswordDialog() {
const samePassword = hasReusablePassword(current, next);
const validationMessage = passwordValidationMessage(
t,
+ initial,
current,
next,
confirm,
@@ -182,7 +241,7 @@ export function ChangePasswordDialog() {
}
setSubmitting(true);
try {
- const data = await requestPasswordChange(current, next);
+ const data = await requestPasswordChange(initial, current, next);
const accessToken = stringField(data, "access_token");
const refreshToken = stringField(data, "refresh_token");
if (!(accessToken && refreshToken)) {
@@ -191,9 +250,10 @@ export function ChangePasswordDialog() {
// The endpoint rotates the JWT secret and returns fresh tokens.
storeAuthTokens(accessToken, refreshToken);
setMustChangePassword(booleanField(data, "must_change_password"));
- toast.success(t("settings.general.passwordDialog.updated"));
+ toast.success(copy.done);
reset();
setOpen(false);
+ onDone?.();
} catch (err) {
toast.error(
err instanceof Error && err.message
@@ -220,7 +280,7 @@ export function ChangePasswordDialog() {
>
<DialogTrigger asChild={true}>
<Button variant="outline" size="sm" className="h-8">
- {t("settings.general.passwordDialog.trigger")}
+ {copy.trigger}
</Button>
</DialogTrigger>
<DialogContent
@@ -239,37 +299,33 @@ export function ChangePasswordDialog() {
>
<form onSubmit={submit}>
<DialogHeader>
- <DialogTitle>
- {t("settings.general.passwordDialog.title")}
- </DialogTitle>
- <DialogDescription>
- {t("settings.general.passwordDialog.description", {
- minLength: MIN_PASSWORD_LENGTH,
- })}
- </DialogDescription>
+ <DialogTitle>{copy.title}</DialogTitle>
+ <DialogDescription>{copy.description}</DialogDescription>
</DialogHeader>
<div className="mt-4 space-y-3">
- <div className="space-y-1.5">
- <Label htmlFor="cp-current">
- {t("settings.general.passwordDialog.currentPassword")}
- </Label>
- <Input
- id="cp-current"
- type="password"
- autoComplete="current-password"
- value={current}
- onChange={(e) => setCurrent(e.target.value)}
- minLength={MIN_PASSWORD_LENGTH}
- disabled={submitting}
- />
- {currentTooShort ? (
- <p className="text-xs text-destructive" aria-live="polite">
- {t("settings.general.passwordDialog.currentTooShort", {
- minLength: MIN_PASSWORD_LENGTH,
- })}
- </p>
- ) : null}
- </div>
+ {initial ? null : (
+ <div className="space-y-1.5">
+ <Label htmlFor="cp-current">
+ {t("settings.general.passwordDialog.currentPassword")}
+ </Label>
+ <Input
+ id="cp-current"
+ type="password"
+ autoComplete="current-password"
+ value={current}
+ onChange={(e) => setCurrent(e.target.value)}
+ minLength={MIN_PASSWORD_LENGTH}
+ disabled={submitting}
+ />
+ {currentTooShort ? (
+ <p className="text-xs text-destructive" aria-live="polite">
+ {t("settings.general.passwordDialog.currentTooShort", {
+ minLength: MIN_PASSWORD_LENGTH,
+ })}
+ </p>
+ ) : null}
+ </div>
+ )}
<div className="space-y-1.5">
<Label htmlFor="cp-new">
{t("settings.general.passwordDialog.newPassword")}
@@ -317,9 +373,7 @@ export function ChangePasswordDialog() {
</div>
<DialogFooter className="mt-5">
<Button type="submit" disabled={disabled}>
- {submitting
- ? t("settings.general.passwordDialog.updating")
- : t("settings.general.passwordDialog.update")}
+ {submitting ? copy.submitting : copy.submit}
</Button>
</DialogFooter>
</form>
diff --git a/studio/frontend/src/features/settings/components/remote-access-section.tsx b/studio/frontend/src/features/settings/components/remote-access-section.tsx
new file mode 100644
index 00000000000..6cf82b11cb9
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/remote-access-section.tsx
@@ -0,0 +1,415 @@
+// 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 { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Switch } from "@/components/ui/switch";
+import { usePlatformStore } from "@/config/env";
+import {
+ loadRemoteAccess,
+ startRemoteAccess,
+ stopRemoteAccess,
+ updateRemoteAccessAutoStart,
+} from "@/features/settings/api/remote-access";
+import {
+ type RemoteAccessStatus,
+ remoteAccessAutoStartReadOnly,
+ remoteAccessBlockMessage,
+ remoteAccessPollDelay,
+ remoteAccessSelfStopPoll,
+ remoteAccessStopDisconnectsOrigin,
+} from "@/features/settings/api/remote-access-state";
+import { isTauri } from "@/lib/api-base";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { Tick02Icon } from "@/lib/tick-icon";
+import { cn } from "@/lib/utils";
+import {
+ Copy01Icon,
+ Globe02Icon,
+ QrCodeIcon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import QRCode from "react-qr-code";
+import { ChangePasswordDialog } from "./change-password-dialog";
+import { SettingsRow } from "./settings-row";
+
+type RemoteAccessOperation = "start" | "stop" | "auto";
+
+const STATE_LABEL: Record<RemoteAccessStatus["state"], string> = {
+ off: "Off",
+ starting: "Starting",
+ online: "Online",
+ stopping: "Stopping",
+ error: "Error",
+};
+
+const OWNER_LABEL: Record<
+ Exclude<RemoteAccessStatus["managedBy"], null>,
+ string
+> = {
+ launch: "Launch managed",
+ settings: "Settings managed",
+ colab: "Colab managed",
+};
+
+function stateDotClass(state?: RemoteAccessStatus["state"]): string {
+ if (state === "online") {
+ return "bg-emerald-500";
+ }
+ if (state === "starting" || state === "stopping") {
+ return "animate-pulse bg-blue-500";
+ }
+ return state === "error" ? "bg-red-500" : "bg-muted-foreground";
+}
+
+function AccessStatus({ status }: { status: RemoteAccessStatus | null }) {
+ const owner = status?.managedBy ? OWNER_LABEL[status.managedBy] : null;
+ return (
+ <output
+ className="flex items-center gap-1.5 text-xs text-muted-foreground"
+ aria-live="polite"
+ >
+ <span
+ className={cn("size-2 rounded-full", stateDotClass(status?.state))}
+ />
+ {status ? STATE_LABEL[status.state] : "Unavailable"}
+ {owner ? ` · ${owner}` : ""}
+ </output>
+ );
+}
+
+function CopyRemoteUrlButton({ url }: { url: string }) {
+ const [copied, setCopied] = useState(false);
+ const copyTimer = useRef<number | null>(null);
+ useEffect(() => {
+ return () => {
+ if (copyTimer.current !== null) {
+ window.clearTimeout(copyTimer.current);
+ }
+ };
+ }, []);
+ return (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="gap-1.5"
+ onClick={async () => {
+ if (!(await copyToClipboard(url))) {
+ return;
+ }
+ setCopied(true);
+ if (copyTimer.current !== null) {
+ window.clearTimeout(copyTimer.current);
+ }
+ copyTimer.current = window.setTimeout(() => setCopied(false), 1800);
+ }}
+ >
+ <HugeiconsIcon
+ icon={copied ? Tick02Icon : Copy01Icon}
+ className="size-3.5"
+ />
+ {copied ? "Copied" : "Copy URL"}
+ </Button>
+ );
+}
+
+function RemoteUrlQrButton({ url }: { url: string }) {
+ return (
+ <Dialog>
+ <DialogTrigger asChild={true}>
+ <Button type="button" size="sm" variant="outline" className="gap-1.5">
+ <HugeiconsIcon icon={QrCodeIcon} className="size-3.5" />
+ QR
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-xs">
+ <DialogHeader>
+ <DialogTitle>Open on your phone</DialogTitle>
+ <DialogDescription>
+ Scan to open the remote URL in your phone’s browser.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="mx-auto mt-2 rounded-md bg-white p-3">
+ <QRCode value={url} size={192} />
+ </div>
+ <code className="block break-all text-center font-mono text-xs text-muted-foreground">
+ {url}
+ </code>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function StatusMessage({
+ message,
+ destructive,
+}: {
+ message?: string | null;
+ destructive?: boolean;
+}) {
+ if (!message) {
+ return null;
+ }
+ return (
+ <p
+ className={cn(
+ "border-t border-border/60 px-4 py-2.5 text-xs leading-snug",
+ destructive ? "text-destructive" : "text-muted-foreground",
+ )}
+ >
+ {message}
+ </p>
+ );
+}
+
+function RemoteUrlPanel({ url }: { url: string | null }) {
+ if (!url) {
+ return null;
+ }
+ 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">
+ <span className="text-sm font-medium text-foreground">Remote URL</span>
+ <div className="flex items-center gap-2">
+ <RemoteUrlQrButton url={url} />
+ <CopyRemoteUrlButton url={url} />
+ </div>
+ </div>
+ <code className="block w-full break-all rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground">
+ {url}
+ </code>
+ <span className="text-xs text-muted-foreground leading-snug">
+ Anyone with this URL and the remote password can sign in.
+ </span>
+ </div>
+ );
+}
+
+// Desktop signs in with a local secret, so the account password exists only for
+// remote browsers and is managed here rather than in the General tab.
+function RemotePasswordRow({
+ status,
+ onDone,
+}: {
+ status: RemoteAccessStatus | null;
+ onDone: () => void;
+}) {
+ if (!(isTauri && status)) {
+ return null;
+ }
+ return (
+ <SettingsRow
+ label="Remote password"
+ description="Remote browsers sign in as unsloth. The Unsloth Desktop App keeps signing in automatically."
+ >
+ <ChangePasswordDialog initial={status.passwordPending} onDone={onDone} />
+ </SettingsRow>
+ );
+}
+
+export function RemoteAccessSection() {
+ const [status, setStatus] = useState<RemoteAccessStatus | null>(null);
+ const [busy, setBusy] = useState<RemoteAccessOperation | null>(null);
+ const [pollRevision, setPollRevision] = useState(0);
+ const [pollEnabled, setPollEnabled] = useState(true);
+ const mutationEpoch = useRef(0);
+ const pollSuppressed = useRef(false);
+ const selfStopDisconnectExpected = useRef(false);
+
+ const applyStatus = useCallback((next: RemoteAccessStatus) => {
+ setStatus(next);
+ usePlatformStore.setState({ cloudflareUrl: next.url });
+ }, []);
+
+ // A password change rotates credentials outside this section's requests;
+ // discard any in-flight poll and re-read so the block resolves at once.
+ const refreshStatus = useCallback(() => {
+ mutationEpoch.current += 1;
+ setPollEnabled(true);
+ setPollRevision((revision) => revision + 1);
+ }, []);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: pollRevision intentionally restarts polling after a mutation
+ useEffect(() => {
+ if (!pollEnabled) {
+ return;
+ }
+ let stopped = false;
+ let timer: number | null = null;
+ const schedule = (next: RemoteAccessStatus | null) => {
+ if (!stopped && !pollSuppressed.current) {
+ timer = window.setTimeout(poll, remoteAccessPollDelay(next));
+ }
+ };
+ const poll = () => {
+ if (pollSuppressed.current) {
+ return;
+ }
+ const epoch = mutationEpoch.current;
+ loadRemoteAccess()
+ .then((next) => {
+ if (
+ !stopped &&
+ !pollSuppressed.current &&
+ mutationEpoch.current === epoch
+ ) {
+ const settled = remoteAccessSelfStopPoll(
+ next,
+ selfStopDisconnectExpected.current,
+ );
+ selfStopDisconnectExpected.current = settled.expectingDisconnect;
+ if (settled.apply) {
+ applyStatus(next);
+ }
+ }
+ schedule(next);
+ })
+ .catch(() => {
+ if (mutationEpoch.current !== epoch) {
+ return;
+ }
+ if (selfStopDisconnectExpected.current) {
+ setPollEnabled(false);
+ return;
+ }
+ schedule(null);
+ });
+ };
+ poll();
+ return () => {
+ stopped = true;
+ if (timer !== null) {
+ window.clearTimeout(timer);
+ }
+ };
+ }, [applyStatus, pollEnabled, pollRevision]);
+
+ const perform = async (
+ operation: RemoteAccessOperation,
+ request: () => Promise<RemoteAccessStatus>,
+ pausePollingAfterSuccess = false,
+ ) => {
+ mutationEpoch.current += 1;
+ pollSuppressed.current = true;
+ setBusy(operation);
+ try {
+ applyStatus(await request());
+ if (pausePollingAfterSuccess) {
+ selfStopDisconnectExpected.current = true;
+ }
+ } catch {
+ // Polling resumes below and reconciles the visible state.
+ } finally {
+ setBusy(null);
+ pollSuppressed.current = false;
+ // A stop through the tunnel latches polling off when its own origin dies.
+ // Any later action means the user is on a reachable origin, so resume.
+ setPollEnabled(true);
+ setPollRevision((revision) => revision + 1);
+ }
+ };
+
+ const start = () => perform("start", startRemoteAccess);
+ const stop = () =>
+ perform(
+ "stop",
+ stopRemoteAccess,
+ remoteAccessStopDisconnectsOrigin(
+ status?.url ?? null,
+ typeof window === "undefined" ? "" : window.location.origin,
+ ),
+ );
+ const setAutoStart = (enabled: boolean) =>
+ perform("auto", () => updateRemoteAccessAutoStart(enabled));
+
+ const blockMessage = remoteAccessBlockMessage(
+ status?.blockReason ?? null,
+ isTauri,
+ );
+ const stopAction =
+ status?.canStop === true ||
+ status?.state === "starting" ||
+ status?.state === "online" ||
+ status?.state === "stopping";
+ const actionDisabled =
+ busy !== null || (stopAction ? !status?.canStop : !status?.canStart);
+ const actionLabel =
+ busy === "start"
+ ? "Starting…"
+ : busy === "stop"
+ ? "Stopping…"
+ : stopAction
+ ? "Stop"
+ : "Start";
+
+ return (
+ <section
+ data-settings-label="Remote access"
+ className="overflow-hidden rounded-lg border border-border/70"
+ >
+ <div className="flex items-center justify-between gap-4 bg-muted/30 p-4">
+ <div className="flex min-w-0 items-start gap-3">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-md border border-border/70 bg-muted/40">
+ <HugeiconsIcon
+ icon={Globe02Icon}
+ className="size-4 text-foreground"
+ />
+ </div>
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="text-base font-semibold font-heading text-foreground">
+ Remote access
+ </h2>
+ <AccessStatus status={status} />
+ </div>
+ <p className="text-xs text-muted-foreground leading-relaxed">
+ Use Unsloth and its APIs from other devices through a secure,
+ temporary Cloudflare URL.
+ </p>
+ </div>
+ </div>
+ <Button
+ type="button"
+ size="sm"
+ variant={stopAction ? "outline" : "default"}
+ className="min-w-20 shrink-0"
+ onClick={stopAction ? stop : start}
+ disabled={actionDisabled}
+ >
+ {actionLabel}
+ </Button>
+ </div>
+
+ <StatusMessage
+ message={blockMessage ?? status?.error}
+ destructive={!blockMessage}
+ />
+ <RemoteUrlPanel url={status?.url ?? null} />
+
+ <div className="border-t border-border/60 px-4 py-1">
+ <RemotePasswordRow status={status} onDone={refreshStatus} />
+
+ <SettingsRow
+ label="Start automatically"
+ description="Create a new remote URL each time Unsloth starts. Stopping remote access now won’t turn this off."
+ >
+ <Switch
+ checked={status?.autoStart ?? false}
+ disabled={busy !== null || remoteAccessAutoStartReadOnly(status)}
+ onCheckedChange={setAutoStart}
+ aria-label="Start automatically"
+ />
+ </SettingsRow>
+ </div>
+ </section>
+ );
+}
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 33aa900b5cc..b20f948ed38 100644
--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
@@ -19,6 +19,7 @@ import { ApiKeyRow } from "../components/api-key-row";
import { CreateKeyForm } from "../components/create-key-form";
import { ModelAutoSwitchSection } from "../components/model-auto-switch-section";
import { KeyRevealCard } from "../components/key-reveal-card";
+import { RemoteAccessSection } from "../components/remote-access-section";
import { UsageExamples } from "../components/usage-examples";
export function ApiKeysTab() {
@@ -170,6 +171,8 @@ export function ApiKeysTab() {
<MonitorLink />
+ <RemoteAccessSection />
+
<ModelAutoSwitchSection />
<UsageExamples apiKey={revealed} />
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index 7f739d24031..f8427b7320c 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -550,8 +550,8 @@ export function GeneralTab() {
</div>
</SettingsRow>
{/* The desktop app authenticates via desktop auto-auth with a generated
- secret, so there is no user-entered password to change here (and
- changing it would clear the desktop secret). Web only. */}
+ secret, so this password only governs remote browsers and is managed
+ in Remote access instead. Web only. */}
{isTauri ? null : (
<SettingsRow
label={t("settings.general.password")}
diff --git a/studio/frontend/src/features/studio/history-card-grid.tsx b/studio/frontend/src/features/studio/history-card-grid.tsx
index da243242802..670f58c2c19 100644
--- a/studio/frontend/src/features/studio/history-card-grid.tsx
+++ b/studio/frontend/src/features/studio/history-card-grid.tsx
@@ -253,28 +253,8 @@ export function HistoryCardGrid({
const [manualFetchInFlight, setManualFetchInFlight] = useState(false);
const { resumeTrainingRunFromHistory, startBlocked, stopRequested } =
useTrainingActions();
- // Copy-link base: Cloudflare tunnel > LAN host:port > origin. The tunnel registers shortly
- // after startup, so poll (bounded) until it shows.
- const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
- const serverUrl = usePlatformStore((s) => s.serverUrl);
- useEffect(() => {
- if (cloudflareUrl) return;
- let cancelled = false;
- void (async () => {
- for (let attempt = 0; attempt < 12 && !cancelled; attempt++) {
- try {
- await fetchDeviceType({ force: true });
- } catch {
- // Ignore startup blips; copy-link falls back to serverUrl/origin.
- }
- if (cancelled || usePlatformStore.getState().cloudflareUrl) return;
- await new Promise((r) => setTimeout(r, 2500));
- }
- })();
- return () => {
- cancelled = true;
- };
- }, [cloudflareUrl]);
+ // Copy-link base: Cloudflare tunnel > LAN host:port > origin. The tunnel can now
+ // start and stop at any time, so refresh on click instead of polling at mount.
const userControllerRef = useRef<AbortController | null>(null);
const pollControllerRef = useRef<AbortController | null>(null);
@@ -622,11 +602,20 @@ export function HistoryCardGrid({
size="xs"
variant="outline"
className="absolute bottom-3 right-4 z-10 h-6 rounded-full px-2.5 text-ui-11 leading-none shadow-sm"
- onClick={async () => {
+ onClick={async (e) => {
+ e.stopPropagation();
+ try {
+ await fetchDeviceType({ force: true });
+ } catch {
+ // Fall back to the last known server URL or this origin.
+ }
+ // Encode each segment but keep "/" so the /p route matches.
const ref = (run.preview_ref ?? "")
.split("/")
.map(encodeURIComponent)
.join("/");
+ const { cloudflareUrl, serverUrl } =
+ usePlatformStore.getState();
const base = (
cloudflareUrl ??
serverUrl ??
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 31ad29850c3..cd7aee6ad6b 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -317,6 +317,13 @@ export const ar = {
title: "تغيير كلمة المرور",
description:
"أدخل كلمة المرور الحالية واختر كلمة مرور جديدة (بحد أدنى {minLength} حرفًا).",
+ setTrigger: "تعيين كلمة مرور الوصول عن بُعد",
+ setTitle: "تعيين كلمة مرور الوصول عن بُعد",
+ setDescription:
+ "اختر كلمة المرور التي تسجّل بها المتصفحات البعيدة الدخول باسم unsloth (بحد أدنى {minLength} حرفًا). سيواصل تطبيق Unsloth لسطح المكتب تسجيل الدخول تلقائيًا.",
+ setSubmit: "تعيين كلمة المرور",
+ setting: "جارٍ التعيين...",
+ setDone: "تم تعيين كلمة المرور.",
currentPassword: "كلمة المرور الحالية",
newPassword: "كلمة المرور الجديدة",
confirmPassword: "تأكيد كلمة المرور الجديدة",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index ef50b19c83a..d42ce3354bb 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -329,6 +329,13 @@ export const de = {
title: "Passwort ändern",
description:
"Geben Sie Ihr aktuelles Passwort ein und wählen Sie ein neues (mindestens {minLength} Zeichen).",
+ setTrigger: "Remote-Passwort festlegen",
+ setTitle: "Remote-Passwort festlegen",
+ setDescription:
+ "Wählen Sie das Passwort, mit dem sich entfernte Browser als unsloth anmelden (mindestens {minLength} Zeichen). Die Unsloth Desktop-App meldet sich weiterhin automatisch an.",
+ setSubmit: "Passwort festlegen",
+ setting: "Wird festgelegt...",
+ setDone: "Passwort festgelegt.",
currentPassword: "Aktuelles Passwort",
newPassword: "Neues Passwort",
confirmPassword: "Neues Passwort bestätigen",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 7a55d29fc8a..f0af4dc67fc 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -313,6 +313,13 @@ export const en = {
title: "Change password",
description:
"Enter your current password and choose a new one (at least {minLength} characters).",
+ setTrigger: "Set remote password",
+ setTitle: "Set remote password",
+ setDescription:
+ "Choose the password remote browsers sign in with as unsloth (at least {minLength} characters). The Unsloth Desktop App keeps signing in automatically.",
+ setSubmit: "Set password",
+ setting: "Setting...",
+ setDone: "Password set.",
currentPassword: "Current password",
newPassword: "New password",
confirmPassword: "Confirm new password",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index bb8f3d46969..20bfc92eadf 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -326,6 +326,13 @@ export const es = {
title: "Cambiar contraseña",
description:
"Introduce tu contraseña actual y elige una nueva (al menos {minLength} caracteres).",
+ setTrigger: "Establecer contraseña remota",
+ setTitle: "Establecer contraseña remota",
+ setDescription:
+ "Elige la contraseña con la que los navegadores remotos inician sesión como unsloth (al menos {minLength} caracteres). La app de escritorio de Unsloth sigue iniciando sesión automáticamente.",
+ setSubmit: "Establecer contraseña",
+ setting: "Estableciendo...",
+ setDone: "Contraseña establecida.",
currentPassword: "Contraseña actual",
newPassword: "Contraseña nueva",
confirmPassword: "Confirmar contraseña nueva",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 6382ea2ba6f..5d70202bdc1 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -328,6 +328,13 @@ export const fr = {
title: "Changer le mot de passe",
description:
"Saisissez votre mot de passe actuel et choisissez-en un nouveau (au moins {minLength} caractères).",
+ setTrigger: "Définir le mot de passe distant",
+ setTitle: "Définir le mot de passe distant",
+ setDescription:
+ "Choisissez le mot de passe utilisé par les navigateurs distants pour se connecter avec l'identifiant unsloth (au moins {minLength} caractères). L'application de bureau Unsloth continue de se connecter automatiquement.",
+ setSubmit: "Définir le mot de passe",
+ setting: "Définition...",
+ setDone: "Mot de passe défini.",
currentPassword: "Mot de passe actuel",
newPassword: "Nouveau mot de passe",
confirmPassword: "Confirmer le nouveau mot de passe",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index f9fb8ebc110..15a5ef77fc5 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -322,6 +322,13 @@ export const hi = {
title: "पासवर्ड बदलें",
description:
"अपना वर्तमान पासवर्ड दर्ज करें और एक नया चुनें (कम से कम {minLength} अक्षर)।",
+ setTrigger: "रिमोट पासवर्ड सेट करें",
+ setTitle: "रिमोट पासवर्ड सेट करें",
+ setDescription:
+ "वह पासवर्ड चुनें जिससे रिमोट ब्राउज़र unsloth के रूप में साइन इन करते हैं (कम से कम {minLength} अक्षर)। Unsloth डेस्कटॉप ऐप स्वतः साइन इन करता रहेगा।",
+ setSubmit: "पासवर्ड सेट करें",
+ setting: "सेट हो रहा है...",
+ setDone: "पासवर्ड सेट हो गया।",
currentPassword: "वर्तमान पासवर्ड",
newPassword: "नया पासवर्ड",
confirmPassword: "नए पासवर्ड की पुष्टि करें",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 6cc3d3d0984..c168befd529 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -293,6 +293,13 @@ export const it = {
title: "Cambia password",
description:
"Inserisci la password attuale e scegline una nuova (almeno {minLength} caratteri).",
+ setTrigger: "Imposta la password remota",
+ setTitle: "Imposta la password remota",
+ setDescription:
+ "Scegli la password con cui i browser remoti accedono come unsloth (almeno {minLength} caratteri). L'app desktop di Unsloth continua ad accedere automaticamente.",
+ setSubmit: "Imposta la password",
+ setting: "Impostazione...",
+ setDone: "Password impostata.",
currentPassword: "Password attuale",
newPassword: "Nuova password",
confirmPassword: "Conferma la nuova password",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 7364e987486..8f64f7edfc4 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -319,6 +319,12 @@ export const ja = {
trigger: "パスワード変更",
title: "パスワード変更",
description: "現在のパスワードと新しいパスワード(最低 {minLength} 文字)を入力してください。",
+ setTrigger: "リモートパスワードを設定",
+ setTitle: "リモートパスワードを設定",
+ setDescription: "リモートのブラウザーが unsloth としてサインインするためのパスワード(最低 {minLength} 文字)を選んでください。Unsloth デスクトップアプリは引き続き自動でサインインします。",
+ setSubmit: "パスワードを設定",
+ setting: "設定中...",
+ setDone: "パスワードを設定しました。",
currentPassword: "現在のパスワード",
newPassword: "新しいパスワード",
confirmPassword: "新しいパスワード(確認)",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 63481615e4d..e099e740de9 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -317,6 +317,13 @@ export const ko = {
title: "비밀번호 변경",
description:
"현재 비밀번호를 입력하고 새 비밀번호를 선택하세요(최소 {minLength}자).",
+ setTrigger: "원격 비밀번호 설정",
+ setTitle: "원격 비밀번호 설정",
+ setDescription:
+ "원격 브라우저가 unsloth 계정으로 로그인할 때 사용할 비밀번호를 선택하세요(최소 {minLength}자). Unsloth 데스크톱 앱은 계속 자동으로 로그인합니다.",
+ setSubmit: "비밀번호 설정",
+ setting: "설정 중...",
+ setDone: "비밀번호가 설정되었습니다.",
currentPassword: "현재 비밀번호",
newPassword: "새 비밀번호",
confirmPassword: "새 비밀번호 확인",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index e0f6e63116f..69a1b1399b1 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -323,6 +323,13 @@ export const ptBR = {
title: "Alterar senha",
description:
"Insira sua senha atual e escolha uma nova (no mínimo {minLength} caracteres).",
+ setTrigger: "Definir senha remota",
+ setTitle: "Definir senha remota",
+ setDescription:
+ "Escolha a senha que os navegadores remotos usam para entrar como unsloth (no mínimo {minLength} caracteres). O aplicativo de desktop da Unsloth continua entrando automaticamente.",
+ setSubmit: "Definir senha",
+ setting: "Definindo...",
+ setDone: "Senha definida.",
currentPassword: "Senha atual",
newPassword: "Nova senha",
confirmPassword: "Confirmar nova senha",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 7475b81f369..94f5ff45c17 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -322,6 +322,13 @@ export const ru = {
title: "Изменить пароль",
description:
"Введите текущий пароль и выберите новый (не менее {minLength} символов).",
+ setTrigger: "Задать удалённый пароль",
+ setTitle: "Задать удалённый пароль",
+ setDescription:
+ "Выберите пароль, с которым удалённые браузеры входят как unsloth (не менее {minLength} символов). Настольное приложение Unsloth продолжит входить автоматически.",
+ setSubmit: "Задать пароль",
+ setting: "Установка...",
+ setDone: "Пароль задан.",
currentPassword: "Текущий пароль",
newPassword: "Новый пароль",
confirmPassword: "Подтвердите новый пароль",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 28e1c67f538..02673b62719 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -307,6 +307,13 @@ export const zhCN = {
trigger: "更改密码",
title: "更改密码",
description: "输入当前密码并选择新密码(至少 {minLength} 个字符)。",
+ setTrigger: "设置远程密码",
+ setTitle: "设置远程密码",
+ setDescription:
+ "选择远程浏览器以 unsloth 身份登录时使用的密码(至少 {minLength} 个字符)。Unsloth 桌面应用仍会自动登录。",
+ setSubmit: "设置密码",
+ setting: "正在设置...",
+ setDone: "密码已设置。",
currentPassword: "当前密码",
newPassword: "新密码",
confirmPassword: "确认新密码",
diff --git a/studio/frontend/tests/remote-access-state.test.ts b/studio/frontend/tests/remote-access-state.test.ts
new file mode 100644
index 00000000000..be35a8426af
--- /dev/null
+++ b/studio/frontend/tests/remote-access-state.test.ts
@@ -0,0 +1,338 @@
+// 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";
+
+// remote-access-section.tsx pulls in the router, motion and hugeicons, so it
+// cannot be imported here. These drive the pure state helpers it consumes.
+import {
+ type ApiRemoteAccessStatus,
+ normalizeRemoteAccessStatus,
+ remoteAccessAutoStartReadOnly,
+ remoteAccessBlockMessage,
+ remoteAccessPollDelay,
+ remoteAccessSelfStopPoll,
+ remoteAccessStopDisconnectsOrigin,
+ remoteApiOrigin,
+} from "../src/features/settings/api/remote-access-state.ts";
+
+const TUNNEL = "https://calm-otter-review.trycloudflare.com";
+
+function apiStatus(
+ over: Partial<ApiRemoteAccessStatus> = {},
+): ApiRemoteAccessStatus {
+ return {
+ state: "off",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ auto_start: false,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ default_auto_start: false,
+ available: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ can_start: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ can_stop: false,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ streaming_supported: true,
+ ...over,
+ };
+}
+
+// ── normalizeRemoteAccessStatus ──
+
+test("normalize maps every snake_case field onto its camelCase name", () => {
+ const s = normalizeRemoteAccessStatus(
+ apiStatus({
+ state: "online",
+ url: TUNNEL,
+ error: null,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ auto_start: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ default_auto_start: true,
+ available: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ managed_by: "settings",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ can_start: false,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ can_stop: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ block_reason: null,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ password_pending: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ streaming_supported: true,
+ }),
+ );
+ assert.deepEqual(s, {
+ state: "online",
+ url: TUNNEL,
+ error: null,
+ autoStart: true,
+ defaultAutoStart: true,
+ available: true,
+ managedBy: "settings",
+ canStart: false,
+ canStop: true,
+ blockReason: null,
+ passwordPending: true,
+ streamingSupported: true,
+ });
+ // No field may normalize to undefined -- a wrong key would silently do so.
+ for (const [k, v] of Object.entries(s)) {
+ assert.notEqual(v, undefined, `${k} normalized to undefined`);
+ }
+});
+
+test("normalize defaults the optional fields an older backend may omit", () => {
+ const s = normalizeRemoteAccessStatus(apiStatus());
+ assert.equal(s.url, null);
+ assert.equal(s.error, null);
+ assert.equal(s.managedBy, null);
+ assert.equal(s.blockReason, null);
+ assert.equal(s.passwordPending, false);
+});
+
+test("passwordPending is strict: only a real true counts", () => {
+ for (const raw of [undefined, null, 0, "", "true", 1]) {
+ const s = normalizeRemoteAccessStatus(
+ // biome-ignore lint/style/useNamingConvention: API schema
+ apiStatus({ password_pending: raw as never }),
+ );
+ assert.equal(
+ s.passwordPending,
+ false,
+ `password_pending=${JSON.stringify(raw)} must not be truthy`,
+ );
+ }
+ assert.equal(
+ // biome-ignore lint/style/useNamingConvention: API schema
+ normalizeRemoteAccessStatus(apiStatus({ password_pending: true }))
+ .passwordPending,
+ true,
+ );
+});
+
+// ── remoteAccessPollDelay ──
+
+test("poll delay is fast only while a transition is in flight", () => {
+ assert.equal(remoteAccessPollDelay(null), 5000);
+ for (const state of ["starting", "stopping"] as const) {
+ assert.equal(
+ remoteAccessPollDelay(normalizeRemoteAccessStatus(apiStatus({ state }))),
+ 1000,
+ );
+ }
+ for (const state of ["off", "online", "error"] as const) {
+ assert.equal(
+ remoteAccessPollDelay(normalizeRemoteAccessStatus(apiStatus({ state }))),
+ 5000,
+ );
+ }
+});
+
+// ── remoteApiOrigin ──
+
+test("remote origin prefers the live tunnel and falls back to the local one", () => {
+ assert.equal(remoteApiOrigin(TUNNEL, "http://127.0.0.1:8888"), TUNNEL);
+ assert.equal(
+ remoteApiOrigin(null, "http://127.0.0.1:8888"),
+ "http://127.0.0.1:8888",
+ );
+ // An empty string is a real origin ("" from a non-browser context), not a miss.
+ assert.equal(remoteApiOrigin(null, ""), "");
+});
+
+// ── remoteAccessAutoStartReadOnly ──
+
+test("auto-start is read-only with no status, or under Colab ownership", () => {
+ assert.equal(remoteAccessAutoStartReadOnly(null), true);
+ assert.equal(
+ remoteAccessAutoStartReadOnly(
+ // biome-ignore lint/style/useNamingConvention: API schema
+ normalizeRemoteAccessStatus(apiStatus({ managed_by: "colab" })),
+ ),
+ true,
+ );
+ assert.equal(
+ remoteAccessAutoStartReadOnly(
+ // biome-ignore lint/style/useNamingConvention: API schema
+ normalizeRemoteAccessStatus(apiStatus({ block_reason: "colab" })),
+ ),
+ true,
+ );
+ assert.equal(
+ remoteAccessAutoStartReadOnly(
+ // biome-ignore lint/style/useNamingConvention: API schema
+ normalizeRemoteAccessStatus(apiStatus({ managed_by: "launch" })),
+ ),
+ false,
+ );
+ assert.equal(
+ remoteAccessAutoStartReadOnly(normalizeRemoteAccessStatus(apiStatus())),
+ false,
+ );
+});
+
+// ── remoteAccessStopDisconnectsOrigin ──
+// This decides whether the user is warned that Stop will cut their own
+// connection, so a false negative silently drops the warning.
+
+test("stop-disconnects detects the browser sitting on the tunnel origin", () => {
+ assert.equal(remoteAccessStopDisconnectsOrigin(TUNNEL, TUNNEL), true);
+});
+
+test("stop-disconnects normalizes trailing slashes on both sides", () => {
+ assert.equal(remoteAccessStopDisconnectsOrigin(`${TUNNEL}/`, TUNNEL), true);
+ assert.equal(remoteAccessStopDisconnectsOrigin(TUNNEL, `${TUNNEL}/`), true);
+ assert.equal(
+ remoteAccessStopDisconnectsOrigin(`${TUNNEL}///`, `${TUNNEL}/`),
+ true,
+ );
+});
+
+test("stop-disconnects is false for a local browser or a different tunnel", () => {
+ assert.equal(
+ remoteAccessStopDisconnectsOrigin(TUNNEL, "http://127.0.0.1:8888"),
+ false,
+ );
+ assert.equal(
+ remoteAccessStopDisconnectsOrigin(
+ TUNNEL,
+ "https://other-name.trycloudflare.com",
+ ),
+ false,
+ );
+ assert.equal(remoteAccessStopDisconnectsOrigin(null, TUNNEL), false);
+ assert.equal(remoteAccessStopDisconnectsOrigin(null, ""), false);
+});
+
+test("stop-disconnects does not treat a path prefix as the same origin", () => {
+ // A tunnel URL is an origin; nothing should match a longer path under it.
+ assert.equal(
+ remoteAccessStopDisconnectsOrigin(`${TUNNEL}/settings`, TUNNEL),
+ false,
+ );
+});
+
+// ── remoteAccessBlockMessage ──
+
+test("every block reason the backend can emit has a message", () => {
+ // Mirrors utils/remote_access_settings.py's block_reason chain.
+ const reasons = [
+ "server_starting",
+ "admin_password_change_required",
+ "explicitly_disabled",
+ "launch_managed",
+ "colab_managed",
+ "colab",
+ ];
+ for (const reason of reasons) {
+ for (const isDesktop of [true, false]) {
+ const msg = remoteAccessBlockMessage(reason, isDesktop);
+ assert.ok(
+ msg && msg.length > 0,
+ `no message for ${reason} (desktop=${isDesktop})`,
+ );
+ }
+ }
+});
+
+test("the pending-password message is desktop-aware", () => {
+ const desktop = remoteAccessBlockMessage(
+ "admin_password_change_required",
+ true,
+ );
+ const web = remoteAccessBlockMessage("admin_password_change_required", false);
+ assert.notEqual(desktop, web);
+ // Only the web copy should send the user to the CLI.
+ assert.ok(!desktop?.includes("reset-password"));
+ assert.ok(web?.includes("reset-password"));
+});
+
+test("an unknown or absent reason yields no message", () => {
+ assert.equal(remoteAccessBlockMessage(null, false), null);
+ assert.equal(remoteAccessBlockMessage("something_new", false), null);
+ assert.equal(remoteAccessBlockMessage("", true), null);
+});
+
+// ── remoteAccessSelfStopPoll ──
+
+// The frames a Settings page loaded from the tunnel actually sees after Stop:
+// the route fabricates a terminal off, the stop worker then answers "stopping"
+// for the ~50ms teardown drain, and finally the origin goes away.
+const TERMINAL_OFF = normalizeRemoteAccessStatus(
+ apiStatus({
+ state: "off",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ can_start: false,
+ }),
+);
+const DRAINING = normalizeRemoteAccessStatus(
+ apiStatus({
+ state: "stopping",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ managed_by: "settings",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ can_start: false,
+ }),
+);
+
+test("a teardown frame never overwrites the terminal off of a self-origin stop", () => {
+ const settled = remoteAccessSelfStopPoll(DRAINING, true);
+ assert.equal(settled.apply, false);
+ assert.equal(settled.expectingDisconnect, true);
+});
+
+test("a stop that left the connector running takes the card back over", () => {
+ const alive = normalizeRemoteAccessStatus(
+ apiStatus({
+ state: "online",
+ url: TUNNEL,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ managed_by: "settings",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ can_start: false,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ can_stop: true,
+ }),
+ );
+ const settled = remoteAccessSelfStopPoll(alive, true);
+ assert.equal(settled.apply, true);
+ assert.equal(settled.expectingDisconnect, false);
+});
+
+test("a stop that failed still surfaces its error", () => {
+ const failed = normalizeRemoteAccessStatus(
+ apiStatus({ state: "error", error: "cloudflared could not be stopped" }),
+ );
+ const settled = remoteAccessSelfStopPoll(failed, true);
+ assert.equal(settled.apply, true);
+});
+
+test("polls lead as usual when no self-origin stop is pending", () => {
+ for (const frame of [TERMINAL_OFF, DRAINING]) {
+ const settled = remoteAccessSelfStopPoll(frame, false);
+ assert.equal(settled.apply, true);
+ assert.equal(settled.expectingDisconnect, false);
+ }
+});
+
+test("a self-origin stop settles on off, not a permanent stopping", () => {
+ let shown = TERMINAL_OFF;
+ let expecting = true;
+ // Polling restarts in perform()'s finally, so the first poll can still land
+ // inside the drain window before cloudflared exits.
+ for (const frame of [DRAINING, DRAINING]) {
+ const settled = remoteAccessSelfStopPoll(frame, expecting);
+ expecting = settled.expectingDisconnect;
+ if (settled.apply) {
+ shown = frame;
+ }
+ }
+ assert.equal(shown.state, "off");
+ // The origin then dies; the section latches polling off on this flag.
+ assert.equal(expecting, true);
+});
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index 3437bd28b09..7af1426eaf3 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -38,6 +38,10 @@ ROOT_ROUTE = FRONTEND / "app/routes/__root.tsx"
IMAGES_PAGE = FRONTEND / "features/images/images-page.tsx"
VIDEO_PAGE = FRONTEND / "features/video/video-page.tsx"
+REMOTE_ACCESS_SECTION = FRONTEND / "features/settings/components/remote-access-section.tsx"
+PASSWORD_DIALOG = FRONTEND / "features/settings/components/change-password-dialog.tsx"
+GENERAL_TAB = FRONTEND / "features/settings/tabs/general-tab.tsx"
+
CLIPBOARD_FILES = FRONTEND / "features/chat/utils/clipboard-files.ts"
TAURI_CAPABILITIES = REPO / "studio/src-tauri/capabilities/default.json"
CHAT_PAGE = FRONTEND / "features/chat/chat-page.tsx"
@@ -311,6 +315,37 @@ def test_mac_dock_reopens_hidden_main_window():
assert "show_main_window(app)" in reopen_handler
+def test_desktop_manages_the_remote_password_through_the_account_dialog():
+ section = REMOTE_ACCESS_SECTION.read_text(encoding = "utf-8")
+ dialog = PASSWORD_DIALOG.read_text(encoding = "utf-8")
+
+ row = section.split("function RemotePasswordRow", 1)[1].split(
+ "export function RemoteAccessSection", 1
+ )[0]
+ assert "if (!(isTauri && status)) {" in row
+ assert "initial={status.passwordPending}" in row
+ assert "<RemotePasswordRow status={status} onDone={refreshStatus} />" in section
+ assert "{isTauri ? null : (" in GENERAL_TAB.read_text(encoding = "utf-8")
+ # A password change rotates credentials outside the polling requests.
+ refresh = section.split("const refreshStatus = useCallback(", 1)[1].split("}, []);", 1)[0]
+ assert "mutationEpoch.current += 1;" in refresh
+ assert "setPollRevision(" in refresh
+ # Initial mode sends no current password; the web flow it serves keeps it.
+ body = dialog.split("function changePasswordBody", 1)[1].split("function dialogCopy", 1)[0]
+ assert '? [["new_password", nextPassword]]' in body
+ assert '["current_password", currentPassword],' in body
+ post = dialog.split("function postChangePassword", 1)[1].split(
+ "async function requestPasswordChange", 1
+ )[0]
+ assert '? "/api/auth/desktop-initial-password"' in post
+ assert ': "/api/auth/change-password",' in post
+ assert "{initial ? null : (" in dialog
+ assert "if (!initial && currentPassword.length < MIN_PASSWORD_LENGTH)" in dialog
+ submitted = dialog.split("async function submit", 1)[1].split("\n }", 1)[0]
+ assert "storeAuthTokens(accessToken, refreshToken)" in submitted
+ assert "onDone?.()" in submitted
+
+
def test_desktop_startup_waits_for_auth_without_intermediate_handoff():
source = APP_PROVIDER.read_text(encoding = "utf-8")
diff --git a/tests/studio/test_settings_compact_overflow_contract.py b/tests/studio/test_settings_compact_overflow_contract.py
index 46af046aec4..1c8f9dbe7e0 100644
--- a/tests/studio/test_settings_compact_overflow_contract.py
+++ b/tests/studio/test_settings_compact_overflow_contract.py
@@ -8,6 +8,7 @@ SETTINGS_DIALOG = REPO / "studio/frontend/src/features/settings/settings-dialog.
# The monitor has its own page and Settings links to it; the shrink contract covers both.
API_MONITOR_PAGE = REPO / "studio/frontend/src/features/api-monitor/api-monitor-page.tsx"
MONITOR_LINK = REPO / "studio/frontend/src/features/settings/components/monitor-link.tsx"
+REMOTE_ACCESS = REPO / "studio/frontend/src/features/settings/components/remote-access-section.tsx"
GENERAL_TAB = REPO / "studio/frontend/src/features/settings/tabs/general-tab.tsx"
@@ -35,6 +36,16 @@ def test_settings_monitor_link_can_shrink():
assert '<span className="truncate text-xs text-muted-foreground">' in source
+def test_remote_access_card_can_shrink():
+ source = REMOTE_ACCESS.read_text(encoding = "utf-8")
+ # The heading and its status sit beside a button, so they need to shrink.
+ assert '<div className="flex min-w-0 items-start gap-3">' in source
+ assert '<div className="flex min-w-0 flex-col gap-0.5">' in source
+ # A tunnel URL has no spaces to wrap on, so it needs break-all.
+ assert "block w-full break-all rounded-md" in source
+ assert "<RemoteUrlPanel url={status?.url ?? null} />" in source
+
+
def test_embedding_model_controls_stack_on_the_narrowest_viewports():
source = GENERAL_TAB.read_text(encoding = "utf-8")
assert (
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 55457827e22..0796d79af10 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -109,6 +109,7 @@ DESKTOP_SECRET_HASH_KEY = "desktop_secret_hash"
DESKTOP_SECRET_CREATED_AT_KEY = "desktop_secret_created_at"
PBKDF2_ITERATIONS = 100_000
_START_API_KEY_MARKER_ENV = "_UNSLOTH_START_API_KEY_MARKER"
+_CLOUDFLARE_INTENT_ENV = "_UNSLOTH_CLOUDFLARE_INTENT"
def _consume_start_api_key_marker_env() -> bool:
@@ -116,6 +117,19 @@ def _consume_start_api_key_marker_env() -> bool:
return os.environ.pop(_START_API_KEY_MARKER_ENV, None) == "1"
+def _preserve_cloudflare_intent(cloudflare: Optional[bool], secure: bool) -> None:
+ """Carry the user's tri-state choice across compatibility re-execs."""
+ if _CLOUDFLARE_INTENT_ENV in os.environ:
+ return
+ if secure or cloudflare is True:
+ intent = "enabled"
+ elif cloudflare is False:
+ intent = "disabled"
+ else:
+ intent = "unset"
+ os.environ[_CLOUDFLARE_INTENT_ENV] = intent
+
+
# __file__ is unsloth_cli/commands/studio.py -- two parents up is the package root
# (either site-packages or the repo root for editable installs).
_PACKAGE_ROOT = Path(__file__).resolve().parent.parent.parent
@@ -1461,6 +1475,8 @@ def studio_default(
raise typer.Exit(2)
return
+ _preserve_cloudflare_intent(cloudflare, secure)
+
# --secure requires the tunnel; force a loopback bind.
if secure:
if cloudflare is False:
@@ -2024,6 +2040,7 @@ def run(
# Back-compat: --not-secure is a deprecated alias for --no-secure.
secure = _resolve_secure(secure, not_secure)
+ _preserve_cloudflare_intent(cloudflare, secure)
extra_llama_args: List[str] = list(ctx.args) if ctx.args else []
# Tool-call healing/nudging are read from the env at backend import. Resolve here
diff --git a/unsloth_cli/tests/test_studio_cloudflare_flag.py b/unsloth_cli/tests/test_studio_cloudflare_flag.py
index 7287737f75b..d242f326dee 100644
--- a/unsloth_cli/tests/test_studio_cloudflare_flag.py
+++ b/unsloth_cli/tests/test_studio_cloudflare_flag.py
@@ -112,24 +112,32 @@ def _invoke_run(monkeypatch, args):
@pytest.mark.parametrize(
- "extra_flags,expected,unexpected",
+ "extra_flags,expected,unexpected,expected_intent",
[
# Default (no flag) forwards --no-cloudflare explicitly so a mixed-version
# child venv (old default: --cloudflare on) can't re-enable the tunnel.
- ([], "--no-cloudflare", "--cloudflare"),
- (["--cloudflare"], "--cloudflare", "--no-cloudflare"),
- (["--no-cloudflare"], "--no-cloudflare", "--cloudflare"),
+ ([], "--no-cloudflare", "--cloudflare", "unset"),
+ (["--cloudflare"], "--cloudflare", "--no-cloudflare", "enabled"),
+ (["--no-cloudflare"], "--no-cloudflare", "--cloudflare", "disabled"),
# --secure implies the tunnel; never forward --no-cloudflare with it.
- (["--secure"], None, "--no-cloudflare"),
+ (["--secure"], None, "--no-cloudflare", "enabled"),
],
)
-def test_run_reexec_forwards_cloudflare_polarity(monkeypatch, extra_flags, expected, unexpected):
+def test_run_reexec_forwards_cloudflare_polarity(
+ monkeypatch, extra_flags, expected, unexpected, expected_intent
+):
+ studio_mod = _studio()
+ assert f'_CLOUDFLARE_INTENT_ENV = "{studio_mod._CLOUDFLARE_INTENT_ENV}"' in (
+ _REPO_ROOT / "studio/backend/run.py"
+ ).read_text(encoding = "utf-8")
+ monkeypatch.delenv(studio_mod._CLOUDFLARE_INTENT_ENV, raising = False)
captured = _invoke_run(monkeypatch, _BASE + extra_flags)
assert len(captured) == 1, captured
argv = captured[0]
if expected is not None:
assert expected in argv, f"expected {expected} in child argv; got {argv}"
assert unexpected not in argv, f"unexpected {unexpected} in child argv; got {argv}"
+ assert studio_mod.os.environ[studio_mod._CLOUDFLARE_INTENT_ENV] == expected_intent
# ── re-exec forwarding: plain `unsloth studio` ───────────────────────
@@ -171,25 +179,30 @@ def _invoke_studio_default(
@pytest.mark.parametrize(
- "extra_flags,expected,unexpected",
+ "extra_flags,expected,unexpected,expected_intent",
[
# Default (no flag) forwards --no-cloudflare explicitly: _find_run_py can fall
# back to an older studio-venv run.py (default on), so a mixed install must
# not re-enable the tunnel.
- ([], "--no-cloudflare", "--cloudflare"),
- (["--cloudflare"], "--cloudflare", "--no-cloudflare"),
- (["--no-cloudflare"], "--no-cloudflare", "--cloudflare"),
+ ([], "--no-cloudflare", "--cloudflare", "unset"),
+ (["--cloudflare"], "--cloudflare", "--no-cloudflare", "enabled"),
+ (["--no-cloudflare"], "--no-cloudflare", "--cloudflare", "disabled"),
# --secure implies the tunnel; never forward --no-cloudflare with it.
- (["--secure"], None, "--no-cloudflare"),
+ (["--secure"], None, "--no-cloudflare", "enabled"),
],
)
-def test_studio_default_reexec_forwards_cloudflare(monkeypatch, extra_flags, expected, unexpected):
+def test_studio_default_reexec_forwards_cloudflare(
+ monkeypatch, extra_flags, expected, unexpected, expected_intent
+):
+ studio_mod = _studio()
+ monkeypatch.delenv(studio_mod._CLOUDFLARE_INTENT_ENV, raising = False)
captured = _invoke_studio_default(monkeypatch, ["-H", "0.0.0.0"] + extra_flags)
assert len(captured) == 1, captured
argv = captured[0]
if expected is not None:
assert expected in argv, f"expected {expected}; got {argv}"
assert unexpected not in argv, f"unexpected {unexpected}; got {argv}"
+ assert studio_mod.os.environ[studio_mod._CLOUDFLARE_INTENT_ENV] == expected_intent
# ── in-venv path forwards cloudflare into run_server ─────────────────