Skip to content

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

Studio: regenerate a chat's title from its latest turns (#13197)

Daniel Han8fc939580914
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index e57eaebdc46..f94ca9481d1 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -107,6 +107,7 @@ import {
Delete02Icon,
Download01Icon,
Edit03Icon,
+ Refresh01Icon,
FolderExportIcon,
Folder01Icon,
Folder02Icon,
@@ -166,6 +167,7 @@ import {
canForkChatRow,
EditProjectDialog,
forkChatRow,
+ regenerateChatTitle,
showForkCreatedToast,
getSidebarItemThreadIds,
useForkInFlight,
@@ -3091,6 +3093,21 @@ export function AppSidebar() {
}
}
+ async function regenerateChatTitleFromMenu(item: SidebarItem) {
+ // A fast refresh would only flash the toast.
+ const toastId = `regenerate-title-${item.id}`;
+ const slow = setTimeout(() => toast.loading("Regenerating title...", { id: toastId }), 400);
+ const outcome = await regenerateChatTitle(item);
+ clearTimeout(slow);
+ 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);
+ }
+ }
+
type RenameTarget =
// `inline` is the row's own pill, and a chord has no row under the cursor
// and may have none on screen at all, so it opens the dialog instead.
@@ -3688,6 +3705,8 @@ export function AppSidebar() {
: null,
section: section ? { id: section.id, name: section.name } : null,
rename: () => openRenameChat(item, false),
+ canRegenerateTitle: !generating,
+ regenerateTitle: () => void regenerateChatTitleFromMenu(item),
togglePin: () => togglePinnedChat(item.id),
toggleUnread: () =>
unread
@@ -4646,6 +4665,13 @@ export function AppSidebar() {
<HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
<span>Rename</span>
</P.Item>
+ <P.Item
+ disabled={isGenerating}
+ onSelect={() => void regenerateChatTitleFromMenu(item)}
+ >
+ <HugeiconsIcon icon={Refresh01Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("library.menu.regenerateTitle")}</span>
+ </P.Item>
<P.Item onSelect={() => togglePinnedChat(item.id)}>
<HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
<span>{isPinned ? "Unpin" : "Pin"}</span>
diff --git a/studio/frontend/src/features/chat/components/chat-header-menu.tsx b/studio/frontend/src/features/chat/components/chat-header-menu.tsx
index 71e4f7e783e..5b64e59bc05 100644
--- a/studio/frontend/src/features/chat/components/chat-header-menu.tsx
+++ b/studio/frontend/src/features/chat/components/chat-header-menu.tsx
@@ -41,6 +41,7 @@ import {
PinIcon,
PinOffIcon,
PlusSignIcon,
+ Refresh01Icon,
ViewIcon,
ViewOffSlashIcon,
} from "@hugeicons/core-free-icons";
@@ -169,6 +170,13 @@ function ChatMenuItems({ menu }: { menu: ActiveChatMenu }) {
<Item icon={Edit03Icon} onSelect={menu.rename} shortcut="renameChat">
{t("common.rename")}
</Item>
+ <Item
+ icon={Refresh01Icon}
+ onSelect={menu.regenerateTitle}
+ disabled={!menu.canRegenerateTitle}
+ >
+ {t("library.menu.regenerateTitle")}
+ </Item>
<Item
icon={menu.pinned ? PinOffIcon : PinIcon}
onSelect={menu.togglePin}
diff --git a/studio/frontend/src/features/chat/components/chat-row-menu.ts b/studio/frontend/src/features/chat/components/chat-row-menu.ts
index d8f579dafdb..17e42ef15c6 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,18 @@ 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 { 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 +33,19 @@ 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 {
+ buildTitleRefreshRequest,
+ heuristicChatTitle,
+ titleFromStream,
+ titleRefreshExcerpt,
+} from "../utils/chat-title";
export type ConversationExportFormat =
| "raw-jsonl"
@@ -110,6 +132,101 @@ function forkRefused(): Error {
);
}
+export type RegenerateTitleOutcome =
+ | "renamed"
+ | "unchanged"
+ | "empty"
+ | "busy"
+ | "failed";
+
+const regeneratingTitles = new Set<string>();
+// Past this, the title is picked from the messages instead.
+const TITLE_MODEL_WAIT_MS = 15_000;
+
+async function titleFromModel(checkpoint: string, excerpt: string): Promise<string | null> {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), TITLE_MODEL_WAIT_MS);
+ try {
+ const request = await buildTitleRefreshRequest(checkpoint, excerpt);
+ if (!request) return null;
+ return await titleFromStream(streamChatCompletions(request, controller.signal));
+ } catch {
+ return null;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/** A local model is asked only while it is serving: a request naming an idle-unloaded one makes the
+ * backend load it again, multi-GB for a few words. */
+async function titleModelServing(checkpoint: string): Promise<boolean> {
+ if (parseExternalModelId(checkpoint) !== null) return true;
+ try {
+ // Scoped to the slot serving it, which need not be the primary one.
+ const status = await getInferenceStatus(undefined, checkpoint);
+ 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;
+ }
+}
+
+/** Uses the selected model, never the one that answered, and only while it is serving; else the
+ * messages. A comparison's panes share user turns, so one is read. */
+export async function regenerateChatTitle(
+ item: SidebarItem,
+): Promise<RegenerateTitleOutcome> {
+ if (regeneratingTitles.has(item.id)) return "busy";
+ regeneratingTitles.add(item.id);
+ try {
+ const threadId = getSidebarItemThreadIds(item)[0];
+ const liveBranch = liveThreadBranch(threadId);
+ const { params, modelLoading } = useChatRuntimeStore.getState();
+ const checkpoint = !modelLoading ? params.checkpoint : "";
+ const [startTitle, raw, serving] = await Promise.all([
+ getStoredChatThread(threadId).then((thread) => thread?.title),
+ listStoredChatMessages(threadId),
+ checkpoint ? titleModelServing(checkpoint) : false,
+ ]);
+ // 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";
+ const title =
+ (serving ? await titleFromModel(checkpoint, excerpt) : null) ?? heuristicChatTitle(branch);
+ if (!title) return "empty";
+ if (title === startTitle) return "unchanged";
+ const ids =
+ item.type === "single"
+ ? [threadId]
+ : [...new Set((await listStoredChatThreads({ pairId: item.id, includeArchived: true })).map((t) => t.id))];
+ try {
+ // Guarded: a rename that lands while the title is generated wins (409).
+ await Promise.all(
+ ids.map((id) =>
+ updateChatThread(id, { title }, startTitle === undefined ? {} : { expectedTitle: startTitle }),
+ ),
+ );
+ } catch {
+ return (await getStoredChatThread(threadId))?.title !== startTitle ? "unchanged" : "failed";
+ }
+ return "renamed";
+ } catch {
+ return "failed";
+ } finally {
+ regeneratingTitles.delete(item.id);
+ }
+}
+
/** 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.ts
index 8eb582e75c7..fa6f0d1cdfa 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -355,6 +355,7 @@ export {
forkChatRow,
getSidebarItemThreadIds,
recordedSandboxSessionIds,
+ regenerateChatTitle,
sandboxSessionIdsHolding,
type ConversationExportFormat,
} from "./components/chat-row-menu";
diff --git a/studio/frontend/src/features/chat/stores/active-chat-menu-store.ts b/studio/frontend/src/features/chat/stores/active-chat-menu-store.ts
index ea09fd67e32..55c971533b8 100644
--- a/studio/frontend/src/features/chat/stores/active-chat-menu-store.ts
+++ b/studio/frontend/src/features/chat/stores/active-chat-menu-store.ts
@@ -19,6 +19,9 @@ export interface ActiveChatMenu {
project: Place | null;
section: Place | null;
rename: () => void;
+ /** Off while generating: the reply is still changing the topic. */
+ canRegenerateTitle: boolean;
+ regenerateTitle: () => void;
togglePin: () => void;
toggleUnread: () => void;
fork: () => void;
diff --git a/studio/frontend/src/features/chat/utils/chat-title.ts b/studio/frontend/src/features/chat/utils/chat-title.ts
index c6747e9b59d..68161589ef5 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,132 @@ 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;
+ // Names (React, LoRA) weigh more.
+ 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 +540,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/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 6cecbf5da2a..b41b280ac8a 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -3987,6 +3987,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.ts
index 9e93fa67c7e..addc437bc60 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -4059,6 +4059,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.ts
index 827080a2a8d..ac5092b2e2c 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -4017,6 +4017,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.ts
index 8ce2d13a3be..c7f74f550f8 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -4058,6 +4058,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.ts
index 74b9ed796cb..f448d4d6c1f 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -4070,6 +4070,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.ts
index 59a28c6da14..aaab011578c 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -4102,6 +4102,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.ts
index b2df24f5121..bd05e87af84 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -3995,6 +3995,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.ts
index a57c8afbc2f..53988346a4e 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -4060,6 +4060,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.ts
index 1590c968ea7..9a9f16d37d4 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -3935,6 +3935,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.ts
index 0ca3a9b18b9..430a0b03420 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -3978,6 +3978,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.ts
index 1cf87257c72..9806ba16731 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -4018,6 +4018,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.ts
index a19e18ac914..4b461f53e63 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -4014,6 +4014,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.ts
index 05701dde8fa..b05ffbb90e0 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -4243,6 +4243,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.ts
index fcb0945a301..83aef557eea 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -3892,6 +3892,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.ts
new file mode 100644
index 00000000000..d18982e13d9
--- /dev/null
+++ b/studio/frontend/tests/chat-title-refresh.test.ts
@@ -0,0 +1,213 @@
+// 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,
+ titleRefreshExcerpt,
+} = await import("../src/features/chat/utils/chat-title.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 asks the selected model only while it is serving, and writes the title guarded", () => {
+ 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.
+ assert.match(serving, /const status = await getInferenceStatus\(undefined, checkpoint\);/);
+ assert.match(serving, /if \(!status\.active_model \|\| status\.is_audio \|\| status\.is_diffusion\) return false;/);
+ const body = source.slice(
+ source.indexOf("export async function regenerateChatTitle"),
+ source.indexOf("/** The sandbox"),
+ );
+ assert.match(body, /const checkpoint = !modelLoading \? params\.checkpoint : "";/);
+ assert.match(
+ body,
+ /\(serving \? await titleFromModel\(checkpoint, excerpt\) : null\) \?\? heuristicChatTitle\(branch\)/,
+ );
+ assert.match(body, /updateChatThread\(id, \{ title \}, startTitle === undefined \? \{\} : \{ expectedTitle: startTitle \}\)/);
+ assert.doesNotMatch(body, /answeringCheckpoint|titleCheckpoint/);
+});
+
+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);
+});