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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studio: stream event feeds over post (#9533)
Maheswar Kumar27e0ff1abe55
diff --git a/studio/backend/routes/data_recipe/jobs.py b/studio/backend/routes/data_recipe/jobs.pyindex 8555914e36e..e64814d1c95 100644--- a/studio/backend/routes/data_recipe/jobs.py+++ b/studio/backend/routes/data_recipe/jobs.py@@ -6,6 +6,7 @@from __future__ import annotationsimport copy+import timefrom datetime import datetime, timedelta, timezonefrom typing import Annotated, Any, Optionalfrom urllib.parse import urlparse@@ -39,6 +40,9 @@ from utils.utils import safe_error_detail, safe_curated_detail, log_and_http_errlogger = get_logger(__name__)router = APIRouter()+# Keepalive cadence, well inside the ~100s a quick tunnel allows between body bytes.+_KEEPALIVE_EVERY_S = 15.0+# A stdio provider is a command this host would run, so only a UI session may# supply one. Annotated, not a Depends default, so a direct call gets False.ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]@@ -615,7 +619,9 @@ def publish_job_dataset(job_id: str, payload: PublishDatasetRequest):}[email protected]("/jobs/{job_id}/events")+# POST too: quick tunnels hold a streamed GET until it closes. The hidden GET keeps old clients.[email protected]("/jobs/{job_id}/events")[email protected]("/jobs/{job_id}/events", include_in_schema = False)async def job_events(request: Request, job_id: str):mgr = get_job_manager()last_id = request.headers.get("last-event-id")@@ -639,6 +645,7 @@ async def job_events(request: Request, job_id: str):async def gen():try:+ last_sent = time.monotonic()for event in sub.replay:yield sub.format_sse(event)@@ -647,9 +654,18 @@ async def job_events(request: Request, job_id: str):breakevent = await sub.next_event(timeout_sec = 1.0)if event is None:+ # A quiet job would otherwise go silent for minutes and take a tunnel 524.+ if time.monotonic() - last_sent >= _KEEPALIVE_EVERY_S:+ last_sent = time.monotonic()+ yield ": keepalive\n\n"continue+ last_sent = time.monotonic()yield sub.format_sse(event)finally:mgr.unsubscribe(sub)- return StreamingResponse(gen(), media_type = "text/event-stream")+ return StreamingResponse(+ gen(),+ media_type = "text/event-stream",+ headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ )diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.pyindex 5ec4b94dc62..ccc19889cc9 100644--- a/studio/backend/routes/export.py+++ b/studio/backend/routes/export.py@@ -213,11 +213,10 @@ async def get_export_logs(The SSE endpoint (`/logs/stream`) is the low-latency path, but some reverseproxies -- notably Cloudflare quick tunnels (`*.trycloudflare.com`) used by- `--secure` mode -- buffer `text/event-stream` responses and only flush when- the stream closes, so over the tunnel the browser sees nothing for the whole- export ("connecting..." with no logs). This endpoint returns the same- ring-buffer lines as a short, complete JSON response that no proxy buffers,- so the frontend can poll it and still show logs in near real time.+ `--secure` mode -- buffer streamed GET responses until the stream closes.+ This endpoint returns the same ring-buffer lines as a short, complete JSON+ response that no proxy buffers, so the frontend can poll it and still show+ logs in near real time even where the stream itself does not arrive.Shares the orchestrator's monotonic `seq` cursor with the SSE stream, so thetwo transports can run together and the client de-dupes by seq.@@ -509,7 +508,9 @@ def _format_sse(return "\n".join(lines)[email protected]("/logs/stream")+# POST too: quick tunnels hold a streamed GET until it closes. The hidden GET keeps old clients.[email protected]("/logs/stream")[email protected]("/logs/stream", include_in_schema = False)async def stream_export_logs(request: Request,since: Optional[int] = Query(diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.pyindex b7cbcad93dd..596e54a85bc 100644--- a/studio/backend/routes/rag.py+++ b/studio/backend/routes/rag.py@@ -812,7 +812,9 @@ def job_status(job_id: str, subject: str = Depends(get_current_subject)) -> dict}[email protected]("/jobs/{job_id}/events")+# POST too: quick tunnels hold a streamed GET until it closes. The hidden GET keeps old clients.[email protected]("/jobs/{job_id}/events")[email protected]("/jobs/{job_id}/events", include_in_schema = False)def job_events(job_id: str, subject: str = Depends(get_current_subject)) -> StreamingResponse:_require_rag()@@ -865,7 +867,9 @@ def folder_job_status(job_id: str, subject: str = Depends(get_current_subject))return _folder_job_view(row)[email protected]("/linked-folder-jobs/{job_id}/events")+# POST too, for the same reason as /jobs/{job_id}/events above.[email protected]("/linked-folder-jobs/{job_id}/events")[email protected]("/linked-folder-jobs/{job_id}/events", include_in_schema = False)def folder_job_events(job_id: str, subject: str = Depends(get_current_subject)) -> StreamingResponse:diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex 669febd7056..e88d3d73f3f 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -2067,7 +2067,9 @@ async def get_training_metrics()[email protected]("/progress")+# POST too: quick tunnels hold a streamed GET until it closes. The hidden GET keeps old clients.[email protected]("/progress")[email protected]("/progress", include_in_schema = False)async def stream_training_progress(request: Request,expected_job_id: Optional[str] = None,diff --git a/studio/backend/tests/test_quick_tunnel_streaming_routes.py b/studio/backend/tests/test_quick_tunnel_streaming_routes.pynew file mode 100644index 00000000000..45c723ac4b4--- /dev/null+++ b/studio/backend/tests/test_quick_tunnel_streaming_routes.py@@ -0,0 +1,81 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Keep first-party event streams usable through Cloudflare Quick Tunnels.++Measured on three fresh quick tunnels, one generator on both verbs so only the method+differs: GET delivers its first byte when the stream closes (~12s), POST in under 300ms,+and no response header recovers GET. Checks registration rather than source text, since a+route that stopped resolving or lost a dependency would still spell "post" in the file.+"""++import importlib++import pytest+++_CASES = [+ ("routes.training", "/progress", "stream_training_progress"),+ ("routes.export", "/logs/stream", "stream_export_logs"),+ ("routes.rag", "/jobs/{job_id}/events", "job_events"),+ ("routes.rag", "/linked-folder-jobs/{job_id}/events", "folder_job_events"),+ ("routes.data_recipe.jobs", "/jobs/{job_id}/events", "job_events"),+]+++def _routes_at(module_name: str, route_path: str) -> list:+ router = importlib.import_module(module_name).router+ return [r for r in router.routes if getattr(r, "path", None) == route_path]++[email protected]("module_name,route_path,function_name", _CASES)+def test_first_party_event_streams_accept_post_and_get(+ module_name: str, route_path: str, function_name: str+) -> None:+ routes = _routes_at(module_name, route_path)+ by_method = {m: r for r in routes for m in r.methods if m in ("GET", "POST")}++ assert set(by_method) == {"GET", "POST"}+ assert by_method["GET"].endpoint is by_method["POST"].endpoint+ assert by_method["GET"].endpoint.__name__ == function_name+ # Only POST is public, so a generated client picks the verb that survives a tunnel.+ assert by_method["POST"].include_in_schema is True+ assert by_method["GET"].include_in_schema is False++[email protected]("module_name,route_path,function_name", _CASES)+def test_both_verbs_carry_the_same_dependencies(+ module_name: str, route_path: str, function_name: str+) -> None:+ """A second registration re-runs the decorator, so divergence here is divergent auth."""+ signatures = {+ tuple(sorted(d.call.__name__ for d in r.dependant.dependencies))+ for r in _routes_at(module_name, route_path)+ }+ assert len(signatures) == 1, signatures+++def test_only_post_reaches_the_schema() -> None:+ """One api_route for both verbs would give them one operationId; two registrations+ with GET hidden keeps the ids unique and the public contract single."""+ import main++ schema = main.app.openapi()+ for full_path in (+ "/api/train/progress",+ "/api/export/logs/stream",+ "/api/rag/jobs/{job_id}/events",+ "/api/rag/linked-folder-jobs/{job_id}/events",+ "/api/data-recipe/jobs/{job_id}/events",+ "/api/chat/research-runs/{run_id}/events",+ ):+ assert full_path in schema["paths"], full_path+ assert {v for v in schema["paths"][full_path] if v in ("get", "post")} == {"post"}++ operation_ids = [+ operation["operationId"]+ for path_item in schema["paths"].values()+ for verb, operation in path_item.items()+ if verb in ("get", "post", "put", "patch", "delete") and "operationId" in operation+ ]+ assert len(operation_ids) == len(set(operation_ids))diff --git a/studio/backend/tests/test_sse_streaming_headers.py b/studio/backend/tests/test_sse_streaming_headers.pyindex ef6022fa26b..6192c795643 100644--- a/studio/backend/tests/test_sse_streaming_headers.py+++ b/studio/backend/tests/test_sse_streaming_headers.py@@ -3,11 +3,9 @@"""Regression tests for the shared SSE streaming-response helper.-Streaming endpoints must disable proxy buffering (``X-Accel-Buffering: no``);-without it a reverse proxy (nginx / cloudflare tunnel) buffers the response and-tokens stop appearing in real time. The native ``/generate/stream`` and legacy-``/v1/completions`` streams historically omitted it and now route through the-shared helper, so locking the helper's headers guards every standard path.+Streaming endpoints must disable nginx buffering (``X-Accel-Buffering: no``); Cloudflare+Quick Tunnels additionally need first-party clients on POST, since they hold a streamed+GET. ``/generate/stream`` and legacy ``/v1/completions`` route through this helper."""import routes.inference as inference_routediff --git a/studio/backend/utils/remote_access_settings.py b/studio/backend/utils/remote_access_settings.pyindex 7d13f6aad03..d00b859b026 100644--- a/studio/backend/utils/remote_access_settings.py+++ b/studio/backend/utils/remote_access_settings.py@@ -239,11 +239,9 @@ def remote_access_status(app_state) -> dict:"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.+ # Plain GET/EventSource support, not Studio's own streams, which use POST.+ # Measured on three quick tunnels: a streamed GET delivers nothing until it+ # closes, and no response header changes that."streaming_supported": status["url"] is None,}diff --git a/studio/frontend/src/features/export/api/export-api.ts b/studio/frontend/src/features/export/api/export-api.tsindex be9767a24f8..5175ef4089c 100644--- a/studio/frontend/src/features/export/api/export-api.ts+++ b/studio/frontend/src/features/export/api/export-api.ts@@ -3,6 +3,7 @@import { authFetch } from "@/features/auth";import { readFastApiError } from "@/lib/format-fastapi-error";+import { openStreamResponse } from "@/lib/open-stream-response";const readError = (r: Response): Promise<string> => readFastApiError(r);@@ -263,11 +264,9 @@ export interface ExportLogsResponse {}/**- * Tunnel-safe JSON fallback for {@link streamExportLogs}. Cloudflare quick- * tunnels (`--secure` mode) buffer `text/event-stream`, so the SSE stream- * delivers nothing until it closes; this plain-JSON poll is never buffered and- * carries the same ring-buffer lines. Poll it while a run is active and merge- * the entries into the store (de-duped by seq), so logs appear over the tunnel.+ * Short-response fallback for {@link streamExportLogs}, carrying the same+ * ring-buffer lines when a proxy drops or stalls the stream. Poll it while a run+ * is active and merge entries into the store, de-duped by seq.*/export async function fetchExportLogs(since: number | null,@@ -345,8 +344,7 @@ export async function streamExportLogs(options: {? `/api/export/logs/stream?since=${options.since}`: "/api/export/logs/stream";- const response = await authFetch(url, {- method: "GET",+ const response = await openStreamResponse(authFetch, url, {headers,signal: options.signal,});diff --git a/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts b/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.tsindex cdf771f2b76..a55988bc702 100644--- a/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts+++ b/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts@@ -12,10 +12,7 @@ import { useExportRuntimeStore } from "../stores/export-runtime-store";const STATUS_POLL_INTERVAL_MS = 5000;const STREAM_RECONNECT_DELAY_MS = 600;-// JSON log poll cadence. The SSE stream is the low-latency path on localhost,-// but Cloudflare quick tunnels (`--secure`) buffer `text/event-stream`, so this-// poll is the transport that actually delivers logs over the tunnel. Short-// JSON responses are never buffered, so this works through any proxy.+// Short-response fallback cadence, for a proxy that drops or stalls the log stream.const LOG_POLL_INTERVAL_MS = 750;/**diff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.tsindex 68bf7ca2c6e..18294e90f06 100644--- a/studio/frontend/src/features/rag/api/rag-api.ts+++ b/studio/frontend/src/features/rag/api/rag-api.ts@@ -4,6 +4,7 @@import { authFetch } from "@/features/auth";import { apiUrl } from "@/lib/api-base";import { formatFastApiDetail } from "@/lib/format-fastapi-error";+import { openStreamResponse } from "@/lib/open-stream-response";import { readSseJsonEvents } from "@/lib/sse-json-events";import type {DocumentUploadResult,@@ -730,7 +731,7 @@ async function openEventStream(url: string,signal: AbortSignal | undefined,): Promise<ReadableStream<Uint8Array>> {- const response = await authFetch(url, signal ? { signal } : undefined);+ const response = await openStreamResponse(authFetch, url, { signal });if (!response.ok) {const body = await response.json().catch(() => null);// also gated on the extension, and also not routed through ragRequestdiff --git a/studio/frontend/src/features/recipe-studio/api/index.ts b/studio/frontend/src/features/recipe-studio/api/index.tsindex dafe7c504a4..c99c21eca1b 100644--- a/studio/frontend/src/features/recipe-studio/api/index.ts+++ b/studio/frontend/src/features/recipe-studio/api/index.ts@@ -6,6 +6,7 @@ import {formatFastApiDetail,readFastApiError,} from "@/lib/format-fastapi-error";+import { openStreamResponse } from "@/lib/open-stream-response";const DEFAULT_BASE = "/api/data-recipe";@@ -379,13 +380,10 @@ export async function streamRecipeJobEvents(options: {query = `?after=${options.lastEventId}`;}- const response = await authFetch(+ const response = await openStreamResponse(+ authFetch,`${DATA_DESIGNER_API_BASE}/jobs/${options.jobId}/events${query}`,- {- method: "GET",- headers,- signal: options.signal,- },+ { headers, signal: options.signal },);if (!response.ok) {throw new Error(await parseErrorResponse(response));diff --git a/studio/frontend/src/features/settings/lib/debug-log-buffer.ts b/studio/frontend/src/features/settings/lib/debug-log-buffer.tsindex 96ed2189357..733fe1fce50 100644--- a/studio/frontend/src/features/settings/lib/debug-log-buffer.ts+++ b/studio/frontend/src/features/settings/lib/debug-log-buffer.ts@@ -63,8 +63,7 @@ export interface LogBufferState {export const EMPTY_BUFFER: LogBufferState = { lines: [], cursor: null };/** Poll delay for a mode, or null when the user drives it by hand. "live" polls- * rather than opening a socket: Cloudflare quick tunnels buffer- * text/event-stream and only flush at close, which is why the export log polls too.+ * with short requests rather than streaming, so it survives any proxy.*/export function pollDelayMs(mode: RefreshMode): number | null {switch (mode) {diff --git a/studio/frontend/src/features/training/api/train-api.ts b/studio/frontend/src/features/training/api/train-api.tsindex 06fe537cd9d..dcaaac69397 100644--- a/studio/frontend/src/features/training/api/train-api.ts+++ b/studio/frontend/src/features/training/api/train-api.ts@@ -3,6 +3,7 @@import { authFetch } from "@/features/auth";import { readFastApiError } from "@/lib/format-fastapi-error";+import { openStreamResponse } from "@/lib/open-stream-response";import { createScopedSingleFlightRequest } from "@/lib/single-flight-request";import {type ParsedTrainingProgressEvent,@@ -363,13 +364,10 @@ export async function streamTrainingProgress(options: {}const expectedJobId = encodeURIComponent(options.expectedJobId);- const response = await authFetch(+ const response = await openStreamResponse(+ authFetch,`/api/train/progress?expected_job_id=${expectedJobId}`,- {- method: "GET",- headers,- signal: options.signal,- },+ { headers, signal: options.signal },{ retryNetworkErrors: false },);diff --git a/studio/frontend/src/lib/open-stream-response.ts b/studio/frontend/src/lib/open-stream-response.tsnew file mode 100644index 00000000000..c22d1e3e929--- /dev/null+++ b/studio/frontend/src/lib/open-stream-response.ts@@ -0,0 +1,31 @@+// 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 StreamFetcher = (+ url: string,+ init: RequestInit,+ options?: { retryNetworkErrors?: boolean },+) => Promise<Response>;++/**+ * Open an event stream over POST, retrying once as GET on 405.+ *+ * Quick tunnels hold a streamed GET until it closes, so POST is the verb that works.+ * The retry covers version skew only: the desktop app ships its own SPA but updates the+ * Python backend separately, so a newer UI can meet a GET-only backend. That pairing is+ * always loopback, where a streamed GET is fine.+ *+ * 405 only. These routes answer 404 for an unknown job, and retrying would double misses.+ */+export async function openStreamResponse(+ fetcher: StreamFetcher,+ url: string,+ init: RequestInit = {},+ options?: { retryNetworkErrors?: boolean },+): Promise<Response> {+ const response = await fetcher(url, { ...init, method: "POST" }, options);+ if (response.status !== 405) {+ return response;+ }+ return fetcher(url, { ...init, method: "GET" }, options);+}diff --git a/studio/frontend/tests/quick-tunnel-streaming-methods.test.ts b/studio/frontend/tests/quick-tunnel-streaming-methods.test.tsnew file mode 100644index 00000000000..539f7c673a4--- /dev/null+++ b/studio/frontend/tests/quick-tunnel-streaming-methods.test.ts@@ -0,0 +1,130 @@+// 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 { readFile } from "node:fs/promises";+import test from "node:test";+import { openStreamResponse } from "../src/lib/open-stream-response.ts";++const GET_METHOD_RE = /method:\s*"GET"/;+const OPEN_STREAM_RE = /openStreamResponse\s*\(/;++/** Drop comments first: a stale "// method: GET" note would fail the test and a+ * commented-out call would pass it. Own-the-line only, so "https://" in a string lives. */+function stripComments(source: string): string {+ return source+ .replace(/\/\*[\s\S]*?\*\//g, "")+ .replace(/^[ \t]*\/\/[^\n]*/gm, "");+}++/** Brace-balanced, so an object literal closing at column 0 cannot end the body early.+ * Skips the parameter list first: an inline options type opens a brace before the body. */+function functionBody(source: string, name: string): string {+ const start = source.search(+ new RegExp(`(async )?function\\*?\\s+${name}\\b`),+ );+ if (start < 0) {+ throw new Error(`${name} is gone or was renamed`);+ }+ let parens = 0;+ let i = source.indexOf("(", start);+ for (; i < source.length; i++) {+ if (source[i] === "(") parens++;+ else if (source[i] === ")" && --parens === 0) break;+ }+ let braces = 0;+ for (i = source.indexOf("{", i); i < source.length; i++) {+ if (source[i] === "{") braces++;+ else if (source[i] === "}" && --braces === 0)+ return source.slice(start, i + 1);+ }+ throw new Error(`could not find the end of ${name}`);+}++for (const [relativePath, functionName] of [+ ["features/training/api/train-api.ts", "streamTrainingProgress"],+ ["features/export/api/export-api.ts", "streamExportLogs"],+ ["features/rag/api/rag-api.ts", "openEventStream"],+ ["features/recipe-studio/api/index.ts", "streamRecipeJobEvents"],+] as const) {+ test(`${functionName} opens its event stream through openStreamResponse`, async () => {+ const source = await readFile(+ new URL(`../src/${relativePath}`, import.meta.url),+ "utf8",+ );+ const body = functionBody(stripComments(source), functionName);+ assert.match(body, OPEN_STREAM_RE);+ // A caller that pinned GET itself would silently opt out of the tunnel fix.+ assert.doesNotMatch(body, GET_METHOD_RE);+ });+}++function recorder(statuses: number[]) {+ const calls: Array<{ url: string; method?: string; init: RequestInit }> = [];+ const fetcher = (url: string, init: RequestInit) => {+ calls.push({ url, method: init.method, init });+ const status = statuses[calls.length - 1] ?? 200;+ return Promise.resolve(new Response(null, { status }));+ };+ return { calls, fetcher };+}++test("openStreamResponse asks for POST first", async () => {+ const { calls, fetcher } = recorder([200]);+ const response = await openStreamResponse(fetcher, "/api/train/progress");+ assert.equal(response.status, 200);+ assert.deepEqual(+ calls.map((c) => c.method),+ ["POST"],+ );+});++test("openStreamResponse retries as GET on 405, which is the old-backend reply", async () => {+ const { calls, fetcher } = recorder([405, 200]);+ const response = await openStreamResponse(fetcher, "/api/train/progress");+ assert.equal(response.status, 200);+ assert.deepEqual(+ calls.map((c) => c.method),+ ["POST", "GET"],+ );+ assert.equal(calls[0].url, calls[1].url);+});++for (const status of [400, 401, 403, 404, 409, 500]) {+ test(`openStreamResponse does not retry on ${status}`, async () => {+ const { calls, fetcher } = recorder([status, 200]);+ const response = await openStreamResponse(+ fetcher,+ "/api/rag/jobs/x/events",+ );+ // 404 is a real answer here (unknown job); retrying would double every miss.+ assert.equal(response.status, status);+ assert.deepEqual(+ calls.map((c) => c.method),+ ["POST"],+ );+ });+}++test("openStreamResponse forwards headers, signal and fetch options to both attempts", async () => {+ const { calls, fetcher } = recorder([405, 200]);+ const controller = new AbortController();+ const headers = new Headers({ "Last-Event-ID": "7" });+ await openStreamResponse(+ fetcher,+ "/api/export/logs/stream?since=7",+ { headers, signal: controller.signal },+ { retryNetworkErrors: false },+ );+ for (const call of calls) {+ assert.equal((call.init.headers as Headers).get("Last-Event-ID"), "7");+ assert.equal(call.init.signal, controller.signal);+ }+});++test("openStreamResponse retries at most once", async () => {+ const { calls, fetcher } = recorder([405, 405]);+ const response = await openStreamResponse(fetcher, "/api/train/progress");+ assert.equal(response.status, 405);+ assert.equal(calls.length, 2);+});