Skip to content

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

Merged
danielhanchen merged 26 commits into
unslothai:mainfrom
Lyxot:feat/studio-public-access
Aug 6, 2026
Merged

danielhanchen merged 26 commits into
unslothai:mainfrom
Lyxot:feat/studio-public-access

Conversation

@Lyxot

@Lyxot Lyxot commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • reuse the existing Cloudflare Quick Tunnel implementation through one runtime-managed controller for launch, settings, and Colab ownership
  • add UI-session-only remote-access controls and a persisted, default-off auto-start preference
  • add a Remote access section to API Settings in desktop and web Unsloth, including lifecycle status, URL copy, Start/Stop, and launch-policy guidance
  • preserve Stop responses sent through the tunnel and log the ready URL for both manual and automatic settings-managed starts
  • serve the packaged WebUI through a live desktop Remote access URL while keeping direct desktop backend requests API-only
  • add a desktop-only Remote password row to that section: it sets the browser/remote login password while the seeded administrator password is still pending, and changes it afterwards
  • keep the local desktop credential valid when the desktop app itself sets or changes that password, so desktop auto-auth stays passwordless

Why

The CLI can launch Unsloth with --secure, but the desktop app cannot supply that flag after launch. The existing Quick Tunnel foundation was tied to startup ownership, so users could not safely start or stop remote access from the running desktop or web UI. This change makes that existing capability runtime-manageable without introducing a second tunnel implementation or persisting ephemeral URLs.

In web Unsloth, a settings-managed Quick Tunnel exposes the full Unsloth origin. Desktop Unsloth launches the backend with --api-only; direct local backend requests stay API-only, while a live Remote access Quick Tunnel also serves the packaged WebUI. In both modes, routes remain subject to their existing authentication and authorization. Generated Quick Tunnel URLs and runtime state remain ephemeral; only the explicit auto-start preference is persisted.

Desktop Unsloth signs in with a generated local secret and never sees the seeded administrator password, which is only printed to a terminal. Remote access refuses to open a tunnel while that seeded password is still in place, so a desktop user had no way forward: the ordinary change-password flow needs a current password they do not have, and the General settings tab hides its password row on desktop for the same reason. POST /api/auth/desktop-initial-password closes that gap. It accepts only a desktop-issued JWT and refuses web UI sessions and sk-unsloth-... API keys, applies only while the seeded credential is unchanged, and binds its write to the credential version it read so a concurrent web password change or unsloth studio reset-password is never overwritten. Remote browser users then sign in as unsloth with the password that was set.

Both password routes now keep the local desktop credential valid and mint desktop-issued tokens when the caller is the desktop app, so the desktop session survives the credential rotation it triggered and auto-auth stays passwordless. Browser callers keep the previous behavior: the local desktop credential is revoked and ordinary tokens are issued. Remote access status reports a pending seeded password on its own, independently of block precedence, so the desktop row stays correct even when another block hides the reason. The row reuses the existing account password dialog in an initial-password mode rather than adding a second dialog.

What changed

Tunnel ownership. cloudflare_tunnel.py becomes one thread-safe controller with a serialized off/starting/online/stopping/error lifecycle, a single URL publication path, and explicit launch, settings, and colab ownership. The existing --secure/--cloudflare startup path and the Colab helper both run through it, so their banners, failure handling, and cleanup are unchanged. A connector that exits after readiness now clears the URL and reports error instead of leaving a stale online state.

Settings API. /api/settings/remote-access reports status and schedules idempotent start, stop, and auto-start changes. It requires a UI session JWT and refuses sk-unsloth-... API keys, because this is process control rather than ordinary API surface. Auto-start is one server-wide boolean in app_settings, default off, failing closed on unreadable or non-boolean values; generated URLs, lifecycle, and errors are never persisted. It runs in the background after the final port is bound, so TAURI_PORT and the login page are not delayed.

Launch policy. The launch gate's decision is computed once and reused for password gating, published Settings policy, and launch startup, so a launch that intentionally starts no tunnel (non-secure loopback, API-only) stays controllable from Settings while --secure and wildcard binds keep precedence. The outer CLI now carries the user's original unset/enabled/disabled Cloudflare intent across re-exec, so an omitted choice is no longer indistinguishable from an explicit --no-cloudflare.

Stop through the tunnel. A Stop request that arrives over the connector it is tearing down completes first: an ASGI-level lease holds teardown from admission through the final response body, admission closes atomically before teardown, and it reopens after an aborted or failed stop so a retry is still admitted.

Public runtime trust. While a settings-managed URL is live, remote browser origins are accepted, including in API-only desktop mode, and the automatically enabled loopback/desktop stdio MCP default is suspended for the whole physical connector lifetime -- from before cloudflared spawns until every connector process is confirmed gone. Explicit stdio MCP environment policy remains authoritative.

Desktop WebUI. A Tauri-owned API-only backend mounts the packaged SPA behind a Cloudflare-provenance gate, so a Remote access URL serves the WebUI while direct local requests and headless --api-only launches stay frontend-free.

Desktop password. A desktop-only Remote password row sets the browser/remote login password while the seeded administrator password is still pending, and changes it afterwards, through POST /api/auth/desktop-initial-password and the existing change-password route. It reuses the account password dialog in an initial-password mode rather than adding a second dialog.

UI. The API Settings tab gains the Remote access section: status with a lifecycle indicator, one lifecycle-aware Start/Stop action, persisted auto-start, the full URL with copy, ownership and eligibility guidance, and the password row above. Polling is scoped to the mounted section and is mutation-safe across tabs, so a change made in one authenticated session is observed in another. Usage examples and coding-agent commands target the live public URL through the existing endpoint control, while request bodies, streaming flags, response handling, and signed preview links are unchanged.

Desktop

off(need a password):
2ceb82956a9cf3a3792d3bf16104b990

off:
图片

on:
698a066c01588cdc91dade3b3e6c4da6

access from the url:
2aac7e30292c015f4b69e2bb018a1501

Web

off:
图片

on:
图片

override by launch flag:
图片

Validation

  • 396 focused backend tests across the Cloudflare, remote-access, desktop-auth, credential-rotation, middleware, and preview suites
  • focused remote-access settings coverage, including manual and auto-start URL logging mutation coverage, and pending-password reporting under a higher-precedence block
  • focused desktop remote-password coverage: desktop-only authorization with web sessions and API keys refused, refusal once a password exists, and desktop-versus-browser handling of the local desktop credential and token flag on the existing change-password route
  • focused desktop frontend admission coverage for root, assets, SPA fallback, direct local requests, and headless API-only serving policy
  • 334 frontend tests
  • frontend typecheck, locale parity check, Biome checks, and production build
  • Ruff, repository formatting hooks, and git diff --check
  • real Quick Tunnel validation for manual start, persisted auto-start across restart, /api and /v1 reachability, UI-session-only management authorization, public-origin Stop completion, explicit --no-cloudflare suppression, launch-managed --secure ownership, and URL clearing after cloudflared exits

@Lyxot
Lyxot marked this pull request as ready for review August 4, 2026 19:22
@Lyxot
Lyxot requested a review from danielhanchen as a code owner August 4, 2026 19:22

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 08822ec31b

ℹ️ 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".

Lyxot commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 94d408f864

ℹ️ 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".

@Lyxot
Lyxot force-pushed the feat/studio-public-access branch from 94d408f to 680691e Compare August 5, 2026 07:50

Lyxot commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 680691ee7b

ℹ️ 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".

@Lyxot Lyxot changed the title feat(studio): add settings-managed public access feat(studio): add settings-managed remote access Aug 5, 2026

Lyxot commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@Lyxot
Lyxot force-pushed the feat/studio-public-access branch from 2f11cc3 to 5120526 Compare August 5, 2026 08:39

Lyxot commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 5120526e96

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

Lyxot commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: bbc8fe2d39

ℹ️ 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".

The desktop app signs in with a local secret and never sees the seeded administrator password, which is only printed to a terminal. Remote access refuses to open a tunnel while that seeded password is still in place, so a desktop user had no way forward: the change-password flow needs a current password they do not have, and the General tab hides its password row on desktop.

Add a Remote password row to the Remote access section, desktop only. While the seeded password is pending it sets the first password through a new POST /api/auth/desktop-initial-password; once a password exists the same row changes it through the existing endpoint. The new route accepts only a desktop-issued JWT (web sessions and API keys are refused), applies only while the seeded credential is unchanged, and binds its write to the credential version it read so a concurrent web change or CLI reset is not overwritten.

Both password routes now keep the local desktop credential valid and mint desktop-flagged tokens when the caller is the desktop app, so auto-auth stays passwordless and the session survives the change it made. Browser callers keep their existing behavior: the credential is revoked and ordinary tokens are issued.

Remote access status reports password_pending on its own, independent of block precedence, so the row is correct even when another block hides the reason. Re-reading status after either operation clears the pending-password block and lets the tunnel start; remote browsers then sign in as unsloth with the new password.

The action reuses the account password dialog in an initial-password mode rather than adding a component, and adds no file.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@Lyxot

Lyxot commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fcb15df5c6

ℹ️ 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".

Comment thread studio/backend/run.py Resolved
The remote access controls rendered as flat settings rows, so the
feature read as hidden and the tunnel URL was squeezed into a
description cell. Rebuild remote-access-section.tsx as a bordered card:

- header with globe icon, title, live status dot plus state text and
  the start/stop action together
- online state gets a dedicated URL panel with a copy button, a QR
  button that opens a scannable code for phones (react-qr-code, svg,
  zero deps), and a note that the URL plus remote password grants
  sign in
- block reasons and tunnel errors render as their own strip,
  destructive styling on error
- shine sweep on the status text while starting or stopping
- password and auto start rows move below a divider inside the card

Polling and start/stop/auto-start logic are unchanged.
Lyxot added 2 commits August 6, 2026 15:51
Cloudflare routes quick tunnels by TLS SNI, so the edge serves a tunnel as soon as its connection registers, before the hostname resolves anywhere. Probing an edge address with the tunnel's name in SNI and Host takes that hostname's DNS off the startup path, along with the wait that existed only to keep an early lookup from caching the miss.

Measured over four fresh tunnels each: verification after registration falls from 10.97s to 6.61s on average, and a whole start from 22.9s to 16.8s. It also removes the case behind the slowest starts, where one DoH query sent before the record propagates is negative-cached, blinding the poll until its own cap expires and pushing a start past 30s.

The hostname path stays as the fallback for networks that block direct addresses or intercept TLS. It is entered as soon as the edge looks unreachable rather than merely unready: an error 1033 page is an answer, a failed connection is not.
feat(studio): polish remote access ui and fix slow tunnel start
@Lyxot

Lyxot commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Instructions

  1. Set a remote password in Settings -> API -> Remote access -> Remote password
图片
  1. Click the Start button
图片
  1. Wait for starting
图片
  1. Access via Remote URL or scan the QR code
图片

@shimmyshimmer

Copy link
Copy Markdown
Member

@codex review

Verifying a quick tunnel at Cloudflare's edge shipped with two defects. The wait checked the clock only after trying every address, so a full pass always ran: verify_public_url with a 0.05s timeout still took 12s, against 1.65s before the edge probe existed, and a pass of two real TLS handshakes overshot the 15s cap to about 19s, taken out of the hostname fallback's share of the same deadline. The clock is now read before every attempt, and no attempt is given more time than the deadline leaves.

The addresses were also not distinct. macOS reports the A records again as IPv4-mapped under AF_INET6, so taking one per family dialled a single frontend twice, as 104.16.230.132 and ::ffff:104.16.230.132. That doubled the cost of a pass, halved the poll rate, and let two dependent samples of one address exhaust the unreachable counter. Deduplicating by frontend yields 104.16.230.132 and 104.16.231.132 here.

An intercepting proxy answering with its own page is an answer rather than an unreachable edge, so it resets that counter exactly as error 1033 does and the wait ends at the cap instead. The comments claimed interception left through the early exit; they now describe what it does.
@shimmyshimmer

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9e3cc9c6fa

ℹ️ 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".

@Lyxot

Lyxot commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@Lyxot

Lyxot commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

1 similar comment
@shimmyshimmer

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 9e3cc9c6fa

ℹ️ 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".

…gates

The tunnel test annotated a helper with `str | None`, which evaluates on the 3.9 floor that pyproject declares and pushed the studio union ratchet from 35 files to 36. Six new test reads took the platform default encoding, so they break on Windows the moment those files gain a non-ASCII byte. The remote password dialog's six new strings existed only in en, which strict locale parity rejects; they are now translated into every overlay.
…phans for PR unslothai#7875

PR_SET_PDEATHSIG is a parent-THREAD death signal, not parent-process: the kernel
fires it when the thread that forked the child exits. start_remote_access forks
cloudflared from a short-lived worker thread, so the connector was SIGTERMed
about a second after it came online, every time. Reproduced 3/3 on a real
install: the URL is logged, then state goes to error with "cloudflared exited".
Auto-start shares the same worker, so it was affected too.

Only Linux and WSL are hit. macOS arms no per-thread signal and Windows uses a
process-wide Job Object, so both were fine, as was the launch path, which forks
from the main thread.

Changes:

- process_lifetime: spawn_on_lifetime_thread() performs the fork on one
  process-lifetime daemon thread, so PDEATHSIG means "die with the parent
  process" again. Non-Linux spawns directly. Falls back to an inline spawn when
  no helper thread can be obtained, so it can never block.
- cloudflare_tunnel: spawn through that helper. The abort branch now tears the
  connector down instead of returning the URL of a process it just detached,
  which could leave a live public tunnel no later stop_studio_tunnel() could
  reach. Restore _tunnel_state to "starting" after attempt 1's teardown so the
  http2 retry no longer advertises "stopping", which made stop_studio_tunnel()
  early-return and stop nothing, and made the Settings Stop route a no-op.
- run.py: an explicit --cloudflare/--no-cloudflare/--secure on this invocation
  now beats an inherited _UNSLOTH_CLOUDFLARE_INTENT, so a stale export, Docker
  ENV or systemd Environment= cannot re-enable a tunnel the user opted out of.
  The marker still softens the compatibility --no-cloudflare into "unset".
- Add tests for remote-access-state.ts, which had no coverage. No bugs found
  there; the logic is correct, it simply was not exercised.

Verified: 701 passed in the focused backend slice (the one failure is a
pre-existing missing optional dep, and fails on main too), 347 frontend tests,
typecheck, biome and 80 simulation tests including a real-child-process tunnel
lifecycle and Chromium/Firefox/WebKit CORS runs.
@danielhanchen

Copy link
Copy Markdown
Member

Thanks for this, the ownership model and the fail-closed stop_pending design are nice work, and the Cloudflare edge-probe tests are the strongest part of the diff.

I could not push to the branch directly because "Allow edits by maintainers" is off on this PR, so the fixes are in Lyxot#4 against feat/studio-public-access. Merging that brings them in here.

The main one: settings-managed tunnels do not survive on Linux

PR_SET_PDEATHSIG is a parent-thread death signal, not parent-process. It fires when the thread that forked the child exits. start_remote_access forks cloudflared from a short-lived worker thread whose last action is logging the URL, so the connector is SIGTERMed about a second after it comes online. Reproduced 3/3 on a real install of this branch:

09:36:32 INFO Secure link access via Cloudflare: https://valentine-consist-rational-plasma.trycloudflare.com
09:36:33 state=error  url=None  error="cloudflared exited"

maybe_auto_start_remote_access uses the same worker, so auto-start is affected too.

Not environmental: standalone cloudflared stays up on the same host, and --secure launch-managed works end to end from this build because it forks from the main thread. Only Linux and WSL are hit. macOS arms no per-thread signal and Windows uses a process-wide Job Object, so both are fine.

No existing test can catch it, since every tunnel test substitutes a stub and never spawns a real child from a worker thread.

Second: stop during the http2 retry

_tunnel_state is set to "stopping" for attempt 1's teardown and never restored, so the whole retry advertises "stopping". stop_studio_tunnel early-returns in that state and stops nothing, the Stop route still reports off, and the abort branch returns the URL of a connector it just detached. That leaves a live public tunnel no later stop can reach, with the controller wedged at can_start and can_stop both false. On Linux it is currently masked by the first bug, so the two need fixing together.

Other findings, not in that PR

  • /api/auth/desktop-login is unauthenticated, unthrottled and async def, and runs a 100k-round PBKDF2 on the event loop before touching the DB. Once the API is published, one client with 8 connections took /api/health p50 from 1.2 ms to 200 ms, with zero 429s. main.py's _is_local_bootstrap_request is the interlock that fits here.
  • routes/auth.py:_client_ip never reads CF-Connecting-IP, so every tunneled visitor shares the loopback bucket with the local user. Five failed remote logins return 429 to the owner, and _clear_login_bucket only runs on a successful login, which they can no longer perform. utils/client_ip.py already solves this and its docstring describes this exact case; routes/preview.py and hub/routes/token.py use it.
  • A persisted auto-start opens a tunnel on plain loopback unsloth studio with no flags and no banner line, since the gate only blocks on intent == "disabled". Worth confirming that is intended.
  • Changing the password from the desktop app no longer revokes .desktop_secret. Browser callers still do, correctly, but that was the documented way to revoke a leaked desktop credential and the general-tab.tsx comment that said so was rewritten. Only unsloth studio reset-password rotates it now, and nothing tells the user that.
  • Desktop --api-only now 405s unmatched non-GET paths that used to 404, including under /v1, and its 404s lost their JSON body.
  • test_remote_access_settings.py never makes an HTTP request. The API-key refusal, which is the headline authorization claim, is asserted with source.count("_ui_session: None = Depends(_require_ui_session)") == 4. I wrote the real version with a live sk-unsloth- key and a UI JWT: the enforcement is correct, 401/403/200 across all four routes, so this is only test robustness. test_secure_tunnel_gate.py also pins exact source indentation.
  • server_starting, colab_managed, colab and explicitly_disabled have no coverage, and neither does the error-normalization allowlist that keeps raw cloudflared stderr away from remote browsers.

Verified as correct

Cached stdio MCP sessions are not a bypass: tools.py re-checks stdio_mcp_enabled() on every tool call, before session lookup. The desktop initial-password compare-and-swap is sound, since all three writers of must_change_password = 0 also rewrite password_hash. No token survives a rotation. There is no lock-order cycle, online is never published for a dead process, and the launch-gate single-evaluation fix resolves the earlier P2 properly.

Lyxot and others added 2 commits August 6, 2026 19:29
Fix settings-managed tunnels dying on Linux, and stop-during-retry orphans
… polling for PR unslothai#7875

Follow-ups from reviewing the remote access flow on Linux. The tunnel lifetime
fix landed already; these are the smaller things around it.

- remote_access_status collapsed "cloudflared could not be stopped" into the
  generic "Cloudflare tunnel failed". That is the one error the user can act on:
  the connector's exit was never confirmed, so it still holds the runtime slot
  and Start stays disabled. Pass it through like the other known messages.

- The Stop worker waited on a live start worker with no deadline, polling at
  100 Hz. A start that never claims settings ownership (foreign owner, or one
  that bailed on admission) deferred the user's Stop for the full probe
  deadline, up to about 170s. Bound it at 5s and poll at 50 Hz.

- setPollEnabled(false) had no path back to true. It fires when you stop a
  tunnel from a browser connected through that tunnel, which is correct, but
  the section then stayed dark until it unmounted. Resume on any later action
  or on a password-change refresh, since both prove the origin is reachable.

- test_change_password_policy called change_password positionally, so the new
  is_desktop parameter defaulted to the Depends object, which is truthy. Harmless
  today because the assertions fire earlier, but it silently exercises the
  preserve-desktop-secret branch. Pass False explicitly.

Verified: 230 passed in the focused backend slice, 347 frontend tests, typecheck,
build, locale parity, and no new biome warnings. Re-checked on a real install:
auto-start brought a tunnel up at boot and it stayed online, and Stop through
that tunnel returned 200 in 0.07s. The one backend failure
(test_health_response_reports_desktop_capability_fields) is a pre-existing
environment gap and fails on main too.
@danielhanchen

Copy link
Copy Markdown
Member

Went through this one carefully, including a real Quick Tunnel on a Linux box. Pushed a small follow-up commit; everything below is either in that commit or a question for you.

Pushed

  • remote_access_status hid the one actionable error. "cloudflared could not be stopped" was collapsing into the generic "Cloudflare tunnel failed". That is exactly the state where the connector's exit was never confirmed, so it still holds the runtime slot and Start stays disabled. The user needs to see it. Added it to the passthrough set.
  • The Stop worker waited on a live start worker with no deadline, at 100 Hz. A start that never claims settings ownership (foreign owner, or one that bailed on admission) deferred the user's Stop for the full probe deadline, roughly 170s worst case. Bounded at 5s, polling at 50 Hz.
  • setPollEnabled(false) had no path back to true. Latching it when you stop a tunnel from a browser connected through that tunnel is right, but the section then stayed dark until it unmounted. It now resumes on any later action or on a password-change refresh, since both prove the origin is reachable.
  • test_change_password_policy called change_password positionally, so the new is_desktop parameter defaulted to the Depends object, which is truthy. Harmless today because the assertions fire before it is read, but it silently exercises the preserve-desktop-secret branch. Passing False explicitly.

Verified: 230 passed in the focused backend slice, 347 frontend tests, typecheck, build, locale parity, no new Biome warnings. On a real install, auto-start brought a tunnel up at boot and it stayed online, and Stop through that tunnel returned 200 in 0.07s. The single backend failure, test_health_response_reports_desktop_capability_fields, is a pre-existing environment gap and fails on main too.

One question, not pushed

RemoteAccessCORSMiddleware.is_allowed_origin accepts every origin while a URL is published, not just the tunnel origin. Since cors_origins_for_mode already returns ["*"] in every mode except api_only and not secure, the only real change is the desktop api-only loopback listener, which drops its Tauri origin lockdown for the tunnel's lifetime.

I could not find a client that needs the wide version. The SPA served through the tunnel is same-origin (apiBase is "" outside Tauri), the Tauri webview uses the statically allowed tauri:// origins, and the other cloudflareUrl consumers are display-only base URLs for copy-paste. If there is no browser client I am missing, scoping this to the published tunnel origin would be strictly tighter. If you do intend third-party browser apps to call the tunnel, that is a fine answer, and it is worth saying so in the docstring, since test_api_only_cors_tracks_published_public_url currently encodes the broad behaviour without explaining why.

Left alone deliberately

  • Nothing in remote-access-section.tsx goes through the translation layer, while the six password-dialog strings this PR adds are translated into all 12 locales. i18n:check cannot catch it because it only diffs overlay key sets against en. There are about 27 strings once remoteAccessBlockMessage is included, so I would rather you write those in your own voice than have me guess at 11 languages. Doing that would also let the section join SETTINGS_SEARCH_INDEX, which is typed to TranslationKey[], so today data-settings-label="Remote access" is dead and the section is unreachable from settings search.
  • POST /remote-access/stop overriding the response to a terminal off while the worker has only been scheduled. For the caller connected through the dying tunnel this is clearly the right call, and a polling UI self-corrects within a second, so I did not touch it. Worth knowing that a one-shot API consumer is told the public URL is gone when it may not be yet, and that it also forces can_stop: false even when the truth is can_stop: true with stop_pending set.

Everything else held up well under adversarial testing. The stop lease genuinely does what it claims, the UI-session-only gate refuses sk-unsloth- keys on all four routes while the same key still works on /v1/models, auto-start defaults off and rejects non-booleans with 422, and the stdio MCP suspension is fail-closed and re-read per call. Nice work.

… the spawner across fork for PR unslothai#7875

Findings from simulating the remote access paths across platforms, browsers and
upgrade scenarios. Three small fixes, each measured rather than reasoned.

- streaming_supported was a hardcoded True. Every tunnel Studio opens is a
  Cloudflare Quick Tunnel, and Cloudflare documents that Quick Tunnels do not
  support Server-Sent Events. Measured against a real tunnel: a local SSE
  endpoint delivers 6 events over a 5.0s spread, and the same endpoint through
  the tunnel answers 200 with text/event-stream and then delivers nothing at all
  before the read times out. Chunked non-SSE streaming was blackholed the same
  way, so no transport change works around it. The field now reports whether a
  tunnel is currently carrying the traffic, so it is true locally and false while
  a tunnel is live. Nothing branches on it yet, which is exactly why it should be
  right before something does.

- The CORS middleware inherited Starlette's 600s Access-Control-Max-Age.
  is_allowed_origin closes the instant the tunnel URL clears, but a preflight the
  browser already cached does not. Measured across four engines: after remote
  access was stopped, WebKit reused its cached preflight and the state-changing
  POST still reached the server, while Chromium, Firefox and Edge re-preflighted
  and were refused. Pinning max_age to 60 keeps preflight caching useful and
  makes revocation nearly as immediate as every other trust signal here.

- spawn_on_lifetime_thread keeps a module-level lock and a helper thread. A fork
  child inherits the lock in whatever state it was in, and a spawner whose thread
  does not exist in the child. Reproduced: forking while the lock is held
  deadlocks the child permanently. Not reachable today, since the backend only
  uses the spawn start method and the one fork start method lives in the training
  worker, which never imports the tunnel. Registering an at-fork reset is three
  lines and closes the class of bug rather than the instance.

Also verified and unchanged: no schema change in any store, so an old studio.db
with no remote_access_auto_start row reads as false and fail-closed on corrupt or
non-boolean values; the argument parser is byte-identical to main, so no launch
flag default moved; the PR touches no hardware, GPU or desktop files, and all
twelve OS x accelerator combinations produce an identical remote-access status.
Host and Origin are forbidden request headers in all four engines, so no page
script can forge the Cloudflare provenance gate.

Verified: 95 simulation cases, 41 adversarial cases, 109 in the directly affected
backend slice, 347 frontend tests, typecheck, build and locale parity. On a real
install: auto-start brought a tunnel up at boot and it stayed online, Stop through
that tunnel returned 200 in 0.09s, and the live status now reports max-age 60 and
streaming_supported false.
@danielhanchen

Copy link
Copy Markdown
Member

Ran a broader simulation pass over this: process lifetime across platforms, an upgrade-in-place audit, the four browser engines, and a real Quick Tunnel. Pushed three small fixes. Everything below was measured, not reasoned.

Pushed

1. streaming_supported was a hardcoded True, and it is not true through a tunnel.

Cloudflare documents that Quick Tunnels do not support Server-Sent Events, and every tunnel Studio opens is a Quick Tunnel. Measured against a real one:

endpoint local through the tunnel
text/event-stream 6 events over a 5.00s spread 200, text/event-stream, then zero events until read timeout

Chunked non-SSE was blackholed the same way, so switching transport does not work around it. The field now reports whether a tunnel is currently carrying the traffic: true locally, false while one is live. Nothing branches on it yet, which is why it is worth correcting before something does.

Worth deciding separately: Studio chat is SSE, so chat opened through a Remote access URL will not stream. That is a platform limitation rather than anything this PR did wrong, but the section copy ("Use Unsloth and its APIs from other devices") currently gives no hint. A short caveat in the UI would save people a confusing first session.

2. CORS inherited Starlette's 600s Access-Control-Max-Age.

is_allowed_origin closes the instant the tunnel URL clears; a preflight the browser already cached does not. Measured across four engines after Stop:

engine JS sees did the request reach the server?
WebKit blocked yes
Chromium blocked no
Firefox blocked no
Edge blocked no

WebKit reuses the cached preflight and still sends the state-changing request; the others re-preflight and are refused. Pinned max_age = 60, which keeps preflight caching useful and makes revocation nearly as immediate as every other trust signal in this PR.

3. spawn_on_lifetime_thread is not fork-safe.

A fork child inherits _spawner_lock in whatever state it was in, plus a _spawner whose thread does not exist there. Reproduced: forking while the lock is held deadlocks the child permanently. Not reachable today, since the backend only uses the spawn start method and the one fork start method lives in the training worker, which never imports the tunnel. The at-fork reset is three lines and closes the class rather than the instance.

Verified unchanged

  • No schema change in any store. An old studio.db with no remote_access_auto_start row reads as False, and corrupt or non-boolean values fail closed. No migration needed.
  • The argument parser is byte-identical to main, so no launch flag default moved.
  • Zero hardware, GPU or src-tauri files touched. All twelve OS x accelerator combinations produce an identical remote-access status, so nothing hardware-specific leaked into this path.
  • Host and Origin are forbidden request headers in all four engines — the server saw the real values when a page tried to forge them. That is what bounds the Cloudflare provenance gate against browser scripts. CF-Connecting-IP is not forbidden and does pass through, so the Host check is the part doing the work.
  • Clipboard behaviour genuinely differs by engine (headless Chromium rejects writeText with NotAllowedError; Firefox, WebKit and Edge allowed it). The existing execCommand fallback in copy-to-clipboard.ts covers this correctly.

One upgrade case worth knowing about

An old outer CLI with a new backend leaves remote access permanently reporting explicitly_disabled, and a saved auto_start never fires. The CLI unconditionally appends --no-cloudflare to the re-exec for version compatibility, and _UNSLOTH_CLOUDFLARE_INTENT is what tells the backend that this was compatibility rather than an opt-out. An old CLI sets no marker, so the backend reads a deliberate opt-out.

I did not change this, because the alternative is to stop honouring an explicit --no-cloudflare when no marker is present, and that would weaken a real opt-out on a direct run.py launch. Nothing that previously worked breaks; the new feature is just inert until the outer CLI updates, which it does in the normal single-distribution layout. Flagging it in case you want a clearer message than "explicitly disabled" for that case.

Test totals

95 simulation cases, 41 adversarial cases, 109 in the directly affected backend slice, 347 frontend tests, typecheck, build and locale parity. On a real install: auto-start brought a tunnel up at boot and it stayed online, Stop through that tunnel returned 200 in 0.09s, and the live status now reports max-age 60 and streaming_supported false.

Resolves two conflicts:
- studio/backend/main.py: comment only, keeps main's wording and the note that
  the desktop stdio MCP loopback default is tracked so a runtime tunnel can
  suspend it.
- studio/frontend/src/features/studio/history-card-grid.tsx: keeps main's
  startBlocked/stopRequested resume gating and the z-10 on the copy button, and
  keeps this branch's on-demand fetchDeviceType refresh plus stopPropagation in
  the copy handler. The bounded mount-time cloudflare poll is dropped because
  the tunnel can now start and stop at any time, so the click-time refresh
  supersedes it.
…op on off for PR unslothai#7875

The desktop spawns "studio --api-only" with no --frontend, and install.sh
--tauri skips the frontend build outright. The new desktop-owned branch made
_serve_frontend true for that launch, so an unresolvable studio/frontend/dist
raised SystemExit before TAURI_PORT was emitted and the app never got a
backend. The SPA only backs the optional remote web UI there, so warn and
carry on API-only; a web UI launch still aborts loudly.

A Stop sent from the tunnel's own origin is answered with a terminal off, then
polling restarts in perform()'s finally and the first poll can still land
inside the ~50ms teardown drain, where the backend reports "stopping". That
overwrote the terminal off, cloudflared then exited, and the card latched on a
permanent "Stopping" for a tunnel that was already down. Teardown frames no
longer overwrite it, while a poll that can still stop the connector proves
teardown was abandoned and takes the card back over.
@danielhanchen
danielhanchen merged commit 4a4509c into unslothai:main Aug 6, 2026
69 of 85 checks passed
@danielhanchen

Copy link
Copy Markdown
Member

Merged main into the branch and resolved the two conflicts, so the branch is mergeable again. Worth a look since one of them was not mechanical:

studio/backend/main.py was comment-only. Kept main's wording and folded in the note that the desktop stdio MCP loopback default is tracked so a runtime tunnel can suspend it.

studio/frontend/src/features/studio/history-card-grid.tsx was substantive. main added startBlocked / stopRequested to the resume button and a z-10 on the copy button; both kept. This branch replaced the bounded 12 x 2.5s mount-time cloudflare poll with an on-demand fetchDeviceType({ force: true }) inside the copy handler, plus e.stopPropagation(). I kept that and dropped the poll: with remote access now startable and stoppable at any time, a mount-time poll both misses later starts and burns requests, while the click-time refresh is always current. If you meant to keep the poll as well, say so and I will put it back.

Also fixed the two live review items in the same push:

studio/backend/run.py no longer aborts a desktop API-only start when no SPA dist resolves. The desktop spawns studio --api-only with no --frontend, and install.sh --tauri sets _SKIP_FRONTEND=1 because the app bundles its own frontend, so a --tauri --local build has no studio/frontend/dist at all. The new desktop_owned branch made _serve_frontend true there, and frontend_path defaults to an always-truthy Path, so the SystemExit fired before TAURI_PORT was emitted and the app never got a backend. It now warns and continues API-only; a web UI launch still aborts loudly.

remote-access-section.tsx no longer settles on a permanent "Stopping" after a Stop sent from the tunnel's own origin. The route answers with a fabricated terminal off, polling restarts in perform()'s finally, and the first poll can still land inside the ~50ms teardown drain and return stopping, which overwrote the off. cloudflared then exits, the next poll fails, polling latches off, and the card is stuck. remoteAccessSelfStopPoll now drops teardown frames while a self-origin disconnect is expected, while a frame that can still stop the connector proves teardown was abandoned and takes the card back over.

Both fixes have regression tests that were checked by reverting the fix and watching them fail. On the merged tree: frontend typecheck clean, 724/724 frontend tests, no new eslint or biome findings, and the affected backend suites (frontend resolution, secure tunnel gate, remote access settings, host defaults, stdio MCP, process lifetime) at 166 passed / 1 skipped.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c13118930f

ℹ️ 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".

Comment thread studio/backend/run.py


def _frontend_serving_mode(*, api_only: bool, desktop_owned: bool) -> tuple[bool, bool]:
tunnel_only = api_only and desktop_owned

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fall back to non-streaming before serving the desktop SPA

For a Tauri-owned --api-only launch, this newly mounts the full SPA behind a Cloudflare Quick Tunnel, but normal text chats still submit stream: true in chat-adapter.ts (lines 4288-4294) and consume the resulting SSE response. remote_access_settings.py explicitly records that these tunnels return an SSE response but deliver no events (lines 242-247), so a remote desktop user can load and authenticate to the UI but then have ordinary chats stall after inference starts. Make the remote SPA use a non-streaming request path, or avoid exposing the SPA until its streaming-dependent flows are supported.

Useful? React with 👍 / 👎.

danielhanchen added a commit that referenced this pull request Aug 16, 2026
…8975)

* Stop six backend tests waiting on the clock instead of on a signal

These six files spend most of their runtime asleep rather than working, and the
waiting buys nothing: every one of them is waiting out a fixed window when it
could be waiting for the event it actually cares about.

Measured on a fresh worktree off main, the six files together:
118.0s and 118.8s before, 56.5s and 55.3s after. 404 passed and 3 skipped in
every run, before and after. Backend tests runs on four Python versions, so
that is about 4 runner-minutes a run.

No production constant is lowered. The diff is six files, all under
studio/backend/tests/. Where a delay was reachable from production code the test
now passes an existing parameter at the call site: _terminate_validation_server
already takes grace, defaulted to 5.0, and the sibling test in the same commit
already passes 0.2, so this one passes 1.0 instead of taking the default four
times over. The measured margin there is 25 to 50x, since with the kill mutated
out the sentinel appears in 20 to 40ms.

test_tool_output_streaming.py is the bulk of it, 61.5s to 32.1s. Seven
grandchild processes were fused with sleep 3 and the test then waited 4s or 11s
for them. The fuse is now a gate file the test owns, so the grandchild lives
indefinitely and the assertion is stronger than "3 is greater than 1".

test_cloudflare_tunnel.py is a correctness fix that happens to save 5s.
monkeypatch.setattr(ct.threading, "Thread", ...) sets the attribute on the
threading module itself, so it replaced threading.Thread process-wide rather
than just the tunnel's stdout reader. utils/process_lifetime._Spawner then
started a helper thread that never ran, burned its full 5s readiness backstop,
and fell back to spawning inline, which silently gives up the PR_SET_PDEATHSIG
guarantee that helper thread exists to provide. No assertion is masked today
because Popen is faked too, but the patch reaches far outside what the test
meant to stub. It is now a shim that overrides Thread and proxies the rest.

Detection power is unchanged, and that is measured rather than asserted.
Neutering _killpg_captured in core/inference/tools.py fails 7 of the 55 tests in
test_tool_output_streaming.py on this branch, and the identical mutation on
unpatched main fails the same 7 by name. Same for the others: the installer test
fails when the post-SIGKILL group escalation goes, the probe test fails when the
probe runs inline, the child-lifetime test fails when PDEATHSIG is dropped, and
the cloudflare test fails when the pending-stop record is not cleared.

Attribution, since these were deliberate in some cases and accidental in others:
#7083 added the grandchild fuses, #8170 the installer grace and child lifetime,
#6494 the startup probe, #7875 the cloudflare backstop, #7454 the cold scan.
Two of those were sound decisions and are strengthened here rather than weakened.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants