Repository navigation
Studio: auto Cloudflare tunnel for 0.0.0.0 launches - #6204
Conversation
Binding Studio to 0.0.0.0 for remote access often leaves the raw http://<ip>:<port> URL unreachable (https-vs-http, blocked high ports, closed cloud security groups). On a wildcard bind, auto-start a free cloudflared quick tunnel and show its https://*.trycloudflare.com URL in the startup banner: Secure link access via Cloudflare: https://<random>.trycloudflare.com - new studio/backend/cloudflare_tunnel.py: find or download+cache the cloudflared binary (per-OS/arch GitHub release, safe .tgz extract), start the tunnel, parse the URL, tear it down. Stdlib only; best-effort and non-fatal throughout (a missing binary or offline box never blocks or slows startup). - run_server starts the tunnel for 0.0.0.0 only (skips loopback, api-only and Colab), prints the line in the banner, and _graceful_shutdown stops the child so it never orphans. - --cloudflare/--no-cloudflare flag (default on) on `unsloth studio` and `unsloth studio run`, forwarded through the re-exec into run_server. - tests for the helper, the CLI flag forwarding, and the run.py defaults.
There was a problem hiding this comment.
Code Review
This pull request introduces a free Cloudflare quick tunnel integration for Unsloth Studio's 0.0.0.0 launches, allowing secure external access via a trycloudflare.com URL. It adds a new cloudflare_tunnel.py module to handle downloading, caching, and running the cloudflared binary, integrates it into the server startup and shutdown lifecycle, and exposes a --cloudflare/--no-cloudflare CLI flag. Comprehensive tests are also added. The review feedback suggests specifying a custom User-Agent header when downloading the binary from GitHub to prevent potential 403 Forbidden errors from their CDN.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| with urllib.request.urlopen(url, timeout = _DOWNLOAD_TIMEOUT) as response: | ||
| shutil.copyfileobj(response, handle) |
There was a problem hiding this comment.
GitHub's servers and CDN standardly require a valid User-Agent header for all requests, including release asset downloads. Requests made with Python's default urllib User-Agent can be rejected with a 403 Forbidden error. Specifying a custom User-Agent header ensures reliable downloads.
| with urllib.request.urlopen(url, timeout = _DOWNLOAD_TIMEOUT) as response: | |
| shutil.copyfileobj(response, handle) | |
| req = urllib.request.Request(url, headers = {"User-Agent": "unsloth-studio-cloudflare"}) | |
| with urllib.request.urlopen(req, timeout = _DOWNLOAD_TIMEOUT) as response: | |
| shutil.copyfileobj(response, handle) |
There was a problem hiding this comment.
Good catch, applied. Set an explicit User-Agent on the cloudflared download and pinned it with a test.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1848529460
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| cloudflare: bool = typer.Option( | ||
| True, | ||
| "--cloudflare/--no-cloudflare", | ||
| help = "Auto-create a free Cloudflare HTTPS tunnel when bound to 0.0.0.0 (default on).", |
There was a problem hiding this comment.
Reject parent-level Cloudflare opt-out for subcommands
When the opt-out is placed before the subcommand, e.g. unsloth studio --no-cloudflare run -H 0.0.0.0, Typer parses this parent callback option but the callback immediately returns for subcommands, so the run command receives its own default cloudflare=True and still starts the tunnel. This silently defeats the advertised opt-out in a common invocation style; handle cloudflare is False in the ctx.invoked_subcommand branch (as is already done for --parallel) or avoid accepting it at the parent level for subcommands.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. --no-cloudflare placed before a subcommand now errors with a hint to put it after the subcommand, mirroring the --parallel guard.
| with _active_lock: | ||
| prior, _active_tunnel = _active_tunnel, tunnel |
There was a problem hiding this comment.
Register the tunnel before waiting for its URL
If Studio is shut down during the startup window after tunnel.start() but before the quick-tunnel URL is emitted, _graceful_shutdown() cannot stop this child because stop_studio_tunnel() only sees _active_tunnel, and _active_tunnel is assigned only after wait_for_url() succeeds. Since the server is already accepting requests while this wait runs, an /api/shutdown or other in-process shutdown in that window can leave cloudflared running after Studio exits; make the new tunnel visible to shutdown before waiting, or guard the wait with cleanup that also handles concurrent shutdown.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The tunnel is registered in _active_tunnel before wait_for_url, so a shutdown during the URL wait stops cloudflared; on no-url it clears the slot and stops the child.
| run_kwargs = dict( | ||
| host = host, port = port, silent = True, llama_parallel_slots = parallel, | ||
| cloudflare = cloudflare, | ||
| ) |
There was a problem hiding this comment.
Stop the tunnel when model startup aborts
In the in-venv unsloth studio run -H 0.0.0.0 path, passing cloudflare into run_server() starts a cloudflared child before the later health check and model-load steps. If _wait_for_server() times out, API-key creation fails, model loading raises, or the user interrupts before the final wait loop, this command exits via typer.Exit/exception without calling _graceful_shutdown(), so the new tunnel child can be left behind; wrap the post-run_server() startup sequence in cleanup that stops the server/tunnel on abort.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The post-run_server startup (health check, API key, model load) is wrapped so any abort before the wait loop calls _graceful_shutdown, tearing down the server and its children incl the tunnel.
GitHub's CDN can 403 the default Python-urllib User-Agent on release asset downloads. Set an explicit UA and pin it with a test.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 11e6356e09
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| global _cloudflare_url | ||
| _cloudflare_url = None | ||
| app.state.cloudflare_url = None | ||
| _cloudflare_enabled = cloudflare and host == "0.0.0.0" and not api_only and not _IS_COLAB |
There was a problem hiding this comment.
Trust tunnel proxy headers before serving the UI
When this enables the Cloudflare tunnel for -H 0.0.0.0, uvicorn is still configured to trust forwarded scheme headers only in the Colab branch (config_kwargs["proxy_headers"] is set only for _IS_COLAB). Requests for https://*.trycloudflare.com/ therefore reach FastAPI as plain http, so setup_frontend() treats the browser Origin: https://...trycloudflare.com as cross-origin and skips _inject_bootstrap(). On a fresh Studio install opened through the advertised tunnel URL, the setup page no longer receives window.__UNSLOTH_BOOTSTRAP__, making first-login onboarding fail unless the user manually finds and enters the saved bootstrap password; enable proxy header handling for the trusted cloudflared origin or otherwise account for the forwarded scheme when the tunnel is active.
Useful? React with 👍 / 👎.
| silent = silent, | ||
| api_only = api_only, | ||
| llama_parallel_slots = parallel, | ||
| cloudflare = cloudflare, | ||
| ) |
There was a problem hiding this comment.
Install SIGTERM cleanup before starting the tunnel
In the in-venv plain unsloth studio -H 0.0.0.0 path, passing cloudflare here can start a cloudflared child, but this Typer wrapper only calls _graceful_shutdown() for KeyboardInterrupt in the later wait loop and never registers the SIGTERM handler that run.py installs. Since unsloth studio stop sends SIGTERM to the PID file owner, that common shutdown path terminates the Python process without running stop_studio_tunnel(), leaving the new tunnel process behind; register the same signal cleanup before run_server() or make stop trigger app.state.trigger_shutdown.
Useful? React with 👍 / 👎.
| fake_backend_run = sys.modules.setdefault( | ||
| "studio.backend.run", types.ModuleType("studio.backend.run") | ||
| ) | ||
| fake_backend_run.run_server = fake_run_server | ||
| fake_backend_run._resolve_external_ip = lambda: "127.0.0.1" |
There was a problem hiding this comment.
Restore the fake run module after this test
This test writes a fake studio.backend.run module (or mutates the real one) directly in sys.modules and assigns stub functions without using monkeypatch, so the stub remains after the test finishes. If this file runs before any later tests that import studio.backend.run, they receive a partial module or a run_server that raises _RunServerCaptured, creating order-dependent suite failures; use monkeypatch.setitem(sys.modules, ...) and monkeypatch.setattr(...) so pytest restores the module state.
Useful? React with 👍 / 👎.
| if _cf_url: | ||
| typer.echo(f" Secure link access via Cloudflare: {_cf_url}") |
There was a problem hiding this comment.
Show the tunnel URL in SDK examples
When _cf_url is present, this line advertises the Cloudflare URL but the SDK base URL and all curl examples printed just below still use sdk_base_url, which is built from the raw http://<external-ip>:<port>. In exactly the cloud/security-group scenarios this feature is meant to solve, copying the displayed OpenAI/Anthropic examples will still fail even though the tunnel is working; include the tunneled /v1 base URL or switch the examples to it when the tunnel is active.
Useful? React with 👍 / 👎.
…ardown) - reject --no-cloudflare placed before a subcommand (it would not reach the subcommand), mirroring the --parallel guard - register the tunnel before waiting for its URL so a shutdown during the wait stops cloudflared instead of orphaning it - tear the server + children down if `unsloth studio run` startup aborts (health timeout, model-load error, Ctrl+C) before the wait loop
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b82f33bbe9
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if api_only: | ||
| args.append("--api-only") | ||
| # Forward the explicit polarity (matches run.py's BooleanOptionalAction). | ||
| args.append("--cloudflare" if cloudflare else "--no-cloudflare") |
There was a problem hiding this comment.
Avoid forcing new flags into older Studio venvs
When a user has an existing Studio venv from the previous release, _find_run_py() still points at that venv's run.py, whose argparse parser has no --cloudflare option. Because this appends --cloudflare even for the default value and even for loopback launches, unsloth studio exits with “unrecognized arguments: --cloudflare” instead of starting until the venv is manually refreshed; only pass the new flag when it is needed, or detect that the child supports it.
Useful? React with 👍 / 👎.
| # child reverts to its default and silently drops the value. | ||
| args.extend(["--parallel", str(parallel)]) | ||
| # Forward the explicit polarity (same rationale as --load-in-4bit above). | ||
| args.append("--cloudflare" if cloudflare else "--no-cloudflare") |
There was a problem hiding this comment.
Preserve
studio run with older venv CLIs
In the re-exec path, this invokes the existing venv's unsloth studio run command, but older installed venvs do not define --cloudflare/--no-cloudflare. Since the default --cloudflare is always appended, users who update the outer CLI but still have the prior Studio venv can no longer run any model (No such option: --cloudflare); avoid forwarding the default to older children or gate it on child support.
Useful? React with 👍 / 👎.
What
When Studio is launched on
0.0.0.0for remote/cloud access, auto-start a free Cloudflare quick tunnel and show itshttps://*.trycloudflare.comURL in the startup banner:Binding
0.0.0.0exposes the API on a high port, but the rawhttp://<ip>:<port>is frequently unreachable for the user:https://typed against a plain-HTTP port, blocked high ports, or closed cloud security groups. The quick tunnel serves HTTPS through Cloudflare's edge and works from any network, with no account or domain.Behavior
0.0.0.0binds only. Loopback,--api-onlyand Colab (its own proxy) are skipped. Opt out with--no-cloudflareon bothunsloth studioandunsloth studio run.cloudflaredis not on PATH, it is downloaded once and cached under the Studio home (studio_root()/bin), per OS/arch (Linux, macOS, Windows), then reused on later launches._graceful_shutdownalongside the other Studio subprocesses, so it never orphans.How it fits
studio/backend/cloudflare_tunnel.py(stdlib only, lazy backend imports): find or download+cache the binary (safe single-member.tgzextract on macOS), start the tunnel, parse the URL with a bounded wait, stop it.run_serverstarts the tunnel after the port binds and before the banner, and exposes the URL onapp.state.cloudflare_urlso both the plain banner and theunsloth studio runbanner can show it.--cloudflare/--no-cloudflare(default on) is plumbed through the CLI re-exec intorun_server.Tests
studio/backend/tests/test_cloudflare_tunnel.py: URL parsing, OS/arch asset mapping, binary discovery, download+cache (incl. Windows.exeand macOS.tgz),.tgzpath-traversal guard, tunnel start/stop, and run.py AST defaults.unsloth_cli/tests/test_studio_cloudflare_flag.py: the flag is registered (default on) on both commands and the chosen polarity reaches the re-exec'd child andrun_server.38 new tests pass; existing host-default and parallel-flag tests are unaffected.