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: keep chat titles whole so a wider sidebar shows more of them (#8078)
Michael Han467e564f56a7
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex cb235281145..b00ad1f5616 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -17,6 +17,7 @@ from utils.utils import safe_curated_detail, log_and_http_errorfrom storage.studio_db import (ChatMessageConflictError,ChatMessageProtectedError,+ ChatThreadPreconditionFailed,CorruptSettingsError,clear_chat_history,count_chat_threads,@@ -70,6 +71,10 @@ class ChatThread(BaseModel):class ChatThreadPatch(BaseModel):title: Optional[str] = None+ # Apply only while the row still holds this title, so a rename beats a background rewrite.+ expectedTitle: Optional[str] = None+ # Apply only while this is still the opening user message, so a title from a deleted one is rejected.+ expectedOpeningMessageId: Optional[str] = NonemodelType: Optional[Literal["base", "lora", "model1", "model2"]] = NonemodelId: Optional[str] = NonepairId: Optional[str] = None@@ -276,6 +281,8 @@ async def patch_thread(current_subject: str = Depends(get_current_subject),):patch = payload.model_dump(exclude_unset = True)+ expected_title = patch.pop("expectedTitle", None)+ expected_opening_message_id = patch.pop("expectedOpeningMessageId", None)for field in ("title", "modelType", "modelId", "archived", "createdAt", "updatedAt"):if field in patch and patch[field] is None:raise HTTPException(status_code = 400, detail = f"{field} cannot be null")@@ -284,10 +291,18 @@ async def patch_thread(status_code = 404,detail = f"Project {patch['projectId']} not found",)- thread = update_chat_thread(- thread_id,- patch,- )+ try:+ thread = update_chat_thread(+ thread_id,+ patch,+ expected_title = expected_title,+ expected_opening_message_id = expected_opening_message_id,+ )+ except ChatThreadPreconditionFailed:+ raise HTTPException(+ status_code = 409,+ detail = f"Thread {thread_id} changed since it was read",+ )if thread is None:raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")return ChatThread(**thread)diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 09df021b5af..0f76ee45b3f 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -1583,7 +1583,28 @@ def upsert_chat_thread(thread: dict) -> dict:conn.close()-def update_chat_thread(id: str, patch: dict) -> Optional[dict]:+class ChatThreadPreconditionFailed(Exception):+ """The thread changed between the caller reading it and writing it."""+++# Same order the title migration picks its opening message in.+_OPENING_USER_MESSAGE = """(+ SELECT id FROM chat_messages+ WHERE thread_id = ? AND role = 'user'+ ORDER BY created_at ASC, id ASC LIMIT 1+) IS ?"""+++def update_chat_thread(+ id: str,+ patch: dict,+ expected_title: Optional[str] = None,+ expected_opening_message_id: Optional[str] = None,+) -> Optional[dict]:+ """Patch a thread. With expected_title, the write only lands while the row+ still holds that title, so a concurrent rename wins instead of being lost.+ expected_opening_message_id guards a title derived from that message: if it+ is gone, the write is rejected rather than expanding deleted text."""allowed = {"title": ("title", patch.get("title")),"modelType": ("model_type", patch.get("modelType")),@@ -1621,13 +1642,28 @@ def update_chat_thread(id: str, patch: dict) -> Optional[dict]:conn = get_connection()try:- conn.execute(- f"UPDATE chat_threads SET {', '.join(assignments)} WHERE id = ?",- (*values, id),+ # Guards ride in the WHERE clause, so check and write are one statement.+ where = ["id = ?"]+ guard: list = [id]+ if expected_title is not None:+ where.append("title = ?")+ guard.append(expected_title)+ if expected_opening_message_id is not None:+ where.append(_OPENING_USER_MESSAGE)+ guard += [id, expected_opening_message_id]+ guarded = expected_title is not None or expected_opening_message_id is not None+ cursor = conn.execute(+ f"UPDATE chat_threads SET {', '.join(assignments)} WHERE {' AND '.join(where)}",+ (*values, *guard),)+ applied = cursor.rowcountconn.commit()row = conn.execute("SELECT * FROM chat_threads WHERE id = ?", (id,)).fetchone()- return _chat_thread_from_row(row) if row is not None else None+ if row is None:+ return None+ if guarded and applied == 0:+ raise ChatThreadPreconditionFailed(id)+ return _chat_thread_from_row(row)finally:conn.close()diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex b889942cea0..586c2701b0b 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -728,16 +728,31 @@ export async function saveChatThread(return savedThread;}+export interface UpdateChatThreadOptions {+ /** Apply only while the row still holds this title, else 409. */+ expectedTitle?: string;+ /** And only while this is still the thread's opening user message. */+ expectedOpeningMessageId?: string;+}+export async function updateChatThread(threadId: string,patch: Partial<ThreadRecord>,+ options: UpdateChatThreadOptions = {},): Promise<ThreadRecord> {+ const body: Record<string, unknown> = { ...patch };+ if (options.expectedTitle !== undefined) {+ body.expectedTitle = options.expectedTitle;+ }+ if (options.expectedOpeningMessageId !== undefined) {+ body.expectedOpeningMessageId = options.expectedOpeningMessageId;+ }const response = await authFetch(`/api/chat/threads/${encodeURIComponent(threadId)}`,{method: "PATCH",headers: { "Content-Type": "application/json" },- body: JSON.stringify(patch),+ body: JSON.stringify(body),},);const thread = await parseJsonOrThrow<ThreadRecord>(response);diff --git a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.tsindex fcc46580eae..2edfc91fe44 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts@@ -23,6 +23,7 @@ import {removeChatThreadTombstones,} from "../utils/chat-thread-tombstones";import { requestPromptQueueStop } from "../utils/prompt-queue-boundary";+import { repairLegacyChatTitles } from "../utils/repair-legacy-chat-titles";export interface SidebarItem {type: "single" | "compare";@@ -131,6 +132,9 @@ export function useChatSidebarItems(options?: {if (cancelled || seq !== requestSeq) return;setAllThreads(threads);setLoaded(true);+ // Pre-cut legacy titles cannot grow with the sidebar. The repair reads+ // its own messages, as late as it can, not this list's.+ void repairLegacyChatTitles(threads).catch(() => undefined);} catch (error) {if (isExpectedBackgroundChatStorageError(error)) {return;diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex d715f57e1b2..51bfe1d5cec 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -101,6 +101,7 @@ import {markChatThreadDeleted,} from "./utils/chat-thread-tombstones";import { chatHistoryClearBoundary } from "./utils/chat-history-clear-boundary";+import { fallbackTitleFromUserText } from "./utils/chat-title";import { syncExportedRepositoryToBackend } from "./utils/delete-thread-message";import { getImageInputUnavailableReason } from "./utils/image-input-support";import { isAssistantLocalThreadId } from "./utils/thread-ids";@@ -580,14 +581,6 @@ async function generateTitleWithModel(payload: {const inflightTitleByKey = new Set<string>();-function fallbackTitleFromUserText(userText: string): string {- const firstLine = (userText || "").split(/\r?\n/, 1)[0] ?? "";- const cleaned = firstLine.replace(/\s+/g, " ").trim();- const max = 48;- if (!cleaned) return "New Chat";- return cleaned.slice(0, max) + (cleaned.length > max ? "..." : "");-}-function cloneContent(content: ThreadMessage["content"],): ThreadMessage["content"] {diff --git a/studio/frontend/src/features/chat/utils/chat-title.ts b/studio/frontend/src/features/chat/utils/chat-title.tsnew file mode 100644index 00000000000..e7f28f839c4--- /dev/null+++ b/studio/frontend/src/features/chat/utils/chat-title.ts@@ -0,0 +1,183 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { MessageRecord, ThreadRecord } from "../types";++/** Store the whole first line and let the sidebar clip it with CSS, so a wider+ * one shows more. Matches the rename input's maxLength: UTF-16 units, ellipsis+ * included. */+export const FALLBACK_TITLE_MAX = 120;++/** Older titles were stored pre-cut at 48 chars with a literal "...". Kept to+ * find and rewrite those rows. */+export const LEGACY_FALLBACK_TITLE_MAX = 48;+const LEGACY_FALLBACK_SUFFIX = "...";++/** Drop unpaired surrogates: they render as nothing, and one reaching the+ * backend fails its SQLite bind and 500s the title write. Iteration yields a+ * valid pair whole, so a length-1 unit in the range is a lone surrogate. */+function dropLoneSurrogates(text: string): string {+ let out = "";+ for (const character of text) {+ const code = character.codePointAt(0) ?? 0;+ if (character.length === 1 && code >= 0xd800 && code <= 0xdfff) continue;+ out += character;+ }+ return out;+}++function firstLineOf(text: string): string {+ const firstLine = (text || "").split(/\r?\n/, 1)[0] ?? "";+ // Drop surrogates first, or removing one can leave a double or trailing space.+ return dropLoneSurrogates(firstLine).replace(/\s+/g, " ").trim();+}++/** Cut to at most `maxUnits` UTF-16 units without splitting an astral character:+ * a lone surrogate parses fine and then fails the backend's SQLite bind. */+function cutToUnits(text: string, maxUnits: number): string {+ let out = "";+ for (const character of text) {+ if (out.length + character.length > maxUnits) break;+ out += character;+ }+ return out;+}++export function fallbackTitleFromUserText(userText: string): string {+ const cleaned = firstLineOf(userText);+ if (!cleaned) return "New Chat";+ if (cleaned.length <= FALLBACK_TITLE_MAX) return cleaned;+ // The ellipsis takes one of the budget, so the title still fits the input.+ return cutToUnits(cleaned, FALLBACK_TITLE_MAX - 1).trimEnd() + "…";+}++/** Pre-filter on the title alone: only these are worth fetching messages for. */+export function couldBeLegacyClippedTitle(title: string | undefined): boolean {+ return (+ typeof title === "string" &&+ title.endsWith(LEGACY_FALLBACK_SUFFIX) &&+ title.length === LEGACY_FALLBACK_TITLE_MAX + LEGACY_FALLBACK_SUFFIX.length+ );+}++/** True when `title` is exactly the old 48-character cut of `userText`. */+export function isLegacyClippedTitle(+ title: string | undefined,+ userText: string,+): boolean {+ if (!couldBeLegacyClippedTitle(title)) return false;+ const kept = (title as string).slice(0, LEGACY_FALLBACK_TITLE_MAX);+ const cleaned = firstLineOf(userText);+ return (+ cleaned.length > LEGACY_FALLBACK_TITLE_MAX &&+ cleaned.slice(0, LEGACY_FALLBACK_TITLE_MAX) === kept+ );+}++function textOf(message: MessageRecord | undefined): string {+ if (!message) return "";+ const content = message.content;+ if (typeof content === "string") return content;+ if (!Array.isArray(content)) return "";+ return content+ .filter(+ (part): part is Extract<typeof part, { type: "text" }> =>+ part.type === "text",+ )+ .map((part) => part.text)+ .join("")+ .trim();+}++export interface LegacyTitleRepair {+ threadId: string;+ /** The clipped title the rewrite is based on, guarding the write. */+ previousTitle: string;+ /** The message the title came from, guarded too: deleting it must not leave+ * its text expanded into the title. */+ openingMessageId: string;+ title: string;+}++export interface LegacyRepairPage {+ candidates: ThreadRecord[];+ /** What this page skipped. The next page reads it, so a row this page failed+ * on is not redrawn by the same drain. */+ rest: ThreadRecord[];+ hasMore: boolean;+}++/** One page of rows to look at, skipping the ones already tried. */+export function selectLegacyRepairPage(+ threads: ThreadRecord[],+ attempted: ReadonlySet<string>,+ limit: number,+): LegacyRepairPage {+ const pending = threads.filter(+ (thread) =>+ couldBeLegacyClippedTitle(thread.title) && !attempted.has(thread.id),+ );+ const candidates = pending.slice(0, limit);+ const taken = new Set(candidates.map((thread) => thread.id));+ return {+ candidates,+ rest: threads.filter((thread) => !taken.has(thread.id)),+ hasMore: pending.length > limit,+ };+}++/** Threads the backend holds no messages for. */+export function threadsMissingMessages(+ ids: readonly string[],+ messagesByThreadId: ReadonlyMap<string, MessageRecord[]>,+): string[] {+ return ids.filter((id) => (messagesByThreadId.get(id) ?? []).length === 0);+}++/** Of those, the ones still worth retrying: no record of their import+ * finishing, so their messages may yet land. One the ledger knows is simply+ * empty, and retrying it would re-read it on every refresh for the session,+ * since its title stays clipped and keeps matching the pre-filter. */+export function threadsAwaitingImport(+ ids: readonly string[],+ messagesByThreadId: ReadonlyMap<string, MessageRecord[]>,+ importedThreadIds: ReadonlySet<string>,+): string[] {+ return threadsMissingMessages(ids, messagesByThreadId).filter(+ (id) => !importedThreadIds.has(id),+ );+}++/** Rows to rewrite. A title must be the exact old cut of its own first+ * message, so a rename ending in "..." is left alone. */+export function planLegacyTitleRepairs(+ threads: ThreadRecord[],+ messagesByThreadId: Map<string, MessageRecord[]>,+): LegacyTitleRepair[] {+ const repairs: LegacyTitleRepair[] = [];+ for (const thread of threads) {+ const messages = messagesByThreadId.get(thread.id) ?? [];+ // Earliest, not first in the array; ties break on id, as the backend does.+ const opening = messages+ .filter((m) => m.role === "user")+ .reduce<MessageRecord | undefined>((earliest, m) => {+ if (earliest === undefined) return m;+ if (m.createdAt !== earliest.createdAt) {+ return m.createdAt < earliest.createdAt ? m : earliest;+ }+ return m.id < earliest.id ? m : earliest;+ }, undefined);+ const userText = textOf(opening);+ if (opening === undefined) continue;+ if (!isLegacyClippedTitle(thread.title, userText)) continue;+ const title = fallbackTitleFromUserText(userText);+ if (title === thread.title) continue;+ repairs.push({+ threadId: thread.id,+ previousTitle: thread.title,+ openingMessageId: opening.id,+ title,+ });+ }+ return repairs;+}diff --git a/studio/frontend/src/features/chat/utils/openapi-support.ts b/studio/frontend/src/features/chat/utils/openapi-support.tsnew file mode 100644index 00000000000..94db2a5a73b--- /dev/null+++ b/studio/frontend/src/features/chat/utils/openapi-support.ts@@ -0,0 +1,34 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++const GUARD_FIELDS = ["expectedTitle", "expectedOpeningMessageId"] as const;++/** Whether the served schema declares the guard fields. The desktop app ships+ * its own frontend against a separately installed backend, and an older one+ * drops these and writes unguarded. Anything unrecognised is unsupported. */+export function schemaDeclaresRepairGuards(document: unknown): boolean {+ if (typeof document !== "object" || document === null) return false;+ const components = (document as { components?: unknown }).components;+ if (typeof components !== "object" || components === null) return false;+ const schemas = (components as { schemas?: unknown }).schemas;+ if (typeof schemas !== "object" || schemas === null) return false;+ const patch = (schemas as Record<string, unknown>).ChatThreadPatch;+ if (typeof patch !== "object" || patch === null) return false;+ const properties = (patch as { properties?: unknown }).properties;+ if (typeof properties !== "object" || properties === null) return false;+ const declared = properties as Record<string, unknown>;+ return GUARD_FIELDS.every((field) => field in declared);+}++export interface GuardProbe {+ supported: boolean;+ /** Only a schema that arrived and parsed settles it. A 401 while the token+ * warms up or a 503 at startup is a moment, not an answer, and caching one+ * would park the migration for the session. */+ settled: boolean;+}++export function readGuardProbe(ok: boolean, document: unknown): GuardProbe {+ if (!ok) return { supported: false, settled: false };+ return { supported: schemaDeclaresRepairGuards(document), settled: true };+}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.tsnew file mode 100644index 00000000000..9aed8d5e81a--- /dev/null+++ b/studio/frontend/src/features/chat/utils/repair-legacy-chat-titles.ts@@ -0,0 +1,147 @@+// 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 { authFetch } from "@/features/auth";+import {+ batchListChatMessages,+ listChatImportLedger,+ updateChatThread,+} from "../api/chat-api";+import type { MessageRecord, ThreadRecord } from "../types";+import {+ planLegacyTitleRepairs,+ selectLegacyRepairPage,+ threadsAwaitingImport,+ threadsMissingMessages,+} from "./chat-title";+import { type GuardProbe, readGuardProbe } from "./openapi-support";+import { runWithConcurrency } from "./run-with-concurrency";+import { createSerialQueue } from "./serial-queue";++/** Threads already tried, so ones that could not be rewritten stay off every+ * later refresh. */+const attempted = new Set<string>();++/** Rows per pass, so a long history drains in pages. */+const REPAIR_PER_PASS = 100;++/** Writes in flight. Each PATCH is a synchronous SQLite call server side. */+const REPAIR_CONCURRENCY = 4;++/** Breather between pages. */+const REPAIR_PAGE_PAUSE_MS = 500;++/** Several sidebars can be mounted at once, so REPAIR_CONCURRENCY only holds if+ * their passes queue rather than overlap. */+const serial = createSerialQueue();++/** Cached once the served schema answers. A failed probe is not cached, so a+ * startup hiccup does not park the migration for the session. */+let guardSupport: Promise<boolean> | null = null;++/** Whether this backend enforces the conditional title patch. Probing by+ * sending one would let an older backend apply the write, the very harm being+ * checked for, so the served schema answers; anything unreadable is a no. */+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 };+ }+ // Only a settled answer is worth remembering.+ if (!probe.settled) guardSupport = null;+ return probe.supported;+ })();+ return guardSupport;+}++/** Rewrite titles stored pre-cut at 48 chars so they grow with the sidebar. */+export function repairLegacyChatTitles(+ threads: ThreadRecord[],+): Promise<number> {+ return serial(() => runRepairPass(threads));+}++async function runRepairPass(threads: ThreadRecord[]): Promise<number> {+ // Claim nothing until the guard is known: a rewrite that can silently beat a+ // rename is not worth a tidier title.+ if (!(await backendEnforcesTitleGuard())) return 0;++ const { candidates, rest, hasMore } = selectLegacyRepairPage(+ threads,+ attempted,+ REPAIR_PER_PASS,+ );+ if (candidates.length === 0) return 0;+ const ids = candidates.map((thread) => thread.id);+ for (const id of ids) attempted.add(id);++ let messages: Map<string, MessageRecord[]>;+ try {+ // Not the caller's earlier map: the backend's own view, taken as late as+ // possible, is what the rewrite has to be based on. One batched call.+ messages = await batchListChatMessages(ids);+ } catch {+ // Nothing was decided, so let a later refresh try these again.+ for (const id of ids) attempted.delete(id);+ return 0;+ }++ // Backend messages only: Dexie keeps rows the backend has pruned, so merging+ // the two could put a deleted prompt back into a title. A chat not imported+ // yet reads as unknown below and is retried once its messages land.+ const repairs = planLegacyTitleRepairs(candidates, messages);++ // Nothing stored means either mid-import or emptied by the user; the ledger+ // tells them apart, and is only fetched when there is something to decide.+ const withoutMessages = threadsMissingMessages(ids, messages);+ if (withoutMessages.length > 0) {+ let imported = new Set<string>();+ try {+ imported = await listChatImportLedger();+ } catch {+ // Undecided, so keep every one of them retryable.+ }+ for (const id of threadsAwaitingImport(ids, messages, imported)) {+ attempted.delete(id);+ }+ }++ let repaired = 0;+ await runWithConcurrency(repairs, REPAIR_CONCURRENCY, async (repair) => {+ try {+ // The backend PATCH directly, not updateStoredChatThread: that ensures+ // the thread first, re-importing one deleted on another client from the+ // Dexie rows still here, and a migration must never create anything.+ // Both guards answer 409 if a rename or a delete of the opening prompt+ // lands first, and a title patch leaves updatedAt alone, so Recents keeps+ // its order.+ await updateChatThread(+ repair.threadId,+ { title: repair.title },+ {+ expectedTitle: repair.previousTitle,+ expectedOpeningMessageId: repair.openingMessageId,+ },+ );+ repaired += 1;+ } catch {+ attempted.delete(repair.threadId);+ }+ });++ // A page that wrote nothing fires no history update, so schedule the next one+ // here. It runs on `rest`, so rows this page unmarked are not drawn again.+ if (hasMore) {+ setTimeout(() => {+ void repairLegacyChatTitles(rest).catch(() => undefined);+ }, REPAIR_PAGE_PAUSE_MS);+ }+ return repaired;+}diff --git a/studio/frontend/src/features/chat/utils/run-with-concurrency.ts b/studio/frontend/src/features/chat/utils/run-with-concurrency.tsnew file mode 100644index 00000000000..597de30b62b--- /dev/null+++ b/studio/frontend/src/features/chat/utils/run-with-concurrency.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Run `task` over `items`, at most `limit` at a time, in order. */+export async function runWithConcurrency<T>(+ items: readonly T[],+ limit: number,+ task: (item: T) => Promise<void>,+): Promise<void> {+ const lanes = Math.max(1, Math.min(limit, items.length));+ let next = 0;+ await Promise.all(+ Array.from({ length: lanes }, async () => {+ while (next < items.length) {+ const item = items[next];+ next += 1;+ await task(item as T);+ }+ }),+ );+}diff --git a/studio/frontend/src/features/chat/utils/serial-queue.ts b/studio/frontend/src/features/chat/utils/serial-queue.tsnew file mode 100644index 00000000000..074f92d4a69--- /dev/null+++ b/studio/frontend/src/features/chat/utils/serial-queue.ts@@ -0,0 +1,15 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** One task at a time, in call order. A rejected task does not block the next. */+export function createSerialQueue() {+ let tail: Promise<unknown> = Promise.resolve();+ return function run<T>(task: () => Promise<T>): Promise<T> {+ const next = tail.then(task, task);+ tail = next.then(+ () => undefined,+ () => undefined,+ );+ return next;+ };+}diff --git a/studio/frontend/tests/chat-title-clip.test.ts b/studio/frontend/tests/chat-title-clip.test.tsnew file mode 100644index 00000000000..db2b70312e4--- /dev/null+++ b/studio/frontend/tests/chat-title-clip.test.ts@@ -0,0 +1,298 @@+import assert from "node:assert/strict";+import test from "node:test";++import type {+ MessageRecord,+ ThreadRecord,+} from "../src/features/chat/types.ts";+import {+ fallbackTitleFromUserText,+ isLegacyClippedTitle,+ planLegacyTitleRepairs,+ selectLegacyRepairPage,+ threadsAwaitingImport,+ threadsMissingMessages,+} from "../src/features/chat/utils/chat-title.ts";++const LONG =+ "Can you plot a Mandelbrot set and explain how the escape time algorithm works";++function thread(id: string, title: string): ThreadRecord {+ return { id, title, createdAt: 1, updatedAt: 1 } as ThreadRecord;+}++function userMessage(threadId: string, text: string): MessageRecord {+ return {+ id: `${threadId}-m1`,+ threadId,+ role: "user",+ content: [{ type: "text", text }],+ createdAt: 1,+ } as MessageRecord;+}++/** A high surrogate with no low after it, or a low with no high before it. */+const UNPAIRED_SURROGATE =+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;++test("a title the sidebar can clip keeps the whole first line", () => {+ assert.equal(fallbackTitleFromUserText(LONG), LONG);+ assert.equal(fallbackTitleFromUserText(" spaced out "), "spaced out");+ assert.equal(fallbackTitleFromUserText("first\nsecond"), "first");+ assert.equal(fallbackTitleFromUserText(" "), "New Chat");+});++test("only a pasted wall of text is cut, and with a real ellipsis", () => {+ const wall = "x".repeat(200);+ const title = fallbackTitleFromUserText(wall);+ // 120 UTF-16 units including the ellipsis, which is what the input accepts.+ assert.equal(title.length, 120);+ assert.ok(title.endsWith("…"));+ assert.ok(!title.includes("..."));+});++test("an emoji wall is capped by the same budget the input counts", () => {+ // maxLength counts UTF-16 units, so 120 astral code points would be 240.+ const title = fallbackTitleFromUserText("\u{1F600}".repeat(200));+ assert.ok(title.length <= 120);+ assert.equal(UNPAIRED_SURROGATE.test(title), false);+ assert.ok(title.endsWith("…"));+});++test("a line already inside the budget is stored whole", () => {+ const exact = "y".repeat(120);+ assert.equal(fallbackTitleFromUserText(exact), exact);+});++test("the cap never splits an emoji into a lone surrogate", () => {+ // A lone surrogate survives JSON.stringify but 500s the backend's SQLite bind.+ const line = "x".repeat(119) + "\u{1F600} tail";+ // A raw cut at the budget lands mid-pair.+ assert.equal(UNPAIRED_SURROGATE.test(line.slice(0, 120)), true);+ const title = fallbackTitleFromUserText(line);+ assert.equal(UNPAIRED_SURROGATE.test(title), false);+ // The emoji needs two units and only one is left, so it is left out whole.+ assert.equal(title, "x".repeat(119) + "…");+ assert.equal(title.length, 120);+});++test("a lone surrogate is dropped even when the line is under the cap", () => {+ // The cut sanitises what it walks, so under-cap lines used to be stored as+ // they came, and one unpaired surrogate 500s the backend's title write.+ const line = "x".repeat(60) + "\uD83D";+ assert.ok(line.length <= 120);+ assert.equal(UNPAIRED_SURROGATE.test(line), true);+ const title = fallbackTitleFromUserText(line);+ assert.equal(UNPAIRED_SURROGATE.test(title), false);+ assert.equal(title, "x".repeat(60));+ // A trailing low surrogate with no high before it goes the same way.+ assert.equal(fallbackTitleFromUserText("hi \uDE00"), "hi");+ // A valid pair under the cap is untouched.+ assert.equal(fallbackTitleFromUserText("hi \u{1F600}"), "hi \u{1F600}");+});++test("a legacy title is recognised only against the text it was cut from", () => {+ const legacy = LONG.slice(0, 48) + "...";+ assert.equal(isLegacyClippedTitle(legacy, LONG), true);+ assert.equal(+ isLegacyClippedTitle(legacy, "a different first message"),+ false,+ );+ // A rename that merely ends in "..." is left alone.+ assert.equal(isLegacyClippedTitle("Wait for it...", LONG), false);+ assert.equal(isLegacyClippedTitle(LONG, LONG), false);+});++test("repair rewrites legacy rows and leaves every other row untouched", () => {+ const legacy = LONG.slice(0, 48) + "...";+ const threads = [+ thread("a", legacy),+ thread("b", "Mandelbrot escape time"),+ thread("c", legacy),+ ];+ const messages = new Map<string, MessageRecord[]>([+ ["a", [userMessage("a", LONG)]],+ ["b", [userMessage("b", LONG)]],+ // No stored messages: nothing to rewrite the title from.+ ["c", []],+ ]);++ assert.deepEqual(planLegacyTitleRepairs(threads, messages), [+ { threadId: "a", previousTitle: legacy, openingMessageId: "a-m1", title: LONG },+ ]);+});++test("a drain advances even when a whole page failed and was unmarked", () => {+ // Failures get unmarked for a later refresh. Selecting the next page off the+ // same list would draw them straight back in and never reach the rest.+ const legacy = LONG.slice(0, 48) + "...";+ const threads = ["a", "b", "c", "d"].map((id) => thread(id, legacy));++ const first = selectLegacyRepairPage(threads, new Set(), 2);+ assert.deepEqual(+ first.candidates.map((t) => t.id),+ ["a", "b"],+ );+ // Every write failed, so nothing stayed marked.+ const second = selectLegacyRepairPage(first.rest, new Set(), 2);+ assert.deepEqual(+ second.candidates.map((t) => t.id),+ ["c", "d"],+ );+ assert.equal(second.hasMore, false);+ assert.deepEqual(second.rest, []);+});++test("the opening message is the earliest one, not the first row returned", () => {+ // A local read comes back in index order, so it can start on a later turn.+ const later: MessageRecord = {+ ...userMessage("a", "a later question entirely"),+ id: "a-m9",+ createdAt: 99,+ };+ const opening: MessageRecord = {+ ...userMessage("a", LONG),+ id: "a-m1",+ createdAt: 1,+ };+ const legacy = LONG.slice(0, 48) + "...";++ assert.deepEqual(+ planLegacyTitleRepairs(+ [thread("a", legacy)],+ new Map([["a", [later, opening]]]),+ ),+ // Guarded on the opening message, not the row the array happens to start on.+ [{ threadId: "a", previousTitle: legacy, openingMessageId: "a-m1", title: LONG }],+ );+});++test("two prompts sharing a timestamp break on id, as the backend does", () => {+ // The write is guarded on this id, so both orders must pick the same message.+ const legacy = LONG.slice(0, 48) + "...";+ const first: MessageRecord = { ...userMessage("a", LONG), id: "a-m1" };+ const second: MessageRecord = {+ ...userMessage("a", "a different question"),+ id: "a-m2",+ };++ for (const order of [+ [first, second],+ [second, first],+ ]) {+ assert.deepEqual(+ planLegacyTitleRepairs([thread("a", legacy)], new Map([["a", order]])),+ [+ {+ threadId: "a",+ previousTitle: legacy,+ openingMessageId: "a-m1",+ title: LONG,+ },+ ],+ );+ }+});++test("a page skips rows already tried and reports the leftovers", () => {+ const legacy = LONG.slice(0, 48) + "...";+ const threads = [+ thread("a", legacy),+ thread("b", "a plain title"),+ thread("c", legacy),+ thread("d", legacy),+ ];++ const first = selectLegacyRepairPage(threads, new Set(), 2);+ assert.deepEqual(+ first.candidates.map((t) => t.id),+ ["a", "c"],+ );+ // Without this the rest of a long history waits on an unrelated refresh.+ assert.equal(first.hasMore, true);++ const second = selectLegacyRepairPage(threads, new Set(["a", "c"]), 2);+ assert.deepEqual(+ second.candidates.map((t) => t.id),+ ["d"],+ );+ assert.equal(second.hasMore, false);++ const done = selectLegacyRepairPage(threads, new Set(["a", "c", "d"]), 2);+ assert.deepEqual(done.candidates, []);+ assert.equal(done.hasMore, false);+});++test("a thread the backend has nothing for still gets a local read", () => {+ // A not-yet-imported chat reads empty; an unknown id is missing from the map.+ const messages = new Map<string, MessageRecord[]>([+ ["a", [userMessage("a", LONG)]],+ ["b", []],+ ]);+ assert.deepEqual(threadsMissingMessages(["a", "b", "c"], messages), [+ "b",+ "c",+ ]);+});++++test("a chat with nothing stored is left for a later refresh", () => {+ // Its messages may not be imported yet, so a later pass rewrites the title.+ const legacy = LONG.slice(0, 48) + "...";+ const candidates = [thread("a", legacy)];+ const messages = new Map<string, MessageRecord[]>();++ assert.deepEqual(planLegacyTitleRepairs(candidates, messages), []);+ assert.deepEqual(threadsMissingMessages(["a"], messages), ["a"]);++ messages.set("a", [userMessage("a", LONG)]);+ assert.deepEqual(threadsMissingMessages(["a"], messages), []);+ assert.deepEqual(planLegacyTitleRepairs(candidates, messages), [+ { threadId: "a", previousTitle: legacy, openingMessageId: "a-m1", title: LONG },+ ]);+});++test("a chat whose opening prompt is gone is decided, not retried forever", () => {+ // A chat that does have messages is a complete answer: the opening prompt was+ // deleted or edited, so no later pass can prove the title. Unmarking it would+ // re-select it on every refresh, since its title stays clipped.+ const legacy = LONG.slice(0, 48) + "...";+ const candidates = [thread("a", legacy)];+ const messages = new Map<string, MessageRecord[]>([+ ["a", [{ ...userMessage("a", "a different question entirely"), id: "a-m9" }]],+ ]);++ assert.deepEqual(planLegacyTitleRepairs(candidates, messages), []);+ assert.deepEqual(threadsMissingMessages(["a"], messages), []);+ // So it stays marked, and the next page passes over it.+ assert.deepEqual(+ selectLegacyRepairPage(candidates, new Set(["a"]), 100).candidates,+ [],+ );+});++test("an emptied chat is decided, one still importing is not", () => {+ // Both read back as zero messages. The ledger tells them apart: one it knows+ // was imported is simply empty, one it has never seen may still be on its way.+ const ids = ["emptied", "importing", "fine"];+ const messages = new Map<string, MessageRecord[]>([+ ["emptied", []],+ ["importing", []],+ ["fine", [userMessage("fine", LONG)]],+ ]);++ assert.deepEqual(threadsMissingMessages(ids, messages), [+ "emptied",+ "importing",+ ]);+ assert.deepEqual(+ threadsAwaitingImport(ids, messages, new Set(["emptied"])),+ ["importing"],+ );+ // An unreadable ledger decides nothing, so both stay retryable.+ assert.deepEqual(threadsAwaitingImport(ids, messages, new Set()), [+ "emptied",+ "importing",+ ]);+});diff --git a/studio/frontend/tests/openapi-support.test.ts b/studio/frontend/tests/openapi-support.test.tsnew file mode 100644index 00000000000..60187315748--- /dev/null+++ b/studio/frontend/tests/openapi-support.test.ts@@ -0,0 +1,86 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ readGuardProbe,+ schemaDeclaresRepairGuards,+} from "../src/features/chat/utils/openapi-support.ts";++/** The shape FastAPI serves for the patch model. */+function documentWith(properties: Record<string, unknown>) {+ return {+ components: {+ schemas: {+ ChatThreadPatch: { title: "ChatThreadPatch", type: "object", properties },+ },+ },+ };+}++const OLD_PROPERTIES = {+ title: { type: "string" },+ modelType: { type: "string" },+ archived: { type: "boolean" },+};++const GUARDED = {+ ...OLD_PROPERTIES,+ expectedTitle: { type: "string" },+ expectedOpeningMessageId: { type: "string" },+};++test("a backend that declares the fields enforces the guards", () => {+ assert.equal(schemaDeclaresRepairGuards(documentWith(GUARDED)), true);+});++test("a backend from before the fields does not", () => {+ // It drops the unknown fields and writes anyway, so the migration stays off.+ assert.equal(schemaDeclaresRepairGuards(documentWith(OLD_PROPERTIES)), false);+});++test("half the guards is not enough", () => {+ // Only the pair rejects a repair based on a deleted prompt.+ assert.equal(+ schemaDeclaresRepairGuards(+ documentWith({ ...OLD_PROPERTIES, expectedTitle: { type: "string" } }),+ ),+ false,+ );+});++test("anything unreadable reads as unsupported", () => {+ for (const document of [+ null,+ undefined,+ "",+ 42,+ {},+ { components: null },+ { components: {} },+ { components: { schemas: {} } },+ { components: { schemas: { ChatThreadPatch: {} } } },+ { components: { schemas: { ChatThreadPatch: { properties: null } } } },+ ]) {+ assert.equal(schemaDeclaresRepairGuards(document), false);+ }+});++test("a schema that arrived settles the question either way", () => {+ const supported = readGuardProbe(true, documentWith(GUARDED));+ assert.deepEqual(supported, { supported: true, settled: true });++ // An old backend is a real answer, so it is worth remembering.+ assert.deepEqual(readGuardProbe(true, documentWith(OLD_PROPERTIES)), {+ supported: false,+ settled: true,+ });+});++test("an HTTP failure is a moment, not an answer", () => {+ // 401 while the token warms up, 503 at startup. Caching one would park the+ // migration for the session.+ assert.deepEqual(readGuardProbe(false, null), {+ supported: false,+ settled: false,+ });+});diff --git a/studio/frontend/tests/run-with-concurrency.test.ts b/studio/frontend/tests/run-with-concurrency.test.tsnew file mode 100644index 00000000000..4fa5fabed22--- /dev/null+++ b/studio/frontend/tests/run-with-concurrency.test.ts@@ -0,0 +1,50 @@+import assert from "node:assert/strict";+import test from "node:test";++import { runWithConcurrency } from "../src/features/chat/utils/run-with-concurrency.ts";++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}++test("never runs more than the limit at once", async () => {+ const gates = Array.from({ length: 10 }, deferred);+ let active = 0;+ let peak = 0;+ const started: number[] = [];++ const all = runWithConcurrency([...gates.keys()], 3, async (index) => {+ started.push(index);+ active += 1;+ peak = Math.max(peak, active);+ await gates[index].promise;+ active -= 1;+ });++ await Promise.resolve();+ assert.deepEqual(started, [0, 1, 2]);+ for (const gate of gates) gate.resolve();+ await all;+ assert.equal(peak, 3);+ assert.equal(started.length, 10);+});++test("a limit above the item count still runs every item once", async () => {+ const seen: number[] = [];+ await runWithConcurrency([1, 2, 3], 99, async (n) => {+ seen.push(n);+ });+ assert.deepEqual(seen.sort(), [1, 2, 3]);+});++test("an empty list resolves without running anything", async () => {+ let ran = false;+ await runWithConcurrency([], 4, async () => {+ ran = true;+ });+ assert.equal(ran, false);+});diff --git a/studio/frontend/tests/serial-queue.test.ts b/studio/frontend/tests/serial-queue.test.tsnew file mode 100644index 00000000000..44ffc9741bc--- /dev/null+++ b/studio/frontend/tests/serial-queue.test.ts@@ -0,0 +1,69 @@+import assert from "node:assert/strict";+import test from "node:test";++import { createSerialQueue } from "../src/features/chat/utils/serial-queue.ts";++function deferred() {+ let resolve!: () => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<void>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++test("a second caller waits rather than running alongside the first", async () => {+ // Two sidebars can be mounted at once; overlapping passes would make the+ // write concurrency cap per pass only.+ const run = createSerialQueue();+ const first = deferred();+ let active = 0;+ let peak = 0;++ const a = run(async () => {+ active += 1;+ peak = Math.max(peak, active);+ await first.promise;+ active -= 1;+ });+ const b = run(async () => {+ active += 1;+ peak = Math.max(peak, active);+ active -= 1;+ });++ await Promise.resolve();+ assert.equal(active, 1);+ first.resolve();+ await Promise.all([a, b]);+ assert.equal(peak, 1);+});++test("a rejected task does not block the next one", async () => {+ const run = createSerialQueue();+ let ran = false;+ const failed = run(async () => {+ throw new Error("read failed");+ });+ const after = run(async () => {+ ran = true;+ return 7;+ });+ await assert.rejects(failed, /read failed/);+ assert.equal(await after, 7);+ assert.equal(ran, true);+});++test("tasks run in the order they were queued", async () => {+ const run = createSerialQueue();+ const order: number[] = [];+ await Promise.all(+ [1, 2, 3].map((n) =>+ run(async () => {+ order.push(n);+ }),+ ),+ );+ assert.deepEqual(order, [1, 2, 3]);+});diff --git a/tests/studio/test_chat_thread_title_cas.py b/tests/studio/test_chat_thread_title_cas.pynew file mode 100644index 00000000000..3a4cda6f940--- /dev/null+++ b/tests/studio/test_chat_thread_title_cas.py@@ -0,0 +1,185 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""A title patch can carry guards, so a rename or a deleted opening message+beats a background rewrite.++studio_db imports its siblings by bare name (utils.paths), so the functional+checks run in a subprocess with studio/backend on PYTHONPATH rather than+putting those names on this session's sys.path.+"""++from __future__ import annotations++import json+import os+import subprocess+import sys+from pathlib import Path++import pytest+++REPO = Path(__file__).resolve().parents[2]+BACKEND = REPO / "studio" / "backend"+ROUTE = BACKEND / "routes" / "chat_history.py"++PROBE = r"""+import json, sys+from storage import studio_db as db++def message(thread_id, message_id, role, text, created_at):+ db.upsert_chat_message({+ "id": message_id,+ "threadId": thread_id,+ "role": role,+ "content": [{"type": "text", "text": text}],+ "createdAt": created_at,+ })++def thread(thread_id, title):+ db.upsert_chat_thread({+ "id": thread_id,+ "title": title,+ "modelType": "base",+ "createdAt": 1,+ "updatedAt": 1,+ })++out = {}++# No guard: the write lands, as every other caller expects.+thread("t1", "old")+out["unguarded"] = db.update_chat_thread("t1", {"title": "new"})["title"]++# Guard matches: the rewrite lands.+thread("t2", "legacy title...")+out["guard_match"] = db.update_chat_thread(+ "t2", {"title": "whole first line"}, expected_title = "legacy title..."+)["title"]++# A rename landed after the rewrite read the row: the rename has to win.+thread("t3", "legacy title...")+db.update_chat_thread("t3", {"title": "what the user typed"})+try:+ db.update_chat_thread(+ "t3", {"title": "whole first line"}, expected_title = "legacy title..."+ )+ out["guard_stale"] = "no error"+except db.ChatThreadPreconditionFailed:+ out["guard_stale"] = "mismatch"+out["after_stale"] = db.get_chat_thread("t3")["title"]++# The opening message guard, while that message is still the opening one.+thread("t4", "legacy title...")+message("t4", "m2", "user", "second", 20)+message("t4", "m1", "user", "first", 10)+message("t4", "a1", "assistant", "reply", 15)+out["opening_match"] = db.update_chat_thread(+ "t4",+ {"title": "whole first line"},+ expected_title = "legacy title...",+ expected_opening_message_id = "m1",+)["title"]++# The opening message was deleted after the rewrite read it. Its text must not+# be expanded into the title.+thread("t5", "legacy title...")+message("t5", "t5m1", "user", "first", 10)+message("t5", "t5m2", "user", "second", 20)+db.sync_chat_messages("t5", [+ {"id": "t5m2", "threadId": "t5", "role": "user",+ "content": [{"type": "text", "text": "second"}], "createdAt": 20},+], prune_missing = True)+try:+ db.update_chat_thread(+ "t5",+ {"title": "whole first line"},+ expected_title = "legacy title...",+ expected_opening_message_id = "t5m1",+ )+ out["opening_deleted"] = "no error"+except db.ChatThreadPreconditionFailed:+ out["opening_deleted"] = "mismatch"+out["after_opening_deleted"] = db.get_chat_thread("t5")["title"]++# A thread whose messages are all gone: the subquery is NULL, still no match.+thread("t6", "legacy title...")+try:+ db.update_chat_thread(+ "t6",+ {"title": "whole first line"},+ expected_opening_message_id = "t6m1",+ )+ out["opening_empty"] = "no error"+except db.ChatThreadPreconditionFailed:+ out["opening_empty"] = "mismatch"++# A thread that is gone reads as missing, not as a mismatch.+out["missing"] = db.update_chat_thread(+ "gone", {"title": "anything"}, expected_title = "legacy title..."+)++# updatedAt is untouched by a title patch, so Recents keeps its order.+out["updated_at"] = db.get_chat_thread("t2")["updatedAt"]++print(json.dumps(out))+"""++[email protected](scope = "module")+def probe(tmp_path_factory) -> dict:+ env = dict(os.environ)+ env["UNSLOTH_STUDIO_HOME"] = str(tmp_path_factory.mktemp("studio_home"))+ env["PYTHONPATH"] = str(BACKEND)+ result = subprocess.run(+ [sys.executable, "-c", PROBE],+ capture_output = True,+ text = True,+ env = env,+ )+ assert result.returncode == 0, result.stderr+ return json.loads(result.stdout.strip().splitlines()[-1])+++def test_a_patch_without_a_guard_still_applies(probe):+ assert probe["unguarded"] == "new"+++def test_the_guard_lets_the_write_through_while_the_title_is_unchanged(probe):+ assert probe["guard_match"] == "whole first line"+++def test_a_rename_between_the_read_and_the_write_wins(probe):+ assert probe["guard_stale"] == "mismatch"+ assert probe["after_stale"] == "what the user typed"+++def test_a_missing_thread_reads_as_missing_not_as_a_mismatch(probe):+ assert probe["missing"] is None+++def test_a_title_patch_leaves_updated_at_alone(probe):+ assert probe["updated_at"] == 1+++def test_the_opening_guard_matches_the_earliest_user_message(probe):+ """Earliest by createdAt, not by insertion order, and not the assistant's."""+ assert probe["opening_match"] == "whole first line"+++def test_a_prompt_deleted_between_the_read_and_the_write_wins(probe):+ assert probe["opening_deleted"] == "mismatch"+ assert probe["after_opening_deleted"] == "legacy title..."+++def test_a_thread_with_no_messages_left_reads_as_a_mismatch(probe):+ assert probe["opening_empty"] == "mismatch"+++def test_the_route_turns_a_failed_precondition_into_409():+ source = ROUTE.read_text(encoding = "utf-8")+ assert 'expected_title = patch.pop("expectedTitle", None)' in source+ assert 'expected_opening_message_id = patch.pop("expectedOpeningMessageId", None)' in source+ assert "except ChatThreadPreconditionFailed:" in source+ assert "status_code = 409," in sourcediff --git a/tests/studio/test_legacy_chat_title_repair.py b/tests/studio/test_legacy_chat_title_repair.pynew file mode 100644index 00000000000..c3c57fe3949--- /dev/null+++ b/tests/studio/test_legacy_chat_title_repair.py@@ -0,0 +1,145 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Wiring for the legacy chat title repair, where a unit test cannot reach.++The repair module pulls in the chat API, so these are source checks on the+seams: which map it reads from, and what keeps it going page to page.+"""++from __future__ import annotations++from pathlib import Path+++REPO = Path(__file__).resolve().parents[2]+FRONTEND = REPO / "studio/frontend/src/features/chat"+BACKEND = REPO / "studio/backend"+REPAIR = FRONTEND / "utils/repair-legacy-chat-titles.ts"+HOOK = FRONTEND / "hooks/use-chat-sidebar-items.ts"+STORAGE = FRONTEND / "utils/chat-history-storage.ts"+++def _read(path: Path) -> str:+ return " ".join(path.read_text(encoding = "utf-8").split())+++def test_the_repair_reads_its_own_messages_as_late_as_it_can():+ """Not the sidebar's map. That map takes its empty-backend entries from+ listStoredChatMessages, which merges Dexie rows the backend has pruned, and+ it is fetched at load time rather than at write time."""+ hook = _read(HOOK)+ assert "void repairLegacyChatTitles(threads).catch(() => undefined);" in hook++ repair = _read(REPAIR)+ assert "messages = await batchListChatMessages(ids);" in repair+ assert (+ "export function repairLegacyChatTitles( threads: ThreadRecord[], ): Promise<number> {"+ in repair+ )++ storage = _read(STORAGE)+ # Nothing hands a message map out of the shared list function.+ assert "messagesByThreadId" not in storage+++def test_the_repair_reads_only_stored_messages():+ """Dexie keeps rows the backend has pruned, because deleting a message never+ clears them. Reading it here could put a deleted prompt back into a title,+ so a chat whose messages are not stored yet is left for a later refresh+ instead."""+ repair = _read(REPAIR)+ assert "listUnimportedChatMessages" not in repair+ assert "mergeMessagesById" not in repair+ assert "db.messages" not in repair+++def test_an_emptied_chat_is_not_retried_for_the_session():+ """A chat the user deleted every message from reads back the same as one+ still importing. Retrying it would re-read it on every refresh, since its+ title stays clipped and keeps matching the pre-filter."""+ repair = _read(REPAIR)+ assert "const withoutMessages = threadsMissingMessages(ids, messages);" in repair+ # Only fetched when there is something to decide.+ assert "if (withoutMessages.length > 0) {" in repair+ assert "imported = await listChatImportLedger();" in repair+ assert (+ "for (const id of threadsAwaitingImport(ids, messages, imported)) { attempted.delete(id); }"+ in repair+ )+++def test_the_repair_never_creates_anything():+ """updateStoredChatThread ensures the thread first, which re-imports one+ deleted on another client from the Dexie rows still sitting here. A+ migration patching a row that is gone has to 404, not resurrect it."""+ repair = _read(REPAIR)+ # The storage layer is out of the picture entirely, not just at this call.+ assert 'from "./chat-history-storage"' not in repair+ assert "await updateChatThread( repair.threadId, { title: repair.title }," in repair+++def test_the_next_page_is_scheduled_rather_than_waited_for():+ """A page that writes nothing fires no history update, so nothing else+ would come back for the rest of the backlog."""+ repair = _read(REPAIR)+ assert "if (hasMore) { setTimeout(" in repair+ # On `rest`: a row this page unmarked must not starve the rows behind it.+ assert "void repairLegacyChatTitles(rest)" in repair+ assert "REPAIR_PAGE_PAUSE_MS" in repair+++def test_only_one_repair_pass_runs_at_a_time():+ """Several sidebars can be mounted at once, so the write concurrency cap+ only holds if their passes queue."""+ repair = _read(REPAIR)+ assert "const serial = createSerialQueue();" in repair+ assert "return serial(() => runRepairPass(threads));" in repair+++def test_a_rename_is_left_to_the_backend_guard():+ """The pass only runs where the guard is enforced, so re-listing the whole+ history per page to check titles client side was both redundant and+ quadratic: every page of 100 pulled every thread the account has."""+ repair = _read(REPAIR)+ assert "listChatThreads" not in repair+ assert "repairsStillValid" not in repair+ assert "await runWithConcurrency(repairs, REPAIR_CONCURRENCY," in repair+ assert "expectedTitle: repair.previousTitle," in repair+++def test_the_write_is_guarded_on_the_message_it_took_the_title_from():+ """Deleting the opening prompt does not change the title, so expectedTitle+ alone still matches and would expand the deleted text."""+ repair = _read(REPAIR)+ assert "expectedOpeningMessageId: repair.openingMessageId," in repair++ backend = (BACKEND / "routes/chat_history.py").read_text(encoding = "utf-8")+ assert "expectedOpeningMessageId: Optional[str] = None" in backend+++def test_the_migration_stays_off_where_the_guard_is_not_enforced():+ """A backend from before expectedTitle drops it and writes anyway. Sending+ one to find out is the destructive act itself, so the served schema is what+ answers, and anything unreadable counts as unsupported."""+ repair = _read(REPAIR)+ assert "if (!(await backendEnforcesTitleGuard())) return 0;" in repair+ assert 'const response = await authFetch("/openapi.json");' in repair+ assert (+ "probe = 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.+ assert "if (!probe.settled) guardSupport = null;" in repair++ backend = (BACKEND / "routes/chat_history.py").read_text(encoding = "utf-8")+ # The probe reads the schema, so the fields have to be declared on the model.+ assert "expectedTitle: Optional[str] = None" in backend+++def test_a_failed_read_leaves_the_rows_retryable():+ repair = _read(REPAIR)+ assert (+ "} catch { // Nothing was decided, so let a later refresh try these again. for (const id of ids) attempted.delete(id); return 0; }"+ in repair+ )