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: Regenerate title only in the Library's chat menu (#13491)
Michael Han9aab77b0eacb
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 8d51c3a3543..fe6157140fc 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -285,6 +285,8 @@ 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+ # Title regeneration must not move an old conversation up in Last modified.+ preserveTitleModifiedAt: bool = False# 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"]] = None@@ -716,6 +718,7 @@ def patch_thread():patch = payload.model_dump(exclude_unset = True)expected_title = patch.pop("expectedTitle", None)+ preserve_title_modified_at = patch.pop("preserveTitleModifiedAt", False)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:@@ -728,6 +731,7 @@ def patch_thread(thread_id,patch,expected_title = expected_title,+ preserve_title_modified_at = preserve_title_modified_at,expected_opening_message_id = expected_opening_message_id,settings_write = settings_write,)diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 1ea9f725312..c854f91048d 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -2247,6 +2247,7 @@ def update_chat_thread(expected_title: Optional[str] = None,expected_opening_message_id: Optional[str] = None,settings_write: Optional[dict] = None,+ preserve_title_modified_at: bool = False,) -> 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@@ -2298,11 +2299,14 @@ def update_chat_thread("fork_title_base = CASE WHEN title = ? THEN fork_title_base ELSE NULL END")values.append(patch.get("title"))- # Stamp real renames, moves and (un)archives. The CASE reads the pre-update row.+ # Generated title refreshes preserve recency. Moves and (un)archives still stamp it.+ # The CASE reads the pre-update row.edited = [(column, value)for key, (column, value) in allowed.items()- if key in patch and key in ("title", "projectId", "archived")+ if key in patch+ and key in ("title", "projectId", "archived")+ and not (key == "title" and preserve_title_modified_at)]if edited:changed = " OR ".join(f"{column} IS NOT ?" for column, _ in edited)diff --git a/studio/backend/tests/test_chat_thread_settings.py b/studio/backend/tests/test_chat_thread_settings.pyindex cb05c8bd4b7..c4f0ac72e8b 100644--- a/studio/backend/tests/test_chat_thread_settings.py+++ b/studio/backend/tests/test_chat_thread_settings.py@@ -730,3 +730,96 @@ def test_the_response_says_absent_for_a_key_the_snapshot_never_held(stored, expewith TestClient(app) as client:assert client.get("/thread").json()["settings"] == expected++[email protected]("modified_at", [None, 1_700_000_000_100])[email protected]("comparison", [False, True])+def test_regenerate_title_preserves_each_threads_recency(+ tmp_path, monkeypatch, modified_at, comparison+):+ from routes.chat_history import patch_thread++ _reset_studio_db(tmp_path, monkeypatch)+ ids = ["left", "right"] if comparison else ["single"]+ for index, thread_id in enumerate(ids):+ studio_db.upsert_chat_thread(+ _thread(+ thread_id,+ title = f"Old title {index}",+ pairId = "pair" if comparison else None,+ updatedAt = 1_700_000_001_000 + index,+ )+ )+ with sqlite3.connect(studio_db_path()) as conn:+ conn.execute(+ "UPDATE chat_threads SET modified_at = ? WHERE id = ?", (modified_at, thread_id)+ )+ before = studio_db.get_chat_thread(thread_id)+ saved = patch_thread(+ thread_id,+ ChatThreadPatch(+ title = "Generated title",+ expectedTitle = before["title"],+ preserveTitleModifiedAt = True,+ ),+ current_subject = "test",+ )+ assert saved.title == "Generated title"+ after = studio_db.get_chat_thread(thread_id)+ for field in ("createdAt", "updatedAt", "modifiedAt"):+ assert after[field] == before[field]+++def test_regenerated_title_keeps_new_activity_and_manual_rename_guard(tmp_path, monkeypatch):+ from fastapi import HTTPException+ from routes.chat_history import patch_thread++ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread(updatedAt = 1_700_000_001_000))+ # New activity lands while generation is pending. Never restore a timestamp from the client.+ studio_db.update_chat_thread("thread-1", {"updatedAt": 1_700_000_002_000})+ patch_thread(+ "thread-1",+ ChatThreadPatch(+ title = "Generated title",+ expectedTitle = "Test Chat",+ preserveTitleModifiedAt = True,+ ),+ current_subject = "test",+ )+ assert studio_db.get_chat_thread("thread-1")["updatedAt"] == 1_700_000_002_000++ patch_thread("thread-1", ChatThreadPatch(title = "Manual rename"), current_subject = "test")+ before = studio_db.get_chat_thread("thread-1")+ assert before["modifiedAt"] is not None+ with pytest.raises(HTTPException) as error:+ patch_thread(+ "thread-1",+ ChatThreadPatch(+ title = "Stale generated title",+ expectedTitle = "Generated title",+ preserveTitleModifiedAt = True,+ ),+ current_subject = "test",+ )+ assert error.value.status_code == 409+ assert studio_db.get_chat_thread("thread-1") == before+++def test_preserving_title_recency_does_not_suppress_other_edits(tmp_path, monkeypatch):+ from routes.chat_history import patch_thread++ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ patch_thread(+ "thread-1",+ ChatThreadPatch(+ title = "Generated title",+ archived = True,+ preserveTitleModifiedAt = True,+ ),+ current_subject = "test",+ )+ saved = studio_db.get_chat_thread("thread-1")+ assert saved["archived"] is True+ assert saved["modifiedAt"] is not Nonediff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex b7224df1e93..f218ad8ef34 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -1109,6 +1109,8 @@ export async function saveChatThread(export interface UpdateChatThreadOptions {/** Apply only while the row still holds this title, else 409. */expectedTitle?: string;+ /** Regenerate a title without changing conversation recency. */+ preserveTitleModifiedAt?: boolean;/** And only while this is still the thread's opening user message. */expectedOpeningMessageId?: string;/** Off for one update inside a bulk action, which announces itself once at the end. Every notification is a@@ -1137,6 +1139,9 @@ export async function updateChatThread(if (options.expectedTitle !== undefined) {body.expectedTitle = options.expectedTitle;}+ if (options.preserveTitleModifiedAt !== undefined) {+ body.preserveTitleModifiedAt = options.preserveTitleModifiedAt;+ }if (options.expectedOpeningMessageId !== undefined) {body.expectedOpeningMessageId = options.expectedOpeningMessageId;}diff --git a/studio/frontend/src/features/chat/components/chat-row-menu.ts b/studio/frontend/src/features/chat/components/chat-row-menu.tsindex d8f579dafdb..1f8f147add9 100644--- a/studio/frontend/src/features/chat/components/chat-row-menu.ts+++ b/studio/frontend/src/features/chat/components/chat-row-menu.ts@@ -13,8 +13,19 @@ import {} from "../utils/conversation-markdown";import { allRecordedSandboxSessionIds } from "../utils/recorded-sandbox-session";import { liveThreadBranch } from "../utils/live-thread-head";-import { forkChatThread } from "../api/chat-api";-import { settleThreadScopedSettingsForCopy } from "../stores/chat-runtime-store";+import {+ forkChatThread,+ getInferenceStatus,+ streamChatCompletions,+ updateChatThread,+} from "../api/chat-api";+import { parseExternalModelId } from "../external-providers";+import { disposableTimeoutSignal } from "../../hub/lib/abort-signals";+import { normalizeModelIdentity } from "../../hub/lib/model-identity";+import {+ settleThreadScopedSettingsForCopy,+ useChatRuntimeStore,+} from "../stores/chat-runtime-store";import type { SidebarItem } from "../hooks/use-chat-sidebar-items";import {exportConversationCsv,@@ -23,7 +34,21 @@ import {exportConversationRawJsonl,exportConversationShareGPT,} from "../prompt-storage/prompt-storage-dialog";-import { listStoredChatMessages } from "../utils/chat-history-storage";+import {+ getStoredChatThread,+ listStoredChatMessages,+ listStoredChatThreads,+} from "../utils/chat-history-storage";+import { savedBranchHead } from "../utils/branch-head";+import { orderByParentChain } from "../utils/message-order";+import {+ answeringCheckpoint,+ buildTitleRefreshRequest,+ heuristicChatTitle,+ titleCheckpoint,+ titleFromStream,+ titleRefreshExcerpt,+} from "../utils/chat-title";export type ConversationExportFormat =| "raw-jsonl"@@ -110,6 +135,144 @@ function forkRefused(): Error {);}+export type RegenerateTitleOutcome =+ | "renamed"+ | "unchanged"+ | "empty"+ | "busy"+ | "failed";++const regeneratingTitles = new Set<string>();+const TITLE_MODEL_WAIT_MS = 15_000;+const TITLE_STATUS_WAIT_MS = 5_000;+const TITLE_REGENERATE_DEADLINE_MS = 30_000;++async function titleFromModel(checkpoint: string, excerpt: string): Promise<string | null> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), TITLE_MODEL_WAIT_MS);+ // Covers building the request too: a stored provider key is encrypted through the backend.+ const timedOut = new Promise<never>((_, reject) => {+ controller.signal.addEventListener("abort", () => reject(new Error("title request timed out")), { once: true });+ });+ timedOut.catch(() => undefined);+ try {+ const request = await Promise.race([buildTitleRefreshRequest(checkpoint, excerpt), timedOut]);+ if (!request) return null;+ return await Promise.race([titleFromStream(streamChatCompletions(request, controller.signal)), timedOut]);+ } catch {+ return null;+ } finally {+ clearTimeout(timer);+ }+}++/** Only while serving: naming an idle-unloaded local model makes the backend reload it. */+async function titleModelServing(checkpoint: string): Promise<boolean> {+ if (parseExternalModelId(checkpoint) !== null) return true;+ // The helper, not AbortSignal.timeout: WebKitGTK before 2.38 has none.+ const wait = disposableTimeoutSignal(TITLE_STATUS_WAIT_MS);+ try {+ // Raced, not only signalled: a 401 first awaits a token refresh that takes no signal.+ const timedOut = new Promise<never>((_, reject) => {+ wait.signal.addEventListener("abort", () => reject(new Error("status check timed out")), { once: true });+ });+ timedOut.catch(() => undefined);+ const status = await Promise.race([getInferenceStatus(wait.signal, checkpoint), timedOut]);+ if (!status.active_model || status.is_audio || status.is_diffusion) return false;+ const want = normalizeModelIdentity(checkpoint);+ return [status.model_identifier, status.active_model, ...(status.serving_checkpoints ?? [])].some(+ (id) => !!id && (id === checkpoint || normalizeModelIdentity(id) === want),+ );+ } catch {+ return false;+ } finally {+ wait.dispose();+ }+}++/** Asks the connection that answered (a local model only while serving), so messages never reach a+ * provider they were not sent to; else picks from the messages. */+export async function regenerateChatTitle(+ item: SidebarItem,+): Promise<RegenerateTitleOutcome> {+ if (regeneratingTitles.has(item.id)) return "busy";+ regeneratingTitles.add(item.id);+ // One deadline over every step, so a stall anywhere releases the busy mark and the toast.+ // Past the deadline the run may still finish, so it must not write: a retry may already own the chat.+ const run = { expired: false };+ let timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = new Promise<RegenerateTitleOutcome>((resolve) => {+ timer = setTimeout(() => {+ run.expired = true;+ resolve("failed");+ }, TITLE_REGENERATE_DEADLINE_MS);+ });+ try {+ return await Promise.race([regenerateChatTitleNow(item, run), deadline]);+ } finally {+ clearTimeout(timer);+ regeneratingTitles.delete(item.id);+ }+}++async function regenerateChatTitleNow(+ item: SidebarItem,+ run: { expired: boolean },+): Promise<RegenerateTitleOutcome> {+ try {+ const threadId = getSidebarItemThreadIds(item)[0];+ const liveBranch = liveThreadBranch(threadId);+ const { params, modelLoading } = useChatRuntimeStore.getState();+ const selected = !modelLoading ? params.checkpoint : "";+ // Panes can differ (a restored backup keeps each title), so each is guarded with its own.+ const [startTitle, raw, panes] = await Promise.all([+ getStoredChatThread(threadId).then((thread) => thread?.title),+ listStoredChatMessages(threadId),+ item.type === "single"+ ? Promise.resolve(null)+ : listStoredChatThreads({ pairId: item.id, includeArchived: true }),+ ]);+ // The branch on screen, else the one reopening the chat shows, as the exports read it.+ const storedIds = new Set(raw.map((m) => m.id));+ const headId = liveBranch?.length+ ? ([...liveBranch].reverse().find((id) => storedIds.has(id)) ?? null)+ : savedBranchHead(threadId, raw);+ const branch = raw.some((m) => m.parentId != null)+ ? orderByParentChain(raw, { includeSiblings: false, headId })+ : raw;+ const excerpt = titleRefreshExcerpt(branch);+ if (!excerpt) return "empty";+ // Only a stamped final answer names a recipient: never fall back to an older answer's provider,+ // which never saw the later turns.+ const lastMessage = branch.at(-1);+ const answeredWith =+ lastMessage?.role === "assistant" ? answeringCheckpoint(lastMessage.metadata?.custom) : "";+ const checkpoint = titleCheckpoint(answeredWith, selected);+ const serving = checkpoint ? await titleModelServing(checkpoint) : false;+ const title =+ (serving ? await titleFromModel(checkpoint, excerpt) : null) ?? heuristicChatTitle(branch);+ if (!title) return "empty";+ if (panes ? panes.every((pane) => pane.title === title) : title === startTitle) return "unchanged";+ if (run.expired) return "failed";+ const targets = panes+ ? [...new Map(panes.map((pane) => [pane.id, pane.title])).entries()]+ : [[threadId, startTitle] as const];+ try {+ // Guarded: a rename that lands while the title is generated wins (409).+ await Promise.all(+ targets.map(([id, before]) =>+ updateChatThread(id, { title }, { expectedTitle: before, preserveTitleModifiedAt: true }),+ ),+ );+ } catch {+ return (await getStoredChatThread(threadId))?.title !== startTitle ? "unchanged" : "failed";+ }+ return "renamed";+ } catch {+ return "failed";+ }+}+/** The sandbox sessions this chat's stored tool results name, if any. */export async function recordedSandboxSessionIds(ids: string[],diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex f180e015370..be40afa8e24 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -356,6 +356,7 @@ export {forkChatRow,getSidebarItemThreadIds,recordedSandboxSessionIds,+ regenerateChatTitle,sandboxSessionIdsHolding,type ConversationExportFormat,} from "./components/chat-row-menu";diff --git a/studio/frontend/src/features/chat/utils/chat-title.ts b/studio/frontend/src/features/chat/utils/chat-title.tsindex c6747e9b59d..cbe81e7a713 100644--- a/studio/frontend/src/features/chat/utils/chat-title.ts+++ b/studio/frontend/src/features/chat/utils/chat-title.ts@@ -31,6 +31,7 @@ import type {OpenAIChatCompletionsRequest,} from "../types/api";import { extractDeltaText } from "./parse-assistant-content";+import { attachmentsSample } from "./pasted-text";/** 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. */@@ -382,9 +383,131 @@ function titleMaxTokens(connection: ResolvedExternalConnection): number {const TITLE_SYSTEM_PROMPT ="Write 1 concise chat title summarizing the conversation topic, not the user's exact wording. Use the assistant reply as context when provided. Rules: 2-6 words, no quotes, no punctuation, ASCII only, do not echo input. Output title only.";+const TITLE_REFRESH_SYSTEM_PROMPT =+ "Write 1 concise chat title for what this conversation is about now. The excerpt holds its latest messages, oldest first; weight the newest most. Rules: 2-6 words, no quotes, no punctuation, ASCII only, do not echo input. Output title only.";++// About 250 tokens however long the chat: the last 2-3 turns, Open WebUI's {{MESSAGES:END:2}} window.+const REFRESH_MESSAGE_CHARS = 300;+const REFRESH_EXCERPT_CHARS = 900;+const REFRESH_MIN_CHARS = 40;++function textPartsOf(message: MessageRecord): string {+ const { content } = message;+ const text =+ typeof content === "string"+ ? content+ : Array.isArray(content)+ ? content.map((part) => (part?.type === "text" ? part.text : "")).join("")+ : "";+ if (message.role !== "user") return text;+ // A long paste is stored as an attachment, so a paste-only turn has no inline text.+ const pasted = attachmentsSample(message.attachments);+ return pasted ? `${text}\n\n${pasted}` : text;+}++/** The newest user and assistant turns that fit the budget, oldest first; text parts only. */+export function titleRefreshExcerpt(messages: readonly MessageRecord[]): string {+ const lines: string[] = [];+ let used = 0;+ for (let i = messages.length - 1; i >= 0; i--) {+ const message = messages[i];+ if (message.role !== "user" && message.role !== "assistant") continue;+ const text = dropLoneSurrogates(textPartsOf(message))+ .replace(/\s+/g, " ")+ .trim();+ if (!text) continue;+ const label = message.role === "user" ? "User: " : "Assistant: ";+ const room = Math.min(REFRESH_MESSAGE_CHARS, REFRESH_EXCERPT_CHARS - used - label.length);+ // A stub of a few words says less than leaving the turn out.+ if (room < REFRESH_MIN_CHARS) break;+ const line = label + cutToUnits(text, room).trimEnd();+ lines.push(line);+ used += line.length + 1;+ }+ return lines.reverse().join("\n");+}++// A title phrase never starts or ends on one of these (English plus common es/fr/de/pt).+const TITLE_STOPWORDS = new Set(+ (+ "a an the and or but if then so of in on at to for from by with about into over after before under between through during without within " ++ "is are was were be been being am do does did done have has had having i me my mine we us our you your yours he him his she her it its they them their " ++ "this that these those there here what which who whom whose when where why how can could would should will shall may might must not no yes ok okay " ++ "thanks thank please hi hello hey sure great cool nice just also actually really very quite now still again more most less some any all each every " ++ "both either neither other another such same own only than too want wants wanted need needs like help tell give show make let get got know think see " ++ "use using write explain describe work works one two lot lots thing things something anything everything way ways kind sort bit time today " ++ "de la el los las y en que un una le les des et du der die das und ist zu mit para por com um uma une como cómo puedo puede qué cuál con sin mi tu su " ++ "es son hay sobre del al lo se te nos est pour avec sur dans comment wie was ich kann ein eine für auf posso não mais os em na"+ ).split(" "),+);+// \p{M} inside a word: Devanagari vowel signs and Arabic harakat are marks, not word breaks.+const TITLE_WORD = /[\p{L}\p{N}][\p{L}\p{M}\p{N}'’_-]*/gu;+const TITLE_MAX_WORDS = 6;++function isTitleWord(word: string): boolean {+ return word.length >= 3 && !TITLE_STOPWORDS.has(word.toLowerCase()) && !/^\d+$/.test(word);+}++/** Title without a model: the newest real user message's phrase the latest turns keep repeating. Open WebUI+ * uses the first message instead, the topic a drifted chat has left. */+export function heuristicChatTitle(messages: readonly MessageRecord[]): string | null {+ const turns = messages+ .filter((m) => m.role === "user" || m.role === "assistant")+ .map((m) => ({ role: m.role, text: dropLoneSurrogates(textPartsOf(m)) }))+ .filter((m) => m.text.trim());+ const weight = new Map<string, number>();+ const count = (text: string, value: number) => {+ for (const word of text.match(TITLE_WORD) ?? []) {+ if (!isTitleWord(word)) continue;+ const name = /[A-Z]/.test(word) ? 1.5 : 1;+ const key = word.toLowerCase();+ weight.set(key, (weight.get(key) ?? 0) + value * name);+ }+ };+ turns.slice(-6).reverse().forEach((turn, age) => {+ const recency = 1 / (1 + age * 0.3);+ count(turn.text, (turn.role === "user" ? 2 : 1) * recency);+ if (turn.role === "assistant") {+ for (const emphasis of turn.text.match(/^#{1,6}\s+.*$|\*\*[^*]+\*\*/gm) ?? []) {+ count(emphasis, recency);+ }+ }+ });+ const users = turns.filter((t) => t.role === "user").reverse();+ const anchor =+ users.find((t) => (t.text.match(TITLE_WORD) ?? []).filter(isTitleWord).length >= 2) ?? users[0];+ if (!anchor) return null;+ let best: { score: number; words: string[] } | null = null;+ for (const clause of anchor.text.split(/[.?!;:,\n()"“”]+/)) {+ const words = clause.match(TITLE_WORD) ?? [];+ for (let i = 0; i < words.length; i++) {+ if (!isTitleWord(words[i])) continue;+ for (let j = i; j < Math.min(words.length, i + TITLE_MAX_WORDS); j++) {+ if (!isTitleWord(words[j])) continue;+ const span = words.slice(i, j + 1);+ const sum = span.reduce((total, w) => total + (weight.get(w.toLowerCase()) ?? 0), 0);+ // Longer phrases read better but must earn it; one word is a last resort.+ const score = (sum / span.length ** 0.35) * (span.length === 1 ? 0.6 : 1);+ if (!best || score > best.score) best = { score, words: span };+ }+ }+ }+ if (!best) return fallbackTitleFromUserText(anchor.text);+ const title = best.words.join(" ");+ return fallbackTitleFromUserText(title.charAt(0).toUpperCase() + title.slice(1));+}++export function buildTitleRefreshRequest(+ checkpoint: string,+ excerpt: string,+): Promise<OpenAIChatCompletionsRequest | null> {+ return buildTitleRequest(checkpoint, excerpt, TITLE_REFRESH_SYSTEM_PROMPT);+}+export async function buildTitleRequest(checkpoint: string,prompt: string,+ systemPrompt: string = TITLE_SYSTEM_PROMPT,): Promise<OpenAIChatCompletionsRequest | null> {const routing = resolveExternalRouting(checkpoint);if (routing.kind === "unavailable") return null;@@ -416,7 +539,7 @@ export async function buildTitleRequest(// Else the server's tools-on default adds tool schemas.enable_tools: false,messages: [- { role: "system", content: TITLE_SYSTEM_PROMPT },+ { role: "system", content: systemPrompt },{ role: "user", content: prompt },],...(routing.kind === "external"diff --git a/studio/frontend/src/features/library/chats/chats-items.tsx b/studio/frontend/src/features/library/chats/chats-items.tsxindex c33e79cec82..6791b62ec5b 100644--- a/studio/frontend/src/features/library/chats/chats-items.tsx+++ b/studio/frontend/src/features/library/chats/chats-items.tsx@@ -53,6 +53,7 @@ import {PinIcon,PinOffIcon,PlusSignIcon,+ Refresh01Icon,Settings02Icon,Upload01Icon,ViewIcon,@@ -139,6 +140,7 @@ export interface ChatsActions {toggleSelected: (id: string, range?: boolean) => void;open: (chat: SidebarItem) => void;rename: (chat: SidebarItem) => void;+ regenerateTitle: (chat: SidebarItem) => void;togglePin: (chat: SidebarItem) => void;setFavorite: (chats: SidebarItem[], favorite: boolean) => void;toggleFavoriteProject: (projectId: string) => void;@@ -345,6 +347,23 @@ export function MoveSubmenu({);}+/** Off while any of its threads generates; a comparison's id is its pair's. */+function RegenerateTitleItem({ chat }: { chat: SidebarItem }) {+ const t = useT();+ const actions = useChatsActions();+ const generating = useChatRuntimeStore((s) =>+ (chat.threadIds?.length ? chat.threadIds : [chat.id]).some((id) => Boolean(s.runningByThreadId[id])),+ );+ return (+ <MenuItem+ icon={Refresh01Icon}+ label={t("library.menu.regenerateTitle")}+ disabled={generating}+ onSelect={() => actions.regenerateTitle(chat)}+ />+ );+}+/** Off while generating or forking, as in the sidebar. Mounts only when the menu opens. */function ForkItem({ chat }: { chat: SidebarItem }) {const t = useT();@@ -472,6 +491,7 @@ function ChatMenu({label={t("common.rename")}onSelect={() => actions.rename(chat)}/>+ <RegenerateTitleItem chat={chat} />{!archived && (<><MenuItemdiff --git a/studio/frontend/src/features/library/chats/chats-library.tsx b/studio/frontend/src/features/library/chats/chats-library.tsxindex f0bfba96c03..4bad84afdf5 100644--- a/studio/frontend/src/features/library/chats/chats-library.tsx+++ b/studio/frontend/src/features/library/chats/chats-library.tsx@@ -38,6 +38,7 @@ import {normalizeSectionName,notifyChatHistoryUpdated,rangeBetween,+ regenerateChatTitle,removeCustomSectionWithUndo,renameChatItem,showForkCreatedToast,@@ -205,6 +206,23 @@ const SECTION_SORTS: SortChoice<SectionSortKey>[] = [const NO_CHATS: SidebarItem[] = [];+async function regenerateChatTitleWithToast(chat: SidebarItem): Promise<void> {+ // A fast refresh would only flash the toast.+ const toastId = `regenerate-title-${chat.id}`;+ const slow = setTimeout(() => toast.loading("Regenerating title...", { id: toastId }), 400);+ const outcome = await regenerateChatTitle(chat);+ clearTimeout(slow);+ // Another request for this chat is running and owns the toast.+ if (outcome === "busy") return;+ if (outcome === "empty") {+ toast.error("This chat has no messages to title yet.", { id: toastId });+ } else if (outcome === "failed") {+ toast.error("Could not regenerate the title.", { id: toastId });+ } else {+ toast.dismiss(toastId);+ }+}+function isDateField(key: string): key is DateField {return (DATE_FIELDS as readonly string[]).includes(key);}@@ -890,6 +908,7 @@ export function ChatsLibrary({},open: openChat,rename: setRenaming,+ regenerateTitle: (chat) => void regenerateChatTitleWithToast(chat),togglePin: (chat) => togglePinned(chat.id),setFavorite: (chats, favorite) => {setFavoriteChats(diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 812665c6bc7..98b983f283a 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -4089,6 +4089,7 @@ export const ar = {chatAboutThis: "الدردشة حول هذا",chatWithModel: "الدردشة مع هذا النموذج",addToFavorites: "إضافة إلى المفضلة",+ regenerateTitle: "إعادة إنشاء العنوان",removeFromFavorites: "إزالة من المفضلة",download: "تنزيل",addToFolder: "إضافة إلى مجلد",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex b06351ca6d6..f3c1db418b9 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -4161,6 +4161,7 @@ export const de = {chatAboutThis: "Darüber chatten",chatWithModel: "Mit diesem Modell chatten",addToFavorites: "Zu Favoriten hinzufügen",+ regenerateTitle: "Titel neu generieren",removeFromFavorites: "Aus Favoriten entfernen",download: "Herunterladen",addToFolder: "Zu Ordner hinzufügen",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 87c45a22e6c..d012ecc5268 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -4120,6 +4120,7 @@ export const en = {chatAboutThis: "Chat about this",chatWithModel: "Chat with this model",addToFavorites: "Add to Favorites",+ regenerateTitle: "Regenerate title",removeFromFavorites: "Remove from Favorites",download: "Download",addToFolder: "Add to folder",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex b55428c5628..96e35b0fcaa 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -4160,6 +4160,7 @@ export const es = {chatAboutThis: "Chatear sobre esto",chatWithModel: "Chatear con este modelo",addToFavorites: "Añadir a Favoritos",+ regenerateTitle: "Regenerar título",removeFromFavorites: "Quitar de Favoritos",download: "Descargar",addToFolder: "Añadir a carpeta",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 53a1628ee4b..407e7dfe7f5 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -4172,6 +4172,7 @@ export const fr = {chatAboutThis: "Discuter de ce fichier",chatWithModel: "Discuter avec ce modèle",addToFavorites: "Ajouter aux favoris",+ regenerateTitle: "Régénérer le titre",removeFromFavorites: "Retirer des favoris",download: "Télécharger",addToFolder: "Ajouter à un dossier",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 03b821c7e37..8a6d0e2d57c 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -4202,6 +4202,7 @@ export const he = {chatAboutThis: "שוחח על זה",chatWithModel: "שוחח עם מודל זה",addToFavorites: "הוסף למועדפים",+ regenerateTitle: "יצירת כותרת מחדש",removeFromFavorites: "הסר מהמועדפים",download: "הורדה",addToFolder: "הוסף לתיקייה",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 7cc49625172..db6129301ad 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -4097,6 +4097,7 @@ export const hi = {chatAboutThis: "इसके बारे में चैट करें",chatWithModel: "इस मॉडल से चैट करें",addToFavorites: "पसंदीदा में जोड़ें",+ regenerateTitle: "शीर्षक फिर से बनाएं",removeFromFavorites: "पसंदीदा से हटाएँ",download: "डाउनलोड करें",addToFolder: "फ़ोल्डर में जोड़ें",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex dd2931781a9..5dcd44e64c5 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -4162,6 +4162,7 @@ export const it = {chatAboutThis: "Chatta su questo",chatWithModel: "Chatta con questo modello",addToFavorites: "Aggiungi ai preferiti",+ regenerateTitle: "Rigenera titolo",removeFromFavorites: "Rimuovi dai preferiti",download: "Scarica",addToFolder: "Aggiungi a cartella",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 9c1f77c4fe3..dcd507219cf 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -4037,6 +4037,7 @@ export const ja = {chatAboutThis: "これについてチャット",chatWithModel: "このモデルとチャット",addToFavorites: "お気に入りに追加",+ regenerateTitle: "タイトルを再生成",removeFromFavorites: "お気に入りから削除",download: "ダウンロード",addToFolder: "フォルダに追加",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 0c1afbc9cee..4b08c986238 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -4080,6 +4080,7 @@ export const ko = {chatAboutThis: "이 파일로 채팅",chatWithModel: "이 모델과 채팅",addToFavorites: "즐겨찾기에 추가",+ regenerateTitle: "제목 다시 생성",removeFromFavorites: "즐겨찾기에서 제거",download: "다운로드",addToFolder: "폴더에 추가",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex c418dc06541..fcf1304b521 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -4120,6 +4120,7 @@ export const ptBR = {chatAboutThis: "Conversar sobre isto",chatWithModel: "Conversar com este modelo",addToFavorites: "Adicionar aos Favoritos",+ regenerateTitle: "Regenerar título",removeFromFavorites: "Remover dos Favoritos",download: "Baixar",addToFolder: "Adicionar à pasta",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 449355e6fd3..9c821f40a43 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -4116,6 +4116,7 @@ export const ru = {chatAboutThis: "Обсудить в чате",chatWithModel: "Чат с этой моделью",addToFavorites: "Добавить в избранное",+ regenerateTitle: "Создать название заново",removeFromFavorites: "Удалить из избранного",download: "Скачать",addToFolder: "Добавить в папку",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 1c7e899e104..697bf34cec2 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -4342,6 +4342,7 @@ export const sv = {chatAboutThis: "Chatta om detta",chatWithModel: "Chatta med den här modellen",addToFavorites: "Lägg till i Favoriter",+ regenerateTitle: "Generera om titel",removeFromFavorites: "Ta bort från Favoriter",download: "Hämta",addToFolder: "Lägg till i mapp",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex e7cc6b1b2b1..fcfcfd1b2ab 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -3994,6 +3994,7 @@ export const zhCN = {chatAboutThis: "就此聊天",chatWithModel: "与此模型聊天",addToFavorites: "加入收藏",+ regenerateTitle: "重新生成标题",removeFromFavorites: "取消收藏",download: "下载",addToFolder: "添加到文件夹",diff --git a/studio/frontend/tests/chat-title-refresh.test.ts b/studio/frontend/tests/chat-title-refresh.test.tsnew file mode 100644index 00000000000..ee4187a07ae--- /dev/null+++ b/studio/frontend/tests/chat-title-refresh.test.ts@@ -0,0 +1,284 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";++import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";++registerBundlerResolver();+installLocalStorageFake();+Object.assign((globalThis.window as { location: object }).location, {+ href: "http://localhost/",+});++const {+ buildTitleRefreshRequest,+ buildTitleRequest,+ heuristicChatTitle,+ titleCheckpoint,+ titleRefreshExcerpt,+} = await import("../src/features/chat/utils/chat-title.ts");+const { buildExternalModelId, parseExternalModelId } = await import("../src/features/chat/external-providers.ts");+type MessageRecord = import("../src/features/chat/types.ts").MessageRecord;++const LOCAL = "unsloth/gemma-4-E2B-it-GGUF";++function message(+ index: number,+ role: MessageRecord["role"],+ content: MessageRecord["content"],+): MessageRecord {+ return {+ id: `m${index}`,+ threadId: "t",+ role,+ content,+ createdAt: index,+ } as MessageRecord;+}++const text = (value: string) => [{ type: "text", text: value }] as MessageRecord["content"];++test("a refresh reads the latest turns, oldest first, not the opening exchange", () => {+ const messages: MessageRecord[] = [+ message(0, "user", text("help me write a follow-up email")),+ message(1, "assistant", text("Sure, here is a draft ".repeat(40))),+ ];+ for (let i = 2; i < 12; i += 2) {+ messages.push(message(i, "user", text(`what about clause ${i} of the contract`)));+ messages.push(message(i + 1, "assistant", text(`Clause ${i} limits liability. `.repeat(20))));+ }+ const excerpt = titleRefreshExcerpt(messages);+ assert.ok(excerpt.length <= 900, String(excerpt.length));+ assert.doesNotMatch(excerpt, /follow-up email/);+ const lines = excerpt.split("\n");+ assert.match(lines.at(-1) ?? "", /^Assistant: Clause 10 limits liability/);+ assert.match(lines.at(-2) ?? "", /^User: what about clause 10 of the contract$/);+ for (const line of lines) {+ assert.ok(line.length <= 300 + "Assistant: ".length, line);+ // A message is sent whole, or cut to at least 40 characters, never as a stub.+ const body = line.replace(/^(User|Assistant): /, "");+ assert.ok(body.length >= 40 || /^what about clause \d+ of the contract$/.test(body), line);+ }+});++test("a message that would fit only as a stub is left out", () => {+ // Newest first: 312 + 307 + 239 = 858 used, so the opening prompt has 36 characters of room.+ const excerpt = titleRefreshExcerpt([+ message(0, "user", text("opening question about the email we started with")),+ message(1, "assistant", text("a".repeat(227))),+ message(2, "user", text("d".repeat(400))),+ message(3, "assistant", text("c".repeat(400))),+ ]);+ assert.doesNotMatch(excerpt, /opening/);+ assert.match(excerpt, /^Assistant: a{227}$/m);+});++test("only visible text is sent: no reasoning, tool calls, images or system turns", () => {+ const excerpt = titleRefreshExcerpt([+ message(0, "system", text("You are terse")),+ message(1, "user", "a legacy string message" as unknown as MessageRecord["content"]),+ message(2, "assistant", [+ { type: "reasoning", text: "SECRET THOUGHTS" },+ { type: "tool-call", toolName: "web_search", args: {}, result: "SEARCH DUMP" },+ { type: "text", text: "Here are the\nresults" },+ ] as unknown as MessageRecord["content"]),+ message(3, "user", [{ type: "image", image: "data:image/png;base64,AAAA" }] as unknown as MessageRecord["content"]),+ ]);+ assert.equal(excerpt, "User: a legacy string message\nAssistant: Here are the results");+});++test("an empty chat has nothing to title", () => {+ assert.equal(titleRefreshExcerpt([]), "");+ assert.equal(titleRefreshExcerpt([message(0, "assistant", text(" "))]), "");+});++test("a refresh is as cheap as the automatic title, with its own prompt", async () => {+ const automatic = await buildTitleRequest(LOCAL, "User: hi");+ const refresh = await buildTitleRefreshRequest(LOCAL, "User: hi");+ // The automatic prompt is unchanged byte for byte.+ assert.equal(+ automatic?.messages?.[0]?.content,+ "Write 1 concise chat title summarizing the conversation topic, not the user's exact wording. Use the assistant reply as context when provided. Rules: 2-6 words, no quotes, no punctuation, ASCII only, do not echo input. Output title only.",+ );+ assert.match(String(refresh?.messages?.[0]?.content), /latest messages/);+ assert.deepEqual(+ { ...refresh, messages: undefined },+ { ...automatic, messages: undefined },+ );+ assert.deepEqual(+ [refresh?.max_tokens, refresh?.enable_thinking, refresh?.enable_tools],+ [24, false, false],+ );+});++test("a refresh follows the connection that answered, and asks a local model only while it is serving", () => {+ const source = readFileSync(+ new URL("../src/features/chat/components/chat-row-menu.ts", import.meta.url),+ "utf8",+ ).replace(/\s+/g, " ");+ const serving = source.slice(+ source.indexOf("async function titleModelServing"),+ source.indexOf("export async function regenerateChatTitle"),+ );+ // An idle-unloaded local model is reloaded by any completion naming it, so residency is read first,+ // bounded: a stalled status check must still reach the heuristic fallback.+ // With the WebKitGTK-safe helper (no AbortSignal.timeout before 2.38), disposed once settled.+ assert.match(serving, /const wait = disposableTimeoutSignal\(TITLE_STATUS_WAIT_MS\);/);+ assert.match(serving, /const status = await Promise\.race\(\[getInferenceStatus\(wait\.signal, checkpoint\), timedOut\]\);/);+ assert.match(serving, /finally \{ wait\.dispose\(\); \}/);+ assert.doesNotMatch(source, /AbortSignal\.timeout\(/);+ assert.match(serving, /if \(!status\.active_model \|\| status\.is_audio \|\| status\.is_diffusion\) return false;/);+ // The model's wait covers building the request (a stored key is encrypted through the backend) as well as the stream.+ const fromModel = source.slice(+ source.indexOf("async function titleFromModel"),+ source.indexOf("async function titleModelServing"),+ );+ assert.match(fromModel, /await Promise\.race\(\[buildTitleRefreshRequest\(checkpoint, excerpt\), timedOut\]\)/);+ assert.match(fromModel, /await Promise\.race\(\[titleFromStream\(streamChatCompletions\(request, controller\.signal\)\), timedOut\]\)/);+ const body = source.slice(+ source.indexOf("export async function regenerateChatTitle"),+ source.indexOf("/** The sandbox"),+ );+ assert.match(body, /const selected = !modelLoading \? params\.checkpoint : "";/);+ // The latest answer on the branch names the connection; never the live selection alone.+ assert.match(body, /const lastMessage = branch\.at\(-1\);/);+ assert.match(+ body,+ /lastMessage\?\.role === "assistant" \? answeringCheckpoint\(lastMessage\.metadata\?\.custom\) : "";/,+ );+ assert.match(body, /const checkpoint = titleCheckpoint\(answeredWith, selected\);/);+ assert.match(+ body,+ /\(serving \? await titleFromModel\(checkpoint, excerpt\) : null\) \?\? heuristicChatTitle\(branch\)/,+ );+ // One deadline over the whole regeneration releases the busy mark whichever step stalls.+ assert.match(body, /return await Promise\.race\(\[regenerateChatTitleNow\(item, run\), deadline\]\);/);+ // A run that lost the race never writes: a retry may already own the chat.+ assert.match(body, /run\.expired = true; resolve\("failed"\);/);+ assert.match(body, /if \(run\.expired\) return "failed"; const targets = panes/);+ assert.match(body, /finally \{ clearTimeout\(timer\); regeneratingTitles\.delete\(item\.id\); \}/);+ // Unchanged only when every pane already has the title.+ assert.match(body, /if \(panes \? panes\.every\(\(pane\) => pane\.title === title\) : title === startTitle\) return "unchanged";/);+ // Each pane is guarded with its own starting title: a comparison's panes can differ.+ assert.match(body, /item\.type === "single" \? Promise\.resolve\(null\) : listStoredChatThreads\(\{ pairId: item\.id, includeArchived: true \}\)/);+ assert.match(body, /updateChatThread\(id, \{ title \}, \{ expectedTitle: before, preserveTitleModifiedAt: true \}\)/);+});++test("a locally answered chat is never sent to a selected external provider", () => {+ const external = buildExternalModelId("prov-1", "gpt-x");+ assert.notEqual(parseExternalModelId(external), null);+ // Local answer, external selected: no model asked, the messages pick the title.+ assert.equal(titleCheckpoint(LOCAL, external), "");+ assert.equal(titleCheckpoint("", external), "");+ // Local answer, local selected: unchanged.+ assert.equal(titleCheckpoint(LOCAL, LOCAL), LOCAL);+ // External answer: the connection that already has these messages.+ assert.equal(titleCheckpoint(external, LOCAL), external);+});++const DRIFTED: MessageRecord[] = [+ message(0, "user", text("Help me write a short follow-up email to a client after our kickoff meeting.")),+ message(1, "assistant", text("Sure! **Subject:** Follow-Up on Our Kickoff Meeting. Dear client, thanks for the meeting.")),+ message(2, "user", text("Actually the client now wants to renegotiate the contract. They want to lower the liability cap. What should I push back on?")),+ message(3, "assistant", text("## Liability cap negotiation\nIf the client asks to **lower the liability cap**, push back on carve-outs for indemnification.")),+ message(4, "user", text("How should indemnification and limitation of liability clauses interact in a software license agreement?")),+ message(5, "assistant", text("## 1. Indemnification vs limitation of liability\nIn a **software license agreement**, indemnification is often carved out of the liability cap.")),+];++test("without a model the title follows where the chat went, not where it started", () => {+ assert.equal(heuristicChatTitle(DRIFTED), "Indemnification and limitation of liability clauses");+});++test("without a model a closing thanks or nudge does not become the title", () => {+ assert.equal(+ heuristicChatTitle([+ message(0, "user", text("How do I fine-tune Llama 3 with LoRA on a single GPU?")),+ message(1, "assistant", text("## LoRA fine-tuning on one GPU\nUse **QLoRA** with 4-bit quantization.")),+ message(2, "user", text("thanks!")),+ ]),+ "LoRA on a single GPU",+ );+ assert.equal(+ heuristicChatTitle([+ message(0, "user", text("Write a story about a dragon who loves baking bread")),+ message(1, "assistant", text("Once upon a time, a dragon named Ember baked bread.")),+ message(2, "user", text("ok continue")),+ ]),+ "Dragon who loves baking bread",+ );+});++test("without a model text with no spaced words keeps its first line", () => {+ assert.equal(heuristicChatTitle([message(0, "user", text("如何用Python读取CSV文件?"))]), "如何用Python读取CSV文件");+ assert.equal(heuristicChatTitle([]), null);+ assert.equal(heuristicChatTitle([message(0, "assistant", text("Hello there"))]), null);+});++test("a paste-only turn titles from its pasted text", () => {+ const paste = {+ ...message(2, "user", text("")),+ attachments: [{ type: "document", name: "notes.txt", content: [{ type: "text", text: "Quarterly revenue forecast for the Berlin retail stores" }] }],+ } as unknown as MessageRecord;+ const turns = [+ message(0, "user", text("Help me write a short follow-up email to a client")),+ message(1, "assistant", text("Sure, here is a draft.")),+ paste,+ ];+ assert.match(titleRefreshExcerpt(turns), /^User: .*Quarterly revenue forecast/m);+ assert.match(heuristicChatTitle(turns) ?? "", /revenue forecast/i);+});++test("without a model words with combining marks stay whole", () => {+ const hindi = "मुझे पायथन डेकोरेटर समझाओ, खासकर तर्क वाले डेकोरेटर";+ const title = heuristicChatTitle([message(0, "user", text(hindi))]) ?? "";+ assert.ok(title.length > 0);+ for (const word of title.split(" ")) assert.ok(hindi.split(/[\s,]+/).includes(word), word);+});++test("without a model reasoning and tool output never pick the title", () => {+ const title = heuristicChatTitle([+ message(0, "user", text("Plan a three day trip to Kyoto in autumn")),+ message(1, "assistant", [+ { type: "reasoning", text: "Database migration database migration database migration" },+ { type: "tool-call", toolName: "web_search", args: {}, result: "database migration" },+ { type: "text", text: "Day one: **Kyoto temples** in autumn." },+ ] as unknown as MessageRecord["content"]),+ ]);+ assert.equal(title, "Day trip to Kyoto in autumn");+ assert.doesNotMatch(title ?? "", /database|migration/i);+});++test("the Library's Regenerate title is off while any of the chat's panes is generating", () => {+ const source = readFileSync(+ new URL("../src/features/library/chats/chats-items.tsx", import.meta.url),+ "utf8",+ ).replace(/\s+/g, " ");+ const item = source.slice(+ source.indexOf("function RegenerateTitleItem"),+ source.indexOf("function ForkItem"),+ );+ // A comparison's id is its pair's; runningByThreadId is keyed by each pane's thread.+ assert.match(+ item,+ /\(chat\.threadIds\?\.length \? chat\.threadIds : \[chat\.id\]\)\.some\(\(id\) => Boolean\(s\.runningByThreadId\[id\]\)\)/,+ );+ assert.match(item, /disabled=\{generating\}/);+});++test("a second Regenerate title while one runs leaves the running request's toast alone", () => {+ const source = readFileSync(+ new URL("../src/features/library/chats/chats-library.tsx", import.meta.url),+ "utf8",+ ).replace(/\s+/g, " ");+ const fn = source.slice(+ source.indexOf("async function regenerateChatTitleWithToast"),+ source.indexOf("function isDateField"),+ );+ assert.match(fn, /if \(outcome === "busy"\) return; if \(outcome === "empty"\)/);+});diff --git a/studio/frontend/tests/thread-read-sharing.test.ts b/studio/frontend/tests/thread-read-sharing.test.tsindex af7ab4a6bc3..ceb0a1842aa 100644--- a/studio/frontend/tests/thread-read-sharing.test.ts+++ b/studio/frontend/tests/thread-read-sharing.test.ts@@ -14,7 +14,7 @@ type Module = {threadId: string,options?: { bounded?: boolean; timeoutMs?: number; signal?: AbortSignal; share?: boolean },) => Promise<Row | null>;- updateChatThread: (threadId: string, patch: object) => Promise<Row>;+ updateChatThread: (threadId: string, patch: object, options?: { expectedTitle?: string; preserveTitleModifiedAt?: boolean }) => Promise<Row>;saveChatMessage: (message: { id: string; threadId: string }) => Promise<unknown>;};@@ -226,3 +226,18 @@ test("a read started under one auth session is never joined by the next", asyncassert.deepEqual(await before, { id: "t1", title: "first session" });assert.deepEqual(await after, row);});++test("title regeneration sends the recency option while an ordinary rename omits it", async () => {+ for (const regenerate of [false, true]) {+ const { module, pending } = harness();+ const write = module.updateChatThread("t1", { title: "New title" },+ regenerate ? { expectedTitle: "T", preserveTitleModifiedAt: true } : undefined);+ await tick();+ const request = pending.find((p) => p.init?.method === "PATCH")!;+ assert.deepEqual(JSON.parse(String(request.init?.body)), regenerate+ ? { title: "New title", expectedTitle: "T", preserveTitleModifiedAt: true }+ : { title: "New title" });+ request.resolve(200, { ...row, title: "New title" });+ assert.equal((await write).title, "New title");+ }+});