Skip to content

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

Studio: resume local chat generation after disconnect (#9187)

Etherl485423ff8096
diff --git a/studio/backend/core/inference/chat_generation_runs.py b/studio/backend/core/inference/chat_generation_runs.py
new file mode 100644
index 00000000000..08dea20fdcf
--- /dev/null
+++ b/studio/backend/core/inference/chat_generation_runs.py
@@ -0,0 +1,451 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Background producer for durable local Studio chat generations."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import threading
+import time
+from typing import Any, AsyncIterator
+
+from starlette.requests import Request
+
+from core.inference.llama_keepwarm import InferenceActivityReservation
+from loggers import get_logger
+from models.inference import ChatCompletionRequest
+from state import active_generations
+from storage import chat_generation_runs_db as db
+
+logger = get_logger(__name__)
+_EVENT_BATCH_SIZE = 16
+_EVENT_BATCH_MIN_SIZE = 2
+_EVENT_BATCH_SECONDS = 0.1
+_EVENT_SINGLE_FLUSH_SECONDS = 1.0
+_SHUTDOWN_GRACE_SECONDS = 10.0
+# Second budget, after task.cancel(). Shorter than the grace period: by this point the
+# run is already being abandoned, and the only question is whether shutdown returns.
+_SHUTDOWN_CANCEL_SECONDS = 5.0
+
+
+class _SSEDecoder:
+ def __init__(self) -> None:
+ self.buffer = ""
+
+ def feed(self, text: str) -> list[str]:
+ self.buffer += text.replace("\r\n", "\n")
+ values: list[str] = []
+ while "\n\n" in self.buffer:
+ block, self.buffer = self.buffer.split("\n\n", 1)
+ data = "\n".join(
+ line[5:].lstrip() for line in block.splitlines() if line.startswith("data:")
+ )
+ if data:
+ values.append(data)
+ return values
+
+
+def _background_request(app: Any, run_id: str, cancel_event: threading.Event) -> Request:
+ scope = {
+ "type": "http",
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
+ "http_version": "1.1",
+ "method": "POST",
+ "scheme": "http",
+ "path": "/api/inference/chat-runs/producer",
+ "raw_path": b"/api/inference/chat-runs/producer",
+ "query_string": b"",
+ "headers": [(b"x-unsloth-generation-run", run_id.encode("ascii", "ignore"))],
+ "client": ("127.0.0.1", 0),
+ "server": ("127.0.0.1", 0),
+ "app": app,
+ "state": {"generation_cancel_event": cancel_event},
+ }
+
+ async def receive():
+ return {"type": "http.request", "body": b"", "more_body": False}
+
+ return Request(scope, receive)
+
+
+def _chunk_finish_reason(chunk: dict[str, Any]) -> str | None:
+ choices = chunk.get("choices")
+ if not isinstance(choices, list):
+ return None
+ for choice in choices:
+ if isinstance(choice, dict) and choice.get("finish_reason") is not None:
+ return str(choice["finish_reason"])
+ return None
+
+
+def _chunk_error(chunk: dict[str, Any]) -> str | None:
+ error = chunk.get("error")
+ if isinstance(error, dict):
+ return str(error.get("message") or error.get("detail") or "Generation failed")[:1000]
+ if error:
+ return str(error)[:1000]
+ return None
+
+
+async def _close_iterator(iterator: AsyncIterator[Any] | None) -> None:
+ close = getattr(iterator, "aclose", None)
+ if close is not None:
+ try:
+ await close()
+ except Exception:
+ pass
+
+
+class ChatGenerationSupervisor:
+ def __init__(self, app: Any) -> None:
+ self.app = app
+ self._tasks: dict[str, asyncio.Task] = {}
+ self._cancel_events: dict[str, threading.Event] = {}
+ self._active_registrations: dict[str, active_generations.ActiveGeneration] = {}
+ self._activities: dict[str, InferenceActivityReservation] = {}
+ self._shutdown_runs: set[str] = set()
+ self._stopping = False
+
+ def _ensure_reservation(
+ self,
+ run_id: str,
+ *,
+ thread_id: str | None = None,
+ model: str | None = None,
+ ) -> bool:
+ if self._stopping:
+ return False
+ cancel_event = self._cancel_events.get(run_id)
+ if cancel_event is not None:
+ # Enrich an early run-only reservation with authoritative identity.
+ with active_generations.ActiveGeneration(
+ cancel_event,
+ run_id = run_id,
+ thread_id = thread_id,
+ model = model,
+ ):
+ pass
+ return True
+ cancel_event = threading.Event()
+ activity = InferenceActivityReservation()
+ activity.reserve()
+ registration = active_generations.ActiveGeneration(
+ cancel_event,
+ run_id = run_id,
+ thread_id = thread_id,
+ model = model,
+ )
+ registration.__enter__()
+ self._cancel_events[run_id] = cancel_event
+ self._activities[run_id] = activity
+ self._active_registrations[run_id] = registration
+ return True
+
+ def start(
+ self,
+ run_id: str,
+ *,
+ thread_id: str | None = None,
+ model: str | None = None,
+ ) -> None:
+ if (
+ self._stopping
+ or run_id in self._tasks
+ or not self._ensure_reservation(run_id, thread_id = thread_id, model = model)
+ ):
+ return
+ cancel_event = self._cancel_events[run_id]
+ activity = self._activities[run_id]
+ try:
+ task = asyncio.create_task(
+ self._produce(run_id, cancel_event, activity),
+ name = f"chat-generation-{run_id}",
+ )
+ except BaseException:
+ self._cleanup_registration(run_id)
+ raise
+ self._tasks[run_id] = task
+ task.add_done_callback(lambda completed, rid = run_id: self._task_done(rid, completed))
+
+ def _cleanup_registration(self, run_id: str) -> None:
+ self._cancel_events.pop(run_id, None)
+ activity = self._activities.pop(run_id, None)
+ if activity is not None:
+ activity.finish()
+ registration = self._active_registrations.pop(run_id, None)
+ if registration is not None:
+ registration.__exit__(None, None, None)
+
+ def _task_done(self, run_id: str, task: asyncio.Task) -> None:
+ self._tasks.pop(run_id, None)
+ self._cleanup_registration(run_id)
+ self._shutdown_runs.discard(run_id)
+ if task.cancelled():
+ return
+ try:
+ task.result()
+ except Exception as exc:
+ logger.error("Durable chat generation %s crashed: %s", run_id, exc)
+
+ def cancel(self, run_id: str) -> None:
+ cancel_event = self._cancel_events.get(run_id)
+ if cancel_event is not None:
+ cancel_event.set()
+ else:
+ task = self._tasks.get(run_id)
+ if task is not None and not task.done():
+ # Defensive compatibility for a task registered by a caller
+ # other than start(); production tasks always own an event.
+ task.cancel()
+ active_generations.cancel_run(run_id)
+ # The inference cancel registry closes the narrow gap where registration is imminent
+ # but this supervisor has not yet observed it.
+ from routes.inference import _cancel_by_cancel_id_or_stash
+
+ _cancel_by_cancel_id_or_stash(run_id)
+
+ async def stop(self) -> None:
+ self._stopping = True
+ tasks = list(self._tasks.items())
+ self._shutdown_runs.update(run_id for run_id, _task in tasks)
+ for run_id, _task in tasks:
+ self.cancel(run_id)
+ if not tasks:
+ return
+ # asyncio.wait, not wait_for(gather(...)): on timeout wait_for cancels the inner
+ # future and then awaits it, so a producer that does not unwind on cancellation --
+ # an engine draining its subprocess inside the generator's aclose -- makes the
+ # wait itself unbounded, and takes the whole uvicorn shutdown down with it. wait
+ # returns the pending set instead and leaves those tasks alone.
+ pending = {task for _run_id, task in tasks}
+ _done, pending = await asyncio.wait(pending, timeout = _SHUTDOWN_GRACE_SECONDS)
+ if not pending:
+ return
+ for task in pending:
+ task.cancel()
+ _done, pending = await asyncio.wait(pending, timeout = _SHUTDOWN_CANCEL_SECONDS)
+ if pending:
+ stuck = [run_id for run_id, task in tasks if task in pending]
+ # Abandoned, not leaked: the run is already fenced and reconcile_orphaned_runs
+ # settles it on the next boot. Process exit reclaims the rest.
+ logger.warning(
+ "Durable chat generations did not stop within the shutdown budget: %s",
+ ", ".join(stuck),
+ )
+
+ async def _produce(
+ self,
+ run_id: str,
+ cancel_event: threading.Event | None = None,
+ activity: InferenceActivityReservation | None = None,
+ ) -> None:
+ cancel_event = cancel_event or threading.Event()
+ if activity is None:
+ activity = InferenceActivityReservation()
+ activity.reserve()
+ pending: list[tuple[str, dict[str, Any], int]] = []
+ iterator: AsyncIterator[Any] | None = None
+ last_flush = time.monotonic()
+ finish_reason: str | None = None
+ error: str | None = None
+ saw_done = False
+ worker_token: str | None = None
+ next_raw_task: asyncio.Task | None = None
+ try:
+ worker_run = await asyncio.to_thread(db.get_worker_run, run_id)
+ if worker_run is None:
+ return
+ run, owner, worker_token = worker_run
+ if cancel_event.is_set():
+ shutting_down = run_id in self._shutdown_runs
+ await asyncio.to_thread(
+ db.finish_run,
+ run_id,
+ worker_token = worker_token,
+ status = "failed" if shutting_down else "cancelled",
+ finish_reason = "interrupted" if shutting_down else "cancelled",
+ error = "Studio shut down during generation" if shutting_down else None,
+ )
+ return
+ await activity.start(cancel_event)
+ if cancel_event.is_set():
+ shutting_down = run_id in self._shutdown_runs
+ await asyncio.to_thread(
+ db.finish_run,
+ run_id,
+ worker_token = worker_token,
+ status = "failed" if shutting_down else "cancelled",
+ finish_reason = "interrupted" if shutting_down else "cancelled",
+ error = "Studio shut down during generation" if shutting_down else None,
+ )
+ return
+ if not await asyncio.to_thread(db.mark_running, run_id, worker_token):
+ return
+ worker_run = await asyncio.to_thread(db.get_worker_run, run_id, worker_token)
+ if worker_run is None:
+ return
+ run, owner, worker_token = worker_run
+ if run["status"] != "running" or run["cancelRequested"]:
+ await asyncio.to_thread(
+ db.finish_run,
+ run_id,
+ worker_token = worker_token,
+ status = "cancelled",
+ )
+ return
+
+ from routes.inference import produce_openai_chat_completions
+
+ payload = ChatCompletionRequest.model_validate(run["requestPayload"])
+ response = await produce_openai_chat_completions(
+ payload,
+ _background_request(self.app, run_id, cancel_event),
+ owner,
+ cancel_on_disconnect = False,
+ )
+ if int(getattr(response, "status_code", 200)) >= 400:
+ raise RuntimeError(f"Local generation returned HTTP {response.status_code}")
+ iterator = getattr(response, "body_iterator", None)
+ if iterator is None:
+ raise RuntimeError("Local generation did not return an event stream")
+ decoder = _SSEDecoder()
+ next_raw_task = asyncio.create_task(iterator.__anext__())
+ while True:
+ timeout = (
+ max(
+ 0.0,
+ (
+ _EVENT_BATCH_SECONDS
+ if len(pending) >= _EVENT_BATCH_MIN_SIZE
+ else _EVENT_SINGLE_FLUSH_SECONDS
+ )
+ - (time.monotonic() - last_flush),
+ )
+ if pending
+ else None
+ )
+ ready, _waiting = await asyncio.wait({next_raw_task}, timeout = timeout)
+ if not ready:
+ await asyncio.to_thread(
+ db.append_events,
+ run_id,
+ worker_token,
+ pending,
+ )
+ pending = []
+ last_flush = time.monotonic()
+ continue
+ try:
+ raw = next_raw_task.result()
+ except StopAsyncIteration:
+ next_raw_task = None
+ break
+ next_raw_task = asyncio.create_task(iterator.__anext__())
+ text = raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw)
+ for encoded in decoder.feed(text):
+ if encoded == "[DONE]":
+ saw_done = True
+ break
+ try:
+ chunk = json.loads(encoded)
+ except (TypeError, ValueError):
+ continue
+ if not isinstance(chunk, dict):
+ continue
+ pending.append(("chunk", chunk, db.now_ms()))
+ finish_reason = _chunk_finish_reason(chunk) or finish_reason
+ error = _chunk_error(chunk) or error
+ now = time.monotonic()
+ if len(pending) >= _EVENT_BATCH_SIZE or (
+ len(pending) >= _EVENT_BATCH_MIN_SIZE
+ and now - last_flush >= _EVENT_BATCH_SECONDS
+ ):
+ await asyncio.to_thread(
+ db.append_events,
+ run_id,
+ worker_token,
+ pending,
+ )
+ pending = []
+ last_flush = now
+ if saw_done:
+ break
+
+ current = await asyncio.to_thread(db.get_run, run_id)
+ if current is None:
+ return
+ if run_id in self._shutdown_runs:
+ status = "failed"
+ finish_reason = "interrupted"
+ error = "Studio shut down during generation"
+ elif current["cancelRequested"] or (cancel_event.is_set() and error is None):
+ # A bare event is not proof of a user stop: the streaming paths set this
+ # same event from their cleanup after emitting an in-band error, so a
+ # parsed failure outranks it. An explicit cancelRequested still wins,
+ # and a real Stop carries no error chunk, so neither loses its identity.
+ status = "cancelled"
+ finish_reason = "cancelled"
+ elif error is not None:
+ status = "failed"
+ elif not saw_done and finish_reason is None:
+ status = "failed"
+ finish_reason = "interrupted"
+ error = "Generation stream ended before completion"
+ else:
+ status = "completed"
+ await asyncio.to_thread(
+ db.finish_run,
+ run_id,
+ worker_token = worker_token,
+ status = status,
+ finish_reason = finish_reason,
+ error = error,
+ pending_events = pending,
+ )
+ pending = []
+ except asyncio.CancelledError:
+ if worker_token is not None:
+ shutting_down = run_id in self._shutdown_runs
+ cancelled = cancel_event.is_set() and not shutting_down
+ await asyncio.to_thread(
+ db.finish_run,
+ run_id,
+ worker_token = worker_token,
+ status = "cancelled" if cancelled else "failed",
+ finish_reason = "cancelled" if cancelled else "interrupted",
+ error = None if cancelled else "Generation worker stopped unexpectedly",
+ pending_events = pending,
+ )
+ pending = []
+ raise
+ except Exception as exc:
+ if worker_token is not None:
+ shutting_down = run_id in self._shutdown_runs
+ cancelled = cancel_event.is_set() and not shutting_down
+ await asyncio.to_thread(
+ db.finish_run,
+ run_id,
+ worker_token = worker_token,
+ status = "cancelled" if cancelled else "failed",
+ finish_reason = (
+ "cancelled" if cancelled else "interrupted" if shutting_down else "error"
+ ),
+ error = (
+ None
+ if cancelled
+ else "Studio shut down during generation"
+ if shutting_down
+ else str(exc)[:1000]
+ ),
+ pending_events = pending,
+ )
+ pending = []
+ finally:
+ if next_raw_task is not None:
+ if not next_raw_task.done():
+ next_raw_task.cancel()
+ await asyncio.gather(next_raw_task, return_exceptions = True)
+ await _close_iterator(iterator)
+ activity.finish()
diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.py
index f9b8eceeb1e..24254ea79fe 100644
--- a/studio/backend/core/inference/llama_keepwarm.py
+++ b/studio/backend/core/inference/llama_keepwarm.py
@@ -60,16 +60,24 @@ _lifecycle_lock = threading.Lock()
@contextlib.asynccontextmanager
-async def _unload_gate():
- # Non-blocking acquire first (common uncontended case), else poll off a short sleep.
- # Polling keeps the wait off this loop AND cancellation-safe: a cancel lands during the
- # sleep, when the gate is not held, so it never leaks (mirrors the auto-switch swap gate).
- while not _lifecycle_lock.acquire(blocking = False):
- await asyncio.sleep(0.02)
+async def _unload_gate(cancel_event: threading.Event | None = None):
+ # Acquire off the loop: non-blocking first (the common uncontended case), else
+ # poll a non-blocking acquire off a short sleep. Polling keeps the wait off this
+ # loop AND cancellation-safe -- a cancel lands during the sleep, when the gate is
+ # not held, so it never leaks (mirrors the auto-switch swap gate).
+ acquired = False
try:
+ while not _lifecycle_lock.acquire(blocking = False):
+ if cancel_event is not None and cancel_event.is_set():
+ raise asyncio.CancelledError()
+ await asyncio.sleep(0.02)
+ acquired = True
+ if cancel_event is not None and cancel_event.is_set():
+ raise asyncio.CancelledError()
yield
finally:
- _lifecycle_lock.release()
+ if acquired:
+ _lifecycle_lock.release()
_INFERENCE_PREFIXES = ("/v1/", "/api/inference/")
@@ -154,6 +162,45 @@ def _note_end(is_preview: bool = False) -> None:
_preview_inflight = max(0, _preview_inflight - 1)
+class InferenceActivityReservation:
+ """Keep a background inference job visible to lifecycle and idle-unload guards."""
+
+ def __init__(self) -> None:
+ self._state = "new"
+ self._state_lock = threading.Lock()
+
+ def reserve(self) -> None:
+ """Publish pending work synchronously, before its asyncio task can run."""
+ with self._state_lock:
+ if self._state != "new":
+ return
+ _note_pending()
+ self._state = "pending"
+
+ async def start(self, cancel_event: threading.Event | None = None) -> None:
+ """Claim the inference slot after any model lifecycle operation completes."""
+ with self._state_lock:
+ if self._state != "pending":
+ return
+ async with _unload_gate(cancel_event):
+ with self._state_lock:
+ if self._state != "pending":
+ return
+ _note_start()
+ self._state = "started"
+
+ def finish(self) -> None:
+ """Balance a pending or started reservation. Idempotent."""
+ with self._state_lock:
+ if self._state == "pending":
+ _note_unpending()
+ elif self._state == "started":
+ _note_end()
+ else:
+ return
+ self._state = "finished"
+
+
def _note_untracked_end(is_preview: bool = False) -> None:
# Drop a request that never used the local GGUF without stamping activity, so
# external-provider traffic can't keep the model warm.
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index d3e6028128c..af065b89d82 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -51,6 +51,10 @@ def __getattr__(name: str):
logger = get_logger(__name__)
+class _LoadCancelled(Exception):
+ """Internal control flow for a caller-cancelled model load."""
+
+
_CTX = mp.get_context("spawn")
@@ -628,6 +632,7 @@ class InferenceOrchestrator:
self,
expected_type: str,
timeout: float = 300.0,
+ cancel_event: Optional[threading.Event] = None,
) -> dict:
"""Block until a response of the expected type arrives.
@@ -645,8 +650,11 @@ class InferenceOrchestrator:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
+ if cancel_event is not None and cancel_event.is_set():
+ raise _LoadCancelled()
remaining = max(0.1, deadline - time.monotonic())
- resp = self._read_resp(timeout = min(remaining, 1.0))
+ poll_seconds = 0.1 if cancel_event is not None else 1.0
+ resp = self._read_resp(timeout = min(remaining, poll_seconds))
if resp is None:
# Check subprocess health
@@ -1410,6 +1418,11 @@ class InferenceOrchestrator:
# Parent-detected backend for the worker's apply_gpu_ids().
sub_config["device_backend"] = get_device().value
+ if load_cancel_event is not None and load_cancel_event.is_set():
+ self.loading_models.discard(model_name)
+ logger.info("Load cancelled before worker teardown: %s", model_name)
+ return False
+
# Recheck the sidecar reservation BEFORE tearing the old worker down,
# for REPAIRS only: an install holds this same lifecycle gate, so it
# cannot swap while this load runs, and its queued-load snapshot
@@ -1453,7 +1466,10 @@ class InferenceOrchestrator:
# lands before any child exists (GPU placement, or between retries) there is
# nothing to kill, and without this check the loop would spawn a worker and
# load the model after /unload reported it unloaded. Observe removal and stop.
- if model_name not in self.loading_models:
+ if model_name not in self.loading_models or (
+ load_cancel_event is not None and load_cancel_event.is_set()
+ ):
+ self.loading_models.discard(model_name)
logger.info(
"Load for '%s' was cancelled before spawn; not starting a worker",
model_name,
@@ -1478,7 +1494,10 @@ class InferenceOrchestrator:
# orphaning this fresh worker; the load would then wait for "loaded" and
# publish a model /unload reported unloaded, over a live subprocess nothing
# reaps. Recheck now the child exists and tear it down before publishing.
- if model_name not in self.loading_models:
+ if model_name not in self.loading_models or (
+ load_cancel_event is not None and load_cancel_event.is_set()
+ ):
+ self.loading_models.discard(model_name)
logger.info(
"Load for '%s' was cancelled during spawn; tearing the worker down",
model_name,
@@ -1489,7 +1508,20 @@ class InferenceOrchestrator:
return False
try:
- resp = self._wait_response("loaded")
+ if load_cancel_event is None:
+ resp = self._wait_response("loaded")
+ else:
+ resp = self._wait_response("loaded", cancel_event = load_cancel_event)
+ except _LoadCancelled:
+ logger.info(
+ "Load for '%s' was cancelled while waiting for 'loaded'",
+ model_name,
+ )
+ self.loading_models.discard(model_name)
+ self._shutdown_subprocess(timeout = 5)
+ self.active_model_name = None
+ self.models.clear()
+ return False
except DownloadStallError:
# First stall with Xet on -> retry with Xet disabled
if attempt == 0 and not disable_xet:
@@ -1517,12 +1549,20 @@ class InferenceOrchestrator:
# /unload reported cancelled, over a subprocess cancel_load just killed;
# its post-teardown re-clear cannot undo a publish that lands after it
# returns. Observe the removal and abort; cancel_load owns teardown.
- if model_name not in self.loading_models:
+ if model_name not in self.loading_models or (
+ load_cancel_event is not None and load_cancel_event.is_set()
+ ):
+ cancelled_by_event = (
+ load_cancel_event is not None and load_cancel_event.is_set()
+ )
+ self.loading_models.discard(model_name)
logger.info(
"Load for '%s' was cancelled while waiting for 'loaded'; "
"not publishing the cancelled model",
model_name,
)
+ if cancelled_by_event:
+ self._shutdown_subprocess(timeout = 5)
self.active_model_name = None
self.models.clear()
return False
diff --git a/studio/backend/main.py b/studio/backend/main.py
index eee91679be4..71b188a8e10 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -309,6 +309,7 @@ from routes import (
openai_codex_auth_router,
rag_router,
research_runs_router,
+ chat_generation_runs_router,
training_history_router,
training_router,
video_router,
@@ -669,6 +670,17 @@ async def lifespan(app: FastAPI):
except Exception as exc:
_lifespan_log.warning("cleanup_orphaned_runs failed at startup: %s", exc)
+ try:
+ from storage.chat_generation_runs_db import reconcile_orphaned_runs
+ reconciled_chat_runs = reconcile_orphaned_runs()
+ if reconciled_chat_runs:
+ _lifespan_log.warning(
+ "Marked %s interrupted chat generation run(s) failed after restart.",
+ reconciled_chat_runs,
+ )
+ except Exception as exc:
+ _lifespan_log.warning("chat generation orphan reconciliation failed: %s", exc)
+
reap_hub_orphan_workers()
try:
from hub.utils.download_manifest import migrate_ordinary_v2_manifests_for_downgrade
@@ -703,6 +715,10 @@ async def lifespan(app: FastAPI):
app.state.research_supervisor = ResearchSupervisor(app)
app.state.research_supervisor.start()
+ from core.inference.chat_generation_runs import ChatGenerationSupervisor
+
+ app.state.chat_generation_supervisor = ChatGenerationSupervisor(app)
+
# Idle auto-unload loop (no-op unless the OpenAI auto-unload TTL is set).
from core.inference.llama_keepwarm import idle_unload_loop, sweep_slot_save_dir
@@ -798,6 +814,10 @@ async def lifespan(app: FastAPI):
if _research_supervisor is not None:
await _research_supervisor.stop()
+ _chat_generation_supervisor = getattr(app.state, "chat_generation_supervisor", None)
+ if _chat_generation_supervisor is not None:
+ await _chat_generation_supervisor.stop()
+
from core.inference.llama_http import aclose as _close_llama_http
await _close_llama_http()
@@ -1382,6 +1402,11 @@ app.include_router(training_router, prefix = "/api/train", tags = ["training"])
app.include_router(models_router, prefix = "/api/models", tags = ["models"])
app.include_router(chat_history_router, prefix = "/api/chat", tags = ["chat"])
app.include_router(research_runs_router, prefix = "/api/chat/research-runs", tags = ["research-runs"])
+app.include_router(
+ chat_generation_runs_router,
+ prefix = "/api/inference/chat-runs",
+ tags = ["inference"],
+)
app.include_router(inference_router, prefix = "/api/inference", tags = ["inference"])
# Unsloth-only inference endpoints (cancel, etc.) are not on the /v1 OpenAI-compat prefix.
app.include_router(inference_studio_router, prefix = "/api/inference", tags = ["inference"])
diff --git a/studio/backend/routes/__init__.py b/studio/backend/routes/__init__.py
index c15e5ab7c65..875d1aad62b 100644
--- a/studio/backend/routes/__init__.py
+++ b/studio/backend/routes/__init__.py
@@ -22,6 +22,7 @@ from routes.openai_codex_auth import router as openai_codex_auth_router
from routes.mcp_servers import router as mcp_servers_router
from routes.rag import router as rag_router
from routes.research_runs import router as research_runs_router
+from routes.chat_generation_runs import router as chat_generation_runs_router
from routes.youtube import router as youtube_router
__all__ = [
@@ -41,8 +42,9 @@ __all__ = [
"mcp_servers_router",
"rag_router",
"research_runs_router",
+ "chat_generation_runs_router",
"youtube_router",
]
# Bind the re-export so the import-hoist verifier counts it as used.
-_ = (rag_router, video_router, research_runs_router, youtube_router)
+_ = (rag_router, video_router, research_runs_router, chat_generation_runs_router, youtube_router)
diff --git a/studio/backend/routes/chat_generation_runs.py b/studio/backend/routes/chat_generation_runs.py
new file mode 100644
index 00000000000..c6cbcf9dfcc
--- /dev/null
+++ b/studio/backend/routes/chat_generation_runs.py
@@ -0,0 +1,366 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Authenticated API for resumable, server-owned Studio chat generations."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+import sqlite3
+from concurrent.futures import ThreadPoolExecutor
+from typing import Any
+
+from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request
+from fastapi.responses import StreamingResponse
+from pydantic import BaseModel, ConfigDict, Field, ValidationError
+
+from auth.authentication import get_current_subject
+from core.inference.llama_keepwarm import inference_lifecycle_gate
+from models.inference import ChatCompletionRequest
+from storage import chat_generation_runs_db as db
+from utils.api_errors import safe_validation_errors
+
+router = APIRouter()
+_EVENT_WAIT_EXECUTOR = ThreadPoolExecutor(
+ max_workers = 32,
+ thread_name_prefix = "chat-generation-events",
+)
+_SENSITIVE_KEYS = {
+ "accesskey",
+ "authorization",
+ "encryptionkey",
+ "password",
+ "privatekey",
+ "secret",
+ "secretkey",
+ "signingkey",
+ "sshkey",
+ "token",
+ "apikey",
+ "credential",
+ "credentials",
+ "encryptedapikey",
+}
+_SENSITIVE_SUFFIXES = (
+ "token",
+ "secret",
+ "password",
+ "credential",
+ "credentials",
+)
+_EXTERNAL_ROUTING_FIELDS = {
+ "provider_id",
+ "provider_type",
+ "external_model",
+ "encrypted_api_key",
+ "provider_base_url",
+}
+# Attachments the composer sends inline. Durable replay has no representation for them.
+_MEDIA_FIELDS = {
+ "image_base64",
+ "audio_base64",
+ "video_base64",
+}
+_SQLITE_MAX_INTEGER = 9_223_372_036_854_775_807
+_ENVELOPE_MAX_DEPTH = 64
+_ENVELOPE_MAX_NODES = 20_000
+_ENVELOPE_MAX_JSON_CHARS = 1_000_000
+
+
+class CreateChatGenerationRun(BaseModel):
+ model_config = ConfigDict(extra = "forbid")
+ runId: str = Field(min_length = 1, max_length = 128, pattern = r"^[A-Za-z0-9_-]+$")
+ threadId: str = Field(min_length = 1, max_length = 256)
+ userMessageId: str = Field(min_length = 1, max_length = 256)
+ assistantMessageId: str = Field(min_length = 1, max_length = 256)
+ requestPayload: dict[str, Any]
+
+
+def _normalized_key(key: object) -> str:
+ return re.sub(r"[^a-z0-9]", "", str(key).casefold())
+
+
+def _is_sensitive_key(key: object) -> bool:
+ normalized = _normalized_key(key)
+ return normalized in _SENSITIVE_KEYS or normalized.endswith(_SENSITIVE_SUFFIXES)
+
+
+def _contains_sensitive_json_key_text(value: str) -> bool:
+ for match in re.finditer(r'"((?:\\.|[^"\\])*)"\s*:', value):
+ try:
+ key = json.loads(f'"{match.group(1)}"')
+ except (json.JSONDecodeError, TypeError):
+ key = match.group(1)
+ if _is_sensitive_key(key):
+ return True
+ return False
+
+
+def _contains_sensitive_key(value: object) -> bool:
+ stack: list[tuple[object, int]] = [(value, 0)]
+ nodes = 0
+ decoded_chars = 0
+ while stack:
+ item, depth = stack.pop()
+ nodes += 1
+ if depth > _ENVELOPE_MAX_DEPTH or nodes > _ENVELOPE_MAX_NODES:
+ return True
+ if isinstance(item, dict):
+ for key, nested in item.items():
+ if _is_sensitive_key(key):
+ return True
+ stack.append((nested, depth + 1))
+ elif isinstance(item, (list, tuple)):
+ stack.extend((nested, depth + 1) for nested in item)
+ elif isinstance(item, str):
+ candidate = item.lstrip()
+ if not candidate.startswith(("{", "[", '"')):
+ continue
+ decoded_chars += len(candidate)
+ if decoded_chars > _ENVELOPE_MAX_JSON_CHARS:
+ return True
+ try:
+ decoded = json.loads(candidate)
+ except json.JSONDecodeError:
+ if _contains_sensitive_json_key_text(candidate):
+ return True
+ continue
+ except (MemoryError, RecursionError):
+ return True
+ stack.append((decoded, depth + 1))
+ return False
+
+
+def _sanitize_request(payload: CreateChatGenerationRun) -> dict[str, Any]:
+ raw = dict(payload.requestPayload)
+ unknown = set(raw) - set(ChatCompletionRequest.model_fields)
+ if unknown:
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Unsupported durable request fields: {', '.join(sorted(unknown))}",
+ )
+ try:
+ request = ChatCompletionRequest.model_validate(raw)
+ except ValidationError as exc:
+ raise HTTPException(
+ status_code = 422,
+ detail = safe_validation_errors(exc.errors()),
+ ) from exc
+ # Message content/reasoning are user-authored data, not routing configuration. Scan every
+ # other persisted field, including extra message-envelope fields, with the credential policy.
+ durable_config = {
+ key: value
+ for key, value in raw.items()
+ if key != "messages" and key not in _EXTERNAL_ROUTING_FIELDS and value is not None
+ }
+ message_envelopes = [
+ {
+ key: value
+ for key, value in message.items()
+ if key not in {"content", "reasoning_content"}
+ }
+ for message in raw.get("messages", [])
+ if isinstance(message, dict)
+ ]
+ if _contains_sensitive_key(durable_config) or _contains_sensitive_key(message_envelopes):
+ raise HTTPException(status_code = 400, detail = "Credentials cannot be persisted")
+ if any(raw.get(field) not in (None, "") for field in _EXTERNAL_ROUTING_FIELDS):
+ raise HTTPException(
+ status_code = 400,
+ detail = "Durable chat runs are available only for local inference",
+ )
+ # Recovery rebuilds text and reasoning deltas. A media turn has neither the same
+ # chunk shape nor a replayable transcript, and its payload is persisted verbatim,
+ # so a base64 blob would live in request_json for the life of the thread. Studio's
+ # own composer already keeps these on the legacy stream; keep the server in step so
+ # a stale tab or a direct caller cannot open a path nothing replays.
+ if any(raw.get(field) not in (None, "") for field in _MEDIA_FIELDS):
+ raise HTTPException(
+ status_code = 400,
+ detail = "Media chat runs use the legacy streaming path",
+ )
+ # Recovery currently rebuilds text and reasoning deltas, not server-side tool
+ # events. Keep any request whose effective policy can enter the local tool loop
+ # on the legacy subscriber-owned stream until those events are replayable.
+ from routes.inference import _checkpoint_recall_may_enable_tools, _effective_enable_tools
+
+ request = request.model_copy(update = {"thread_id": payload.threadId})
+
+ if (
+ raw.get("tools")
+ or request.enable_tools is True
+ or bool(request.mcp_enabled)
+ or _effective_enable_tools(request) is True
+ or _checkpoint_recall_may_enable_tools(request)
+ ):
+ raise HTTPException(
+ status_code = 400,
+ detail = "Tool-enabled chat runs use the legacy streaming path",
+ )
+ if (request.n or 1) != 1:
+ raise HTTPException(status_code = 400, detail = "Durable chat runs require n=1")
+ sanitized = request.model_dump(mode = "json", exclude_none = True)
+ for field in _EXTERNAL_ROUTING_FIELDS:
+ sanitized.pop(field, None)
+ sanitized["stream"] = True
+ sanitized["thread_id"] = payload.threadId
+ sanitized["cancel_id"] = payload.runId
+ sanitized["generation_run_id"] = payload.runId
+ return sanitized
+
+
+def _require_run(run_id: str) -> dict[str, Any]:
+ run = db.get_run(run_id)
+ if run is None:
+ raise HTTPException(status_code = 404, detail = "Chat generation run not found")
+ return run
+
+
+def _event_cursor(after: int | None, last_event_id: str | None) -> int:
+ if after is not None and after > _SQLITE_MAX_INTEGER:
+ raise HTTPException(status_code = 400, detail = "Event cursor is too large")
+ header_after = 0
+ if last_event_id:
+ if re.fullmatch(r"[0-9]+", last_event_id, flags = re.ASCII) is None:
+ raise HTTPException(status_code = 400, detail = "Last-Event-ID must be an integer")
+ max_text = str(_SQLITE_MAX_INTEGER)
+ normalized = last_event_id.lstrip("0") or "0"
+ if len(normalized) > len(max_text) or (
+ len(normalized) == len(max_text) and normalized > max_text
+ ):
+ raise HTTPException(status_code = 400, detail = "Event cursor is too large")
+ header_after = int(normalized)
+ return max(after or 0, header_after)
+
+
[email protected]("", status_code = 202)
+async def create_chat_generation_run(
+ payload: CreateChatGenerationRun,
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+):
+ sanitized = _sanitize_request(payload)
+ # Serialize the off-loop commit with model lifecycle work. If create wins,
+ # the run is registered before the gate opens; if unload/swap wins, the run
+ # is admitted afterward. SSE and unrelated requests stay responsive while
+ # SQLite waits on a lock.
+ async with inference_lifecycle_gate():
+ try:
+ run, created = await asyncio.to_thread(
+ db.create_run,
+ run_id = payload.runId,
+ owner_subject = current_subject,
+ thread_id = payload.threadId,
+ user_message_id = payload.userMessageId,
+ assistant_message_id = payload.assistantMessageId,
+ request_payload = sanitized,
+ )
+ except db.ChatGenerationConflictError as exc:
+ raise HTTPException(status_code = 409, detail = str(exc)) from exc
+ except KeyError as exc:
+ raise HTTPException(status_code = 404, detail = "Thread not found") from exc
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
+ except sqlite3.IntegrityError as exc:
+ raise HTTPException(status_code = 409, detail = "Generation run conflicts") from exc
+ supervisor = getattr(request.app.state, "chat_generation_supervisor", None)
+ if supervisor is not None and run["status"] == "queued":
+ supervisor.start(
+ run["id"],
+ thread_id = run["threadId"],
+ model = run["requestPayload"].get("model"),
+ )
+ return {**run, "created": created}
+
+
+def active_chat_generation_runs(
+ thread_id: str = Query(alias = "threadId"), current_subject: str = Depends(get_current_subject)
+):
+ return {"runs": db.list_active(thread_id)}
+
+
[email protected]("/{run_id}")
+def get_chat_generation_run(run_id: str, current_subject: str = Depends(get_current_subject)):
+ return _require_run(run_id)
+
+
[email protected]("/{run_id}/cancel")
+def cancel_chat_generation_run(
+ run_id: str,
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+):
+ _require_run(run_id)
+ run = db.request_cancel(run_id)
+ if run is None:
+ raise HTTPException(status_code = 404, detail = "Chat generation run not found")
+ supervisor = getattr(request.app.state, "chat_generation_supervisor", None)
+ if supervisor is not None and run["status"] in {"cancelling", "cancelled"}:
+ supervisor.cancel(run_id)
+ return run
+
+
[email protected]("/{run_id}/events")
+async def chat_generation_events(
+ run_id: str,
+ request: Request,
+ after: int | None = Query(None, ge = 0, le = _SQLITE_MAX_INTEGER),
+ last_event_id: str | None = Header(None, alias = "Last-Event-ID"),
+ current_subject: str = Depends(get_current_subject),
+):
+ _require_run(run_id)
+ cursor = _event_cursor(after, last_event_id)
+
+ async def stream():
+ nonlocal cursor
+ loop = asyncio.get_running_loop()
+ # A client that reconnects already caught up on a settled run has nothing to replay,
+ # and wait_for_events would hold it for the full timeout: the finished answer reads
+ # as still generating and an event-wait worker is tied up meanwhile. Only the first
+ # wait needs this guard, since every later pass already returns on the same test
+ # against the snapshot it read after waiting.
+ opening = await asyncio.to_thread(db.get_run, run_id)
+ if opening is None:
+ return
+ if opening["status"] in db.TERMINAL_STATUSES and cursor >= int(opening["lastEventSeq"]):
+ return
+ while True:
+ events = await loop.run_in_executor(
+ _EVENT_WAIT_EXECUTOR,
+ db.wait_for_events,
+ run_id,
+ cursor,
+ 15,
+ )
+ snapshot = await asyncio.to_thread(db.get_run, run_id)
+ if snapshot is None:
+ return
+ for event in events:
+ cursor = int(event["seq"])
+ data = {
+ "seq": cursor,
+ "type": event["type"],
+ "payload": event["payload"],
+ "createdAt": event["createdAt"],
+ }
+ if event["type"] != "chunk":
+ data["run"] = snapshot
+ encoded = json.dumps(data, ensure_ascii = False, separators = (",", ":"))
+ yield f"id: {cursor}\nevent: {event['type']}\ndata: {encoded}\n\n"
+ if snapshot["status"] in db.TERMINAL_STATUSES and cursor >= int(
+ snapshot["lastEventSeq"]
+ ):
+ return
+ if await request.is_disconnected():
+ return
+ if not events:
+ yield ": keep-alive\n\n"
+
+ return StreamingResponse(
+ stream(),
+ media_type = "text/event-stream",
+ headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
+ )
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 5b2597495e5..d1c6c13d424 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -45,7 +45,7 @@ from storage.studio_db import (
count_forks_for_message,
delete_chat_attachment,
delete_chat_project,
- delete_chat_threads,
+ delete_chat_threads_with_active_runs,
ensure_chat_project_workspace,
fork_chat_thread,
fork_counts_for_thread,
@@ -353,6 +353,7 @@ class ChatMessageListResponse(BaseModel):
class ChatMessageSyncRequest(BaseModel):
messages: list[ChatMessage]
pruneMissing: bool = False
+ deletedMessageIds: list[str] = Field(default_factory = list)
class ChatDeleteRequest(BaseModel):
@@ -739,6 +740,25 @@ def _cancel_active_generations(thread_ids: list[str]) -> None:
continue
+def _cancel_chat_generation_runs(request: Request, run_ids: list[str]) -> None:
+ """Cancel durable producers whose rows were captured before thread cascade."""
+ if not run_ids:
+ return
+ supervisor = getattr(request.app.state, "chat_generation_supervisor", None)
+ for run_id in run_ids:
+ try:
+ if supervisor is not None:
+ supervisor.cancel(run_id)
+ else:
+ from routes.inference import _cancel_by_cancel_id_or_stash
+ from state import active_generations
+
+ active_generations.cancel_run(run_id)
+ _cancel_by_cancel_id_or_stash(run_id)
+ except Exception: # noqa: BLE001 - deletion must still complete
+ logger.warning("Could not signal chat generation run %s", run_id, exc_info = True)
+
+
@router.delete("/threads")
async def delete_threads(
payload: ChatDeleteRequest,
@@ -749,8 +769,12 @@ async def delete_threads(
# Before the rows go, so a thread id that comes back in the gap is cut here.
cutoff = _archive_cutoff()
- deleted_research_run_ids = await run_in_threadpool(delete_chat_threads, payload.ids)
+ deleted_research_run_ids, deleted_chat_run_ids = await run_in_threadpool(
+ delete_chat_threads_with_active_runs,
+ payload.ids,
+ )
_cancel_research_runs(request, deleted_research_run_ids)
+ _cancel_chat_generation_runs(request, deleted_chat_run_ids)
_cancel_active_generations(payload.ids)
# Keyed by thread id, so nothing can reference the folder once the thread
# is gone. Clean it up rather than leaking one per chat.
@@ -1105,19 +1129,21 @@ async def delete_project(
status_code = 404,
detail = f"Project {project_id} not found",
)
+ # The transaction is authoritative about membership and captured the worker ids before its
+ # cascades. Signal them before any potentially slow RAG or workspace cleanup.
+ member_ids = list(project.get("memberIds") or [])
+ _cancel_research_runs(request, list(project.get("activeResearchRunIds") or []))
+ _cancel_chat_generation_runs(
+ request,
+ list(project.get("activeChatGenerationRunIds") or []),
+ )
+ _cancel_active_generations(member_ids)
# before any workspace work: the row is already gone, so a later failure must not
# leave the scope owned by nothing
try:
await run_in_threadpool(_delete_project_rag_sources, project_id)
except Exception: # noqa: BLE001 - source cleanup must not block project deletion
logger.warning("failed to delete RAG sources for project %s", project_id, exc_info = True)
- # The transaction is the only authority on membership and it runs first, so
- # a chat moved in just before is deleted and one moved out survives. An
- # earlier listing would stop a chat that is still there.
- member_ids = list(project.get("memberIds") or [])
- # By run id: the rows are gone by now, so there is nothing left to look up.
- _cancel_research_runs(request, list(project.get("activeResearchRunIds") or []))
- _cancel_active_generations(member_ids)
# The project's chats go with it, so their archives have to as well.
await run_in_threadpool(_remove_conversation_archives, member_ids, cutoff = cutoff)
if project.get("sandboxPath"):
@@ -1281,6 +1307,7 @@ def save_thread_message(
thread_id: str,
message_id: str,
payload: ChatMessage,
+ allow_generation_edit: Annotated[bool, Query(alias = "allowGenerationEdit")] = False,
current_subject: str = Depends(get_current_subject),
):
if thread_id != payload.threadId or message_id != payload.id:
@@ -1288,7 +1315,9 @@ def save_thread_message(
if get_chat_thread(thread_id) is None:
raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")
try:
- return ChatMessage(**upsert_chat_message(payload.model_dump()))
+ return ChatMessage(
+ **upsert_chat_message(payload.model_dump(), allow_generation_edit = allow_generation_edit)
+ )
except sqlite3.IntegrityError as exc:
if get_chat_thread(thread_id) is None:
raise _missing_thread_error(thread_id) from exc
@@ -1328,6 +1357,7 @@ def replace_thread_messages(
thread_id,
messages,
prune_missing = payload.pruneMissing,
+ deleted_message_ids = payload.deletedMessageIds,
)
]
)
@@ -1386,7 +1416,7 @@ async def clear_history(
else [thread["id"] for thread in await run_in_threadpool(list_chat_threads)]
)
- def _clear_rows() -> tuple[list[str], list[str], bool, Optional[set]]:
+ def _clear_rows() -> tuple[list[str], list[str], list[str], bool, Optional[set]]:
"""The clear, and the image snapshot the reap will be bounded to.
Both in ONE threadpool call, so there is no await between them. Split across two,
@@ -1405,15 +1435,24 @@ async def clear_history(
from core.inference.search_images import snapshot_and_fence_registrations
if payload is None:
- cleared, cleared_runs = clear_chat_history()
- return cleared, cleared_runs, False, snapshot_and_fence_registrations()
+ cleared, cleared_runs, cleared_chat_runs = clear_chat_history(
+ include_chat_generation_runs = True
+ )
+ return (
+ cleared,
+ cleared_runs,
+ cleared_chat_runs,
+ False,
+ snapshot_and_fence_registrations(),
+ )
# Answered by the transaction itself. Read separately beforehand it is a guess:
# a concurrent retry of the same operation id sees the same unrecorded ledger,
# and the one BEGIN IMMEDIATE puts second replays while still believing it
# cleared. `replayed` here is whichever the transaction actually did.
- cleared, cleared_runs, replayed = clear_chat_history_with_replay_status(
+ cleared, cleared_runs, cleared_chat_runs, replayed = clear_chat_history_with_replay_status(
payload.ids,
operation_id = payload.operationId,
+ include_chat_generation_runs = True,
)
if replayed:
# A replay takes no snapshot of its own -- the chats created since the original
@@ -1422,6 +1461,7 @@ async def clear_history(
return (
cleared,
cleared_runs,
+ cleared_chat_runs,
True,
unreaped_clear_operation_image_ids(payload.operationId),
)
@@ -1429,12 +1469,18 @@ async def clear_history(
# Recorded before the reap runs, so a crash in the seconds of cleanup that follow
# leaves a retry able to finish exactly this set and nothing wider.
record_clear_operation_reap_scope(payload.operationId, snapshot)
- return cleared, cleared_runs, False, snapshot
+ return cleared, cleared_runs, cleared_chat_runs, False, snapshot
# The clear reports what it deleted, which is what gets cleaned up: a thread
# added between the listing above and the delete is gone too, and its
# sandbox would otherwise be stranded.
- cleared, cleared_runs, replayed, reapable_image_ids = await run_in_threadpool(_clear_rows)
+ (
+ cleared,
+ cleared_runs,
+ cleared_chat_runs,
+ replayed,
+ reapable_image_ids,
+ ) = await run_in_threadpool(_clear_rows)
# A chat started between the listing and the transaction is in `cleared`
# but was never cancelled, and a generation still running would dispatch a
# tool and rebuild the sandbox this call is about to remove.
@@ -1445,6 +1491,7 @@ async def clear_history(
_cancel_active_generations(late)
# By id: the rows went with the threads, so nothing can look them up now.
_cancel_research_runs(request, cleared_runs)
+ _cancel_chat_generation_runs(request, cleared_chat_runs)
# Same archive cleanup as DELETE /threads. Without it "Clear all chats" leaves every
# conversation searchable in rag.db, and a reused thread id reads the old archive.
await run_in_threadpool(
@@ -1457,7 +1504,7 @@ async def clear_history(
removed, kept = await _remove_sandboxes(list(dict.fromkeys(thread_ids + cleared)), delete_files)
# Search thumbnails are keyed by id, not thread, so this is the one place they
# can be reaped; they reveal what was searched for. Runs for both _clear_rows
- # branches -- each calls clear_chat_history(), which drops every thread -- so this
+ # branches -- each drops every thread -- so this
# is NOT gated on `payload is None`, which the frontend never sends and which
# therefore meant the reap never ran.
#
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 90b2b6e632c..a00c46500cf 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1217,19 +1217,42 @@ def _chat_final_chunk(completion_id, created, model_name, finish_reason) -> str:
)
-def _stats_finish_reason(stats, default: str = "stop") -> str:
+def _stats_finish_reason(
+ stats,
+ default: str = "stop",
+ *,
+ token_budget: int | None = None,
+) -> str:
"""``"length"`` when the backend reports the turn ran out of token budget.
A backend that names its own reason is believed: MLX decides between a stop
token and exhaustion from the last token it sampled, which a count at the cap
- cannot distinguish. The in-process backends instead fill ``truncated``, and a
- backend reporting neither keeps ``default``.
+ cannot distinguish. The in-process backends instead fill ``truncated``. A caller
+ that knows its backend reports ``stop`` at the cap may also supply the effective
+ token budget; every other path keeps ``default``.
"""
if not isinstance(stats, dict):
return default
if stats.get("finish_reason") in ("stop", "length"):
return stats["finish_reason"]
- return "length" if stats.get("truncated") else default
+ if stats.get("truncated"):
+ return "length"
+ usage = stats.get("usage")
+ completion_tokens = usage.get("completion_tokens") if isinstance(usage, dict) else None
+ if (
+ token_budget is not None
+ and isinstance(completion_tokens, int)
+ and not isinstance(completion_tokens, bool)
+ and completion_tokens >= token_budget
+ ):
+ return "length"
+ return default
+
+
+def _safetensors_finish_reason(stats, payload, *, is_mlx: bool, durable_run: bool) -> str:
+ """Normalize MLX's stop-at-cap only for server-owned Studio runs."""
+ token_budget = _effective_openai_max_tokens(payload) if is_mlx and durable_run else None
+ return _stats_finish_reason(stats, token_budget = token_budget)
def _chat_tool_calls_chunk(completion_id, created, model_name, tool_calls) -> str:
@@ -3556,6 +3579,7 @@ class _TrackedCancel:
event: threading.Event,
*keys,
thread_id = None,
+ run_id = None,
model = None,
kind = "chat",
):
@@ -3564,7 +3588,7 @@ class _TrackedCancel:
# kind reaches the swap prompt: embeddings and raw completions have no conversation, so
# naming them chats would offer to stop something the user never started from a thread.
self._active = active_generations.ActiveGeneration(
- event, thread_id = thread_id, model = model, kind = kind
+ event, thread_id = thread_id, run_id = run_id, model = model, kind = kind
)
@classmethod
@@ -3574,6 +3598,7 @@ class _TrackedCancel:
event,
*keys,
thread_id = getattr(payload, "thread_id", None),
+ run_id = getattr(payload, "generation_run_id", None),
model = getattr(payload, "model", None),
)
@@ -4490,6 +4515,20 @@ def _checkpoint_needs_search() -> bool:
return False
+def _checkpoint_recall_may_enable_tools(payload) -> bool:
+ """Whether checkpoint recovery can force the internal recall tool loop."""
+ from state.tool_policy import get_tool_policy
+ return bool(
+ get_tool_policy() is not False
+ and _rolling_context_policy(payload) is not None
+ and _checkpoint_needs_search()
+ and _thread_has_conversation_archive(getattr(payload, "thread_id", None))
+ and _thread_has_checkpoint(
+ getattr(payload, "thread_id", None), getattr(payload, "messages", None)
+ )
+ )
+
+
def _apply_compaction_nudge(
nudge: str,
tools: list[dict],
@@ -6972,6 +7011,16 @@ async def _maybe_auto_switch_model(
preview_swapped_since_entry,
)
+ generation_cancel_event = getattr(
+ getattr(fastapi_request, "state", None),
+ "generation_cancel_event",
+ None,
+ )
+
+ def _raise_if_generation_cancelled() -> None:
+ if generation_cancel_event is not None and generation_cancel_event.is_set():
+ raise HTTPException(status_code = 409, detail = "Generation cancelled")
+
# Passed auth and reached local inference, so count it in the admitted-inference tally
# the preview busy guard uses instead of raw _inflight (no-op for preview scopes).
_swap_scope = getattr(fastapi_request, "scope", None)
@@ -7040,6 +7089,7 @@ async def _maybe_auto_switch_model(
async def _resolve_and_switch() -> None:
from core.inference.openai_auto_download import looks_like_quant, split_model_ref
+ _raise_if_generation_cancelled()
# Off the loop: a cold-cache rebuild walks several model dirs + HF caches.
# With auto-switch off (or an omitted-model reload-only request), skip the
# resolve so only the reload-stash path runs and no name is ever matched.
@@ -7245,12 +7295,18 @@ async def _maybe_auto_switch_model(
_switch_prior_marker = _get_preview_resident()
_switch_loaded_ok = False
try:
+ durable_cancel_kw = (
+ {"load_cancel_event": generation_cancel_event}
+ if generation_cancel_event is not None
+ else {}
+ )
try:
await _load_model_impl(
LoadRequest(**load_kwargs),
fastapi_request,
current_subject,
current_request_counted = True,
+ **durable_cancel_kw,
)
except HTTPException as exc:
# The pre-flight check cannot mirror every loader gpu_ids rule,
@@ -7273,7 +7329,9 @@ async def _maybe_auto_switch_model(
fastapi_request,
current_subject,
current_request_counted = True,
+ **durable_cancel_kw,
)
+ _raise_if_generation_cancelled()
_switch_loaded_ok = True
finally:
if not claim_resident:
@@ -17870,11 +17928,56 @@ def _fill_recommended_sampling_completions(body: dict, model_id) -> None:
body[_COMPLETIONS_SAMPLING_BODY_KEY.get(field, field)] = value
+class _DisconnectPolicyRequest:
+ """Delegate a request while making generation disconnect policy explicit."""
+
+ def __init__(self, request: Request, *, cancel_on_disconnect: bool) -> None:
+ self._request = request
+ self._cancel_on_disconnect = cancel_on_disconnect
+
+ async def is_disconnected(self) -> bool:
+ if not self._cancel_on_disconnect:
+ return False
+ return await self._request.is_disconnected()
+
+ def __getattr__(self, name):
+ return getattr(self._request, name)
+
+
+def _chat_cancel_event(request: Request) -> threading.Event:
+ """Reuse a durable run's event across auto-load and generation registration."""
+ event = getattr(getattr(request, "state", None), "generation_cancel_event", None)
+ return event if event is not None else threading.Event()
+
+
@router.post("/chat/completions")
async def openai_chat_completions(
payload: ChatCompletionRequest,
request: Request,
current_subject: str = Depends(get_current_subject),
+):
+ from auth.authentication import request_admitted_without_credential
+ if (payload.provider_id or payload.provider_type) and request_admitted_without_credential(
+ request
+ ):
+ raise HTTPException(
+ status_code = 403,
+ detail = "External providers can only be used from the Unsloth UI or with an API key.",
+ )
+ return await produce_openai_chat_completions(
+ payload,
+ request,
+ current_subject,
+ cancel_on_disconnect = True,
+ )
+
+
+async def produce_openai_chat_completions(
+ payload: ChatCompletionRequest,
+ request: Request,
+ current_subject: str,
+ *,
+ cancel_on_disconnect: bool,
):
"""
OpenAI-compatible chat completions endpoint.
@@ -17892,6 +17995,11 @@ async def openai_chat_completions(
- GGUF models → llama-server via LlamaCppBackend
- Other models → Unsloth/transformers via InferenceBackend
"""
+ request = _DisconnectPolicyRequest(
+ request,
+ cancel_on_disconnect = cancel_on_disconnect,
+ )
+
# OpenAI's newer "developer" role is equivalent to "system". Normalize it
# before provider routing so external providers (which may not accept the
# "developer" role) get "system" too, matching the local path.
@@ -18296,7 +18404,7 @@ async def openai_chat_completions(
except Exception as e:
api_monitor.fail(monitor_id, _friendly_error(e))
raise
- cancel_event = threading.Event()
+ cancel_event = _chat_cancel_event(request)
completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
created = int(time.time())
@@ -18672,7 +18780,7 @@ async def openai_chat_completions(
"Image provided but current GGUF model does not support vision.",
)
- cancel_event = threading.Event()
+ cancel_event = _chat_cancel_event(request)
completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
# `stream` defaults to False on ChatCompletionRequest (OpenAI spec
# parity). Naive curl / .NET / System.Text.Json clients omitting the
@@ -18762,7 +18870,7 @@ async def openai_chat_completions(
if video_b64:
_inject_video_part(gguf_messages, video_b64)
- cancel_event = threading.Event()
+ cancel_event = _chat_cancel_event(request)
completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
created = int(time.time())
@@ -18828,16 +18936,8 @@ async def openai_chat_completions(
if (
not use_tools
and not _tool_loop_unusable
- and _cli_policy is not False
and llama_backend.supports_tools
- and _rolling_context_policy(payload) is not None
- and _checkpoint_needs_search()
- and _thread_has_conversation_archive(getattr(payload, "thread_id", None))
- # And an epoch actually happened here: a rolling-window thread archives
- # identically, and there the loop would open for a repair that cannot happen.
- and _thread_has_checkpoint(
- getattr(payload, "thread_id", None), getattr(payload, "messages", None)
- )
+ and _checkpoint_recall_may_enable_tools(payload)
):
use_tools = True
@@ -20510,7 +20610,7 @@ async def openai_chat_completions(
reasoning_prefilled = prefilled,
)
- cancel_event = threading.Event()
+ cancel_event = _chat_cancel_event(request)
completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
created = int(time.time())
@@ -21330,7 +21430,16 @@ async def openai_chat_completions(
_finish = (
"tool_calls"
if (healer is not None and not _cancelled and healer.healed)
- else ("stop" if _cancelled else _stats_finish_reason(_stats))
+ else (
+ "stop"
+ if _cancelled
+ else _safetensors_finish_reason(
+ _stats,
+ payload,
+ is_mlx = bool(_sf_model_info.get("is_mlx", False)),
+ durable_run = not cancel_on_disconnect,
+ )
+ )
)
yield _chat_final_chunk(completion_id, created, model_name, _finish)
# Reuse the reason already sent to the client. Outside the stats block
diff --git a/studio/backend/state/active_generations.py b/studio/backend/state/active_generations.py
index d1f2812c590..0c0bb584cc3 100644
--- a/studio/backend/state/active_generations.py
+++ b/studio/backend/state/active_generations.py
@@ -35,28 +35,55 @@ class ActiveGeneration:
Each __enter__ mints its own handle, so overlapping uses never clobber.
"""
- __slots__ = ("thread_id", "cancel_event", "model", "kind", "_handle")
+ __slots__ = (
+ "thread_id",
+ "run_id",
+ "cancel_event",
+ "model",
+ "kind",
+ "_handle",
+ "_borrowed",
+ )
def __init__(
self,
cancel_event: threading.Event,
*,
thread_id: Optional[str] = None,
+ run_id: Optional[str] = None,
model: Optional[str] = None,
kind: str = "chat",
):
self.thread_id = thread_id or None
+ self.run_id = run_id or None
self.cancel_event = cancel_event
self.model = model or None
self.kind = kind
self._handle: Optional[str] = None
+ self._borrowed = False
def __enter__(self) -> "ActiveGeneration":
- self._handle = uuid.uuid4().hex
with _LOCK:
+ # A durable supervisor registers before model loading starts. The
+ # route later enters its normal tracker with that exact event/run;
+ # borrow the outer registration so lifecycle counts stay truthful.
+ if self.run_id:
+ for entry in _ACTIVE.values():
+ if entry["run_id"] != self.run_id or entry["event"] is not self.cancel_event:
+ continue
+ if self.thread_id:
+ entry["thread_id"] = self.thread_id
+ if self.model:
+ entry["model"] = self.model
+ if self.kind:
+ entry["kind"] = self.kind
+ self._borrowed = True
+ return self
+ self._handle = uuid.uuid4().hex
_ACTIVE[self._handle] = {
"handle": self._handle,
"thread_id": self.thread_id,
+ "run_id": self.run_id,
"model": self.model,
"kind": self.kind,
"started_at": time.time(),
@@ -65,6 +92,9 @@ class ActiveGeneration:
return self
def __exit__(self, *exc) -> bool:
+ if self._borrowed:
+ self._borrowed = False
+ return False
handle, self._handle = self._handle, None
if handle is not None:
with _LOCK:
@@ -81,6 +111,7 @@ def snapshot() -> list[dict[str, Any]]:
{
"handle": e["handle"],
"thread_id": e["thread_id"],
+ "run_id": e["run_id"],
"model": e["model"],
"kind": e["kind"],
"started_at": e["started_at"],
@@ -140,6 +171,20 @@ def cancel_thread(thread_id: str) -> int:
return len(events)
+def cancel_run(run_id: str) -> int:
+ """Signal only the generation registered for a durable Studio run."""
+ if not run_id:
+ return 0
+ with _LOCK:
+ events = [e["event"] for e in _ACTIVE.values() if e["run_id"] == run_id]
+ for ev in events:
+ try:
+ ev.set()
+ except Exception:
+ pass
+ return len(events)
+
+
def reset_for_tests() -> None:
"""Drop every entry. Test-only; never called from request paths."""
with _LOCK:
diff --git a/studio/backend/storage/chat_generation_runs_db.py b/studio/backend/storage/chat_generation_runs_db.py
new file mode 100644
index 00000000000..27cb5de0ab4
--- /dev/null
+++ b/studio/backend/storage/chat_generation_runs_db.py
@@ -0,0 +1,648 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Transactional state and cursor events for durable Studio chat generations."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import secrets
+import sqlite3
+import threading
+import time
+from typing import Any, Iterable, Union
+
+from storage.studio_db import get_connection
+
+ACTIVE_STATUSES = frozenset({"queued", "running", "cancelling"})
+TERMINAL_STATUSES = frozenset({"cancelled", "completed", "failed"})
+ALL_STATUSES = ACTIVE_STATUSES | TERMINAL_STATUSES
+_EVENTS_CHANGED = threading.Condition()
+_RUN_TOMBSTONE_PREFIX = "chat-generation-run-tombstone:"
+ChatGenerationEventInput = Union[tuple[str, dict[str, Any]], tuple[str, dict[str, Any], int]]
+
+
+class ChatGenerationConflictError(RuntimeError):
+ pass
+
+
+def now_ms() -> int:
+ return int(time.time() * 1000)
+
+
+def _loads(value: str | None, fallback: Any) -> Any:
+ if value is None:
+ return fallback
+ try:
+ return json.loads(value)
+ except (TypeError, ValueError):
+ return fallback
+
+
+def canonical_request(
+ *,
+ thread_id: str,
+ user_message_id: str,
+ assistant_message_id: str,
+ request_payload: dict[str, Any],
+) -> tuple[str, str]:
+ request_json = json.dumps(
+ request_payload,
+ sort_keys = True,
+ separators = (",", ":"),
+ ensure_ascii = False,
+ )
+ identity = json.dumps(
+ {
+ "threadId": thread_id,
+ "userMessageId": user_message_id,
+ "assistantMessageId": assistant_message_id,
+ "requestPayload": request_payload,
+ },
+ sort_keys = True,
+ separators = (",", ":"),
+ ensure_ascii = False,
+ )
+ return request_json, hashlib.sha256(identity.encode("utf-8")).hexdigest()
+
+
+def _run_from_row(row: sqlite3.Row) -> dict[str, Any]:
+ return {
+ "id": row["id"],
+ "threadId": row["thread_id"],
+ "userMessageId": row["user_message_id"],
+ "assistantMessageId": row["assistant_message_id"],
+ "requestHash": row["request_hash"],
+ "requestPayload": _loads(row["request_json"], {}),
+ "status": row["status"],
+ "cancelRequested": bool(row["cancel_requested"]),
+ "lastEventSeq": int(row["last_event_seq"]),
+ "finishReason": row["finish_reason"],
+ "error": row["error_message"],
+ "createdAt": int(row["created_at"]),
+ "updatedAt": int(row["updated_at"]),
+ "startedAt": row["started_at"],
+ "completedAt": row["completed_at"],
+ }
+
+
+def _append_events_locked(
+ conn: sqlite3.Connection, run_id: str, events: Iterable[ChatGenerationEventInput]
+) -> list[int]:
+ row = conn.execute(
+ "SELECT last_event_seq FROM chat_generation_runs WHERE id=?",
+ (run_id,),
+ ).fetchone()
+ if row is None:
+ raise KeyError(run_id)
+ seq = int(row["last_event_seq"])
+ batch_created = now_ms()
+ sequences: list[int] = []
+ for event in events:
+ event_type, payload = event[:2]
+ created = event[2] if len(event) == 3 else batch_created
+ seq += 1
+ conn.execute(
+ """INSERT INTO chat_generation_events
+ (run_id, seq, event_type, payload_json, created_at)
+ VALUES (?, ?, ?, ?, ?)""",
+ (
+ run_id,
+ seq,
+ event_type,
+ json.dumps(payload, ensure_ascii = False, separators = (",", ":")),
+ created,
+ ),
+ )
+ sequences.append(seq)
+ if sequences:
+ conn.execute(
+ "UPDATE chat_generation_runs SET last_event_seq=?, updated_at=? WHERE id=?",
+ (seq, batch_created, run_id),
+ )
+ return sequences
+
+
+def _commit(conn: sqlite3.Connection, *, notify: bool = False) -> None:
+ conn.commit()
+ if notify:
+ with _EVENTS_CHANGED:
+ _EVENTS_CHANGED.notify_all()
+
+
+def _sync_assistant_status_locked(conn: sqlite3.Connection, run_id: str, status: str) -> None:
+ row = conn.execute(
+ """SELECT r.assistant_message_id, r.finish_reason, m.metadata_json
+ FROM chat_generation_runs r
+ LEFT JOIN chat_messages m ON m.id=r.assistant_message_id
+ WHERE r.id=?""",
+ (run_id,),
+ ).fetchone()
+ if row is None or row["metadata_json"] is None:
+ return
+ metadata = _loads(row["metadata_json"], {})
+ if not isinstance(metadata, dict) or metadata.get("generationRunId") not in (None, run_id):
+ return
+ metadata.update(
+ {
+ "generationRunId": run_id,
+ "generationStatus": status,
+ "serverManaged": True,
+ }
+ )
+ if status == "cancelled":
+ metadata["incomplete"] = {"reason": "cancelled"}
+ elif status == "failed":
+ metadata["incomplete"] = {"reason": "interrupted"}
+ elif status == "completed":
+ if row["finish_reason"] == "length":
+ metadata["incomplete"] = {"reason": "length"}
+ else:
+ metadata.pop("incomplete", None)
+ conn.execute(
+ "UPDATE chat_messages SET metadata_json=? WHERE id=?",
+ (json.dumps(metadata, ensure_ascii = False), row["assistant_message_id"]),
+ )
+
+
+def create_run(
+ *,
+ run_id: str,
+ owner_subject: str,
+ thread_id: str,
+ user_message_id: str,
+ assistant_message_id: str,
+ request_payload: dict[str, Any],
+) -> tuple[dict[str, Any], bool]:
+ request_json, request_hash = canonical_request(
+ thread_id = thread_id,
+ user_message_id = user_message_id,
+ assistant_message_id = assistant_message_id,
+ request_payload = request_payload,
+ )
+ created = now_ms()
+ worker_token = secrets.token_hex(16)
+ conn = get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ existing = conn.execute(
+ "SELECT * FROM chat_generation_runs WHERE id=?",
+ (run_id,),
+ ).fetchone()
+ if existing is not None:
+ if (
+ existing["owner_subject"] != owner_subject
+ or existing["request_hash"] != request_hash
+ ):
+ raise ChatGenerationConflictError("Run ID is already bound to another request")
+ conn.commit()
+ return _run_from_row(existing), False
+ tombstone = conn.execute(
+ "SELECT 1 FROM app_settings WHERE key=?",
+ (f"{_RUN_TOMBSTONE_PREFIX}{run_id}",),
+ ).fetchone()
+ if tombstone is not None:
+ raise ChatGenerationConflictError("Run ID has already been used")
+
+ thread = conn.execute("SELECT 1 FROM chat_threads WHERE id=?", (thread_id,)).fetchone()
+ user_message = conn.execute(
+ "SELECT thread_id, role FROM chat_messages WHERE id=?",
+ (user_message_id,),
+ ).fetchone()
+ if thread is None:
+ raise KeyError("thread")
+ if (
+ user_message is None
+ or user_message["thread_id"] != thread_id
+ or user_message["role"] != "user"
+ ):
+ raise ValueError("userMessageId must identify a user message in the thread")
+ active = conn.execute(
+ """SELECT 1 FROM chat_generation_runs
+ WHERE thread_id=? AND status IN ('queued','running','cancelling')""",
+ (thread_id,),
+ ).fetchone()
+ if active is not None:
+ raise ChatGenerationConflictError("This thread already has an active generation")
+
+ metadata = {
+ "generationRunId": run_id,
+ "generationSeq": 0,
+ "generationStatus": "queued",
+ "serverManaged": True,
+ }
+ assistant = conn.execute(
+ "SELECT * FROM chat_messages WHERE id=?",
+ (assistant_message_id,),
+ ).fetchone()
+ if assistant is None:
+ conn.execute(
+ """INSERT INTO chat_messages
+ (id, thread_id, parent_id, role, content_json, metadata_json, created_at)
+ VALUES (?, ?, ?, 'assistant', '[]', ?, ?)""",
+ (
+ assistant_message_id,
+ thread_id,
+ user_message_id,
+ json.dumps(metadata, ensure_ascii = False),
+ created,
+ ),
+ )
+ else:
+ assistant_metadata = _loads(assistant["metadata_json"], {})
+ existing_run_id = (
+ assistant_metadata.get("generationRunId")
+ if isinstance(assistant_metadata, dict)
+ else None
+ )
+ content = _loads(assistant["content_json"], [])
+ has_content = isinstance(content, list) and any(
+ isinstance(part, dict)
+ and (
+ (part.get("type") == "text" and str(part.get("text") or "").strip())
+ or part.get("type") not in (None, "text")
+ )
+ for part in content
+ )
+ if (
+ assistant["thread_id"] != thread_id
+ or assistant["parent_id"] != user_message_id
+ or assistant["role"] != "assistant"
+ or existing_run_id not in (None, run_id)
+ or (existing_run_id is None and has_content)
+ ):
+ raise ChatGenerationConflictError(
+ "Assistant message does not match this generation run"
+ )
+ merged_metadata = (
+ dict(assistant_metadata) if isinstance(assistant_metadata, dict) else {}
+ )
+ merged_metadata.update(metadata)
+ conn.execute(
+ "UPDATE chat_messages SET metadata_json=? WHERE id=?",
+ (json.dumps(merged_metadata, ensure_ascii = False), assistant_message_id),
+ )
+
+ try:
+ conn.execute(
+ """INSERT INTO chat_generation_runs
+ (id, owner_subject, thread_id, user_message_id, assistant_message_id,
+ request_hash, request_json, worker_token, status, cancel_requested, last_event_seq,
+ created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'queued', 0, 0, ?, ?)""",
+ (
+ run_id,
+ owner_subject,
+ thread_id,
+ user_message_id,
+ assistant_message_id,
+ request_hash,
+ request_json,
+ worker_token,
+ created,
+ created,
+ ),
+ )
+ except sqlite3.IntegrityError as exc:
+ active = conn.execute(
+ """SELECT 1 FROM chat_generation_runs
+ WHERE thread_id=?
+ AND status IN ('queued','running','cancelling')""",
+ (thread_id,),
+ ).fetchone()
+ if active is not None:
+ raise ChatGenerationConflictError(
+ "This thread already has an active generation"
+ ) from exc
+ raise
+ _append_events_locked(conn, run_id, [("run.created", {"status": "queued"})])
+ row = conn.execute("SELECT * FROM chat_generation_runs WHERE id=?", (run_id,)).fetchone()
+ _commit(conn, notify = True)
+ return _run_from_row(row), True
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def get_run(run_id: str, owner_subject: str | None = None) -> dict[str, Any] | None:
+ conn = get_connection()
+ try:
+ if owner_subject is None:
+ row = conn.execute(
+ "SELECT * FROM chat_generation_runs WHERE id=?",
+ (run_id,),
+ ).fetchone()
+ else:
+ row = conn.execute(
+ "SELECT * FROM chat_generation_runs WHERE id=? AND owner_subject=?",
+ (run_id, owner_subject),
+ ).fetchone()
+ return _run_from_row(row) if row is not None else None
+ finally:
+ conn.close()
+
+
+def get_worker_token(run_id: str) -> str | None:
+ conn = get_connection()
+ try:
+ row = conn.execute(
+ "SELECT worker_token FROM chat_generation_runs WHERE id=?",
+ (run_id,),
+ ).fetchone()
+ return str(row["worker_token"]) if row is not None else None
+ finally:
+ conn.close()
+
+
+def get_worker_run(
+ run_id: str, worker_token: str | None = None
+) -> tuple[dict[str, Any], str, str] | None:
+ """Return one fenced producer snapshot and its owner from the same row read."""
+ conn = get_connection()
+ try:
+ if worker_token is None:
+ row = conn.execute(
+ "SELECT * FROM chat_generation_runs WHERE id=?",
+ (run_id,),
+ ).fetchone()
+ else:
+ row = conn.execute(
+ "SELECT * FROM chat_generation_runs WHERE id=? AND worker_token=?",
+ (run_id, worker_token),
+ ).fetchone()
+ if row is None:
+ return None
+ return _run_from_row(row), str(row["owner_subject"]), str(row["worker_token"])
+ finally:
+ conn.close()
+
+
+def list_active(thread_id: str) -> list[dict[str, Any]]:
+ conn = get_connection()
+ try:
+ rows = conn.execute(
+ """SELECT * FROM chat_generation_runs
+ WHERE thread_id=?
+ AND status IN ('queued','running','cancelling')
+ ORDER BY created_at, id""",
+ (thread_id,),
+ ).fetchall()
+ return [_run_from_row(row) for row in rows]
+ finally:
+ conn.close()
+
+
+def append_events(
+ run_id: str, worker_token: str, events: Iterable[ChatGenerationEventInput]
+) -> list[int]:
+ batch = list(events)
+ if not batch:
+ return []
+ conn = get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ row = conn.execute(
+ "SELECT status FROM chat_generation_runs WHERE id=? AND worker_token=?",
+ (run_id, worker_token),
+ ).fetchone()
+ if row is None:
+ raise KeyError(run_id)
+ if row["status"] not in ACTIVE_STATUSES:
+ conn.commit()
+ return []
+ sequences = _append_events_locked(conn, run_id, batch)
+ _commit(conn, notify = True)
+ return sequences
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def mark_running(run_id: str, worker_token: str) -> bool:
+ conn = get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ row = conn.execute(
+ """SELECT status, cancel_requested FROM chat_generation_runs
+ WHERE id=? AND worker_token=?""",
+ (run_id, worker_token),
+ ).fetchone()
+ if row is None:
+ raise KeyError(run_id)
+ if row["status"] == "running":
+ conn.commit()
+ return True
+ if row["status"] != "queued" or bool(row["cancel_requested"]):
+ conn.commit()
+ return False
+ started = now_ms()
+ conn.execute(
+ """UPDATE chat_generation_runs
+ SET status='running', started_at=COALESCE(started_at, ?), updated_at=?
+ WHERE id=?""",
+ (started, started, run_id),
+ )
+ _sync_assistant_status_locked(conn, run_id, "running")
+ _append_events_locked(conn, run_id, [("run.started", {"status": "running"})])
+ _commit(conn, notify = True)
+ return True
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def request_cancel(run_id: str, owner_subject: str | None = None) -> dict[str, Any] | None:
+ conn = get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ sql = "SELECT * FROM chat_generation_runs WHERE id=?"
+ args: tuple[Any, ...] = (run_id,)
+ if owner_subject is not None:
+ sql += " AND owner_subject=?"
+ args += (owner_subject,)
+ row = conn.execute(sql, args).fetchone()
+ if row is None:
+ conn.commit()
+ return None
+ status = row["status"]
+ if status in TERMINAL_STATUSES or status == "cancelling":
+ conn.commit()
+ return _run_from_row(row)
+ updated = now_ms()
+ if status == "queued":
+ conn.execute(
+ """UPDATE chat_generation_runs
+ SET status='cancelled', cancel_requested=1, finish_reason='cancelled',
+ updated_at=?, completed_at=? WHERE id=?""",
+ (updated, updated, run_id),
+ )
+ _append_events_locked(
+ conn,
+ run_id,
+ [("run.cancelled", {"status": "cancelled", "finishReason": "cancelled"})],
+ )
+ _sync_assistant_status_locked(conn, run_id, "cancelled")
+ else:
+ conn.execute(
+ """UPDATE chat_generation_runs
+ SET status='cancelling', cancel_requested=1, updated_at=? WHERE id=?""",
+ (updated, run_id),
+ )
+ _append_events_locked(conn, run_id, [("run.cancelling", {"status": "cancelling"})])
+ _sync_assistant_status_locked(conn, run_id, "cancelling")
+ updated_row = conn.execute(
+ "SELECT * FROM chat_generation_runs WHERE id=?",
+ (run_id,),
+ ).fetchone()
+ _commit(conn, notify = True)
+ return _run_from_row(updated_row)
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def finish_run(
+ run_id: str,
+ *,
+ worker_token: str,
+ status: str,
+ finish_reason: str | None = None,
+ error: str | None = None,
+ pending_events: Iterable[ChatGenerationEventInput] = (),
+) -> dict[str, Any] | None:
+ if status not in TERMINAL_STATUSES:
+ raise ValueError(f"Invalid terminal status: {status}")
+ conn = get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ row = conn.execute(
+ "SELECT * FROM chat_generation_runs WHERE id=? AND worker_token=?",
+ (run_id, worker_token),
+ ).fetchone()
+ if row is None:
+ conn.commit()
+ return None
+ if row["status"] in TERMINAL_STATUSES:
+ conn.commit()
+ return _run_from_row(row)
+ if bool(row["cancel_requested"]):
+ status = "cancelled"
+ finish_reason = "cancelled"
+ error = None
+ _append_events_locked(conn, run_id, list(pending_events))
+ terminal_payload: dict[str, Any] = {
+ "status": status,
+ "finishReason": finish_reason,
+ }
+ if error:
+ terminal_payload["error"] = error
+ _append_events_locked(conn, run_id, [(f"run.{status}", terminal_payload)])
+ completed = now_ms()
+ conn.execute(
+ """UPDATE chat_generation_runs
+ SET status=?, finish_reason=?, error_message=?, updated_at=?, completed_at=?
+ WHERE id=?""",
+ (status, finish_reason, error, completed, completed, run_id),
+ )
+ _sync_assistant_status_locked(conn, run_id, status)
+ updated = conn.execute(
+ "SELECT * FROM chat_generation_runs WHERE id=?",
+ (run_id,),
+ ).fetchone()
+ _commit(conn, notify = True)
+ return _run_from_row(updated)
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def list_events(
+ run_id: str,
+ after: int = 0,
+ limit: int = 1000,
+) -> list[dict[str, Any]]:
+ conn = get_connection()
+ try:
+ rows = conn.execute(
+ """SELECT seq, event_type, payload_json, created_at
+ FROM chat_generation_events
+ WHERE run_id=? AND seq>? ORDER BY seq LIMIT ?""",
+ (run_id, after, limit),
+ ).fetchall()
+ return [
+ {
+ "seq": int(row["seq"]),
+ "type": row["event_type"],
+ "payload": _loads(row["payload_json"], {}),
+ "createdAt": int(row["created_at"]),
+ }
+ for row in rows
+ ]
+ finally:
+ conn.close()
+
+
+def wait_for_events(
+ run_id: str,
+ after: int = 0,
+ timeout: float = 15,
+) -> list[dict[str, Any]]:
+ events = list_events(run_id, after)
+ if events:
+ return events
+ with _EVENTS_CHANGED:
+ events = list_events(run_id, after)
+ if events:
+ return events
+ _EVENTS_CHANGED.wait(timeout)
+ return list_events(run_id, after)
+
+
+def reconcile_orphaned_runs(error: str = "Studio restarted during generation") -> int:
+ conn = get_connection()
+ changed = 0
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ rows = conn.execute(
+ """SELECT id, status, cancel_requested FROM chat_generation_runs
+ WHERE status IN ('queued','running','cancelling') ORDER BY created_at, id"""
+ ).fetchall()
+ completed = now_ms()
+ for row in rows:
+ run_id = row["id"]
+ # A Stop that was already recorded outlives the restart. Reporting it as a
+ # backend failure would tell the user Studio broke when they stopped it, and
+ # finish_run settles this same case as cancelled.
+ if str(row["status"]) == "cancelling" or bool(row["cancel_requested"]):
+ status, finish_reason, message = "cancelled", "cancelled", None
+ terminal = ("run.cancelled", {"status": status, "finishReason": finish_reason})
+ else:
+ status, finish_reason, message = "failed", "interrupted", error
+ terminal = ("run.failed", {"status": status, "error": error, "interrupted": True})
+ _append_events_locked(conn, run_id, [terminal])
+ conn.execute(
+ """UPDATE chat_generation_runs
+ SET status=?, finish_reason=?, error_message=?,
+ updated_at=?, completed_at=? WHERE id=?""",
+ (status, finish_reason, message, completed, completed, run_id),
+ )
+ _sync_assistant_status_locked(conn, run_id, status)
+ changed += 1
+ _commit(conn, notify = bool(changed))
+ return changed
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index ca2acbd7f56..c5abd62c339 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -878,6 +878,106 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
"CREATE INDEX IF NOT EXISTS idx_research_document_sources_run "
"ON research_document_sources(run_id, id)"
)
+ conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS chat_generation_runs (
+ id TEXT NOT NULL PRIMARY KEY,
+ owner_subject TEXT NOT NULL,
+ thread_id TEXT NOT NULL REFERENCES chat_threads(id) ON DELETE CASCADE,
+ user_message_id TEXT NOT NULL REFERENCES chat_messages(id) ON DELETE CASCADE,
+ assistant_message_id TEXT NOT NULL REFERENCES chat_messages(id) ON DELETE CASCADE,
+ request_hash TEXT NOT NULL,
+ request_json TEXT NOT NULL,
+ worker_token TEXT NOT NULL,
+ status TEXT NOT NULL CHECK(status IN (
+ 'queued', 'running', 'cancelling', 'cancelled', 'completed', 'failed'
+ )),
+ cancel_requested INTEGER NOT NULL DEFAULT 0,
+ last_event_seq INTEGER NOT NULL DEFAULT 0,
+ finish_reason TEXT,
+ error_message TEXT,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ started_at INTEGER,
+ completed_at INTEGER
+ )
+ """
+ )
+ chat_generation_run_cols = {
+ row[1] for row in conn.execute("PRAGMA table_info(chat_generation_runs)").fetchall()
+ }
+ if "worker_token" not in chat_generation_run_cols:
+ conn.execute("ALTER TABLE chat_generation_runs ADD COLUMN worker_token TEXT")
+ conn.execute(
+ """UPDATE chat_generation_runs SET worker_token=lower(hex(randomblob(16)))
+ WHERE worker_token IS NULL"""
+ )
+ conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS chat_generation_events (
+ run_id TEXT NOT NULL REFERENCES chat_generation_runs(id) ON DELETE CASCADE,
+ seq INTEGER NOT NULL,
+ event_type TEXT NOT NULL,
+ payload_json TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ PRIMARY KEY(run_id, seq)
+ ) WITHOUT ROWID
+ """
+ )
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_chat_generation_runs_owner_thread_status "
+ "ON chat_generation_runs(owner_subject, thread_id, status)"
+ )
+ conn.execute("DROP INDEX IF EXISTS idx_chat_generation_runs_one_active_thread")
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_chat_generation_runs_thread_status "
+ "ON chat_generation_runs(thread_id, status)"
+ )
+ conn.execute(
+ """
+ CREATE TRIGGER IF NOT EXISTS reject_second_active_chat_generation_insert
+ BEFORE INSERT ON chat_generation_runs
+ WHEN NEW.status IN ('queued','running','cancelling')
+ AND EXISTS (
+ SELECT 1 FROM chat_generation_runs
+ WHERE thread_id = NEW.thread_id
+ AND status IN ('queued','running','cancelling')
+ )
+ BEGIN
+ SELECT RAISE(ABORT, 'thread already has an active chat generation');
+ END
+ """
+ )
+ conn.execute(
+ """
+ CREATE TRIGGER IF NOT EXISTS reject_second_active_chat_generation_update
+ BEFORE UPDATE OF thread_id, status ON chat_generation_runs
+ WHEN NEW.status IN ('queued','running','cancelling')
+ AND EXISTS (
+ SELECT 1 FROM chat_generation_runs
+ WHERE thread_id = NEW.thread_id
+ AND id != NEW.id
+ AND status IN ('queued','running','cancelling')
+ )
+ BEGIN
+ SELECT RAISE(ABORT, 'thread already has an active chat generation');
+ END
+ """
+ )
+ conn.execute(
+ """
+ CREATE TRIGGER IF NOT EXISTS tombstone_chat_generation_run_id
+ BEFORE DELETE ON chat_generation_runs
+ BEGIN
+ INSERT OR REPLACE INTO app_settings (key, value_json, updated_at)
+ VALUES (
+ 'chat-generation-run-tombstone:' || OLD.id,
+ 'true',
+ CAST(strftime('%s', 'now') AS INTEGER) * 1000
+ );
+ END
+ """
+ )
inventory_state = conn.execute(
"""
SELECT inventory_version, dirty
@@ -2182,15 +2282,41 @@ def _active_research_run_ids(
return [row["id"] for row in sorted(rows, key = lambda row: (row["created_at"], row["id"]))]
-def delete_chat_threads_with_active_research_runs(ids: list[str]) -> list[str]:
+def _active_chat_generation_run_ids(
+ conn: sqlite3.Connection, thread_ids: set[str] | None = None
+) -> list[str]:
+ if thread_ids is None:
+ rows = conn.execute(
+ """SELECT id, created_at FROM chat_generation_runs
+ WHERE status IN ('queued','running','cancelling')"""
+ ).fetchall()
+ else:
+ rows = []
+ sorted_thread_ids = sorted(thread_ids)
+ for start in range(0, len(sorted_thread_ids), _SQLITE_IN_CHUNK_SIZE):
+ chunk = sorted_thread_ids[start : start + _SQLITE_IN_CHUNK_SIZE]
+ placeholders = ",".join("?" for _ in chunk)
+ rows.extend(
+ conn.execute(
+ f"""SELECT id, created_at FROM chat_generation_runs
+ WHERE status IN ('queued','running','cancelling')
+ AND thread_id IN ({placeholders})""",
+ chunk,
+ ).fetchall()
+ )
+ return [row["id"] for row in sorted(rows, key = lambda row: (row["created_at"], row["id"]))]
+
+
+def delete_chat_threads_with_active_runs(ids: list[str]) -> tuple[list[str], list[str]]:
if not ids:
- return []
+ return [], []
conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)
try:
conn.execute("BEGIN IMMEDIATE")
_ensure_chat_attachment_inventory_current(conn)
thread_ids = set(ids)
active_research_run_ids = _active_research_run_ids(conn, thread_ids)
+ active_chat_run_ids = _active_chat_generation_run_ids(conn, thread_ids)
_reparent_surviving_forks(conn, thread_ids)
# Record the delete even when no row exists yet. A late POST carrying the same unique id
# must not recreate a thread after this request has confirmed deletion.
@@ -2202,7 +2328,7 @@ def delete_chat_threads_with_active_research_runs(ids: list[str]) -> list[str]:
conn.executemany("DELETE FROM chat_threads WHERE id = ?", [(id,) for id in ids])
_mark_chat_attachment_inventory_clean(conn)
conn.commit()
- return active_research_run_ids
+ return active_research_run_ids, active_chat_run_ids
except Exception:
conn.rollback()
raise
@@ -2210,6 +2336,11 @@ def delete_chat_threads_with_active_research_runs(ids: list[str]) -> list[str]:
conn.close()
+def delete_chat_threads_with_active_research_runs(ids: list[str]) -> list[str]:
+ research_run_ids, _chat_run_ids = delete_chat_threads_with_active_runs(ids)
+ return research_run_ids
+
+
def delete_chat_threads(ids: list[str]) -> list[str]:
"""Delete threads and return the active research runs removed with them."""
return delete_chat_threads_with_active_research_runs(ids)
@@ -2309,22 +2440,33 @@ def clear_chat_history_with_active_research_runs(
def clear_chat_history(
- additional_thread_ids: Iterable[str] = (), operation_id: Optional[str] = None
-) -> "tuple[list[str], list[str]]":
+ additional_thread_ids: Iterable[str] = (),
+ operation_id: Optional[str] = None,
+ include_chat_generation_runs: bool = False,
+) -> "tuple[list[str], list[str]] | tuple[list[str], list[str], list[str]]":
"""Delete every chat thread. Returns (thread ids removed, research runs cascaded)."""
- removed, active_runs, _replayed = clear_chat_history_with_replay_status(
+
+ result = clear_chat_history_with_replay_status(
additional_thread_ids,
operation_id = operation_id,
+ include_chat_generation_runs = include_chat_generation_runs,
)
+ if include_chat_generation_runs:
+ removed, active_runs, active_chat_runs, _replayed = result
+ return removed, active_runs, active_chat_runs
+ removed, active_runs, _replayed = result
return removed, active_runs
def clear_chat_history_with_replay_status(
- additional_thread_ids: Iterable[str] = (), operation_id: Optional[str] = None
-) -> "tuple[list[str], list[str], bool]":
+ additional_thread_ids: Iterable[str] = (),
+ operation_id: Optional[str] = None,
+ include_chat_generation_runs: bool = False,
+) -> "tuple[list[str], list[str], bool] | tuple[list[str], list[str], list[str], bool]":
"""`clear_chat_history`, plus whether this call replayed a recorded outcome.
- Returns (thread ids removed, research runs cascaded, replayed).
+ Returns (thread ids removed, research runs cascaded, replayed), optionally
+ including active chat generation run ids before the replay flag.
The first two are taken inside the same transaction: another process can add a
thread between a listing and this call, its sandbox has to be cleaned up too, and
@@ -2356,7 +2498,8 @@ def clear_chat_history_with_replay_status(
conn.commit()
# The original request already signalled its workers. Replaying that signal can
# leave a cancellation event behind after the worker has exited.
- return list(json.loads(completed["deleted_thread_ids_json"])), [], True
+ replay = (list(json.loads(completed["deleted_thread_ids_json"])), [])
+ return (*replay, [], True) if include_chat_generation_runs else (*replay, True)
_ensure_chat_attachment_inventory_current(conn)
removed = sorted(str(row[0]) for row in conn.execute("SELECT id FROM chat_threads"))
status_placeholders = ",".join("?" for _ in _ACTIVE_RESEARCH_RUN_STATUSES)
@@ -2368,6 +2511,7 @@ def clear_chat_history_with_replay_status(
_ACTIVE_RESEARCH_RUN_STATUSES,
)
]
+ active_chat_runs = _active_chat_generation_run_ids(conn)
# Fence pending frontend writes and legacy-only ids in the same transaction as the clear.
_tombstone_chat_threads(conn, sorted(set(additional_thread_ids) | set(removed)))
conn.execute("DELETE FROM chat_attachment_tombstones")
@@ -2388,6 +2532,8 @@ def clear_chat_history_with_replay_status(
),
)
conn.commit()
+ if include_chat_generation_runs:
+ return removed, active_runs, active_chat_runs, False
return removed, active_runs, False
except Exception:
conn.rollback()
@@ -2556,6 +2702,7 @@ def delete_chat_project(id: str, delete_files: bool = False) -> Optional[dict]:
if thread_ids
else []
)
+ active_chat_runs = _active_chat_generation_run_ids(conn, thread_ids)
_reparent_surviving_forks(conn, thread_ids)
# Fence the exact membership selected by this transaction so a late writer cannot
# recreate a project member after the project and its workspace are gone.
@@ -2571,6 +2718,7 @@ def delete_chat_project(id: str, delete_files: bool = False) -> Optional[dict]:
project = dict(project)
project["memberIds"] = sorted(thread_ids)
project["activeResearchRunIds"] = active_runs
+ project["activeChatGenerationRunIds"] = active_chat_runs
return project
except Exception:
conn.rollback()
@@ -2713,6 +2861,65 @@ def _research_message_ids(conn: sqlite3.Connection, thread_id: str) -> set[str]:
}
+def _generation_message_ids(conn: sqlite3.Connection, thread_id: str) -> set[str]:
+ return {
+ str(message_id)
+ for row in conn.execute(
+ """SELECT user_message_id, assistant_message_id
+ FROM chat_generation_runs WHERE thread_id = ?""",
+ (thread_id,),
+ ).fetchall()
+ for message_id in row
+ if message_id is not None
+ }
+
+
+def _terminal_generation_message_ids(conn: sqlite3.Connection, thread_id: str) -> set[str]:
+ terminal = {
+ str(message_id)
+ for row in conn.execute(
+ """SELECT user_message_id, assistant_message_id
+ FROM chat_generation_runs
+ WHERE thread_id = ? AND status IN ('cancelled', 'completed', 'failed')""",
+ (thread_id,),
+ ).fetchall()
+ for message_id in row
+ if message_id is not None
+ }
+ active = {
+ str(message_id)
+ for row in conn.execute(
+ """SELECT user_message_id, assistant_message_id
+ FROM chat_generation_runs
+ WHERE thread_id = ? AND status IN ('queued', 'running', 'cancelling')""",
+ (thread_id,),
+ ).fetchall()
+ for message_id in row
+ if message_id is not None
+ }
+ return terminal - active
+
+
+def _references_tombstoned_generation(conn: sqlite3.Connection, message: dict) -> bool:
+ metadata = message.get("metadata")
+ if not isinstance(metadata, dict) or metadata.get("serverManaged") is not True:
+ return False
+ run_id = metadata.get("generationRunId")
+ if not isinstance(run_id, str) or not run_id:
+ return False
+ return (
+ conn.execute(
+ "SELECT 1 FROM app_settings WHERE key=?",
+ (f"chat-generation-run-tombstone:{run_id}",),
+ ).fetchone()
+ is not None
+ )
+
+
+def _server_managed_message_ids(conn: sqlite3.Connection, thread_id: str) -> set[str]:
+ return _research_message_ids(conn, thread_id) | _generation_message_ids(conn, thread_id)
+
+
def _surviving_parent_id(
conn: sqlite3.Connection, thread_id: str, message_id: str, pruned: set
) -> "str | None":
@@ -2786,22 +2993,169 @@ def _research_message_would_change(
)
-def _guard_research_messages(
+_GENERATION_ACTIVE_STATUSES = {"queued", "running", "cancelling"}
+_GENERATION_TERMINAL_STATUSES = {"cancelled", "completed", "failed"}
+_GENERATION_STATUS_RANK = {"queued": 0, "running": 1, "cancelling": 2}
+
+
+def _safe_generation_assistant_update(
+ conn: sqlite3.Connection, thread_id: str, message: dict
+) -> bool:
+ """Allow only monotonic writes to the assistant row owned by one run."""
+ row = conn.execute(
+ """SELECT r.id AS run_id, r.status AS run_status, r.last_event_seq,
+ m.parent_id, m.role, m.content_json, m.metadata_json,
+ m.attachments_json, m.created_at
+ FROM chat_generation_runs r
+ JOIN chat_messages m ON m.id = r.assistant_message_id
+ WHERE r.thread_id = ? AND r.assistant_message_id = ?""",
+ (thread_id, str(message["id"])),
+ ).fetchone()
+ if row is None or str(message.get("role")) != "assistant":
+ return False
+ if (message.get("parentId") or None) != (row["parent_id"] or None):
+ return False
+ if int(message.get("createdAt", row["created_at"])) != int(row["created_at"]):
+ return False
+
+ stored_attachments = json.loads(row["attachments_json"]) if row["attachments_json"] else None
+ if json.dumps(message.get("attachments"), sort_keys = True) != json.dumps(
+ stored_attachments, sort_keys = True
+ ):
+ return False
+
+ incoming = message.get("metadata")
+ stored = json.loads(row["metadata_json"]) if row["metadata_json"] else {}
+ if not isinstance(incoming, dict) or not isinstance(stored, dict):
+ return False
+ if incoming.get("serverManaged") is not True:
+ return False
+ if incoming.get("generationRunId") != row["run_id"]:
+ return False
+
+ incoming_seq = incoming.get("generationSeq")
+ stored_seq = stored.get("generationSeq", 0)
+ if (
+ isinstance(incoming_seq, bool)
+ or not isinstance(incoming_seq, int)
+ or isinstance(stored_seq, bool)
+ or not isinstance(stored_seq, int)
+ or incoming_seq < stored_seq
+ or incoming_seq > int(row["last_event_seq"])
+ ):
+ return False
+ if incoming_seq == stored_seq and json.dumps(
+ message.get("content", []), sort_keys = True
+ ) != json.dumps(json.loads(row["content_json"] or "[]"), sort_keys = True):
+ return False
+
+ # A settled terminal row is immutable. Repeated repository syncs may send
+ # the exact row again, but an old tab must not erase authoritative finish
+ # metadata or replace it with an earlier view at the same cursor.
+ if stored.get("generationSettled") is True:
+ return incoming == stored
+
+ incoming_status = incoming.get("generationStatus")
+ stored_status = stored.get("generationStatus")
+ run_status = str(row["run_status"])
+ if incoming_status not in _GENERATION_ACTIVE_STATUSES | _GENERATION_TERMINAL_STATUSES:
+ return False
+ if run_status in _GENERATION_TERMINAL_STATUSES and incoming_status != run_status:
+ return False
+ if run_status in _GENERATION_TERMINAL_STATUSES:
+ # Terminal settlement may add client timing/details, but it must retain
+ # every field already persisted by the producer (especially incomplete).
+ for key in stored:
+ if key not in incoming:
+ return False
+ if incoming.get("incomplete") != stored.get("incomplete"):
+ return False
+ if (
+ run_status in _GENERATION_ACTIVE_STATUSES
+ and incoming_status in _GENERATION_TERMINAL_STATUSES
+ ):
+ return False
+ if (
+ incoming.get("generationSettled") is True
+ and run_status not in _GENERATION_TERMINAL_STATUSES
+ ):
+ return False
+ if incoming.get("generationSettled") is True and incoming_seq != int(row["last_event_seq"]):
+ return False
+ if stored_status in _GENERATION_TERMINAL_STATUSES and incoming_status != stored_status:
+ return False
+ if stored.get("generationSettled") is True and incoming.get("generationSettled") is not True:
+ return False
+ if (
+ stored_status in _GENERATION_ACTIVE_STATUSES
+ and incoming_status in _GENERATION_ACTIVE_STATUSES
+ and _GENERATION_STATUS_RANK[incoming_status] < _GENERATION_STATUS_RANK[stored_status]
+ ):
+ return False
+ return True
+
+
+def _guard_server_managed_messages(
conn: sqlite3.Connection,
thread_id: str,
messages: list[dict],
pruned: set = frozenset(),
+ *,
+ allow_research_update: bool = False,
) -> None:
- protected = _research_message_ids(conn, thread_id)
+ generation = _generation_message_ids(conn, thread_id)
+ protected = set(generation)
+ if not allow_research_update:
+ protected.update(_research_message_ids(conn, thread_id))
if not protected:
return
for message in messages:
- if str(message["id"]) in protected and _research_message_would_change(
- conn, thread_id, message, pruned
+ message_id = str(message["id"])
+ if (
+ message_id in generation
+ and not _safe_generation_assistant_update(conn, thread_id, message)
+ ) or (
+ message_id in protected
+ and message_id not in generation
+ and _research_message_would_change(conn, thread_id, message, pruned)
):
- raise ChatMessageProtectedError(
- "Research prompts and responses are server-managed and cannot be edited"
- )
+ raise ChatMessageProtectedError("server-managed generation messages cannot be edited")
+
+
+def _detach_terminal_generation_for_edit(
+ conn: sqlite3.Connection, thread_id: str, message: dict
+) -> bool:
+ row = conn.execute(
+ """SELECT r.id AS run_id, r.status AS run_status,
+ m.parent_id, m.role, m.metadata_json, m.attachments_json, m.created_at
+ FROM chat_generation_runs r
+ JOIN chat_messages m ON m.id = r.assistant_message_id
+ WHERE r.thread_id = ? AND r.assistant_message_id = ?""",
+ (thread_id, str(message["id"])),
+ ).fetchone()
+ if row is None or str(row["run_status"]) not in _GENERATION_TERMINAL_STATUSES:
+ return False
+ stored_metadata = json.loads(row["metadata_json"]) if row["metadata_json"] else {}
+ incoming_metadata = message.get("metadata")
+ if (
+ not isinstance(stored_metadata, dict)
+ or stored_metadata.get("serverManaged") is not True
+ or stored_metadata.get("generationRunId") != row["run_id"]
+ or stored_metadata.get("generationSettled") is not True
+ or isinstance(incoming_metadata, dict)
+ and incoming_metadata.get("serverManaged") is True
+ or str(message.get("role")) != str(row["role"])
+ or (message.get("parentId") or None) != (row["parent_id"] or None)
+ or int(message.get("createdAt", row["created_at"])) != int(row["created_at"])
+ ):
+ return False
+ stored_attachments = json.loads(row["attachments_json"]) if row["attachments_json"] else None
+ if json.dumps(message.get("attachments"), sort_keys = True) != json.dumps(
+ stored_attachments, sort_keys = True
+ ):
+ return False
+ conn.execute("DELETE FROM chat_generation_runs WHERE id = ?", (row["run_id"],))
+ return True
_CONTENT_PART_ID_PREFIX = "content-part-sha256-"
@@ -3079,6 +3433,7 @@ def upsert_chat_message(
message: dict,
*,
allow_research_update: bool = False,
+ allow_generation_edit: bool = False,
expected_research_run_id: str | None = None,
expected_research_attempt: int | None = None,
) -> dict | None:
@@ -3103,8 +3458,18 @@ def upsert_chat_message(
conn.rollback()
return None
_ensure_chat_attachment_inventory_current(conn)
- if not allow_research_update:
- _guard_research_messages(conn, message["threadId"], [message])
+ if _references_tombstoned_generation(conn, message):
+ raise ChatMessageProtectedError(
+ "deleted server-managed generation messages cannot be restored"
+ )
+ if allow_generation_edit:
+ _detach_terminal_generation_for_edit(conn, message["threadId"], message)
+ _guard_server_managed_messages(
+ conn,
+ message["threadId"],
+ [message],
+ allow_research_update = allow_research_update,
+ )
_raise_if_chat_message_thread_conflicts(
conn,
message["threadId"],
@@ -3179,23 +3544,46 @@ def sync_chat_messages(
prune_missing: bool = False,
*,
allow_research_update: bool = False,
+ deleted_message_ids: Iterable[str] = (),
) -> list[dict]:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
_ensure_chat_attachment_inventory_current(conn)
- # Research messages are server-managed: keep the server record rather than reject the
+ # Dropping a stale tab's view of a tombstoned run is a content decision, not a delete
+ # one. Once an edit detaches an assistant, the run row is gone, so the id no longer
+ # counts as generation-linked and nothing else would hold it back from the prune below.
+ tombstoned_ids = {
+ str(message["id"])
+ for message in messages
+ if _references_tombstoned_generation(conn, message)
+ }
+ messages = [message for message in messages if str(message["id"]) not in tombstoned_ids]
+ # Generation-linked messages are server-managed: keep the record rather than reject the
# batch on client drift. No _guard_research_messages call here as a result -- these ids
# never reach it. upsert_chat_message still guards, so the single-message route keeps
# rejecting edits.
research_ids = _research_message_ids(conn, thread_id)
+ generation_ids = _generation_message_ids(conn, thread_id)
+ managed_ids = research_ids | generation_ids
+ requested_ids = {str(m["id"]) for m in messages}
+ # Snapshot pruning is not delete intent: terminal generation messages may be absent from
+ # a stale client snapshot and must survive unless the delete flow names them explicitly.
+ explicitly_deleted_ids = {str(message_id) for message_id in deleted_message_ids}
+ explicitly_deleted_terminal_ids = explicitly_deleted_ids & _terminal_generation_message_ids(
+ conn, thread_id
+ )
+ prune_protected_ids = (
+ research_ids
+ | (generation_ids - explicitly_deleted_terminal_ids)
+ | (tombstoned_ids - explicitly_deleted_ids)
+ )
# The rows this sync will delete, computed before the upsert so a relink forced by
# that deletion can be told apart from an edit. Research ids are subtracted because
# the delete below exempts them: counting one as pruned would walk the reseat past a
# parent that actually survives, detaching a research turn from its own prompt.
pruned: set = set()
if prune_missing:
- retained = {str(m["id"]) for m in messages}
pruned = (
{
str(row["id"])
@@ -3204,20 +3592,28 @@ def sync_chat_messages(
(thread_id,),
).fetchall()
}
- - retained
- - research_ids
+ - requested_ids
+ - prune_protected_ids
+ )
+ protected = generation_ids if allow_research_update else managed_ids
+ messages = [
+ m
+ for m in messages
+ if str(m["id"]) not in protected
+ or (
+ str(m["id"]) in generation_ids
+ and _safe_generation_assistant_update(conn, thread_id, m)
)
- protected = set() if allow_research_update else research_ids
- messages = [m for m in messages if str(m["id"]) not in protected]
+ ]
# Content is dropped, structure is not: the prune below can delete a research
# message's parent, and a dangling parent makes the whole thread unimportable. The
# replacement is walked from the stored chain, never taken from the client.
#
- # Candidates come from research_ids rather than `protected` because the delete exempts
+ # Candidates come from managed_ids rather than `protected` because the delete exempts
# research rows whatever allow_research_update says, so a narrower set would leave one
# dangling. Ids the batch itself writes are excluded: an authorized caller reparenting
# a research row must not have that overwritten by the repair.
- reseat_candidates = research_ids - {str(m["id"]) for m in messages}
+ reseat_candidates = managed_ids - {str(m["id"]) for m in messages}
reseat_parents = {
message_id: _surviving_parent_id(conn, thread_id, message_id, pruned)
for message_id, stored_parent in _parents_of(conn, thread_id, reseat_candidates).items()
@@ -3280,7 +3676,6 @@ def sync_chat_messages(
content_json,
)
if prune_missing:
- retained_ids = {m["id"] for m in reconciled_messages}
existing_ids = {
row["id"]
for row in conn.execute(
@@ -3290,7 +3685,7 @@ def sync_chat_messages(
}
# Update permission is not delete permission: prune-exempt even for
# allow_research_update callers.
- missing_ids = sorted(existing_ids - retained_ids - research_ids)
+ missing_ids = sorted(existing_ids - requested_ids - prune_protected_ids)
for start in range(0, len(missing_ids), _SQLITE_IN_CHUNK_SIZE):
chunk = missing_ids[start : start + _SQLITE_IN_CHUNK_SIZE]
placeholders = ",".join("?" for _ in chunk)
@@ -3354,6 +3749,12 @@ _RESEARCH_LINK_KEYS = {
"researchPlanRevision",
"serverManaged",
}
+_SERVER_MANAGED_LINK_KEYS = _RESEARCH_LINK_KEYS | {
+ "generationRunId",
+ "generationSeq",
+ "generationStatus",
+ "generationSettled",
+}
def _detach_research_message_json(
@@ -3364,12 +3765,12 @@ def _detach_research_message_json(
custom = metadata.get("custom") if isinstance(metadata, dict) else None
linked = (
isinstance(metadata, dict)
- and any(key in metadata for key in _RESEARCH_LINK_KEYS)
+ and any(key in metadata for key in _SERVER_MANAGED_LINK_KEYS)
or isinstance(custom, dict)
- and any(key in custom for key in _RESEARCH_LINK_KEYS)
+ and any(key in custom for key in _SERVER_MANAGED_LINK_KEYS)
or isinstance(content, list)
and any(
- isinstance(part, dict) and any(key in part for key in _RESEARCH_LINK_KEYS)
+ isinstance(part, dict) and any(key in part for key in _SERVER_MANAGED_LINK_KEYS)
for part in content
)
)
@@ -3378,17 +3779,19 @@ def _detach_research_message_json(
if isinstance(content, list):
content = [
- {key: value for key, value in part.items() if key not in _RESEARCH_LINK_KEYS}
+ {key: value for key, value in part.items() if key not in _SERVER_MANAGED_LINK_KEYS}
if isinstance(part, dict)
else part
for part in content
]
if isinstance(metadata, dict):
- metadata = {key: value for key, value in metadata.items() if key not in _RESEARCH_LINK_KEYS}
+ metadata = {
+ key: value for key, value in metadata.items() if key not in _SERVER_MANAGED_LINK_KEYS
+ }
custom = metadata.get("custom")
if isinstance(custom, dict):
metadata["custom"] = {
- key: value for key, value in custom.items() if key not in _RESEARCH_LINK_KEYS
+ key: value for key, value in custom.items() if key not in _SERVER_MANAGED_LINK_KEYS
}
return (
json.dumps(content, ensure_ascii = False),
@@ -3815,7 +4218,10 @@ def delete_chat_attachment(message_id: str, attachment_id: str) -> bool:
if row is None:
conn.rollback()
return False
- if str(message_id) in _research_message_ids(conn, str(row["thread_id"])):
+ protected_message_ids = _server_managed_message_ids(
+ conn, str(row["thread_id"])
+ ) - _terminal_generation_message_ids(conn, str(row["thread_id"]))
+ if str(message_id) in protected_message_ids:
conn.rollback()
raise ChatMessageProtectedError(
"Research prompts and responses are server-managed and cannot be edited"
diff --git a/studio/backend/tests/test_active_generations.py b/studio/backend/tests/test_active_generations.py
index 670d62395fd..8a4d2b44df0 100644
--- a/studio/backend/tests/test_active_generations.py
+++ b/studio/backend/tests/test_active_generations.py
@@ -71,7 +71,7 @@ def test_snapshot_is_json_safe_and_ordered_by_start():
assert [e["thread_id"] for e in snap] == ["first", "second"]
# The threading.Event must not leak into an HTTP response body.
assert all("event" not in e for e in snap)
- assert {"handle", "thread_id", "model", "kind", "started_at"} == set(snap[0])
+ assert {"handle", "thread_id", "run_id", "model", "kind", "started_at"} == set(snap[0])
def test_thread_ids_are_deduped_and_skip_unnamed_runs():
@@ -117,6 +117,34 @@ def test_cancel_thread_with_no_match_is_a_no_op():
assert not a.is_set()
+def test_cancel_run_targets_only_matching_durable_generation():
+ durable, sibling = threading.Event(), threading.Event()
+ with active_generations.ActiveGeneration(durable, thread_id = "t1", run_id = "run-1"):
+ with active_generations.ActiveGeneration(sibling, thread_id = "t1", run_id = "run-2"):
+ assert active_generations.cancel_run("run-1") == 1
+ assert durable.is_set()
+ assert not sibling.is_set()
+
+
+def test_same_durable_run_and_event_borrows_existing_registration():
+ event = threading.Event()
+ with active_generations.ActiveGeneration(
+ event, run_id = "run-1", thread_id = "stale", model = "stale"
+ ):
+ with active_generations.ActiveGeneration(
+ event, run_id = "run-1", thread_id = "thread-1", model = "local"
+ ):
+ snapshot = active_generations.snapshot()[0]
+ assert (active_generations.count(), snapshot["thread_id"], snapshot["model"]) == (
+ 1,
+ "thread-1",
+ "local",
+ )
+ assert active_generations.cancel_all() == 1
+ assert event.is_set()
+ assert active_generations.count() == 0
+
+
def test_cancel_does_not_unregister_entries():
# __exit__ owns removal, so a generation mid-cleanup is not lost.
a = threading.Event()
diff --git a/studio/backend/tests/test_chat_generation_runs.py b/studio/backend/tests/test_chat_generation_runs.py
new file mode 100644
index 00000000000..8201c7334a1
--- /dev/null
+++ b/studio/backend/tests/test_chat_generation_runs.py
@@ -0,0 +1,627 @@
+# 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 json
+
+import pytest
+
+from routes.chat_generation_runs import (
+ CreateChatGenerationRun,
+ _contains_sensitive_key,
+ _event_cursor,
+ _sanitize_request,
+)
+from storage import chat_generation_runs_db as runs_db
+from storage import studio_db
+from state.tool_policy import reset_tool_policy, set_tool_policy, set_tool_policy_default
+
+
[email protected](autouse = True)
+def _clean_tool_policy():
+ reset_tool_policy()
+ yield
+ reset_tool_policy()
+
+
+def _seed_thread(
+ thread_id = "thread-1",
+ user_id = "user-1",
+ text = "Hello",
+ created_at = 1,
+):
+ studio_db.upsert_chat_thread(
+ {
+ "id": thread_id,
+ "title": "Chat",
+ "modelType": "base",
+ "modelId": "local",
+ "createdAt": created_at,
+ }
+ )
+ studio_db.upsert_chat_message(
+ {
+ "id": user_id,
+ "threadId": thread_id,
+ "role": "user",
+ "content": [{"type": "text", "text": text}],
+ "createdAt": created_at + 1,
+ }
+ )
+
+
+def chat_home():
+ _seed_thread()
+
+
+def _request(**overrides):
+ request = {"model": "local", "messages": [{"role": "user", "content": "Hello"}], "stream": True}
+ request.update(overrides)
+ return request
+
+
+def _model(**overrides):
+ return CreateChatGenerationRun(
+ runId = "run-1",
+ threadId = "thread-1",
+ userMessageId = "user-1",
+ assistantMessageId = "assistant-1",
+ requestPayload = _request(**overrides),
+ )
+
+
+def _tool_messages(arguments):
+ return [
+ {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": "call-1",
+ "type": "function",
+ "function": {"name": "lookup", "arguments": arguments},
+ }
+ ],
+ }
+ ]
+
+
+def _assert_protected(message):
+ with pytest.raises(studio_db.ChatMessageProtectedError):
+ studio_db.upsert_chat_message(message)
+
+
+def _create(
+ run_id = "run-1",
+ owner = "alice",
+ request = None,
+):
+ return runs_db.create_run(
+ run_id = run_id,
+ owner_subject = owner,
+ thread_id = "thread-1",
+ user_message_id = "user-1",
+ assistant_message_id = "assistant-1" if run_id == "run-1" else f"assistant-{run_id}",
+ request_payload = request or _request(),
+ )
+
+
+def test_create_is_owner_scoped_idempotent_and_binds_placeholder(chat_home):
+ run, created = _create()
+ replay, replay_created = _create()
+ assert created is True and replay_created is False
+ assert replay == run
+ assert runs_db.get_run("run-1", "bob") is None
+ assert [run["id"] for run in runs_db.list_active("thread-1")] == ["run-1"]
+ message = studio_db.get_chat_message("thread-1", "assistant-1")
+ assert message["metadata"] == {
+ "generationRunId": "run-1",
+ "generationSeq": 0,
+ "generationStatus": "queued",
+ "serverManaged": True,
+ }
+ _assert_protected({**message, "content": [{"type": "text", "text": "stale overwrite"}]})
+ synced = studio_db.sync_chat_messages("thread-1", [], prune_missing = True)
+ assert {message["id"] for message in synced} == {"user-1", "assistant-1"}
+ assert runs_db.get_run("run-1", "alice") is not None
+ explicitly_pruned = studio_db.sync_chat_messages(
+ "thread-1",
+ [],
+ prune_missing = True,
+ deleted_message_ids = {"assistant-1"},
+ )
+ assert {message["id"] for message in explicitly_pruned} == {"user-1", "assistant-1"}
+ assert runs_db.get_run("run-1", "alice") is not None
+ with pytest.raises(runs_db.ChatGenerationConflictError):
+ _create(owner = "bob")
+ with pytest.raises(runs_db.ChatGenerationConflictError):
+ _create(request = _request(max_tokens = 9))
+
+
+def test_shared_thread_rejects_a_second_subjects_active_generation(chat_home):
+ _create()
+ with pytest.raises(runs_db.ChatGenerationConflictError, match = "active generation"):
+ _create("run-2", owner = "bob")
+ assert [run["id"] for run in runs_db.list_active("thread-1")] == ["run-1"]
+ assert studio_db.get_chat_message("thread-1", "assistant-run-2") is None
+
+
+def test_explicit_prune_deletes_terminal_generation_messages(chat_home):
+ user = studio_db.get_chat_message("thread-1", "user-1")
+ user["attachments"] = [{"id": "file-1", "name": "notes.txt"}]
+ studio_db.upsert_chat_message(user)
+ _create()
+ with pytest.raises(studio_db.ChatMessageProtectedError):
+ studio_db.delete_chat_attachment("user-1", "file-1")
+ stale_assistant = studio_db.get_chat_message("thread-1", "assistant-1")
+ active = studio_db.sync_chat_messages("thread-1", [], prune_missing = True)
+ assert {message["id"] for message in active} == {"user-1", "assistant-1"}
+
+ token = runs_db.get_worker_token("run-1")
+ assert runs_db.mark_running("run-1", token)
+ runs_db.finish_run("run-1", worker_token = token, status = "completed")
+ assert studio_db.delete_chat_attachment("user-1", "file-1") is True
+ user = studio_db.get_chat_message("thread-1", "user-1")
+ assert user.get("attachments") == []
+
+ retained = studio_db.sync_chat_messages("thread-1", [user], prune_missing = True)
+ assert {message["id"] for message in retained} == {"user-1", "assistant-1"}
+ assert runs_db.get_run("run-1", "alice") is not None
+
+ deleted = studio_db.sync_chat_messages(
+ "thread-1",
+ [user],
+ prune_missing = True,
+ deleted_message_ids = {"assistant-1"},
+ )
+ assert [message["id"] for message in deleted] == ["user-1"]
+ assert studio_db.get_chat_message("thread-1", "assistant-1") is None
+ assert runs_db.get_run("run-1", "alice") is None
+
+ stale_sync = studio_db.sync_chat_messages(
+ "thread-1", [user, stale_assistant], prune_missing = True
+ )
+ assert [message["id"] for message in stale_sync] == ["user-1"]
+ assert studio_db.get_chat_message("thread-1", "assistant-1") is None
+ _assert_protected(stale_assistant)
+
+
+def test_terminal_run_does_not_unprotect_a_message_shared_with_an_active_run(chat_home):
+ user = studio_db.get_chat_message("thread-1", "user-1")
+ user["attachments"] = [{"id": "file-1", "name": "notes.txt"}]
+ studio_db.upsert_chat_message(user)
+ _create()
+ token = runs_db.get_worker_token("run-1")
+ assert runs_db.mark_running("run-1", token)
+ runs_db.finish_run("run-1", worker_token = token, status = "completed")
+ _create("run-2")
+
+ with pytest.raises(studio_db.ChatMessageProtectedError):
+ studio_db.delete_chat_attachment("user-1", "file-1")
+ studio_db.sync_chat_messages(
+ "thread-1",
+ [],
+ prune_missing = True,
+ deleted_message_ids = {"user-1"},
+ )
+
+ assert studio_db.get_chat_message("thread-1", "user-1") is not None
+ assert runs_db.get_run("run-2") is not None
+
+
+def test_generation_message_writes_are_run_bound_and_monotonic(chat_home):
+ _create()
+ token = runs_db.get_worker_token("run-1")
+ assert runs_db.mark_running("run-1", token)
+ runs_db.append_events("run-1", token, [("chunk", {"text": "A"})])
+ message = studio_db.get_chat_message("thread-1", "assistant-1")
+ message["content"] = [{"type": "text", "text": "A"}]
+ message["metadata"].update({"generationSeq": 3, "generationStatus": "running"})
+ studio_db.upsert_chat_message(message)
+
+ forged_terminal = {
+ **message,
+ "metadata": {
+ **message["metadata"],
+ "generationStatus": "completed",
+ "generationSettled": True,
+ },
+ }
+ _assert_protected(forged_terminal)
+ for metadata in (
+ {**message["metadata"], "generationSeq": 2},
+ {**message["metadata"], "generationRunId": "other-run"},
+ ):
+ _assert_protected(
+ {**message, "content": [{"type": "text", "text": "stale"}], "metadata": metadata}
+ )
+ runs_db.finish_run("run-1", worker_token = token, status = "completed", finish_reason = "length")
+ stale = {
+ **message,
+ "content": [{"type": "text", "text": "downgraded"}],
+ "metadata": {**message["metadata"], "generationStatus": "running"},
+ }
+ _assert_protected(stale)
+ studio_db.sync_chat_messages("thread-1", [stale])
+ stored = studio_db.get_chat_message("thread-1", "assistant-1")
+ assert stored["content"] == [{"type": "text", "text": "A"}]
+ assert stored["metadata"]["generationStatus"] == "completed"
+ stored["metadata"]["generationSettled"] = True
+ _assert_protected(stored)
+ stored["metadata"].update(
+ {"generationSeq": 4, "generationSettled": True, "responseDetails": {"durationMs": 1}}
+ )
+ studio_db.upsert_chat_message(stored)
+ stored["metadata"]["generationSettled"] = False
+ _assert_protected(stored)
+ authoritative = studio_db.get_chat_message("thread-1", "assistant-1")
+ stale = {
+ **authoritative,
+ "metadata": {
+ key: value
+ for key, value in authoritative["metadata"].items()
+ if key not in {"incomplete", "responseDetails"}
+ },
+ }
+ _assert_protected(stale)
+ studio_db.sync_chat_messages("thread-1", [stale])
+ preserved = studio_db.get_chat_message("thread-1", "assistant-1")["metadata"]
+ assert preserved["incomplete"] == {"reason": "length"}
+ assert preserved["responseDetails"] == {"durationMs": 1}
+
+
+def test_settled_generation_response_can_be_explicitly_edited(chat_home):
+ _create()
+ token = runs_db.get_worker_token("run-1")
+ assert runs_db.mark_running("run-1", token)
+ assert runs_db.finish_run("run-1", worker_token = token, status = "completed", finish_reason = "stop")
+ run = runs_db.get_run("run-1", "alice")
+ stored = studio_db.get_chat_message("thread-1", "assistant-1")
+ stored["metadata"].update(
+ {
+ "generationSeq": run["lastEventSeq"],
+ "generationStatus": "completed",
+ "generationSettled": True,
+ }
+ )
+ studio_db.upsert_chat_message(stored)
+ authoritative = studio_db.get_chat_message("thread-1", "assistant-1")
+ edited = {key: value for key, value in authoritative.items() if key != "metadata"}
+ edited["content"] = [{"type": "text", "text": "edited"}]
+
+ _assert_protected(edited)
+ saved = studio_db.upsert_chat_message(edited, allow_generation_edit = True)
+ assert saved["content"] == [{"type": "text", "text": "edited"}]
+ assert saved.get("metadata") is None
+ assert runs_db.get_run("run-1", "alice") is None
+ _assert_protected(authoritative)
+
+
+def test_batched_events_have_gapless_cursor_and_terminal_flush(chat_home):
+ run, _created = _create()
+ worker_token = runs_db.get_worker_token("run-1")
+ assert runs_db.mark_running("run-1", worker_token) is True
+ assert runs_db.append_events(
+ "run-1", worker_token, [("chunk", {"i": 1}), ("chunk", {"i": 2})]
+ ) == [3, 4]
+ cancelling = runs_db.request_cancel("run-1", "alice")
+ assert cancelling["status"] == "cancelling"
+ terminal = runs_db.finish_run(
+ "run-1",
+ worker_token = worker_token,
+ status = "completed",
+ finish_reason = "stop",
+ pending_events = [("chunk", {"i": 3})],
+ )
+ assert terminal["status"] == "cancelled"
+ events = runs_db.list_events("run-1")
+ assert [event["seq"] for event in events] == list(range(1, 8))
+ assert [event["payload"].get("i") for event in events if event["type"] == "chunk"] == [1, 2, 3]
+ assert runs_db.list_events("run-1", after = 4)[0]["seq"] == 5
+ assert runs_db.request_cancel("run-1", "alice")["lastEventSeq"] == 7
+
+
+def test_batched_events_preserve_receipt_timestamps(chat_home):
+ _create()
+ worker_token = runs_db.get_worker_token("run-1")
+ assert runs_db.mark_running("run-1", worker_token) is True
+ runs_db.append_events(
+ "run-1",
+ worker_token,
+ [("chunk", {"i": 1}, 1001), ("chunk", {"i": 2}, 1002)],
+ )
+ chunks = [event for event in runs_db.list_events("run-1") if event["type"] == "chunk"]
+ assert [event["createdAt"] for event in chunks] == [1001, 1002]
+
+
+def test_cancel_before_registration_and_startup_orphan_reconciliation(chat_home):
+ queued, _created = _create("queued")
+ cancelled = runs_db.request_cancel("queued", "alice")
+ assert cancelled["status"] == "cancelled"
+ assert runs_db.mark_running("queued", runs_db.get_worker_token("queued")) is False
+ orphan, _created = _create("orphan", request = _request(seed = 2))
+ assert runs_db.mark_running("orphan", runs_db.get_worker_token("orphan")) is True
+ assert runs_db.reconcile_orphaned_runs() == 1
+ orphan = runs_db.get_run("orphan", "alice")
+ assert (orphan["status"], orphan["finishReason"]) == ("failed", "interrupted")
+ assert runs_db.list_events("orphan")[-1]["payload"]["interrupted"] is True
+
+
+def test_a_stop_in_flight_survives_a_restart_as_a_cancellation(chat_home):
+ """Stop recorded, worker not yet settled, Studio restarts.
+
+ Reporting this as a backend failure would tell the user Studio broke when in fact they
+ stopped it, and finish_run already settles the same case as cancelled.
+ """
+ _create()
+ runs_db.mark_running("run-1", runs_db.get_worker_token("run-1"))
+ assert runs_db.request_cancel("run-1", "alice")["status"] == "cancelling"
+
+ assert runs_db.reconcile_orphaned_runs() == 1
+
+ run = runs_db.get_run("run-1", "alice")
+ assert (run["status"], run["finishReason"]) == ("cancelled", "cancelled")
+ assert run["error"] is None
+ assert runs_db.list_events("run-1")[-1]["type"] == "run.cancelled"
+
+
+def test_an_uncancelled_run_still_reconciles_as_interrupted(chat_home):
+ """The cancellation branch above must not swallow a genuine restart."""
+ _create()
+ runs_db.mark_running("run-1", runs_db.get_worker_token("run-1"))
+
+ assert runs_db.reconcile_orphaned_runs() == 1
+
+ run = runs_db.get_run("run-1", "alice")
+ assert (run["status"], run["finishReason"]) == ("failed", "interrupted")
+ assert run["error"] == "Studio restarted during generation"
+ assert runs_db.list_events("run-1")[-1]["payload"]["interrupted"] is True
+
+
+def test_deleted_run_id_is_tombstoned_against_stale_tabs(chat_home):
+ _original, _created = _create()
+ studio_db.delete_chat_threads(["thread-1"])
+ _seed_thread("thread-2", "user-2", "Next", 3)
+ with pytest.raises(runs_db.ChatGenerationConflictError, match = "already been used"):
+ runs_db.create_run(
+ run_id = "run-1",
+ owner_subject = "alice",
+ thread_id = "thread-2",
+ user_message_id = "user-2",
+ assistant_message_id = "assistant-2",
+ request_payload = _request(seed = 2),
+ )
+ assert runs_db.get_run("run-1", "alice") is None
+
+
+_SYNC_USER = {
+ "id": "user-1",
+ "threadId": "thread-1",
+ "role": "user",
+ "content": [{"type": "text", "text": "Hello"}],
+ "createdAt": 2,
+}
+
+
+def _edited_generated_assistant():
+ """Settle a generated assistant the way the pipeline does, then edit it by hand.
+
+ Returns the stale pre-edit copy another tab would still be holding.
+ """
+ studio_db.upsert_chat_message(
+ {
+ "id": "assistant-1",
+ "threadId": "thread-1",
+ "role": "assistant",
+ "parentId": "user-1",
+ "content": [],
+ "createdAt": 3,
+ "metadata": {},
+ }
+ )
+ _create()
+ token = runs_db.get_worker_token("run-1")
+ runs_db.mark_running("run-1", token)
+ runs_db.finish_run("run-1", worker_token = token, status = "completed", finish_reason = "stop")
+
+ metadata = dict(studio_db.get_chat_message("thread-1", "assistant-1")["metadata"])
+ metadata["generationSeq"] = int(runs_db.get_run("run-1", "alice")["lastEventSeq"])
+ metadata["generationSettled"] = True
+ settled = {
+ "id": "assistant-1",
+ "threadId": "thread-1",
+ "role": "assistant",
+ "parentId": "user-1",
+ "content": [{"type": "text", "text": "generated answer"}],
+ "createdAt": 3,
+ "metadata": metadata,
+ }
+ studio_db.sync_chat_messages("thread-1", [_SYNC_USER, settled])
+ assert (
+ studio_db.get_chat_message("thread-1", "assistant-1")["metadata"]["generationSettled"]
+ is True
+ ), "the settle write did not land, so anything built on it would prove nothing"
+ stale_tab_copy = json.loads(json.dumps(settled))
+
+ studio_db.upsert_chat_message(
+ {
+ "id": "assistant-1",
+ "threadId": "thread-1",
+ "role": "assistant",
+ "parentId": "user-1",
+ "content": [{"type": "text", "text": "edited by hand"}],
+ "createdAt": 3,
+ "metadata": {},
+ },
+ allow_generation_edit = True,
+ )
+ assert runs_db.get_run("run-1", "alice") is None, "the edit did not detach the run"
+ return stale_tab_copy
+
+
+def test_a_stale_tab_sync_cannot_prune_an_edited_generated_assistant(chat_home):
+ """Editing a settled generated answer detaches it; another open tab must not delete it.
+
+ The edit drops the run row, so the id stops counting as generation-linked. A stale tab
+ still holding the pre-edit copy has that copy filtered out as tombstoned, which would
+ otherwise leave the id absent from the requested set and inside the prune.
+ """
+ stale_tab_copy = _edited_generated_assistant()
+
+ studio_db.sync_chat_messages("thread-1", [_SYNC_USER, stale_tab_copy], prune_missing = True)
+
+ survivor = studio_db.get_chat_message("thread-1", "assistant-1")
+ assert survivor is not None, "the stale tab's sync deleted the user's edited message"
+ # Kept, but still not writable by the stale copy.
+ assert survivor["content"] == [{"type": "text", "text": "edited by hand"}]
+
+
+def test_an_explicit_delete_still_removes_a_detached_generated_assistant(chat_home):
+ """The retention above is snapshot-pruning only; naming the id must still delete it."""
+ stale_tab_copy = _edited_generated_assistant()
+
+ studio_db.sync_chat_messages(
+ "thread-1",
+ [_SYNC_USER, stale_tab_copy],
+ prune_missing = True,
+ deleted_message_ids = ["assistant-1"],
+ )
+ assert studio_db.get_chat_message("thread-1", "assistant-1") is None
+
+
+ "override,detail",
+ [
+ ({"provider_id": "external"}, "only for local"),
+ ({"tools": [{"type": "function"}]}, "legacy streaming"),
+ ({"enable_tools": True}, "legacy streaming"),
+ ({"rag_scope": {"access_token": "secret"}}, "Credentials"),
+ ({"rag_scope": {"signing_key": "secret"}}, "Credentials"),
+ ({"rag_scope": {"ssh_key": "secret"}}, "Credentials"),
+ ({"rag_scope": {"encryption_key": "secret"}}, "Credentials"),
+ ({"rag_scope": {"secret_key": "secret"}}, "Credentials"),
+ ({"rag_scope": {"api_token": "secret"}}, "Credentials"),
+ (
+ {
+ "messages": [
+ {"role": "user", "content": "Hello", "extra_content": {"api_key": "secret"}}
+ ]
+ },
+ "Credentials",
+ ),
+ (
+ {"messages": _tool_messages('{"api_key":"secret"}')},
+ "Credentials",
+ ),
+ ],
+)
+def test_request_sanitization_rejects_nonlocal_or_sensitive_payloads(override, detail):
+ with pytest.raises(Exception, match = detail):
+ _sanitize_request(_model(**override))
+
+
+def test_request_sanitization_pins_server_owned_fields():
+ sanitized = _sanitize_request(_model(stream = False, cancel_id = "legacy", thread_id = "wrong"))
+ assert sanitized["stream"] is True
+ assert sanitized["cancel_id"] == "run-1"
+ assert sanitized["thread_id"] == "thread-1"
+
+
+def test_request_sanitization_treats_message_text_as_data():
+ sanitized = _sanitize_request(
+ _model(messages = [{"role": "user", "content": '{"api_key":"example"}'}])
+ )
+ assert sanitized["messages"][0]["content"] == '{"api_key":"example"}'
+
+
[email protected]("key", ["key", "lookup_key", "monkey", "hockey", "keyboard"])
+def test_request_sanitization_accepts_benign_tool_argument_keys(key):
+ arguments = json.dumps({key: "value"})
+ sanitized = _sanitize_request(_model(messages = _tool_messages(arguments)))
+ assert sanitized["messages"][0]["tool_calls"][0]["function"]["arguments"] == arguments
+
+
+ "key",
+ ["api_key", "access_key", "private_key", "secret_key", "signing_key", "ssh_key"],
+)
+def test_request_sanitization_rejects_known_credential_keys(key):
+ arguments = json.dumps({key: "secret"})
+ with pytest.raises(Exception, match = "Credentials"):
+ _sanitize_request(_model(messages = _tool_messages(arguments)))
+
+
[email protected]("value", ['{"api_key":"secret"', '"{\\"api_key\\":\\"secret\\"}"'])
+def test_request_sanitization_scans_json_string_envelopes(value):
+ assert _contains_sensitive_key(value) is True
+
+
+def test_request_sanitization_bounds_nested_envelopes():
+ nested = {"value": None}
+ for _ in range(100):
+ nested = {"value": nested}
+ assert _contains_sensitive_key(nested) is True
+ assert _contains_sensitive_key("[" * 5000 + "0" + "]" * 5000) is True
+ with pytest.raises(Exception, match = "Credentials"):
+ _sanitize_request(
+ _model(messages = [{"role": "user", "content": "hello", "extra_content": nested}])
+ )
+
+
[email protected]("messages", [None, 1, [{"role": "user", "content": None}]])
+def test_request_sanitization_returns_json_safe_validation_errors(messages):
+ with pytest.raises(Exception) as exc_info:
+ _sanitize_request(_model(messages = messages))
+ assert exc_info.value.status_code == 422
+ json.dumps(exc_info.value.detail)
+
+
+ "overrides",
+ [{"provider_id": ""}, {"provider_id": None, "encrypted_api_key": None}, {"tools": []}],
+)
+def test_request_sanitization_accepts_empty_optional_routing(overrides):
+ assert _sanitize_request(_model(**overrides))["stream"] is True
+
+
+def test_request_sanitization_rejects_launcher_default_tools():
+ set_tool_policy_default(True)
+ with pytest.raises(Exception, match = "legacy streaming path"):
+ _sanitize_request(_model())
+
+
+def test_request_sanitization_rejects_cli_tools_override_even_when_request_disables_tools():
+ set_tool_policy(True)
+ with pytest.raises(Exception, match = "legacy streaming path"):
+ _sanitize_request(_model(enable_tools = False))
+
+
+def test_request_sanitization_rejects_checkpoint_recall_tool_loop(monkeypatch):
+ import routes.inference as inference_routes
+ monkeypatch.setattr(
+ inference_routes, "_checkpoint_recall_may_enable_tools", lambda request: True, raising = False
+ )
+ with pytest.raises(Exception, match = "legacy streaming path"):
+ _sanitize_request(_model(enable_tools = False))
+
+
+def test_event_cursor_rejects_values_outside_sqlite_integer_range():
+ with pytest.raises(Exception, match = "cursor is too large"):
+ _event_cursor(10**30, None)
+ with pytest.raises(Exception, match = "cursor is too large"):
+ _event_cursor(None, str(10**30))
+ with pytest.raises(Exception, match = "must be an integer"):
+ _event_cursor(None, "²")
+ with pytest.raises(Exception, match = "cursor is too large"):
+ _event_cursor(None, "9" * 4301)
+
+
[email protected]("field", ["image_base64", "audio_base64", "video_base64"])
+def test_request_sanitization_rejects_inline_media(field):
+ """Media stays on the legacy stream on the server too, not only in the composer.
+
+ Recovery rebuilds text and reasoning deltas, and the request is persisted verbatim,
+ so admitting one of these would park a base64 blob in request_json for the life of
+ the thread and hand the client a transcript it has no way to replay.
+ """
+ with pytest.raises(Exception, match = "legacy streaming path"):
+ _sanitize_request(_model(**{field: "iVBORw0KGgo="}))
diff --git a/studio/backend/tests/test_chat_generation_supervisor.py b/studio/backend/tests/test_chat_generation_supervisor.py
new file mode 100644
index 00000000000..95aab4da751
--- /dev/null
+++ b/studio/backend/tests/test_chat_generation_supervisor.py
@@ -0,0 +1,578 @@
+# 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 asyncio
+import json
+import threading
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from core.inference import llama_keepwarm
+from core.inference.chat_generation_runs import ChatGenerationSupervisor
+from models.inference import ChatCompletionRequest
+from routes import chat_generation_runs as run_routes
+from routes import inference
+from state import active_generations
+from storage import chat_generation_runs_db as runs_db
+from storage import studio_db
+
+
+def durable_run(request):
+ engine = getattr(request, "param", "gguf")
+ model = "local.gguf" if engine == "gguf" else "local.safetensors"
+ studio_db.upsert_chat_thread(
+ {"id": "thread-1", "title": "Chat", "modelType": "base", "modelId": model, "createdAt": 1}
+ )
+ studio_db.upsert_chat_message(
+ {
+ "id": "user-1",
+ "threadId": "thread-1",
+ "role": "user",
+ "content": [{"type": "text", "text": "Hello"}],
+ "createdAt": 2,
+ }
+ )
+ run, _created = runs_db.create_run(
+ run_id = "run-1",
+ owner_subject = "alice",
+ thread_id = "thread-1",
+ user_message_id = "user-1",
+ assistant_message_id = "assistant-1",
+ request_payload = {
+ "model": model,
+ "messages": [{"role": "user", "content": "Hello"}],
+ "stream": True,
+ "cancel_id": "run-1",
+ "thread_id": "thread-1",
+ "generation_run_id": "run-1",
+ },
+ )
+ active_generations.reset_for_tests()
+ yield run
+ active_generations.reset_for_tests()
+
+
+def _create_payload(content = "Hello"):
+ return run_routes.CreateChatGenerationRun(
+ runId = "run-1",
+ threadId = "thread-1",
+ userMessageId = "user-1",
+ assistantMessageId = "assistant-1",
+ requestPayload = {"model": "local", "messages": [{"role": "user", "content": content}]},
+ )
+
+
+def _route_request(supervisor):
+ return SimpleNamespace(
+ app = SimpleNamespace(state = SimpleNamespace(chat_generation_supervisor = supervisor))
+ )
+
+
+async def test_public_chat_wrapper_keeps_cancel_on_disconnect(monkeypatch):
+ observed = []
+
+ async def fake(_payload, _request, _subject, *, cancel_on_disconnect):
+ observed.append(cancel_on_disconnect)
+ return "response"
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ payload = ChatCompletionRequest(
+ model = "local",
+ messages = [{"role": "user", "content": "Hello"}],
+ )
+ assert await inference.openai_chat_completions(payload, object(), "alice") == "response"
+ assert observed == [True]
+
+
+ "is_mlx,durable_run,generation_run_id,completion_tokens,expected",
+ [
+ (True, True, "run-1", 8, "length"),
+ (True, True, "run-1", 7, "stop"),
+ (True, False, "run-1", 8, "stop"),
+ (False, True, "run-1", 8, "stop"),
+ ],
+)
+def test_only_durable_mlx_normalizes_stop_at_token_cap(
+ is_mlx, durable_run, generation_run_id, completion_tokens, expected
+):
+ payload = SimpleNamespace(
+ generation_run_id = generation_run_id,
+ max_tokens = 8,
+ max_completion_tokens = None,
+ )
+ stats = {"usage": {"completion_tokens": completion_tokens}}
+ assert (
+ inference._safetensors_finish_reason(stats, payload, is_mlx = is_mlx, durable_run = durable_run)
+ == expected
+ )
+
+
+async def test_create_route_schedules_producer_on_request_loop(monkeypatch):
+ started = []
+ supervisor = SimpleNamespace(
+ start = lambda run_id, **identity: started.append((run_id, identity))
+ )
+ request = _route_request(supervisor)
+
+ def create_run(**_kwargs):
+ assert started == []
+ return (
+ {
+ "id": "run-1",
+ "status": "queued",
+ "threadId": "thread-1",
+ "requestPayload": {"model": "local"},
+ },
+ True,
+ )
+
+ monkeypatch.setattr(run_routes.db, "create_run", create_run)
+ response = await run_routes.create_chat_generation_run(_create_payload(), request, "alice")
+ assert response["created"] is True
+ assert started == [("run-1", {"thread_id": "thread-1", "model": "local"})]
+
+
+async def test_terminal_idempotent_create_does_not_reserve_generation(monkeypatch):
+ terminal = {
+ "id": "run-1",
+ "status": "completed",
+ "threadId": "thread-1",
+ "requestPayload": {"model": "local"},
+ }
+ supervisor = SimpleNamespace(
+ start = lambda *_args, **_kwargs: pytest.fail("terminal run must not start"),
+ )
+ request = _route_request(supervisor)
+ monkeypatch.setattr(run_routes.db, "create_run", lambda **_kwargs: (terminal, False))
+ response = await run_routes.create_chat_generation_run(_create_payload("Hi"), request, "alice")
+ assert response["created"] is False
+
+
+async def test_background_producer_persists_chunks_and_completes(durable_run, monkeypatch):
+ observed = []
+ leaked = []
+ chunks = [
+ {"choices": [{"delta": {"content": "Hello"}, "finish_reason": None}]},
+ {"choices": [{"delta": {}, "finish_reason": "stop"}]},
+ ]
+
+ async def body():
+ for chunk in chunks:
+ yield f"data: {json.dumps(chunk)}\n\n"
+ yield "data: [DONE]\n\n"
+
+ async def fake(_payload, _request, _subject, *, cancel_on_disconnect):
+ observed.append(cancel_on_disconnect)
+ return SimpleNamespace(status_code = 200, body_iterator = body())
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ supervisor = ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))
+ loop = asyncio.get_running_loop()
+ previous_handler = loop.get_exception_handler()
+ loop.set_exception_handler(lambda _loop, context: leaked.append(context))
+ try:
+ await supervisor._produce("run-1")
+ await asyncio.sleep(0)
+ finally:
+ loop.set_exception_handler(previous_handler)
+ run = runs_db.get_run("run-1", "alice")
+ assert leaked == []
+ assert observed == [False]
+ assert (run["status"], run["finishReason"]) == ("completed", "stop")
+ assert [
+ event["payload"] for event in runs_db.list_events("run-1") if event["type"] == "chunk"
+ ] == chunks
+
+
+async def _subscriber_sequences(after = 0):
+ response = await run_routes.chat_generation_events(
+ "run-1",
+ SimpleNamespace(is_disconnected = AsyncMock(return_value = True)),
+ after = after,
+ last_event_id = None,
+ current_subject = "alice",
+ )
+ raw = ""
+ async for part in response.body_iterator:
+ raw += part.decode() if isinstance(part, bytes) else part
+ return [int(line[4:]) for line in raw.splitlines() if line.startswith("id: ")]
+
+
+def _route_engine(monkeypatch, model, first, release):
+ gguf = model.endswith(".gguf")
+
+ def generate(*, stats_holder = None, **_kwargs):
+ first.set()
+ yield "A"
+ assert release.wait(5)
+ yield "AB"
+ if stats_holder is None:
+ yield {"type": "metadata", "finish_reason": "stop"}
+ else:
+ stats_holder["stats"] = {"usage": {"completion_tokens": 2}}
+
+ llama = SimpleNamespace(
+ is_loaded = gguf,
+ model_identifier = model,
+ base_url = "http://llama.test",
+ effective_parallel_slots = 1,
+ supports_tools = False,
+ is_vision = False,
+ _is_audio = False,
+ context_length = None,
+ generate_chat_completion = generate,
+ )
+ mlx = SimpleNamespace(
+ active_model_name = model,
+ models = {model: {"is_mlx": True, "chat_template_info": {"template": "chatml"}}},
+ generate_chat_response = generate,
+ reset_generation_state = lambda *_a, **_k: None,
+ )
+ monkeypatch.setattr(inference, "get_llama_cpp_backend", lambda: llama)
+ monkeypatch.setattr(inference, "get_inference_backend", lambda: mlx)
+ monkeypatch.setattr(inference, "_automatic_model_load_may_run", lambda: False)
+ monkeypatch.setattr(
+ inference, "_detect_safetensors_features", lambda *_a, **_k: {"supports_tools": False}
+ )
+ monkeypatch.setattr(inference, "_effective_enable_tools", lambda _payload: False)
+
+ async def no_switch(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(inference, "_maybe_auto_switch_model", no_switch)
+
+
[email protected]("durable_run", ["gguf", "mlx"], indirect = True)
+async def test_subscribers_detach_then_replay_the_same_engine_run(durable_run, monkeypatch):
+ first_chunk, release = threading.Event(), threading.Event()
+ _route_engine(monkeypatch, durable_run["requestPayload"]["model"], first_chunk, release)
+ task = asyncio.create_task(
+ ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))._produce("run-1")
+ )
+ if not await asyncio.to_thread(first_chunk.wait, 5):
+ await task
+ pytest.fail(str(runs_db.get_run("run-1", "alice")))
+ while len(runs_db.list_events("run-1")) < 4:
+ await asyncio.sleep(0.01)
+ first, second = await asyncio.gather(_subscriber_sequences(), _subscriber_sequences())
+ assert first == second == list(range(1, max(first) + 1))
+ assert runs_db.get_run("run-1", "alice")["status"] == "running"
+ release.set()
+ await task
+ tail = await _subscriber_sequences(after = max(first))
+ run = runs_db.get_run("run-1", "alice")
+ assert first + tail == list(range(1, run["lastEventSeq"] + 1))
+ deltas = [
+ event["payload"].get("choices", [{}])[0].get("delta", {}).get("content")
+ for event in runs_db.list_events("run-1")
+ if event["type"] == "chunk"
+ ]
+ assert [text for text in deltas if text] == ["A", "B"]
+
+
+async def test_event_batch_flushes_while_upstream_is_idle(durable_run, monkeypatch):
+ release = asyncio.Event()
+ chunks = [
+ {"choices": [{"delta": {"role": "assistant"}}]},
+ {"choices": [{"delta": {"content": "Hello"}}]},
+ ]
+
+ async def body():
+ for chunk in chunks:
+ yield f"data: {json.dumps(chunk)}\n\n"
+ await release.wait()
+ yield "data: [DONE]\n\n"
+
+ async def fake(*_args, **_kwargs):
+ return SimpleNamespace(status_code = 200, body_iterator = body())
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ supervisor = ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))
+ task = asyncio.create_task(supervisor._produce("run-1"))
+ await asyncio.sleep(0.2)
+ stored = [e["payload"] for e in runs_db.list_events("run-1") if e["type"] == "chunk"]
+ assert stored == chunks
+ release.set()
+ await task
+
+
+async def test_model_lifecycle_cancel_reaches_same_registered_event(durable_run, monkeypatch):
+ registered = asyncio.Event()
+
+ async def body(cancel_event):
+ with active_generations.ActiveGeneration(
+ cancel_event,
+ thread_id = "thread-1",
+ run_id = "run-1",
+ ):
+ registered.set()
+ while not cancel_event.is_set():
+ await asyncio.sleep(0.01)
+ if False:
+ yield ""
+
+ async def fake(_payload, request, *_args, **_kwargs):
+ return SimpleNamespace(
+ status_code = 200,
+ body_iterator = body(request.state.generation_cancel_event),
+ )
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ supervisor = ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))
+ task = asyncio.create_task(supervisor._produce("run-1"))
+ await asyncio.wait_for(registered.wait(), timeout = 2)
+ assert active_generations.cancel_all() == 1
+ await asyncio.wait_for(task, timeout = 2)
+ assert runs_db.get_run("run-1", "alice")["status"] == "cancelled"
+ metadata = studio_db.get_chat_message("thread-1", "assistant-1")["metadata"]
+ assert metadata["incomplete"] == {"reason": "cancelled"}
+ assert active_generations.count() == 0
+
+
+async def test_cancel_before_registration_signals_load_event(durable_run, monkeypatch):
+ entered = asyncio.Event()
+ cancel_ids = []
+ supervisor = ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))
+
+ async def fake(_payload, request, *_args, **_kwargs):
+ event = request.state.generation_cancel_event
+ entered.set()
+ while not event.is_set():
+ await asyncio.sleep(0.01)
+
+ async def body():
+ if False:
+ yield ""
+
+ return SimpleNamespace(status_code = 200, body_iterator = body())
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ monkeypatch.setattr(
+ inference,
+ "_cancel_by_cancel_id_or_stash",
+ lambda run_id: cancel_ids.append(run_id) or 0,
+ )
+ supervisor.start("run-1")
+ await asyncio.wait_for(entered.wait(), timeout = 2)
+ supervisor.cancel("run-1")
+ await asyncio.wait_for(supervisor._tasks["run-1"], timeout = 2)
+ assert cancel_ids == ["run-1"]
+ assert runs_db.get_run("run-1", "alice")["status"] == "cancelled"
+
+
+async def test_start_reserves_slot_and_lifecycle_before_worker_runs(durable_run, monkeypatch):
+ monkeypatch.setattr(llama_keepwarm, "_pending", 0)
+ monkeypatch.setattr(llama_keepwarm, "_inflight", 0)
+ supervisor = ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))
+ supervisor.start("run-1", thread_id = "thread-1", model = "local")
+ assert (llama_keepwarm._pending, active_generations.count()) == (1, 1)
+ assert active_generations.snapshot()[0]["thread_id"] == "thread-1"
+ supervisor.cancel("run-1")
+ await asyncio.wait_for(supervisor._tasks["run-1"], timeout = 2)
+ assert runs_db.get_run("run-1", "alice")["status"] == "cancelled"
+ assert (llama_keepwarm._pending, llama_keepwarm._inflight) == (0, 0)
+
+
+async def test_cancelled_producer_error_is_cancelled(durable_run, monkeypatch):
+ entered = asyncio.Event()
+
+ async def fake(_payload, request, *_args, **_kwargs):
+ entered.set()
+ while not request.state.generation_cancel_event.is_set():
+ await asyncio.sleep(0.01)
+ raise RuntimeError("Generation cancelled")
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ supervisor = ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))
+ supervisor.start("run-1")
+ await asyncio.wait_for(entered.wait(), timeout = 2)
+ assert active_generations.cancel_all() == 1
+ await asyncio.wait_for(supervisor._tasks["run-1"], timeout = 2)
+ assert runs_db.get_run("run-1", "alice")["status"] == "cancelled"
+
+
+async def test_uncancelled_partial_eof_is_interrupted(durable_run, monkeypatch):
+ async def body():
+ yield 'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
+
+ async def fake(*_args, **_kwargs):
+ return SimpleNamespace(status_code = 200, body_iterator = body())
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ await ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))._produce("run-1")
+ run = runs_db.get_run("run-1", "alice")
+ assert (run["status"], run["finishReason"]) == ("failed", "interrupted")
+
+
+async def test_a_caught_up_reconnect_to_a_settled_run_does_not_block(durable_run, monkeypatch):
+ """Nothing left to replay must return at once, not after the 15s event wait.
+
+ Otherwise a finished answer reads as still generating for the whole timeout and one of
+ the event-wait workers is held for it.
+ """
+
+ async def body():
+ yield 'data: {"choices":[{"delta":{"content":"done"},"finish_reason":"stop"}]}\n\n'
+ yield "data: [DONE]\n\n"
+
+ async def fake(*_args, **_kwargs):
+ return SimpleNamespace(status_code = 200, body_iterator = body())
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ await ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))._produce("run-1")
+ settled = runs_db.get_run("run-1", "alice")
+ assert settled["status"] == "completed"
+
+ caught_up = await asyncio.wait_for(
+ _subscriber_sequences(after = int(settled["lastEventSeq"])),
+ timeout = 5,
+ )
+ assert caught_up == []
+ # A client that is behind still gets the whole ledger.
+ assert await _subscriber_sequences() == list(range(1, int(settled["lastEventSeq"]) + 1))
+
+
+async def test_streamed_error_outranks_cleanup_cancellation(durable_run, monkeypatch):
+ """A backend failure must not be recorded as if the user pressed Stop.
+
+ ``gguf_stream_chunks`` emits the error in band, follows it with ``[DONE]`` and then
+ sets this same ``cancel_event`` from its ``finally`` because the stream did not
+ complete. Nobody asked to cancel, so the run has to settle as ``failed`` carrying
+ the diagnostic the user needs to act on.
+ """
+
+ async def body(cancel_event):
+ try:
+ yield 'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
+ yield 'data: {"error": {"message": "Out of memory"}}\n\ndata: [DONE]\n\n'
+ finally:
+ cancel_event.set()
+
+ async def fake(_payload, request, *_args, **_kwargs):
+ return SimpleNamespace(
+ status_code = 200,
+ body_iterator = body(request.state.generation_cancel_event),
+ )
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ await ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))._produce("run-1")
+ run = runs_db.get_run("run-1", "alice")
+ assert run["status"] == "failed"
+ assert run["error"] == "Out of memory"
+ assert run["finishReason"] != "cancelled"
+ metadata = studio_db.get_chat_message("thread-1", "assistant-1")["metadata"]
+ assert metadata["incomplete"] != {"reason": "cancelled"}
+
+
+async def test_graceful_supervisor_shutdown_is_interrupted(durable_run, monkeypatch):
+ entered = asyncio.Event()
+
+ async def body(request):
+ entered.set()
+ while not request.state.generation_cancel_event.is_set():
+ await asyncio.sleep(0.01)
+ if False:
+ yield ""
+
+ async def fake(_payload, request, *_args, **_kwargs):
+ return SimpleNamespace(status_code = 200, body_iterator = body(request))
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ supervisor = ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))
+ supervisor.start("run-1")
+ await asyncio.wait_for(entered.wait(), timeout = 2)
+ await supervisor.stop()
+ run = runs_db.get_run("run-1", "alice")
+ assert (run["status"], run["finishReason"]) == ("failed", "interrupted")
+ assert run["error"] == "Studio shut down during generation"
+
+
+def test_thread_delete_captures_durable_run_before_cascade(durable_run):
+ research_ids, chat_ids = studio_db.delete_chat_threads_with_active_runs(["thread-1"])
+ assert research_ids == []
+ assert chat_ids == ["run-1"]
+ assert runs_db.get_run("run-1", "alice") is None
+
+
+def test_project_delete_captures_durable_run_before_cascade(durable_run):
+ studio_db.upsert_chat_project(
+ {"id": "project-1", "name": "Project", "createdAt": 1, "updatedAt": 1}
+ )
+ studio_db.update_chat_thread("thread-1", {"projectId": "project-1"})
+ deleted = studio_db.delete_chat_project("project-1")
+ assert deleted["activeChatGenerationRunIds"] == ["run-1"]
+
+
+def test_clear_captures_durable_run_before_cascade(durable_run):
+ removed, research_ids, chat_ids = studio_db.clear_chat_history(
+ include_chat_generation_runs = True
+ )
+ assert (removed, research_ids, chat_ids) == (["thread-1"], [], ["run-1"])
+
+
+def test_startup_reconcile_marks_stored_assistant_interrupted(durable_run):
+ worker_token = runs_db.get_worker_token("run-1")
+ assert runs_db.mark_running("run-1", worker_token)
+ assert runs_db.reconcile_orphaned_runs() == 1
+ message = studio_db.get_chat_message("thread-1", "assistant-1")
+ assert message["metadata"]["generationStatus"] == "failed"
+ assert message["metadata"]["incomplete"] == {"reason": "interrupted"}
+
+
+async def test_shutdown_returns_even_when_a_producer_will_not_unwind(durable_run, monkeypatch):
+ """A generator whose teardown blocks must not take uvicorn's shutdown with it.
+
+ The grace period is bounded, but the gather after task.cancel() has to be too:
+ an engine draining a subprocess inside aclose never completes its cancellation,
+ and stop() would then wait on it forever.
+ """
+ import core.inference.chat_generation_runs as chat_generation_runs
+
+ monkeypatch.setattr(chat_generation_runs, "_SHUTDOWN_GRACE_SECONDS", 0.2)
+ monkeypatch.setattr(chat_generation_runs, "_SHUTDOWN_CANCEL_SECONDS", 0.5)
+
+ wedged = asyncio.Event()
+ release = asyncio.Event()
+
+ async def body():
+ yield 'data: {"choices":[{"delta":{"content":"a"}}]}\n\n'
+ wedged.set()
+ try:
+ await release.wait()
+ except (asyncio.CancelledError, GeneratorExit):
+ await release.wait()
+ raise
+ yield "data: [DONE]\n\n"
+
+ async def fake(_payload, _request, _subject, *, cancel_on_disconnect):
+ return SimpleNamespace(status_code = 200, body_iterator = body())
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ supervisor = ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))
+ supervisor.start("run-1", thread_id = "thread-1", model = "local.gguf")
+ await asyncio.wait_for(wedged.wait(), 10)
+
+ try:
+ await asyncio.wait_for(supervisor.stop(), timeout = 10)
+ finally:
+ release.set()
+ await asyncio.sleep(0)
diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.py
index aa5c0cdd1a3..a2a5ebfddda 100644
--- a/studio/backend/tests/test_chat_history_routes.py
+++ b/studio/backend/tests/test_chat_history_routes.py
@@ -98,6 +98,26 @@ def test_replace_thread_messages_reports_protected_research_turn(monkeypatch):
assert "Research prompts and responses" in str(exc_info.value.detail)
+def test_save_thread_message_forwards_explicit_generation_edit(monkeypatch):
+ monkeypatch.setattr(chat_history, "get_chat_thread", lambda _thread_id: {"id": "thread-1"})
+ captured = {}
+
+ def save(message, *, allow_generation_edit = False):
+ captured["allow_generation_edit"] = allow_generation_edit
+ return message
+
+ monkeypatch.setattr(chat_history, "upsert_chat_message", save)
+ payload = _message("assistant-1", "thread-1").model_copy(update = {"role": "assistant"})
+ chat_history.save_thread_message(
+ "thread-1",
+ "assistant-1",
+ payload,
+ allow_generation_edit = True,
+ current_subject = "test-user",
+ )
+ assert captured == {"allow_generation_edit": True}
+
+
def test_save_thread_message_returns_404_when_thread_is_deleted_during_write(monkeypatch):
parent_reads = iter(({"id": "thread-1"}, None))
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _thread_id: next(parent_reads))
@@ -205,10 +225,15 @@ def test_clear_history_fences_pending_thread_ids(monkeypatch):
captured: list[str] = []
captured_operation_ids: list[str | None] = []
- def clear_with_ids(thread_ids = (), operation_id = None):
+ def clear_with_ids(
+ thread_ids = (),
+ operation_id = None,
+ include_chat_generation_runs = False,
+ ):
captured.extend(thread_ids)
captured_operation_ids.append(operation_id)
- return list(thread_ids), [], False
+ result = (list(thread_ids), [])
+ return (*result, [], False) if include_chat_generation_runs else (*result, False)
async def remove_sandboxes(_thread_ids, _delete_files):
return 0, []
@@ -254,7 +279,9 @@ def test_clear_history_reaps_search_thumbnails_with_a_body(monkeypatch):
monkeypatch.setattr(
chat_history,
"clear_chat_history_with_replay_status",
- lambda thread_ids = (), operation_id = None: ([], [], False),
+ lambda thread_ids = (), operation_id = None, include_chat_generation_runs = False: (
+ ([], [], [], False) if include_chat_generation_runs else ([], [], False)
+ ),
)
monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)
monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)
diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.py
index 4df2bcedd41..0f7f5bdc7e7 100644
--- a/studio/backend/tests/test_chat_history_storage.py
+++ b/studio/backend/tests/test_chat_history_storage.py
@@ -802,10 +802,11 @@ def test_fork_chat_thread_detaches_research_run_metadata(tmp_path, monkeypatch):
def test_fork_detachment_detects_non_id_research_content_keys():
content_json, metadata_json = studio_db._detach_research_message_json(
'[{"type":"text","text":"Report","serverManaged":true}]',
- '{"model":"local-model"}',
+ '{"model":"local-model","generationRunId":"run-1","generationSeq":3}',
)
assert "serverManaged" not in content_json
+ assert "generationRunId" not in metadata_json
assert metadata_json == '{"model": "local-model"}'
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 627f2c47cd1..5cbd06ae99a 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -2216,7 +2216,7 @@ def test_chat_validates_non_system_message_before_auto_switch():
# A system-only chat must be rejected before the hook so an invalid request
# never swaps the resident model. Asserted on source order.
import inspect
- src = inspect.getsource(inference_route.openai_chat_completions)
+ src = inspect.getsource(inference_route.produce_openai_chat_completions)
assert src.index("At least one non-system message is required.") < src.index(
"_maybe_auto_switch_model"
)
@@ -2226,7 +2226,7 @@ def test_chat_untracks_external_provider_before_proxy():
# The external-provider branch must untrack the request before proxying so its
# stream can't block a concurrent local auto-switch.
import inspect
- src = inspect.getsource(inference_route.openai_chat_completions)
+ src = inspect.getsource(inference_route.produce_openai_chat_completions)
assert src.index("untrack_current_request") < src.index("_proxy_to_external_provider")
@@ -3557,7 +3557,7 @@ def test_chat_validates_confirm_and_modality_before_switch():
# the hook rejects a non-vision target before the load.
import inspect
- src = inspect.getsource(inference_route.openai_chat_completions)
+ src = inspect.getsource(inference_route.produce_openai_chat_completions)
assert src.index("confirm_tool_calls requires stream=true") < src.index(
"_maybe_auto_switch_model"
)
diff --git a/studio/backend/tests/test_orchestrator_load_cancel_event.py b/studio/backend/tests/test_orchestrator_load_cancel_event.py
new file mode 100644
index 00000000000..d6f9766a885
--- /dev/null
+++ b/studio/backend/tests/test_orchestrator_load_cancel_event.py
@@ -0,0 +1,44 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+
+import threading
+import time
+from types import SimpleNamespace
+
+from core.inference import orchestrator as orch_mod
+from core.inference.orchestrator import InferenceOrchestrator
+
+
+def test_safetensors_load_event_interrupts_worker_wait(monkeypatch):
+ orchestrator = InferenceOrchestrator.__new__(InferenceOrchestrator)
+ orchestrator.__dict__.update(
+ loading_models = set(), active_model_name = None, models = {}, _proc = None, _resp_queue = object()
+ )
+ cancel_event = threading.Event()
+ shutdowns = []
+ spawned = {"value": False}
+ monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *_a, **_k: ([], "auto"))
+ monkeypatch.setattr(orch_mod, "get_device", lambda: SimpleNamespace(value = "cpu"))
+ monkeypatch.setattr("utils.transformers_version.needs_transformers_5", lambda _model: False)
+ monkeypatch.setattr("utils.transformers_version.sidecar_swap_kind", lambda: None)
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: spawned["value"])
+ monkeypatch.setattr(
+ orchestrator, "_spawn_subprocess", lambda _config: spawned.__setitem__("value", True)
+ )
+ monkeypatch.setattr(orchestrator, "_read_resp", lambda timeout = 1: time.sleep(timeout) or None)
+ monkeypatch.setattr(
+ orchestrator, "_shutdown_subprocess", lambda timeout = 5: shutdowns.append(timeout) or True
+ )
+ timer = threading.Timer(0.05, cancel_event.set)
+ timer.start()
+ try:
+ started = time.monotonic()
+ loaded = orchestrator.load_model(
+ SimpleNamespace(identifier = "local.safetensors"), load_cancel_event = cancel_event
+ )
+ finally:
+ timer.cancel()
+ assert loaded is False
+ assert time.monotonic() - started < 0.5
+ assert shutdowns == [5]
+ assert orchestrator.loading_models == set()
+ assert orchestrator.models == {}
diff --git a/studio/backend/tests/test_preview_routes.py b/studio/backend/tests/test_preview_routes.py
index b59d9dcc099..beccc1b06bd 100644
--- a/studio/backend/tests/test_preview_routes.py
+++ b/studio/backend/tests/test_preview_routes.py
@@ -729,7 +729,7 @@ def test_cancelled_json_response_does_not_claim_slot(slot_state):
import inspect
import threading
- src = inspect.getsource(inference.openai_chat_completions)
+ src = inspect.getsource(inference.produce_openai_chat_completions)
assert src.count("_mark_cancelled_json_response_failed(request, cancel_event)") == 3
_reset_keepwarm_counters()
diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
index bdfccb47844..ceca5f50c05 100644
--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py
+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
@@ -468,7 +468,7 @@ def test_clearing_all_chats_cleans_up_their_sandboxes(tmp_path, monkeypatch):
import routes.chat_history as chat_history
monkeypatch.setattr(chat_history, "list_chat_threads", lambda: [{"id": "__LOCALID_bulk111"}])
- monkeypatch.setattr(chat_history, "clear_chat_history", lambda: ([], []))
+ monkeypatch.setattr(chat_history, "clear_chat_history", lambda **_kwargs: ([], [], []))
monkeypatch.setattr(chat_history, "_cancel_active_research", lambda request, ids: None)
import asyncio
@@ -2564,7 +2564,7 @@ def test_clearing_every_chat_reports_what_it_deleted(tmp_path, monkeypatch):
assert "return removed, active_runs, False" in source
route = inspect.getsource(chat_history.clear_history)
- assert "cleared, cleared_runs = clear_chat_history()" in route
+ assert "cleared, cleared_runs, cleared_chat_runs = clear_chat_history(" in route
assert "cleared" in route.split("_remove_sandboxes(", 1)[1].split(")", 1)[0]
@@ -2695,9 +2695,6 @@ def test_deleting_a_chat_stops_a_generation_that_would_recreate_it(monkeypatch):
import routes.chat_history as chat_history
cancelled = []
- monkeypatch.setattr(chat_history, "delete_chat_threads", lambda ids: None)
- monkeypatch.setattr(chat_history, "_cancel_active_research", lambda request, ids: None)
-
from state import active_generations
monkeypatch.setattr(active_generations, "cancel_thread", lambda tid: cancelled.append(tid) or 1)
@@ -3282,9 +3279,9 @@ def test_a_chat_started_during_the_clear_is_cancelled_too():
source = inspect.getsource(chat_history.clear_history)
assert "late" in source
- assert source.index("cleared, cleared_runs = clear_chat_history()") < source.index(
- "_cancel_active_generations(late)"
- )
+ assert source.index(
+ "cleared, cleared_runs, cleared_chat_runs = clear_chat_history("
+ ) < source.index("_cancel_active_generations(late)")
assert source.index("_cancel_active_generations(late)") < source.index("_remove_sandboxes(")
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 9705adf3e93..6a4b85d7d59 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -84,7 +84,6 @@ import {
isPromptCacheTtl,
loadExternalProviders,
parseExternalModelId,
-
providerModelSupportsStudioTools,
providerModelSupportsVision,
supportsProviderPromptCacheTtl,
@@ -94,13 +93,10 @@ import {
import {
addCodexReasoning,
-
codexLocalToolRoundId,
codexReasoningForToolCalls,
readCodexReasoning,
-
shouldReplayAssistantReasoning,
-
startsNewCodexToolRound,
type CodexReasoningLedger,
} from "../codex-reasoning";
@@ -151,7 +147,10 @@ import {
flushPendingChatSettings,
useChatRuntimeStore,
} from "../stores/chat-runtime-store";
-import { resolveFitMaxSeqLength, resolveManualAutoCtxPin } from "../presets/preset-policy";
+import {
+ resolveFitMaxSeqLength,
+ resolveManualAutoCtxPin,
+} from "../presets/preset-policy";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import { useExternalProvidersStore } from "../stores/external-providers-store";
import {
@@ -229,6 +228,11 @@ import {
rejectsAssistantPrefill,
resumesExactly,
} from "../utils/continuation";
+import {
+ generationChunkCountsTowardTiming,
+ generationChunkHasSubstantiveDelta,
+ generationIsSettled,
+} from "../utils/chat-generation-recovery";
import {
generateAudio,
GenerationLengthError,
@@ -258,11 +262,32 @@ import {
watchResearchRun,
} from "../stores/research-run-store";
import { cancelResearchRun, createResearchRun } from "./research-api";
+import {
+ cancelChatGenerationRun,
+ chatGenerationStopPlan,
+ isLegacyFallbackChatGenerationAdmissionError,
+ type ChatGenerationRun,
+ type ChatGenerationStatus,
+ createChatGenerationRunUntilAbort,
+ explicitStopSignal,
+ followChatGenerationRun,
+ supportsChatGenerationRuns,
+} from "./chat-generation-api";
// Small models (<=9B) answer from memory instead of calling search, so "auto"
// forces retrieval for them and leaves it to larger ones.
const AUTOINJECT_AUTO_MAX_SIZE_B = 9;
+class ChatGenerationTerminalError extends Error {
+ readonly generationStatus: "cancelled" | "failed";
+
+ constructor(generationStatus: "cancelled" | "failed", message: string) {
+ super(message);
+ this.name = "ChatGenerationTerminalError";
+ this.generationStatus = generationStatus;
+ }
+}
+
type ThreadRecordReader = () => Promise<ThreadRecord | undefined>;
function resolveAutoInject(mode: RagAutoInject, checkpoint: string): boolean {
@@ -460,7 +485,10 @@ function getNestedValue(
values: Record<string, unknown>,
path: string,
): unknown | undefined {
- const parts = path.split(".").map((part) => part.trim()).filter(Boolean);
+ const parts = path
+ .split(".")
+ .map((part) => part.trim())
+ .filter(Boolean);
if (parts.length === 0) {
return undefined;
}
@@ -680,8 +708,7 @@ function documentCitationToSource(
// Anthropic numbers inline [N] per citation, not per source URL.
// Fold citation type + position-bearing fields into the id so distinct
// citations on the same source keep separate Sources entries.
- const citationType =
- typeof cit.type === "string" ? String(cit.type) : "";
+ const citationType = typeof cit.type === "string" ? String(cit.type) : "";
const positionParts = [
cit.search_result_index,
cit.start_char_index,
@@ -1089,9 +1116,7 @@ function isSandboxWrapper(
return isSandboxToolResult(result);
}
-export function isMcpImageToolResult(
- val: unknown,
-): val is McpImageToolResult {
+export function isMcpImageToolResult(val: unknown): val is McpImageToolResult {
if (typeof val !== "object" || val === null) {
return false;
}
@@ -1217,7 +1242,6 @@ function setAssistantCodexReasoning(
message.extra_content = { ...extra, openai_codex_reasoning: reasoning };
}
-
function attachAssistantThoughtSignature(
messages: SerializedMessage[],
thoughtSignature: string | undefined,
@@ -1363,7 +1387,6 @@ function serializeAssistantReplayMessages(
continue;
}
-
const provenance = getToolReplayProvenance(toolPart);
const localRoundId = codexLocalToolRoundId(provenance);
if (
@@ -1694,7 +1717,8 @@ function extractVideoPartBase64(
): string | undefined {
if (!part || part.type !== "file") return undefined;
const filePart = part as unknown as { data?: string; mimeType?: string };
- if (!filePart.data || !/^video\//i.test(filePart.mimeType ?? "")) return undefined;
+ if (!filePart.data || !/^video\//i.test(filePart.mimeType ?? ""))
+ return undefined;
return filePart.data.startsWith("data:")
? filePart.data.split(",")[1]
: filePart.data;
@@ -1939,7 +1963,8 @@ async function resolveUseAdapter(
return undefined;
}
try {
- const thread = await (readThreadRecord?.() ?? getStoredChatThread(threadId));
+ const thread = await (readThreadRecord?.() ??
+ getStoredChatThread(threadId));
if (!thread?.pairId) {
return undefined;
}
@@ -2119,10 +2144,14 @@ function autoLoadCandidateKey(
return `${kind}:${normalizeTarget(id)}:${(ggufVariant ?? "").toLowerCase()}`;
}
-function hasBigEndianGgufMarker(filename: string, quant?: string | null): boolean {
+function hasBigEndianGgufMarker(
+ filename: string,
+ quant?: string | null,
+): boolean {
const normalized = filename.replace(/\\/g, "/").toLowerCase();
const separatorIndex = normalized.lastIndexOf("/");
- const basename = separatorIndex >= 0 ? normalized.slice(separatorIndex + 1) : normalized;
+ const basename =
+ separatorIndex >= 0 ? normalized.slice(separatorIndex + 1) : normalized;
const parent = separatorIndex >= 0 ? normalized.slice(0, separatorIndex) : "";
const stem = basename.replace(/\.[^.]*$/, "");
const quantKey = quant?.trim().toLowerCase() || "";
@@ -2136,7 +2165,9 @@ function hasBigEndianGgufMarker(filename: string, quant?: string | null): boolea
if (quantIndex >= 0 && quantIndex < (match.index ?? 0)) {
return true;
}
- const tail = stem.slice((match.index ?? 0) + match[0].length).replace(/^[._-]+/, "");
+ const tail = stem
+ .slice((match.index ?? 0) + match[0].length)
+ .replace(/^[._-]+/, "");
if (!tail || !GGUF_KNOWN_QUANT_RE.test(tail)) {
return !quantInParentOnly;
}
@@ -2279,12 +2310,11 @@ function snapshotVisibleModelState(
function restoreVisibleModelState(snapshot: VisibleModelStateSnapshot): void {
const liveUsage = useChatRuntimeStore.getState();
- liveUsage
- .setCheckpoint(snapshot.settings.params.checkpoint, undefined, {
- trackQueuedSettings: false,
- // The model being stepped off is the one the background load put there.
- persist: false,
- });
+ liveUsage.setCheckpoint(snapshot.settings.params.checkpoint, undefined, {
+ trackQueuedSettings: false,
+ // The model being stepped off is the one the background load put there.
+ persist: false,
+ });
useChatRuntimeStore.setState({
...snapshot.runtime,
...snapshot.settings,
@@ -2437,7 +2467,9 @@ function isAutoLoadableLocalRow(
// Reading only the field made such a row a Transformers source, which sends the
// safetensors context length to /load and remembers the wrong kind.
function isGgufLocalRow(row: LocalModelInfo): boolean {
- return row.model_format === "gguf" || row.path.toLowerCase().endsWith(".gguf");
+ return (
+ row.model_format === "gguf" || row.path.toLowerCase().endsWith(".gguf")
+ );
}
/** Chat-only installs run GGUF anywhere and MLX on a Mac; the picker hides
@@ -2891,12 +2923,18 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
function noteLoadFailure(label: string, error: unknown): void {
const detail =
- error instanceof Error && error.message.trim() ? error.message.trim() : "";
+ error instanceof Error && error.message.trim()
+ ? error.message.trim()
+ : "";
// loadModel also rejects before /api/inference/load is sent (dismissed token dialog, dead
// backend): those stop the Hub download, but must not blame the model.
- const marker = error as { unslothTransportFailure?: boolean; unslothUserCancelled?: boolean };
+ const marker = error as {
+ unslothTransportFailure?: boolean;
+ unslothUserCancelled?: boolean;
+ };
const blamesModel = !(
- marker?.unslothTransportFailure === true || marker?.unslothUserCancelled === true
+ marker?.unslothTransportFailure === true ||
+ marker?.unslothUserCancelled === true
);
loadFailure.current = {
label,
@@ -2992,7 +3030,10 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
const failureLabel = candidate.ggufVariant
? `${candidate.id} (${candidate.ggufVariant})`
: candidate.id;
- const { config } = resolveInitialConfig(candidate.id, candidate.ggufVariant);
+ const { config } = resolveInitialConfig(
+ candidate.id,
+ candidate.ggufVariant,
+ );
const effectiveMaxSeqLength = resolveLoadMaxSeqLength({
modelId: candidate.id,
ggufVariant: candidate.ggufVariant,
@@ -3104,9 +3145,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
// comes up as it did before the feature existed.
}
}
- const effectiveTensorParallel = isDiffusion
- ? false
- : config.tensorParallel;
+ const effectiveTensorParallel = isDiffusion ? false : config.tensorParallel;
// The diffusion runner has no projector to skip, so the toggle is inert there.
const effectiveDisableVision = isDiffusion ? false : config.disableVision;
const effectiveGpuIds =
@@ -3268,7 +3307,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
: { maxSeqLength: effectiveMaxSeqLength }),
maxTokens:
candidate.kind === "gguf"
- ? loadResp.context_length ?? 131072
+ ? (loadResp.context_length ?? 131072)
: effectiveMaxSeqLength,
},
{
@@ -3301,16 +3340,13 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
);
// Slots this auto-load committed. Diffusion ignores --parallel, so a count
// there would mint a phantom override a saved preset carries onto a GGUF.
- const committedSlots = (loadResp.is_diffusion ?? false)
- ? null
- : (config.nParallel ?? null);
+ const committedSlots =
+ (loadResp.is_diffusion ?? false) ? null : (config.nParallel ?? null);
// same rule for the batch sizes
- const committedNBatch = (loadResp.is_diffusion ?? false)
- ? null
- : (config.nBatch ?? null);
- const committedNUbatch = (loadResp.is_diffusion ?? false)
- ? null
- : (config.nUbatch ?? null);
+ const committedNBatch =
+ (loadResp.is_diffusion ?? false) ? null : (config.nBatch ?? null);
+ const committedNUbatch =
+ (loadResp.is_diffusion ?? false) ? null : (config.nUbatch ?? null);
useChatRuntimeStore.setState({
ggufContextLength: loadResp.context_length ?? 131072,
ggufMaxContextLength:
@@ -3352,8 +3388,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
// own model and config, so a stale true would show Vision off over a
// loaded projector, and the next Apply would send it.
disableVision: loadResp.disable_vision ?? false,
- loadedVisionDisabledByUser:
- loadResp.vision_disabled_by_user ?? false,
+ loadedVisionDisabledByUser: loadResp.vision_disabled_by_user ?? false,
...loadedGpuMemoryFields(loadResp),
loadedCustomContextLength: keepCustomCtx,
defaultChatTemplate: loadResp.chat_template ?? null,
@@ -3470,7 +3505,9 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
cachedModelsRunOnThisPlatform()
? allModelRepos.filter(isChattableCachedRepo)
: [],
- localRows.filter((row) => isAutoLoadableLocalRow(row, cachedInventoryFailed)),
+ localRows.filter((row) =>
+ isAutoLoadableLocalRow(row, cachedInventoryFailed),
+ ),
store.params.maxSeqLength,
options?.abortSignal,
),
@@ -3504,7 +3541,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
while (!autoLoadCancelled && loadAttempts < MAX_AUTO_LOAD_ATTEMPTS) {
const candidate = await resolveAutoLoadCandidate(
source,
- isRemembered ? lastLoaded?.ggufVariant ?? null : null,
+ isRemembered ? (lastLoaded?.ggufVariant ?? null) : null,
isTried,
);
options?.abortSignal?.throwIfAborted();
@@ -3667,11 +3704,9 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
persistGpuMemoryModeOnLoad(loadResp, rt.gpuMemoryMode);
useChatRuntimeStore
.getState()
- .setCheckpoint(
- DEFAULT_CHAT_MODEL_REPO,
- DEFAULT_CHAT_MODEL_VARIANT,
- { trackQueuedSettings: !options?.preserveVisibleSettings },
- );
+ .setCheckpoint(DEFAULT_CHAT_MODEL_REPO, DEFAULT_CHAT_MODEL_VARIANT, {
+ trackQueuedSettings: !options?.preserveVisibleSettings,
+ });
const store = useChatRuntimeStore.getState();
store.setModelRequiresTrustRemoteCode(
loadResp.requires_trust_remote_code ?? false,
@@ -3702,46 +3737,48 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
store.setModels([...store.models, defaultModel]);
}
useChatRuntimeStore.setState({
- ggufContextLength: loadResp.context_length ?? 131072,
- ggufMaxContextLength:
- loadResp.max_context_length ?? loadResp.context_length ?? 131072,
- supportsReasoning: loadResp.supports_reasoning ?? false,
- reasoningAlwaysOn: loadResp.reasoning_always_on ?? false,
- reasoningEnabled: loadResp.supports_reasoning ?? false,
- ...reasoningCapsFromLoad(loadResp),
- supportsPreserveThinking: loadResp.supports_preserve_thinking ?? false,
- preserveThinking: resolvePreserveThinkingOnLoad(loadResp),
- supportsTools: loadResp.supports_tools ?? false,
- ...resolveToolsEnabledOnLoad(loadResp.supports_tools ?? false),
- kvCacheDtype: loadResp.cache_type_kv ?? null,
- loadedKvCacheDtype: loadResp.cache_type_kv ?? null,
- ...mlxRuntimeStateFrom(loadResp),
- // The request above omits n_parallel: a staged override left from a
- // preset would read as applied and be re-sent by the next Apply.
- nParallel: null,
- loadedNParallel: null,
- nBatch: null,
- loadedNBatch: null,
- nUbatch: null,
- loadedNUbatch: null,
- ...clearedServerTuningState(),
- tensorParallel: loadResp.tensor_parallel ?? false,
- loadedTensorParallel: loadResp.tensor_parallel ?? false,
- loadedDisableVision: loadResp.disable_vision ?? false,
- // The request above omits disable_vision, so the echo is what the load
- // ran with; adopting it stops a previous model's Vision-off carrying over.
- disableVision: loadResp.disable_vision ?? false,
- loadedVisionDisabledByUser: loadResp.vision_disabled_by_user ?? false,
- ...loadedGpuMemoryFields(loadResp),
- // Drives the GPU Memory controls' diffusion gate; set alongside the
- // GPU fields on every load path so the gate can't read stale.
- loadedIsDiffusion: loadResp.is_diffusion ?? false,
- defaultChatTemplate: loadResp.chat_template ?? null,
- chatTemplateOverride: null,
- loadedIsMultimodal: isMultimodalResponse(loadResp),
- mmprojFallbackReason: loadResp.mmproj_fallback_reason ?? null,
- activeModelIsLocal: loadResp.is_local_model ?? false,
- ...resolveLoadedSpeculativeSettings(loadResp),
+ ggufContextLength: loadResp.context_length ?? 131072,
+ ggufMaxContextLength:
+ loadResp.max_context_length ?? loadResp.context_length ?? 131072,
+ supportsReasoning: loadResp.supports_reasoning ?? false,
+ reasoningAlwaysOn: loadResp.reasoning_always_on ?? false,
+ reasoningEnabled: loadResp.supports_reasoning ?? false,
+ ...reasoningCapsFromLoad(loadResp),
+ supportsPreserveThinking:
+ loadResp.supports_preserve_thinking ?? false,
+ preserveThinking: resolvePreserveThinkingOnLoad(loadResp),
+ supportsTools: loadResp.supports_tools ?? false,
+ ...resolveToolsEnabledOnLoad(loadResp.supports_tools ?? false),
+ kvCacheDtype: loadResp.cache_type_kv ?? null,
+ loadedKvCacheDtype: loadResp.cache_type_kv ?? null,
+ ...mlxRuntimeStateFrom(loadResp),
+ // The request above omits n_parallel: a staged override left from a
+ // preset would read as applied and be re-sent by the next Apply.
+ nParallel: null,
+ loadedNParallel: null,
+ nBatch: null,
+ loadedNBatch: null,
+ nUbatch: null,
+ loadedNUbatch: null,
+ ...clearedServerTuningState(),
+ tensorParallel: loadResp.tensor_parallel ?? false,
+ loadedTensorParallel: loadResp.tensor_parallel ?? false,
+ loadedDisableVision: loadResp.disable_vision ?? false,
+ // The request above omits disable_vision, so the echo is what the load
+ // ran with; adopting it stops a previous model's Vision-off carrying over.
+ disableVision: loadResp.disable_vision ?? false,
+ loadedVisionDisabledByUser:
+ loadResp.vision_disabled_by_user ?? false,
+ ...loadedGpuMemoryFields(loadResp),
+ // Drives the GPU Memory controls' diffusion gate; set alongside the
+ // GPU fields on every load path so the gate can't read stale.
+ loadedIsDiffusion: loadResp.is_diffusion ?? false,
+ defaultChatTemplate: loadResp.chat_template ?? null,
+ chatTemplateOverride: null,
+ loadedIsMultimodal: isMultimodalResponse(loadResp),
+ mmprojFallbackReason: loadResp.mmproj_fallback_reason ?? null,
+ activeModelIsLocal: loadResp.is_local_model ?? false,
+ ...resolveLoadedSpeculativeSettings(loadResp),
});
recordLastLocalModelLoad({
id: DEFAULT_CHAT_MODEL_REPO,
@@ -3776,9 +3813,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
}
}
-async function resolveQueuedEmptyLocalModel(
- abortSignal: AbortSignal,
-): Promise<{
+async function resolveQueuedEmptyLocalModel(abortSignal: AbortSignal): Promise<{
loaded: boolean;
blockedByTrustRemoteCode: boolean;
loadFailureReported?: boolean;
@@ -3967,12 +4002,8 @@ export function createOpenAIStreamAdapter(
? async () => (await sharedThreadRecordRead()).thread
: undefined;
const releaseCurrentPreStreamRun = () =>
- releasePreStreamRunForThreadIds([
- unstable_threadId,
- resolvedThreadId,
- ]);
- const queuedRunSettings =
- consumeQueuedChatRunSettings(resolvedThreadId);
+ releasePreStreamRunForThreadIds([unstable_threadId, resolvedThreadId]);
+ const queuedRunSettings = consumeQueuedChatRunSettings(resolvedThreadId);
let queuedEmptyModelRuntime: QueuedResolvedModelRuntime | null = null;
const persistResolvedQueuedModel = async (
modelId: string,
@@ -4103,7 +4134,9 @@ export function createOpenAIStreamAdapter(
"Deep research could not bind its assistant message. Please retry the send.",
);
}
- const userMessage = [...messages].reverse().find((m) => m.role === "user");
+ const userMessage = [...messages]
+ .reverse()
+ .find((m) => m.role === "user");
if (!userMessage) throw new Error("Research requires a user message.");
const userMessageIndex = messages.indexOf(userMessage);
const userMessageParentId =
@@ -4114,10 +4147,12 @@ export function createOpenAIStreamAdapter(
runtime.activeGgufVariant,
);
const selectedCheckpoint = params.checkpoint.trim();
- const researchExternalSelection = parseExternalModelId(selectedCheckpoint);
+ const researchExternalSelection =
+ parseExternalModelId(selectedCheckpoint);
const researchExternalProvider = researchExternalSelection
? loadExternalProviders().find(
- (provider) => provider.id === researchExternalSelection.providerId,
+ (provider) =>
+ provider.id === researchExternalSelection.providerId,
)
: null;
if (
@@ -4173,10 +4208,10 @@ export function createOpenAIStreamAdapter(
? runtime.ragEnabled && runtime.ragSource.type === "kb"
? {
kb_id: runtime.ragSource.kbId,
- default_top_k: runtime.ragTopK,
- mode: runtime.ragMode,
- autoinject: runtime.ragAutoInject,
- autoinject_min_score: runtime.ragAutoInjectMinScore,
+ default_top_k: runtime.ragTopK,
+ mode: runtime.ragMode,
+ autoinject: runtime.ragAutoInject,
+ autoinject_min_score: runtime.ragAutoInjectMinScore,
}
: {
...(runtime.ragEnabled
@@ -4185,10 +4220,10 @@ export function createOpenAIStreamAdapter(
...(projectRagEnabled && researchProjectId
? { project_id: researchProjectId }
: {}),
- default_top_k: runtime.ragTopK,
- mode: runtime.ragMode,
- autoinject: runtime.ragAutoInject,
- autoinject_min_score: runtime.ragAutoInjectMinScore,
+ default_top_k: runtime.ragTopK,
+ mode: runtime.ragMode,
+ autoinject: runtime.ragAutoInject,
+ autoinject_min_score: runtime.ragAutoInjectMinScore,
}
: undefined;
@@ -4207,7 +4242,9 @@ export function createOpenAIStreamAdapter(
};
runtime.registerThreadServerCancel(threadKey, researchServerCancel);
releaseCurrentPreStreamRun();
- runtime.setThreadRunning(threadKey, true, { owner: researchServerCancel });
+ runtime.setThreadRunning(threadKey, true, {
+ owner: researchServerCancel,
+ });
let report = "";
let releaseResearchFollow: (() => void) | null = null;
const researchFollowController = new AbortController();
@@ -4217,13 +4254,15 @@ export function createOpenAIStreamAdapter(
const forwardAdapterAbort = () => {
researchFollowController.abort(abortSignal.reason);
};
- abortSignal.addEventListener("abort", forwardAdapterAbort, { once: true });
+ abortSignal.addEventListener("abort", forwardAdapterAbort, {
+ once: true,
+ });
try {
// The normal history adapter persists messages after model execution,
// but research validates the user message before it can start.
- const storedUserMessage = (await listStoredChatMessages(resolvedThreadId)).find(
- (message) => message.id === userMessage.id,
- );
+ const storedUserMessage = (
+ await listStoredChatMessages(resolvedThreadId)
+ ).find((message) => message.id === userMessage.id);
await saveStoredChatMessage({
id: userMessage.id,
threadId: resolvedThreadId,
@@ -4306,14 +4345,19 @@ export function createOpenAIStreamAdapter(
};
}
} catch (error) {
- if (!abortSignal.aborted && !researchFollowController.signal.aborted) {
+ if (
+ !abortSignal.aborted &&
+ !researchFollowController.signal.aborted
+ ) {
throw error;
}
} finally {
abortSignal.removeEventListener("abort", forwardAdapterAbort);
releaseResearchFollow?.();
runtime.clearThreadServerCancel(threadKey, researchServerCancel);
- runtime.setThreadRunning(threadKey, false, { owner: researchServerCancel });
+ runtime.setThreadRunning(threadKey, false, {
+ owner: researchServerCancel,
+ });
}
};
const deepResearchHandoff = newDeepResearchHandoff();
@@ -4569,7 +4613,6 @@ export function createOpenAIStreamAdapter(
isExternalRequest &&
!externalApiKey &&
!externalProvider?.hasApiKey &&
-
!externalProviderUsesOAuth &&
!externalProviderIsCustom &&
!externalProviderIsGeminiCustomBase
@@ -4636,14 +4679,16 @@ export function createOpenAIStreamAdapter(
// boundaries, not two spellings of one feature, so the stored pill keeps
// meaning the provider's sandbox wherever it meant that before the Unsloth
// loop reached these providers. See code-tool-placement.ts.
- const { local: studioLocalCodeTools, hosted: hostedCodeToolsForThisTurn } =
- selectCodeToolNames({
- codeToolsEnabled,
- hostedCodeExecutionForThisTurn: codeExecEnabledForThisTurn,
- providerHostsCodeExecution: providerHostsCodeExecution(
- externalProvider?.providerType,
- ),
- });
+ const {
+ local: studioLocalCodeTools,
+ hosted: hostedCodeToolsForThisTurn,
+ } = selectCodeToolNames({
+ codeToolsEnabled,
+ hostedCodeExecutionForThisTurn: codeExecEnabledForThisTurn,
+ providerHostsCodeExecution: providerHostsCodeExecution(
+ externalProvider?.providerType,
+ ),
+ });
if (selectedImageEditReference && !imageGenerationEnabledForThisTurn) {
clearSelectedImageEditReference();
@@ -4663,9 +4708,7 @@ export function createOpenAIStreamAdapter(
// follow-ups; the backend Gemini translator rebuilds the
// functionCall / functionResponse parts (with thoughtSignature).
const outboundMessages = survivingMessages
- .flatMap((message) =>
- toOpenAIMessages(message, !isExternalRequest),
- )
+ .flatMap((message) => toOpenAIMessages(message, !isExternalRequest))
.filter((message): message is NonNullable<typeof message> =>
Boolean(message),
);
@@ -4943,6 +4986,51 @@ export function createOpenAIStreamAdapter(
const activeModel = runtime.models.find(
(m) => m.id === params.checkpoint,
);
+ const generationUserMessage = [...survivingMessages]
+ .reverse()
+ .find((message) => message.role === "user");
+ const generationCandidate = Boolean(
+ !isExternalRequest &&
+ !activeModel?.isAudio &&
+ !runtime.loadedIsDiffusion &&
+ !imageBase64 &&
+ !audioBase64 &&
+ !videoBase64 &&
+ // Continue seeds the partial into the sibling assistant and yields it before the
+ // request starts, so the autosave can land before admission does. Admission
+ // refuses a substantive placeholder with a 409, which is not a fallback error,
+ // and the turn would fail outright. Continuations keep the legacy stream.
+ !continuation &&
+ resolvedThreadId &&
+ !isThreadIncognito(resolvedThreadId) &&
+ unstable_assistantMessageId &&
+ generationUserMessage,
+ );
+ let generationDecision: "pending" | "durable" | "legacy" =
+ generationCandidate ? "pending" : "legacy";
+ let generationRun: ChatGenerationRun | null = null;
+ let generationRunId: string | null = null;
+ let generationSeq = 0;
+ let generationStatus: ChatGenerationStatus | null = null;
+ let generationFirstChunkAt: number | undefined;
+ let generationChunkCount = 0;
+ let generationStopRequested = false;
+ const generationCustom = () =>
+ generationRunId
+ ? {
+ generationRunId,
+ generationSeq,
+ generationStatus,
+ generationFirstChunkAt,
+ generationChunkCount,
+ generationSettled: generationIsSettled(
+ generationStatus,
+ generationSeq,
+ generationRun?.lastEventSeq ?? Number.POSITIVE_INFINITY,
+ ),
+ serverManaged: true,
+ }
+ : {};
if (activeModel?.isAudio && !activeModel?.hasAudioInput) {
const audioCancel = () => runAbort.abort();
runtime.registerThreadServerCancel(threadKey, audioCancel);
@@ -5119,6 +5207,7 @@ export function createOpenAIStreamAdapter(
openaiCodexReasoning: codexReasoningLedger,
contextTruncation,
incomplete: { reason: "cancelled" as const },
+ ...generationCustom(),
});
// Why this turn stopped early. Drives the Continue affordance.
let incompleteReason: IncompleteReason | null = null;
@@ -5305,6 +5394,15 @@ export function createOpenAIStreamAdapter(
if ((runSignal.reason as { detach?: boolean } | undefined)?.detach) {
return;
}
+ generationStopRequested = true;
+ const stopPlan = chatGenerationStopPlan(
+ generationDecision,
+ generationRunId,
+ );
+ if (stopPlan.cancelRunId) {
+ void cancelChatGenerationRun(stopPlan.cancelRunId).catch(() => {});
+ }
+ if (!stopPlan.postLegacyCancel) return;
const body: Record<string, string> = { cancel_id: cancelId };
if (sandboxSessionId) body.session_id = sandboxSessionId;
// Plain fetch, not authFetch: authFetch redirects to login on
@@ -5359,9 +5457,7 @@ export function createOpenAIStreamAdapter(
params.checkpoint ||
"Unknown model",
responseModelId:
- responseModelId ||
- externalSelection?.modelId ||
- params.checkpoint,
+ responseModelId || externalSelection?.modelId || params.checkpoint,
...(externalProvider?.id ? { providerId: externalProvider.id } : {}),
providerName:
externalProvider?.name ??
@@ -5391,10 +5487,10 @@ export function createOpenAIStreamAdapter(
codeExecEnabledForThisTurn ||
(!isExternalRequest && supportsTools && codeToolsEnabled),
images: imageGenerationEnabledForThisTurn,
- mcp:
- supportsStudioToolsForThisTurn && mcpEnabledForChat,
+ mcp: supportsStudioToolsForThisTurn && mcpEnabledForChat,
docs:
- supportsStudioToolsForThisTurn && (ragEnabled || projectRagEnabled),
+ supportsStudioToolsForThisTurn &&
+ (ragEnabled || projectRagEnabled),
artifacts: renderHtmlToolEnabledForThisTurn,
confirmToolCalls,
bypassPermissions,
@@ -5668,8 +5764,12 @@ export function createOpenAIStreamAdapter(
// older bundle sent meaning hosted search, so without this
// flag Search silently stayed hosted.
run_tools_locally: true,
- ...(sandboxSessionId ? { session_id: sandboxSessionId } : {}),
- ...(resolvedThreadId ? { thread_id: resolvedThreadId } : {}),
+ ...(sandboxSessionId
+ ? { session_id: sandboxSessionId }
+ : {}),
+ ...(resolvedThreadId
+ ? { thread_id: resolvedThreadId }
+ : {}),
...(ragEnabled || projectRagEnabled
? {
rag_scope: {
@@ -5780,7 +5880,11 @@ export function createOpenAIStreamAdapter(
: {
reasoning_effort: fallbackExternalEffort,
}
- : { thinking: { type: reasoningEnabled ? "enabled" : "disabled" } }
+ : {
+ thinking: {
+ type: reasoningEnabled ? "enabled" : "disabled",
+ },
+ }
: {}),
};
}
@@ -5906,7 +6010,9 @@ export function createOpenAIStreamAdapter(
? { whole_doc: false }
: {}),
context_length:
- runtime.ggufContextLength ?? params.maxSeqLength ?? undefined,
+ runtime.ggufContextLength ??
+ params.maxSeqLength ??
+ undefined,
},
}
: {}),
@@ -5940,7 +6046,104 @@ export function createOpenAIStreamAdapter(
clearSelectedImageEditReference();
requestedMaxTokens = requestPayload.max_tokens;
await ThreadAutosaveHandle.awaitFirstSave(resolvedThreadId);
- const stream = streamChatCompletions(requestPayload, runSignal);
+ if (generationDecision === "pending") {
+ const clientTools = (
+ requestPayload as unknown as { tools?: unknown }
+ ).tools;
+ if (
+ requestPayload.enable_tools === true ||
+ (Array.isArray(clientTools) && clientTools.length > 0)
+ ) {
+ // Confirmation and browser-executed tool chains still use the
+ // subscriber-owned stream in this PR.
+ generationDecision = "legacy";
+ } else {
+ const admission = explicitStopSignal(runSignal);
+ const supported = await supportsChatGenerationRuns(
+ resolvedThreadId!,
+ admission.signal,
+ ).finally(admission.dispose);
+ if (!supported) {
+ generationDecision = "legacy";
+ } else {
+ generationDecision = "durable";
+ try {
+ generationRun = await createChatGenerationRunUntilAbort(
+ {
+ runId: cancelId,
+ threadId: resolvedThreadId!,
+ userMessageId: generationUserMessage!.id,
+ assistantMessageId: unstable_assistantMessageId!,
+ requestPayload,
+ },
+ runSignal,
+ );
+ } catch (error) {
+ if (!isLegacyFallbackChatGenerationAdmissionError(error)) {
+ throw error;
+ }
+ // Durable recovery does not yet replay server-side tool events.
+ // Use the subscriber-owned stream for this policy-forced case.
+ generationDecision = "legacy";
+ }
+ if (!generationRun) {
+ if (generationDecision === "durable") return;
+ } else {
+ generationRunId = generationRun.id;
+ generationStatus = generationRun.status;
+ if (generationStopRequested) {
+ void cancelChatGenerationRun(generationRun.id).catch(
+ () => {},
+ );
+ }
+ }
+ }
+ }
+ }
+
+ const durableStream = async function* () {
+ for await (const update of followChatGenerationRun(
+ generationRunId!,
+ {
+ initialRun: generationRun!,
+ replayFrom: 0,
+ signal: runSignal,
+ },
+ )) {
+ generationRun = update.run;
+ generationStatus = update.run.status;
+ if (update.event) {
+ generationSeq = Math.max(generationSeq, update.event.seq);
+ if (update.event.type === "chunk") {
+ const chunk = update.event.payload as OpenAIChatChunk;
+ if (generationChunkCountsTowardTiming(chunk)) {
+ generationChunkCount += 1;
+ if (generationChunkHasSubstantiveDelta(chunk)) {
+ generationFirstChunkAt ??= update.event.createdAt;
+ }
+ }
+ yield chunk;
+ }
+ }
+ }
+ if (generationStatus === "failed") {
+ throw new ChatGenerationTerminalError(
+ "failed",
+ generationRun?.error ||
+ "The Studio backend restarted during generation.",
+ );
+ }
+ if (generationStatus === "cancelled" && !runSignal.aborted) {
+ throw new ChatGenerationTerminalError(
+ "cancelled",
+ "Generation was cancelled.",
+ );
+ }
+ };
+ const stream =
+ generationDecision === "durable"
+ ? durableStream()
+ : streamChatCompletions(requestPayload, runSignal);
// Per run, not per module: two turns must not share a cycle.
const canPublish = createStreamPublishGate();
@@ -6003,9 +6206,7 @@ export function createOpenAIStreamAdapter(
const reasoningMs = (
chunk as { _reasoningDurationMs?: number } | null | undefined
)?._reasoningDurationMs;
- if (
- reasoningDurationTracker.recordServerDuration(reasoningMs)
- ) {
+ if (reasoningDurationTracker.recordServerDuration(reasoningMs)) {
continue;
}
@@ -6196,8 +6397,7 @@ export function createOpenAIStreamAdapter(
? `${toolConfirmationScopeId}:${approvalId}`
: backendToolCallId
? resolveToolPartId(backendToolCallId)
- : approvalId ||
- `${toolEvent.tool_name}_${Date.now()}`;
+ : approvalId || `${toolEvent.tool_name}_${Date.now()}`;
if (awaitingConfirmation && backendToolCallId) {
toolConfirmationIdsByBackendId.set(backendToolCallId, id);
}
@@ -6331,7 +6531,8 @@ export function createOpenAIStreamAdapter(
text: rawResult.slice(0, mcpImgIdx),
images,
};
- if (isMcpImageToolResult(candidate)) mcpImages = candidate;
+ if (isMcpImageToolResult(candidate))
+ mcpImages = candidate;
} catch {
// Not a valid envelope; fall through below.
}
@@ -6551,10 +6752,8 @@ export function createOpenAIStreamAdapter(
}
const rawDelta = chunk.choices?.[0]?.delta?.content;
// Normalize structured delta.content (mistral magistral).
- const {
- text: delta,
- structuredReasoningContinues,
- } = extractDeltaText(rawDelta);
+ const { text: delta, structuredReasoningContinues } =
+ extractDeltaText(rawDelta);
// Latest Gemini text-part thoughtSignature for next-turn replay.
const deltaExtraContent = (
chunk.choices?.[0]?.delta as
@@ -6566,17 +6765,24 @@ export function createOpenAIStreamAdapter(
// replay. Pace previews, never state.
let replayStateChanged = false;
if (deltaExtraContent && typeof deltaExtraContent === "object") {
- const extraRecord = deltaExtraContent as Record<string, unknown>;
+ const extraRecord = deltaExtraContent as Record<
+ string,
+ unknown
+ >;
const eGoogle = extraRecord.google;
if (eGoogle && typeof eGoogle === "object") {
- const sig = (eGoogle as Record<string, unknown>).thought_signature;
+ const sig = (eGoogle as Record<string, unknown>)
+ .thought_signature;
if (typeof sig === "string" && sig) {
replayStateChanged ||= sig !== latestTextThoughtSignature;
latestTextThoughtSignature = sig;
}
}
const codexReasoning = extraRecord.openai_codex_reasoning;
- if (Array.isArray(codexReasoning) && codexReasoning.length > 0) {
+ if (
+ Array.isArray(codexReasoning) &&
+ codexReasoning.length > 0
+ ) {
codexReasoningLedger = addCodexReasoning(
codexReasoningLedger,
codexReasoning,
@@ -6719,7 +6925,8 @@ export function createOpenAIStreamAdapter(
toolCallParts[existingIndex] = updated;
} else {
const callId =
- stablePartId || `tool_call_${idx ?? toolCallParts.length}`;
+ stablePartId ||
+ `tool_call_${idx ?? toolCallParts.length}`;
if (!codexRoundToolCallIds.includes(callId)) {
codexRoundToolCallIds.push(callId);
@@ -6833,8 +7040,7 @@ export function createOpenAIStreamAdapter(
const parsedReasoningGroupCount =
countReasoningGroups(assistantContent);
if (
- parsedReasoningGroupCount >
- reasoningDurationTracker.groupCount
+ parsedReasoningGroupCount > reasoningDurationTracker.groupCount
) {
reasoningDurationTracker.startGroup(
parsedReasoningGroupCount - 1,
@@ -7044,7 +7250,8 @@ export function createOpenAIStreamAdapter(
}
if (
usageThreadIsVisible &&
- useChatRuntimeStore.getState().params.checkpoint === params.checkpoint
+ useChatRuntimeStore.getState().params.checkpoint ===
+ params.checkpoint
) {
useChatRuntimeStore.getState().setContextUsage(usage);
}
@@ -7188,7 +7395,9 @@ export function createOpenAIStreamAdapter(
openaiCodexReasoning: codexReasoningLedger,
contextTruncation,
- incomplete: incompleteReason ? { reason: incompleteReason } : undefined,
+ incomplete: incompleteReason
+ ? { reason: incompleteReason }
+ : undefined,
// Persisted refusal flag driving the two-pass prune.
anthropicRefusal: anthropicRefusalSeen || undefined,
serverTimings: meta?.timings ?? undefined,
@@ -7204,6 +7413,7 @@ export function createOpenAIStreamAdapter(
: undefined,
responseDetails: buildResponseDetails(finishedAt),
timing: finalTiming,
+ ...generationCustom(),
},
},
};
@@ -7221,6 +7431,15 @@ export function createOpenAIStreamAdapter(
"chat Settings or turn off thinking, then retry.",
duration: 8000,
});
+ } else if (err instanceof ChatGenerationTerminalError) {
+ if (err.generationStatus === "failed") {
+ toast.error("Response interrupted", {
+ description:
+ err.message ||
+ "The Studio backend stopped during generation.",
+ duration: 8000,
+ });
+ }
} else if (err instanceof StreamInterruptedError) {
// Connection dropped mid-turn: surface it explicitly (the rethrow
// below also marks the message with an inline error + Retry).
@@ -7320,9 +7539,13 @@ export function createOpenAIStreamAdapter(
reason:
err instanceof GenerationLengthError
? "length"
- : "interrupted",
+ : err instanceof ChatGenerationTerminalError &&
+ err.generationStatus === "cancelled"
+ ? "cancelled"
+ : "interrupted",
},
timing: partialTiming,
+ ...generationCustom(),
},
},
};
@@ -7381,8 +7604,7 @@ export function createOpenAIStreamAdapter(
args.unstable_threadId,
useChatRuntimeStore.getState().activeThreadId,
);
- const reservationToken =
- findPreStreamRunReservation(preStreamThreadIds);
+ const reservationToken = findPreStreamRunReservation(preStreamThreadIds);
if (reservationToken) {
adoptPreStreamRunReservation(reservationToken, preStreamThreadIds);
}
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 6eefe685cd4..e56fa134c1b 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -1107,10 +1107,13 @@ export async function getChatMessage(
export async function saveChatMessage(
message: MessageRecord,
- options: { coalesce?: boolean } = {},
+ options: { allowGenerationEdit?: boolean; coalesce?: boolean } = {},
): Promise<MessageRecord> {
+ const editQuery = options.allowGenerationEdit
+ ? "?allowGenerationEdit=true"
+ : "";
const response = await authFetch(
- `/api/chat/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.id)}`,
+ `/api/chat/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.id)}${editQuery}`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
@@ -1127,7 +1130,7 @@ export async function saveChatMessage(
export async function syncChatMessages(
threadId: string,
messages: MessageRecord[],
- options: { pruneMissing?: boolean } = {},
+ options: { pruneMissing?: boolean; deletedMessageIds?: string[] } = {},
): Promise<MessageRecord[]> {
const response = await threadWriteFetch(
`/api/chat/threads/${encodeURIComponent(threadId)}/messages`,
@@ -1137,6 +1140,7 @@ export async function syncChatMessages(
body: JSON.stringify({
messages,
pruneMissing: options.pruneMissing ?? false,
+ deletedMessageIds: options.deletedMessageIds ?? [],
}),
},
);
diff --git a/studio/frontend/src/features/chat/api/chat-generation-api.ts b/studio/frontend/src/features/chat/api/chat-generation-api.ts
new file mode 100644
index 00000000000..aff2dc13553
--- /dev/null
+++ b/studio/frontend/src/features/chat/api/chat-generation-api.ts
@@ -0,0 +1,432 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// eslint-disable-next-line no-restricted-imports -- Avoid the auth barrel's React login page.
+import { authFetch } from "@/features/auth/api";
+import type {
+ OpenAIChatChunk,
+ OpenAIChatCompletionsRequest,
+} from "../types/api";
+
+export type ChatGenerationStatus =
+ | "queued"
+ | "running"
+ | "cancelling"
+ | "cancelled"
+ | "completed"
+ | "failed";
+
+export interface ChatGenerationRun {
+ id: string;
+ threadId: string;
+ userMessageId: string;
+ assistantMessageId: string;
+ requestHash: string;
+ requestPayload: OpenAIChatCompletionsRequest;
+ status: ChatGenerationStatus;
+ cancelRequested: boolean;
+ lastEventSeq: number;
+ finishReason: string | null;
+ error: string | null;
+ createdAt: number;
+ updatedAt: number;
+ startedAt: number | null;
+ completedAt: number | null;
+ created?: boolean;
+}
+
+export interface CreateChatGenerationRunInput {
+ runId: string;
+ threadId: string;
+ userMessageId: string;
+ assistantMessageId: string;
+ requestPayload: OpenAIChatCompletionsRequest;
+}
+
+export interface ChatGenerationEvent {
+ seq: number;
+ type: string;
+ payload: OpenAIChatChunk | Record<string, unknown>;
+ createdAt: number;
+ run?: ChatGenerationRun;
+}
+
+export interface ChatGenerationRunUpdate {
+ run: ChatGenerationRun;
+ event?: ChatGenerationEvent;
+ source: "snapshot" | "event";
+}
+
+export function normalizeChatGenerationChunkPayload(
+ payload: OpenAIChatChunk | Record<string, unknown>,
+): OpenAIChatChunk | Record<string, unknown> {
+ if (
+ payload !== null &&
+ typeof payload === "object" &&
+ "type" in payload &&
+ payload.type === "reasoning_summary"
+ ) {
+ return {
+ _reasoningDurationMs: (payload as { duration_ms?: unknown }).duration_ms,
+ } as unknown as OpenAIChatChunk;
+ }
+ return payload;
+}
+
+const TERMINAL_STATUSES = new Set<ChatGenerationStatus>([
+ "cancelled",
+ "completed",
+ "failed",
+]);
+
+export class ChatGenerationApiError extends Error {
+ readonly status: number;
+
+ constructor(message: string, status: number) {
+ super(message);
+ this.name = "ChatGenerationApiError";
+ this.status = status;
+ }
+}
+
+export function isToolEnabledChatGenerationAdmissionError(
+ error: unknown,
+): boolean {
+ return (
+ error instanceof ChatGenerationApiError &&
+ error.status === 400 &&
+ error.message === "Tool-enabled chat runs use the legacy streaming path"
+ );
+}
+
+export function isLegacyFallbackChatGenerationAdmissionError(
+ error: unknown,
+): boolean {
+ return (
+ isToolEnabledChatGenerationAdmissionError(error) ||
+ (error instanceof ChatGenerationApiError &&
+ error.status === 400 &&
+ error.message === "Credentials cannot be persisted") ||
+ (error instanceof ChatGenerationApiError &&
+ error.status === 404 &&
+ error.message === "Thread not found") ||
+ (error instanceof ChatGenerationApiError &&
+ error.status === 400 &&
+ error.message ===
+ "userMessageId must identify a user message in the thread")
+ );
+}
+
+async function json<T>(response: Response): Promise<T> {
+ const body = await response.json().catch(() => null);
+ if (!response.ok) {
+ const detail = (body as { detail?: unknown; message?: unknown } | null)
+ ?.detail;
+ const message = (body as { message?: unknown } | null)?.message;
+ throw new ChatGenerationApiError(
+ typeof detail === "string"
+ ? detail
+ : typeof message === "string"
+ ? message
+ : `Chat generation request failed (${response.status})`,
+ response.status,
+ );
+ }
+ return body as T;
+}
+
+function isPermanent(error: unknown): boolean {
+ return (
+ error instanceof ChatGenerationApiError &&
+ error.status >= 400 &&
+ error.status < 500 &&
+ error.status !== 408 &&
+ error.status !== 429
+ );
+}
+
+function reconnectDelay(failures: number): number {
+ return Math.min(8_000, 500 * 2 ** Math.max(0, failures - 1));
+}
+
+function waitForReconnect(ms: number, signal?: AbortSignal): Promise<void> {
+ if (signal?.aborted) return Promise.resolve();
+ return new Promise((resolve) => {
+ const finish = () => {
+ globalThis.clearTimeout(timer);
+ signal?.removeEventListener("abort", finish);
+ resolve();
+ };
+ const timer = globalThis.setTimeout(finish, ms);
+ signal?.addEventListener("abort", finish, { once: true });
+ });
+}
+
+export function isTerminalChatGenerationRun(run: ChatGenerationRun): boolean {
+ return TERMINAL_STATUSES.has(run.status);
+}
+
+/** Where a Stop has to be sent, given how far durable admission has got.
+ *
+ * Admission resolves well after the abort listener is installed: the turn first has to
+ * auto-load a model, retrieve RAG, upload attachments and save history. A Stop landing
+ * in that window has no run id yet and may still end up on the legacy stream, so it
+ * needs the `cancel_id` POST, whose server side stashes the cancel for a generation
+ * that registers afterwards. That POST is safe once the run does exist too, because the
+ * durable request pins `cancel_id` to the same run id.
+ */
+export function chatGenerationStopPlan(
+ decision: "pending" | "durable" | "legacy",
+ runId: string | null,
+): { cancelRunId: string | null; postLegacyCancel: boolean } {
+ if (runId) return { cancelRunId: runId, postLegacyCancel: false };
+ if (decision === "durable") return { cancelRunId: null, postLegacyCancel: false };
+ return { cancelRunId: null, postLegacyCancel: true };
+}
+
+export function explicitStopSignal(signal: AbortSignal): {
+ signal: AbortSignal;
+ dispose: () => void;
+} {
+ const controller = new AbortController();
+ const forward = () => {
+ const detached = Boolean(
+ (signal.reason as { detach?: boolean } | undefined)?.detach,
+ );
+ if (!detached) controller.abort(signal.reason);
+ };
+ if (signal.aborted) {
+ forward();
+ } else {
+ signal.addEventListener("abort", forward, { once: true });
+ }
+ return {
+ signal: controller.signal,
+ dispose: () => signal.removeEventListener("abort", forward),
+ };
+}
+
+export async function supportsChatGenerationRuns(
+ threadId: string,
+ signal?: AbortSignal,
+): Promise<boolean> {
+ const query = new URLSearchParams({ threadId });
+ const response = await authFetch(
+ `/api/inference/chat-runs/active?${query.toString()}`,
+ { signal },
+ );
+ if (response.status === 404 || response.status === 405) return false;
+ await json<{ runs: ChatGenerationRun[] }>(response);
+ return true;
+}
+
+export async function getActiveChatGenerationRuns(
+ threadId: string,
+ signal?: AbortSignal,
+): Promise<ChatGenerationRun[]> {
+ const query = new URLSearchParams({ threadId });
+ const response = await authFetch(
+ `/api/inference/chat-runs/active?${query.toString()}`,
+ { signal },
+ );
+ if (response.status === 404 || response.status === 405) return [];
+ return (await json<{ runs: ChatGenerationRun[] }>(response)).runs ?? [];
+}
+
+export async function createChatGenerationRun(
+ input: CreateChatGenerationRunInput,
+): Promise<ChatGenerationRun> {
+ let failures = 0;
+ while (true) {
+ try {
+ return await json<ChatGenerationRun>(
+ await authFetch("/api/inference/chat-runs", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ }),
+ );
+ } catch (error) {
+ if (isPermanent(error)) throw error;
+ failures += 1;
+ await waitForReconnect(reconnectDelay(failures));
+ }
+ }
+}
+
+/** Start idempotently, but let an explicit Stop return before a slow create reply. */
+export async function createChatGenerationRunUntilAbort(
+ input: CreateChatGenerationRunInput,
+ signal: AbortSignal,
+): Promise<ChatGenerationRun | null> {
+ const createPromise = createChatGenerationRun(input);
+ let resolveAbort: (() => void) | undefined;
+ const aborted = new Promise<null>((resolve) => {
+ resolveAbort = () => resolve(null);
+ if (signal.aborted) {
+ resolveAbort();
+ } else {
+ signal.addEventListener("abort", resolveAbort, { once: true });
+ }
+ });
+ try {
+ const run = await Promise.race([createPromise, aborted]);
+ if (run) {
+ return run;
+ }
+ const detached = Boolean(
+ (signal.reason as { detach?: boolean } | undefined)?.detach,
+ );
+ createPromise
+ .then((created) =>
+ detached ? undefined : cancelChatGenerationRun(created.id),
+ )
+ .catch(() => undefined);
+ return null;
+ } finally {
+ if (resolveAbort) {
+ signal.removeEventListener("abort", resolveAbort);
+ }
+ }
+}
+
+export async function getChatGenerationRun(
+ id: string,
+ signal?: AbortSignal,
+): Promise<ChatGenerationRun> {
+ return json<ChatGenerationRun>(
+ await authFetch(`/api/inference/chat-runs/${encodeURIComponent(id)}`, {
+ signal,
+ }),
+ );
+}
+
+export async function cancelChatGenerationRun(
+ id: string,
+): Promise<ChatGenerationRun> {
+ return json<ChatGenerationRun>(
+ await authFetch(
+ `/api/inference/chat-runs/${encodeURIComponent(id)}/cancel`,
+ { method: "POST" },
+ ),
+ );
+}
+
+// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SSE framing retains state across reader chunks.
+async function* streamChatGenerationEvents(
+ id: string,
+ after: number,
+ signal?: AbortSignal,
+): AsyncGenerator<ChatGenerationEvent> {
+ const response = await authFetch(
+ `/api/inference/chat-runs/${encodeURIComponent(id)}/events?after=${Math.max(0, after)}`,
+ { method: "POST", headers: { accept: "text/event-stream" }, signal },
+ );
+ if (!response.ok) await json(response);
+ if (!response.body)
+ throw new Error("Chat generation event stream returned no body");
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ buffer += decoder.decode(value, { stream: !done });
+ buffer = buffer.replace(/\r\n/g, "\n");
+ let boundary = buffer.indexOf("\n\n");
+ while (boundary >= 0) {
+ const block = buffer.slice(0, boundary);
+ buffer = buffer.slice(boundary + 2);
+ const data: string[] = [];
+ for (const line of block.split("\n")) {
+ if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
+ }
+ if (data.length > 0) {
+ const event = JSON.parse(data.join("\n")) as ChatGenerationEvent;
+ if (event.type === "chunk") {
+ event.payload = normalizeChatGenerationChunkPayload(event.payload);
+ }
+ yield event;
+ }
+ boundary = buffer.indexOf("\n\n");
+ }
+ if (done) return;
+ }
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ }
+}
+
+/** Replay from the caller's applied cursor and reconnect until the run is terminal. */
+export async function* followChatGenerationRun(
+ id: string,
+ options: {
+ initialRun?: ChatGenerationRun;
+ replayFrom?: number;
+ signal?: AbortSignal;
+ } = {},
+): AsyncGenerator<ChatGenerationRunUpdate> {
+ const { replayFrom, signal } = options;
+ let run = options.initialRun;
+ let failures = 0;
+ while (!(run || signal?.aborted)) {
+ try {
+ run = await getChatGenerationRun(id, signal);
+ } catch (error) {
+ if (signal?.aborted) return;
+ if (isPermanent(error)) throw error;
+ failures += 1;
+ await waitForReconnect(reconnectDelay(failures), signal);
+ }
+ }
+ if (!run || signal?.aborted) return;
+ let currentRun = run;
+ let cursor = replayFrom ?? run.lastEventSeq;
+ yield { run, source: "snapshot" };
+ if (isTerminalChatGenerationRun(run) && replayFrom === undefined) return;
+
+ while (!signal?.aborted) {
+ try {
+ for await (const event of streamChatGenerationEvents(
+ id,
+ cursor,
+ signal,
+ )) {
+ if (event.seq <= cursor) continue;
+ cursor = event.seq;
+ if (event.run) currentRun = event.run;
+ failures = 0;
+ yield { run: currentRun, event, source: "event" };
+ if (
+ isTerminalChatGenerationRun(currentRun) &&
+ cursor >= currentRun.lastEventSeq
+ ) {
+ return;
+ }
+ }
+ } catch (error) {
+ if (signal?.aborted) return;
+ if (isPermanent(error)) throw error;
+ failures += 1;
+ }
+ if (signal?.aborted) return;
+ try {
+ const fresh = await getChatGenerationRun(id, signal);
+ const changed =
+ fresh.status !== currentRun.status ||
+ fresh.updatedAt !== currentRun.updatedAt ||
+ fresh.lastEventSeq !== currentRun.lastEventSeq;
+ currentRun = fresh;
+ if (changed || cursor < fresh.lastEventSeq) {
+ yield { run: fresh, source: "snapshot" };
+ }
+ if (isTerminalChatGenerationRun(fresh) && cursor >= fresh.lastEventSeq)
+ return;
+ } catch (error) {
+ if (signal?.aborted) return;
+ if (isPermanent(error)) throw error;
+ failures += 1;
+ }
+ await waitForReconnect(reconnectDelay(failures), signal);
+ }
+}
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index c0e09d1af62..b1dc511e800 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -42,6 +42,12 @@ import {
} from "./api/chat-adapter";
import { CHAT_HISTORY_UPDATED_EVENT } from "./api/chat-api";
import { getResearchThreadState } from "./api/research-api";
+import {
+ cancelChatGenerationRun,
+ type ChatGenerationRun,
+ getActiveChatGenerationRuns,
+ followChatGenerationRun,
+} from "./api/chat-generation-api";
import {
TEXT_ATTACHMENT_ACCEPT,
extractDocxAttachmentText,
@@ -79,6 +85,27 @@ import { ToolPaneScopeContext, toolPaneScope } from "./tool-output-scope";
import { ChatProjectScopeContext } from "./chat-project-scope";
import { readThreadCreationClaim } from "./utils/chat-thread-creation-claim";
import type { MessageRecord, ModelType, ThreadRecord } from "./types";
+import type { OpenAIChatChunk } from "./types/api";
+import {
+ budgetImpliesTruncation,
+ restoredAssistantStatus,
+} from "./utils/continuation";
+import {
+ generationChunkCountsTowardTiming,
+ generationChunkHasSubstantiveDelta,
+ generationNeedsRecovery,
+ loadGenerationOverlaySnapshot,
+ recoveredReasoningSummaryMetadata,
+ recoveredGenerationFinalMetadata,
+ generationRecoveryMetadata,
+ shouldPreserveGenerationMetadata,
+ subscribeGenerationRecoveryTriggers,
+} from "./utils/chat-generation-recovery";
+import { mergeContextTruncation } from "./utils/context-truncation";
+import {
+ extractDeltaText,
+ parseAssistantContent,
+} from "./utils/parse-assistant-content";
import {
chatContentPartAttachmentIdFromSignature,
chatContentPartAttachmentSignature,
@@ -671,6 +698,14 @@ function toThreadMessage(m: MessageRecord): ThreadMessage {
const savedTiming = custom.timing as
| import("@assistant-ui/react").MessageTiming
| undefined;
+ const restoredStatus = restoredAssistantStatus({ custom });
+ const generationStatus = custom.generationStatus;
+ const needsGenerationRecovery =
+ typeof custom.generationRunId === "string" &&
+ (generationStatus === "queued" ||
+ generationStatus === "running" ||
+ generationStatus === "cancelling" ||
+ (generationStatus === "completed" && custom.generationSettled !== true));
return {
id: m.id,
createdAt: new Date(m.createdAt),
@@ -679,7 +714,7 @@ function toThreadMessage(m: MessageRecord): ThreadMessage {
ThreadMessage,
{ role: "assistant" }
>["content"],
- status: { type: "complete" as const, reason: "unknown" as const },
+ status: needsGenerationRecovery ? { type: "running" } : restoredStatus,
metadata: {
custom,
...(savedTiming ? { timing: savedTiming } : {}),
@@ -691,6 +726,290 @@ function toThreadMessage(m: MessageRecord): ThreadMessage {
};
}
+type GenerationRecovery = {
+ promise: Promise<void>;
+ views: Set<ReturnType<typeof useAui>>;
+};
+
+const generationRecoveries = new Map<string, GenerationRecovery>();
+
+function generationRawContent(content: MessageRecord["content"]): {
+ raw: string;
+ reasoningOpen: boolean;
+} {
+ if (typeof content === "string") {
+ return { raw: content, reasoningOpen: false };
+ }
+ if (!Array.isArray(content)) return { raw: "", reasoningOpen: false };
+ let raw = "";
+ let reasoningOpen = false;
+ for (const part of content) {
+ if (!part || typeof part !== "object") continue;
+ const record = part as { type?: string; text?: unknown };
+ const text = typeof record.text === "string" ? record.text : "";
+ if (record.type === "reasoning") {
+ if (reasoningOpen) raw += text;
+ else raw += `<think>${text}`;
+ reasoningOpen = true;
+ } else if (record.type === "text") {
+ if (reasoningOpen) raw += "</think>";
+ raw += text;
+ reasoningOpen = false;
+ }
+ }
+ return { raw, reasoningOpen };
+}
+
+function scheduleGenerationRecovery(
+ threadId: string,
+ storedMessage: MessageRecord,
+ aui: ReturnType<typeof useAui>,
+): void {
+ const metadata = (storedMessage.metadata ?? {}) as Record<string, unknown>;
+ const runId = metadata.generationRunId;
+ if (typeof runId !== "string" || !generationNeedsRecovery(metadata)) return;
+ const existingRecovery = generationRecoveries.get(runId);
+ if (existingRecovery) {
+ existingRecovery.views.add(aui);
+ return;
+ }
+ const views = new Set([aui]);
+
+ const recovery = (async () => {
+ let cursor = Number(metadata.generationSeq ?? 0);
+ if (!Number.isSafeInteger(cursor) || cursor < 0) cursor = 0;
+ let { raw, reasoningOpen } = generationRawContent(storedMessage.content);
+ let completionTokens: number | undefined;
+ let recoveryUsage:
+ | {
+ prompt_tokens?: unknown;
+ completion_tokens?: unknown;
+ total_tokens?: unknown;
+ prompt_tokens_details?: { cached_tokens?: unknown };
+ cache_creation_input_tokens?: unknown;
+ cache_read_input_tokens?: unknown;
+ }
+ | undefined = (metadata.generationRecoveryUsage as typeof recoveryUsage) ?? undefined;
+ let recoveryTimings: Record<string, unknown> | undefined =
+ (metadata.generationRecoveryTimings as Record<string, unknown>) ?? undefined;
+ let firstChunkAt =
+ typeof metadata.generationFirstChunkAt === "number" &&
+ Number.isFinite(metadata.generationFirstChunkAt)
+ ? metadata.generationFirstChunkAt
+ : undefined;
+ let totalChunks = Number(metadata.generationChunkCount ?? 0);
+ if (!Number.isSafeInteger(totalChunks) || totalChunks < 0) totalChunks = 0;
+ let currentMetadata = { ...metadata };
+ const serverCancel = () => {
+ void cancelChatGenerationRun(runId).catch(() => {});
+ };
+ const runtime = useChatRuntimeStore.getState();
+ runtime.registerThreadServerCancel(threadId, serverCancel);
+ runtime.setThreadRunning(threadId, true, {
+ local: true,
+ owner: serverCancel,
+ });
+
+ const publish = async (run: ChatGenerationRun) => {
+ const status = run.status;
+ const runModel = useChatRuntimeStore
+ .getState()
+ .models.find((model) => model.id === run.requestPayload.model);
+ const lengthLimited =
+ run.finishReason === "length" ||
+ budgetImpliesTruncation({
+ isMlx: runModel?.isMlx === true,
+ maxTokens: run.requestPayload.max_tokens,
+ completionTokens,
+ });
+ let nextMetadata = generationRecoveryMetadata({
+ current: currentMetadata,
+ runId,
+ status,
+ cursor,
+ lastEventSeq: run.lastEventSeq,
+ lengthLimited,
+ firstChunkAt,
+ totalChunks,
+ usage: recoveryUsage,
+ timings: recoveryTimings,
+ });
+ if (nextMetadata.generationSettled === true) {
+ nextMetadata = recoveredGenerationFinalMetadata({
+ current: nextMetadata,
+ run,
+ usage: recoveryUsage,
+ timings: recoveryTimings,
+ firstChunkAt,
+ totalChunks,
+ });
+ }
+ currentMetadata = nextMetadata;
+ const content = parseAssistantContent(
+ reasoningOpen ? `${raw}</think>` : raw,
+ ) as MessageRecord["content"];
+ await saveStoredChatMessage({
+ id: storedMessage.id,
+ threadId,
+ parentId: storedMessage.parentId ?? null,
+ role: "assistant",
+ content,
+ metadata: nextMetadata,
+ createdAt: storedMessage.createdAt,
+ }).catch(() => {
+ // The producer may have committed a newer status between the event and
+ // this write. Keep following; the terminal publish carries all content.
+ });
+
+ for (const view of views) {
+ if (view.threadListItem().getState().remoteId !== threadId) continue;
+ try {
+ const exported = view.thread().export();
+ const messages = exported.messages.map((item) =>
+ item.message.id === storedMessage.id
+ ? {
+ ...item,
+ message: {
+ ...item.message,
+ content,
+ status: generationNeedsRecovery(nextMetadata)
+ ? { type: "running" as const }
+ : restoredAssistantStatus({ custom: nextMetadata }),
+ metadata: {
+ ...item.message.metadata,
+ custom: nextMetadata,
+ },
+ } as ThreadMessage,
+ }
+ : item,
+ );
+ view.thread().import({ ...exported, messages });
+ } catch {
+ // Storage remains authoritative if the thread unmounted between awaits.
+ }
+ }
+ };
+
+ try {
+ let lastPublishedStatus = "";
+ let identityValidated = false;
+ for await (const update of followChatGenerationRun(runId, {
+ replayFrom: cursor,
+ })) {
+ if (!identityValidated) {
+ if (
+ update.run.threadId !== threadId ||
+ update.run.assistantMessageId !== storedMessage.id
+ ) {
+ return;
+ }
+ if (cursor === 0 && raw.length === 0) {
+ const requestMessages = update.run.requestPayload.messages;
+ const lastRequestMessage = Array.isArray(requestMessages)
+ ? requestMessages.at(-1)
+ : undefined;
+ if (
+ lastRequestMessage?.role === "assistant" &&
+ typeof lastRequestMessage.content === "string"
+ ) {
+ // Continue sends the old partial as an assistant prefill. The
+ // server-owned placeholder is empty until the first client save,
+ // so a reload before that save must seed replay from the request.
+ raw = lastRequestMessage.content;
+ }
+ }
+ identityValidated = true;
+ }
+ if (update.event && update.event.seq > cursor) {
+ cursor = update.event.seq;
+ if (update.event.type === "chunk") {
+ const chunk = update.event.payload as {
+ _reasoningDurationMs?: unknown;
+ usage?: {
+ prompt_tokens?: unknown;
+ completion_tokens?: unknown;
+ total_tokens?: unknown;
+ prompt_tokens_details?: { cached_tokens?: unknown };
+ cache_creation_input_tokens?: unknown;
+ cache_read_input_tokens?: unknown;
+ };
+ timings?: Record<string, unknown>;
+ choices?: Array<{
+ delta?: {
+ content?: unknown;
+ reasoning_content?: unknown;
+ };
+ }>;
+ context_truncated?: OpenAIChatChunk["context_truncated"];
+ };
+ if ("_reasoningDurationMs" in chunk) {
+ currentMetadata = recoveredReasoningSummaryMetadata(
+ currentMetadata,
+ chunk._reasoningDurationMs,
+ );
+ lastPublishedStatus = update.run.status;
+ await publish(update.run);
+ continue;
+ }
+ if (generationChunkCountsTowardTiming(chunk)) {
+ totalChunks += 1;
+ }
+ if (generationChunkHasSubstantiveDelta(chunk)) {
+ firstChunkAt ??= update.event.createdAt;
+ }
+ if (chunk.context_truncated) {
+ currentMetadata = {
+ ...currentMetadata,
+ contextTruncation: mergeContextTruncation(
+ currentMetadata.contextTruncation as OpenAIChatChunk["context_truncated"],
+ chunk.context_truncated,
+ ),
+ };
+ }
+ if (chunk.usage) recoveryUsage = chunk.usage;
+ if (chunk.timings) recoveryTimings = chunk.timings;
+ if (typeof chunk.usage?.completion_tokens === "number") {
+ completionTokens = chunk.usage.completion_tokens;
+ }
+ const deltaRecord = chunk.choices?.[0]?.delta;
+ const reasoning =
+ typeof deltaRecord?.reasoning_content === "string"
+ ? deltaRecord.reasoning_content
+ : "";
+ const delta = extractDeltaText(deltaRecord?.content).text;
+ if (reasoning) {
+ if (!reasoningOpen) raw += "<think>";
+ raw += reasoning;
+ reasoningOpen = true;
+ }
+ if (delta) {
+ if (reasoningOpen) raw += "</think>";
+ raw += delta;
+ reasoningOpen = false;
+ }
+ }
+ }
+ const shouldPublish =
+ update.event?.type === "chunk" ||
+ update.run.status !== lastPublishedStatus ||
+ (["cancelled", "completed", "failed"].includes(update.run.status) &&
+ cursor >= update.run.lastEventSeq);
+ if (shouldPublish) {
+ lastPublishedStatus = update.run.status;
+ await publish(update.run);
+ }
+ }
+ } finally {
+ const store = useChatRuntimeStore.getState();
+ store.setThreadRunning(threadId, false, { owner: serverCancel });
+ store.clearThreadServerCancel(threadId, serverCancel);
+ }
+ })()
+ .catch(() => {})
+ .finally(() => generationRecoveries.delete(runId));
+ generationRecoveries.set(runId, { promise: recovery, views });
+}
+
export async function ensureThreadRecord({
threadId,
modelType,
@@ -936,7 +1255,9 @@ function createStudioDbAdapter(
const firstAssistant =
firstUserIndex === -1
? undefined
- : messages.find((m, i) => m.role === "assistant" && i > firstUserIndex);
+ : messages.find(
+ (m, i) => m.role === "assistant" && i > firstUserIndex,
+ );
const userText = titleTextOf(firstUser) || defaultTitle;
const assistantText = extractTextParts(firstAssistant);
@@ -1177,6 +1498,31 @@ function useStudioRuntimeAdapters(
): StudioRuntimeAdapters {
const aui = useAui();
+ useEffect(() => {
+ const recoverCurrentThread = () => {
+ const remoteId = aui.threadListItem().getState().remoteId;
+ if (!remoteId) return;
+ void listStoredChatMessages(remoteId)
+ .then((messages) => {
+ for (const message of messages) {
+ if (
+ message.role === "assistant" &&
+ typeof (message.metadata as Record<string, unknown> | undefined)
+ ?.generationRunId === "string"
+ ) {
+ scheduleGenerationRecovery(remoteId, message, aui);
+ }
+ }
+ })
+ .catch(() => {});
+ };
+ return subscribeGenerationRecoveryTriggers(
+ globalThis,
+ document,
+ recoverCurrentThread,
+ );
+ }, [aui]);
+
// Mirror Data-tab attachment deletions into the loaded thread. The in-memory
// repository otherwise keeps the attachment, and a later repo-to-storage sync
// (e.g. deleting a message in the thread) would write it back.
@@ -1365,19 +1711,40 @@ function useStudioRuntimeAdapters(
assistant: 2,
};
let msgs: MessageRecord[];
+ let activeGenerationRuns: ChatGenerationRun[];
try {
- msgs = await listStoredChatMessages(remoteId);
+ const snapshot = await loadGenerationOverlaySnapshot(
+ remoteId,
+ getActiveChatGenerationRuns,
+ listStoredChatMessages,
+ );
+ msgs = snapshot.messages;
+ activeGenerationRuns = snapshot.activeRuns;
} catch (error) {
if (!isExpectedBackgroundChatStorageError(error)) {
throw error;
}
msgs = [];
+ activeGenerationRuns = [];
+ }
+ for (const run of activeGenerationRuns) {
+ const assistant = msgs.find(
+ (message) => message.id === run.assistantMessageId,
+ );
+ if (!assistant) continue;
+ assistant.metadata = {
+ ...(assistant.metadata ?? {}),
+ generationRunId: run.id,
+ generationStatus: run.status,
+ generationSettled: false,
+ serverManaged: true,
+ };
}
// Durable research can outlive this runtime. Reattach its server-owned
// assistant message to the inline card after navigation or refresh.
- const researchThreadState = await getResearchThreadState(remoteId).catch(
- () => null,
- );
+ const researchThreadState = await getResearchThreadState(
+ remoteId,
+ ).catch(() => null);
if (researchThreadState) {
useResearchRunStore
.getState()
@@ -1406,6 +1773,23 @@ function useStudioRuntimeAdapters(
if (aOrder !== bOrder) return aOrder - bOrder;
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
});
+ for (const message of msgs) {
+ if (
+ message.role === "assistant" &&
+ typeof (message.metadata as Record<string, unknown> | undefined)
+ ?.generationRunId === "string"
+ ) {
+ scheduleGenerationRecovery(
+ remoteId,
+ {
+ ...message,
+ content: cloneContent(message.content),
+ metadata: { ...(message.metadata ?? {}) },
+ },
+ aui,
+ );
+ }
+ }
// Restore context usage from last assistant message if model matches.
const lastAssistant = [...msgs]
@@ -1580,9 +1964,18 @@ function useStudioRuntimeAdapters(
const sameResearchRun =
typeof existingMetadata?.researchRunId === "string" &&
existingMetadata.researchRunId === incomingMetadata?.researchRunId;
+ const sameGenerationRun =
+ typeof existingMetadata?.generationRunId === "string" &&
+ existingMetadata.generationRunId ===
+ incomingMetadata?.generationRunId;
+ const preserveGeneration = shouldPreserveGenerationMetadata(
+ existingMetadata,
+ incomingMetadata,
+ );
const preserveServerManaged =
existingMetadata?.serverManaged === true &&
- (sameResearchRun ||
+ (preserveGeneration ||
+ sameResearchRun ||
!incomingMetadata?.serverManaged ||
existingRevision > incomingRevision);
// Echo the backend's stored metadata verbatim on autosave: merging
diff --git a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
new file mode 100644
index 00000000000..537f6115d76
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
@@ -0,0 +1,328 @@
+// 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 type { ChatGenerationStatus } from "../api/chat-generation-api";
+import { extractDeltaText } from "./parse-assistant-content";
+
+export type StoredGenerationStatus = ChatGenerationStatus;
+
+const TERMINAL = new Set<StoredGenerationStatus>([
+ "cancelled",
+ "completed",
+ "failed",
+]);
+
+export function generationChunkHasSubstantiveDelta(payload: unknown): boolean {
+ const delta = (
+ payload as {
+ choices?: Array<{
+ delta?: {
+ content?: unknown;
+ reasoning_content?: unknown;
+ reasoning_details?: unknown;
+ };
+ }>;
+ }
+ )?.choices?.[0]?.delta;
+ const reasoning =
+ typeof delta?.reasoning_content === "string" ? delta.reasoning_content : "";
+ const reasoningDetails = Array.isArray(delta?.reasoning_details)
+ ? delta.reasoning_details.some(
+ (part) =>
+ part !== null &&
+ typeof part === "object" &&
+ typeof (part as { text?: unknown }).text === "string" &&
+ Boolean((part as { text: string }).text),
+ )
+ : false;
+ return Boolean(
+ reasoning || reasoningDetails || extractDeltaText(delta?.content).text,
+ );
+}
+
+export function generationChunkCountsTowardTiming(payload: unknown): boolean {
+ const chunk = payload as
+ | {
+ _reasoningDurationMs?: unknown;
+ context_truncated?: unknown;
+ usage?: unknown;
+ choices?: unknown[];
+ }
+ | null
+ | undefined;
+ if (!chunk || typeof chunk !== "object") return false;
+ if ("_reasoningDurationMs" in chunk || chunk.context_truncated) return false;
+ return !(chunk.usage && Array.isArray(chunk.choices) && chunk.choices.length === 0);
+}
+
+export function recoveredReasoningSummaryMetadata(
+ current: Record<string, unknown>,
+ reasoningMs: unknown,
+): Record<string, unknown> {
+ if (
+ typeof reasoningMs !== "number" ||
+ !Number.isFinite(reasoningMs) ||
+ reasoningMs < 0
+ ) {
+ return current;
+ }
+ const durations = Array.isArray(current.reasoningDurations)
+ ? current.reasoningDurations.filter(
+ (duration): duration is number =>
+ typeof duration === "number" && Number.isFinite(duration),
+ )
+ : [];
+ const duration = Math.max(0, Math.round(reasoningMs / 1000));
+ return {
+ ...current,
+ reasoningDuration: duration,
+ reasoningDurations: [...durations, duration],
+ };
+}
+
+export function generationIsSettled(
+ status: StoredGenerationStatus | null,
+ cursor: number,
+ lastEventSeq: number,
+): boolean {
+ return status !== null && TERMINAL.has(status) && cursor >= lastEventSeq;
+}
+
+export async function loadGenerationOverlaySnapshot<TMessage, TRun>(
+ threadId: string,
+ listActiveRuns: (id: string) => Promise<TRun[]>,
+ listMessages: (id: string) => Promise<TMessage[]>,
+): Promise<{ messages: TMessage[]; activeRuns: TRun[] }> {
+ // Runs first closes the create-between-snapshots gap. If a run commits after
+ // this read, the later message snapshot already carries its durable metadata.
+ const activeRuns = await listActiveRuns(threadId).catch(() => []);
+ const messages = await listMessages(threadId);
+ return { messages, activeRuns };
+}
+
+type RecoveryUsage = {
+ prompt_tokens?: unknown;
+ completion_tokens?: unknown;
+ total_tokens?: unknown;
+ prompt_tokens_details?: { cached_tokens?: unknown };
+ cache_creation_input_tokens?: unknown;
+ cache_read_input_tokens?: unknown;
+};
+
+type RecoveryTimings = {
+ cache_n?: unknown;
+ predicted_per_second?: unknown;
+ [key: string]: unknown;
+};
+
+export function recoveredGenerationFinalMetadata(options: {
+ current: Record<string, unknown>;
+ run: {
+ id: string;
+ requestPayload: { model?: unknown };
+ createdAt: number;
+ startedAt: number | null;
+ completedAt: number | null;
+ };
+ usage?: RecoveryUsage;
+ timings?: RecoveryTimings;
+ firstChunkAt?: number;
+ totalChunks: number;
+}): Record<string, unknown> {
+ const { current, run, usage, timings, firstChunkAt, totalChunks } = options;
+ const modelId =
+ typeof run.requestPayload.model === "string"
+ ? run.requestPayload.model
+ : "Unknown model";
+ const startedAt = run.startedAt ?? run.createdAt;
+ const finishedAt = run.completedAt ?? Date.now();
+ const completionTokens =
+ typeof usage?.completion_tokens === "number"
+ ? usage.completion_tokens
+ : undefined;
+ const tokensPerSecond =
+ typeof timings?.predicted_per_second === "number"
+ ? timings.predicted_per_second
+ : completionTokens !== undefined && finishedAt > startedAt
+ ? completionTokens / ((finishedAt - startedAt) / 1000)
+ : undefined;
+ const next = { ...current };
+
+ if (next.serverTimings === undefined && timings !== undefined) {
+ next.serverTimings = timings;
+ }
+ if (
+ next.contextUsage === undefined &&
+ typeof usage?.prompt_tokens === "number" &&
+ completionTokens !== undefined &&
+ typeof usage.total_tokens === "number"
+ ) {
+ next.contextUsage = {
+ promptTokens: usage.prompt_tokens,
+ completionTokens,
+ totalTokens: usage.total_tokens,
+ cachedTokens:
+ (typeof timings?.cache_n === "number" ? timings.cache_n : undefined) ??
+ (typeof usage.prompt_tokens_details?.cached_tokens === "number"
+ ? usage.prompt_tokens_details.cached_tokens
+ : undefined) ??
+ (typeof usage.cache_read_input_tokens === "number"
+ ? usage.cache_read_input_tokens
+ : 0),
+ cacheWriteTokens:
+ typeof usage.cache_creation_input_tokens === "number"
+ ? usage.cache_creation_input_tokens
+ : 0,
+ modelId,
+ };
+ }
+ if (next.responseDetails === undefined) {
+ next.responseDetails = {
+ modelId,
+ modelLabel: modelId,
+ responseModelId: modelId,
+ providerName: "Local model",
+ providerType: "local",
+ startedAt,
+ finishedAt,
+ durationMs: Math.max(0, finishedAt - startedAt),
+ cancelId: run.id,
+ toolCalls: [],
+ };
+ }
+ if (next.timing === undefined) {
+ next.timing = {
+ streamStartTime: startedAt,
+ firstTokenTime:
+ firstChunkAt === undefined ? undefined : Math.max(0, firstChunkAt - startedAt),
+ totalStreamTime: Math.max(0, finishedAt - startedAt),
+ tokenCount: completionTokens,
+ tokensPerSecond,
+ totalChunks,
+ toolCallCount: 0,
+ };
+ }
+ return next;
+}
+
+export function generationNeedsRecovery(
+ metadata: Record<string, unknown>,
+): boolean {
+ const status = String(metadata.generationStatus) as StoredGenerationStatus;
+ return (
+ typeof metadata.generationRunId === "string" &&
+ (metadata.generationSettled !== true || !TERMINAL.has(status))
+ );
+}
+
+export function generationRecoveryMetadata(options: {
+ current: Record<string, unknown>;
+ runId: string;
+ status: StoredGenerationStatus;
+ cursor: number;
+ lastEventSeq: number;
+ lengthLimited: boolean;
+ firstChunkAt?: number;
+ totalChunks?: number;
+ usage?: unknown;
+ timings?: unknown;
+}): Record<string, unknown> {
+ const {
+ current,
+ runId,
+ status,
+ cursor,
+ lastEventSeq,
+ lengthLimited,
+ firstChunkAt,
+ totalChunks,
+ usage,
+ timings,
+ } = options;
+ const settled = generationIsSettled(status, cursor, lastEventSeq);
+ const next: Record<string, unknown> = {
+ ...current,
+ generationRunId: runId,
+ generationSeq: cursor,
+ generationStatus: status,
+ generationSettled: settled,
+ serverManaged: true,
+ };
+ if (status === "completed") {
+ if (lengthLimited) {
+ next.incomplete = { reason: "length" };
+ } else {
+ next.incomplete = undefined;
+ }
+ } else if (status === "failed") {
+ next.incomplete = { reason: "interrupted" };
+ } else {
+ next.incomplete = { reason: "cancelled" };
+ }
+ if (firstChunkAt !== undefined) {
+ next.generationFirstChunkAt = firstChunkAt;
+ }
+ if (totalChunks !== undefined) {
+ next.generationChunkCount = totalChunks;
+ }
+ // Carried with the cursor for the same reason the two above are: the usage chunk arrives
+ // before the terminal event, so a cursor published past it and then reloaded would resume
+ // after it and lose the token counts and server timings for good.
+ if (usage !== undefined) {
+ next.generationRecoveryUsage = usage;
+ }
+ if (timings !== undefined) {
+ next.generationRecoveryTimings = timings;
+ }
+ return next;
+}
+
+export function shouldPreserveGenerationMetadata(
+ existing: Record<string, unknown> | undefined,
+ incoming: Record<string, unknown> | undefined,
+): boolean {
+ if (typeof existing?.generationRunId !== "string") {
+ return false;
+ }
+ const sameRun = existing.generationRunId === incoming?.generationRunId;
+ const existingSeq = Number(existing.generationSeq ?? -1);
+ const incomingSeq = Number(incoming?.generationSeq ?? -1);
+ const existingStatus = String(existing.generationStatus);
+ return (
+ !sameRun ||
+ incoming?.serverManaged !== true ||
+ existingSeq > incomingSeq ||
+ (TERMINAL.has(existingStatus as StoredGenerationStatus) &&
+ incoming?.generationStatus !== existing.generationStatus) ||
+ (existing.generationSettled === true &&
+ incoming?.generationSettled !== true)
+ );
+}
+
+type RecoveryEventTarget = Pick<
+ EventTarget,
+ "addEventListener" | "removeEventListener"
+>;
+type RecoveryVisibilityTarget = RecoveryEventTarget & {
+ readonly visibilityState: string;
+};
+
+export function subscribeGenerationRecoveryTriggers(
+ windowTarget: RecoveryEventTarget,
+ documentTarget: RecoveryVisibilityTarget,
+ recover: () => void,
+): () => void {
+ const onVisible = () => {
+ if (documentTarget.visibilityState === "visible") {
+ recover();
+ }
+ };
+ windowTarget.addEventListener("online", recover);
+ windowTarget.addEventListener("pageshow", recover);
+ documentTarget.addEventListener("visibilitychange", onVisible);
+ return () => {
+ windowTarget.removeEventListener("online", recover);
+ windowTarget.removeEventListener("pageshow", recover);
+ documentTarget.removeEventListener("visibilitychange", onVisible);
+ };
+}
diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
index 5fe311df714..f7bfb7edcc9 100644
--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
@@ -963,7 +963,7 @@ export async function saveStoredChatMessage(
export async function syncStoredChatMessages(
threadId: string,
messages: MessageRecord[],
- options: { pruneMissing?: boolean } = {},
+ options: { pruneMissing?: boolean; deletedMessageIds?: string[] } = {},
): Promise<MessageRecord[]> {
if (isThreadIncognito(threadId)) return messages;
if (isChatThreadDeleted(threadId)) return [];
diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.ts
index 7f0913481b6..b588bea9193 100644
--- a/studio/frontend/src/features/chat/utils/continuation.ts
+++ b/studio/frontend/src/features/chat/utils/continuation.ts
@@ -48,6 +48,33 @@ export function readIncompleteInfo(metadata: unknown): IncompleteInfo | null {
return null;
}
+/**
+ * assistant-ui's reason for each of ours. `length` is a truthful stop, not a failure:
+ * mapping it to `error` paints MessagePrimitive.Error's red box and a Retry button over
+ * a turn that already offers the Continue bar below it, on every reloaded max-tokens
+ * answer including ones written before this feature existed. `interrupted` keeps `error`
+ * on purpose -- a cut stream is the thing the user has to be told about.
+ */
+const STATUS_REASON: Record<
+ IncompleteReason,
+ "cancelled" | "length" | "error"
+> = {
+ cancelled: "cancelled",
+ length: "length",
+ interrupted: "error",
+};
+
+/** Restore assistant-ui's status without losing the product-specific stop reason. */
+export function restoredAssistantStatus(
+ metadata: unknown,
+): import("@assistant-ui/react").MessageStatus {
+ const incomplete = readIncompleteInfo(metadata);
+ if (!incomplete) {
+ return { type: "complete", reason: "unknown" };
+ }
+ return { type: "incomplete", reason: STATUS_REASON[incomplete.reason] };
+}
+
const INCOMPLETE_LABELS: Record<IncompleteReason, string> = {
length: "Response hit the Max Tokens limit",
cancelled: "Response stopped",
diff --git a/studio/frontend/src/features/chat/utils/delete-thread-message.ts b/studio/frontend/src/features/chat/utils/delete-thread-message.ts
index 89ffeac11de..126f511f715 100644
--- a/studio/frontend/src/features/chat/utils/delete-thread-message.ts
+++ b/studio/frontend/src/features/chat/utils/delete-thread-message.ts
@@ -112,7 +112,7 @@ async function withStoredResearchMessages(
export async function syncExportedRepositoryToBackend(
remoteId: string,
exp: ExportedMessageRepository,
- options: { pruneMissing?: boolean } = {},
+ options: { pruneMissing?: boolean; deletedMessageIds?: string[] } = {},
): Promise<void> {
// No ensureStoredChatThread here: syncStoredChatMessages ensures the row itself, and
// this used to make every save pay for the same GET /threads/{id} twice.
@@ -122,7 +122,10 @@ export async function syncExportedRepositoryToBackend(
await syncStoredChatMessages(
remoteId,
await withStoredResearchMessages(remoteId, records),
- { pruneMissing: options.pruneMissing },
+ {
+ pruneMissing: options.pruneMissing,
+ deletedMessageIds: options.deletedMessageIds,
+ },
);
}
@@ -167,6 +170,7 @@ export async function deleteThreadMessage(args: {
if (remoteId) {
await syncExportedRepositoryToBackend(remoteId, next, {
pruneMissing: true,
+ deletedMessageIds: [messageId, ...assistantReplyIds],
});
}
thread.import(next);
diff --git a/studio/frontend/src/features/chat/utils/update-thread-message.ts b/studio/frontend/src/features/chat/utils/update-thread-message.ts
index ee3ea825e97..41109730831 100644
--- a/studio/frontend/src/features/chat/utils/update-thread-message.ts
+++ b/studio/frontend/src/features/chat/utils/update-thread-message.ts
@@ -136,14 +136,17 @@ export async function updateThreadMessage(args: {
// If it's NOT incognito, we attempt to save to the DB regardless of the ID.
if (remoteId && !isIncognito) {
try {
- await saveChatMessage({
- id: messageId,
- threadId: remoteId,
- parentId: originalParentId,
- role: "assistant",
- content: (updatedMessages.find(m => m.message.id === messageId)?.message.content) || [],
- createdAt: originalCreatedAt ? Number(originalCreatedAt) : Date.now(),
- });
+ await saveChatMessage(
+ {
+ id: messageId,
+ threadId: remoteId,
+ parentId: originalParentId,
+ role: "assistant",
+ content: (updatedMessages.find(m => m.message.id === messageId)?.message.content) || [],
+ createdAt: originalCreatedAt ? Number(originalCreatedAt) : Date.now(),
+ },
+ { allowGenerationEdit: true },
+ );
} catch (e) {
thread.import(originalExport);
console.error("Backend sync failed for message update. Rolling back UI.", e);
@@ -152,4 +155,4 @@ export async function updateThreadMessage(args: {
}
return (updatedMessages.find(m => m.message.id === messageId)?.message.content) || [];
-}
\ No newline at end of file
+}
diff --git a/studio/frontend/tests/chat-generation-reconnect.test.ts b/studio/frontend/tests/chat-generation-reconnect.test.ts
new file mode 100644
index 00000000000..afc46a6e6f5
--- /dev/null
+++ b/studio/frontend/tests/chat-generation-reconnect.test.ts
@@ -0,0 +1,362 @@
+// 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 { register } from "node:module";
+import test, { afterEach } from "node:test";
+
+import type { ChatGenerationRun } from "../src/features/chat/api/chat-generation-api.ts";
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+register("./helpers/settings-api-resolver.mjs", import.meta.url);
+registerBundlerResolver();
+installLocalStorageFake();
+
+const originalFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+const {
+ cancelChatGenerationRun,
+ chatGenerationStopPlan,
+ createChatGenerationRun,
+ createChatGenerationRunUntilAbort,
+ explicitStopSignal,
+ isLegacyFallbackChatGenerationAdmissionError,
+ isToolEnabledChatGenerationAdmissionError,
+ followChatGenerationRun,
+ supportsChatGenerationRuns,
+} = await import("../src/features/chat/api/chat-generation-api.ts");
+
+test("durable admission ignores detach but still observes explicit Stop", () => {
+ const detached = new AbortController();
+ const detachedAdmission = explicitStopSignal(detached.signal);
+ detached.abort({ detach: true });
+ assert.equal(detachedAdmission.signal.aborted, false);
+ detachedAdmission.dispose();
+
+ const stopped = new AbortController();
+ const stoppedAdmission = explicitStopSignal(stopped.signal);
+ stopped.abort({ detach: false });
+ assert.equal(stoppedAdmission.signal.aborted, true);
+ stoppedAdmission.dispose();
+});
+
+const run = (
+ status: ChatGenerationRun["status"],
+ seq: number,
+): ChatGenerationRun => ({
+ id: "run-1",
+ threadId: "thread-1",
+ userMessageId: "user-1",
+ assistantMessageId: "assistant-1",
+ requestHash: "hash",
+ requestPayload: { model: "local", messages: [], stream: true, max_tokens: 8 },
+ status,
+ cancelRequested: false,
+ lastEventSeq: seq,
+ finishReason: status === "completed" ? "stop" : null,
+ error: null,
+ createdAt: 1,
+ updatedAt: seq + 1,
+ startedAt: 1,
+ completedAt: status === "completed" ? 9 : null,
+});
+
+const createInput = () => ({
+ runId: "run-1",
+ threadId: "thread-1",
+ userMessageId: "user-1",
+ assistantMessageId: "assistant-1",
+ requestPayload: run("queued", 1).requestPayload,
+});
+
+const frame = (
+ seq: number,
+ type: string,
+ payload: object,
+ snapshot?: ChatGenerationRun,
+) =>
+ `id: ${seq}\nevent: ${type}\ndata: ${JSON.stringify({
+ seq,
+ type,
+ payload,
+ createdAt: seq,
+ ...(snapshot ? { run: snapshot } : {}),
+ })}\n\n`;
+
+function sse(frames: string[]): Response {
+ const encoder = new TextEncoder();
+ const body = new ReadableStream({
+ start(controller) {
+ for (const value of frames) controller.enqueue(encoder.encode(value));
+ controller.close();
+ },
+ });
+ return new Response(body, {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+}
+
+test("reconnect resumes from the applied cursor without duplicate chunks", async () => {
+ const eventUrls: string[] = [];
+ let follows = 0;
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.includes("/events")) {
+ eventUrls.push(url);
+ follows += 1;
+ return follows === 1
+ ? sse([
+ frame(1, "chunk", { choices: [{ delta: { content: "A" } }] }),
+ frame(2, "chunk", { choices: [{ delta: { content: "B" } }] }),
+ ])
+ : sse([
+ frame(3, "chunk", { choices: [{ delta: { content: "C" } }] }),
+ frame(
+ 4,
+ "run.completed",
+ { status: "completed" },
+ run("completed", 4),
+ ),
+ ]);
+ }
+ return new Response(
+ JSON.stringify(follows ? run("completed", 4) : run("queued", 2)),
+ {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ },
+ );
+ }) as typeof fetch;
+ const sequences: number[] = [];
+ const snapshots: Array<[string, number]> = [];
+ for await (const update of followChatGenerationRun("run-1", {
+ initialRun: run("running", 0),
+ replayFrom: 0,
+ })) {
+ if (update.event) sequences.push(update.event.seq);
+ else snapshots.push([update.run.status, sequences.length]);
+ }
+ assert.deepEqual(sequences, [1, 2, 3, 4]);
+ assert.deepEqual(snapshots, [
+ ["running", 0],
+ ["completed", 2],
+ ]);
+ assert.match(eventUrls[0], /after=0$/);
+ assert.match(eventUrls[1], /after=2$/);
+ assert.equal(
+ eventUrls.some((url) => url.includes("chat/completions")),
+ false,
+ );
+});
+
+test("durable replay normalizes reasoning summary control frames", async () => {
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
+ if (String(input).includes("/events")) {
+ return sse([
+ frame(1, "chunk", { type: "reasoning_summary", duration_ms: 3200 }),
+ frame(2, "run.completed", { status: "completed" }, run("completed", 2)),
+ ]);
+ }
+ return new Response(JSON.stringify(run("completed", 2)), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }) as typeof fetch;
+ const chunks: object[] = [];
+ for await (const update of followChatGenerationRun("run-1", {
+ initialRun: run("running", 0),
+ replayFrom: 0,
+ })) {
+ if (update.event?.type === "chunk") chunks.push(update.event.payload);
+ }
+ assert.deepEqual(chunks, [{ _reasoningDurationMs: 3200 }]);
+});
+
+test("a backend without chat runs selects the legacy path", async () => {
+ globalThis.fetch = (async () =>
+ new Response(null, { status: 404 })) as typeof fetch;
+ assert.equal(await supportsChatGenerationRuns("thread-1"), false);
+});
+
+test("tool-enabled durable admission errors select the legacy stream", async () => {
+ globalThis.fetch = (async () =>
+ new Response(
+ JSON.stringify({ detail: "Tool-enabled chat runs use the legacy streaming path" }),
+ { status: 400, headers: { "content-type": "application/json" } },
+ )) as typeof fetch;
+ await assert.rejects(
+ createChatGenerationRun(createInput()),
+ (error: unknown) => {
+ assert.equal(isToolEnabledChatGenerationAdmissionError(error), true);
+ return true;
+ },
+ );
+});
+
+test("credential-safe durable admission errors select the legacy stream", async () => {
+ globalThis.fetch = (async () =>
+ new Response(JSON.stringify({ detail: "Credentials cannot be persisted" }), {
+ status: 400,
+ headers: { "content-type": "application/json" },
+ })) as typeof fetch;
+ await assert.rejects(
+ createChatGenerationRun(createInput()),
+ (error: unknown) => {
+ assert.equal(isLegacyFallbackChatGenerationAdmissionError(error), true);
+ return true;
+ },
+ );
+});
+
+test("missing history rows select the legacy stream", async () => {
+ for (const [status, detail] of [
+ [404, "Thread not found"],
+ [400, "userMessageId must identify a user message in the thread"],
+ ] as const) {
+ globalThis.fetch = (async () =>
+ new Response(JSON.stringify({ detail }), {
+ status,
+ headers: { "content-type": "application/json" },
+ })) as typeof fetch;
+ await assert.rejects(
+ createChatGenerationRun(createInput()),
+ (error: unknown) => isLegacyFallbackChatGenerationAdmissionError(error),
+ );
+ }
+});
+
+test("an ambiguous create retries the same run instead of starting generation twice", async () => {
+ const bodies: string[] = [];
+ globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
+ bodies.push(String(init?.body));
+ if (bodies.length === 1) throw new TypeError("network reset");
+ return new Response(JSON.stringify(run("queued", 1)), {
+ status: 202,
+ headers: { "content-type": "application/json" },
+ });
+ }) as typeof fetch;
+ const created = await createChatGenerationRun(createInput());
+ assert.equal(created.id, "run-1");
+ assert.equal(bodies.length, 2);
+ assert.equal(JSON.parse(bodies[0]).runId, JSON.parse(bodies[1]).runId);
+});
+
+test("Stop cancels the server run while an event reconnect is delayed", async () => {
+ const controller = new AbortController();
+ let eventCalls = 0;
+ let cancelCalls = 0;
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.endsWith("/cancel")) {
+ cancelCalls += 1;
+ return new Response(JSON.stringify(run("cancelled", 0)), { status: 200 });
+ }
+ if (url.includes("/events")) {
+ eventCalls += 1;
+ throw new TypeError("offline");
+ }
+ return new Response(JSON.stringify(run("running", 0)), { status: 200 });
+ }) as typeof fetch;
+ const following = (async () => {
+ for await (const update of followChatGenerationRun("run-1", {
+ initialRun: run("running", 0),
+ replayFrom: 0,
+ signal: controller.signal,
+ })) {
+ assert.equal(update.run.status, "running");
+ }
+ })();
+ while (eventCalls === 0)
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await cancelChatGenerationRun("run-1");
+ controller.abort();
+ await following;
+ assert.equal(cancelCalls, 1);
+ assert.equal(eventCalls, 1);
+});
+
+test("completed, cancelled, and backend-restarted snapshots are terminal", async () => {
+ for (const status of ["completed", "cancelled", "failed"] as const) {
+ const terminal = run(status, 0);
+ globalThis.fetch = (async (input: RequestInfo | URL) =>
+ String(input).includes("/events")
+ ? sse([])
+ : new Response(JSON.stringify(terminal), {
+ status: 200,
+ })) as typeof fetch;
+ const seen: string[] = [];
+ for await (const update of followChatGenerationRun("run-1", {
+ initialRun: terminal,
+ replayFrom: 0,
+ })) {
+ seen.push(update.run.status);
+ }
+ assert.deepEqual(seen, [status]);
+ }
+});
+
+test("Stop during create cancels the run after its delayed reply", async () => {
+ const controller = new AbortController();
+ let releaseCreate!: () => void;
+ const delayed = new Promise<void>((resolve) => {
+ releaseCreate = resolve;
+ });
+ let cancelled = 0;
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
+ if (String(input).endsWith("/cancel")) {
+ cancelled += 1;
+ return new Response(JSON.stringify(run("cancelled", 1)), { status: 200 });
+ }
+ await delayed;
+ return new Response(JSON.stringify(run("queued", 1)), { status: 202 });
+ }) as typeof fetch;
+ const creating = createChatGenerationRunUntilAbort(
+ createInput(),
+ controller.signal,
+ );
+ controller.abort({ detach: false });
+ assert.equal(await creating, null);
+ releaseCreate();
+ while (cancelled === 0)
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(cancelled, 1);
+});
+
+test("Stop before admission resolves still reaches the server", () => {
+ // Admission resolves long after the abort listener is installed (model auto-load,
+ // RAG, attachment upload, first history save). A Stop in that window has no run id
+ // and the turn may still fall back to the legacy stream, so it has to send the
+ // cancel_id POST the backend stashes for a generation that registers afterwards.
+ assert.deepEqual(chatGenerationStopPlan("pending", null), {
+ cancelRunId: null,
+ postLegacyCancel: true,
+ });
+ assert.deepEqual(chatGenerationStopPlan("legacy", null), {
+ cancelRunId: null,
+ postLegacyCancel: true,
+ });
+
+ // Once the run exists, cancelling it is enough and is the precise thing to do.
+ assert.deepEqual(chatGenerationStopPlan("pending", "run-7"), {
+ cancelRunId: "run-7",
+ postLegacyCancel: false,
+ });
+ assert.deepEqual(chatGenerationStopPlan("durable", "run-7"), {
+ cancelRunId: "run-7",
+ postLegacyCancel: false,
+ });
+
+ // Durable with no id means create was aborted before it replied; that path chains
+ // its own cancel onto the pending create, so a second POST would be noise.
+ assert.deepEqual(chatGenerationStopPlan("durable", null), {
+ cancelRunId: null,
+ postLegacyCancel: false,
+ });
+});
diff --git a/studio/frontend/tests/chat-runtime-reload-status.test.ts b/studio/frontend/tests/chat-runtime-reload-status.test.ts
new file mode 100644
index 00000000000..5cf8317e42f
--- /dev/null
+++ b/studio/frontend/tests/chat-runtime-reload-status.test.ts
@@ -0,0 +1,355 @@
+// 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 test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { readIncompleteInfo, restoredAssistantStatus } = await import(
+ "../src/features/chat/utils/continuation.ts"
+);
+const {
+ generationChunkCountsTowardTiming,
+ generationChunkHasSubstantiveDelta,
+ generationIsSettled,
+ generationNeedsRecovery,
+ loadGenerationOverlaySnapshot,
+ recoveredReasoningSummaryMetadata,
+ recoveredGenerationFinalMetadata,
+ generationRecoveryMetadata,
+ shouldPreserveGenerationMetadata,
+ subscribeGenerationRecoveryTriggers,
+} = await import("../src/features/chat/utils/chat-generation-recovery.ts");
+
+test("first-token recovery ignores role and control chunks", () => {
+ assert.equal(
+ generationChunkHasSubstantiveDelta({
+ choices: [{ delta: { role: "assistant" } }],
+ }),
+ false,
+ );
+ assert.equal(
+ generationChunkHasSubstantiveDelta({
+ choices: [],
+ usage: { completion_tokens: 1 },
+ }),
+ false,
+ );
+ assert.equal(
+ generationChunkHasSubstantiveDelta({
+ choices: [{ delta: { content: "token" } }],
+ }),
+ true,
+ );
+ assert.deepEqual(
+ [
+ { choices: [{ delta: { role: "assistant" } }] },
+ { context_truncated: { checkpoint: true } },
+ { choices: [], usage: { completion_tokens: 1 } },
+ { choices: [{ delta: { content: "token" } }] },
+ ].map(generationChunkCountsTowardTiming),
+ [true, false, false, true],
+ );
+ assert.equal(
+ generationChunkHasSubstantiveDelta({
+ choices: [{ delta: { reasoning_content: "thought" } }],
+ }),
+ true,
+ );
+ assert.equal(
+ generationChunkHasSubstantiveDelta({
+ choices: [{ delta: { reasoning_details: [{ text: "thought" }] } }],
+ }),
+ true,
+ );
+});
+
+test("reload recovery preserves server reasoning durations", () => {
+ const metadata = recoveredReasoningSummaryMetadata(
+ {
+ reasoningDuration: 1,
+ reasoningDurations: [1],
+ },
+ 3200,
+ );
+ assert.equal(metadata.reasoningDuration, 3);
+ assert.deepEqual(metadata.reasoningDurations, [1, 3]);
+ assert.equal(recoveredReasoningSummaryMetadata(metadata, -1), metadata);
+});
+
+test("stored assistant status remains truthful after reload", () => {
+ const interrupted = { custom: { incomplete: { reason: "interrupted" } } };
+ assert.deepEqual(restoredAssistantStatus(interrupted), {
+ type: "incomplete",
+ reason: "error",
+ });
+ assert.deepEqual(readIncompleteInfo(interrupted), { reason: "interrupted" });
+
+ // Every reason keeps its own identity, so the Continue bar and the error box
+ // cannot disagree about what happened.
+ const length = { custom: { incomplete: { reason: "length" } } };
+ assert.deepEqual(restoredAssistantStatus(length), {
+ type: "incomplete",
+ reason: "length",
+ });
+ assert.deepEqual(readIncompleteInfo(length), { reason: "length" });
+
+ assert.deepEqual(
+ restoredAssistantStatus({
+ custom: { incomplete: { reason: "cancelled" } },
+ }),
+ { type: "incomplete", reason: "cancelled" },
+ );
+
+ assert.deepEqual(restoredAssistantStatus({ custom: {} }), {
+ type: "complete",
+ reason: "unknown",
+ });
+ assert.deepEqual(restoredAssistantStatus(undefined), {
+ type: "complete",
+ reason: "unknown",
+ });
+});
+
+test("terminal status settles only after the replay cursor catches up", () => {
+ assert.equal(generationIsSettled("completed", 3, 5), false);
+ assert.equal(generationIsSettled("completed", 5, 5), true);
+ assert.equal(generationIsSettled("running", 5, 5), false);
+});
+
+test("active runs are read before messages so a concurrent create is visible", async () => {
+ const calls: string[] = [];
+ const stored = [{ id: "user-1" }];
+ const snapshot = await loadGenerationOverlaySnapshot(
+ "thread-1",
+ () => {
+ calls.push("runs");
+ stored.push({ id: "assistant-1" });
+ return Promise.resolve([{ assistantMessageId: "assistant-1" }]);
+ },
+ () => {
+ calls.push("messages");
+ return Promise.resolve([...stored]);
+ },
+ );
+ assert.deepEqual(calls, ["runs", "messages"]);
+ assert.equal(
+ snapshot.messages.some(
+ (message) => message.id === snapshot.activeRuns[0]?.assistantMessageId,
+ ),
+ true,
+ );
+});
+
+test("terminal recovery restores final local usage and timing metadata", () => {
+ const metadata = recoveredGenerationFinalMetadata({
+ current: { generationSettled: true },
+ run: {
+ id: "run-1",
+ requestPayload: { model: "local/model" },
+ createdAt: 100,
+ startedAt: 120,
+ completedAt: 1120,
+ },
+ usage: {
+ prompt_tokens: 8,
+ completion_tokens: 12,
+ total_tokens: 20,
+ prompt_tokens_details: { cached_tokens: 3 },
+ },
+ timings: { predicted_per_second: 12, prompt_ms: 25 },
+ firstChunkAt: 220,
+ totalChunks: 4,
+ });
+ assert.deepEqual(metadata.contextUsage, {
+ promptTokens: 8,
+ completionTokens: 12,
+ totalTokens: 20,
+ cachedTokens: 3,
+ cacheWriteTokens: 0,
+ modelId: "local/model",
+ });
+ assert.deepEqual(metadata.serverTimings, {
+ predicted_per_second: 12,
+ prompt_ms: 25,
+ });
+ assert.deepEqual(metadata.timing, {
+ streamStartTime: 120,
+ firstTokenTime: 100,
+ totalStreamTime: 1000,
+ tokenCount: 12,
+ tokensPerSecond: 12,
+ totalChunks: 4,
+ toolCallCount: 0,
+ });
+ assert.deepEqual(metadata.responseDetails, {
+ modelId: "local/model",
+ modelLabel: "local/model",
+ responseModelId: "local/model",
+ providerName: "Local model",
+ providerType: "local",
+ startedAt: 120,
+ finishedAt: 1120,
+ durationMs: 1000,
+ cancelId: "run-1",
+ toolCalls: [],
+ });
+});
+
+test("reload, wake, and stale-tab recovery stays monotonic and truthful", () => {
+ const apply = (
+ status: "running" | "completed" | "failed" | "cancelled",
+ cursor: number,
+ lengthLimited = false,
+ ) =>
+ generationRecoveryMetadata({
+ current: { generationRunId: "run-1" },
+ runId: "run-1",
+ status,
+ cursor,
+ lastEventSeq: 4,
+ lengthLimited,
+ });
+ assert.deepEqual(
+ [
+ ["running", 2],
+ ["completed", 2],
+ ["completed", 2, true],
+ ["completed", 4, true],
+ ["failed", 4],
+ ["cancelled", 4],
+ ].map(([status, cursor, limited]) => {
+ const metadata = apply(
+ status as "running" | "completed" | "failed" | "cancelled",
+ cursor as number,
+ Boolean(limited),
+ );
+ return [generationNeedsRecovery(metadata), metadata.incomplete];
+ }),
+ [
+ [true, { reason: "cancelled" }],
+ [true, undefined],
+ [true, { reason: "length" }],
+ [false, { reason: "length" }],
+ [false, { reason: "interrupted" }],
+ [false, { reason: "cancelled" }],
+ ],
+ );
+
+ const windowTarget = new EventTarget();
+ const documentTarget = Object.assign(new EventTarget(), {
+ visibilityState: "hidden",
+ });
+ let recoveries = 0;
+ const unsubscribe = subscribeGenerationRecoveryTriggers(
+ windowTarget,
+ documentTarget,
+ () => {
+ recoveries += 1;
+ },
+ );
+ windowTarget.dispatchEvent(new Event("online"));
+ windowTarget.dispatchEvent(new Event("pageshow"));
+ documentTarget.dispatchEvent(new Event("visibilitychange"));
+ documentTarget.visibilityState = "visible";
+ documentTarget.dispatchEvent(new Event("visibilitychange"));
+ unsubscribe();
+ windowTarget.dispatchEvent(new Event("online"));
+ assert.equal(recoveries, 3);
+
+ const existing = {
+ generationRunId: "run-1",
+ generationSeq: 4,
+ generationStatus: "completed",
+ generationSettled: true,
+ serverManaged: true,
+ };
+ const incoming = { ...existing };
+ assert.deepEqual(
+ [
+ incoming,
+ { ...incoming, generationSeq: 3 },
+ { ...incoming, generationRunId: "run-2" },
+ { ...incoming, generationStatus: "running" },
+ { ...incoming, generationSettled: false },
+ ].map((candidate) => shouldPreserveGenerationMetadata(existing, candidate)),
+ [false, true, true, true, true],
+ );
+});
+
+test("recovery persists recovered usage alongside the cursor it advanced", () => {
+ // The usage chunk arrives before the terminal event. A cursor published past it and then
+ // reloaded would resume after it, so the counts have to travel with the cursor.
+ const usage = { prompt_tokens: 8, completion_tokens: 12, total_tokens: 20 };
+ const timings = { predicted_per_second: 12 };
+ const midStream = generationRecoveryMetadata({
+ current: { generationRunId: "run-1" },
+ runId: "run-1",
+ status: "running",
+ cursor: 3,
+ lastEventSeq: 5,
+ lengthLimited: false,
+ usage,
+ timings,
+ });
+ assert.equal(midStream.generationSettled, false);
+ assert.deepEqual(midStream.generationRecoveryUsage, usage);
+ assert.deepEqual(midStream.generationRecoveryTimings, timings);
+
+ // A recovery that never saw one must not invent or erase it.
+ const withoutUsage = generationRecoveryMetadata({
+ current: { generationRunId: "run-1" },
+ runId: "run-1",
+ status: "running",
+ cursor: 1,
+ lastEventSeq: 5,
+ lengthLimited: false,
+ });
+ assert.equal("generationRecoveryUsage" in withoutUsage, false);
+
+ // Reloading picks the stored counts back up, so settlement still reports them.
+ const settled = recoveredGenerationFinalMetadata({
+ current: { generationSettled: true },
+ run: {
+ id: "run-1",
+ requestPayload: { model: "local/model" },
+ createdAt: 100,
+ startedAt: 120,
+ completedAt: 1120,
+ },
+ usage: midStream.generationRecoveryUsage as typeof usage,
+ timings: midStream.generationRecoveryTimings as typeof timings,
+ firstChunkAt: 220,
+ totalChunks: 4,
+ });
+ assert.deepEqual(settled.contextUsage, {
+ promptTokens: 8,
+ completionTokens: 12,
+ totalTokens: 20,
+ cachedTokens: 0,
+ cacheWriteTokens: 0,
+ modelId: "local/model",
+ });
+ assert.deepEqual(settled.serverTimings, timings);
+});
+
+test("recovery persists the replay prefix statistics it has applied", () => {
+ const metadata = generationRecoveryMetadata({
+ current: {
+ generationRunId: "run-1",
+ generationChunkCount: 4,
+ },
+ runId: "run-1",
+ status: "running",
+ cursor: 7,
+ lastEventSeq: 9,
+ lengthLimited: false,
+ firstChunkAt: 220,
+ totalChunks: 6,
+ });
+ assert.equal(metadata.generationFirstChunkAt, 220);
+ assert.equal(metadata.generationChunkCount, 6);
+});
diff --git a/studio/frontend/tests/reload-snapshot.test.ts b/studio/frontend/tests/reload-snapshot.test.ts
index f0c86f883ff..7f9b2dd73a3 100644
--- a/studio/frontend/tests/reload-snapshot.test.ts
+++ b/studio/frontend/tests/reload-snapshot.test.ts
@@ -820,7 +820,7 @@ test("mirrors Temporary Chat privacy and lets history completion retire chat she
);
assert.match(
runtimeProviderSource,
- /async load\(\) \{[\s\S]*?const completeLoad =[\s\S]*?unsloth:app-shell-ready[\s\S]*?await listStoredChatMessages\(remoteId\)[\s\S]*?return completeLoad/,
+ /async load\(\) \{[\s\S]*?const completeLoad =[\s\S]*?unsloth:app-shell-ready[\s\S]*?await loadGenerationOverlaySnapshot\([\s\S]*?listStoredChatMessages[\s\S]*?return completeLoad/,
);
assert.match(
runtimeProviderSource,
diff --git a/studio/frontend/tests/rolling-context-window.test.ts b/studio/frontend/tests/rolling-context-window.test.ts
index c1a4a1a354f..f6875675ad2 100644
--- a/studio/frontend/tests/rolling-context-window.test.ts
+++ b/studio/frontend/tests/rolling-context-window.test.ts
@@ -32,6 +32,17 @@ test("the transport preserves standard chunks with context metadata", () => {
assert.match(adapter, /contextTruncation = mergeContextTruncation\(/);
});
+test("durable replay persists context-truncation metadata", () => {
+ const runtimeProvider = readFileSync(
+ new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(runtimeProvider, /contextTruncation: mergeContextTruncation\(/);
+ assert.match(runtimeProvider, /generationChunkCount/);
+ assert.match(adapter, /generationFirstChunkAt/);
+ assert.match(adapter, /generationChunkCount \+= 1/);
+});
+
test("the compaction notice follows the boundary, not the accumulated drops", () => {
// A tool-heavy turn reports 12 drops while the boundary moved to 4. Recording 12 as
// the high-water mark means the next two real advances, to 8 and to 10, are silent.
diff --git a/tests/studio/test_deep_research_frontend_contract.py b/tests/studio/test_deep_research_frontend_contract.py
index c4318ca5fae..76e306f07d7 100644
--- a/tests/studio/test_deep_research_frontend_contract.py
+++ b/tests/studio/test_deep_research_frontend_contract.py
@@ -155,7 +155,7 @@ def test_research_metadata_and_server_merge_are_persisted() -> None:
runtime = source("features/chat/runtime-provider.tsx")
assert "researchRunId: run.id" in adapter
assert "serverManaged: true" in adapter
- assert "getResearchThreadState(remoteId)" in runtime
+ assert re.search(r"getResearchThreadState\(\s*remoteId,?\s*\)", runtime)
assert "preserveServerManaged" in runtime
assert "sameResearchRun" in runtime
assert "existingRevision > incomingRevision" in runtime
diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.py
index e1befe6a858..5d92a3b5112 100644
--- a/tests/studio/test_multi_chat_prompt_queue_contract.py
+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py
@@ -704,11 +704,37 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
)
assert "if (audioBase64 && !queuedRunSettings)" in CHAT_ADAPTER
assert ".setThreadContextUsage(usageThreadKey, usage)" in CHAT_ADAPTER
- assert (
- "usageThreadIsVisible &&\n"
- " useChatRuntimeStore.getState().params.checkpoint === params.checkpoint"
- in CHAT_ADAPTER
+ assert re.search(
+ r"usageThreadIsVisible\s*&&\s*"
+ r"useChatRuntimeStore\.getState\(\)\.params\.checkpoint\s*===\s*params\.checkpoint",
+ CHAT_ADAPTER,
+ )
+
+
+def test_base64_media_turns_stay_on_the_legacy_stream():
+ candidate = _between(
+ CHAT_ADAPTER,
+ "const generationCandidate = Boolean(",
+ ");",
+ )
+ assert "!imageBase64" in candidate
+ assert "!audioBase64" in candidate
+ assert "!videoBase64" in candidate
+
+
+def test_continuations_stay_on_the_legacy_stream():
+ """Continue yields its seeded partial before the request starts.
+
+ That autosave can reach storage before durable admission does, and admission refuses a
+ placeholder that already has content with a 409, which is not one of the errors that
+ falls back to the legacy stream. So the turn would fail outright rather than generate.
+ """
+ candidate = _between(
+ CHAT_ADAPTER,
+ "const generationCandidate = Boolean(",
+ ");",
)
+ assert "!continuation" in candidate
def test_compare_prompt_list_resets_when_preflight_never_starts_a_run():
diff --git a/tests/studio/test_stream_cancel_registration_timing.py b/tests/studio/test_stream_cancel_registration_timing.py
index 5a28432aed9..f0714b0266b 100644
--- a/tests/studio/test_stream_cancel_registration_timing.py
+++ b/tests/studio/test_stream_cancel_registration_timing.py
@@ -100,10 +100,10 @@ def test_no_tracker_enter_inside_async_generators():
def test_tracker_enter_exists_in_sync_body_of_chat_completions():
top = None
for n in ast.walk(_TREE):
- if isinstance(n, ast.AsyncFunctionDef) and n.name == "openai_chat_completions":
+ if isinstance(n, ast.AsyncFunctionDef) and n.name == "produce_openai_chat_completions":
top = n
break
- assert top is not None, "openai_chat_completions handler missing"
+ assert top is not None, "produce_openai_chat_completions handler missing"
count = 0
for sub in ast.walk(top):
if not isinstance(sub, ast.Call):
@@ -117,7 +117,7 @@ def test_tracker_enter_exists_in_sync_body_of_chat_completions():
):
count += 1
assert count >= 3, (
- f"expected >=3 _tracker.__enter__() calls in openai_chat_completions "
+ f"expected >=3 _tracker.__enter__() calls in produce_openai_chat_completions "
f"(one per streaming path), got {count}"
)
@@ -148,7 +148,7 @@ def test_async_generators_cleanup_tracker_in_finally():
def test_chat_completions_streams_avoid_starlette_task_group():
- top = _async_function("openai_chat_completions")
+ top = _async_function("produce_openai_chat_completions")
legacy_calls = []
same_task_calls = 0
for sub in ast.walk(top):
@@ -190,7 +190,7 @@ def test_openai_passthrough_stream_avoids_starlette_task_group():
def test_local_chat_streams_install_same_task_disconnect_watcher():
- top = _async_function("openai_chat_completions")
+ top = _async_function("produce_openai_chat_completions")
assert _calls_name(top, "_await_disconnect_then_cancel"), (
"Local same-task streams must watch request disconnects themselves; "
"do not restore Starlette's task-group StreamingResponse for this."
@@ -725,7 +725,7 @@ def test_stream_chunks_cancel_branch_resets_backend_state():
fn = None
top = None
for n in ast.walk(_TREE):
- if isinstance(n, ast.AsyncFunctionDef) and n.name == "openai_chat_completions":
+ if isinstance(n, ast.AsyncFunctionDef) and n.name == "produce_openai_chat_completions":
top = n
break
assert top is not None