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
Transcript stream: never drop a phase change behind a newer update (#12760)
Daniel Han858381b6b6c6
diff --git a/studio/backend/core/inference/transcript_stream.py b/studio/backend/core/inference/transcript_stream.pyindex 9435dc5c6f6..7d60aa59225 100644--- a/studio/backend/core/inference/transcript_stream.py+++ b/studio/backend/core/inference/transcript_stream.py@@ -4,6 +4,7 @@"""Progress and durable results for the Studio transcription screen."""import asyncio+import collectionsimport contextlibimport jsonimport time@@ -18,16 +19,27 @@ logger = get_logger(__name__)async def stream_transcript(transcribe, title: str):loop = asyncio.get_running_loop()- updates = asyncio.Queue(maxsize = 1)+ # Text progress is latest-wins: a newer update replaces an unread text one. A phase change is+ # never replaced, so a model that loads within one tick cannot swallow "loading" before the+ # client reads it. Only phases accumulate, and a run has a handful of them.+ updates = collections.deque()+ ready = asyncio.Event()closed = Falselast_update = 0.0def publish(update):if closed:return- if updates.full():- updates.get_nowait()- updates.put_nowait({"type": "progress", **update})+ if updates and not updates[-1].get("phase"):+ updates.pop()+ updates.append({"type": "progress", **update})+ ready.set()++ async def next_update():+ while not updates:+ ready.clear()+ await ready.wait()+ return updates.popleft()def on_progress(update):nonlocal last_update@@ -50,7 +62,7 @@ async def stream_transcript(transcribe, title: str):return {"type": "complete", **result, "record": record}task = asyncio.create_task(run())- pending = asyncio.create_task(updates.get())+ pending = asyncio.create_task(next_update())try:yield json.dumps({"type": "progress", "text": ""}) + "\n"while not task.done():@@ -59,9 +71,20 @@ async def stream_transcript(transcribe, title: str):)if pending in done:yield json.dumps(pending.result()) + "\n"- pending = asyncio.create_task(updates.get())+ pending = asyncio.create_task(next_update())elif not done:yield json.dumps({"type": "heartbeat"}) + "\n"+ # Updates published before the run finished still go out ahead of its result, in order.+ # Stop the reader first: left running, it would take the next update off the deque while+ # this generator is suspended on a yield below, and that update would never be sent.+ if not pending.done():+ pending.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await pending+ if not pending.cancelled():+ yield json.dumps(pending.result()) + "\n"+ while updates:+ yield json.dumps(updates.popleft()) + "\n"yield json.dumps(task.result()) + "\n"except HTTPException as exc:yield json.dumps({"type": "error", "message": exc.detail}) + "\n"diff --git a/studio/backend/tests/test_transcript_stream.py b/studio/backend/tests/test_transcript_stream.pyindex 1f3c012da5c..b62e3177501 100644--- a/studio/backend/tests/test_transcript_stream.py+++ b/studio/backend/tests/test_transcript_stream.py@@ -47,6 +47,57 @@ def test_phases_are_never_throttled(monkeypatch):assert [e["phase"] for e in events if "phase" in e] == ["loading", "transcribing"]+def test_back_to_back_phases_all_reach_the_client(monkeypatch):+ """A sidecar that loads within one tick reports "loading" and "transcribing" from its worker+ thread back to back, and may finish right after. Both phases have to reach the client, in order,+ ahead of the result: with a latest-wins queue of one, "transcribing" evicted "loading" whenever+ both landed before the reader ran, which is what made the source-route test flaky under xdist."""+ monkeypatch.setattr(transcript_stream.transcript_gallery, "save", lambda result, title: {})++ def worker(progress):+ progress({"text": "", "phase": "loading"})+ progress({"text": "", "phase": "transcribing"})++ async def transcribe(progress):+ await asyncio.to_thread(worker, progress)+ return {"text": "done", "model": "moss"}++ async def collect(stream):+ return [json.loads(line) async for line in stream]++ for _ in range(20):+ events = asyncio.run(collect(transcript_stream.stream_transcript(transcribe, "clip")))+ assert [e["phase"] for e in events if "phase" in e] == ["loading", "transcribing"]+ assert events[-1]["type"] == "complete"+++def test_every_queued_phase_reaches_a_client_that_yields_between_chunks(monkeypatch):+ """StreamingResponse awaits each chunk's send, so the generator is suspended between yields. A+ reader still running then could take a queued update off the deque mid-drain and drop it."""+ monkeypatch.setattr(transcript_stream.transcript_gallery, "save", lambda result, title: {})+ phases = ("loading", "downloading_aligner", "transcribing")++ def worker(progress):+ for phase in phases:+ progress({"text": "", "phase": phase})++ async def transcribe(progress):+ await asyncio.to_thread(worker, progress)+ return {"text": "done", "model": "moss"}++ async def collect(stream):+ events = []+ async for line in stream:+ events.append(json.loads(line))+ await asyncio.sleep(0)+ return events++ for _ in range(20):+ events = asyncio.run(collect(transcript_stream.stream_transcript(transcribe, "clip")))+ assert [e["phase"] for e in events if "phase" in e] == list(phases)+ assert events[-1]["type"] == "complete"++def test_save_failure_returns_complete_text(monkeypatch):async def transcribe(progress):return {"text": "keep this", "model": "tiny"}