Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: retry remote access when cloudflared gives no URL (#11225)

Nilayc073b926ce26
diff --git a/studio/backend/cloudflare_tunnel.py b/studio/backend/cloudflare_tunnel.py
index 6efa299ed73..7fb6eb8490c 100644
--- a/studio/backend/cloudflare_tunnel.py
+++ b/studio/backend/cloudflare_tunnel.py
@@ -20,6 +20,7 @@ import subprocess
import sys
import threading
import time
+from collections import deque
from pathlib import Path
from typing import Callable, Optional, Tuple
@@ -32,6 +33,11 @@ _REGISTERED_MARKER = "Registered tunnel connection"
_RELEASE_BASE = "https://github.com/cloudflare/cloudflared/releases/latest/download"
_READY_TIMEOUT = 15.0
+# No URL means the trycloudflare.com request failed; cloudflared exits at once or on its own 15s timeout.
+_NO_URL_RETRY_DELAYS = (2.0, 5.0)
+# run.py starts the tunnel before the CLI banner, so no-URL retries only start if they end within this.
+_NO_URL_RETRY_BUDGET = 30.0
+_OUTPUT_TAIL_LINES = 8
_DOWNLOAD_TIMEOUT = 60
# A registered edge connection does not mean the hostname resolves yet, so the URL is fetched once before it is
@@ -489,6 +495,10 @@ class CloudflareTunnel:
self.on_exit: Optional[Callable[["CloudflareTunnel"], None]] = None
self._reader_exited = False
self._runtime_active = False
+ self._tail: deque = deque(maxlen = _OUTPUT_TAIL_LINES)
+
+ def output_tail(self) -> str:
+ return "\n".join(self._tail)
def start(self) -> None:
cmd = [
@@ -537,6 +547,7 @@ class CloudflareTunnel:
try:
if proc.stdout is not None:
for line in proc.stdout:
+ self._tail.append(line.rstrip())
# stdout closed -> cloudflared has exited. Record why, and unblock any waiters at once
# instead of letting them wait out the full timeout.
if self.url is None:
@@ -645,6 +656,8 @@ _active_lock = threading.Lock()
_start_lock = threading.Lock()
# Latched by stop_studio_tunnel so a shutdown landing between retries cannot start a tunnel nobody will stop.
_shutdown_requested = False
+# Set alongside it so a pending retry delay, which holds _start_lock, ends at once.
+_cancel_retry = threading.Event()
_tunnel_generation = 0
_tunnel_lifecycle = 0
_accepting_starts = True
@@ -809,6 +822,11 @@ def _set_online_locked(url: str) -> None:
_tunnel_error = None
+def _wait_before_retry(delay: float) -> bool:
+ """True if a stop cancelled the delay."""
+ return _cancel_retry.wait(delay)
+
+
def start_studio_tunnel(
port: int,
timeout: float = _READY_TIMEOUT,
@@ -852,6 +870,7 @@ def start_studio_tunnel(
):
return None
_shutdown_requested = False
+ _cancel_retry.clear()
_tunnel_generation += 1
generation = _tunnel_generation
prior_at_start, _active_tunnel = _active_tunnel, None
@@ -873,7 +892,11 @@ def start_studio_tunnel(
_set_failed(generation, managed_by, port, "cloudflared is unavailable")
return None
- for protocol in (None, "http2"):
+ protocols = [None, "http2"]
+ no_url_delays = list(_NO_URL_RETRY_DELAYS)
+ no_url_started = time.monotonic()
+ while protocols:
+ protocol = protocols[0]
with _active_lock:
if _shutdown_requested or generation != _tunnel_generation:
_active_tunnel = None
@@ -941,6 +964,15 @@ def start_studio_tunnel(
return None
return url
saw_url = tunnel.url is not None
+ retry_no_url = not saw_url and bool(no_url_delays)
+ tail = tunnel.output_tail() if hasattr(tunnel, "output_tail") else ""
+ logging.getLogger(__name__).warning(
+ "cloudflared attempt failed (protocol=%s, url=%s, registered=%s)%s",
+ protocol or "auto",
+ saw_url,
+ registered,
+ f":\n{tail}" if tail else "",
+ )
with _active_lock:
was_active = _active_tunnel is tunnel
if was_active:
@@ -961,9 +993,9 @@ def start_studio_tunnel(
elif generation == _tunnel_generation and _active_tunnel is tunnel:
if stopped:
_active_tunnel = None
- # Reset from "stopping" before the http2 retry, or stop_studio_tunnel() early-returns and stops
+ # Reset from "stopping" before a retry, or stop_studio_tunnel() early-returns and stops
# nothing.
- if _tunnel_state == "stopping" and protocol is None:
+ if _tunnel_state == "stopping" and (protocol is None or retry_no_url):
_tunnel_state = "starting"
else:
_active_tunnel = tunnel
@@ -973,12 +1005,19 @@ def start_studio_tunnel(
return None
if not stopped:
return None
+ if retry_no_url:
+ spent = time.monotonic() - no_url_started
+ if spent + no_url_delays[0] + timeout <= _NO_URL_RETRY_BUDGET:
+ if _wait_before_retry(no_url_delays.pop(0)):
+ return None
+ continue
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
+ protocols.pop(0)
_set_failed(generation, managed_by, port, "cloudflared did not register a connection")
return None
@@ -994,9 +1033,11 @@ def stop_studio_tunnel(*, admission: Optional[Tuple[int, int]] = None) -> None:
# 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
+ _cancel_retry.set()
_tunnel_generation += 1
return
_shutdown_requested = True
+ _cancel_retry.set()
_tunnel_generation += 1
stop_generation = _tunnel_generation
tunnel = _active_tunnel
diff --git a/studio/backend/tests/test_cloudflare_tunnel.py b/studio/backend/tests/test_cloudflare_tunnel.py
index 48ac13fd266..45df3fbb651 100644
--- a/studio/backend/tests/test_cloudflare_tunnel.py
+++ b/studio/backend/tests/test_cloudflare_tunnel.py
@@ -18,6 +18,7 @@ import sys
import tarfile
import tempfile
import threading as _real_threading
+import time as _real_time
import types
from pathlib import Path
from typing import Optional
@@ -37,6 +38,7 @@ def _load_ct():
ct = _load_ct()
+_real_wait_before_retry = ct._wait_before_retry
# ── URL parsing ──────────────────────────────────────────────────────
@@ -458,6 +460,13 @@ def test_reader_captures_url_and_registration():
assert exited == [t]
+def test_reader_keeps_the_output_tail():
+ t = ct.CloudflareTunnel(8080, "/bin/cloudflared")
+ lines = [f"ERR line {i}" for i in range(ct._OUTPUT_TAIL_LINES + 3)]
+ t._reader(_fake_proc("".join(f"{line}\n" for line in lines)))
+ assert t.output_tail() == "\n".join(lines[-ct._OUTPUT_TAIL_LINES :])
+
+
def test_reader_url_without_registration_is_not_ready():
# A URL but no "Registered tunnel connection" (e.g. quic control stream
# fails) must not be advertised -- it returns Cloudflare error 1033.
@@ -875,6 +884,7 @@ def _stub_public_probe(monkeypatch, request):
if not request.node.name.startswith("test_start_studio_tunnel"):
return
monkeypatch.setattr(ct, "verify_public_url", lambda url, **kw: True)
+ monkeypatch.setattr(ct, "_wait_before_retry", lambda _d: False)
def test_start_studio_tunnel_no_binary(monkeypatch):
@@ -1166,8 +1176,8 @@ def test_start_studio_tunnel_no_retry_when_shutdown_between_attempts(monkeypatch
def test_start_studio_tunnel_no_http2_retry_when_no_url(monkeypatch):
- # No URL at all is an API/network failure; the http2 fallback would not help,
- # so it must be skipped (don't burn a second timeout window).
+ # No URL at all is an API/network failure, and http2 would not fix it: the retries stay on the
+ # same protocol and http2 is never reached.
attempts = []
class _Stub:
@@ -1193,7 +1203,101 @@ def test_start_studio_tunnel_no_http2_retry_when_no_url(monkeypatch):
monkeypatch.setattr(ct, "ensure_cloudflared", lambda: "/bin/cloudflared")
monkeypatch.setattr(ct, "CloudflareTunnel", _Stub)
assert ct.start_studio_tunnel(8080) is None
+ assert attempts == [None] * (1 + len(ct._NO_URL_RETRY_DELAYS))
+
+
+def _no_url_stub(
+ attempts,
+ succeed_on = None,
+ fail_after = 0.0,
+ clock = None,
+):
+ class _Stub:
+ def __init__(
+ self,
+ port,
+ binary,
+ protocol = None,
+ origin_host = "localhost",
+ ):
+ self.url = None
+ attempts.append(protocol)
+
+ def start(self):
+ if succeed_on is not None and len(attempts) >= succeed_on:
+ self.url = "https://words.trycloudflare.com"
+
+ def wait_for_ready(self, timeout):
+ if clock is not None:
+ clock[0] += min(fail_after, timeout)
+ return self.url
+
+ def stop(self):
+ pass
+
+ return _Stub
+
+
+def test_start_studio_tunnel_retries_when_no_url(monkeypatch):
+ attempts, slept = [], []
+ monkeypatch.setattr(ct, "ensure_cloudflared", lambda: "/bin/cloudflared")
+ monkeypatch.setattr(ct, "CloudflareTunnel", _no_url_stub(attempts, succeed_on = 2))
+ monkeypatch.setattr(ct, "_wait_before_retry", lambda d: slept.append(d) or False)
+ try:
+ assert ct.start_studio_tunnel(8080) == "https://words.trycloudflare.com"
+ assert attempts == [None, None]
+ assert slept == [2.0]
+ assert ct.get_studio_tunnel_status()["state"] == "online"
+ finally:
+ ct.stop_studio_tunnel()
+
+
+ "fail_after, timeout, expected_attempts, expected_clock",
+ [
+ (0.0, 15.0, 3, 7.0), # refused at once: both delays are waited out
+ (5.0, 15.0, 2, 12.0), # 5 + 2 + 5 spent, so 12 + 5 + 15 overruns
+ (15.0, 15.0, 1, 15.0), # swallowed request: a retry would double the startup stall
+ (0.0, 60.0, 1, 0.0), # a caller's longer timeout is what the next attempt may cost
+ ],
+)
+def test_start_studio_tunnel_no_url_retries_stay_inside_the_budget(
+ monkeypatch, fail_after, timeout, expected_attempts, expected_clock
+):
+ attempts, clock = [], [0.0]
+ monkeypatch.setattr(ct, "ensure_cloudflared", lambda: "/bin/cloudflared")
+ monkeypatch.setattr(
+ ct, "CloudflareTunnel", _no_url_stub(attempts, fail_after = fail_after, clock = clock)
+ )
+ monkeypatch.setattr(ct.time, "monotonic", lambda: clock[0])
+ monkeypatch.setattr(
+ ct, "_wait_before_retry", lambda d: clock.__setitem__(0, clock[0] + d) or False
+ )
+ assert ct.start_studio_tunnel(8080, timeout) is None
+ assert attempts == [None] * expected_attempts
+ assert clock[0] == expected_clock
+ status = ct.get_studio_tunnel_status()
+ assert status["state"] == "error"
+ assert status["error"] == "cloudflared did not produce a URL"
+
+
+def test_start_studio_tunnel_no_url_retry_delay_ends_on_stop(monkeypatch):
+ # The delay holds _start_lock, so Stop must end it early.
+ attempts = []
+
+ def wait(delay):
+ _real_threading.Timer(0.05, ct.stop_studio_tunnel).start()
+ return _real_wait_before_retry(delay)
+
+ monkeypatch.setattr(ct, "ensure_cloudflared", lambda: "/bin/cloudflared")
+ monkeypatch.setattr(ct, "CloudflareTunnel", _no_url_stub(attempts))
+ monkeypatch.setattr(ct, "_NO_URL_RETRY_DELAYS", (5.0, 5.0))
+ monkeypatch.setattr(ct, "_wait_before_retry", wait)
+ t0 = _real_time.monotonic()
+ assert ct.start_studio_tunnel(8080) is None
+ assert _real_time.monotonic() - t0 < 2.0
assert attempts == [None]
+ assert ct.get_studio_tunnel_status()["state"] == "off"
def test_start_studio_tunnel_both_protocols_fail_registration(monkeypatch):