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: advertise the chat-title repair guards on the thread lists instead of fetching /openapi.json (#15685)
Daniel Hanae41442dccfc
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex cdca1a92a07..bbb3355839e 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1359,8 +1359,8 @@ def _nonced_docs_response(html: str, *, tag: "_re.Pattern[str]") -> HTMLResponsereturn HTMLResponse(nonced, headers = {_CSP_SCRIPT_NONCE_HEADER: nonce})-# FastAPI's own /openapi.json builds the schema on the event loop: seconds for ~550 routes, fetched by the chat-# sidebar every session, stalling every request behind it (#9712). Built once in a worker thread instead.+# FastAPI's own /openapi.json builds the schema on the event loop: seconds for ~550 routes, fetched by older chat+# sidebars every session, stalling every request behind it (#9712). Built once in a worker thread instead._openapi_build_lock = threading.Lock()_build_openapi_schema = app.openapidiff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 876a948cb6c..84ab60562e6 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -353,8 +353,16 @@ class ChatProjectPatch(BaseModel):updatedAt: Optional[SqliteInt] = None+# Advertised on the thread lists so the title repair skips fetching /openapi.json (older backends still need it).+_THREAD_PATCH_GUARD_FIELDS = ("expectedTitle", "expectedOpeningMessageId")+THREAD_PATCH_GUARDS = all(+ name in ChatThreadPatch.model_fields for name in _THREAD_PATCH_GUARD_FIELDS+)++class ChatThreadListResponse(BaseModel):threads: list[ChatThread]+ threadPatchGuards: bool = Falseclass ChatProjectListResponse(BaseModel):@@ -397,6 +405,7 @@ class ChatSidebarRowsResponse(BaseModel):nextCursor: Optional[str] = NonehasMore: booltotal: int+ threadPatchGuards: bool = Falseclass ChatSidebarThreadRowsResponse(BaseModel):@@ -762,7 +771,10 @@ def list_threads(project_id = project_id,include_archived = include_archived,)- return ChatThreadListResponse(threads = [thread_from_row(t) for t in threads])+ return ChatThreadListResponse(+ threads = [thread_from_row(t) for t in threads],+ threadPatchGuards = THREAD_PATCH_GUARDS,+ )@router.post(@@ -788,7 +800,7 @@ def list_sidebar_rows()except SidebarCursorError as exc:raise HTTPException(status_code = 400, detail = str(exc)) from exc- return ChatSidebarRowsResponse(**page)+ return ChatSidebarRowsResponse(**page, threadPatchGuards = THREAD_PATCH_GUARDS)_SIDEBAR_THREAD_ROWS_MAX = 500diff --git a/studio/backend/tests/test_chat_thread_patch_guards_flag.py b/studio/backend/tests/test_chat_thread_patch_guards_flag.pynew file mode 100644index 00000000000..90ce2b0657b--- /dev/null+++ b/studio/backend/tests/test_chat_thread_patch_guards_flag.py@@ -0,0 +1,70 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Thread lists advertise the title-repair guards; /openapi.json must still declare them for older frontends."""++import os+import sys++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++_backend = os.path.join(os.path.dirname(__file__), "..")+sys.path.insert(0, _backend)++from auth.authentication import get_current_subject+from routes import chat_history+from storage import studio_db++GUARD_FIELDS = ("expectedTitle", "expectedOpeningMessageId")+++def app(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ app = FastAPI()+ app.include_router(chat_history.router, prefix = "/api/chat")+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ return app+++def _schema_declares_guards(document: dict) -> bool:+ """Python twin of the frontend's schemaDeclaresRepairGuards (openapi-support.ts)."""+ properties = (+ document.get("components", {})+ .get("schemas", {})+ .get("ChatThreadPatch", {})+ .get("properties", {})+ )+ return all(field in properties for field in GUARD_FIELDS)+++def test_thread_list_advertises_the_guards(app):+ body = TestClient(app).get("/api/chat/threads").json()+ assert body["threadPatchGuards"] is True+ assert body["threads"] == []+++def test_sidebar_rows_advertise_the_guards(app):+ body = TestClient(app).post("/api/chat/sidebar/rows", json = {}).json()+ assert body["threadPatchGuards"] is True+ assert body["rows"] == [] and body["hasMore"] is False+++def test_flag_agrees_with_the_schema_older_frontends_probe(app):+ client = TestClient(app)+ document = client.get("/openapi.json").json()+ assert _schema_declares_guards(document) is True+ assert client.get("/api/chat/threads").json()["threadPatchGuards"] == _schema_declares_guards(+ document+ )+++def test_flag_follows_the_patch_model():+ assert chat_history.THREAD_PATCH_GUARDS == all(+ name in chat_history.ChatThreadPatch.model_fields for name in GUARD_FIELDS+ )+ assert chat_history.THREAD_PATCH_GUARDS is Truediff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 87f631c0096..9b6163ea2b9 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -32,6 +32,7 @@ import {} from "@/lib/model-lifecycle-events";import type { AgentsMdRecord } from "../utils/agents-md";import { showLoadWarning } from "../utils/load-warning-toast";+import { readAdvertisedPatchGuards } from "../utils/openapi-support";import { validateRequestBody, wireLoadRequest } from "../lib/load-request";import type {MessageRecord,@@ -813,6 +814,17 @@ export async function deleteFineTunedModel(args: {await parseJsonOrThrow<unknown>(response);}+let advertisedPatchGuards: boolean | null = null;++export function advertisedThreadPatchGuards(): boolean | null {+ return advertisedPatchGuards;+}++function noteAdvertisedPatchGuards(data: unknown): void {+ const advertised = readAdvertisedPatchGuards(data);+ if (advertised !== null) advertisedPatchGuards = advertised;+}+export async function listChatThreads(args: {modelType?: ModelType;@@ -831,6 +843,7 @@ export async function listChatThreads(const qs = params.toString();const response = await authFetch(`/api/chat/threads${qs ? `?${qs}` : ""}`);const data = await parseJsonOrThrow<{ threads: ThreadRecord[] }>(response);+ noteAdvertisedPatchGuards(data);// Always hand back an array: an older or misbehaving backend may omit it or send a non-array.return Array.isArray(data.threads) ? data.threads : [];}@@ -904,6 +917,7 @@ export async function fetchSidebarRows(if (response.status === 404 || response.status === 405) return null;if (response.status === 400 && request.cursor) throw new SidebarCursorRejectedError();const data = await parseJsonOrThrow<SidebarRowsPage>(response);+ noteAdvertisedPatchGuards(data);return {rows: Array.isArray(data.rows) ? data.rows : [],nextCursor: data.nextCursor ?? null,diff --git a/studio/frontend/src/features/chat/utils/openapi-support.ts b/studio/frontend/src/features/chat/utils/openapi-support.tsindex 07a056ee7cc..75a9557557c 100644--- a/studio/frontend/src/features/chat/utils/openapi-support.ts+++ b/studio/frontend/src/features/chat/utils/openapi-support.ts@@ -28,3 +28,18 @@ export function readGuardProbe(ok: boolean, document: unknown): GuardProbe {if (!ok) return { supported: false, settled: false };return { supported: schemaDeclaresRepairGuards(document), settled: true };}++/** threadPatchGuards from a thread-list response; null when the backend predates the flag. */+export function readAdvertisedPatchGuards(data: unknown): boolean | null {+ if (typeof data !== "object" || data === null) return null;+ const value = (data as { threadPatchGuards?: unknown }).threadPatchGuards;+ return typeof value === "boolean" ? value : null;+}++export async function resolveGuardProbe(+ advertised: boolean | null,+ probeSchema: () => Promise<GuardProbe>,+): Promise<GuardProbe> {+ if (advertised !== null) return { supported: advertised, settled: true };+ return probeSchema();+}diff --git a/studio/frontend/src/features/chat/utils/repair-legacy-chat-titles.ts b/studio/frontend/src/features/chat/utils/repair-legacy-chat-titles.tsindex 6af5f55184d..fc1f8fc8f82 100644--- a/studio/frontend/src/features/chat/utils/repair-legacy-chat-titles.ts+++ b/studio/frontend/src/features/chat/utils/repair-legacy-chat-titles.ts@@ -3,6 +3,7 @@import { authFetch } from "@/features/auth";import {+ advertisedThreadPatchGuards,batchListChatMessages,listChatImportLedger,updateChatThread,@@ -14,7 +15,11 @@ import {threadsAwaitingImport,threadsMissingMessages,} from "./chat-title";-import { type GuardProbe, readGuardProbe } from "./openapi-support";+import {+ type GuardProbe,+ readGuardProbe,+ resolveGuardProbe,+} from "./openapi-support";import { runWithConcurrency } from "./run-with-concurrency";import { createSerialQueue } from "./serial-queue";@@ -35,18 +40,25 @@ const serial = createSerialQueue();let guardSupport: Promise<boolean> | null = null;/** Read from the served schema: probing with a real patch could let an old backend apply it. */+async function probeServedSchema(): Promise<GuardProbe> {+ try {+ const response = await authFetch("/openapi.json");+ return readGuardProbe(+ response.ok,+ response.ok ? await response.json() : null,+ );+ } catch {+ return { supported: false, settled: false };+ }+}++/** Every repair starts from a thread list, so the advertised flag is already known when present. */function backendEnforcesTitleGuard(): Promise<boolean> {guardSupport ??= (async () => {- let probe: GuardProbe = { supported: false, settled: false };- try {- const response = await authFetch("/openapi.json");- probe = readGuardProbe(- response.ok,- response.ok ? await response.json() : null,- );- } catch {- probe = { supported: false, settled: false };- }+ const probe = await resolveGuardProbe(+ advertisedThreadPatchGuards(),+ probeServedSchema,+ );if (!probe.settled) guardSupport = null;return probe.supported;})();diff --git a/studio/frontend/tests/chat-save-conflict-detail.test.ts b/studio/frontend/tests/chat-save-conflict-detail.test.tsindex a4914f8d228..c3490c65f92 100644--- a/studio/frontend/tests/chat-save-conflict-detail.test.ts+++ b/studio/frontend/tests/chat-save-conflict-detail.test.ts@@ -65,6 +65,7 @@ function harness(response: ReturnType<typeof jsonResponse>) {notifyChatHistoryUpdated: () => {},isCoalescedHistoryEvent: () => false,},+ "../utils/openapi-support": { readAdvertisedPatchGuards: () => null },"../utils/load-warning-toast": { showLoadWarning: () => {} },"../lib/load-request": {},"./generation-length.ts": {},diff --git a/studio/frontend/tests/load-rollback-after-lost-reply.test.ts b/studio/frontend/tests/load-rollback-after-lost-reply.test.tsindex 45632bdf223..3e84e839e78 100644--- a/studio/frontend/tests/load-rollback-after-lost-reply.test.ts+++ b/studio/frontend/tests/load-rollback-after-lost-reply.test.ts@@ -112,6 +112,7 @@ function realLoadModel(auth: AuthApi): ChatApi {notifyChatHistoryUpdated: () => {},isCoalescedHistoryEvent: () => false,},+ "../utils/openapi-support": { readAdvertisedPatchGuards: () => null },"../utils/load-warning-toast": { showLoadWarning: () => {} },"../lib/load-request": loadWithStubs(new URL("../src/features/chat/lib/load-request.ts", import.meta.url),diff --git a/studio/frontend/tests/load-warning-toast.test.ts b/studio/frontend/tests/load-warning-toast.test.tsindex 0bc02016486..15dc1d2f9b2 100644--- a/studio/frontend/tests/load-warning-toast.test.ts+++ b/studio/frontend/tests/load-warning-toast.test.ts@@ -50,6 +50,7 @@ function chatApi(body: Record<string, unknown>) {notifyChatHistoryUpdated: () => {},isCoalescedHistoryEvent: () => false,},+ "../utils/openapi-support": { readAdvertisedPatchGuards: () => null },"../utils/load-warning-toast": {showLoadWarning: (warning: string | null | undefined) => shown.push(warning),},diff --git a/studio/frontend/tests/openapi-support.test.ts b/studio/frontend/tests/openapi-support.test.tsindex d44021e9013..8eed715c192 100644--- a/studio/frontend/tests/openapi-support.test.ts+++ b/studio/frontend/tests/openapi-support.test.ts@@ -2,7 +2,10 @@ import assert from "node:assert/strict";import test from "node:test";import {+ type GuardProbe,+ readAdvertisedPatchGuards,readGuardProbe,+ resolveGuardProbe,schemaDeclaresRepairGuards,} from "../src/features/chat/utils/openapi-support.ts";@@ -80,3 +83,80 @@ test("an HTTP failure is a moment, not an answer", () => {settled: false,});});++test("a thread list from a current backend advertises the guards", () => {+ assert.equal(+ readAdvertisedPatchGuards({ threads: [], threadPatchGuards: true }),+ true,+ );+ assert.equal(+ readAdvertisedPatchGuards({+ rows: [],+ hasMore: false,+ total: 0,+ threadPatchGuards: false,+ }),+ false,+ );+});++test("an older backend's list, or anything malformed, advertises nothing", () => {+ for (const data of [+ { threads: [] },+ { rows: [], hasMore: false, total: 0 },+ { threadPatchGuards: "true" },+ { threadPatchGuards: 1 },+ { threadPatchGuards: null },+ null,+ undefined,+ [],+ "threadPatchGuards",+ ]) {+ assert.equal(readAdvertisedPatchGuards(data), null, JSON.stringify(data));+ }+});++function countingProbe(result: GuardProbe) {+ const calls: number[] = [];+ return {+ calls,+ probe: async () => {+ calls.push(1);+ return result;+ },+ };+}++test("an advertised flag settles the guard without fetching the schema", async () => {+ for (const advertised of [true, false]) {+ const { calls, probe } = countingProbe({+ supported: !advertised,+ settled: true,+ });+ assert.deepEqual(await resolveGuardProbe(advertised, probe), {+ supported: advertised,+ settled: true,+ });+ assert.equal(calls.length, 0);+ }+});++test("without a flag (older backend) the schema probe decides as before", async () => {+ for (const result of [+ { supported: true, settled: true },+ { supported: false, settled: true },+ { supported: false, settled: false },+ ]) {+ const { calls, probe } = countingProbe(result);+ assert.deepEqual(await resolveGuardProbe(null, probe), result);+ assert.equal(calls.length, 1);+ }+});++test("the flag and the schema probe agree on what a current backend serves", async () => {+ const schema = readGuardProbe(true, documentWith(GUARDED));+ const flag = await resolveGuardProbe(true, async () => {+ throw new Error("must not probe");+ });+ assert.deepEqual(flag, schema);+});diff --git a/studio/frontend/tests/thread-read-sharing.test.ts b/studio/frontend/tests/thread-read-sharing.test.tsindex feef8435e38..a06af8c4610 100644--- a/studio/frontend/tests/thread-read-sharing.test.ts+++ b/studio/frontend/tests/thread-read-sharing.test.ts@@ -65,6 +65,7 @@ function harness() {publishChatHistoryRevision: () => {},CHAT_HISTORY_REVISION_KEY: "unsloth_chat_history_revision",},+ "../utils/openapi-support": { readAdvertisedPatchGuards: () => null },"../utils/load-warning-toast": { showLoadWarning: () => {} },"../lib/load-request": {},"./generation-length.ts": {},diff --git a/studio/frontend/tests/tool-approval-gone.test.ts b/studio/frontend/tests/tool-approval-gone.test.tsindex f72c5001d72..61c2005ca10 100644--- a/studio/frontend/tests/tool-approval-gone.test.ts+++ b/studio/frontend/tests/tool-approval-gone.test.ts@@ -55,6 +55,7 @@ function harness(response: ReturnType<typeof jsonResponse>) {notifyChatHistoryUpdated: () => {},isCoalescedHistoryEvent: () => false,},+ "../utils/openapi-support": { readAdvertisedPatchGuards: () => null },"../utils/load-warning-toast": { showLoadWarning: () => {} },"../lib/load-request": {},"./generation-length.ts": {},diff --git a/tests/studio/test_legacy_chat_title_repair.py b/tests/studio/test_legacy_chat_title_repair.pyindex 70c2cad7c5a..9222373bdbf 100644--- a/tests/studio/test_legacy_chat_title_repair.py+++ b/tests/studio/test_legacy_chat_title_repair.py@@ -114,9 +114,14 @@ def test_the_migration_stays_off_where_the_guard_is_not_enforced():answers, and anything unreadable counts as unsupported."""repair = _read(REPAIR)assert "if (!(await backendEnforcesTitleGuard())) return 0;" in repair+ # The thread list's advertised flag decides first; only an older backend falls back to the schema.+ assert (+ "const probe = await resolveGuardProbe( advertisedThreadPatchGuards(), probeServedSchema, );"+ in repair+ )assert 'const response = await authFetch("/openapi.json");' in repairassert (- "probe = readGuardProbe( response.ok, response.ok ? await response.json() : null, );"+ "return readGuardProbe( response.ok, response.ok ? await response.json() : null, );"in repair)# Only a settled answer is cached, or a 401 at startup parks the migration.