Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studio: render a chat send without waiting on persistence (#8136)
Maheswar Kumar5c332c323fde
diff --git a/studio/backend/core/rag/ingestion.py b/studio/backend/core/rag/ingestion.pyindex cba076f1bee..2f56f2602c2 100644--- a/studio/backend/core/rag/ingestion.py+++ b/studio/backend/core/rag/ingestion.py@@ -29,7 +29,7 @@ _EMBED_BATCH = 64 # bounds peak memory# Poll with a timeout so the generator wakes periodically to detect a gone# client or a terminal job whose worker died without the None sentinel._SSE_POLL_SECONDS = 1.0-_TERMINAL_JOB_STATUSES = {"completed", "failed"}+_TERMINAL_JOB_STATUSES = {"completed", "failed", "cancelled"}def _sha256_file(path: str) -> str:@@ -89,6 +89,23 @@ def _progress(conn, job_id: str, stage: str, progress: float) -> None:_emit(job_id, {"type": "progress", "stage": stage, "progress": progress})+def _abort_if_document_deleted(conn, job_id: str, document_id: str) -> bool:+ """Retire the job when a project delete or a discarded upload removed its document.++ Opens the write transaction the caller then commits into, so a delete cannot land between+ the check and the write. Chunks carry no foreign key to the document, so writing after one+ would strand rows under a dead scope, and completing would report a deleted document as+ indexed and retire the document it was replacing.+ """+ conn.execute("BEGIN IMMEDIATE")+ if store.get_document(conn, document_id) is not None:+ return False+ conn.rollback()+ _set_job(conn, job_id, status = "cancelled", stage = "done", progress = 1.0)+ _emit(job_id, {"type": "error", "stage": "cancelled", "error": "Document was deleted"})+ return True++def _embed_all(texts: list[str], model_name: str | None):"""Embed texts in batches into a flat vector list."""vectors: list = []@@ -151,13 +168,24 @@ def _ocr_scanned_pages(return out, ocred-def _replace_old_document(conn, replaces: tuple[str, str | None] | None, keep_path: str) -> None:+def _replace_old_document(+ conn, replaces: tuple[str, str | None] | None, keep_path: str, document_id: str+) -> None:"""Drop the document this ingestion replaced (stale embedder / empty prior- ingest), called only after the replacement completed successfully."""+ ingest), called only after the replacement completed successfully.++ Checked against the replacement inside the transaction that retires the old row: every+ store helper commits, so a delete that removed the replacement between the completion and+ this call would otherwise take the still-searchable document it was replacing with it.+ """if replaces is None:returnold_id, old_path = replacestry:+ conn.execute("BEGIN IMMEDIATE")+ if store.get_document(conn, document_id) is None:+ conn.rollback()+ returnstore.delete_document(conn, old_id)_remove_upload(old_path, keep_path = keep_path)except Exception: # noqa: BLE001 - the new document is already live@@ -226,8 +254,12 @@ def _run(count = count,)if not chunks:+ # An empty parse still completes the document and retires the one it replaces, so it+ # needs the same guard as the chunk write below.+ if _abort_if_document_deleted(conn, job_id, document_id):+ returnstore.set_document_status(conn, document_id, "completed", num_chunks = 0)- _replace_old_document(conn, replaces, stored_path)+ _replace_old_document(conn, replaces, stored_path, document_id)_set_job(conn, job_id, status = "completed", stage = "done", progress = 1.0)_emit(job_id, {"type": "complete", "num_chunks": 0})return@@ -246,9 +278,15 @@ def _run(regions = None_progress(conn, job_id, "storing", 0.9)+ if _abort_if_document_deleted(conn, job_id, document_id):+ returnstore.add_chunks(conn, scope, document_id, chunks, vectors, regions)+ # add_chunks commits, which releases the lock taken above, so retake it before reporting+ # success: a delete landing in that gap must not be recorded as a completed ingestion.+ if _abort_if_document_deleted(conn, job_id, document_id):+ returnstore.set_document_status(conn, document_id, "completed", num_chunks = len(chunks))- _replace_old_document(conn, replaces, stored_path)+ _replace_old_document(conn, replaces, stored_path, document_id)_set_job(conn, job_id, status = "completed", stage = "done", progress = 1.0)_emit(job_id, {"type": "complete", "num_chunks": len(chunks)})diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex d4b9134e2f9..6e0f8548b4a 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -3,8 +3,12 @@"""Chat history API routes backed by studio.db.++SQLite-backed handlers are sync defs unless they also perform asynchronous cleanup. Those+mixed handlers explicitly send their database transaction through Starlette's threadpool."""+import sqlite3from typing import Annotated, Any, Literal, Optionalfrom fastapi import APIRouter, Depends, HTTPException, Query, Request@@ -17,14 +21,16 @@ from utils.utils import safe_curated_detail, log_and_http_errorfrom storage.studio_db import (ChatMessageConflictError,ChatMessageProtectedError,+ ChatThreadDeletedError,ChatThreadPreconditionFailed,CorruptSettingsError,+ build_chat_history_export,clear_chat_history,count_chat_threads,count_forks_for_message,delete_chat_attachment,- delete_chat_threads,delete_chat_project,+ delete_chat_threads,ensure_chat_project_workspace,fork_chat_thread,get_chat_attachment,@@ -146,6 +152,14 @@ class ChatDeleteRequest(BaseModel):delete_files: bool = False+class ChatClearRequest(BaseModel):+ # The client fences every legacy Dexie thread it holds, so this bound has to sit above what+ # a migrated install can legitimately collect: a 422 here fails the whole clear, and the+ # identical retry fails with it, leaving backend history behind after Clear all.+ ids: list[str] = Field(default_factory = list, max_length = 200_000)+ operationId: Optional[str] = Field(default = None, min_length = 1, max_length = 128)++class ChatCountResponse(BaseModel):count: int@@ -263,7 +277,7 @@ class ChatImportLedgerRecordResponse(BaseModel):@router.get("/threads", response_model = ChatThreadListResponse)-async def list_threads(+def list_threads(model_type: Optional[str] = Query(None),pair_id: Optional[str] = Query(None),project_id: Optional[str] = Query(None),@@ -279,18 +293,37 @@ async def list_threads(return ChatThreadListResponse(threads = [ChatThread(**t) for t in threads])+def _missing_project_error(project_id: Optional[str]) -> HTTPException:+ """The row references a project that is gone, whether the check or the write noticed it."""+ return HTTPException(status_code = 404, detail = f"Project {project_id} not found")+++def _missing_thread_error(thread_id: str) -> HTTPException:+ return HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")+++def _deleted_thread_error(thread_id: str) -> HTTPException:+ return HTTPException(status_code = 410, detail = f"Thread {thread_id} was deleted")++@router.post("/threads", response_model = ChatThread)-async def save_thread(payload: ChatThread, current_subject: str = Depends(get_current_subject)):+def save_thread(payload: ChatThread, current_subject: str = Depends(get_current_subject)):if payload.projectId and get_chat_project(payload.projectId) is None:- raise HTTPException(- status_code = 404,- detail = f"Project {payload.projectId} not found",- )- return ChatThread(**upsert_chat_thread(payload.model_dump()))+ raise _missing_project_error(payload.projectId)+ try:+ return ChatThread(**upsert_chat_thread(payload.model_dump()))+ except ChatThreadDeletedError as exc:+ raise _deleted_thread_error(payload.id) from exc+ except sqlite3.IntegrityError as exc:+ # The project can be deleted between the check above and this insert, and the foreign key+ # then fails. Report the same 404 rather than surfacing a 500.+ if not payload.projectId:+ raise+ raise _missing_project_error(payload.projectId) from exc@router.get("/threads/{thread_id}", response_model = ChatThread)-async def get_thread(thread_id: str, current_subject: str = Depends(get_current_subject)):+def get_thread(thread_id: str, current_subject: str = Depends(get_current_subject)):thread = get_chat_thread(thread_id)if thread is None:raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")@@ -298,7 +331,7 @@ async def get_thread(thread_id: str, current_subject: str = Depends(get_current_@router.patch("/threads/{thread_id}", response_model = ChatThread)-async def patch_thread(+def patch_thread(thread_id: str,payload: ChatThreadPatch,current_subject: str = Depends(get_current_subject),@@ -310,10 +343,7 @@ async def patch_thread(if field in patch and patch[field] is None:raise HTTPException(status_code = 400, detail = f"{field} cannot be null")if patch.get("projectId") and get_chat_project(patch["projectId"]) is None:- raise HTTPException(- status_code = 404,- detail = f"Project {patch['projectId']} not found",- )+ raise _missing_project_error(patch["projectId"])try:thread = update_chat_thread(thread_id,@@ -321,6 +351,11 @@ async def patch_thread(expected_title = expected_title,expected_opening_message_id = expected_opening_message_id,)+ except sqlite3.IntegrityError as exc:+ # Same race as save_thread: the project can go away before this write lands.+ if not patch.get("projectId"):+ raise+ raise _missing_project_error(patch["projectId"]) from excexcept ChatThreadPreconditionFailed:raise HTTPException(status_code = 409,@@ -331,13 +366,24 @@ async def patch_thread(return ChatThread(**thread)-def _cancel_active_research(request: Request, thread_ids: list[str]) -> None:- """Signal any active research runs on these threads to stop before their rows are deleted.+def _cancel_deleted_research_runs(request: Request, run_ids: list[str]) -> None:+ """Signal workers for active runs captured by the deletion transaction."""+ supervisor = getattr(request.app.state, "research_supervisor", None)+ if supervisor is None:+ return+ for run_id in run_ids:+ try:+ supervisor.cancel(run_id)+ except Exception: # noqa: BLE001 - cancellation is best-effort after commit+ logger.warning(+ "chat_history.cancel_deleted_research_failed run_id=%s",+ run_id,+ exc_info = True,+ )- Deleting a thread cascade-deletes its research_runs row, but the worker only notices at its- next lease check, so it can keep doing model/web/RAG work (up to a tool timeout) for a run- that no longer exists. Best-effort: cancellation bookkeeping must never break the deletion.- """++def _cancel_active_research(request: Request, thread_ids: list[str]) -> None:+ """Compatibility path for callers that must cancel runs before deleting their rows."""if not thread_ids:returntry:@@ -414,9 +460,11 @@ async def delete_threads(request: Request,current_subject: str = Depends(get_current_subject),):- _cancel_active_research(request, payload.ids)+ from starlette.concurrency import run_in_threadpool++ deleted_research_run_ids = await run_in_threadpool(delete_chat_threads, payload.ids)+ _cancel_research_runs(request, deleted_research_run_ids)_cancel_active_generations(payload.ids)- delete_chat_threads(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.# In a worker: right after an upgrade this also runs the legacy move, and a@@ -623,7 +671,7 @@ def delete_attachment(@router.get("/projects", response_model = ChatProjectListResponse)-async def list_projects(+def list_projects(include_archived: bool = Query(False), current_subject: str = Depends(get_current_subject)):return ChatProjectListResponse(@@ -635,12 +683,12 @@ async def list_projects(@router.post("/projects", response_model = ChatProject)-async def save_project(payload: ChatProject, current_subject: str = Depends(get_current_subject)):+def save_project(payload: ChatProject, current_subject: str = Depends(get_current_subject)):return ChatProject(**upsert_chat_project(payload.model_dump()))@router.get("/projects/{project_id}", response_model = ChatProject)-async def get_project(project_id: str, current_subject: str = Depends(get_current_subject)):+def get_project(project_id: str, current_subject: str = Depends(get_current_subject)):project = ensure_chat_project_workspace(project_id)if project is None:raise HTTPException(@@ -651,7 +699,7 @@ async def get_project(project_id: str, current_subject: str = Depends(get_curren@router.patch("/projects/{project_id}", response_model = ChatProject)-async def patch_project(+def patch_project(project_id: str,payload: ChatProjectPatch,current_subject: str = Depends(get_current_subject),@@ -678,10 +726,12 @@ async def delete_project(delete_files: bool = Query(False),current_subject: str = Depends(get_current_subject),):+ from starlette.concurrency import run_in_threadpool+# Rows first, files last: a member chat can still be running a tool in the# workspace, and its cwd disappearing mid-call either kills the call or# leaves what it writes next in a directory no project owns.- project = delete_chat_project(project_id, delete_files = False)+ project = await run_in_threadpool(lambda: delete_chat_project(project_id, delete_files = False))if project is None:raise HTTPException(status_code = 404,@@ -695,8 +745,6 @@ async def delete_project(_cancel_research_runs(request, list(project.get("activeResearchRunIds") or []))_cancel_active_generations(member_ids)if project.get("sandboxPath"):- from starlette.concurrency import run_in_threadpool-from core.inference.tools import (finish_workspace_delete_when_idle,forget_orphaned_project,@@ -846,7 +894,7 @@ async def delete_project(@router.get("/threads/{thread_id}/messages", response_model = ChatMessageListResponse)-async def get_thread_messages(thread_id: str, current_subject: str = Depends(get_current_subject)):+def get_thread_messages(thread_id: str, current_subject: str = Depends(get_current_subject)):if get_chat_thread(thread_id) is None:raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")return ChatMessageListResponse(@@ -855,7 +903,7 @@ async def get_thread_messages(thread_id: str, current_subject: str = Depends(get@router.post("/messages:batch", response_model = ChatMessagesBatchResponse)-async def batch_thread_messages(+def batch_thread_messages(payload: ChatMessagesBatchRequest, current_subject: str = Depends(get_current_subject)):"""One round-trip per sidebar/search rebuild instead of N. Unknown thread ids return empty lists."""@@ -868,7 +916,7 @@ async def batch_thread_messages(@router.get("/threads/{thread_id}/messages/{message_id}", response_model = ChatMessage)-async def get_thread_message(+def get_thread_message(thread_id: str,message_id: str,current_subject: str = Depends(get_current_subject),@@ -894,6 +942,10 @@ def save_thread_message(raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")try:return ChatMessage(**upsert_chat_message(payload.model_dump()))+ except sqlite3.IntegrityError as exc:+ if get_chat_thread(thread_id) is None:+ raise _missing_thread_error(thread_id) from exc+ raiseexcept (ChatMessageConflictError, ChatMessageProtectedError) as exc:raise log_and_http_error(exc,@@ -932,6 +984,10 @@ def replace_thread_messages()])+ except sqlite3.IntegrityError as exc:+ if get_chat_thread(thread_id) is None:+ raise _missing_thread_error(thread_id) from exc+ raiseexcept (ChatMessageConflictError, ChatMessageProtectedError) as exc:raise log_and_http_error(exc,@@ -943,12 +999,12 @@ def replace_thread_messages(@router.get("/count", response_model = ChatCountResponse)-async def count_threads(current_subject: str = Depends(get_current_subject)):+def count_threads(current_subject: str = Depends(get_current_subject)):return ChatCountResponse(count = count_chat_threads())@router.get("/import-ledger", response_model = ChatImportLedgerResponse)-async def get_import_ledger(current_subject: str = Depends(get_current_subject)):+def get_import_ledger(current_subject: str = Depends(get_current_subject)):"""Legacy-Dexie import ledger: legacy thread ids already copied into chat tables.The frontend checks this on tab open to decide whether to re-run the Dexie -> studio.db import.@@ -957,7 +1013,7 @@ async def get_import_ledger(current_subject: str = Depends(get_current_subject))@router.post("/import-ledger", response_model = ChatImportLedgerRecordResponse)-async def record_import_ledger(+def record_import_ledger(payload: ChatImportLedgerRecordRequest, current_subject: str = Depends(get_current_subject)):"""Mark each legacy thread id as imported. Idempotent."""@@ -968,21 +1024,40 @@ async def record_import_ledger(@router.delete("")async def clear_history(request: Request,+ payload: Optional[ChatClearRequest] = None,delete_files: bool = False,current_subject: str = Depends(get_current_subject),):- thread_ids = [thread["id"] for thread in list_chat_threads()]- _cancel_active_research(request, thread_ids)- _cancel_active_generations(thread_ids)+ from starlette.concurrency import run_in_threadpool++ # Admission is already closed in the frontend. Include its pending and legacy ids in the+ # transaction's fence so a delayed POST cannot recreate a chat after this returns.+ thread_ids = (+ list(payload.ids)+ if payload is not None+ else [thread["id"] for thread in await run_in_threadpool(list_chat_threads)]+ )++ def _clear_rows() -> tuple[list[str], list[str]]:+ if payload is None:+ cleared, cleared_runs = clear_chat_history()+ else:+ cleared, cleared_runs = clear_chat_history(+ payload.ids,+ operation_id = payload.operationId,+ )+ return cleared, cleared_runs+# 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 = clear_chat_history()+ cleared, cleared_runs = 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.listed = set(thread_ids)late = [thread_id for thread_id in cleared if thread_id not in listed]+ _cancel_active_generations(thread_ids)if late:_cancel_active_generations(late)# By id: the rows went with the threads, so nothing can look them up now.@@ -992,18 +1067,21 @@ async def clear_history(# delete_files matches DELETE /threads: off by default, since the files are# the user's, but a caller clearing everything can ask for them too.removed, kept = await _remove_sandboxes(list(dict.fromkeys(thread_ids + cleared)), delete_files)- return {"status": "deleted", "sandboxes_removed": removed, "sandboxes_kept": kept}+ return {+ "status": "deleted",+ "deletedThreadIds": cleared,+ "sandboxes_removed": removed,+ "sandboxes_kept": kept,+ }@router.get("/settings", response_model = ChatSettingsResponse)-async def get_settings(current_subject: str = Depends(get_current_subject)):+def get_settings(current_subject: str = Depends(get_current_subject)):return ChatSettingsResponse(settings = list_chat_settings())@router.put("/settings", response_model = ChatSettingsResponse)-async def put_settings(- payload: dict[str, Any], current_subject: str = Depends(get_current_subject)-):+def put_settings(payload: dict[str, Any], current_subject: str = Depends(get_current_subject)):try:parsed = ChatSettingsPayload.model_validate(payload)except ValidationError as exc:@@ -1040,7 +1118,7 @@ class ChatForkCountResponse(BaseModel):@router.post("/threads/{thread_id}/fork", response_model = ChatForkResponse)-async def fork_thread(+def fork_thread(thread_id: str,payload: ChatForkRequest,current_subject: str = Depends(get_current_subject),@@ -1064,16 +1142,21 @@ async def fork_thread()base_title = source.get("title") or "New Chat"new_title = f"fork · {base_title}"- forked = fork_chat_thread(- source_thread_id = thread_id,- branch_message_id = payload.messageId,- new_thread_id = payload.newThreadId,- new_title = new_title,- created_at = payload.createdAt,- id_factory = lambda: str(uuid.uuid4()),- )+ try:+ forked = fork_chat_thread(+ source_thread_id = thread_id,+ branch_message_id = payload.messageId,+ new_thread_id = payload.newThreadId,+ new_title = new_title,+ created_at = payload.createdAt,+ id_factory = lambda: str(uuid.uuid4()),+ )+ except ChatThreadDeletedError as exc:+ raise _deleted_thread_error(payload.newThreadId) from excif forked is None:- raise HTTPException(status_code = 500, detail = "Fork failed")+ # The source can be deleted between the reads above and the fork transaction, which the+ # threadpool lets run concurrently. Report it gone rather than as a server fault.+ raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")messages = list_chat_messages(payload.newThreadId)# Best-effort OpenAI container snapshot. Stub: a follow-up patch can# call /v1/containers list+download / create+upload here and patch@@ -1094,7 +1177,7 @@ async def fork_thread("/threads/{thread_id}/messages/{message_id}/forks",response_model = ChatForkCountResponse,)-async def get_fork_count(+def get_fork_count(thread_id: str,message_id: str,current_subject: str = Depends(get_current_subject),@@ -1103,12 +1186,9 @@ async def get_fork_count(@router.get("/export", response_model = ChatExportResponse)-async def export_history(current_subject: str = Depends(get_current_subject)):+def export_history(current_subject: str = Depends(get_current_subject)):from datetime import datetime, timezone-- threads = list_chat_threads(include_archived = True)- projects = list_chat_projects(include_archived = True)- messages = list_chat_messages_for_threads([thread["id"] for thread in threads])+ projects, threads, messages = build_chat_history_export()return ChatExportResponse(exportedAt = datetime.now(timezone.utc).isoformat(),version = 1,diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.pyindex 918262b934b..ed0b0e1e9bc 100644--- a/studio/backend/routes/rag.py+++ b/studio/backend/routes/rag.py@@ -406,6 +406,20 @@ def list_thread_documents(thread_id: str, subject: str = Depends(get_current_subconn.close()+def _discard_document(document_id: str) -> None:+ """Drop a document and its upload after the scope it was ingested for disappeared."""+ conn = _rag_connection()+ try:+ document = store.get_document(conn, document_id) or {}+ store.delete_document(conn, document_id)+ finally:+ conn.close()+ # Same uploads-root confinement as every other cleanup path, and best-effort for the same+ # reason: on Windows commonpath raises across drives and os.remove raises while the ingestion+ # worker still holds the file, neither of which should turn this into a 500.+ _remove_stored_upload(document.get("stored_path"))++@router.post("/projects/{project_id}/documents")async def upload_project_document(project_id: str,@@ -432,6 +446,11 @@ async def upload_project_document(ocr = ocr,caption = caption,)+ # the project delete runs in the threadpool and can commit after the check above, once its own+ # RAG cleanup has already listed the project's documents+ if get_chat_project(project_id) is None:+ _discard_document(document_id)+ raise HTTPException(status_code = 404, detail = "Project not found")return {"documentId": document_id, "jobId": job_id, "filename": filename}diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.pyindex bd41e769235..f0e43ba5bd8 100644--- a/studio/backend/routes/research_runs.py+++ b/studio/backend/routes/research_runs.py@@ -8,6 +8,7 @@ from __future__ import annotationsimport asyncioimport jsonimport re+import sqlite3import uuidfrom concurrent.futures import ThreadPoolExecutorfrom typing import Any@@ -295,7 +296,7 @@ def _sanitize_config(payload: CreateResearchRun, thread: dict) -> dict:@router.post("", status_code = 202)-async def create_research_run(+def create_research_run(payload: CreateResearchRun,request: Request,current_subject: str = Depends(get_current_subject),@@ -332,6 +333,12 @@ async def create_research_run()except db.ResearchConflictError as exc:raise HTTPException(status_code = 409, detail = str(exc)) from exc+ except sqlite3.IntegrityError as exc:+ # The thread can be deleted between the check above and this insert, and the foreign key+ # then fails. Report it gone rather than as a server fault.+ raise HTTPException(status_code = 404, detail = "Thread not found") from exc+ if run is None:+ raise HTTPException(status_code = 404, detail = "Thread not found")supervisor = getattr(request.app.state, "research_supervisor", None)if supervisor is not None:supervisor.note_request_port(request)@@ -340,7 +347,7 @@ async def create_research_run(@router.get("/active")-async def active_research_runs(+def active_research_runs(thread_id: str = Query(alias = "threadId"), current_subject: str = Depends(get_current_subject)):return {@@ -350,12 +357,12 @@ async def active_research_runs(@router.get("/{run_id}")-async def get_research_run(run_id: str, current_subject: str = Depends(get_current_subject)):+def get_research_run(run_id: str, current_subject: str = Depends(get_current_subject)):return _require_run(run_id)@router.put("/{run_id}/plan")-async def update_research_plan(+def update_research_plan(run_id: str,payload: UpdatePlan,current_subject: str = Depends(get_current_subject),@@ -371,7 +378,7 @@ async def update_research_plan(@router.post("/{run_id}/approve")-async def approve_research_plan(+def approve_research_plan(run_id: str,payload: ApprovePlan,request: Request,@@ -392,7 +399,7 @@ async def approve_research_plan(@router.post("/{run_id}/cancel")-async def cancel_research_run(+def cancel_research_run(run_id: str,request: Request,current_subject: str = Depends(get_current_subject),@@ -408,7 +415,7 @@ async def cancel_research_run(@router.post("/{run_id}/retry")-async def retry_research_run(+def retry_research_run(run_id: str,request: Request,current_subject: str = Depends(get_current_subject),diff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.pyindex c21e21e3a0a..406cebd1109 100644--- a/studio/backend/storage/rag_db.py+++ b/studio/backend/storage/rag_db.py@@ -286,9 +286,11 @@ def reconcile_orphaned_ingestion_jobs() -> int:return 0conn = get_connection()try:+ # 'cancelled' is terminal too: the job stopped because its document was deleted, so+ # rewriting it to failed would report a deliberate cancellation as an indexing failure.rows = conn.execute("SELECT id, document_id FROM ingestion_jobs "- "WHERE status NOT IN ('completed', 'failed')"+ "WHERE status NOT IN ('completed', 'failed', 'cancelled')").fetchall()for row in rows:doc = conn.execute(diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 830452627ec..a83f7d1bf2a 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -244,6 +244,11 @@ def _delete_project_workspace(project: dict) -> None:shutil.rmtree(root_resolved)+def delete_chat_project_workspace(project: dict) -> None:+ """Backward-compatible name for callers predating sandbox-aware cleanup."""+ delete_project_workspace(project)++def _ensure_schema(conn: sqlite3.Connection) -> None:"""Create tables and indexes if they don't exist. Called once per process."""conn.execute("PRAGMA journal_mode=WAL")@@ -380,6 +385,31 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:)""")+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS chat_thread_tombstones (+ id TEXT NOT NULL PRIMARY KEY,+ deleted_at INTEGER NOT NULL+ ) WITHOUT ROWID+ """+ )+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS chat_clear_operations (+ id TEXT NOT NULL PRIMARY KEY,+ active_research_run_ids_json TEXT NOT NULL,+ deleted_thread_ids_json TEXT NOT NULL DEFAULT '[]',+ cleared_at INTEGER NOT NULL+ ) WITHOUT ROWID+ """+ )+ chat_clear_operation_cols = {+ row[1] for row in conn.execute("PRAGMA table_info(chat_clear_operations)").fetchall()+ }+ if "deleted_thread_ids_json" not in chat_clear_operation_cols:+ conn.execute(+ "ALTER TABLE chat_clear_operations ADD COLUMN deleted_thread_ids_json TEXT NOT NULL DEFAULT '[]'"+ )conn.execute("""CREATE TABLE IF NOT EXISTS chat_messages (@@ -958,12 +988,20 @@ def bulk_upsert_prompt_lists(lists: list[dict]) -> int:conn.close()-def get_connection() -> sqlite3.Connection:+# sqlite's own default, kept for every caller that may run on the event loop+_BUSY_TIMEOUT_SECONDS = 5.0++# only for the chat history transactions that run in Starlette's threadpool, where a large clear+# can hold the writer lock past the default and the failure escapes as an unmapped 500+_CONTENDED_BUSY_TIMEOUT_SECONDS = 30.0+++def get_connection(busy_timeout_seconds: float = _BUSY_TIMEOUT_SECONDS) -> sqlite3.Connection:"""Open studio.db with WAL mode, create tables once per process, enable foreign keys."""global _schema_readydb_path = studio_db_path()ensure_dir(db_path.parent)- conn = sqlite3.connect(str(db_path))+ conn = sqlite3.connect(str(db_path), timeout = busy_timeout_seconds)conn.row_factory = sqlite3.Row# foreign_keys is session-scoped; set per connectionconn.execute("PRAGMA foreign_keys=ON")@@ -1611,9 +1649,24 @@ def _chat_message_from_row(row: sqlite3.Row) -> dict:return message+class ChatThreadDeletedError(RuntimeError):+ """Raised when a stale writer tries to recreate a deleted thread id."""+++def _raise_if_chat_thread_deleted(conn: sqlite3.Connection, thread_id: str) -> None:+ row = conn.execute(+ "SELECT 1 FROM chat_thread_tombstones WHERE id = ?",+ (thread_id,),+ ).fetchone()+ if row is not None:+ raise ChatThreadDeletedError(thread_id)++def upsert_chat_thread(thread: dict) -> dict:- conn = get_connection()+ conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)try:+ conn.execute("BEGIN IMMEDIATE")+ _raise_if_chat_thread_deleted(conn, thread["id"])conn.execute("""INSERT INTO chat_threads@@ -1651,6 +1704,9 @@ def upsert_chat_thread(thread: dict) -> dict:)conn.commit()return get_chat_thread(thread["id"]) or thread+ except Exception:+ conn.rollback()+ raisefinally:conn.close()@@ -1781,6 +1837,36 @@ def list_chat_threads(conn.close()+def build_chat_history_export() -> tuple[list[dict], list[dict], list[dict]]:+ """Read projects, threads, and messages from one SQLite snapshot."""+ conn = get_connection()+ try:+ conn.execute("BEGIN")+ thread_rows = conn.execute(+ """+ SELECT * FROM chat_threads+ ORDER BY COALESCE(updated_at, created_at) DESC, created_at DESC+ """+ ).fetchall()+ project_rows = conn.execute(+ "SELECT * FROM chat_projects ORDER BY updated_at DESC"+ ).fetchall()+ message_rows = conn.execute(+ "SELECT * FROM chat_messages ORDER BY created_at ASC, id ASC"+ ).fetchall()+ conn.commit()+ return (+ [_chat_project_from_row(row) for row in project_rows],+ [_chat_thread_from_row(row) for row in thread_rows],+ [_chat_message_from_row(row) for row in message_rows],+ )+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.close()++def _reparent_surviving_forks(conn: sqlite3.Connection, deleted_ids: set[str]) -> None:"""Keep fork lineage connected across any thread deletion path."""if not deleted_ids:@@ -1805,14 +1891,73 @@ def _reparent_surviving_forks(conn: sqlite3.Connection, deleted_ids: set[str]) -)-def delete_chat_threads(ids: list[str]) -> None:+def _tombstone_chat_threads(conn: sqlite3.Connection, thread_ids: Iterable[str]) -> None:+ deleted_at = int(datetime.now(timezone.utc).timestamp() * 1000)+ conn.executemany(+ """+ INSERT INTO chat_thread_tombstones (id, deleted_at)+ VALUES (?, ?)+ ON CONFLICT(id) DO UPDATE SET deleted_at = excluded.deleted_at+ """,+ [(thread_id, deleted_at) for thread_id in sorted(set(thread_ids))],+ )+++# Only these states can already own a worker. Queued, paused, and approval rows are removed before+# they can be claimed, so signalling them would only leave unused supervisor cancellation events.+_ACTIVE_RESEARCH_RUN_STATUSES = (+ "planning",+ "running",+ "cancelling",+)+++def _active_research_run_ids(+ conn: sqlite3.Connection, thread_ids: set[str] | None = None+) -> list[str]:+ # lease_owner is the other half of "can already own a worker": a planning run that no worker+ # has claimed yet never will once its row is gone, and signalling it would leave a+ # cancellation event in the supervisor that nothing is left to consume.+ status_placeholders = ",".join("?" for _ in _ACTIVE_RESEARCH_RUN_STATUSES)+ if thread_ids is None:+ rows = conn.execute(+ f"""+ SELECT id, created_at FROM research_runs+ WHERE status IN ({status_placeholders}) AND lease_owner IS NOT NULL+ """,+ _ACTIVE_RESEARCH_RUN_STATUSES,+ ).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]+ thread_placeholders = ",".join("?" for _ in chunk)+ rows.extend(+ conn.execute(+ f"SELECT id, created_at FROM research_runs "+ f"WHERE thread_id IN ({thread_placeholders}) "+ f"AND status IN ({status_placeholders}) "+ f"AND lease_owner IS NOT NULL",+ (*chunk, *_ACTIVE_RESEARCH_RUN_STATUSES),+ ).fetchall()+ )+ 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]:if not ids:- return- conn = get_connection()+ return []+ conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)try:conn.execute("BEGIN IMMEDIATE")_ensure_chat_attachment_inventory_current(conn)- _reparent_surviving_forks(conn, set(ids))+ thread_ids = set(ids)+ active_research_run_ids = _active_research_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.+ _tombstone_chat_threads(conn, thread_ids)conn.executemany("DELETE FROM chat_attachment_tombstones WHERE thread_id = ?",[(id,) for id in ids],@@ -1820,6 +1965,7 @@ def delete_chat_threads(ids: list[str]) -> None: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_idsexcept Exception:conn.rollback()raise@@ -1827,30 +1973,81 @@ def delete_chat_threads(ids: list[str]) -> None:conn.close()-def clear_chat_history() -> "tuple[list[str], list[str]]":+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)+++def clear_chat_history_with_active_research_runs(+ additional_thread_ids: Iterable[str] = (), operation_id: Optional[str] = None+) -> tuple[list[str], list[str]]:+ removed, active_runs = clear_chat_history(+ additional_thread_ids,+ operation_id = operation_id,+ )+ return active_runs, removed+++def clear_chat_history(+ additional_thread_ids: Iterable[str] = (), operation_id: Optional[str] = None+) -> "tuple[list[str], list[str]]":"""Delete every chat thread. Returns (thread ids removed, research runs cascaded).Both taken inside the same transaction: another process can add a threadbetween a listing and this call, its sandbox has to be cleaned up too, andafter the cascade nothing can tell the supervisor which runs to stop."""- conn = get_connection()+ conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)try:conn.execute("BEGIN IMMEDIATE")+ if operation_id is not None:+ completed = conn.execute(+ """+ SELECT deleted_thread_ids_json+ FROM chat_clear_operations WHERE id = ?+ """,+ (operation_id,),+ ).fetchone()+ if completed is not None:+ 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"])), []_ensure_chat_attachment_inventory_current(conn)- removed = [str(row[0]) for row in conn.execute("SELECT id FROM chat_threads")]+ removed = sorted(str(row[0]) for row in conn.execute("SELECT id FROM chat_threads"))+ status_placeholders = ",".join("?" for _ in _ACTIVE_RESEARCH_RUN_STATUSES)active_runs = [- str(row[0])+ row["id"]for row in conn.execute(- "SELECT id FROM research_runs "- "WHERE status NOT IN ('cancelled', 'completed', 'failed')"+ f"SELECT id FROM research_runs WHERE status IN ({status_placeholders}) "+ "AND lease_owner IS NOT NULL ORDER BY created_at, id",+ _ACTIVE_RESEARCH_RUN_STATUSES,)]+ # 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")conn.execute("DELETE FROM chat_threads")_mark_chat_attachment_inventory_clean(conn)+ if operation_id is not None:+ conn.execute(+ """+ INSERT INTO chat_clear_operations (+ id, active_research_run_ids_json, deleted_thread_ids_json, cleared_at+ ) VALUES (?, ?, ?, ?)+ """,+ (+ operation_id,+ json.dumps(active_runs),+ json.dumps(removed),+ int(datetime.now(timezone.utc).timestamp() * 1000),+ ),+ )conn.commit()return removed, active_runs+ except Exception:+ conn.rollback()+ raisefinally:conn.close()@@ -1936,6 +2133,14 @@ def ensure_chat_project_workspace(id: str) -> Optional[dict]:return Noneroot_path = project.get("rootPath") or _default_project_root(project)root_path = _ensure_project_workspace(root_path)+ # a delete running in another threadpool worker can drop the row at any point before the+ # directory is created, so confirm the project outlived the create rather than trusting a+ # pre-create snapshot. Removing the directory here is not this function's call: only the+ # delete path knows whether the user asked to keep the files, and the row may have had a+ # populated workspace already. An empty directory left behind is the cheaper outcome.+ project = get_chat_project(id)+ if project is None:+ return Noneif project.get("rootPath") == root_path:return projectconn = get_connection()@@ -1972,7 +2177,7 @@ def list_chat_projects(include_archived: bool = False) -> list[dict]:def delete_chat_project(id: str, delete_files: bool = False) -> Optional[dict]:- conn = get_connection()+ conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)try:conn.execute("BEGIN IMMEDIATE")_ensure_chat_attachment_inventory_current(conn)@@ -1996,16 +2201,21 @@ def delete_chat_project(id: str, delete_files: bool = False) -> Optional[dict]:row["id"]for row in conn.execute("SELECT id FROM research_runs WHERE thread_id IN ({}) "- "AND status NOT IN ('cancelled', 'completed', 'failed')".format(- ",".join("?" for _ in thread_ids) or "NULL"+ "AND status IN ({}) AND lease_owner IS NOT NULL "+ "ORDER BY created_at, id".format(+ ",".join("?" for _ in thread_ids) or "NULL",+ ",".join("?" for _ in _ACTIVE_RESEARCH_RUN_STATUSES),),- tuple(thread_ids),+ (*tuple(sorted(thread_ids)), *_ACTIVE_RESEARCH_RUN_STATUSES),)]if thread_idselse [])_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.+ _tombstone_chat_threads(conn, thread_ids)conn.execute("DELETE FROM chat_threads WHERE project_id = ?", (id,))conn.execute("DELETE FROM chat_projects WHERE id = ?", (id,))_mark_chat_attachment_inventory_clean(conn)@@ -2025,6 +2235,13 @@ def delete_chat_project(id: str, delete_files: bool = False) -> Optional[dict]:conn.close()+def delete_chat_project_with_active_research_runs(id: str) -> tuple[Optional[dict], list[str]]:+ project = delete_chat_project(id, delete_files = False)+ if project is None:+ return None, []+ return project, list(project.get("activeResearchRunIds") or [])++class ChatMessageConflictError(RuntimeError):"""Raised when a chat message id already belongs to another thread."""@@ -2833,6 +3050,7 @@ def fork_chat_thread(try:conn.execute("BEGIN IMMEDIATE")_ensure_chat_attachment_inventory_current(conn)+ _raise_if_chat_thread_deleted(conn, new_thread_id)src = conn.execute("SELECT * FROM chat_threads WHERE id = ?", (source_thread_id,)).fetchone()diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.pyindex 26ef2cfbc4b..8766a308747 100644--- a/studio/backend/tests/test_chat_history_routes.py+++ b/studio/backend/tests/test_chat_history_routes.py@@ -2,9 +2,12 @@# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import asyncio+import inspectimport osimport re+import sqlite3import sys+from types import SimpleNamespaceimport pytestfrom fastapi import HTTPException@@ -28,6 +31,22 @@ def _message(message_id: str, thread_id: str) -> chat_history.ChatMessage:)+def test_async_delete_handlers_dispatch_sqlite_to_the_threadpool():+ """Cleanup handlers may be async, but their blocking sqlite work must leave the event loop."""+ coroutine_handlers = sorted(+ route.endpoint.__name__+ for route in chat_history.router.routes+ if inspect.iscoroutinefunction(route.endpoint)+ )+ assert coroutine_handlers == ["clear_history", "delete_project", "delete_threads"]+ for handler in (+ chat_history.clear_history,+ chat_history.delete_project,+ chat_history.delete_threads,+ ):+ assert "run_in_threadpool" in inspect.getsource(handler)++def test_replace_thread_messages_rejects_body_thread_mismatch(monkeypatch):called = False@@ -43,15 +62,13 @@ def test_replace_thread_messages_rejects_body_thread_mismatch(monkeypatch):monkeypatch.setattr(chat_history, "sync_chat_messages", fake_sync_chat_messages)with pytest.raises(HTTPException) as exc_info:- asyncio.run(- chat_history.replace_thread_messages(- "thread-1",- chat_history.ChatMessageSyncRequest(- messages = [_message("msg-1", "thread-2")],- pruneMissing = True,- ),- current_subject = "test-user",- )+ chat_history.replace_thread_messages(+ "thread-1",+ chat_history.ChatMessageSyncRequest(+ messages = [_message("msg-1", "thread-2")],+ pruneMissing = True,+ ),+ current_subject = "test-user",)assert exc_info.value.status_code == 400@@ -70,16 +87,178 @@ def test_replace_thread_messages_reports_protected_research_turn(monkeypatch):monkeypatch.setattr(chat_history, "sync_chat_messages", reject_prune)with pytest.raises(HTTPException) as exc_info:+ chat_history.replace_thread_messages(+ "thread-1",+ chat_history.ChatMessageSyncRequest(messages = [], pruneMissing = True),+ current_subject = "test-user",+ )++ assert exc_info.value.status_code == 409+ assert "Research prompts and responses" in str(exc_info.value.detail)+++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))++ def missing_parent(*_args, **_kwargs):+ raise sqlite3.IntegrityError("FOREIGN KEY constraint failed")++ monkeypatch.setattr(chat_history, "upsert_chat_message", missing_parent)++ with pytest.raises(HTTPException) as exc_info:+ chat_history.save_thread_message(+ "thread-1",+ "msg-1",+ _message("msg-1", "thread-1"),+ current_subject = "test-user",+ )++ assert exc_info.value.status_code == 404+ assert exc_info.value.detail == "Thread thread-1 not found"+++def test_replace_thread_messages_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))++ def missing_parent(*_args, **_kwargs):+ raise sqlite3.IntegrityError("FOREIGN KEY constraint failed")++ monkeypatch.setattr(chat_history, "sync_chat_messages", missing_parent)++ with pytest.raises(HTTPException) as exc_info:+ chat_history.replace_thread_messages(+ "thread-1",+ chat_history.ChatMessageSyncRequest(+ messages = [_message("msg-1", "thread-1")],+ pruneMissing = True,+ ),+ current_subject = "test-user",+ )++ assert exc_info.value.status_code == 404+ assert exc_info.value.detail == "Thread thread-1 not found"+++def test_save_thread_message_does_not_mask_an_unrelated_integrity_error(monkeypatch):+ monkeypatch.setattr(+ chat_history,+ "get_chat_thread",+ lambda _thread_id: {"id": "thread-1"},+ )+ failure = sqlite3.IntegrityError("unrelated constraint")++ def raise_unrelated(*_args, **_kwargs):+ raise failure++ monkeypatch.setattr(chat_history, "upsert_chat_message", raise_unrelated)++ with pytest.raises(sqlite3.IntegrityError) as exc_info:+ chat_history.save_thread_message(+ "thread-1",+ "msg-1",+ _message("msg-1", "thread-1"),+ current_subject = "test-user",+ )++ assert exc_info.value is failure+++def test_save_thread_distinguishes_a_tombstone_from_an_unknown_id(monkeypatch):+ def reject_deleted_thread(_thread):+ raise chat_history.ChatThreadDeletedError("thread-1")++ monkeypatch.setattr(chat_history, "upsert_chat_thread", reject_deleted_thread)+ payload = chat_history.ChatThread(+ id = "thread-1",+ title = "Deleted",+ modelType = "base",+ modelId = "model-1",+ createdAt = 1,+ )++ with pytest.raises(HTTPException) as exc_info:+ chat_history.save_thread(payload, current_subject = "test-user")++ assert exc_info.value.status_code == 410+ assert exc_info.value.detail == "Thread thread-1 was deleted"+++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):+ captured.extend(thread_ids)+ captured_operation_ids.append(operation_id)+ return list(thread_ids), []++ async def remove_sandboxes(_thread_ids, _delete_files):+ return 0, []++ monkeypatch.setattr(chat_history, "clear_chat_history", clear_with_ids)+ monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)+ monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)+ monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)+ request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))++ response = asyncio.run(+ chat_history.clear_history(+ request,+ chat_history.ChatClearRequest(ids = ["pending-thread"], operationId = "clear-operation-1"),+ current_subject = "test-user",+ )+ )++ assert response == {+ "status": "deleted",+ "deletedThreadIds": ["pending-thread"],+ "sandboxes_removed": 0,+ "sandboxes_kept": [],+ }+ assert captured == ["pending-thread"]+ assert captured_operation_ids == ["clear-operation-1"]+++def test_project_delete_cancels_research_before_workspace_cleanup(monkeypatch):+ project = {+ "id": "project-1",+ "name": "Project",+ "createdAt": 1,+ "updatedAt": 1,+ "memberIds": ["thread-1"],+ "activeResearchRunIds": ["run-1"],+ }+ cancelled: list[str] = []+ monkeypatch.setattr(+ chat_history,+ "delete_chat_project",+ lambda _project_id, delete_files = False: project,+ )+ monkeypatch.setattr(+ chat_history,+ "_cancel_research_runs",+ lambda _request, run_ids: cancelled.extend(run_ids),+ )+ monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)++ async def fail_workspace_cleanup(_ids, _delete_files):+ raise OSError("workspace is busy")++ monkeypatch.setattr(chat_history, "_remove_sandboxes", fail_workspace_cleanup)++ with pytest.raises(OSError, match = "workspace is busy"):asyncio.run(- chat_history.replace_thread_messages(- "thread-1",- chat_history.ChatMessageSyncRequest(messages = [], pruneMissing = True),+ chat_history.delete_project(+ "project-1",+ SimpleNamespace(),+ delete_files = True,current_subject = "test-user",))- assert exc_info.value.status_code == 409- assert "Research prompts and responses" in str(exc_info.value.detail)+ assert cancelled == ["run-1"]# ---------------------------------------------------------------------------@@ -244,11 +423,11 @@ def test_get_import_ledger_round_trips_through_storage(monkeypatch):monkeypatch.setattr(chat_history, "list_chat_legacy_imports", fake_list)- response = asyncio.run(chat_history.get_import_ledger(current_subject = "test-user"))+ response = chat_history.get_import_ledger(current_subject = "test-user")assert response.threadIds == []seen.extend(["legacy-a", "legacy-b"])- response = asyncio.run(chat_history.get_import_ledger(current_subject = "test-user"))+ response = chat_history.get_import_ledger(current_subject = "test-user")assert response.threadIds == ["legacy-a", "legacy-b"]@@ -262,13 +441,11 @@ def test_record_import_ledger_returns_accepted_and_inserted(monkeypatch):monkeypatch.setattr(chat_history, "upsert_chat_legacy_imports", fake_upsert)- response = asyncio.run(- chat_history.record_import_ledger(- payload = chat_history.ChatImportLedgerRecordRequest(- threadIds = ["a", "b", "c"],- ),- current_subject = "test-user",- )+ response = chat_history.record_import_ledger(+ payload = chat_history.ChatImportLedgerRecordRequest(+ threadIds = ["a", "b", "c"],+ ),+ current_subject = "test-user",)assert response.accepted == 3assert response.inserted == 1@@ -291,16 +468,14 @@ def test_record_import_ledger_rejects_oversize_payload():def test_fork_thread_404_when_source_missing(monkeypatch):monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: None)with pytest.raises(HTTPException) as exc:- asyncio.run(- chat_history.fork_thread(- thread_id = "missing",- payload = chat_history.ChatForkRequest(- messageId = "m1",- newThreadId = "new",- createdAt = 1,- ),- current_subject = "test-user",- )+ chat_history.fork_thread(+ thread_id = "missing",+ payload = chat_history.ChatForkRequest(+ messageId = "m1",+ newThreadId = "new",+ createdAt = 1,+ ),+ current_subject = "test-user",)assert exc.value.status_code == 404@@ -309,16 +484,14 @@ def test_fork_thread_404_when_branch_message_missing(monkeypatch):monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: {"id": _id, "title": "T"})monkeypatch.setattr(chat_history, "get_chat_message", lambda _t, _m: None)with pytest.raises(HTTPException) as exc:- asyncio.run(- chat_history.fork_thread(- thread_id = "src",- payload = chat_history.ChatForkRequest(- messageId = "missing",- newThreadId = "new",- createdAt = 1,- ),- current_subject = "test-user",- )+ chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(+ messageId = "missing",+ newThreadId = "new",+ createdAt = 1,+ ),+ current_subject = "test-user",)assert exc.value.status_code == 404@@ -372,16 +545,14 @@ def test_fork_thread_happy_path(monkeypatch):}],)- response = asyncio.run(- chat_history.fork_thread(- thread_id = "src",- payload = chat_history.ChatForkRequest(- messageId = "m1",- newThreadId = "new",- createdAt = 2,- ),- current_subject = "test-user",- )+ response = chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(+ messageId = "m1",+ newThreadId = "new",+ createdAt = 2,+ ),+ current_subject = "test-user",)assert response.thread.id == "new"assert response.thread.title == "fork · Original"@@ -430,16 +601,14 @@ def test_fork_thread_warns_when_parent_had_container(monkeypatch):},)monkeypatch.setattr(chat_history, "list_chat_messages", lambda _id: [])- response = asyncio.run(- chat_history.fork_thread(- thread_id = "src",- payload = chat_history.ChatForkRequest(- messageId = "m1",- newThreadId = "new",- createdAt = 2,- ),- current_subject = "test-user",- )+ response = chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(+ messageId = "m1",+ newThreadId = "new",+ createdAt = 2,+ ),+ current_subject = "test-user",)assert response.containerSnapshotWarning is not Noneassert "fresh" in response.containerSnapshotWarning.lower()@@ -447,11 +616,9 @@ def test_fork_thread_warns_when_parent_had_container(monkeypatch):def test_get_fork_count(monkeypatch):monkeypatch.setattr(chat_history, "count_forks_for_message", lambda _t, _m: 3)- response = asyncio.run(- chat_history.get_fork_count(- thread_id = "t",- message_id = "m",- current_subject = "test-user",- )+ response = chat_history.get_fork_count(+ thread_id = "t",+ message_id = "m",+ current_subject = "test-user",)assert response.count == 3diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.pyindex 094aa12682b..136d817b653 100644--- a/studio/backend/tests/test_chat_history_storage.py+++ b/studio/backend/tests/test_chat_history_storage.py@@ -128,6 +128,48 @@ def test_chat_thread_updated_at_bumps_on_message_writes(tmp_path, monkeypatch):assert studio_db.get_chat_thread("thread-1")["updatedAt"] == 1_700_000_001_000+def test_chat_export_reads_one_snapshot_during_concurrent_delete(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ project = studio_db.upsert_chat_project(_project())+ thread = {**_thread(), "projectId": project["id"]}+ studio_db.upsert_chat_thread(thread)+ studio_db.upsert_chat_message(_message("msg-1", 1, "hello"))++ original_get_connection = studio_db.get_connection+ reader = original_get_connection()+ deleted = False++ class InterleavingConnection:+ def execute(+ self,+ sql,+ parameters = (),+ ):+ nonlocal deleted+ cursor = reader.execute(sql, parameters)+ if not deleted and "SELECT * FROM chat_threads" in sql:+ deleted = True+ writer = original_get_connection()+ try:+ writer.execute("DELETE FROM chat_threads WHERE id = ?", (thread["id"],))+ writer.execute("DELETE FROM chat_projects WHERE id = ?", (project["id"],))+ writer.commit()+ finally:+ writer.close()+ return cursor++ def __getattr__(self, name):+ return getattr(reader, name)++ monkeypatch.setattr(studio_db, "get_connection", lambda: InterleavingConnection())+ projects, threads, messages = studio_db.build_chat_history_export()++ assert deleted+ assert [item["id"] for item in projects] == [project["id"]]+ assert [item["id"] for item in threads] == [thread["id"]]+ assert [item["id"] for item in messages] == ["msg-1"]++def test_chat_thread_updated_at_recomputed_when_pruning(tmp_path, monkeypatch):_reset_studio_db(tmp_path, monkeypatch)thread = studio_db.upsert_chat_thread(_thread())@@ -266,6 +308,63 @@ def test_chat_projects_delete_cascades_threads_and_messages(tmp_path, monkeypatcassert studio_db.get_chat_thread("thread-1") is Noneassert studio_db.list_chat_messages("thread-1") == []assert (tmp_path / "Projects" / "Research-project").exists()+ with pytest.raises(studio_db.ChatThreadDeletedError):+ studio_db.upsert_chat_thread({**_thread(), "projectId": "project-1"})+++def test_thread_delete_blocks_a_late_create_with_the_same_id(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)++ studio_db.delete_chat_threads(["late-thread"])++ with pytest.raises(studio_db.ChatThreadDeletedError):+ studio_db.upsert_chat_thread(_thread("late-thread"))+ assert studio_db.get_chat_thread("late-thread") is None+++def test_clear_blocks_a_stale_recreate_of_a_deleted_thread(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread("thread-1"))++ studio_db.clear_chat_history_with_active_research_runs(["pending-thread"])++ with pytest.raises(studio_db.ChatThreadDeletedError):+ studio_db.upsert_chat_thread(_thread("thread-1"))+ with pytest.raises(studio_db.ChatThreadDeletedError):+ studio_db.upsert_chat_thread(_thread("pending-thread"))+ assert studio_db.get_chat_thread("thread-1") is None+ assert studio_db.get_chat_thread("pending-thread") is None+++def test_clear_reports_only_threads_that_had_a_row(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread("thread-1"))++ _, deleted_ids = studio_db.clear_chat_history_with_active_research_runs(["never-committed"])++ # the fenced id is still tombstoned, but reporting it would inflate the cleared count+ assert deleted_ids == ["thread-1"]+ with pytest.raises(studio_db.ChatThreadDeletedError):+ studio_db.upsert_chat_thread(_thread("never-committed"))+++def test_repeated_clear_operation_does_not_delete_later_threads(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread("before-clear"))++ _, first_deleted_ids = studio_db.clear_chat_history_with_active_research_runs(+ operation_id = "clear-operation-1"+ )+ studio_db.upsert_chat_thread(_thread("after-clear"))++ _, repeated_deleted_ids = studio_db.clear_chat_history_with_active_research_runs(+ operation_id = "clear-operation-1"+ )++ assert first_deleted_ids == ["before-clear"]+ assert repeated_deleted_ids == first_deleted_ids+ assert studio_db.get_chat_thread("before-clear") is None+ assert studio_db.get_chat_thread("after-clear") is not Nonedef test_chat_project_delete_files_removes_workspace(@@ -682,6 +781,24 @@ def test_fork_chat_thread_returns_none_for_missing_source(tmp_path, monkeypatch)assert result is None+def test_fork_chat_thread_rejects_a_deleted_target_id(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread("src"))+ studio_db.upsert_chat_message(_msg("m1", None, 1))+ studio_db.delete_chat_threads(["fork"])++ with pytest.raises(studio_db.ChatThreadDeletedError):+ studio_db.fork_chat_thread(+ source_thread_id = "src",+ branch_message_id = "m1",+ new_thread_id = "fork",+ new_title = "f",+ created_at = 2,+ id_factory = lambda: "new-1",+ )+ assert studio_db.get_chat_thread("fork") is None++def test_count_forks_for_message(tmp_path, monkeypatch):_reset_studio_db(tmp_path, monkeypatch)studio_db.upsert_chat_thread(_thread("src"))@@ -944,3 +1061,50 @@ def test_an_empty_stored_parent_reads_as_the_root(tmp_path, monkeypatch):assert studio_db._surviving_parent_id(conn, "src", "a0", set()) is Nonefinally:conn.close()+++def test_deleting_a_thread_signals_only_research_runs_a_worker_owns(tmp_path, monkeypatch):+ # A fresh run sits in 'planning' with no lease. Deleting its thread cascades the row away, so+ # no worker can ever claim it; signalling it would leave a cancellation event in the+ # supervisor that nothing is left to consume.+ _research_thread(tmp_path, monkeypatch)++ assert studio_db.delete_chat_threads_with_active_research_runs(["src"]) == []+++def test_deleting_a_thread_signals_a_leased_research_run(tmp_path, monkeypatch):+ # The same run once a worker owns it: that worker is still running and has to be told.+ _research_thread(tmp_path, monkeypatch)+ conn = studio_db.get_connection()+ try:+ conn.execute(+ "UPDATE research_runs SET lease_owner = 'worker-1', status = 'running' WHERE id = ?",+ ("run-1",),+ )+ conn.commit()+ finally:+ conn.close()++ assert studio_db.delete_chat_threads_with_active_research_runs(["src"]) == ["run-1"]+++def test_replaying_a_clear_does_not_signal_its_research_runs_again(tmp_path, monkeypatch):+ # The request that recorded the operation already signalled these runs on its way out. Its+ # worker may have exited since, so a second signal would leave a cancellation event in the+ # supervisor that nothing is left to consume.+ _research_thread(tmp_path, monkeypatch)+ conn = studio_db.get_connection()+ try:+ conn.execute(+ "UPDATE research_runs SET lease_owner = 'worker-1', status = 'running' WHERE id = ?",+ ("run-1",),+ )+ conn.commit()+ finally:+ conn.close()++ first = studio_db.clear_chat_history_with_active_research_runs(operation_id = "op-1")+ assert first == (["run-1"], ["src"])++ replay = studio_db.clear_chat_history_with_active_research_runs(operation_id = "op-1")+ assert replay == ([], ["src"])diff --git a/studio/backend/tests/test_rag_ingestion.py b/studio/backend/tests/test_rag_ingestion.pyindex 7e9e8036878..15b835ce824 100644--- a/studio/backend/tests/test_rag_ingestion.py+++ b/studio/backend/tests/test_rag_ingestion.py@@ -4,6 +4,7 @@"""Ingestion lifecycle tests: pending -> completed, SSE events, dedupe, delete."""import os+import threadingimport timeimport pytest@@ -22,16 +23,24 @@ def _drain(job_id):return list(ingestion.job_events(job_id))-def _wait_completed(job_id, timeout = 30.0):+def _wait_finished(+ job_id,+ timeout = 30.0,+ terminal = ("completed", "failed", "cancelled"),+):deadline = time.time() + timeoutwhile time.time() < deadline:status = ingestion.get_job_status(job_id)- if status and status["status"] in ("completed", "failed"):+ if status and status["status"] in terminal:return statustime.sleep(0.05)raise AssertionError("ingestion did not finish in time")+def _wait_completed(job_id, timeout = 30.0):+ return _wait_finished(job_id, timeout, ("completed", "failed"))++def test_ingestion_lifecycle_pending_to_completed(rag_home, stub_embeddings, tmp_path):path = _write(tmp_path, "doc.txt", "alpha bravo charlie " * 50)scope = store.kb_scope("K1")@@ -62,6 +71,76 @@ def test_ingestion_lifecycle_pending_to_completed(rag_home, stub_embeddings, tmpconn.close()+def test_ingestion_skips_chunk_write_when_the_document_was_deleted(+ rag_home, stub_embeddings, tmp_path, monkeypatch+):+ """A project delete mid-job must not leave chunks under a scope nothing can reach."""+ path = _write(tmp_path, "doc.txt", "alpha bravo charlie " * 50)+ scope = store.project_scope("P1")+ real_embed_all = ingestion._embed_all+ deleted = {}+ doc_id_known = threading.Event()++ def delete_document_then_embed(texts, model_name):+ vectors = real_embed_all(texts, model_name)+ doc_id_known.wait(30)+ conn = rag_db.get_connection()+ try:+ store.delete_document(conn, deleted["id"])+ finally:+ conn.close()+ return vectors++ monkeypatch.setattr(ingestion, "_embed_all", delete_document_then_embed)+ doc_id, job_id = ingestion.start_ingestion(scope, None, None, "doc.txt", path, project_id = "P1")+ deleted["id"] = doc_id+ doc_id_known.set()++ assert _wait_finished(job_id)["status"] == "cancelled"+ conn = rag_db.get_connection()+ try:+ assert store.get_document(conn, doc_id) is None+ assert store.search_lexical(conn, scope, "alpha", 10) == []+ finally:+ conn.close()+++def test_ingestion_skips_an_empty_completion_when_the_document_was_deleted(+ rag_home, stub_embeddings, tmp_path, monkeypatch+):+ """An empty parse takes the other completion path, and must not report a deleted document+ as indexed or retire the document it was replacing."""+ path = _write(tmp_path, "empty.txt", "alpha bravo charlie " * 50)+ scope = store.project_scope("P1")+ deleted = {}+ doc_id_known = threading.Event()+ real_chunk_pages = ingestion.chunking.chunk_pages++ def delete_document_then_return_nothing(*args, **kwargs):+ real_chunk_pages(*args, **kwargs)+ doc_id_known.wait(30)+ conn = rag_db.get_connection()+ try:+ store.delete_document(conn, deleted["id"])+ finally:+ conn.close()+ return []++ monkeypatch.setattr(ingestion.chunking, "chunk_pages", delete_document_then_return_nothing)+ doc_id, job_id = ingestion.start_ingestion(+ scope, None, None, "empty.txt", path, project_id = "P1"+ )+ deleted["id"] = doc_id+ doc_id_known.set()++ assert _wait_finished(job_id)["status"] == "cancelled"+ conn = rag_db.get_connection()+ try:+ assert store.get_document(conn, doc_id) is None+ finally:+ conn.close()++def test_ingestion_dedupe_by_hash(rag_home, stub_embeddings, tmp_path):path = _write(tmp_path, "doc.txt", "alpha bravo charlie")scope = store.kb_scope("K1")diff --git a/studio/backend/tests/test_rag_job_events_queue_lifecycle.py b/studio/backend/tests/test_rag_job_events_queue_lifecycle.pyindex 0eb115c562a..27cabd5de41 100644--- a/studio/backend/tests/test_rag_job_events_queue_lifecycle.py+++ b/studio/backend/tests/test_rag_job_events_queue_lifecycle.py@@ -74,6 +74,36 @@ def test_disconnect_after_terminal_event_removes_queue(monkeypatch):ing._jobs.pop(jid, None)+def test_disconnect_after_cancelled_event_removes_queue(monkeypatch):+ monkeypatch.setattr(ing, "_SSE_POLL_SECONDS", 0.01)+ # Deleting a document while its worker is storing marks the job cancelled.+ # The UI consumes the error event and closes the stream before the sentinel.+ monkeypatch.setattr(ing, "get_job_status", lambda _jid: {"status": "cancelled"})+ jid = "job-disconnect-after-cancelled"+ q = queue.Queue()+ q.put({"type": "error", "stage": "cancelled", "error": "Document was deleted"})+ q.put(None)+ ing._jobs[jid] = q+ try:+ gen = ing.job_events(jid)+ assert next(gen)["stage"] == "cancelled"+ gen.close()+ assert jid not in ing._jobs, "a cancelled job's queue must drop on disconnect"+ finally:+ ing._jobs.pop(jid, None)+++def test_reaper_removes_cancelled_queue(monkeypatch):+ monkeypatch.setattr(ing, "get_job_status", lambda _jid: {"status": "cancelled"})+ jid = "job-reap-cancelled"+ ing._jobs[jid] = queue.Queue()+ try:+ ing._reap_finished_jobs()+ assert jid not in ing._jobs, "a cancelled job must not remain in the queue registry"+ finally:+ ing._jobs.pop(jid, None)++def test_transient_status_read_failure_does_not_end_stream(monkeypatch):monkeypatch.setattr(ing, "_SSE_POLL_SECONDS", 0.01)# The heartbeat poll hits a momentarily-locked DB. That must not propagate: thediff --git a/studio/backend/tests/test_rag_reconcile_orphaned.py b/studio/backend/tests/test_rag_reconcile_orphaned.pyindex c6932e4588c..13787ba1aea 100644--- a/studio/backend/tests/test_rag_reconcile_orphaned.py+++ b/studio/backend/tests/test_rag_reconcile_orphaned.py@@ -112,3 +112,15 @@ def test_already_failed_doc_has_its_chunks_dropped(rag_conn):assert store.get_document(rag_conn, "failed_doc")["status"] == "failed"assert _chunk_count(rag_conn, "failed_doc") == 0+++def test_cancelled_job_is_terminal_and_survives_a_restart(rag_conn):+ # The worker cancelled itself because the document was deleted mid-ingestion.+ # A restart must leave that verdict alone: rewriting it to 'failed' reports a+ # deliberate cancellation to the UI's getJob fallback as an indexing failure.+ _add_doc(rag_conn, "kb_a", "cancelled_doc", "processing", ["alpha bravo"])+ _orphan_job(rag_conn, "cancelled_doc", "kb_a", status = "cancelled")++ assert rag_db.reconcile_orphaned_ingestion_jobs() == 0++ assert _job_status(rag_conn, "cancelled_doc") == "cancelled"diff --git a/studio/backend/tests/test_research_runs_storage.py b/studio/backend/tests/test_research_runs_storage.pyindex afe87d180a4..c71a0c9aa60 100644--- a/studio/backend/tests/test_research_runs_storage.py+++ b/studio/backend/tests/test_research_runs_storage.py@@ -815,9 +815,69 @@ def test_delete_thread_cancels_active_research_run(research_home):state = SimpleNamespace(research_supervisor = SimpleNamespace(cancel = cancelled.append))))- chat_history._cancel_active_research(request, ["thread-1"])+ chat_history.delete_threads(+ chat_history.ChatDeleteRequest(ids = ["thread-1"]),+ request,+ current_subject = "alice",+ )- assert research_db.get_run("run-1")["status"] == "cancelling"+ assert research_db.get_run("run-1") is None+ assert cancelled == ["run-1"]+++def test_project_delete_cancels_runs_captured_by_delete_transaction(research_home):+ from routes import chat_history++ studio_db.upsert_chat_project(+ {+ "id": "project-1",+ "name": "Research project",+ "createdAt": 1,+ "updatedAt": 1,+ }+ )+ studio_db.update_chat_thread("thread-1", {"projectId": "project-1"})+ _create()+ plan = research_db.set_plan("run-1", _plan(), expected_revision = 0)+ research_db.approve("run-1", 1, plan["planHash"])+ research_db.claim_next("worker-1")++ cancelled: list[str] = []+ request = SimpleNamespace(+ app = SimpleNamespace(+ state = SimpleNamespace(research_supervisor = SimpleNamespace(cancel = cancelled.append))+ )+ )++ deleted = chat_history.delete_project(+ "project-1", request, delete_files = False, current_subject = "alice"+ )++ assert deleted.id == "project-1"+ assert studio_db.get_chat_thread("thread-1") is None+ assert research_db.get_run("run-1") is None+ assert cancelled == ["run-1"]+++def test_clear_history_cancels_runs_captured_by_delete_transaction(research_home):+ from routes import chat_history++ _create()+ plan = research_db.set_plan("run-1", _plan(), expected_revision = 0)+ research_db.approve("run-1", 1, plan["planHash"])+ research_db.claim_next("worker-1")++ cancelled: list[str] = []+ request = SimpleNamespace(+ app = SimpleNamespace(+ state = SimpleNamespace(research_supervisor = SimpleNamespace(cancel = cancelled.append))+ )+ )++ chat_history.clear_history(request, current_subject = "alice")++ assert studio_db.get_chat_thread("thread-1") is None+ assert research_db.get_run("run-1") is Noneassert cancelled == ["run-1"]@@ -2440,16 +2500,14 @@ def test_create_without_assistant_id_does_not_eagerly_create_message(research_hobefore = studio_db.list_chat_messages("thread-1")request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))- run = asyncio.run(- create_research_run(- CreateResearchRun(- threadId = "thread-1",- userMessageId = "user-1",- inferenceRequest = {"model": "local-model"},- ),- request,- current_subject = "alice",- )+ run = create_research_run(+ CreateResearchRun(+ threadId = "thread-1",+ userMessageId = "user-1",+ inferenceRequest = {"model": "local-model"},+ ),+ request,+ current_subject = "alice",)assert run["assistantMessageId"] is None@@ -2483,16 +2541,14 @@ def test_route_rejects_textless_research_before_claim(research_home, content, atrequest = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))with pytest.raises(HTTPException, match = "non-empty text") as caught:- asyncio.run(- create_research_run(- CreateResearchRun(- threadId = "thread-1",- userMessageId = "user-1",- inferenceRequest = {"model": "local-model"},- ),- request,- current_subject = "alice",- )+ create_research_run(+ CreateResearchRun(+ threadId = "thread-1",+ userMessageId = "user-1",+ inferenceRequest = {"model": "local-model"},+ ),+ request,+ current_subject = "alice",)assert caught.value.status_code == 400@@ -2520,16 +2576,14 @@ def test_route_accepts_canonical_text_content_shapes(research_home, content):"createdAt": 2,})- run = asyncio.run(- create_research_run(- CreateResearchRun(- threadId = "thread-1",- userMessageId = "user-1",- inferenceRequest = {"model": "local-model"},- ),- SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace())),- current_subject = "alice",- )+ run = create_research_run(+ CreateResearchRun(+ threadId = "thread-1",+ userMessageId = "user-1",+ inferenceRequest = {"model": "local-model"},+ ),+ SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace())),+ current_subject = "alice",)assert run["status"] == "planning"@@ -2544,16 +2598,14 @@ def test_route_rejects_overlapping_active_run_for_thread(research_home):_create()request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))with pytest.raises(HTTPException) as caught:- asyncio.run(- create_research_run(- CreateResearchRun(- threadId = "thread-1",- userMessageId = "user-1",- inferenceRequest = {"model": "local-model"},- ),- request,- current_subject = "alice",- )+ create_research_run(+ CreateResearchRun(+ threadId = "thread-1",+ userMessageId = "user-1",+ inferenceRequest = {"model": "local-model"},+ ),+ request,+ current_subject = "alice",)assert caught.value.status_code == 409@@ -2673,14 +2725,12 @@ def test_shared_chat_subject_can_follow_and_cancel_research(research_home):)_create()- visible = asyncio.run(get_research_run("run-1", current_subject = "bob"))- active = asyncio.run(active_research_runs("thread-1", current_subject = "bob"))- cancelled = asyncio.run(- cancel_research_run(- "run-1",- SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace())),- current_subject = "bob",- )+ visible = get_research_run("run-1", current_subject = "bob")+ active = active_research_runs("thread-1", current_subject = "bob")+ cancelled = cancel_research_run(+ "run-1",+ SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace())),+ current_subject = "bob",)assert visible["ownerSubject"] == "alice"@@ -3285,7 +3335,7 @@ def test_route_maps_unstable_assistant_conflict_to_409(research_home):request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))with pytest.raises(HTTPException) as caught:- asyncio.run(create_research_run(payload, request, current_subject = "alice"))+ create_research_run(payload, request, current_subject = "alice")assert caught.value.status_code == 409@@ -3302,7 +3352,7 @@ def test_route_accepts_max_tokens_without_treating_it_as_a_credential(research_h)request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))- run = asyncio.run(create_research_run(payload, request, current_subject = "alice"))+ run = create_research_run(payload, request, current_subject = "alice")assert run["config"]["inferenceRequest"]["maxTokens"] == 1024diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.pyindex 94579e5a81b..e6e73ddb315 100644--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py@@ -3007,14 +3007,15 @@ def test_clearing_every_chat_reports_the_files_it_kept():api = (src / "features/chat/api/chat-api.ts").read_text(encoding = "utf-8")clear = api[api.index("export async function clearBackendChats") :]clear = clear[: clear.index("\nexport ")]- assert "Promise<string[]>" in clear+ assert "deletedThreadIds: string[]" in clear+ assert "sandboxesKept: string[]" in clearassert "sandboxes_kept" in clearstorage = (src / "features/chat/utils/chat-history-storage.ts").read_text(encoding = "utf-8",)assert "sandboxesKept" in storage- assert "result.sandboxesKept = await clearBackendChats" in storage+ assert "result.sandboxesKept = backendResult.sandboxesKept" in storagetab = (src / "features/settings/tabs/data-tab.tsx").read_text(encoding = "utf-8")assert "offerToDeleteKeptSandboxes(result.sandboxesKept)" in tabdiff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex fe00b2db31d..7aafc27a4c0 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -1341,6 +1341,9 @@ export const Thread: FC<{const isComposerAttachPending = useAuiState(({ threads }) =>targetThreadId ? threads.mainThreadId !== targetThreadId : false,);+ const runtimeThreadId = useAuiState(+ ({ threadListItem }) => threadListItem.id,+ );const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);const threadId = targetThreadId ?? activeThreadId ?? null;const aui = useAui();@@ -1534,7 +1537,7 @@ export const Thread: FC<{};return (- <GeneratedImageOverlayProvider key={threadId ?? "default"} threadId={threadId}>+ <GeneratedImageOverlayProvider key={runtimeThreadId} threadId={threadId}><PageDragContext.Provider value={pageDragging}><ThreadPrimitive.RootclassName="aui-root aui-thread-root @container relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden"@@ -2745,6 +2748,8 @@ const Composer: FC<{// Tombstone synchronously so a late initializer cannot leave an empty// record visible while backend cleanup completes.markChatThreadDeleted(initializedFreshThreadId);+ // the tombstone is never rolled back: a failed DELETE may still have committed, and the+ // backend tombstones on commit, so resurrecting the id would leave it 410 on every writevoid deleteStoredChatThreads([initializedFreshThreadId]).catch(() => undefined,);diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 07c29f297a8..3348e667f6a 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -1,17 +1,19 @@// 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 { withModelLoadNotice } from "@/lib/model-lifecycle-events";import { authFetch } from "@/features/auth";import { prepareHfTokenForUse } from "@/features/hf-auth";// These helpers are deliberately API-layer-only, not part of their features' public barrels.// eslint-disable-next-line no-restricted-imports+import { disposableTimeoutSignal } from "@/features/hub/lib/abort-signals";+// eslint-disable-next-line no-restricted-importsimport { hubTokenHeader } from "@/features/hub/lib/hub-token-header";// eslint-disable-next-line no-restricted-importsimport { isHuggingFaceOffline } from "@/features/hub/lib/network";// eslint-disable-next-line no-restricted-importsimport { consumeNativePathToken } from "@/features/native-intents/api";import { formatApiErrorBody } from "@/lib/format-fastapi-error";+import { withModelLoadNotice } from "@/lib/model-lifecycle-events";import type {MessageRecord,ModelType,@@ -43,10 +45,26 @@ import { assertCompletedPaddedBody } from "./padded-response";export const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";export const CHAT_PROJECTS_UPDATED_EVENT = "unsloth-chat-projects-updated";+// bounds the request itself so a wedged socket cannot stall every reader waiting on the write+const THREAD_WRITE_TIMEOUT_MS = 30_000;++/** authFetch under a disposed timeout, so the ponyfill path leaves no timer behind. */+async function threadWriteFetch(+ input: string,+ init: RequestInit,+): Promise<Response> {+ const timeout = disposableTimeoutSignal(THREAD_WRITE_TIMEOUT_MS);+ try {+ return await authFetch(input, { ...init, signal: timeout.signal });+ } finally {+ timeout.dispose();+ }+}+/**-* Thrown when the chat SSE stream ends without a terminal signal (`[DONE]` or a finish_reason-* chunk): the connection dropped mid-generation, surfaced as an explicit interrupted state.-*/+ * Thrown when the chat SSE stream ends without a terminal signal (`[DONE]` or a finish_reason+ * chunk): the connection dropped mid-generation, surfaced as an explicit interrupted state.+ */export class StreamInterruptedError extends Error {constructor() {super(@@ -58,9 +76,9 @@ export class StreamInterruptedError extends Error {}/**-* Thrown when a reasoning model consumes its output budget before emitting any standard-* content, so the chat UI can explain a completed stream holding only a thinking panel.-*/+ * Thrown when a reasoning model consumes its output budget before emitting any standard+ * content, so the chat UI can explain a completed stream holding only a thinking panel.+ */export class GenerationLengthError extends Error {constructor() {super(@@ -89,24 +107,32 @@ function parseErrorText(status: number, body: unknown): string {}/**-* `/api/inference/load` and `/unload` pad their body so a proxy cannot time the request out,-* which commits the status early: a later failure can only arrive in-band as `_deferred_error`.-*/-function deferredError(body: unknown): { status: number; message: string } | null {+ * `/api/inference/load` and `/unload` pad their body so a proxy cannot time the request out,+ * which commits the status early: a later failure can only arrive in-band as `_deferred_error`.+ */+function deferredError(+ body: unknown,+): { status: number; message: string } | null {const deferred =body && typeof body === "object"- ? (body as { _deferred_error?: { status_code?: unknown; detail?: unknown } })- ._deferred_error+ ? (+ body as {+ _deferred_error?: { status_code?: unknown; detail?: unknown };+ }+ )._deferred_error: undefined;if (!deferred || typeof deferred !== "object") return null;const status =typeof deferred.status_code === "number" ? deferred.status_code : 500;- return { status, message: parseErrorText(status, { detail: deferred.detail }) };+ return {+ status,+ message: parseErrorText(status, { detail: deferred.detail }),+ };}/**-* `paddedLabel` opts a caller into `assertCompletedPaddedBody`; only the two padded routes may,-* since a truncated body means unfinished there but is legitimate elsewhere. */+ * `paddedLabel` opts a caller into `assertCompletedPaddedBody`; only the two padded routes may,+ * since a truncated body means unfinished there but is legitimate elsewhere. */async function parseJsonOrThrow<T>(response: Response,paddedLabel?: string,@@ -178,9 +204,9 @@ export interface ActiveGenerationsResponse {}/**-* Chats generating on the backend right now. Authoritative where `runningByThreadId` is not:-* that map is per-tab, empty after a reload and blind to a second tab, and /load 409s on these.-*/+ * Chats generating on the backend right now. Authoritative where `runningByThreadId` is not:+ * that map is per-tab, empty after a reload and blind to a second tab, and /load 409s on these.+ */export async function getActiveGenerations(): Promise<ActiveGenerationsResponse> {const response = await authFetch("/api/inference/active-generations");return parseJsonOrThrow<ActiveGenerationsResponse>(response);@@ -277,11 +303,11 @@ export async function validateModel(}/**-* Read a GGUF's header dims (native context length, layer count, MoE expert-layer count) from-* its local file (no GPU load, no download). All null when the file isn't downloaded, isn't a-* GGUF, or is gated. For a native (drag-drop) file, pass `nativePathToken`. Used by the-* deferred-load staging flow to size the context, GPU-layers and MoE sliders before the load.-*/+ * Read a GGUF's header dims (native context length, layer count, MoE expert-layer count) from+ * its local file (no GPU load, no download). All null when the file isn't downloaded, isn't a+ * GGUF, or is gated. For a native (drag-drop) file, pass `nativePathToken`. Used by the+ * deferred-load staging flow to size the context, GPU-layers and MoE sliders before the load.+ */export async function fetchGgufStagedMetadata(payload: {model_path: string;gguf_variant?: string | null;@@ -345,10 +371,10 @@ export async function unloadModel(payload: UnloadModelRequest): Promise<void> {}/**-* Allow or deny a tool call paused awaiting user confirmation. Identified by the backend-* ``approvalId`` echoed in the tool_start event; ``sessionId`` is a scope check. Resolves to-* ``true`` only when the backend matched a pending call, so a stale post can offer a retry.-*/+ * Allow or deny a tool call paused awaiting user confirmation. Identified by the backend+ * ``approvalId`` echoed in the tool_start event; ``sessionId`` is a scope check. Resolves to+ * ``true`` only when the backend matched a pending call, so a stale post can offer a retry.+ */export async function resolveToolConfirmation(sessionId: string,approvalId: string,@@ -423,8 +449,8 @@ export interface DownloadProgressResponse {expected_bytes: number;progress: number;/**- * On-disk path of the snapshot dir (or cache repo root if no snapshot yet); null when- * nothing has been written to the cache for this repo. */+ * On-disk path of the snapshot dir (or cache repo root if no snapshot yet); null when+ * nothing has been written to the cache for this repo. */cache_path: string | null;}@@ -450,8 +476,8 @@ export type ModelLoadPhase = "mmap" | "ready" | null;export interface LoadProgressResponse {/**- * Load phase: "mmap" while llama-server pages weight shards into RAM, "ready" once- * healthy, or null when no load is in flight. */+ * Load phase: "mmap" while llama-server pages weight shards into RAM, "ready" once+ * healthy, or null when no load is in flight. */phase: ModelLoadPhase;bytes_loaded: number;bytes_total: number;@@ -459,11 +485,11 @@ export interface LoadProgressResponse {}/**-* Fetch the active GGUF load's mmap/upload progress. Complements the download progress-* endpoints for the "download complete" -> "chat ready" window, minutes for large MoE models.-*/+ * Fetch the active GGUF load's mmap/upload progress. Complements the download progress+ * endpoints for the "download complete" -> "chat ready" window, minutes for large MoE models.+ */export async function getLoadProgress(): Promise<LoadProgressResponse> {- const response = await authFetch(`/api/inference/load-progress`);+ const response = await authFetch("/api/inference/load-progress");return parseJsonOrThrow(response);}@@ -711,22 +737,44 @@ export async function deleteChatAttachment(export async function getChatThread(threadId: string,+ options: { bounded?: boolean } = {},): Promise<ThreadRecord | null> {- const response = await authFetch(- `/api/chat/threads/${encodeURIComponent(threadId)}`,- );- if (response.status === 404) return null;- return parseJsonOrThrow<ThreadRecord>(response);+ // Bounded for the delete reconciliation: an unbounded read there would hang the delete that+ // the write timeout exists to keep moving. Callers on a render path stay unbounded.+ const timeout = options.bounded+ ? disposableTimeoutSignal(THREAD_WRITE_TIMEOUT_MS)+ : null;+ try {+ const response = await authFetch(+ `/api/chat/threads/${encodeURIComponent(threadId)}`,+ timeout ? { signal: timeout.signal } : undefined,+ );+ if (response.status === 404) return null;+ return parseJsonOrThrow<ThreadRecord>(response);+ } finally {+ timeout?.dispose();+ }+}++export class ChatThreadDeletedError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "ChatThreadDeletedError";+ }}export async function saveChatThread(thread: ThreadRecord,): Promise<ThreadRecord> {- const response = await authFetch("/api/chat/threads", {+ const response = await threadWriteFetch("/api/chat/threads", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(thread),});+ if (response.status === 410) {+ const body = await response.json().catch(() => null);+ throw new ChatThreadDeletedError(parseErrorText(response.status, body));+ }const savedThread = await parseJsonOrThrow<ThreadRecord>(response);notifyChatHistoryUpdated();return savedThread;@@ -751,7 +799,7 @@ export async function updateChatThread(if (options.expectedOpeningMessageId !== undefined) {body.expectedOpeningMessageId = options.expectedOpeningMessageId;}- const response = await authFetch(+ const response = await threadWriteFetch(`/api/chat/threads/${encodeURIComponent(threadId)}`,{method: "PATCH",@@ -809,7 +857,7 @@ export async function deleteChatThreads(args: { deleteFiles?: boolean } = {},): Promise<string[]> {if (threadIds.length === 0) return [];- const response = await authFetch("/api/chat/threads", {+ const response = await threadWriteFetch("/api/chat/threads", {method: "DELETE",headers: { "Content-Type": "application/json" },body: JSON.stringify({ ids: threadIds, delete_files: !!args.deleteFiles }),@@ -904,8 +952,8 @@ export async function listChatMessages(}/**-* Fetch messages for many threads in one HTTP call. Falls back to per-thread-* listChatMessages on 404/405 (older servers without the batch route). */+ * Fetch messages for many threads in one HTTP call. Falls back to per-thread+ * listChatMessages on 404/405 (older servers without the batch route). */export async function batchListChatMessages(threadIds: string[],): Promise<Map<string, MessageRecord[]>> {@@ -965,7 +1013,7 @@ export async function syncChatMessages(messages: MessageRecord[],options: { pruneMissing?: boolean } = {},): Promise<MessageRecord[]> {- const response = await authFetch(+ const response = await threadWriteFetch(`/api/chat/threads/${encodeURIComponent(threadId)}/messages`,{method: "PUT",@@ -989,17 +1037,39 @@ export async function countBackendChats(): Promise<number> {/** Thread ids whose sandbox still holds files, passed through from the route. */export async function clearBackendChats(- options: { notify?: boolean; deleteFiles?: boolean } = {},-): Promise<string[]> {- const response = await authFetch(+ options: {+ notify?: boolean;+ operationId?: string;+ tombstoneThreadIds?: string[];+ deleteFiles?: boolean;+ } = {},+): Promise<{ deletedThreadIds: string[]; sandboxesKept: string[] }> {+ const response = await threadWriteFetch(`/api/chat${options.deleteFiles ? "?delete_files=true" : ""}`,- { method: "DELETE" },+ {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ ids: options.tombstoneThreadIds ?? [],+ operationId: options.operationId,+ }),+ },);- const data = await parseJsonOrThrow<{ sandboxes_kept?: string[] }>(response);+ const data = await parseJsonOrThrow<{+ deletedThreadIds?: string[];+ sandboxes_kept?: string[];+ }>(response);if (options.notify !== false) {notifyChatHistoryUpdated();}- return Array.isArray(data?.sandboxes_kept) ? data.sandboxes_kept : [];+ return {+ deletedThreadIds: Array.isArray(data?.deletedThreadIds)+ ? data.deletedThreadIds+ : [],+ sandboxesKept: Array.isArray(data?.sandboxes_kept)+ ? data.sandboxes_kept+ : [],+ };}export async function buildBackendChatExport(): Promise<{diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 113756c953f..a46860c1c7e 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -5,6 +5,7 @@ export { ChatPage, validateChatSearch, type ChatSearch } from "./chat-page";export {addScanFolder,browseFolders,+ ChatThreadDeletedError,deleteChatAttachment,deleteFineTunedModel,fetchChatAttachmentBlob,@@ -144,10 +145,15 @@ export { offerToDeleteKeptSandboxes } from "./utils/offer-kept-sandbox-files";export { pasteClipboardFiles } from "./utils/clipboard-files";export {deleteStoredChatThreads,+ ensureStoredChatThread,+ isThreadIncognito,listStoredChatThreads,markThreadIncognito,} from "./utils/chat-history-storage";-export { markChatThreadDeleted } from "./utils/chat-thread-tombstones";+export {+ markChatThreadDeleted,+ removeChatThreadTombstones,+} from "./utils/chat-thread-tombstones";export { emitChatAttachmentDeleted } from "./utils/chat-attachment-events";export { resolveReasoningGroupDuration } from "./utils/reasoning-duration";export { ArtifactCard } from "./artifacts/artifact-card";diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 9be1a4d4fed..7ab9bd5c9b7 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -86,8 +86,10 @@ import {setActiveBranchReader,} from "./utils/refresh-context-usage";import {+ awaitStoredChatThreadWrites,deleteStoredChatThreads,ensureStoredChatThread,+ getStoredChatMessage,getStoredChatThread,isExpectedBackgroundChatStorageError,listStoredChatMessages,@@ -95,6 +97,7 @@ import {markThreadIncognito,saveStoredChatMessage,saveStoredChatThread,+ trackStoredChatThreadRecord,updateStoredChatThread,} from "./utils/chat-history-storage";import {@@ -650,30 +653,39 @@ export async function ensureThreadRecord({modelType,pairId,projectId,+ incognito,+ modelId,+ createdAt,}: {threadId: string;modelType: ModelType;pairId?: string;projectId?: string | null;+ /** Snapshot from the send this row belongs to, so a retry cannot read a since-flipped toggle. */+ incognito?: boolean;+ /** Snapshot from the send this row belongs to, so retries cannot adopt a later checkpoint. */+ modelId?: string;+ /** Snapshot from the send this row belongs to, so retries retain its original creation time. */+ createdAt?: number;}): Promise<void> {if (isChatThreadDeleted(threadId)) {return;}- // Snapshot the toggle SYNCHRONOUSLY, before the await below. This runs in- // the same tick as the user's send, so it reliably captures the toggle's- // state at creation. Reading it after the await would let a toggle-off- // that lands mid-await (the list call is a real network round-trip) flip- // the decision and persist what should have been an incognito thread.- const incognitoAtInit = useChatRuntimeStore.getState().incognito;+ // Snapshot mutable creation inputs synchronously, before the await below. This runs in the same+ // tick as the user's send, so a toggle or checkpoint change during the point lookup cannot+ // change the identity of the thread a retry persists.+ const runtimeStateAtInit = useChatRuntimeStore.getState();+ const incognitoAtInit = incognito ?? runtimeStateAtInit.incognito;+ const modelIdAtInit = modelId ?? runtimeStateAtInit.params.checkpoint ?? "";+ const createdAtInit = createdAt ?? Date.now();// Fresh assistant-ui threads are local ids. Temporary chats can skip the// history list entirely so a storage outage cannot block the first send.if (incognitoAtInit && isAssistantLocalThreadId(threadId)) {markThreadIncognito(threadId);return;}- const existing = (await listStoredChatThreads({ includeArchived: true })).find(- (thread) => thread.id === threadId,- );+ // A point lookup, not a listing: this must not scale with how many chats exist.+ const existing = await getStoredChatThread(threadId);if (existing) {return;}@@ -685,16 +697,15 @@ export async function ensureThreadRecord({return;}- const currentModelId = useChatRuntimeStore.getState().params.checkpoint ?? "";const record: ThreadRecord = {id: threadId,title: "New Chat",modelType,- modelId: currentModelId,+ modelId: modelIdAtInit,pairId,projectId: projectId ?? null,archived: false,- createdAt: Date.now(),+ createdAt: createdAtInit,};try {@@ -703,10 +714,10 @@ export async function ensureThreadRecord({// assistant-ui can issue overlapping first-message persistence calls. If// another call created the same thread while this one waited, treat init as// successful and let the message write continue.- const existingAfterRace = await listStoredChatThreads({- includeArchived: true,- }).catch(() => []);- if (existingAfterRace.some((thread) => thread.id === threadId)) {+ const existingAfterRace = await getStoredChatThread(threadId).catch(+ () => undefined,+ );+ if (existingAfterRace) {return;}throw error;@@ -763,13 +774,30 @@ function createStudioDbAdapter(};},- async initialize(threadId: string) {- await ensureThreadRecord({ threadId, modelType, pairId, projectId });+ initialize(threadId: string) {+ // assistant-ui withholds the first message until this resolves, so the row write is tracked, not awaited.+ // Captured here, not inside the creator: a retry belongs to the send that initialized it,+ // not to a later incognito or checkpoint selection.+ const runtimeStateAtInit = useChatRuntimeStore.getState();+ const incognitoAtInit = runtimeStateAtInit.incognito;+ const modelIdAtInit = runtimeStateAtInit.params.checkpoint ?? "";+ const createdAtInit = Date.now();+ trackStoredChatThreadRecord(threadId, () =>+ ensureThreadRecord({+ threadId,+ modelType,+ pairId,+ projectId,+ incognito: incognitoAtInit,+ modelId: modelIdAtInit,+ createdAt: createdAtInit,+ }),+ );// A run already streaming on this thread filed its handles under "__default" because// the id did not exist yet. Re-key them now, or the sidebar row and Stop look up an// id nothing is registered against.useChatRuntimeStore.getState().adoptDefaultThreadRun(threadId);- return { remoteId: threadId, externalId: undefined };+ return Promise.resolve({ remoteId: threadId, externalId: undefined });},async rename(remoteId: string, newTitle: string) {@@ -795,7 +823,11 @@ function createStudioDbAdapter(async generateTitle(remoteId: string, messages: readonly ThreadMessage[]) {const autoTitle = useChatRuntimeStore.getState().autoTitle;- const thread = await getStoredChatThread(remoteId);+ // The run normally waits for its history append, but a bounded persistence wait can expire+ // while the creator is still queued. Use the same retry choke point as other mutations so a+ // temporarily missing row does not permanently skip first-turn title generation. A title is+ // cosmetic, so a row that never landed falls back to the default rather than rejecting here.+ const thread = await ensureStoredChatThread(remoteId).catch(() => undefined);const defaultTitle = "New Chat";function streamTitle(title: string) {@@ -1381,12 +1413,15 @@ function useStudioRuntimeAdapters();const write = (async () => {const { remoteId } = await initializeThread;+ // The model run waits for the authoritative row. Clear-all does not: it tombstones this+ // known id directly, so a stalled request cannot hold the clear hostage.+ await awaitStoredChatThreadWrites(remoteId);if (isChatThreadDeleted(remoteId)) {await deleteStoredChatThreads([remoteId]);return;}- // Keep single-chat runtime state in sync once a new chat is first- // persisted. Compare panes intentionally don't write global activeThreadId.+ // published before the reads below: a temporary chat has no row to confirm, and a read+ // that fails must not leave the runtime pointing at the previously open chatif (modelType === "base" && !pairId) {const store = useChatRuntimeStore.getState();const visibleThreadId = aui.threads().getState().mainThreadId;@@ -1398,32 +1433,16 @@ function useStudioRuntimeAdapters(store.setActiveThreadId(remoteId);}}- const thread = await getStoredChatThread(remoteId);+ // One point read: the model run waits on this write.+ const existingMessage = await getStoredChatMessage(+ remoteId,+ message.id,+ );await throwIfHistoryWasCleared(remoteId);- if (thread) {- await ensureStoredChatThread(remoteId, thread);- await throwIfHistoryWasCleared(remoteId);- }- if (thread?.modelType === "base" && !thread.pairId) {- const store = useChatRuntimeStore.getState();- const visibleThreadId = aui.threads().getState().mainThreadId;- if (- (visibleThreadId === localThreadId ||- visibleThreadId === remoteId) &&- store.activeThreadId !== remoteId- ) {- store.setActiveThreadId(remoteId);- }- }const content = cloneContent(message.content);const attachments =message.role === "user" ? cloneAttachments(message.attachments) : [];const custom = message.metadata?.custom;- const storedMessages = await listStoredChatMessages(remoteId);- await throwIfHistoryWasCleared(remoteId);- const existingMessage = storedMessages.find(- (storedMessage) => storedMessage.id === message.id,- );const createdAt =existingMessage?.createdAt ??message.createdAt?.getTime?.() ??@@ -1463,10 +1482,7 @@ function useStudioRuntimeAdapters(});await throwIfHistoryWasCleared(remoteId);})();- return trackHistoryAppend(- message.id,- chatHistoryClearBoundary.trackPending(write),- );+ return trackHistoryAppend(message.id, write);},}),[aui, modelType, pairId],diff --git a/studio/frontend/src/features/chat/utils/chat-history-clear-boundary.ts b/studio/frontend/src/features/chat/utils/chat-history-clear-boundary.tsindex 38ca695965a..9f93ac27ebd 100644--- a/studio/frontend/src/features/chat/utils/chat-history-clear-boundary.ts+++ b/studio/frontend/src/features/chat/utils/chat-history-clear-boundary.ts@@ -1,6 +1,5 @@export class ChatHistoryClearBoundary {private generation = 0;- private pendingPersistence = new Set<Promise<unknown>>();capture(): number {return this.generation;@@ -10,21 +9,6 @@ export class ChatHistoryClearBoundary {this.generation += 1;return this.generation;}-- trackPending<T>(work: Promise<T>): Promise<T> {- this.pendingPersistence.add(work);- work.then(- () => this.pendingPersistence.delete(work),- () => this.pendingPersistence.delete(work),- );- return work;- }-- async waitForPending(): Promise<void> {- while (this.pendingPersistence.size > 0) {- await Promise.allSettled([...this.pendingPersistence]);- }- }}export const chatHistoryClearBoundary = new ChatHistoryClearBoundary();diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.tsindex c3cf5a964b1..31e8c848f80 100644--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts@@ -2,28 +2,29 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import {+ ChatThreadDeletedError,+ batchListChatMessages,buildBackendChatExport,clearBackendChats,deleteChatProject,deleteChatThreads,- getChatProject,getChatMessage,+ getChatProject,getChatThread,- batchListChatMessages,- listChatProjects,listChatImportLedger,listChatMessages,+ listChatProjects,listChatThreads,notifyChatHistoryUpdated,recordChatImportLedger,- saveChatProject,saveChatMessage,+ saveChatProject,saveChatThread,syncChatMessages,updateChatProject,updateChatThread,} from "../api/chat-api";-import { db, DEXIE_DB_NAME } from "../db";+import { DEXIE_DB_NAME, db } from "../db";import type {MessageRecord,ModelType,@@ -32,8 +33,10 @@ import type {} from "../types";import {isChatThreadDeleted,+ markChatThreadDeleted,markChatThreadsDeleted,} from "./chat-thread-tombstones";+import { ThreadRecordWriteCoordinator } from "./thread-record-write-coordinator";// Thread ids that belong to a temporary/incognito session. A thread is// tagged once, at creation (ensureThreadRecord, when the toggle is on), and@@ -50,7 +53,8 @@ export function markThreadIncognito(threadId: string): void {incognitoThreadIds.add(threadId);}-function isThreadIncognito(threadId: string): boolean {+/** True for a temporary-session thread, which is deliberately never persisted. */+export function isThreadIncognito(threadId: string): boolean {return incognitoThreadIds.has(threadId);}@@ -70,6 +74,70 @@ const LEGACY_CHAT_IMPORT_KEY = "unsloth_chat_legacy_imported_to_studio_db";let legacyChatImportPromise: Promise<void> | null = null;+// Bumped whenever a backend thread row is created or backfilled, so a listing can tell whether its read raced one.+let legacyChatImportGeneration = 0;++// no browser-side ordering: the delete transaction tombstones before removing the row, so a+// confirmed delete always beats a save that reaches sqlite later+const threadRecordWrites = new ThreadRecordWriteCoordinator(+ (threadId) =>+ new Error(+ `Chat history was cleared before thread ${threadId} could be persisted`,+ ),+ (error) => error instanceof ChatThreadDeletedError,+);++const initializingThreadRecords = new Map<string, Promise<void>>();++// creators whose last write failed, since assistant-ui caches a resolved initialize() and never re-asks+const failedThreadRecordByThreadId = new Map<string, () => Promise<void>>();++// bumped by a history clear, so a retried creator cannot resurrect a thread the user removed+let threadRecordClearEpoch = 0;++/** Wait for the row work already registered for this thread, without adopting its failure. */+export function awaitStoredChatThreadWrites(threadId: string): Promise<void> {+ return threadRecordWrites.settleCurrent(threadId);+}++/** Start one background initializer for an id so the first message can render at once.+ * Returns the tracked write so a retry can adopt its outcome; callers that only start one+ * ignore it, and the rejection is always handled below. */+export function trackStoredChatThreadRecord(+ threadId: string,+ createRecord: () => Promise<void>,+): Promise<void> {+ const inFlight = initializingThreadRecords.get(threadId);+ if (inFlight) {+ return inFlight;+ }+ const epoch = threadRecordClearEpoch;+ const work = threadRecordWrites.observe(+ threadId,+ Promise.resolve().then(createRecord),+ );+ initializingThreadRecords.set(threadId, work);+ work.then(+ () => {+ if (initializingThreadRecords.get(threadId) === work) {+ initializingThreadRecords.delete(threadId);+ }+ failedThreadRecordByThreadId.delete(threadId);+ },+ () => {+ if (initializingThreadRecords.get(threadId) === work) {+ initializingThreadRecords.delete(threadId);+ }+ // a clear bumps the epoch before closing admission, so it retires this creator without+ // tombstoning a thread the clear may yet fail to remove+ if (epoch === threadRecordClearEpoch && !isChatThreadDeleted(threadId)) {+ failedThreadRecordByThreadId.set(threadId, createRecord);+ }+ },+ );+ return work;+}+interface ExportedChat {exportedAt: string;version: 1;@@ -235,10 +303,29 @@ function mergeMessages(return { messages: Array.from(byId.values()), shouldSync };}-async function importLegacyThread(+// point imports commit their row before the bump lands, so a listing waits for the ones already+// in flight instead of trusting the generation alone+const pendingLegacyThreadImports = new Set<Promise<unknown>>();++function importLegacyThread(+ thread: ThreadRecord,+): Promise<ThreadRecord | undefined> {+ const work = importLegacyThreadRow(thread);+ pendingLegacyThreadImports.add(work);+ const forget = () => pendingLegacyThreadImports.delete(work);+ work.then(forget, forget);+ return work;+}++async function importLegacyThreadRow(thread: ThreadRecord,): Promise<ThreadRecord | undefined> {- const saved = await saveChatThread(thread);+ const saved = await saveLegacyChatThread(thread);+ if (!saved) {+ return undefined;+ }+ // A point lookup can import a row too, and a listing mid-flight has to re-read to see it.+ legacyChatImportGeneration += 1;const legacyMessages = await db.messages.where("threadId").equals(thread.id)@@ -251,6 +338,25 @@ async function importLegacyThread(return saved;}+/** A backend tombstone is authoritative: retire the stale browser row instead of retrying it. */+async function saveLegacyChatThread(+ thread: ThreadRecord,+): Promise<ThreadRecord | undefined> {+ try {+ return await writeChatThreadRecord(thread);+ } catch (error) {+ if (!(error instanceof ChatThreadDeletedError)) {+ throw error;+ }+ markChatThreadDeleted(thread.id);+ return undefined;+ }+}++function writeChatThreadRecord(thread: ThreadRecord): Promise<ThreadRecord> {+ return threadRecordWrites.write(thread.id, () => saveChatThread(thread));+}+async function backfillLegacyThreadFields(backendThread: ThreadRecord,legacyThread: ThreadRecord | undefined,@@ -271,13 +377,26 @@ async function backfillLegacyThreadFields(legacyThread.anthropicCodeExecContainerId;}if (Object.keys(patch).length === 0) return backendThread;+ const work = applyLegacyThreadBackfill(backendThread, patch);+ pendingLegacyThreadImports.add(work);+ const forget = () => pendingLegacyThreadImports.delete(work);+ work.then(forget, forget);+ return work;+}++async function applyLegacyThreadBackfill(+ backendThread: ThreadRecord,+ patch: Partial<ThreadRecord>,+): Promise<ThreadRecord> {try {- return (- (await updateChatThread(backendThread.id, patch)) ?? {- ...backendThread,- ...patch,- }- );+ const updated = (await updateChatThread(backendThread.id, patch)) ?? {+ ...backendThread,+ ...patch,+ };+ // Bump only once the patch has committed: a listing that read the row mid-flight still needs+ // to see the generation move so it re-reads.+ legacyChatImportGeneration += 1;+ return updated;} catch {return backendThread;}@@ -340,11 +459,12 @@ async function importLegacyChatsIfNeeded(): Promise<void> {// Slow path: diff Dexie against the server-side ledger and import// any threads not already recorded.- const [legacyThreads, backendThreads, importedThreadIds] = await Promise.all([- db.threads.toArray(),- listChatThreads({ includeArchived: true }),- listChatImportLedger(),- ]);+ const [legacyThreads, backendThreads, importedThreadIds] =+ await Promise.all([+ db.threads.toArray(),+ listChatThreads({ includeArchived: true }),+ listChatImportLedger(),+ ]);const backendThreadsById = new Map(backendThreads.map((thread) => [thread.id, thread]),@@ -386,14 +506,21 @@ async function importLegacyChatsIfNeeded(): Promise<void> {const newlyImportedIds: string[] = [];for (const thread of unimportedThreads) {const backendThread = backendThreadsById.get(thread.id);- if (!backendThread) {- await saveChatThread(thread);- backendThreadsById.set(thread.id, thread);- } else {+ if (backendThread) {backendThreadsById.set(thread.id,await backfillLegacyThreadFields(backendThread, thread),);+ } else {+ const saved = await saveLegacyChatThread(thread);+ if (!saved) {+ // Record the authoritative deletion in the migration ledger too, so another browser's+ // stale Dexie copy does not keep attempting the same forbidden import.+ newlyImportedIds.push(thread.id);+ continue;+ }+ backendThreadsById.set(thread.id, thread);+ legacyChatImportGeneration += 1;}const legacyMessages = legacyByThread.get(thread.id) ?? [];@@ -473,6 +600,9 @@ export async function ensureStoredChatThread(// on every autosave (runStart/runEnd) and message append.if (isThreadIncognito(threadId)) return undefined;if (isChatThreadDeleted(threadId)) return undefined;+ // Outcome ignored on purpose: adopting the failure here would skip the retryFailedThreadRecord+ // branch below for exactly the callers already waiting when the write rejected.+ await awaitStoredChatThreadWrites(threadId);const legacyThread = fallback ?? (await db.threads.get(threadId));let backendThread: ThreadRecord | null;try {@@ -486,10 +616,32 @@ export async function ensureStoredChatThread(if (backendThread) {return backfillLegacyThreadFields(backendThread, legacyThread);}- if (!legacyThread || isChatThreadDeleted(legacyThread.id)) return undefined;+ if (!legacyThread || isChatThreadDeleted(legacyThread.id)) {+ return retryFailedThreadRecord(threadId);+ }return importLegacyThread(legacyThread).catch(() => legacyThread);}+/** Re-run a row write that failed, for a thread the reads above could not find. */+async function retryFailedThreadRecord(+ threadId: string,+): Promise<ThreadRecord | undefined> {+ const createRecord = failedThreadRecordByThreadId.get(threadId);+ if (!createRecord && !threadRecordWrites.hasPending(threadId)) {+ return undefined;+ }+ if (createRecord) {+ failedThreadRecordByThreadId.delete(threadId);+ // Through the same initializer path, so a retry that fails again stays retryable, and+ // rethrowing on purpose: a caller handed undefined reads it as "no row to update" and drops+ // its patch, which is how the prompt queue loses its model correction.+ await trackStoredChatThreadRecord(threadId, createRecord);+ } else {+ await awaitStoredChatThreadWrites(threadId);+ }+ return (await getChatThread(threadId)) ?? undefined;+}+export async function listStoredChatMessages(threadId: string,): Promise<MessageRecord[]> {@@ -566,6 +718,7 @@ export async function getStoredChatMessage(export async function listStoredChatThreads(args: ThreadListArgs = {},): Promise<ThreadRecord[]> {+ const importGenerationBeforeRead = legacyChatImportGeneration;const legacyThreads = await listLegacyThreads(args);let backendThreads = await listChatThreads(args).catch((error) => {if (legacyThreads.length > 0) {@@ -575,7 +728,12 @@ export async function listStoredChatThreads(});if (backendThreads) {await importLegacyChatsIfNeeded().catch(() => undefined);- backendThreads = await listChatThreads(args).catch(() => backendThreads);+ // a point import can commit its row before its generation bump lands, so wait on the ones+ // already in flight rather than trusting the generation alone+ await Promise.allSettled([...pendingLegacyThreadImports]);+ if (legacyChatImportGeneration !== importGenerationBeforeRead) {+ backendThreads = await listChatThreads(args).catch(() => backendThreads);+ }}const includeLegacyOnly =!backendThreads ||@@ -591,8 +749,7 @@ export async function listStoredChatThreads(return Array.from(byId.values()).filter((thread) => matchesThreadListArgs(thread, args)).sort(- (a, b) =>- (b.updatedAt ?? b.createdAt) - (a.updatedAt ?? a.createdAt),+ (a, b) => (b.updatedAt ?? b.createdAt) - (a.updatedAt ?? a.createdAt),);}@@ -677,10 +834,12 @@ export async function moveStoredChatItemToProject(const threadIds =item.type === "single"? [item.id]- : (await listStoredChatThreads({- pairId: item.id,- includeArchived: true,- })).map((thread) => thread.id);+ : (+ await listStoredChatThreads({+ pairId: item.id,+ includeArchived: true,+ })+ ).map((thread) => thread.id);await Promise.all(Array.from(new Set(threadIds)).map((threadId) =>@@ -718,7 +877,14 @@ export async function saveStoredChatThread(if (isChatThreadDeleted(thread.id)) {throw new Error(`Thread ${thread.id} was deleted`);}- return saveChatThread(thread);+ try {+ return await writeChatThreadRecord(thread);+ } catch (error) {+ if (error instanceof ChatThreadDeletedError) {+ markChatThreadDeleted(thread.id);+ }+ throw error;+ }}export async function updateStoredChatThread(@@ -736,12 +902,41 @@ export async function deleteStoredChatThreads(idsToDelete: string[],args: { deleteFiles?: boolean } = {},): Promise<string[]> {- // An incognito chat stores no history row, but a tool call it made sent this- // id as the sandbox session, so closing it is the last thing that can name- // that folder. Only the Dexie work below is skipped: it holds nothing.+ // Incognito chats have no history row, but their ids still name sandboxes. Send every id to+ // the backend for file cleanup while limiting Dexie and write-coordinator work to stored chats.+ idsToDelete = Array.from(new Set(idsToDelete));const ids = idsToDelete.filter((id) => !isThreadIncognito(id));if (idsToDelete.length === 0) return [];- const kept = await deleteChatThreads(idsToDelete, args);+ let kept: string[] = [];+ // the backend tombstones every requested id in the transaction that deletes its row, so a save+ // reaching sqlite later is rejected rather than resurrecting the thread+ try {+ kept = await deleteChatThreads(idsToDelete, args);+ } catch (error) {+ // With only incognito ids there is no row whose absence can reconcile an ambiguous response.+ if (ids.length === 0) throw error;+ // an aborted or dropped response is not proof the delete failed. the caller rolls its+ // tombstone back on a throw, and doing that for a row the backend did remove leaves the+ // thread 410 on every later write, so confirm the rows really survived first.+ // Bounded: the DELETE only got here by aborting on a wedged socket, and an unbounded read+ // would hang the delete instead. A read that cannot answer counts the row as surviving.+ const survived = await Promise.all(+ ids.map((id) =>+ getChatThread(id, { bounded: true }).then(+ (thread) => thread !== null,+ () => true,+ ),+ ),+ );+ if (survived.some(Boolean)) {+ throw error;+ }+ }+ for (const id of ids) {+ failedThreadRecordByThreadId.delete(id);+ initializingThreadRecords.delete(id);+ }+ threadRecordWrites.confirmFinalState(ids);if (ids.length === 0) return kept;await db.transaction("rw", db.threads, db.messages, async () => {@@ -766,22 +961,33 @@ export interface ClearStoredChatsResult {sandboxesKept: string[];}-export async function clearStoredChats(): Promise<ClearStoredChatsResult> {- // Clear both sides independently and report each outcome so the toast- // can distinguish full vs partial success.- const [backendThreadsResult, legacyThreads] = await Promise.all([- listChatThreads()- .then((threads) => ({ ok: true as const, threads }))- .catch(() => ({ ok: false as const, threads: [] as ThreadRecord[] })),- db.threads.toArray().catch(() => []),- ]);- const backendInventoryLoaded = backendThreadsResult.ok;- const backendThreadIds = new Set(- backendThreadsResult.threads.map((thread) => thread.id),- );+let clearStoredChatsPromise: Promise<ClearStoredChatsResult> | null = null;++export function clearStoredChats(): Promise<ClearStoredChatsResult> {+ if (clearStoredChatsPromise) return clearStoredChatsPromise;++ threadRecordClearEpoch += 1;+ failedThreadRecordByThreadId.clear();+ const reopenAdmission = threadRecordWrites.closeAdmission();+ const operation = clearStoredChatsWithAdmissionClosed();+ const tracked = operation.finally(() => {+ reopenAdmission();+ if (clearStoredChatsPromise === tracked) {+ clearStoredChatsPromise = null;+ }+ });+ clearStoredChatsPromise = tracked;+ return tracked;+}++async function clearStoredChatsWithAdmissionClosed(): Promise<ClearStoredChatsResult> {+ // Admission is closed before this one-shot fence snapshot.+ const pendingThreadIds = threadRecordWrites.idsRequiringFence();+ const operationId = crypto.randomUUID();+ const legacyThreads = await db.threads.toArray().catch(() => []);const legacyThreadIds = new Set(legacyThreads.map((thread) => thread.id));- const allThreadIds = Array.from(- new Set([...backendThreadIds, ...legacyThreadIds]),+ const idsToFence = Array.from(+ new Set([...legacyThreadIds, ...pendingThreadIds]),);const result: ClearStoredChatsResult = {@@ -791,11 +997,27 @@ export async function clearStoredChats(): Promise<ClearStoredChatsResult> {failedThreadIds: [],sandboxesKept: [],};+ let backendDeletedThreadIds: string[] = [];+ const runBackendClear = () =>+ clearBackendChats({+ notify: false,+ operationId,+ // the transaction finds existing rows itself; these ids additionally fence legacy rows and+ // writes that have not committed yet+ tombstoneThreadIds: idsToFence,+ });try {- // Defer the history refresh until Dexie clear and tombstones finalize,- // so listeners never observe the composite clear mid-flight.- result.sandboxesKept = await clearBackendChats({ notify: false });+ // Retried once under the same operationId, still with admission closed. A request that timed+ // out is not proof its transaction did not run, and the retry takes the writer lock behind+ // that transaction and replays its recorded result, so admission cannot reopen into a window+ // where a new chat is created and then deleted by a clear that lands late.+ const backendResult = await runBackendClear().catch(() =>+ runBackendClear(),+ );+ backendDeletedThreadIds = backendResult.deletedThreadIds;+ result.sandboxesKept = backendResult.sandboxesKept;result.backend = "cleared";+ threadRecordWrites.confirmFinalState(idsToFence);} catch (error) {result.backend = "failed";console.error("clearStoredChats: backend clear failed", error);@@ -812,14 +1034,17 @@ export async function clearStoredChats(): Promise<ClearStoredChatsResult> {console.error("clearStoredChats: legacy Dexie clear failed", error);}- result.deletedThreadIds = allThreadIds.filter((id) => {- const backendDeleted =- result.backend === "cleared" ||- (backendInventoryLoaded && !backendThreadIds.has(id));- const legacyDeleted =- !legacyThreadIds.has(id) || result.legacy === "cleared";- return backendDeleted && legacyDeleted;- });+ // reported from the rows the backend says it removed, never from the fence set: an id fenced for+ // a write that never committed had no chat to delete+ const allThreadIds = Array.from(+ new Set([...legacyThreadIds, ...backendDeletedThreadIds]),+ );+ result.deletedThreadIds =+ result.backend === "cleared"+ ? allThreadIds.filter(+ (id) => !legacyThreadIds.has(id) || result.legacy === "cleared",+ )+ : [];const deleted = new Set(result.deletedThreadIds);result.failedThreadIds = allThreadIds.filter((id) => !deleted.has(id));diff --git a/studio/frontend/src/features/chat/utils/clear-all-chats.ts b/studio/frontend/src/features/chat/utils/clear-all-chats.tsindex ef20659cf02..e2c6bbe834f 100644--- a/studio/frontend/src/features/chat/utils/clear-all-chats.ts+++ b/studio/frontend/src/features/chat/utils/clear-all-chats.ts@@ -25,6 +25,5 @@ export async function clearAllChats() {stopChatThread(threadId);}requestPromptQueueStop();- await chatHistoryClearBoundary.waitForPending();return await clearStoredChats();}diff --git a/studio/frontend/src/features/chat/utils/thread-record-write-coordinator.ts b/studio/frontend/src/features/chat/utils/thread-record-write-coordinator.tsnew file mode 100644index 00000000000..3aeec55169c--- /dev/null+++ b/studio/frontend/src/features/chat/utils/thread-record-write-coordinator.ts@@ -0,0 +1,89 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export class ThreadRecordWriteCoordinator {+ private readonly pending = new Map<string, Set<Promise<unknown>>>();+ private readonly unconfirmed = new Map<string, Set<symbol>>();+ private readonly blockedError: (threadId: string) => Error;+ private readonly confirmsAbsence: (error: unknown) => boolean;+ private admissionClosed = false;++ constructor(+ blockedError: (threadId: string) => Error,+ confirmsAbsence: (error: unknown) => boolean,+ ) {+ this.blockedError = blockedError;+ this.confirmsAbsence = confirmsAbsence;+ }++ observe<T>(threadId: string, work: Promise<T>): Promise<T> {+ const workForThread = this.pending.get(threadId) ?? new Set();+ workForThread.add(work);+ this.pending.set(threadId, workForThread);++ const forget = () => {+ const current = this.pending.get(threadId);+ current?.delete(work);+ if (current?.size === 0) {+ this.pending.delete(threadId);+ }+ };+ work.then(forget, forget);+ return work;+ }++ write<T>(threadId: string, start: () => Promise<T>): Promise<T> {+ if (this.admissionClosed) {+ return Promise.reject(this.blockedError(threadId));+ }++ const operation = Symbol(threadId);+ const unconfirmedForThread = this.unconfirmed.get(threadId) ?? new Set();+ unconfirmedForThread.add(operation);+ this.unconfirmed.set(threadId, unconfirmedForThread);+ const work = Promise.resolve().then(start);+ const confirm = () => {+ const current = this.unconfirmed.get(threadId);+ current?.delete(operation);+ if (current?.size === 0) {+ this.unconfirmed.delete(threadId);+ }+ };+ work.then(confirm, (error: unknown) => {+ if (this.confirmsAbsence(error)) {+ confirm();+ }+ });+ return this.observe(threadId, work);+ }++ async settleCurrent(threadId: string): Promise<void> {+ const current = this.pending.get(threadId);+ if (current) {+ await Promise.allSettled(Array.from(current));+ }+ }++ hasPending(threadId: string): boolean {+ return this.pending.has(threadId);+ }++ idsRequiringFence(): string[] {+ return Array.from(+ new Set([...this.pending.keys(), ...this.unconfirmed.keys()]),+ );+ }++ confirmFinalState(threadIds: Iterable<string>): void {+ for (const threadId of threadIds) {+ this.unconfirmed.delete(threadId);+ }+ }++ closeAdmission(): () => void {+ this.admissionClosed = true;+ return () => {+ this.admissionClosed = false;+ };+ }+}diff --git a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx b/studio/frontend/src/features/rag/components/thread-documents-bar.tsxindex 51d3dee23e3..1b5a1c71fe7 100644--- a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx+++ b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx@@ -7,6 +7,12 @@ import { AttachmentIcon, FileDatabaseIcon } from "@hugeicons/core-free-icons";import { useAui } from "@assistant-ui/react";import { cn } from "@/lib/utils";import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";+import {+ chatHistoryClearBoundary,+ ChatThreadDeletedError,+ ensureStoredChatThread,+ isThreadIncognito,+} from "@/features/chat";import {useNativeAttachmentTargetKey,useNativeIntentStore,@@ -50,6 +56,30 @@ function KnowledgeBaseSourceChip({ kbId }: { kbId: string }) {);}+/**+* Confirm a thread is stored before documents are indexed against it. An id reaches this+* component before its row write lands, from a cached initialize() or from activeThreadId, and+* upload_thread_document does not check the thread itself. A transport failure is not proof the+* row is missing, so only a definitive miss blocks the upload.+*/+async function requireStoredThread(threadId: string): Promise<void> {+ if (isThreadIncognito(threadId)) return;+ let stored: Awaited<ReturnType<typeof ensureStoredChatThread>>;+ try {+ stored = await ensureStoredChatThread(threadId);+ } catch (error) {+ // A backend tombstone is an answer, not an indeterminate transport failure: indexing+ // against it would leave documents under a thread that can never come back.+ if (error instanceof ChatThreadDeletedError) {+ throw error;+ }+ return;+ }+ if (!stored) {+ throw new Error(`Thread ${threadId} was not persisted`);+ }+}+export function ThreadDocumentsBar({threadId,onIndexingChange,@@ -70,8 +100,14 @@ export function ThreadDocumentsBar({// (ProjectLanding's pendingNewThreadId branch) and drop the just-attached chips.const [materializedId, setMaterializedId] = useState<string | null>(null);const effectiveThreadId = threadId ?? materializedId;+ const initPromiseRef = useRef<Promise<string | null> | null>(null);+ const initGenerationRef = useRef(0);useEffect(() => {- if (threadId) setMaterializedId(null);+ if (threadId) {+ setMaterializedId(null);+ initGenerationRef.current += 1;+ initPromiseRef.current = null;+ }}, [threadId]);const lister = useCallback(@@ -100,26 +136,49 @@ export function ThreadDocumentsBar({useEffect(() => () => onIndexingChange?.(false), [onIndexingChange]);// Materialize the thread id on first use; ref-deduped so a double-click can't- // start two threads.- const initPromiseRef = useRef<Promise<string | null> | null>(null);+ // start two threads. A thread switch gets separate work even if the prior request is pending.const ensureThreadId = useCallback((): Promise<string | null> => {- if (effectiveThreadId) return Promise.resolve(effectiveThreadId);- if (initPromiseRef.current) return initPromiseRef.current;+ if (effectiveThreadId) {+ return requireStoredThread(effectiveThreadId).then(+ () => effectiveThreadId,+ () => {+ toast.error("Couldn't start a chat for these documents");+ return null;+ },+ );+ }+ const current = initPromiseRef.current;+ if (current) {+ return current;+ }+ const clearGeneration = chatHistoryClearBoundary.capture();+ const generation = ++initGenerationRef.current;const pending = aui.threadListItem().initialize()- .then(({ remoteId }) => {- setMaterializedId(remoteId);+ .then(async ({ remoteId }) => {+ await requireStoredThread(remoteId);+ // a clear that landed while the row write was in flight is deleting this thread+ if (chatHistoryClearBoundary.capture() !== clearGeneration) {+ throw new Error("Chat history was cleared");+ }+ // an older request can still finish after the component moved to another thread+ if (initGenerationRef.current === generation) {+ setMaterializedId(remoteId);+ }return remoteId;}).catch(() => {toast.error("Couldn't start a chat for these documents");return null;- })- .finally(() => {- initPromiseRef.current = null;});initPromiseRef.current = pending;+ const clear = () => {+ if (initPromiseRef.current === pending) {+ initPromiseRef.current = null;+ }+ };+ pending.then(clear, clear);return pending;}, [aui, effectiveThreadId]);diff --git a/studio/frontend/src/features/rag/components/use-rag-documents.ts b/studio/frontend/src/features/rag/components/use-rag-documents.tsindex fb8375dd96b..d75d98ad45a 100644--- a/studio/frontend/src/features/rag/components/use-rag-documents.ts+++ b/studio/frontend/src/features/rag/components/use-rag-documents.ts@@ -12,7 +12,11 @@ import {uploadProjectDocument,uploadThreadDocument,} from "../api/rag-api";-import type { DocumentStatus, RagDocument } from "../types/rag";+import {+ type RagDocument,+ type TerminalJobStatus,+ terminalJobStatus,+} from "../types/rag";import { resolveVisionOverrides } from "./vision-overrides";export interface TrackedDocument extends RagDocument {@@ -114,11 +118,14 @@ export function useRagDocuments(trackedJobs.current.set(jobId, controller);const finish = (- status: DocumentStatus,+ status: TerminalJobStatus,error?: string | null,numChunks?: number | null,) => {- if (status === "failed") {+ if (status === "cancelled") {+ sigByDocId.current.delete(documentId);+ setDocuments((rows) => rows.filter((row) => row.id !== documentId));+ } else if (status === "failed") {// Drop the chip rather than show "Failed"; warn via toast.sigByDocId.current.delete(documentId);setDocuments((rows) => rows.filter((row) => row.id !== documentId));@@ -150,21 +157,17 @@ export function useRagDocuments(finish("completed", null, ev.num_chunks);return;} else if (ev.type === "error") {- finish("failed", ev.error ?? "Indexing failed");+ finish(+ ev.stage === "cancelled" ? "cancelled" : "failed",+ ev.error ?? "Indexing failed",+ );return;}}// Stream ended with no terminal frame: reconcile.const job = await getJob(jobId);- finish(- job.status === "completed"- ? "completed"- : job.status === "failed"- ? "failed"- : "completed",- job.error,- job.numChunks,- );+ const terminal = terminalJobStatus(job.status);+ finish(terminal ?? "completed", job.error, job.numChunks);} catch {if (controller.signal.aborted) {trackedJobs.current.delete(jobId);@@ -175,10 +178,15 @@ export function useRagDocuments(for (let i = 0; i < 600; i++) {if (controller.signal.aborted) break;const job = await getJob(jobId);- if (job.status === "completed")- return finish("completed", null, job.numChunks);- if (job.status === "failed") {- return finish("failed", job.error ?? "Indexing failed");+ const terminal = terminalJobStatus(job.status);+ if (terminal) {+ return finish(+ terminal,+ terminal === "failed"+ ? (job.error ?? "Indexing failed")+ : job.error,+ job.numChunks,+ );}patchDoc(documentId, {status: job.status === "running" ? "running" : "pending",diff --git a/studio/frontend/src/features/rag/types/rag.ts b/studio/frontend/src/features/rag/types/rag.tsindex 9922c740afb..992dc1ba7b9 100644--- a/studio/frontend/src/features/rag/types/rag.ts+++ b/studio/frontend/src/features/rag/types/rag.ts@@ -37,7 +37,23 @@ export interface DocumentUploadResult {filename: string;}-export type JobStatus = "pending" | "running" | "completed" | "failed";+export type JobStatus =+ | "pending"+ | "running"+ | "completed"+ | "failed"+ | "cancelled";++export type TerminalJobStatus = Extract<+ JobStatus,+ "completed" | "failed" | "cancelled"+>;++export function terminalJobStatus(status: JobStatus): TerminalJobStatus | null {+ return status === "completed" || status === "failed" || status === "cancelled"+ ? status+ : null;+}export interface IndexJob {id: string;diff --git a/studio/frontend/tests/chat-history-clear-boundary.test.ts b/studio/frontend/tests/chat-history-clear-boundary.test.tsindex 3df7a25c375..9acd6436240 100644--- a/studio/frontend/tests/chat-history-clear-boundary.test.ts+++ b/studio/frontend/tests/chat-history-clear-boundary.test.ts@@ -10,21 +10,3 @@ test("a history clear invalidates work captured before it", () => {boundary.advance();assert.notEqual(boundary.capture(), captured);});--test("a history clear can drain persistence accepted before it", async () => {- const boundary = new ChatHistoryClearBoundary();- let finish!: () => void;- const pending = new Promise<void>((resolve) => {- finish = resolve;- });- boundary.trackPending(pending);- let drained = false;- const wait = boundary.waitForPending().then(() => {- drained = true;- });- await Promise.resolve();- assert.equal(drained, false);- finish();- await wait;- assert.equal(drained, true);-});diff --git a/studio/frontend/tests/rag-job-status.test.ts b/studio/frontend/tests/rag-job-status.test.tsnew file mode 100644index 00000000000..f3f406208b1--- /dev/null+++ b/studio/frontend/tests/rag-job-status.test.ts@@ -0,0 +1,18 @@+// 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 { terminalJobStatus } from "../src/features/rag/types/rag.ts";++test("completed, failed, and cancelled jobs are terminal", () => {+ assert.equal(terminalJobStatus("completed"), "completed");+ assert.equal(terminalJobStatus("failed"), "failed");+ assert.equal(terminalJobStatus("cancelled"), "cancelled");+});++test("pending and running jobs are not terminal", () => {+ assert.equal(terminalJobStatus("pending"), null);+ assert.equal(terminalJobStatus("running"), null);+});diff --git a/studio/frontend/tests/thread-record-write-coordinator.test.ts b/studio/frontend/tests/thread-record-write-coordinator.test.tsnew file mode 100644index 00000000000..342e97892fd--- /dev/null+++ b/studio/frontend/tests/thread-record-write-coordinator.test.ts@@ -0,0 +1,127 @@+// 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 { ThreadRecordWriteCoordinator } from "../src/features/chat/utils/thread-record-write-coordinator.ts";++class DeletedError extends Error {}++function coordinator(): ThreadRecordWriteCoordinator {+ return new ThreadRecordWriteCoordinator(+ (threadId) => new Error(`clear:${threadId}`),+ (error) => error instanceof DeletedError,+ );+}++function deferred(): {+ promise: Promise<void>;+ resolve: () => void;+ reject: (error: Error) => void;+} {+ let resolve!: () => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<void>((done, fail) => {+ resolve = done;+ reject = fail;+ });+ return { promise, resolve, reject };+}++test("exposes a write id before its request starts", async () => {+ const writes = coordinator();+ const pending = deferred();+ let started = false;+ const work = writes.write("thread-1", () => {+ started = true;+ return pending.promise;+ });++ assert.equal(started, false);+ assert.deepEqual(writes.idsRequiringFence(), ["thread-1"]);+ await Promise.resolve();+ assert.equal(started, true);++ pending.resolve();+ await work;+ assert.deepEqual(writes.idsRequiringFence(), []);+});++test("retains an unconfirmed id after a transport failure", async () => {+ const writes = coordinator();+ const failure = new Error("connection lost");++ await assert.rejects(+ writes.write("thread-1", () => Promise.reject(failure)),+ failure,+ );+ assert.deepEqual(writes.idsRequiringFence(), ["thread-1"]);++ writes.confirmFinalState(["thread-1"]);+ assert.deepEqual(writes.idsRequiringFence(), []);+});++test("one successful write does not hide a concurrent ambiguous write", async () => {+ const writes = coordinator();+ const ambiguous = deferred();+ const first = writes.write("thread-1", () => ambiguous.promise);+ const second = writes.write("thread-1", () => Promise.resolve());++ await second;+ ambiguous.reject(new Error("connection lost"));+ await assert.rejects(first);++ assert.deepEqual(writes.idsRequiringFence(), ["thread-1"]);+});++test("a backend tombstone confirms that a failed save is absent", async () => {+ const writes = coordinator();+ await assert.rejects(+ writes.write("thread-1", () => Promise.reject(new DeletedError())),+ DeletedError,+ );+ assert.deepEqual(writes.idsRequiringFence(), []);+});++test("clear closes admission before taking its fence snapshot", async () => {+ const writes = coordinator();+ const reopen = writes.closeAdmission();+ let started = false;++ await assert.rejects(+ writes.write("thread-1", () => {+ started = true;+ return Promise.resolve();+ }),+ /clear:thread-1/,+ );+ assert.equal(started, false);+ assert.deepEqual(writes.idsRequiringFence(), []);++ reopen();+ await writes.write("thread-1", () => {+ started = true;+ return Promise.resolve();+ });+ assert.equal(started, true);+});++test("settles all work already observed for a thread", async () => {+ const writes = coordinator();+ const first = deferred();+ const second = deferred();+ writes.observe("thread-1", first.promise);+ writes.observe("thread-1", second.promise);++ let settled = false;+ const waiting = writes.settleCurrent("thread-1").then(() => {+ settled = true;+ });+ first.reject(new Error("failed"));+ await Promise.resolve();+ assert.equal(settled, false);+ second.resolve();+ await waiting;+ assert.equal(settled, true);+});diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.pyindex 67092a9fb9b..0b4172466b6 100644--- a/tests/studio/test_multi_chat_prompt_queue_contract.py+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py@@ -36,6 +36,9 @@ PRE_STREAM_RESERVATION = (FRONTEND / "features/chat/utils/pre-stream-run-reservaCHAT_CLEAR_BOUNDARY = (FRONTEND / "features/chat/utils/chat-history-clear-boundary.ts").read_text(encoding = "utf-8")+CHAT_HISTORY_STORAGE = (FRONTEND / "features/chat/utils/chat-history-storage.ts").read_text(+ encoding = "utf-8"+)QUEUED_SETTINGS = (FRONTEND / "features/chat/utils/queued-chat-run-settings.ts").read_text(encoding = "utf-8")@@ -739,14 +742,35 @@ def test_clear_all_invalidates_and_removes_late_fresh_thread_initialization():"requestPromptQueueStop();")assert CLEAR_ALL_CHATS.index("requestPromptQueueStop();") < CLEAR_ALL_CHATS.index(- "await chatHistoryClearBoundary.waitForPending();"+ "return await clearStoredChats();")assert "const historyClearGeneration = chatHistoryClearBoundary.capture();" in RUNTIME_PROVIDERassert "await throwIfHistoryWasCleared(initialized.remoteId);" in RUNTIME_PROVIDERassert "await throwIfHistoryWasCleared(remoteId);" in RUNTIME_PROVIDER- assert "chatHistoryClearBoundary.trackPending(write)" in RUNTIME_PROVIDER+ assert "trackStoredChatThreadRecord(" in RUNTIME_PROVIDERassert "class ChatHistoryClearBoundary" in CHAT_CLEAR_BOUNDARY- assert "async waitForPending(): Promise<void>" in CHAT_CLEAR_BOUNDARY+ assert "capture(): number" in CHAT_CLEAR_BOUNDARY+ assert "advance(): number" in CHAT_CLEAR_BOUNDARY+ assert "const reopenAdmission = threadRecordWrites.closeAdmission();" in CHAT_HISTORY_STORAGE+ assert (+ "const pendingThreadIds = threadRecordWrites.idsRequiringFence();" in CHAT_HISTORY_STORAGE+ )+ assert "tombstoneThreadIds: idsToFence" in CHAT_HISTORY_STORAGE+ assert "threadRecordWrites.confirmFinalState(idsToFence);" in CHAT_HISTORY_STORAGE+++def test_a_failed_thread_row_write_surfaces_to_the_patch_caller():+ """A retry that reports undefined reads as "no row to update", so the queued run's+ model correction is dropped and never retried: thread.tsx clears+ shouldCorrectPersistedModel right after the awaited updateStoredChatThread."""+ retry = _between(+ CHAT_HISTORY_STORAGE,+ "async function retryFailedThreadRecord(",+ "export async function listStoredChatMessages(",+ )+ # awaiting the tracked write, not the settle-all helper, is what propagates the failure+ assert "await trackStoredChatThreadRecord(threadId, createRecord);" in retry+ assert "await awaitStoredChatThreadWrites(threadId);\n return" not in retrydef test_noop_setting_refreshes_do_not_invalidate_pending_queues():