Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🖲️ fix: Enable Running Chat Menus and Preserve Renamed Titles (#16697)

lia-by-librechat[bot]19092e55bd20
diff --git a/.github/workflows/playwright-mock.yml b/.github/workflows/playwright-mock.yml
index ccfeac169a..6f740ca27d 100644
--- a/.github/workflows/playwright-mock.yml
+++ b/.github/workflows/playwright-mock.yml
@@ -404,6 +404,25 @@ jobs:
retention-days: 7
if-no-files-found: ignore
+ - name: Run first-turn title ownership regressions
+ if: ${{ !cancelled() && matrix.stream_store == 'memory' && startsWith(matrix.shard, '1/') }}
+ env:
+ CI: 'true'
+ E2E_TITLE_CONVO: 'true'
+ run: >-
+ npx playwright test --config=e2e/playwright.config.mock.ts
+ conversation-management.spec.ts --grep 'first-turn|final-title polling' --reporter=line
+ --output=e2e/specs/.test-results/title-ownership
+
+ - name: Upload title ownership diagnostics
+ if: ${{ always() && matrix.stream_store == 'memory' && startsWith(matrix.shard, '1/') }}
+ uses: actions/upload-artifact@v6
+ with:
+ name: playwright-title-ownership-${{ matrix.artifact }}
+ path: e2e/specs/.test-results/title-ownership/**
+ retention-days: 7
+ if-no-files-found: ignore
+
mcp_tool_list_changed:
name: MCP list_changed (replica count ${{ matrix.replicas }})
needs: [codegraph_select]
diff --git a/api/server/routes/__test-utils__/convos-route-mocks.js b/api/server/routes/__test-utils__/convos-route-mocks.js
index 32e7c5899b..34fd583f6e 100644
--- a/api/server/routes/__test-utils__/convos-route-mocks.js
+++ b/api/server/routes/__test-utils__/convos-route-mocks.js
@@ -57,6 +57,8 @@ function resetCheckpointRows(rows = []) {
}
const markConvoSeenHandler = jest.fn();
const markConvoUnreadHandler = jest.fn();
+const renameConversationHandler = jest.fn((_req, res) => res.status(204).end());
+const renameHandlerInputs = [];
module.exports = {
archiveAllHandler,
@@ -71,10 +73,17 @@ module.exports = {
resetCheckpointRows,
markConvoSeenHandler,
markConvoUnreadHandler,
+ renameConversationHandler,
+ renameHandlerInputs,
agents: () => ({ sleep: jest.fn() }),
api: (overrides = {}) => ({
+ createGeneratedTitleHandler: jest.fn(() => jest.fn()),
+ createRenameConversationHandler: jest.fn((deps) => {
+ renameHandlerInputs.push(deps);
+ return renameConversationHandler;
+ }),
/** Mirrors the real helper so query-flag parsing (`isArchived`, `pinned`) is exercised. */
isEnabled: jest.fn((value) => {
if (typeof value === 'boolean') {
diff --git a/api/server/routes/__tests__/convos.spec.js b/api/server/routes/__tests__/convos.spec.js
index ebaf67a0d5..1cc49c7430 100644
--- a/api/server/routes/__tests__/convos.spec.js
+++ b/api/server/routes/__tests__/convos.spec.js
@@ -2057,6 +2057,30 @@ describe('Convos Routes', () => {
});
});
+ describe('POST /update running chat rename', () => {
+ it('delegates rename semantics to the injected TypeScript handler', async () => {
+ const { renameConversationHandler, renameHandlerInputs } = require(MOCKS);
+ const arg = { conversationId: 'running-rename', title: 'Renamed' };
+ expect((await request(app).post('/api/convos/update').send({ arg })).status).toBe(204);
+ expect(renameConversationHandler).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: { arg },
+ user: expect.objectContaining({ id: 'test-user-123' }),
+ }),
+ expect.anything(),
+ expect.anything(),
+ );
+ expect(renameHandlerInputs.at(-1)).toEqual(
+ expect.objectContaining({
+ saveConvo,
+ getConvo,
+ getActiveRunIds: expect.any(Function),
+ logger: expect.anything(),
+ }),
+ );
+ });
+ });
+
describe('POST /archive', () => {
it('should archive a conversation successfully', async () => {
const mockConversationId = 'conv-123';
diff --git a/api/server/routes/config.js b/api/server/routes/config.js
index 1fec348ad4..f8633443b9 100644
--- a/api/server/routes/config.js
+++ b/api/server/routes/config.js
@@ -10,6 +10,7 @@ const {
getAppConfigOptionsFromUser,
resolveBuildInfo,
resolveTitleTiming,
+ getConversationTitleCapabilities,
sanitizeModelSpecs,
excludeHiddenModelSpecs,
isFileSnapshotEnabled,
@@ -303,6 +304,7 @@ router.get('/', async function (req, res) {
...preLoginPayload,
...publicSharePayload,
...buildPostLoginPayload(appConfig),
+ ...getConversationTitleCapabilities(appConfig?.interfaceConfig),
conversationListLimits,
sharedLinksSnapshotFilesEnabled: sharedLinksEnabled && isFileSnapshotEnabled(appConfig),
socialLogins: appConfig?.registration?.socialLogins ?? defaultSocialLogins,
diff --git a/api/server/routes/convos.js b/api/server/routes/convos.js
index 7efc784d00..a8e346f425 100644
--- a/api/server/routes/convos.js
+++ b/api/server/routes/convos.js
@@ -1,6 +1,5 @@
const multer = require('multer');
const express = require('express');
-const { sleep } = require('@librechat/agents');
const {
reportLocatorTraversalFailure,
isEnabled,
@@ -22,17 +21,17 @@ const {
createBackgroundTaskPolicyMiddleware,
backgroundTaskRegistry,
createSubagentThreadViewHandler,
+ createGeneratedTitleHandler,
+ createRenameConversationHandler,
createMarkConvoSeenHandler,
createMarkConvoUnreadHandler,
resolveImportMaxFileSize,
restoreTenantContextFromReq,
deleteAllSharedLinksWithCleanup,
deleteConvoSharedLinksWithCleanup,
- inspectContent,
createContentFilter,
isContentFilterError,
isConversationImportError,
- contentFilterBlockResponse,
extractConversationTitleContent,
extractStoredMessageContent,
GenerationJobManager,
@@ -258,33 +257,14 @@ router.get('/:conversationId', async (req, res) => {
}
});
-router.get('/gen_title/:conversationId', async (req, res) => {
- const { conversationId } = req.params;
- const titleCache = getLogStores(CacheKeys.GEN_TITLE);
- const key = `${req.user.id}-${conversationId}`;
- let title = await titleCache.get(key);
-
- if (!title) {
- // Exponential backoff: 500ms, 1s, 2s, 4s, 8s (total ~15.5s max wait)
- const delays = [500, 1000, 2000, 4000, 8000];
- for (const delay of delays) {
- await sleep(delay);
- title = await titleCache.get(key);
- if (title) {
- break;
- }
- }
- }
-
- if (title) {
- await titleCache.delete(key);
- res.status(200).json({ title });
- } else {
- res.status(404).json({
- message: "Title not found or method not implemented for the conversation's endpoint",
- });
- }
-});
+router.get(
+ '/gen_title/:conversationId',
+ createGeneratedTitleHandler({
+ getConvoTitleState: db.getConvoTitleState,
+ getCache: () => getLogStores(CacheKeys.GEN_TITLE),
+ logger,
+ }),
+);
const POST_DELETE_CANCEL_ATTEMPTS = 3;
const POST_DELETE_CANCEL_BACKOFF_MS = 250;
@@ -717,58 +697,18 @@ router.post('/seen', validateConvoAccess, markConvoSeenHandler);
router.post('/unread', validateConvoAccess, markConvoUnreadHandler);
-/** Maximum allowed length for conversation titles */
-const MAX_CONVO_TITLE_LENGTH = 1024;
-
-/**
- * Updates a conversation's title.
- * @route POST /update
- * @param {string} req.body.arg.conversationId - The conversation ID to update.
- * @param {string} req.body.arg.title - The new title for the conversation.
- * @returns {object} 201 - The updated conversation object.
- */
-router.post('/update', validateConvoAccess, configMiddleware, async (req, res) => {
- const { conversationId, title } = req.body?.arg ?? {};
-
- if (!conversationId) {
- return res.status(400).json({ error: 'conversationId is required' });
- }
-
- if (title === undefined) {
- return res.status(400).json({ error: 'title is required' });
- }
-
- if (typeof title !== 'string') {
- return res.status(400).json({ error: 'title must be a string' });
- }
-
- const sanitizedTitle = title.trim().slice(0, MAX_CONVO_TITLE_LENGTH);
- if (req.config?.filters != null) {
- const finding = inspectContent(extractConversationTitleContent({ title: sanitizedTitle }), {
- filters: req.config.filters,
- });
- if (finding != null) {
- return res.status(400).json(contentFilterBlockResponse(finding));
- }
- }
-
- try {
- const dbResponse = await db.saveConvo(
- {
- userId: req?.user?.id,
- isTemporary: req?.resolvedConversation?.isTemporary,
- expiredAt: req?.resolvedConversation?.expiredAt,
- interfaceConfig: req?.config?.interfaceConfig,
- },
- { conversationId, title: sanitizedTitle },
- { context: `POST /api/convos/update ${conversationId}`, appendMessageIds: [] },
- );
- res.status(201).json(dbResponse);
- } catch (error) {
- logger.error('Error updating conversation', error);
- res.status(500).send('Error updating conversation');
- }
-});
+router.post(
+ '/update',
+ validateConvoAccess,
+ configMiddleware,
+ createRenameConversationHandler({
+ saveConvo: db.saveConvo,
+ getConvo: db.getConvo,
+ getActiveRunIds:
+ GenerationJobManager.getCleanupBlockingJobIdsForConversations.bind(GenerationJobManager),
+ logger,
+ }),
+);
const { importIpLimiter, importUserLimiter } = createImportLimiters();
/** Fork and duplicate share one rate-limit budget (same "clone" operation class) */
diff --git a/api/server/services/Endpoints/agents/title.js b/api/server/services/Endpoints/agents/title.js
index bdbc9c3eec..8649154555 100644
--- a/api/server/services/Endpoints/agents/title.js
+++ b/api/server/services/Endpoints/agents/title.js
@@ -1,8 +1,8 @@
-const { isEnabled } = require('@librechat/api');
+const { isEnabled, publishConversationTitle } = require('@librechat/api');
const { logger } = require('@librechat/data-schemas');
const { CacheKeys } = require('librechat-data-provider');
const getLogStores = require('~/cache/getLogStores');
-const { saveConvo } = require('~/models');
+const { saveConvo, getConvo } = require('~/models');
const { resolveConversationTitle } = require('../titlePolicy');
/**
@@ -30,8 +30,7 @@ const { resolveConversationTitle } = require('../titlePolicy');
* clobber the conversation now owned by the newer run. A plain user Stop does
* NOT abort this — its generated title is kept.
* @param {(params: { conversationId: string, title: string }) => Promise<void>|void} [params.onTitleGenerated]
- * Called after the title is cached and before persistence waits for the
- * conversation row. Used by live streams to push the title immediately.
+ * Called after caching the title for the live stream.
*/
const addTitle = async (
req,
@@ -124,62 +123,21 @@ const addTitle = async (
return;
}
- await titleCache.set(key, title, 120000);
-
- if (!signal?.aborted && typeof onTitleGenerated === 'function') {
- try {
- await onTitleGenerated({ conversationId: convoId, title });
- } catch (error) {
- logger.error('Error emitting generated title:', error);
- }
- }
-
- /** In immediate mode the title is generated in parallel with the response,
- * so the conversation row may not exist yet. `saveConvo` with `noUpsert`
- * is a silent no-op when the row is missing, which would drop the title
- * from the database (the cache above still serves the live UI). Wait for
- * the controller to signal the conversation has been persisted. */
- if (convoReady) {
- await convoReady;
- }
-
- if (discardSignal?.aborted) {
- // This stream was superseded by a newer run (or the turn failed) after the
- // title had already been generated — discard it so a stale title does not
- // clobber the conversation now owned by the newer run. A plain user Stop is
- // not a discard: its generated title falls through and is persisted below.
- // Only clear the cache if it still holds THIS task's title: a replacement
- // stream shares the `userId-conversationId` key and may have already cached
- // its own (valid) title that we must not remove.
- const cached = await titleCache.get(key);
- if (cached === title) {
- await titleCache.delete(key);
- }
- return;
- }
-
- await saveConvo(
- {
- userId: req?.user?.id,
- isTemporary: req?.resolvedConversation?.isTemporary ?? req?.body?.isTemporary,
- expiredAt: req?.resolvedConversation?.expiredAt,
- interfaceConfig: req?.config?.interfaceConfig,
- },
+ await publishConversationTitle(
+ { saveConvo, getConvo, titleCache },
{
+ ctx: {
+ userId: req?.user?.id,
+ isTemporary: req?.resolvedConversation?.isTemporary ?? req?.body?.isTemporary,
+ expiredAt: req?.resolvedConversation?.expiredAt,
+ interfaceConfig: req?.config?.interfaceConfig,
+ },
conversationId: convoId,
title,
- },
- {
- context: 'api/server/services/Endpoints/agents/title.js',
- noUpsert: true,
- preserveUpdatedAt: true,
- /** Metadata-only: write the title and nothing else. Without this, `saveConvo`
- * reads every message id and `$set`s the whole `messages` array, and an
- * immediate-mode title saves while the turn is still running — so a response
- * appending its own id between that read and that write would be erased from
- * the array for good. An empty append is the option's no-message path: it
- * skips both the read and the rewrite. */
- appendMessageIds: [],
+ convoReady,
+ discardSignal,
+ signal,
+ onTitleGenerated,
},
);
} catch (error) {
diff --git a/api/server/services/Endpoints/agents/title.test.js b/api/server/services/Endpoints/agents/title.test.js
index f666771b44..87d2a7da97 100644
--- a/api/server/services/Endpoints/agents/title.test.js
+++ b/api/server/services/Endpoints/agents/title.test.js
@@ -7,6 +7,7 @@ const mockCache = {
delete: jest.fn((key) => mockCacheStore.delete(key)),
};
const mockSaveConvo = jest.fn();
+const mockGetConvo = jest.fn();
jest.mock('@librechat/api', () => ({
...jest.requireActual('@librechat/api'),
@@ -22,6 +23,7 @@ jest.mock('~/cache/getLogStores', () => jest.fn(() => mockCache));
jest.mock('~/models', () => ({
saveConvo: (...args) => mockSaveConvo(...args),
+ getConvo: (...args) => mockGetConvo(...args),
}));
const addTitle = require('./title');
@@ -39,6 +41,11 @@ describe('agents addTitle', () => {
beforeEach(() => {
jest.clearAllMocks();
mockCacheStore.clear();
+ mockCache.get.mockReset().mockImplementation((key) => mockCacheStore.get(key));
+ mockCache.set.mockReset().mockImplementation((key, value) => mockCacheStore.set(key, value));
+ mockCache.delete.mockReset().mockImplementation((key) => mockCacheStore.delete(key));
+ mockSaveConvo.mockReset().mockImplementation(async (_ctx, data) => data);
+ mockGetConvo.mockReset().mockResolvedValue(null);
});
it('uses the explicit conversationId for the cache key and saveConvo (immediate mode)', async () => {
@@ -100,13 +107,17 @@ describe('agents addTitle', () => {
expect(client.titleConvo).toHaveBeenCalledWith(expect.objectContaining({ immediate: false }));
});
- it('caches the title immediately but defers saveConvo until convoReady resolves', async () => {
+ it('caches eagerly but waits for readiness before persisting', async () => {
const client = makeClient('Deferred Title');
let resolveConvo;
const convoReady = new Promise((resolve) => {
resolveConvo = resolve;
});
+ mockSaveConvo.mockImplementationOnce(async (_ctx, data) => {
+ await convoReady;
+ return data;
+ });
const pending = addTitle(makeReq(), {
text: 'hello',
client,
@@ -117,12 +128,7 @@ describe('agents addTitle', () => {
await flush();
- // Title is cached for the live UI, but persistence waits for the row to exist.
- expect(mockCache.set).toHaveBeenCalledWith(
- 'user-1-cid-defer',
- 'Deferred Title',
- expect.any(Number),
- );
+ expect(mockCacheStore.get('user-1-cid-defer')).toBe('Deferred Title');
expect(mockSaveConvo).not.toHaveBeenCalled();
resolveConvo();
@@ -135,7 +141,7 @@ describe('agents addTitle', () => {
);
});
- it('notifies when the title is cached before waiting for convoReady', async () => {
+ it('emits eagerly but waits for readiness before committing', async () => {
const order = [];
const client = makeClient('Streamed Title');
const onTitleGenerated = jest.fn(async () => {
@@ -150,8 +156,10 @@ describe('agents addTitle', () => {
order.push('cache');
mockCacheStore.set(key, value);
});
- mockSaveConvo.mockImplementationOnce(async () => {
+ mockSaveConvo.mockImplementationOnce(async (_ctx, data) => {
+ await convoReady;
order.push('save');
+ return data;
});
const pending = addTitle(makeReq(), {
@@ -279,27 +287,30 @@ describe('agents addTitle', () => {
expect(onTitleGenerated).not.toHaveBeenCalled();
expect(mockSaveConvo).not.toHaveBeenCalled();
- expect(mockCache.delete).toHaveBeenCalledWith('user-1-cid');
+ expect(mockCache.set).not.toHaveBeenCalled();
});
it("does not delete a replacement stream's cached title when superseded", async () => {
const client = makeClient('Stale Title');
const ac = new AbortController();
- ac.abort();
- // Simulate a replacement stream having cached its own (newer) title under the
- // shared `userId-conversationId` key by the time this stale task re-reads it.
- mockCache.get.mockImplementationOnce(() => 'Newer Title');
-
- await addTitle(makeReq(), {
+ let resolveConvo;
+ const convoReady = new Promise((resolve) => {
+ resolveConvo = resolve;
+ });
+ const pending = addTitle(makeReq(), {
text: 'hi',
client,
conversationId: 'cid',
immediate: true,
- convoReady: Promise.resolve(),
- signal: ac.signal,
+ convoReady,
discardSignal: ac.signal,
});
-
+ await flush();
+ mockCacheStore.set('user-1-cid', 'Newer Title');
+ ac.abort();
+ resolveConvo();
+ await pending;
+ expect(mockCacheStore.get('user-1-cid')).toBe('Newer Title');
expect(mockCache.delete).not.toHaveBeenCalled();
expect(mockSaveConvo).not.toHaveBeenCalled();
});
@@ -315,6 +326,10 @@ describe('agents addTitle', () => {
resolveConvo = resolve;
});
+ mockSaveConvo.mockImplementationOnce(async (_ctx, data) => {
+ await convoReady;
+ return data;
+ });
const pending = addTitle(makeReq(), {
text: 'hi',
client,
@@ -326,7 +341,7 @@ describe('agents addTitle', () => {
});
await flush();
- expect(onTitleGenerated).toHaveBeenCalledWith({ conversationId: 'cid', title: 'Kept Title' });
+ expect(onTitleGenerated).toHaveBeenCalledTimes(1);
// User stops mid-response, then the conversation row is persisted.
ac.abort();
@@ -338,7 +353,8 @@ describe('agents addTitle', () => {
expect.objectContaining({ conversationId: 'cid', title: 'Kept Title' }),
expect.objectContaining({ noUpsert: true }),
);
- expect(mockCache.delete).not.toHaveBeenCalled();
+ expect(mockCache.set).toHaveBeenCalledWith('user-1-cid', 'Kept Title', 120000);
+ expect(onTitleGenerated).toHaveBeenCalledTimes(1);
});
/** An immediate-mode title saves while the turn is still running, so its write can
@@ -362,4 +378,93 @@ describe('agents addTitle', () => {
expect.objectContaining({ noUpsert: true, appendMessageIds: [] }),
);
});
+ it('caches the committed manual title instead of a rejected automatic title', async () => {
+ mockSaveConvo.mockResolvedValueOnce(null);
+ mockGetConvo.mockResolvedValueOnce({ conversationId: 'cid', title: 'Renamed' });
+ const onTitleGenerated = jest.fn();
+ await addTitle(makeReq(), {
+ text: 'hi',
+ client: makeClient(),
+ conversationId: 'cid',
+ onTitleGenerated,
+ });
+ expect(mockSaveConvo).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.objectContaining({ titleSource: 'generated' }),
+ );
+ expect(mockCache.set).toHaveBeenCalledWith('user-1-cid', 'Renamed', 120000);
+ expect(onTitleGenerated).not.toHaveBeenCalled();
+ });
+ it('publishes eagerly while a new row is still absent, then fences persistence', async () => {
+ let resolveConvo;
+ const convoReady = new Promise((resolve) => {
+ resolveConvo = resolve;
+ });
+ const onTitleGenerated = jest.fn();
+ const pending = addTitle(makeReq(), {
+ text: 'hello',
+ client: makeClient('Eager Title'),
+ conversationId: 'new-row',
+ immediate: true,
+ convoReady,
+ onTitleGenerated,
+ });
+ await flush();
+ expect(onTitleGenerated).toHaveBeenCalledWith({
+ conversationId: 'new-row',
+ title: 'Eager Title',
+ });
+ mockSaveConvo.mockResolvedValueOnce(null);
+ mockGetConvo.mockResolvedValueOnce({ conversationId: 'new-row', title: 'Renamed' });
+ resolveConvo();
+ await pending;
+ expect(mockCacheStore.get('user-1-new-row')).toBe('Renamed');
+ expect(onTitleGenerated).toHaveBeenCalledTimes(1);
+ });
+ it('retries a missed immediate write when the following read sees the new row', async () => {
+ mockSaveConvo.mockResolvedValueOnce(null);
+ mockGetConvo
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce({ conversationId: 'insert-race', title: 'New Chat' });
+ const onTitleGenerated = jest.fn();
+ await addTitle(makeReq(), {
+ text: 'hello',
+ client: makeClient('Generated title'),
+ conversationId: 'insert-race',
+ immediate: true,
+ convoReady: Promise.resolve(),
+ onTitleGenerated,
+ });
+ expect(mockSaveConvo).toHaveBeenCalledTimes(2);
+ expect(mockCacheStore.get('user-1-insert-race')).toBe('Generated title');
+ expect(onTitleGenerated).toHaveBeenCalledWith({
+ conversationId: 'insert-race',
+ title: 'Generated title',
+ });
+ });
+ it('discards an eager title for a seeded chat before its message is ready', async () => {
+ let resolveConvo;
+ const convoReady = new Promise((resolve) => {
+ resolveConvo = resolve;
+ });
+ const discard = new AbortController();
+ mockGetConvo.mockResolvedValueOnce({ conversationId: 'seeded-chat', title: 'New Chat' });
+ const pending = addTitle(makeReq(), {
+ text: 'attachment',
+ client: makeClient('Seeded title'),
+ conversationId: 'seeded-chat',
+ immediate: true,
+ convoReady,
+ discardSignal: discard.signal,
+ });
+ await flush();
+ expect(mockCacheStore.get('user-1-seeded-chat')).toBe('Seeded title');
+ expect(mockSaveConvo).not.toHaveBeenCalled();
+ discard.abort();
+ resolveConvo();
+ await pending;
+ expect(mockSaveConvo).not.toHaveBeenCalled();
+ expect(mockCacheStore.has('user-1-seeded-chat')).toBe(false);
+ });
});
diff --git a/api/server/services/Endpoints/assistants/title.js b/api/server/services/Endpoints/assistants/title.js
index 4ca54910cd..cf9c08ad3b 100644
--- a/api/server/services/Endpoints/assistants/title.js
+++ b/api/server/services/Endpoints/assistants/title.js
@@ -1,9 +1,15 @@
-const { isEnabled, sanitizeTitle, getAttachmentTitleText } = require('@librechat/api');
+const {
+ isEnabled,
+ sanitizeTitle,
+ getAttachmentTitleText,
+ publishConversationTitle,
+ publishFallbackConversationTitle,
+} = require('@librechat/api');
const { logger } = require('@librechat/data-schemas');
const { CacheKeys } = require('librechat-data-provider');
const getLogStores = require('~/cache/getLogStores');
const initializeClient = require('./initalize');
-const { saveConvo } = require('~/models');
+const { saveConvo, getConvo } = require('~/models');
const { resolveConversationTitle } = require('../titlePolicy');
/**
@@ -57,7 +63,6 @@ const addTitle = async (req, { text, responseText, conversationId }) => {
}
const titleCache = getLogStores(CacheKeys.GEN_TITLE);
- const key = `${req.user.id}-${conversationId}`;
try {
const { openai } = await initializeClient({ req });
@@ -66,7 +71,6 @@ const addTitle = async (req, { text, responseText, conversationId }) => {
if (title == null) {
return;
}
- await titleCache.set(key, title, 120000);
const reqCtx = {
userId: req?.user?.id,
@@ -74,18 +78,9 @@ const addTitle = async (req, { text, responseText, conversationId }) => {
expiredAt: req?.resolvedConversation?.expiredAt,
interfaceConfig: req?.config?.interfaceConfig,
};
- await saveConvo(
- reqCtx,
- {
- conversationId,
- title,
- },
- {
- context: 'api/server/services/Endpoints/assistants/addTitle.js',
- noUpsert: true,
- preserveUpdatedAt: true,
- appendMessageIds: [],
- },
+ await publishConversationTitle(
+ { saveConvo, getConvo, titleCache },
+ { ctx: reqCtx, conversationId, title },
);
} catch (error) {
logger.error('[addTitle] Error generating title:', error);
@@ -105,24 +100,18 @@ const addTitle = async (req, { text, responseText, conversationId }) => {
if (fallbackTitle == null) {
return;
}
- await titleCache.set(key, fallbackTitle, 120000);
- await saveConvo(
- {
- userId: req?.user?.id,
- isTemporary: req?.resolvedConversation?.isTemporary ?? req?.body?.isTemporary,
- expiredAt: req?.resolvedConversation?.expiredAt,
- interfaceConfig: req?.config?.interfaceConfig,
- },
+ await publishFallbackConversationTitle(
+ { saveConvo, getConvo, titleCache, logger },
{
+ ctx: {
+ userId: req?.user?.id,
+ isTemporary: req?.resolvedConversation?.isTemporary ?? req?.body?.isTemporary,
+ expiredAt: req?.resolvedConversation?.expiredAt,
+ interfaceConfig: req?.config?.interfaceConfig,
+ },
conversationId,
title: fallbackTitle,
},
- {
- context: 'api/server/services/Endpoints/assistants/addTitle.js',
- noUpsert: true,
- preserveUpdatedAt: true,
- appendMessageIds: [],
- },
);
}
};
diff --git a/api/server/services/Endpoints/assistants/title.test.js b/api/server/services/Endpoints/assistants/title.test.js
index 93bc3e765a..f7ab04c10e 100644
--- a/api/server/services/Endpoints/assistants/title.test.js
+++ b/api/server/services/Endpoints/assistants/title.test.js
@@ -2,6 +2,7 @@ const mockCache = {
set: jest.fn(),
};
const mockSaveConvo = jest.fn();
+const mockGetConvo = jest.fn();
const mockInitializeClient = jest.fn();
jest.mock('@librechat/api', () => ({
@@ -23,6 +24,7 @@ jest.mock(
);
jest.mock('~/models', () => ({
saveConvo: (...args) => mockSaveConvo(...args),
+ getConvo: (...args) => mockGetConvo(...args),
}));
const addTitle = require('./title');
@@ -30,6 +32,8 @@ const addTitle = require('./title');
describe('assistants addTitle content policy', () => {
beforeEach(() => {
jest.clearAllMocks();
+ mockSaveConvo.mockImplementation(async (_ctx, data) => data);
+ mockGetConvo.mockResolvedValue(null);
});
it('skips the title provider, cache, and save for a normalized temporary request', async () => {
@@ -118,4 +122,28 @@ describe('assistants addTitle content policy', () => {
expect.objectContaining({ noUpsert: true }),
);
});
+ it.each(['database', 'cache'])('owns a detached fallback %s failure', async (boundary) => {
+ mockInitializeClient.mockResolvedValue({
+ openai: {
+ chat: { completions: { create: jest.fn().mockRejectedValue(new Error('provider')) } },
+ },
+ });
+ const failure = new Error('secret-provider-payload');
+ if (boundary === 'database') mockSaveConvo.mockRejectedValueOnce(failure);
+ else mockCache.set.mockRejectedValueOnce(failure);
+ await expect(
+ addTitle(
+ { user: { id: 'user-1' }, body: {} },
+ {
+ text: 'fallback',
+ responseText: 'response',
+ conversationId: 'fallback-chat',
+ },
+ ),
+ ).resolves.toBeUndefined();
+ const { logger } = require('@librechat/data-schemas');
+ expect(logger.error).toHaveBeenCalledWith('[addTitle] Fallback publication failed', {
+ type: 'Error',
+ });
+ });
});
diff --git a/client/src/components/Conversations/Convo.tsx b/client/src/components/Conversations/Convo.tsx
index 6e2f38a488..c2615c4362 100644
--- a/client/src/components/Conversations/Convo.tsx
+++ b/client/src/components/Conversations/Convo.tsx
@@ -3,8 +3,8 @@ import { useDrag } from 'react-dnd';
import { Link2 } from 'lucide-react';
import { useRecoilValue } from 'recoil';
import { useParams } from 'react-router-dom';
-import { Constants } from 'librechat-data-provider';
import { Spinner, useToastContext, useMediaQuery } from '@librechat/client';
+import { Constants, supportsConversationTitleOwnership } from 'librechat-data-provider';
import type { TConversation } from 'librechat-data-provider';
import type { ConversationDragItem } from './dnd';
import {
@@ -12,7 +12,7 @@ import {
usePinConversationMutation,
useUpdateConversationMutation,
} from '~/data-provider';
-import { cn, logger, setDocumentTitle, isConversationUnseen } from '~/utils';
+import { cn, logger, setDocumentTitle, isConversationUnseen, hasRealTitle } from '~/utils';
import { useNavigateToConvo, useLocalize, useShiftKey } from '~/hooks';
import ConversationEndpointIcon from './ConversationEndpointIcon';
import { focusableInRow, resolveRowBeside } from './focus';
@@ -73,10 +73,14 @@ function Conversation({
const isUnseen = isConversationUnseen(conversation);
const isShiftHeld = useShiftKey();
const { conversationId, title = '' } = conversation;
+ const canRename =
+ supportsConversationTitleOwnership(startupConfig) ||
+ (!isGenerating && (conversation.titleSetByUser === true || hasRealTitle(title)));
const [titleInput, setTitleInput] = useState(title || '');
const [renaming, setRenamingState] = useState(false);
const [isPopoverActive, setIsPopoverActive] = useState(false);
+ const [contextMenuPosition, setContextMenuPosition] = useState<{ x: number; y: number }>();
const [isHovered, setIsHovered] = useState(false);
// Lazy-load ConvoOptions to avoid running heavy hooks for all conversations
const [hasInteracted, setHasInteracted] = useState(false);
@@ -139,13 +143,19 @@ function Conversation({
}, [currentConvoId, conversationId, activeConversationId]);
const handleRename = () => {
+ if (!canRename) return;
setIsPopoverActive(false);
+ setContextMenuPosition(undefined);
setTitleInput(title as string);
setRenaming(true);
};
const handleRenameSubmit = async (newTitle: string) => {
- if (!conversationId || newTitle === title) {
+ if (
+ !canRename ||
+ !conversationId ||
+ (newTitle === title && conversation.titleSetByUser === true)
+ ) {
setRenaming(false);
return;
}
@@ -233,6 +243,9 @@ function Conversation({
const handlePopoverOpenChange = useCallback((open: boolean) => {
setIsPopoverActive(open);
+ if (!open) {
+ setContextMenuPosition(undefined);
+ }
}, []);
const handleNavigation = (ctrlOrMetaKey: boolean) => {
@@ -268,13 +281,16 @@ function Conversation({
isArchived: conversation.isArchived === true,
retainView,
renameHandler: handleRename,
+ canRename,
isActiveConvo,
isUnseen,
conversationId,
chatProjectId: conversation.chatProjectId,
isPopoverActive,
+ isGenerating,
+ contextMenuPosition,
onOpenChange: handlePopoverOpenChange,
- isShiftHeld: isActiveConvo ? isShiftHeld : false,
+ isShiftHeld: isActiveConvo && !isGenerating ? isShiftHeld : false,
};
/* The slot takes its width from the row's hover, not from its content. The
@@ -288,7 +304,10 @@ function Conversation({
let actionWidthClassName = isSmallScreen
? 'group-focus-within:w-9 group-hover:w-9'
: 'group-focus-within:w-7 group-hover:w-7';
- if (isPopoverActive || isActiveConvo || isSmallScreen) {
+ if (isGenerating) {
+ actionVisibilityClassName = 'pointer-events-auto scale-x-100 opacity-100';
+ actionWidthClassName = isSmallScreen ? 'w-9' : 'w-7';
+ } else if (isPopoverActive || isActiveConvo || isSmallScreen) {
/** Touch has no hover, so a reveal-on-hover menu is unreachable there. */
actionVisibilityClassName = 'pointer-events-auto scale-x-100 opacity-100';
/** Shift over the active row swaps the menu for archive and delete. */
@@ -299,9 +318,9 @@ function Conversation({
}
}
- const actionContent = renaming ? null : (
+ const actionContent = !renaming ? (
<ConvoActions {...convoOptionsProps} hasInteracted={hasInteracted} />
- );
+ ) : null;
return (
<div
@@ -320,6 +339,20 @@ function Conversation({
}}
onPointerLeave={() => setIsHovered(false)}
onPointerCancel={() => setIsHovered(false)}
+ onContextMenu={(event) => {
+ if (
+ renaming ||
+ !(event.target instanceof Node) ||
+ !event.currentTarget.contains(event.target)
+ ) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ setContextMenuPosition({ x: event.clientX, y: event.clientY });
+ setHasInteracted(true);
+ setIsPopoverActive(true);
+ }}
onMouseEnter={handleMouseEnter}
onFocus={handleMouseEnter}
onClick={(e) => {
@@ -365,7 +398,7 @@ function Conversation({
size={34}
strokeWidth={1.9}
bgOpacity={0.14}
- className="text-text-primary pointer-events-none absolute -top-[7px] -left-[7px]"
+ className="pointer-events-none absolute -top-[7px] -left-[7px]"
/>
)}
{isUnseen && !isGenerating && (
diff --git a/client/src/components/Conversations/ConvoActions.tsx b/client/src/components/Conversations/ConvoActions.tsx
index 20c194ed79..c7619b7fb5 100644
--- a/client/src/components/Conversations/ConvoActions.tsx
+++ b/client/src/components/Conversations/ConvoActions.tsx
@@ -1,4 +1,4 @@
-import { memo, useState } from 'react';
+import { memo, useState, useEffect } from 'react';
import { Ellipsis } from 'lucide-react';
import { Button, useMediaQuery } from '@librechat/client';
import type { MouseEvent } from 'react';
@@ -9,12 +9,15 @@ export type ConvoActionsProps = {
conversationId: string | null;
chatProjectId?: string | null;
title: string | null;
+ canRename?: boolean;
isPinned?: boolean;
isArchived?: boolean;
isUnseen?: boolean;
isActiveConvo: boolean;
isShiftHeld?: boolean;
isPopoverActive: boolean;
+ isGenerating?: boolean;
+ contextMenuPosition?: { x: number; y: number };
/** True once the pointer or focus has reached the row. */
hasInteracted: boolean;
retainView: () => void;
@@ -53,6 +56,7 @@ function ConvoActions({
hasInteracted,
isActiveConvo,
isPopoverActive,
+ isGenerating = false,
onOpenChange,
...options
}: ConvoActionsProps) {
@@ -60,6 +64,12 @@ function ConvoActions({
const isSmallScreen = useMediaQuery('(max-width: 768px)');
const [hasOpenedMenu, setHasOpenedMenu] = useState(false);
+ useEffect(() => {
+ if (isPopoverActive) {
+ setHasOpenedMenu(true);
+ }
+ }, [isPopoverActive]);
+
const handleOpenChange = (open: boolean) => {
if (open) {
setHasOpenedMenu(true);
@@ -69,12 +79,13 @@ function ConvoActions({
const showMenu = isSmallScreen
? isPopoverActive || isActiveConvo || hasOpenedMenu
- : hasInteracted || isActiveConvo;
+ : isPopoverActive || hasOpenedMenu || hasInteracted || isActiveConvo;
if (showMenu) {
return (
<ConvoOptions
{...options}
+ isGenerating={isGenerating}
isActiveConvo={isActiveConvo}
isPopoverActive={isPopoverActive}
setIsPopoverActive={handleOpenChange}
@@ -82,7 +93,7 @@ function ConvoActions({
);
}
- if (!isSmallScreen) {
+ if (!isSmallScreen && !isGenerating) {
return null;
}
@@ -92,7 +103,7 @@ function ConvoActions({
variant="ghost"
aria-label={localize('com_nav_convo_menu_options')}
data-testid="convo-options-trigger"
- className="text-text-secondary size-9"
+ className="size-9"
onClick={(event) => {
event.stopPropagation();
handleOpenChange(true);
diff --git a/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx b/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
index f2eaae3b73..dda9660f31 100644
--- a/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
+++ b/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
@@ -56,10 +56,13 @@ function ConvoOptions({
isUnseen = false,
retainView,
renameHandler,
+ canRename = true,
isPopoverActive,
setIsPopoverActive,
isActiveConvo,
isShiftHeld = false,
+ isGenerating = false,
+ contextMenuPosition,
}: {
conversationId: string | null;
chatProjectId?: string | null;
@@ -70,10 +73,13 @@ function ConvoOptions({
isUnseen?: boolean;
retainView: () => void;
renameHandler: (e: MouseEvent) => void;
+ canRename?: boolean;
isPopoverActive: boolean;
setIsPopoverActive: (open: boolean) => void;
isActiveConvo: boolean;
isShiftHeld?: boolean;
+ isGenerating?: boolean;
+ contextMenuPosition?: { x: number; y: number };
}) {
const localize = useLocalize();
const queryClient = useQueryClient();
@@ -354,6 +360,7 @@ function ConvoOptions({
{
label: localize('com_ui_rename'),
onClick: renameHandler,
+ disabled: !canRename,
icon: <Pen className="icon-sm text-text-primary mr-2" aria-hidden="true" />,
},
{
@@ -414,6 +421,7 @@ function ConvoOptions({
shareHandler,
startupConfig,
renameHandler,
+ canRename,
deleteHandler,
isArchiveLoading,
isArchived,
@@ -431,7 +439,7 @@ function ConvoOptions({
);
const buttonClassName = rowActionClasses({
- visible: isActiveConvo === true || isPopoverActive || isSmallScreen,
+ visible: isActiveConvo === true || isPopoverActive || isSmallScreen || isGenerating,
});
if (isShiftHeld && isActiveConvo && !isPopoverActive && !showShareDialog && !showDeleteDialog) {
@@ -473,8 +481,13 @@ function ConvoOptions({
* `document.body` outside it.
*/
portal={true}
+ getAnchorRect={
+ contextMenuPosition ? () => ({ ...contextMenuPosition, width: 0, height: 0 }) : undefined
+ }
menuId={menuId}
focusLoop={true}
+ finalFocus={menuButtonRef}
+ autoFocusOnShow={true}
className="z-[125]"
unmountOnHide={true}
isOpen={isPopoverActive}
@@ -544,12 +557,15 @@ export default memo(ConvoOptions, (prevProps, nextProps) => {
return (
prevProps.conversationId === nextProps.conversationId &&
prevProps.title === nextProps.title &&
+ prevProps.canRename === nextProps.canRename &&
prevProps.chatProjectId === nextProps.chatProjectId &&
prevProps.isPinned === nextProps.isPinned &&
prevProps.isArchived === nextProps.isArchived &&
prevProps.isUnseen === nextProps.isUnseen &&
prevProps.isPopoverActive === nextProps.isPopoverActive &&
prevProps.isActiveConvo === nextProps.isActiveConvo &&
- prevProps.isShiftHeld === nextProps.isShiftHeld
+ prevProps.isShiftHeld === nextProps.isShiftHeld &&
+ prevProps.isGenerating === nextProps.isGenerating &&
+ prevProps.contextMenuPosition === nextProps.contextMenuPosition
);
});
diff --git a/client/src/components/Conversations/__tests__/Convo.status.spec.tsx b/client/src/components/Conversations/__tests__/Convo.status.spec.tsx
index f02f4e92e6..35762f4f97 100644
--- a/client/src/components/Conversations/__tests__/Convo.status.spec.tsx
+++ b/client/src/components/Conversations/__tests__/Convo.status.spec.tsx
@@ -50,6 +50,7 @@ jest.mock('~/utils', () => ({
logger: { error: jest.fn() },
setDocumentTitle: jest.fn(),
isConversationUnseen: () => mockIsUnseen,
+ hasRealTitle: (title: string) => !!title && title !== 'New Chat',
}));
jest.mock('../ConvoOptions', () => ({
@@ -103,8 +104,10 @@ describe('Conversation row status', () => {
expect(rowButton()).toHaveAccessibleName('com_ui_conversation_label, com_ui_generating');
/* The trailing slot used to hold the spinner in place of the menu, so a running chat
could not be renamed or archived from the list. */
- fireEvent.mouseEnter(screen.getByTestId('convo-item'));
+ fireEvent.contextMenu(screen.getByTestId('convo-item'));
expect(screen.getByTestId('convo-options')).toBeInTheDocument();
+ expect(screen.getAllByTestId('status-ring')).toHaveLength(1);
+ expect(rowButton()).toContainElement(ring);
});
it('marks an unseen reply on the avatar and in the title weight', () => {
diff --git a/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx b/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx
index 9d2933f1fb..1381ab5c4d 100644
--- a/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx
+++ b/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx
@@ -4,6 +4,9 @@ import { render, screen, fireEvent, act } from '@testing-library/react';
import type { TConversation } from 'librechat-data-provider';
let mockIsSmallScreen = true;
+let mockOwnershipEnabled = true;
+let mockOwnershipVersion: number | undefined = 1;
+const mockRename = jest.fn().mockResolvedValue({});
const mockConvoOptionsProps: { isPopoverActive: boolean }[] = [];
let mockCloseMenu: () => void = () => undefined;
@@ -23,8 +26,14 @@ jest.mock('~/hooks', () => ({
}));
jest.mock('~/data-provider', () => ({
- useGetStartupConfig: () => ({ data: { sharedLinksEnabled: false } }),
- useUpdateConversationMutation: () => ({ mutateAsync: jest.fn() }),
+ useGetStartupConfig: () => ({
+ data: {
+ sharedLinksEnabled: false,
+ interface: { runningChatRename: mockOwnershipEnabled },
+ conversationTitleOwnershipVersion: mockOwnershipVersion,
+ },
+ }),
+ useUpdateConversationMutation: () => ({ mutateAsync: mockRename }),
usePinConversationMutation: () => ({ mutate: jest.fn() }),
}));
@@ -45,13 +54,25 @@ jest.mock('~/utils', () => ({
cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),
logger: { error: jest.fn() },
isConversationUnseen: () => false,
+ hasRealTitle: (title: string) => !!title && title !== 'New Chat',
}));
jest.mock('../ConvoOptions', () => ({
- ConvoOptions: (props: { isPopoverActive: boolean; setIsPopoverActive: (o: boolean) => void }) => {
+ ConvoOptions: (props: {
+ isPopoverActive: boolean;
+ canRename: boolean;
+ renameHandler: () => void;
+ setIsPopoverActive: (o: boolean) => void;
+ }) => {
mockConvoOptionsProps.push(props);
mockCloseMenu = () => props.setIsPopoverActive(false);
- return <div data-testid="convo-options" data-open={props.isPopoverActive} />;
+ return (
+ <div data-testid="convo-options" data-open={props.isPopoverActive}>
+ <button disabled={!props.canRename} onClick={props.renameHandler}>
+ {'Rename'}
+ </button>
+ </div>
+ );
},
}));
@@ -67,7 +88,17 @@ jest.mock('../ConvoLink', () => ({
jest.mock('../RenameForm', () => ({
__esModule: true,
- default: () => <form data-testid="rename-form" />,
+ default: ({
+ titleInput,
+ onSubmit,
+ }: {
+ titleInput: string;
+ onSubmit: (title: string) => void;
+ }) => (
+ <button data-testid="rename-form" onClick={() => onSubmit(titleInput)}>
+ {'Save'}
+ </button>
+ ),
}));
import Conversation from '../Convo';
@@ -77,10 +108,15 @@ const conversation = {
title: 'Mobile UI redesign',
} as TConversation;
-const renderRow = () =>
+const renderRow = (isGenerating = false, row = conversation) =>
render(
<DndProvider backend={HTML5Backend}>
- <Conversation conversation={conversation} retainView={jest.fn()} toggleNav={jest.fn()} />
+ <Conversation
+ conversation={row}
+ isGenerating={isGenerating}
+ retainView={jest.fn()}
+ toggleNav={jest.fn()}
+ />
</DndProvider>,
);
@@ -157,3 +193,93 @@ describe('Conversation row on touch', () => {
expect(screen.queryByTestId('convo-options-trigger')).not.toBeInTheDocument();
});
});
+
+describe('Conversation context menu', () => {
+ beforeEach(() => {
+ mockConvoOptionsProps.length = 0;
+ mockIsSmallScreen = false;
+ });
+
+ it.each([false, true])('opens on right-click (generating: %s)', (isGenerating) => {
+ renderRow(isGenerating);
+ fireEvent.contextMenu(screen.getByTestId('convo-item'), { clientX: 120, clientY: 80 });
+ expect(screen.getByTestId('convo-options')).toHaveAttribute('data-open', 'true');
+ expect(mockConvoOptionsProps.at(-1)).toEqual(
+ expect.objectContaining({
+ isGenerating,
+ contextMenuPosition: { x: 120, y: 80 },
+ }),
+ );
+ act(() => mockCloseMenu());
+ expect(screen.getByTestId('convo-options')).toHaveAttribute('data-open', 'false');
+ expect(mockConvoOptionsProps.at(-1)).toEqual(
+ expect.objectContaining({ contextMenuPosition: undefined }),
+ );
+ });
+
+ it('offers a clickable running menu before hover', () => {
+ renderRow(true);
+ const trigger = screen.getByRole('button', { name: 'com_nav_convo_menu_options' });
+ expect(trigger).toBeVisible();
+ fireEvent.click(trigger);
+ expect(screen.getByTestId('convo-options')).toHaveAttribute('data-open', 'true');
+ });
+});
+
+describe('Conversation context menu on small screens', () => {
+ it('keeps the real trigger mounted after an externally opened menu closes', () => {
+ mockIsSmallScreen = true;
+ renderRow(true);
+ fireEvent.contextMenu(screen.getByTestId('convo-item'), { clientX: 120, clientY: 80 });
+ expect(screen.getByTestId('convo-options')).toHaveAttribute('data-open', 'true');
+ act(() => mockCloseMenu());
+ expect(screen.getByTestId('convo-options')).toBeInTheDocument();
+ expect(screen.queryByTestId('convo-options-trigger')).not.toBeInTheDocument();
+ });
+});
+
+describe('Conversation title ownership rollout', () => {
+ beforeEach(() => {
+ mockRename.mockClear();
+ mockOwnershipEnabled = true;
+ mockOwnershipVersion = 1;
+ });
+ afterEach(() => {
+ mockOwnershipEnabled = true;
+ mockOwnershipVersion = 1;
+ });
+
+ it.each([
+ [false, 1],
+ [true, undefined],
+ ])('disables rename on unsafe running rows (enabled %s, protocol %s)', (enabled, version) => {
+ mockOwnershipEnabled = enabled;
+ mockOwnershipVersion = version;
+ renderRow(true);
+ fireEvent.contextMenu(screen.getByTestId('convo-item'));
+ expect(screen.getByRole('button', { name: 'Rename' })).toBeDisabled();
+ });
+ it('also fences an unowned placeholder after a final-timing stream ends', () => {
+ mockOwnershipEnabled = false;
+ renderRow(false, { ...conversation, title: 'New Chat' });
+ fireEvent.contextMenu(screen.getByTestId('convo-item'));
+ expect(screen.getByRole('button', { name: 'Rename' })).toBeDisabled();
+ });
+ it.each([false, true])(
+ 'claims an unchanged unowned title (generating %s)',
+ async (generating) => {
+ renderRow(generating, { ...conversation, title: 'New Chat' });
+ fireEvent.contextMenu(screen.getByTestId('convo-item'));
+ fireEvent.click(screen.getByRole('button', { name: 'Rename' }));
+ await act(async () => fireEvent.click(screen.getByTestId('rename-form')));
+ expect(mockRename).toHaveBeenCalledWith({ conversationId: 'convo-1', title: 'New Chat' });
+ },
+ );
+ it('keeps unchanged owned titles as a no-op', async () => {
+ renderRow(false, { ...conversation, titleSetByUser: true });
+ fireEvent.contextMenu(screen.getByTestId('convo-item'));
+ fireEvent.click(screen.getByRole('button', { name: 'Rename' }));
+ await act(async () => fireEvent.click(screen.getByTestId('rename-form')));
+ expect(mockRename).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx b/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx
index 9ba577f8f8..283749f060 100644
--- a/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx
+++ b/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx
@@ -57,6 +57,7 @@ jest.mock('~/store', () => ({
}));
jest.mock('~/utils', () => ({
+ hasRealTitle: (title: string) => !!title && title !== 'New Chat',
cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),
logger: { error: jest.fn() },
setDocumentTitle: jest.fn(),
diff --git a/client/src/data-provider/SSE/__tests__/useTitleGeneration.test.ts b/client/src/data-provider/SSE/__tests__/useTitleGeneration.test.ts
index 2408a37ac8..60505f317a 100644
--- a/client/src/data-provider/SSE/__tests__/useTitleGeneration.test.ts
+++ b/client/src/data-provider/SSE/__tests__/useTitleGeneration.test.ts
@@ -17,15 +17,17 @@ let mockTiming: 'immediate' | 'final' = 'immediate';
let mockQueriesResults: Array<{
isSuccess?: boolean;
isError?: boolean;
- data?: { title: string };
+ data?: { title: string; titleSetByUser?: boolean; titleRevision?: number };
error?: unknown;
}> = [];
let mockCapturedQueries: Array<{ queryKey: unknown[] }> = [];
const mockSetQueryData = jest.fn();
+const mockGetQueryData = jest.fn();
const mockRemoveQueries = jest.fn();
const mockResetQueries = jest.fn();
const mockUpdateConvoInAllQueries = jest.fn();
+const mockFindManualTitle = jest.fn();
jest.mock('@tanstack/react-query', () => ({
useQuery: jest.fn(() => ({ data: { activeJobIds: mockActiveJobIds } })),
@@ -35,6 +37,7 @@ jest.mock('@tanstack/react-query', () => ({
}),
useQueryClient: jest.fn(() => ({
setQueryData: mockSetQueryData,
+ getQueryData: mockGetQueryData,
removeQueries: mockRemoveQueries,
resetQueries: mockResetQueries,
})),
@@ -45,6 +48,7 @@ jest.mock('../../Endpoints', () => ({
}));
jest.mock('~/utils', () => ({
+ findManualConvoTitleInAllQueries: (...args: unknown[]) => mockFindManualTitle(...args),
isNotFoundError: (error: unknown): boolean => {
if (error != null && typeof error === 'object') {
return (error as { response?: { status?: number } }).response?.status === 404;
@@ -81,6 +85,18 @@ beforeEach(() => {
mockQueriesResults = [];
mockCapturedQueries = [];
jest.clearAllMocks();
+ mockGetQueryData.mockReset();
+ mockFindManualTitle.mockReset().mockImplementation((_client, id, incoming) => {
+ const cached = mockGetQueryData(['conversation', id]);
+ if (
+ cached?.titleSetByUser &&
+ cached.title != null &&
+ (!incoming.titleSetByUser || (cached.titleRevision ?? 0) > (incoming.titleRevision ?? 0))
+ ) {
+ return cached;
+ }
+ return incoming.titleSetByUser ? incoming : undefined;
+ });
});
describe('useTitleGeneration — eligibility', () => {
@@ -124,6 +140,66 @@ describe('useTitleGeneration — eligibility', () => {
});
describe('useTitleGeneration — result handling', () => {
+ it('keeps a persisted manual title when an old title poll resolves', () => {
+ const id = 'conv-manual-poll';
+ const owned = { title: 'New Chat', titleSetByUser: true };
+ mockGetQueryData.mockImplementation((key: string[]) => (key[1] === id ? owned : undefined));
+ const { rerender } = renderHook(() => useTitleGeneration(true));
+ act(() => queueTitleGeneration(id));
+ mockQueriesResults = [{ isSuccess: true, data: { title: 'Old generated title' } }];
+ rerender();
+ const call = mockSetQueryData.mock.calls.find(([key]) => key[1] === id);
+ const updater = call?.[1] as (value: typeof owned) => typeof owned;
+ expect(updater(owned)).toEqual(owned);
+ });
+
+ it.each([
+ [1, 2],
+ [3, 2],
+ ])('orders polled manual revisions (cache %s, poll %s)', (cachedRevision, polledRevision) => {
+ const id = `manual-poll-${cachedRevision}-${polledRevision}`;
+ const cached = { title: 'Cached rename', titleSetByUser: true, titleRevision: cachedRevision };
+ mockGetQueryData.mockImplementation((key: string[]) => (key[1] === id ? cached : undefined));
+ const { rerender } = renderHook(() => useTitleGeneration(true));
+ act(() => queueTitleGeneration(id));
+ mockQueriesResults = [
+ {
+ isSuccess: true,
+ data: { title: 'Polled rename', titleSetByUser: true, titleRevision: polledRevision },
+ },
+ ];
+ rerender();
+ const update = mockSetQueryData.mock.calls.find(([key]) => key[1] === id)?.[1];
+ const expected =
+ polledRevision >= cachedRevision
+ ? { title: 'Polled rename', titleSetByUser: true, titleRevision: polledRevision }
+ : cached;
+ expect(update(cached)).toEqual(expected);
+ const updateLists = mockUpdateConvoInAllQueries.mock.calls.find(([, key]) => key === id)?.[2];
+ expect(updateLists(cached)).toEqual(expected);
+ expect(isEligible(id)).toBe(false);
+ });
+
+ it('propagates the highest cached manual revision instead of an older poll', () => {
+ const id = 'manual-list-poll';
+ const newest = { title: 'List rename', titleSetByUser: true, titleRevision: 3 };
+ mockFindManualTitle.mockReturnValue(newest);
+ const { rerender } = renderHook(() => useTitleGeneration(true));
+ act(() => queueTitleGeneration(id));
+ mockQueriesResults = [
+ { isSuccess: true, data: { title: 'Point rename', titleSetByUser: true, titleRevision: 2 } },
+ ];
+ rerender();
+ const update = mockSetQueryData.mock.calls.find(([key]) => key[1] === id)?.[1];
+ expect(update({ title: 'Point rename', titleSetByUser: true, titleRevision: 2 })).toEqual(
+ newest,
+ );
+ const updateLists = mockUpdateConvoInAllQueries.mock.calls.find(([, key]) => key === id)?.[2];
+ expect(updateLists({ title: 'Other rename', titleSetByUser: true, titleRevision: 1 })).toEqual(
+ newest,
+ );
+ });
+
it('applies the fetched title to the conversation caches on success', () => {
mockTiming = 'immediate';
mockActiveJobIds = ['conv-ok'];
diff --git a/client/src/data-provider/SSE/queries.ts b/client/src/data-provider/SSE/queries.ts
index eca82371d8..e3048181ed 100644
--- a/client/src/data-provider/SSE/queries.ts
+++ b/client/src/data-provider/SSE/queries.ts
@@ -2,7 +2,12 @@ import { useEffect, useMemo, useState } from 'react';
import { useQuery, useQueries, useQueryClient } from '@tanstack/react-query';
import { apiBaseUrl, QueryKeys, request, dataService } from 'librechat-data-provider';
import type { Agents, TConversation, TPendingSteer } from 'librechat-data-provider';
-import { isNotFoundError, updateConvoInAllQueries, setDocumentTitle } from '~/utils';
+import {
+ isNotFoundError,
+ updateConvoInAllQueries,
+ setDocumentTitle,
+ findManualConvoTitleInAllQueries,
+} from '~/utils';
import { generationProtocolHeaders, withGenerationProtocolQuery } from './protocol';
import { useGetStartupConfig } from '../Endpoints';
@@ -77,12 +82,16 @@ const queueListeners = new Set<() => void>();
/** Queue a conversation for title generation (call when starting new conversation) */
export function queueTitleGeneration(conversationId: string) {
- if (!processedTitles.has(conversationId)) {
+ if (!isTitleGenerationProcessed(conversationId)) {
titleQueue.add(conversationId);
queueListeners.forEach((listener) => listener());
}
}
+export function isTitleGenerationProcessed(conversationId: string): boolean {
+ return processedTitles.has(conversationId);
+}
+
export function markTitleGenerationProcessed(conversationId: string) {
processedTitles.add(conversationId);
titleQueue.delete(conversationId);
@@ -177,12 +186,18 @@ export function useTitleGeneration(enabled = true) {
}
if (titleQuery.isSuccess && titleQuery.data) {
- const { title } = titleQuery.data;
- queryClient.setQueryData(
+ const incoming = titleQuery.data;
+ const titleState =
+ findManualConvoTitleInAllQueries(queryClient, conversationId, incoming) ?? incoming;
+ const applyTitle = (convo: TConversation): TConversation => ({ ...convo, ...titleState });
+ queryClient.setQueryData<TConversation>(
[QueryKeys.conversation, conversationId],
- (convo: TConversation | undefined) => (convo ? { ...convo, title } : convo),
+ (convo) => (convo ? applyTitle(convo) : convo),
);
- updateConvoInAllQueries(queryClient, conversationId, (c) => ({ ...c, title }));
+ updateConvoInAllQueries(queryClient, conversationId, applyTitle);
+ const title =
+ queryClient.getQueryData<TConversation>([QueryKeys.conversation, conversationId])
+ ?.title ?? incoming.title;
// Only update document title if this conversation is currently active
if (window.location.pathname.includes(conversationId)) {
setDocumentTitle(title);
diff --git a/client/src/data-provider/__tests__/renameConversation.spec.tsx b/client/src/data-provider/__tests__/renameConversation.spec.tsx
index d4bb1d3e58..199368c8c2 100644
--- a/client/src/data-provider/__tests__/renameConversation.spec.tsx
+++ b/client/src/data-provider/__tests__/renameConversation.spec.tsx
@@ -1,7 +1,7 @@
import { RecoilRoot } from 'recoil';
import { renderHook, act } from '@testing-library/react';
import { QueryKeys, dataService } from 'librechat-data-provider';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { QueryClient, QueryClientProvider, isCancelledError } from '@tanstack/react-query';
import type { TConversation } from 'librechat-data-provider';
import type { ReactNode } from 'react';
import { useUpdateConversationMutation } from '../mutations';
@@ -82,4 +82,129 @@ describe('useUpdateConversationMutation', () => {
expect(cached?.title).toBe('Fresh');
expect(cached?.chatProjectId).toBe('project-a');
});
+ it.each([true, false])('fences a delayed point read (warm cache: %s)', async (warm) => {
+ const { result } = renderHook(() => useUpdateConversationMutation('refreshing'), { wrapper });
+ const key = [QueryKeys.conversation, 'refreshing'];
+ const old = { conversationId: 'refreshing', title: 'Old' } as TConversation;
+ if (warm) activeQueryClient.setQueryData(key, old);
+ let release!: (value: TConversation) => void;
+ const delayed = activeQueryClient
+ .fetchQuery(
+ key,
+ () =>
+ new Promise<TConversation>((resolve) => {
+ release = resolve;
+ }),
+ )
+ .catch((error) => isCancelledError(error));
+ updateConversation.mockResolvedValueOnce({
+ ...old,
+ title: 'Renamed',
+ titleSetByUser: true,
+ titleRevision: 1,
+ });
+ await act(async () =>
+ result.current.mutateAsync({ conversationId: 'refreshing', title: 'Renamed' }),
+ );
+ expect(await delayed).toBe(true);
+ release(old);
+ await act(async () => Promise.resolve());
+ expect(activeQueryClient.getQueryData<TConversation>(key)).toEqual(
+ expect.objectContaining({
+ title: 'Renamed',
+ titleSetByUser: true,
+ }),
+ );
+ });
+ it('does not publish ownership when the rename response is invalid', async () => {
+ const { result } = renderHook(() => useUpdateConversationMutation('invalid-rename'), {
+ wrapper,
+ });
+ const key = [QueryKeys.conversation, 'invalid-rename'];
+ const old = { conversationId: 'invalid-rename', title: 'Old' } as TConversation;
+ activeQueryClient.setQueryData(key, old);
+ updateConversation.mockResolvedValueOnce({ ...old, title: null });
+ await act(async () => {
+ await expect(
+ result.current.mutateAsync({ conversationId: 'invalid-rename', title: 'New' }),
+ ).rejects.toThrow('Conversation rename did not return a title');
+ });
+ expect(activeQueryClient.getQueryData(key)).toEqual(old);
+ });
+ it('does not let an older rename response roll back a newer committed revision', async () => {
+ const { result } = renderHook(() => useUpdateConversationMutation('revision-chat'), {
+ wrapper,
+ });
+ const key = [QueryKeys.conversation, 'revision-chat'];
+ const current = {
+ conversationId: 'revision-chat',
+ title: 'Newer rename',
+ titleSetByUser: true,
+ titleRevision: 3,
+ } as TConversation;
+ activeQueryClient.setQueryData(key, current);
+ updateConversation.mockResolvedValueOnce({
+ ...current,
+ title: 'Older rename',
+ titleRevision: 2,
+ });
+ await act(async () =>
+ result.current.mutateAsync({ conversationId: 'revision-chat', title: 'Older rename' }),
+ );
+ expect(activeQueryClient.getQueryData(key)).toEqual(current);
+ });
+ it('accepts the first durable revision after a legacy rename response', async () => {
+ const { result } = renderHook(() => useUpdateConversationMutation('rolling-chat'), { wrapper });
+ const key = [QueryKeys.conversation, 'rolling-chat'];
+ const base = { conversationId: 'rolling-chat', title: 'Old' } as TConversation;
+ activeQueryClient.setQueryData(key, base);
+ updateConversation.mockResolvedValueOnce({ ...base, title: 'Legacy rename' });
+ await act(async () =>
+ result.current.mutateAsync({ conversationId: 'rolling-chat', title: 'Legacy rename' }),
+ );
+ expect(activeQueryClient.getQueryData<TConversation>(key)?.titleRevision).toBeUndefined();
+ expect(activeQueryClient.getQueryData<TConversation>(key)?.titleSetByUser).toBeUndefined();
+ updateConversation.mockResolvedValueOnce({
+ ...base,
+ title: 'Upgraded rename',
+ titleSetByUser: true,
+ titleRevision: 1,
+ });
+ await act(async () =>
+ result.current.mutateAsync({ conversationId: 'rolling-chat', title: 'Upgraded rename' }),
+ );
+ expect(activeQueryClient.getQueryData(key)).toEqual(
+ expect.objectContaining({
+ title: 'Upgraded rename',
+ titleSetByUser: true,
+ titleRevision: 1,
+ }),
+ );
+ });
+ it('does not invent ownership when a legacy replica omits its metadata', async () => {
+ const { result } = renderHook(() => useUpdateConversationMutation('legacy-rename'), {
+ wrapper,
+ });
+ const key = [QueryKeys.conversation, 'legacy-rename'];
+ activeQueryClient.setQueryData(key, {
+ conversationId: 'legacy-rename',
+ title: 'Before',
+ titleSetByUser: true,
+ titleRevision: 1,
+ });
+ updateConversation.mockResolvedValueOnce({
+ conversationId: 'legacy-rename',
+ title: 'Legacy saved',
+ } as TConversation);
+ await act(async () =>
+ result.current.mutateAsync({ conversationId: 'legacy-rename', title: 'Legacy saved' }),
+ );
+ expect(activeQueryClient.getQueryData(key)).toEqual(
+ expect.objectContaining({
+ title: 'Legacy saved',
+ titleSetByUser: undefined,
+ titleRevision: undefined,
+ }),
+ );
+ });
});
diff --git a/client/src/data-provider/mutations.ts b/client/src/data-provider/mutations.ts
index 2ece6b7749..5909305a05 100644
--- a/client/src/data-provider/mutations.ts
+++ b/client/src/data-provider/mutations.ts
@@ -31,6 +31,7 @@ import useUpdateTagsInConvo from '~/hooks/Conversations/useUpdateTagsInConvo';
import { chatFilterTagsAtom } from '~/components/Conversations/chatFilters';
import { updateConversationTag } from '~/utils/conversationTags';
import { isTemporaryConversation } from '~/utils/conversation';
+import { markTitleGenerationProcessed } from './SSE/queries';
import { useConversationTagsQuery } from './queries';
export const useUpdateConversationMutation = (
@@ -46,16 +47,35 @@ export const useUpdateConversationMutation = (
(payload: t.TUpdateConversationRequest) => dataService.updateConversation(payload),
{
onSuccess: (updatedConvo, payload) => {
+ if (typeof updatedConvo.title !== 'string') {
+ throw new Error('Conversation rename did not return a title');
+ }
const targetId = payload.conversationId || id;
+ void queryClient.cancelQueries(
+ { queryKey: [QueryKeys.conversation, targetId], exact: true },
+ { revert: false },
+ );
+ markTitleGenerationProcessed(targetId);
/* A rename carries only a title, so only the title is taken from its
* response. Writing the whole conversation would also restore its
* pre-request copy of every other field, undoing a concurrent change
* whose response happened to land first: an assignment moving the chat
* to another project would silently revert here. */
- const applyRename = (previous?: t.TConversation): t.TConversation =>
- previous
- ? { ...previous, title: updatedConvo.title, updatedAt: updatedConvo.updatedAt }
- : updatedConvo;
+ const applyRename = (previous?: t.TConversation): t.TConversation => {
+ if (
+ previous &&
+ (previous.titleRevision ?? 0) > (updatedConvo.titleRevision ?? Infinity)
+ ) {
+ return previous;
+ }
+ return {
+ ...(previous ?? updatedConvo),
+ title: updatedConvo.title,
+ titleSetByUser: updatedConvo.titleSetByUser,
+ titleRevision: updatedConvo.titleRevision,
+ updatedAt: updatedConvo.updatedAt,
+ };
+ };
queryClient.setQueryData<t.TConversation>([QueryKeys.conversation, targetId], applyRename);
updateConvoInAllQueries(queryClient, targetId, applyRename);
/* A title-keyset cursor encodes the old ordering; patching loaded rows
diff --git a/client/src/hooks/Conversations/useNavigateToConvo.tsx b/client/src/hooks/Conversations/useNavigateToConvo.tsx
index 90168c94ae..5787a7f348 100644
--- a/client/src/hooks/Conversations/useNavigateToConvo.tsx
+++ b/client/src/hooks/Conversations/useNavigateToConvo.tsx
@@ -1,7 +1,7 @@
import { useCallback } from 'react';
import { useSetRecoilState } from 'recoil';
import { useNavigate } from 'react-router-dom';
-import { useQueryClient } from '@tanstack/react-query';
+import { useQueryClient, isCancelledError } from '@tanstack/react-query';
import {
QueryKeys,
Constants,
@@ -167,6 +167,9 @@ const useNavigateToConvo = (index = 0) => {
spec: data.spec,
}));
} catch (error) {
+ if (isCancelledError(error)) {
+ return;
+ }
logger.error('conversation', 'Error refreshing conversation record on navigation', error);
/** Only a conversation that is confirmed GONE invalidates what is on
* screen. The messages query is already mounted by now, so dropping its
@@ -205,11 +208,22 @@ const useNavigateToConvo = (index = 0) => {
record = await fetchConversationRecord(conversationId);
logger.log('conversation', 'Fetched fresh conversation data', record);
} catch (error) {
- logger.error('conversation', 'Error fetching conversation data on navigation', error);
- /** Nothing is mounted for this conversation yet, so clearing a warm
- * cache here still predates the route change: the target mounts a fresh
- * query rather than rendering contents that may no longer exist. */
- queryClient.removeQueries([QueryKeys.messages, conversationId]);
+ if (isCancelledError(error)) {
+ const committed = queryClient.getQueryData<TConversation>([
+ QueryKeys.conversation,
+ conversationId,
+ ]);
+ if (!committed) {
+ return;
+ }
+ record = committed;
+ } else {
+ logger.error('conversation', 'Error fetching conversation data on navigation', error);
+ /** Nothing is mounted for this conversation yet, so clearing a warm
+ * cache here still predates the route change: the target mounts a fresh
+ * query rather than rendering contents that may no longer exist. */
+ queryClient.removeQueries([QueryKeys.messages, conversationId]);
+ }
}
if (generation !== navigationGeneration || currentRoute() !== routeAtStart) {
logger.log('conversation', 'Discarding superseded navigation', conversationId);
diff --git a/client/src/hooks/SSE/__tests__/titles.spec.tsx b/client/src/hooks/SSE/__tests__/titles.spec.tsx
new file mode 100644
index 0000000000..4602270c25
--- /dev/null
+++ b/client/src/hooks/SSE/__tests__/titles.spec.tsx
@@ -0,0 +1,407 @@
+import { useState } from 'react';
+import { Provider } from 'jotai';
+import { RecoilRoot } from 'recoil';
+import { MemoryRouter } from 'react-router-dom';
+import { act, renderHook } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { Constants, EModelEndpoint, QueryKeys } from 'librechat-data-provider';
+import type { EventSubmission, TConversation } from 'librechat-data-provider';
+import { markTitleGenerationProcessed } from '~/data-provider/SSE/queries';
+import useEventHandlers from '../useEventHandlers';
+
+jest.mock('~/hooks/Agents', () => ({ useApplyAgentTemplate: () => jest.fn() }));
+jest.mock('~/hooks/AuthContext', () => ({ useAuthContext: () => ({ token: 'test' }) }));
+jest.mock('~/Providers', () => ({ useLiveAnnouncer: () => ({ announcePolite: jest.fn() }) }));
+jest.mock('../useContentHandler', () => () => ({}));
+jest.mock('../useAttachmentHandler', () => () => jest.fn());
+jest.mock('../useStepHandler', () => () => ({
+ resetSubagentAtoms: jest.fn(),
+ resetPtcAtoms: jest.fn(),
+}));
+
+const initialConversation = {
+ conversationId: 'saved-chat',
+ endpoint: EModelEndpoint.agents,
+ title: 'Old title',
+} as TConversation;
+const submission: EventSubmission = {
+ isTemporary: false,
+ endpointOption: { endpoint: EModelEndpoint.agents },
+ conversation: initialConversation,
+ messages: [],
+ userMessage: {
+ messageId: 'user-1',
+ text: 'Hello',
+ sender: 'User',
+ isCreatedByUser: true,
+ parentMessageId: 'previous-reply',
+ conversationId: 'saved-chat',
+ },
+ initialResponse: {
+ messageId: 'response-1',
+ parentMessageId: 'user-1',
+ conversationId: 'saved-chat',
+ text: '',
+ sender: 'Assistant',
+ isCreatedByUser: false,
+ },
+};
+
+function setup() {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ queryClient.setQueryData([QueryKeys.conversation, 'saved-chat'], initialConversation);
+ queryClient.setQueryData([QueryKeys.allConversations], {
+ pages: [{ conversations: [initialConversation], nextCursor: null }],
+ pageParams: [],
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={queryClient}>
+ <Provider>
+ <RecoilRoot>
+ <MemoryRouter initialEntries={['/c/saved-chat']}>{children}</MemoryRouter>
+ </RecoilRoot>
+ </Provider>
+ </QueryClientProvider>
+ );
+ const hook = renderHook(
+ () => {
+ const [conversation, setConversation] = useState<TConversation | null>(initialConversation);
+ const handlers = useEventHandlers({
+ setConversation,
+ setMessages: jest.fn(),
+ getMessages: () => [submission.userMessage, submission.initialResponse],
+ setCompleted: jest.fn(),
+ setIsSubmitting: jest.fn(),
+ setShowStopButton: jest.fn(),
+ });
+ return { conversation, ...handlers };
+ },
+ { wrapper },
+ );
+ const rename = (title: string) => {
+ queryClient.setQueryData([QueryKeys.conversation, 'saved-chat'], {
+ ...initialConversation,
+ title,
+ titleSetByUser: true,
+ });
+ };
+ return { ...hook, queryClient, rename };
+}
+
+describe('stream title reconciliation', () => {
+ it.each(['created', 'sync'] as const)(
+ 'keeps a rename on %s, even with a root parent',
+ (frame) => {
+ const { result, rename } = setup();
+ rename('Renamed chat');
+ const rootSubmission = {
+ ...submission,
+ userMessage: { ...submission.userMessage, parentMessageId: String(Constants.NO_PARENT) },
+ };
+ act(() => {
+ if (frame === 'created') {
+ result.current.createdHandler(
+ { created: true, message: rootSubmission.userMessage },
+ rootSubmission,
+ );
+ } else {
+ result.current.syncHandler(
+ {
+ sync: true,
+ conversationId: 'saved-chat',
+ thread_id: 'thread',
+ requestMessage: rootSubmission.userMessage,
+ responseMessage: rootSubmission.initialResponse,
+ },
+ rootSubmission,
+ );
+ }
+ });
+ expect(result.current.conversation?.title).toBe('Renamed chat');
+ },
+ );
+
+ it.each(['Old title', 'New Chat', null])(
+ 'keeps an in-flight rename over final title %s',
+ (title) => {
+ const { result, queryClient, rename } = setup();
+ act(() =>
+ result.current.createdHandler(
+ { created: true, message: submission.userMessage },
+ submission,
+ ),
+ );
+ rename('Renamed while running');
+ act(() =>
+ result.current.finalHandler(
+ {
+ conversation: { ...initialConversation, title },
+ requestMessage: submission.userMessage,
+ responseMessage: { ...submission.initialResponse, text: 'Finished reply' },
+ },
+ submission,
+ ),
+ );
+ expect(result.current.conversation?.title).toBe('Renamed while running');
+ expect(
+ queryClient.getQueryData<TConversation>([QueryKeys.conversation, 'saved-chat'])?.title,
+ ).toBe('Renamed while running');
+ },
+ );
+
+ it('ignores a pending or replayed automatic title after an explicit rename', () => {
+ const { result, queryClient, rename } = setup();
+ rename('New Chat');
+ markTitleGenerationProcessed('saved-chat');
+ act(() =>
+ result.current.titleHandler({
+ event: 'title',
+ data: { conversationId: 'saved-chat', title: 'Late generated title' },
+ }),
+ );
+ expect(
+ queryClient.getQueryData<TConversation>([QueryKeys.conversation, 'saved-chat'])?.title,
+ ).toBe('New Chat');
+ });
+
+ it('does not replace a manual title when an old title event is replayed after reload', () => {
+ const { result, queryClient } = setup();
+ queryClient.setQueryData([QueryKeys.conversation, 'saved-chat'], {
+ ...initialConversation,
+ title: 'New Chat',
+ titleSetByUser: true,
+ });
+ act(() =>
+ result.current.titleHandler({
+ event: 'title',
+ data: { conversationId: 'saved-chat', title: 'Old generated title' },
+ }),
+ );
+ expect(
+ queryClient.getQueryData<TConversation>([QueryKeys.conversation, 'saved-chat'])?.title,
+ ).toBe('New Chat');
+ });
+
+ it('accepts a server-owned rename over an unowned stale point record', () => {
+ const { result } = setup();
+ act(() =>
+ result.current.finalHandler(
+ {
+ conversation: { ...initialConversation, title: 'Persisted rename', titleSetByUser: true },
+ requestMessage: submission.userMessage,
+ responseMessage: { ...submission.initialResponse, text: 'Finished reply' },
+ },
+ submission,
+ ),
+ );
+ expect(result.current.conversation?.title).toBe('Persisted rename');
+ });
+
+ it.each([
+ [1, 2],
+ [3, 2],
+ ])(
+ 'chooses the newer manual revision (cache %s, server %s)',
+ (cachedRevision, serverRevision) => {
+ const { result, queryClient } = setup();
+ queryClient.setQueryData([QueryKeys.conversation, 'saved-chat'], {
+ ...initialConversation,
+ title: 'Cached rename',
+ titleSetByUser: true,
+ titleRevision: cachedRevision,
+ });
+ act(() =>
+ result.current.finalHandler(
+ {
+ conversation: {
+ ...initialConversation,
+ title: 'Remote rename',
+ titleSetByUser: true,
+ titleRevision: serverRevision,
+ },
+ requestMessage: submission.userMessage,
+ responseMessage: { ...submission.initialResponse, text: 'Finished reply' },
+ },
+ submission,
+ ),
+ );
+ const expected = {
+ title: serverRevision >= cachedRevision ? 'Remote rename' : 'Cached rename',
+ titleSetByUser: true,
+ titleRevision: Math.max(cachedRevision, serverRevision),
+ };
+ expect(result.current.conversation).toEqual(expect.objectContaining(expected));
+ expect(queryClient.getQueryData([QueryKeys.conversation, 'saved-chat'])).toEqual(
+ expect.objectContaining(expected),
+ );
+ expect(
+ queryClient.getQueryData<{ pages: { conversations: TConversation[] }[] }>([
+ QueryKeys.allConversations,
+ ])?.pages[0].conversations[0],
+ ).toEqual(expect.objectContaining(expected));
+ },
+ );
+
+ it('preserves a sidebar-only manual placeholder on a replayed title event', () => {
+ const { result, queryClient } = setup();
+ queryClient.removeQueries([QueryKeys.conversation, 'saved-chat']);
+ queryClient.setQueryData([QueryKeys.allConversations], {
+ pages: [
+ {
+ conversations: [
+ { ...initialConversation, title: 'New Chat', titleSetByUser: true, titleRevision: 1 },
+ ],
+ nextCursor: null,
+ },
+ ],
+ pageParams: [],
+ });
+ act(() =>
+ result.current.titleHandler({
+ event: 'title',
+ data: { conversationId: 'saved-chat', title: 'Old generated title' },
+ }),
+ );
+ expect(result.current.conversation?.title).toBe('New Chat');
+ expect(
+ queryClient.getQueryData<{ pages: { conversations: TConversation[] }[] }>([
+ QueryKeys.allConversations,
+ ])?.pages[0].conversations[0],
+ ).toEqual(
+ expect.objectContaining({
+ title: 'New Chat',
+ titleSetByUser: true,
+ titleRevision: 1,
+ }),
+ );
+ });
+
+ it('accepts a newer remote rename to the default placeholder', () => {
+ const { result, queryClient } = setup();
+ queryClient.setQueryData([QueryKeys.conversation, 'saved-chat'], {
+ ...initialConversation,
+ title: 'First rename',
+ titleSetByUser: true,
+ titleRevision: 1,
+ });
+ act(() =>
+ result.current.finalHandler(
+ {
+ conversation: {
+ ...initialConversation,
+ title: 'New Chat',
+ titleSetByUser: true,
+ titleRevision: 2,
+ },
+ requestMessage: submission.userMessage,
+ responseMessage: { ...submission.initialResponse, text: 'Finished reply' },
+ },
+ submission,
+ ),
+ );
+ expect(result.current.conversation).toEqual(
+ expect.objectContaining({
+ title: 'New Chat',
+ titleSetByUser: true,
+ titleRevision: 2,
+ }),
+ );
+ });
+
+ it('accepts an authoritative legacy final title over an unowned stale cache', () => {
+ const { result, queryClient } = setup();
+ act(() =>
+ result.current.finalHandler(
+ {
+ conversation: { ...initialConversation, title: 'Legacy remote rename' },
+ requestMessage: submission.userMessage,
+ responseMessage: { ...submission.initialResponse, text: 'Finished reply' },
+ },
+ submission,
+ ),
+ );
+ expect(result.current.conversation?.title).toBe('Legacy remote rename');
+ expect(
+ queryClient.getQueryData<TConversation>([QueryKeys.conversation, 'saved-chat'])?.title,
+ ).toBe('Legacy remote rename');
+ });
+
+ it('does not propagate an older owned point snapshot over a newer list rename', async () => {
+ const { result, queryClient } = setup();
+ queryClient.clear();
+ const old = {
+ ...initialConversation,
+ title: 'Old owned title',
+ titleSetByUser: true,
+ titleRevision: 1,
+ lastResponseAt: '2026-08-16T10:05:00.000Z',
+ };
+ await queryClient.fetchQuery([QueryKeys.allConversations], async () => ({
+ pages: [
+ {
+ conversations: [{ ...old, title: 'New owned title', titleRevision: 2 }],
+ nextCursor: null,
+ },
+ ],
+ pageParams: [],
+ }));
+ await queryClient.fetchQuery([QueryKeys.conversation, 'saved-chat'], async () => old);
+ act(() =>
+ result.current.finalHandler(
+ {
+ conversation: old,
+ requestMessage: submission.userMessage,
+ responseMessage: { ...submission.initialResponse, text: 'Finished reply' },
+ },
+ submission,
+ ),
+ );
+ const expected = { title: 'New owned title', titleSetByUser: true, titleRevision: 2 };
+ expect(result.current.conversation).toEqual(expect.objectContaining(expected));
+ expect(queryClient.getQueryData([QueryKeys.conversation, 'saved-chat'])).toEqual(
+ expect.objectContaining(expected),
+ );
+ expect(
+ queryClient.getQueryData<{ pages: { conversations: TConversation[] }[] }>([
+ QueryKeys.allConversations,
+ ])?.pages[0].conversations[0],
+ ).toEqual(expect.objectContaining(expected));
+ });
+
+ it('does not mistake a processed automatic title for a manual placeholder rename', () => {
+ const { result, queryClient } = setup();
+ markTitleGenerationProcessed('saved-chat');
+ queryClient.clear();
+ queryClient.setQueryData([QueryKeys.conversation, 'saved-chat'], {
+ ...initialConversation,
+ title: 'New Chat',
+ });
+ act(() =>
+ result.current.finalHandler(
+ {
+ conversation: { ...initialConversation, title: 'Generated title' },
+ requestMessage: submission.userMessage,
+ responseMessage: { ...submission.initialResponse, text: 'Finished reply' },
+ },
+ submission,
+ ),
+ );
+ expect(result.current.conversation?.title).toBe('Generated title');
+ });
+
+ it('accepts the final server title when no local title is available', () => {
+ const { result, queryClient } = setup();
+ queryClient.clear();
+ act(() =>
+ result.current.finalHandler(
+ {
+ conversation: { conversationId: 'new-saved-chat', title: 'Generated title' },
+ requestMessage: submission.userMessage,
+ responseMessage: { ...submission.initialResponse, text: 'Finished reply' },
+ },
+ submission,
+ ),
+ );
+ expect(result.current.conversation?.title).toBe('Generated title');
+ });
+});
diff --git a/client/src/hooks/SSE/__tests__/useEventHandlers.cancel.spec.tsx b/client/src/hooks/SSE/__tests__/useEventHandlers.cancel.spec.tsx
index 24ab6732a1..5c247c7256 100644
--- a/client/src/hooks/SSE/__tests__/useEventHandlers.cancel.spec.tsx
+++ b/client/src/hooks/SSE/__tests__/useEventHandlers.cancel.spec.tsx
@@ -49,6 +49,7 @@ jest.mock('~/data-provider', () => ({
startupConfigKey: ['startup'],
queueTitleGeneration: jest.fn(),
markTitleGenerationProcessed: jest.fn(),
+ isTitleGenerationProcessed: () => false,
}));
jest.mock('~/utils', () => ({
logger: { log: jest.fn(), info: jest.fn(), debug: jest.fn(), error: jest.fn() },
@@ -63,7 +64,8 @@ jest.mock('~/utils', () => ({
upsertConvoInAllQueries: jest.fn(),
updateConvoInAllQueries: jest.fn(),
removeConvoFromAllQueries: jest.fn(),
- findConversationInInfinite: () => undefined,
+ findConvoInAllQueries: () => undefined,
+ findManualConvoTitleInAllQueries: () => undefined,
preserveStreamedContentIdentity: (_old: unknown, current: unknown) => current,
isEmptyContentPart: () => false,
getPartKeyIndex: jest.fn(),
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index 21a98dfb69..4384d6d84a 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -22,10 +22,9 @@ import type {
ChatCreatedFrame,
TMessageContentParts,
} from 'librechat-data-provider';
-import type { InfiniteData } from '@tanstack/react-query';
import type { SetterOrUpdater } from 'recoil';
import type { TResData, TFinalResData, ConvoGenerator } from '~/common';
-import type { ConversationCursorData } from '~/utils';
+import type { ConvoTitleState } from '~/utils/convos';
import {
logger,
setDraft,
@@ -41,7 +40,8 @@ import {
applyServerReplyStamp,
markLocallyCommittedReply,
removeConvoFromAllQueries,
- findConversationInInfinite,
+ findConvoInAllQueries,
+ findManualConvoTitleInAllQueries,
preserveStreamedContentIdentity,
isEmptyContentPart,
getPartKeyIndex,
@@ -533,34 +533,44 @@ export const buildRecoveryPreset = (
);
export const getConvoTitle = ({
- parentId,
queryClient,
currentTitle,
conversationId,
+ titleSetByUser,
+ titleRevision,
+ authoritative = false,
}: {
- parentId?: string | null;
queryClient: ReturnType<typeof useQueryClient>;
currentTitle?: string | null;
conversationId?: string | null;
-}): string | null | undefined => {
- if (
- parentId !== Constants.NO_PARENT &&
- (currentTitle?.toLowerCase().includes('new chat') ?? false)
- ) {
- const currentConvo = queryClient.getQueryData<TConversation>([
- QueryKeys.conversation,
- conversationId,
- ]);
- if (currentConvo?.title) {
- return currentConvo.title;
+ titleSetByUser?: boolean;
+ titleRevision?: number;
+ authoritative?: boolean;
+}): ConvoTitleState => {
+ const incoming = { title: currentTitle ?? null, titleSetByUser, titleRevision };
+ if (!conversationId) {
+ return incoming;
+ }
+ const cached = queryClient.getQueryData<TConversation>([QueryKeys.conversation, conversationId]);
+ const owned = findManualConvoTitleInAllQueries(queryClient, conversationId, incoming);
+ const listed = owned ? undefined : findConvoInAllQueries(queryClient, conversationId);
+ let selected = owned;
+ if (!selected) {
+ if (authoritative && hasRealTitle(incoming.title)) {
+ selected = incoming;
+ } else if (hasRealTitle(cached?.title)) {
+ selected = cached;
+ } else if (hasRealTitle(listed?.title)) {
+ selected = listed;
+ } else {
+ selected = incoming;
}
- const convos = queryClient.getQueryData<InfiniteData<ConversationCursorData>>([
- QueryKeys.allConversations,
- ]);
- const cachedConvo = findConversationInInfinite(convos, conversationId ?? '');
- return cachedConvo?.title ?? currentConvo?.title ?? null;
}
- return currentTitle;
+ return {
+ title: selected?.title ?? null,
+ titleSetByUser: selected?.titleSetByUser,
+ titleRevision: selected?.titleRevision,
+ };
};
export default function useEventHandlers({
@@ -842,19 +852,19 @@ export default function useEventHandlers({
let update = {} as TConversation;
if (setConversation && !isAddedRequest) {
setConversation((prevState) => {
- const parentId = requestMessage.parentMessageId;
- const title = getConvoTitle({
- parentId,
+ const titleState = getConvoTitle({
queryClient,
conversationId,
currentTitle: prevState?.title,
+ titleSetByUser: prevState?.titleSetByUser,
+ titleRevision: prevState?.titleRevision,
});
update = tConvoUpdateSchema.parse({
...prevState,
...acknowledgedCodeEnvironment(prevState, submission),
conversationId,
thread_id,
- title,
+ ...titleState,
messages: [requestMessage.messageId, responseMessage.messageId],
}) as TConversation;
return update;
@@ -927,18 +937,18 @@ export default function useEventHandlers({
let update = {} as TConversation;
if (setConversation && !isAddedRequest) {
setConversation((prevState) => {
- const parentId = isRegenerate ? userMessage.overrideParentMessageId : parentMessageId;
- const title = getConvoTitle({
- parentId,
+ const titleState = getConvoTitle({
queryClient,
conversationId,
currentTitle: prevState?.title,
+ titleSetByUser: prevState?.titleSetByUser,
+ titleRevision: prevState?.titleRevision,
});
update = tConvoUpdateSchema.parse({
...prevState,
...acknowledgedCodeEnvironment(prevState, submission),
conversationId,
- title,
+ ...titleState,
}) as TConversation;
return update;
});
@@ -992,15 +1002,25 @@ export default function useEventHandlers({
const titleHandler = useCallback(
(event: TTitleEvent) => {
- const { conversationId, title } = event.data ?? {};
- if (!conversationId || !hasRealTitle(title)) {
+ const { conversationId, title: generatedTitle } = event.data ?? {};
+ if (!conversationId || !hasRealTitle(generatedTitle)) {
return;
}
+ const titleState = getConvoTitle({
+ queryClient,
+ conversationId,
+ currentTitle: generatedTitle,
+ });
+ const title = titleState.title ?? generatedTitle;
queryClient.setQueryData<TConversation>([QueryKeys.conversation, conversationId], (convo) =>
- convo ? { ...convo, title } : convo,
+ convo ? { ...convo, ...titleState, title } : convo,
);
- updateConvoInAllQueries(queryClient, conversationId, (convo) => ({ ...convo, title }));
+ updateConvoInAllQueries(queryClient, conversationId, (convo) => ({
+ ...convo,
+ ...titleState,
+ title,
+ }));
markTitleGenerationProcessed(conversationId);
if (location.pathname.includes(conversationId)) {
@@ -1018,6 +1038,7 @@ export default function useEventHandlers({
return {
...prevState,
conversationId,
+ ...titleState,
title,
};
});
@@ -1223,12 +1244,7 @@ export default function useEventHandlers({
removeConvoFromAllQueries(queryClient, submissionConvo.conversationId);
}
- /** A title applied locally (e.g. an immediate-mode title fetched while the
- * response was still streaming) must survive the final event, whose
- * `conversation` was built before the title was saved and so carries no
- * title yet, otherwise the chat reverts to "New Chat" until reload. This
- * holds for a stopped turn too: the server persists a title that finished
- * generating before the Stop, so the local one stays in sync. */
+ /** Stream snapshots cannot overwrite a rename or generated title already in the cache. */
if (setConversation && isAddedRequest !== true) {
/* Pair the durable server stamp with the exact final messages cache object before
* point/list cache events can ask useConversationSeen to acknowledge it. */
@@ -1254,11 +1270,26 @@ export default function useEventHandlers({
if (prevState?.model != null && prevState.model !== submissionConvo.model) {
update.model = prevState.model;
}
- const prevTitle = prevState?.title;
- if (!hasRealTitle(conversation.title) && hasRealTitle(prevTitle)) {
- update.title = prevTitle;
- }
+ const titleState = getConvoTitle({
+ queryClient,
+ conversationId: conversation.conversationId,
+ titleSetByUser: conversation.titleSetByUser,
+ titleRevision: conversation.titleRevision,
+ authoritative: true,
+ currentTitle:
+ !conversation.titleSetByUser &&
+ !hasRealTitle(conversation.title) &&
+ prevState?.conversationId === conversation.conversationId &&
+ hasRealTitle(prevState.title)
+ ? prevState.title
+ : conversation.title,
+ });
+ Object.assign(update, titleState);
if (conversation.conversationId) {
+ updateConvoInAllQueries(queryClient, conversation.conversationId, (convo) => ({
+ ...convo,
+ ...titleState,
+ }));
queryClient.setQueryData<TConversation>(
[QueryKeys.conversation, conversation.conversationId],
(cachedConvo) => {
@@ -1269,10 +1300,7 @@ export default function useEventHandlers({
: cachedConvo,
conversation.conversationId,
);
- const cachedTitle = cachedConvo?.title;
- if (!hasRealTitle(serverConversation.title) && hasRealTitle(cachedTitle)) {
- merged.title = cachedTitle;
- }
+ Object.assign(merged, titleState);
return merged;
},
);
diff --git a/client/src/utils/convos.spec.ts b/client/src/utils/convos.spec.ts
index e8393a3aa2..b72ee17c33 100644
--- a/client/src/utils/convos.spec.ts
+++ b/client/src/utils/convos.spec.ts
@@ -22,6 +22,8 @@ import {
upsertConvoInAllQueries,
updateConvoInAllQueries,
findConvoInAllQueries,
+ findManualConvoTitleInAllQueries,
+ trackConvoQueryAuthority,
isConvoInAggregateCaches,
isConversationUnseen,
applyServerReplyStamp,
@@ -1335,6 +1337,129 @@ describe('Conversation Utilities', () => {
expect(data!.pages[0].conversations[0].lastResponseAt).toBe('2026-08-16T10:00:00.000Z');
});
+ it.each([
+ 'allConversations',
+ 'archivedConversations',
+ 'pinnedConversations',
+ 'runningConversation',
+ ])(
+ 'reads the highest manual title revision from %s without changing reply selection',
+ (root) => {
+ const old = {
+ ...convoA,
+ title: 'Old owned title',
+ titleSetByUser: true,
+ titleRevision: 1,
+ lastResponseAt: '2026-08-16T10:05:00.000Z',
+ };
+ const freshTitle = {
+ ...old,
+ title: 'New Chat',
+ titleRevision: 2,
+ lastResponseAt: '2026-08-16T10:00:00.000Z',
+ };
+ queryClient.clear();
+ queryClient.setQueryData(['conversation', 'a'], old);
+ const key =
+ root === 'runningConversation' ? [root, 'a'] : [root, { tag: 'older-snapshot' }];
+ let data;
+ if (root === 'runningConversation') {
+ data = freshTitle;
+ } else if (root === 'pinnedConversations') {
+ data = { conversations: [freshTitle] };
+ } else {
+ data = { pages: [{ conversations: [freshTitle] }], pageParams: [] };
+ }
+ queryClient.setQueryData(key, data, { updatedAt: Date.now() - 10 * 60_000 });
+ expect(findConvoInAllQueries(queryClient, 'a')?.title).toBe(old.title);
+ expect(findManualConvoTitleInAllQueries(queryClient, 'a')).toEqual({
+ title: 'New Chat',
+ titleSetByUser: true,
+ titleRevision: 2,
+ });
+ expect(findManualConvoTitleInAllQueries(queryClient, 'missing')).toBeUndefined();
+ },
+ );
+
+ it('compares repeated rows within a paginated variant and a pinned cache', () => {
+ queryClient.clear();
+ const old = { ...convoA, title: 'Old owned title', titleSetByUser: true, titleRevision: 1 };
+ queryClient.setQueryData(['allConversations'], {
+ pages: [
+ { conversations: [old] },
+ { conversations: [{ ...old, title: 'Page rename', titleRevision: 2 }] },
+ ],
+ pageParams: [],
+ });
+ expect(findManualConvoTitleInAllQueries(queryClient, 'a')?.titleRevision).toBe(2);
+ queryClient.setQueryData(['pinnedConversations'], {
+ conversations: [old, { ...old, title: 'Pinned rename', titleRevision: 3 }],
+ });
+ expect(findManualConvoTitleInAllQueries(queryClient, 'a')?.titleRevision).toBe(3);
+ });
+
+ it('uses durable revisions independently of server request ordering', async () => {
+ queryClient.clear();
+ const old = { ...convoA, title: 'Old owned title', titleSetByUser: true, titleRevision: 1 };
+ trackConvoQueryAuthority(queryClient);
+ let release!: (value: InfiniteData<ConversationCursorData>) => void;
+ const list = queryClient.fetchQuery(
+ ['allConversations'],
+ () =>
+ new Promise<InfiniteData<ConversationCursorData>>((resolve) => {
+ release = resolve;
+ }),
+ );
+ await queryClient.fetchQuery(['conversation', 'a'], async () => old);
+ release({
+ pages: [
+ {
+ conversations: [{ ...old, title: 'New owned title', titleRevision: 2 }],
+ nextCursor: null,
+ },
+ ],
+ pageParams: [],
+ });
+ await list;
+ expect(findConvoInAllQueries(queryClient, 'a')?.titleRevision).toBe(1);
+ expect(findManualConvoTitleInAllQueries(queryClient, 'a')?.titleRevision).toBe(2);
+ });
+
+ it('prefers an authoritative incoming title on equal revision and preserves later cache revisions', () => {
+ queryClient.clear();
+ queryClient.setQueryData(['conversation', 'a'], {
+ ...convoA,
+ title: 'Cached',
+ titleSetByUser: true,
+ titleRevision: 2,
+ });
+ expect(
+ findManualConvoTitleInAllQueries(queryClient, 'a', {
+ title: 'Incoming',
+ titleSetByUser: true,
+ titleRevision: 2,
+ })?.title,
+ ).toBe('Incoming');
+ expect(
+ findManualConvoTitleInAllQueries(queryClient, 'a', {
+ title: 'Stale',
+ titleSetByUser: true,
+ titleRevision: 1,
+ })?.title,
+ ).toBe('Cached');
+ queryClient.setQueryData(['allConversations', { tag: 'unrelated' }], {
+ pages: [
+ {
+ conversations: [
+ { ...convoB, title: 'Unrelated', titleSetByUser: true, titleRevision: 99 },
+ ],
+ },
+ ],
+ pageParams: [],
+ });
+ expect(findManualConvoTitleInAllQueries(queryClient, 'a')?.titleRevision).toBe(2);
+ });
+
it('findConvoInAllQueries reads from whichever cached list query holds the conversation', () => {
queryClient.setQueryData(['allConversations', { isArchived: true }], {
pages: [{ conversations: [convoB], nextCursor: null }],
diff --git a/client/src/utils/convos.ts b/client/src/utils/convos.ts
index 4d9f44782c..615e6c5df6 100644
--- a/client/src/utils/convos.ts
+++ b/client/src/utils/convos.ts
@@ -1593,6 +1593,54 @@ export function findConvoInAllQueries(
)?.convo;
}
+export type ConvoTitleState = Pick<TConversation, 'title' | 'titleSetByUser' | 'titleRevision'>;
+
+/** Manual revisions are monotonic even when reply snapshots or request order disagree. */
+export function findManualConvoTitleInAllQueries(
+ queryClient: QueryClient,
+ conversationId: string,
+ incoming?: ConvoTitleState,
+): ConvoTitleState | undefined {
+ let newest = incoming?.titleSetByUser ? incoming : undefined;
+ const consider = (candidate: TConversation | undefined | null) => {
+ if (
+ candidate?.conversationId === conversationId &&
+ candidate.titleSetByUser &&
+ (!newest || (candidate.titleRevision ?? 0) > (newest.titleRevision ?? 0))
+ ) {
+ newest = candidate;
+ }
+ };
+ for (const query of queryClient.getQueryCache().getAll()) {
+ const [root, id] = query.queryKey;
+ if (root === QueryKeys.allConversations || root === QueryKeys.archivedConversations) {
+ const data = queryClient.getQueryData<InfiniteData<ConversationCursorData>>(query.queryKey);
+ for (const page of data?.pages ?? []) {
+ for (const convo of page.conversations) {
+ consider(convo);
+ }
+ }
+ } else if (root === QueryKeys.pinnedConversations) {
+ const data = queryClient.getQueryData<PinnedConversationsData>(query.queryKey);
+ for (const convo of data?.conversations ?? []) {
+ consider(convo);
+ }
+ } else if (
+ (root === QueryKeys.conversation || root === QueryKeys.runningConversation) &&
+ id === conversationId
+ ) {
+ consider(queryClient.getQueryData<TConversation | null>(query.queryKey));
+ }
+ }
+ return (
+ newest && {
+ title: newest.title,
+ titleSetByUser: newest.titleSetByUser,
+ titleRevision: newest.titleRevision,
+ }
+ );
+}
+
type RunningRemovalState = {
owner?: string;
all: boolean;
diff --git a/e2e/README.md b/e2e/README.md
index 94c11f7ab8..c741a51255 100644
--- a/e2e/README.md
+++ b/e2e/README.md
@@ -2,6 +2,15 @@
The mock e2e profile is the safest default for generated tests. It starts LibreChat with `e2e/config/librechat.e2e.yaml`, injects an in-process fake LLM (via `LIBRECHAT_TEST_RUN_HOOK`), creates an authenticated e2e user, and avoids real provider credentials.
+## Automatic title regressions
+
+The standard mock profile disables automatic titles. CI runs the title-enabled cases once on the first memory shard. To run them locally after building the app:
+
+```sh
+E2E_TITLE_CONVO=true npx playwright test --config=e2e/playwright.config.mock.ts \
+ conversation-management.spec.ts --grep 'first-turn|final-title polling'
+```
+
## Deployed-instance smoke test
The deployed profile exercises an existing LibreChat deployment without starting another app or
@@ -205,3 +214,14 @@ For a historical revision without this lane, copy the two `e2e/screenshots/*.ts`
Each PNG has a JSON sidecar containing the revision, browser version, viewport, theme, scenario hash, lockfile hash, built HTML hash, and image hash. Visible images must decode, fonts must finish loading, greeting springs must settle, and consecutive captures must match. A passing run and human inspection are both required before treating the pair as reviewed evidence; sidecars from a failed run are not complete evidence. Compare matching filenames between revisions. Pin the browser and font environment as well as the app revisions.
Keep storage state, traces, logs, and session data private. Check that the PNGs contain only intended synthetic test data before uploading with the attachment-capable `gh` described in the PR template, then read back the PR body to verify real asset URLs. Mark any pending visual review explicitly. Do not commit the images. A new surface has no before state; label it accordingly rather than substituting another screen.
+
+## Running-chat rename rollout
+
+`interface.runningChatRename` defaults to `false`. Keep it off during rolling upgrades.
+After **every API replica** supports title ownership, drain all title-generation tasks
+started on older replicas, then enable it fleet-wide. The client also requires the
+server's title-ownership capability; an old replica cannot advertise it.
+
+With the fence off, running rows and unowned placeholder titles cannot be renamed.
+Other menu actions remain available. Settled non-placeholder chats retain Rename.
+The isolated mock profile enables the option because it contains no older replicas.
diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yaml
index e3b9dbaf59..470cb7aa91 100644
--- a/e2e/config/librechat.e2e.yaml
+++ b/e2e/config/librechat.e2e.yaml
@@ -5,6 +5,8 @@ version: 1.3.11
cache: true
interface:
+ # Isolated test fleet contains only ownership-aware replicas.
+ runningChatRename: true
# Exercises the cost row in the context usage gauge (off by default).
# Mock models price at the default rate, so synthetic usage yields a value.
contextCost: true
@@ -185,6 +187,30 @@ endpoints:
# Generic fallback inference is intentionally disabled for custom targets.
paramDefinitions:
- key: effort
+ - name: 'Mock Titles immediate'
+ apiKey: 'e2e-mock-title-key'
+ baseURL: 'http://127.0.0.1:8889/v1'
+ models:
+ default:
+ - 'mock-titles-immediate'
+ fetch: false
+ titleConvo: true
+ titleModel: 'mock-title-model'
+ titleMethod: completion
+ titleTiming: immediate
+ modelDisplayLabel: 'Mock Titles immediate'
+ - name: 'Mock Titles final'
+ apiKey: 'e2e-mock-title-key'
+ baseURL: 'http://127.0.0.1:8889/v1'
+ models:
+ default:
+ - 'mock-titles-final'
+ fetch: false
+ titleConvo: true
+ titleModel: 'mock-title-model'
+ titleMethod: completion
+ titleTiming: final
+ modelDisplayLabel: 'Mock Titles final'
- name: 'Mock Provider B'
apiKey: 'e2e-mock-key-b'
baseURL: 'http://127.0.0.1:8889/v1'
@@ -266,6 +292,8 @@ modelSpecs:
# set) limited to entries that don't collide with the spec labels above.
addedEndpoints:
# __E2E_MODEL_RECORD_ADDED_ENDPOINT__
+ - 'Mock Titles immediate'
+ - 'Mock Titles final'
- 'Mock Provider C'
- 'Mock Provider D'
- 'Mock Provider E'
diff --git a/e2e/setup/env.ts b/e2e/setup/env.ts
index 285ee86713..dc584a400e 100644
--- a/e2e/setup/env.ts
+++ b/e2e/setup/env.ts
@@ -145,7 +145,7 @@ export function getBaseE2EEnv(): Record<string, string> {
export function getLocalE2EEnv(): Record<string, string> {
return {
...getBaseE2EEnv(),
- TITLE_CONVO: 'false',
+ TITLE_CONVO: process.env.E2E_TITLE_CONVO ?? 'false',
LOGIN_VIOLATION_SCORE: '0',
REGISTRATION_VIOLATION_SCORE: '0',
CONCURRENT_VIOLATION_SCORE: '0',
diff --git a/e2e/setup/fake-label-server.js b/e2e/setup/fake-label-server.js
index f001ddb83a..1c08013b98 100644
--- a/e2e/setup/fake-label-server.js
+++ b/e2e/setup/fake-label-server.js
@@ -8,7 +8,7 @@
* endpoint config. Those options carry the template's `baseURL`
* (http://127.0.0.1:8889/v1), so a real server on that port serves label
* calls — and only label calls — with no production seam. Every mock endpoint
- * sets `titleConvo: false`, so nothing else lands here.
+ * disables titles except the dedicated title-ownership endpoints.
*
* Beyond returning a label it RECORDS each request, which is what lets a spec
* assert the prompt contract (that the register and the tool OUTPUTS actually
@@ -28,9 +28,12 @@ const DEFAULT_BEHAVIOR = {
phaseLabel: null,
labelsByPrompt: {},
delayMs: 0,
+ hold: false,
+ holdModel: null,
};
let behavior = { ...DEFAULT_BEHAVIOR };
let labelCount = 0;
+const heldResponses = new Set();
function readBody(req) {
return new Promise((resolve) => {
@@ -131,7 +134,17 @@ const server = http.createServer(async (req, res) => {
}
/** Specs reset between cases so counts and prompts stay per-test. */
+ if (req.method === 'POST' && url.pathname === '/__e2e/release') {
+ behavior.hold = false;
+ for (const release of heldResponses) release();
+ heldResponses.clear();
+ sendJson(res, 200, { ok: true });
+ return;
+ }
+
if (req.method === 'POST' && url.pathname === '/__e2e/reset') {
+ for (const release of heldResponses) release();
+ heldResponses.clear();
requests.length = 0;
labelCount = 0;
behavior = { ...DEFAULT_BEHAVIOR };
@@ -150,12 +163,17 @@ const server = http.createServer(async (req, res) => {
const body = await readBody(req);
labelCount += 1;
const prompt = flattenPrompt(body.messages);
- requests.push({
+ const recorded = {
model: body.model,
stream: body.stream === true,
prompt,
messages: body.messages ?? [],
- });
+ completed: false,
+ };
+ requests.push(recorded);
+ if (behavior.hold && (!behavior.holdModel || behavior.holdModel === body.model)) {
+ await new Promise((resolve) => heldResponses.add(resolve));
+ }
if (behavior.delayMs > 0) {
await new Promise((resolve) => setTimeout(resolve, behavior.delayMs));
@@ -179,6 +197,7 @@ const server = http.createServer(async (req, res) => {
behavior.label ??
`E2E activity label ${labelCount}`);
+ recorded.completed = true;
if (body.stream === true) {
sendStream(res, body.model, label);
return;
diff --git a/e2e/specs/mock/conversation-management.spec.ts b/e2e/specs/mock/conversation-management.spec.ts
index 633d98b02a..0c03644584 100644
--- a/e2e/specs/mock/conversation-management.spec.ts
+++ b/e2e/specs/mock/conversation-management.spec.ts
@@ -8,8 +8,10 @@ import {
replyPrompt,
replyText,
selectMockEndpoint,
+ sendMessage,
sendMessageAndWaitForCompletion,
} from './helpers';
+import { openSidebar } from './scenarios/sidebar';
function uniqueLabel(prefix: string) {
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
@@ -81,8 +83,365 @@ test.describe('conversation management', () => {
await sendAndExpectReply(page, label);
await renameConversation(page, conversationRow(page), renamedTitle);
+ const followUp = await sendMessage(page, `E2E_SLOW_REPLY:${label}-follow-up`);
+ expect(followUp.ok()).toBeTruthy();
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeVisible();
+ await expect(conversationRow(page)).toContainText(renamedTitle);
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden({
+ timeout: 30000,
+ });
+ await expect(conversationRow(page)).toContainText(renamedTitle);
await page.reload({ timeout: 10000 });
- await expect(page.getByTestId('convo-item').filter({ hasText: renamedTitle })).toBeVisible();
+ await expect(conversationRow(page)).toContainText(renamedTitle);
+ });
+
+ for (const background of [false, true]) {
+ test(`right-clicks and renames a running ${background ? 'background' : 'active'} chat`, async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ const label = uniqueLabel(`running-${background ? 'background' : 'active'}`);
+ const originalTitle = `Original ${label}`;
+ const renamedTitle = `Renamed ${label}`;
+ await openMockChat(page);
+ await sendAndExpectReply(page, label);
+ await renameConversation(page, conversationRow(page), originalTitle);
+ const conversationUrl = page.url();
+ const run = await sendMessage(page, `E2E_SLOW_REPLY:${label}`);
+ expect(run.ok()).toBeTruthy();
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeVisible();
+ if (background) {
+ await page.getByRole('link', { name: 'New chat', exact: true }).click();
+ await expect(page).toHaveURL(/\/c\/new$/);
+ }
+ const row = conversationRow(page, conversationUrl);
+ await expect(row).toContainText(originalTitle);
+ await expect(row.getByRole('button', { name: /, Generating\.\.\.$/ })).toBeVisible();
+ await row.click({ button: 'right' });
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ await expect(menu).toBeFocused();
+ await page.keyboard.press('ArrowDown');
+ await expect(menu.getByRole('menuitem').first()).toBeFocused();
+ const expectedOptions = ['Share', 'Pin'];
+ if (background) expectedOptions.push('Mark as unread');
+ expectedOptions.push('Rename', 'Duplicate', 'Change project', 'Archive', 'Delete');
+ await expect(menu.getByRole('menuitem')).toHaveText(expectedOptions);
+ await test.info().attach('running-chat-menu', {
+ body: await page.screenshot(),
+ contentType: 'image/png',
+ });
+ await expect(page).toHaveURL(background ? /\/c\/new$/ : conversationUrl);
+ await expect(row.getByRole('button', { name: /, Generating\.\.\.$/ })).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(menu).toBeHidden();
+ await expect(row.getByRole('button', { name: 'Conversation Menu Options' })).toBeFocused();
+ await row.click({ button: 'right' });
+ await page.getByRole('menuitem', { name: 'Rename' }).click();
+ const titleInput = row.getByRole('textbox', { name: 'New Conversation Title' });
+ await titleInput.fill(renamedTitle);
+ const [renamed] = await Promise.all([
+ page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname === '/api/convos/update',
+ ),
+ row.getByRole('button', { name: 'Save' }).click(),
+ ]);
+ expect(renamed.ok()).toBeTruthy();
+ const renamedRow = row;
+ await expect(renamedRow.getByRole('button', { name: /, Generating\.\.\.$/ })).toBeVisible();
+ if (background) {
+ await renamedRow.click();
+ await expect(page).toHaveURL(conversationUrl);
+ }
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden({
+ timeout: 30000,
+ });
+ await expect(renamedRow).toBeVisible();
+ await expect(page.getByTestId('convo-item').filter({ hasText: originalTitle })).toHaveCount(
+ 0,
+ );
+ await page.reload({ timeout: 10000 });
+ await expect(renamedRow).toBeVisible();
+ });
+ }
+
+ test('keeps a rename when an older navigation refresh lands before the next message', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ const label = uniqueLabel('refresh-rename');
+ const originalTitle = `Original ${label}`;
+ const renamedTitle = `Renamed ${label}`;
+ await openMockChat(page);
+ await sendAndExpectReply(page, label);
+ await renameConversation(page, conversationRow(page), originalTitle);
+ const conversationUrl = page.url();
+ const conversationId = new URL(conversationUrl).pathname.split('/').pop()!;
+ await page.getByRole('link', { name: 'New chat', exact: true }).click();
+ let release!: () => void;
+ let captured!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const ready = new Promise<void>((resolve) => {
+ captured = resolve;
+ });
+ const pattern = `**/api/convos/${conversationId}`;
+ await page.route(pattern, async (route) => {
+ const response = await route.fetch();
+ captured();
+ await gate;
+ await route.fulfill({ response });
+ });
+ await conversationRow(page, conversationUrl).click();
+ await ready;
+ await renameConversation(page, conversationRow(page), renamedTitle);
+ const staleRead = page.waitForResponse(
+ (response) => new URL(response.url()).pathname === `/api/convos/${conversationId}`,
+ );
+ release();
+ await staleRead;
+ await page.unroute(pattern);
+ await expect(conversationRow(page)).toContainText(renamedTitle);
+ expect(
+ (await sendMessageAndWaitForCompletion(page, replyPrompt(`${label}-next`))).ok(),
+ ).toBeTruthy();
+ await expect(conversationRow(page)).toContainText(renamedTitle);
+ await page.reload();
+ await expect(conversationRow(page)).toContainText(renamedTitle);
+ });
+
+ test('adopts a newer rename from another tab when the next stream finishes', async ({ page }) => {
+ test.setTimeout(45000);
+ const label = uniqueLabel('cross-tab-rename');
+ const firstTitle = `First ${label}`;
+ const secondTitle = `Second ${label}`;
+ await openMockChat(page);
+ await sendAndExpectReply(page, label);
+ await renameConversation(page, conversationRow(page), firstTitle);
+ const url = page.url();
+ const otherTab = await page.context().newPage();
+ try {
+ await otherTab.goto(url);
+ await expect(otherTab.getByRole('textbox', { name: 'Message input' })).toBeVisible();
+ await renameConversation(otherTab, conversationRow(otherTab), secondTitle);
+ await expect(conversationRow(page)).toContainText(firstTitle);
+ expect(
+ (await sendMessageAndWaitForCompletion(page, replyPrompt(`${label}-next`))).ok(),
+ ).toBeTruthy();
+ await expect(conversationRow(page)).toContainText(secondTitle);
+ await page.reload();
+ await expect(conversationRow(page)).toContainText(secondTitle);
+ } finally {
+ await otherTab.close();
+ }
+ });
+
+ test('leaves the native context menu available on a portaled shared-link input', async ({
+ page,
+ }) => {
+ await openMockChat(page);
+ await sendAndExpectReply(page, uniqueLabel('portal-context'));
+ await conversationRow(page).click({ button: 'right' });
+ await page.getByRole('menuitem', { name: 'Share', exact: true }).click();
+ const dialog = page.getByRole('dialog', { name: 'Share link to chat' });
+ await expect(dialog).toBeVisible();
+ await dialog.getByRole('button', { name: 'Create a shared link' }).click();
+ const input = dialog.getByTestId('shared-link-url');
+ await expect(input).toHaveValue(/\/share\//);
+ const nativeMenuAllowed = await input.evaluate((element) =>
+ element.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })),
+ );
+ expect(nativeMenuAllowed).toBe(true);
+ await expect(dialog).toBeVisible();
+ });
+
+ for (const missingProtocol of [false, true]) {
+ test(`fences running rename with ${missingProtocol ? 'an older replica' : 'deployment opt-out'}`, async ({
+ page,
+ }) => {
+ await page.route('**/api/config', async (route) => {
+ const response = await route.fetch();
+ const config = await response.json();
+ if (missingProtocol) delete config.conversationTitleOwnershipVersion;
+ else config.interface = { ...config.interface, runningChatRename: false };
+ await route.fulfill({ response, json: config });
+ });
+ await openMockChat(page);
+ const label = uniqueLabel('rollout-fence');
+ await sendAndExpectReply(page, label);
+ expect((await sendMessage(page, `E2E_SLOW_REPLY:${label}`)).ok()).toBeTruthy();
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeVisible();
+ const row = conversationRow(page);
+ await row.click({ button: 'right' });
+ await expect(page.getByRole('menuitem', { name: 'Rename', exact: true })).toBeDisabled();
+ await expect(page.getByRole('menuitem', { name: 'Pin', exact: true })).toBeEnabled();
+ await expect(page.getByRole('menuitem', { name: 'Archive', exact: true })).toBeEnabled();
+ await expect(row.getByRole('button', { name: /, Generating\.\.\.$/ })).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(row.getByRole('button', { name: 'Conversation Menu Options' })).toBeFocused();
+ });
+ }
+
+ test('returns focus after right-clicking an unopened running menu on a small screen', async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width: 390, height: 900 });
+ const label = uniqueLabel('running-small');
+ await openMockChat(page);
+ await sendAndExpectReply(page, label);
+ const run = await sendMessage(page, `E2E_SLOW_REPLY:${label}`);
+ expect(run.ok()).toBeTruthy();
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeVisible();
+ const conversationUrl = page.url();
+ await openSidebar(page);
+ await page.getByRole('link', { name: 'New chat', exact: true }).click();
+ await expect(page).toHaveURL(/\/c\/new$/);
+ await expect(page.locator('#mobile-drawer')).toHaveCSS('visibility', 'hidden');
+ await openSidebar(page);
+ const row = conversationRow(page, conversationUrl);
+ await expect(row.getByRole('button', { name: /, Generating\.\.\.$/ })).toBeVisible();
+ await row.click({ button: 'right' });
+ await expect(page.getByRole('menu')).toBeVisible();
+ const trigger = row.getByRole('button', { name: 'Conversation Menu Options' });
+ const originalTrigger = await trigger.elementHandle();
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('menu')).toBeHidden();
+ expect(await originalTrigger?.evaluate((element) => element.isConnected)).toBe(true);
+ await expect(trigger).toBeFocused();
+ });
+
+ for (const timing of ['immediate', 'final', 'unchanged'] as const) {
+ test(`preserves a first-turn rename over a pending ${timing} automatic title`, async ({
+ page,
+ request,
+ }) => {
+ test.skip(process.env.E2E_TITLE_CONVO !== 'true', 'Requires the title-enabled mock profile');
+ test.setTimeout(40000);
+ const label = uniqueLabel(`first-rename-${timing}`);
+ const renamedTitle = timing === 'unchanged' ? 'New Chat' : `Renamed ${label}`;
+ const titleTiming = timing === 'unchanged' ? 'immediate' : timing;
+ const fixture = `http://127.0.0.1:${process.env.E2E_LABEL_PORT ?? '8889'}`;
+ await request.post(`${fixture}/__e2e/reset`);
+ await request.post(`${fixture}/__e2e/behavior`, {
+ data: { label: `Generated ${label}`, hold: true, holdModel: 'mock-title-model' },
+ });
+ try {
+ await page.goto(NEW_CHAT_PATH);
+ await selectMockEndpoint(page, {
+ label: `Mock Titles ${titleTiming}`,
+ model: `mock-titles-${titleTiming}`,
+ });
+ const titleFetch = page.waitForRequest((request) =>
+ new URL(request.url()).pathname.startsWith('/api/convos/gen_title/'),
+ );
+ const run = await sendMessage(page, `E2E_SLOW_REPLY:${label}`);
+ await titleFetch;
+ expect(run.ok()).toBeTruthy();
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeVisible();
+ const { conversationId } = await run.json();
+ await expect(messagesView(page).getByText('chunk-010')).toBeVisible();
+ const row = conversationRow(page, new URL(`/c/${conversationId}`, page.url()).href);
+ await expect(row.getByRole('button', { name: /, Generating\.\.\.$/ })).toBeVisible();
+ const titleRequest = async () => {
+ const body = await (await request.get(`${fixture}/__e2e/requests`)).json();
+ return body.requests.find(
+ (record: { prompt: string; model: string }) =>
+ record.model === 'mock-title-model' && record.prompt.includes(label),
+ );
+ };
+ if (timing === 'unchanged')
+ await expect.poll(async () => !!(await titleRequest())).toBe(true);
+ await row.click({ button: 'right' });
+ await page.getByRole('menuitem', { name: 'Rename' }).click();
+ await row.getByRole('textbox', { name: 'New Conversation Title' }).fill(renamedTitle);
+ const [renameResponse] = await Promise.all([
+ page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname === '/api/convos/update' &&
+ response.request().method() === 'POST',
+ ),
+ row.getByRole('button', { name: 'Save' }).click(),
+ ]);
+ expect(renameResponse.ok()).toBeTruthy();
+ expect(await renameResponse.json()).toEqual(
+ expect.objectContaining({
+ title: renamedTitle,
+ titleSetByUser: true,
+ }),
+ );
+ await expect(row).toContainText(renamedTitle);
+ await expect.poll(async () => !!(await titleRequest())).toBe(true);
+ const published = page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname.startsWith('/api/convos/gen_title/') &&
+ response.status() === 200,
+ { timeout: 30000 },
+ );
+ await request.post(`${fixture}/__e2e/release`);
+ expect((await (await published).json()).title).toBe(renamedTitle);
+ await expect.poll(async () => (await titleRequest())?.completed === true).toBe(true);
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden({
+ timeout: 30000,
+ });
+ await expect(row).toContainText(renamedTitle);
+ await page.reload();
+ await expect(row).toContainText(renamedTitle);
+ } finally {
+ await request.post(`${fixture}/__e2e/reset`, { timeout: 2000 }).catch(() => undefined);
+ }
+ });
+ }
+
+ test('adopts a newer remote rename from delayed final-title polling', async ({
+ page,
+ request,
+ }) => {
+ test.skip(process.env.E2E_TITLE_CONVO !== 'true', 'Requires the title-enabled mock profile');
+ test.setTimeout(50000);
+ const label = uniqueLabel('final-poll-rename');
+ const firstTitle = `First ${label}`;
+ const secondTitle = `Second ${label}`;
+ const fixture = `http://127.0.0.1:${process.env.E2E_LABEL_PORT ?? '8889'}`;
+ await request.post(`${fixture}/__e2e/reset`);
+ await request.post(`${fixture}/__e2e/behavior`, {
+ data: { label: `Generated ${label}`, hold: true, holdModel: 'mock-title-model' },
+ });
+ let otherTab: Page | undefined;
+ try {
+ await page.goto(NEW_CHAT_PATH);
+ await selectMockEndpoint(page, { label: 'Mock Titles final', model: 'mock-titles-final' });
+ const published = page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname.startsWith('/api/convos/gen_title/') &&
+ response.status() === 200,
+ );
+ expect((await sendMessage(page, `E2E_SLOW_REPLY:${label}`)).ok()).toBeTruthy();
+ await expect(messagesView(page).getByText('chunk-010')).toBeVisible();
+ otherTab = await page.context().newPage();
+ await otherTab.goto(page.url());
+ await renameConversation(otherTab, conversationRow(otherTab), firstTitle);
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden({
+ timeout: 30000,
+ });
+ await expect(conversationRow(page)).toContainText(firstTitle);
+ await renameConversation(otherTab, conversationRow(otherTab), secondTitle);
+ await expect(conversationRow(page)).toContainText(firstTitle);
+ await request.post(`${fixture}/__e2e/release`);
+ expect(await (await published).json()).toEqual({
+ title: secondTitle,
+ titleSetByUser: true,
+ titleRevision: 2,
+ });
+ await expect(conversationRow(page)).toContainText(secondTitle);
+ await page.reload();
+ await expect(conversationRow(page)).toContainText(secondTitle);
+ } finally {
+ await otherTab?.close();
+ await request.post(`${fixture}/__e2e/reset`, { timeout: 2000 }).catch(() => undefined);
+ }
});
test('deletes a conversation, clears its messages, and blocks direct URL access', async ({
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 22095413f3..20810f96e9 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -880,14 +880,6 @@
"client/src/components/Conversations/Convo.tsx": {
"shadcn/no-inline-styles": {
"count": 1
- },
- "shadcn/no-restyle": {
- "count": 1
- }
- },
- "client/src/components/Conversations/ConvoActions.tsx": {
- "shadcn/no-restyle": {
- "count": 1
}
},
"client/src/components/Conversations/ConvoLink.tsx": {
diff --git a/librechat.example.yaml b/librechat.example.yaml
index e5bd5e4912..edf598e760 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -155,6 +155,10 @@ projects:
# Custom interface configuration
interface:
customWelcome: 'Welcome to LibreChat! Enjoy your experience.'
+ # After ALL API replicas are upgraded and old title-generation jobs have drained:
+ # runningChatRename: true
+ # Keep false (default) during rolling upgrades. Missing server capability disables
+ # rename for running chats and unowned placeholder titles; other actions stay available.
# Minimum interval between syntax-highlighting passes while streamed code changes (default: 300 ms)
# codeHighlightThrottleMs: 300
# Deployment theme applied to every user, in both light and dark mode (default: unset).
diff --git a/packages/api/src/conversations/index.ts b/packages/api/src/conversations/index.ts
index e3397966fa..30688b865c 100644
--- a/packages/api/src/conversations/index.ts
+++ b/packages/api/src/conversations/index.ts
@@ -7,3 +7,5 @@ export * from './lineage';
export * from './read';
export * from './retention';
export * from './save';
+export * from './title';
+export * from './rename';
diff --git a/packages/api/src/conversations/rename.spec.ts b/packages/api/src/conversations/rename.spec.ts
new file mode 100644
index 0000000000..ea70469186
--- /dev/null
+++ b/packages/api/src/conversations/rename.spec.ts
@@ -0,0 +1,214 @@
+import express from 'express';
+import request from 'supertest';
+import type { AppConfig, ConversationMethods } from '@librechat/data-schemas';
+import { createRenameConversationHandler, getConversationTitleCapabilities } from './rename';
+
+type RenameHandler = ReturnType<typeof createRenameConversationHandler>;
+type RenameRequest = Parameters<RenameHandler>[0];
+
+function setup(
+ options: {
+ enabled?: boolean;
+ current?: RenameRequest['resolvedConversation'];
+ authenticated?: boolean;
+ accessCacheHit?: boolean;
+ } = {},
+) {
+ const config: AppConfig = {
+ interfaceConfig: { runningChatRename: options.enabled ?? true },
+ } as AppConfig;
+ const deps = {
+ getConvo: jest.fn().mockResolvedValue({ conversationId: 'chat', title: 'Established chat' }),
+ saveConvo: jest
+ .fn<
+ ReturnType<ConversationMethods['saveConvo']>,
+ Parameters<ConversationMethods['saveConvo']>
+ >()
+ .mockResolvedValue({
+ conversationId: 'chat',
+ title: 'New Chat',
+ titleSetByUser: true,
+ titleRevision: 1,
+ } as Awaited<ReturnType<ConversationMethods['saveConvo']>>),
+ getActiveRunIds: jest.fn().mockResolvedValue([]),
+ logger: { error: jest.fn() },
+ };
+ const handler = createRenameConversationHandler(deps);
+ const app = express();
+ app.use(express.json());
+ app.post('/rename', async (req, res) => {
+ let current = options.current;
+ if (options.accessCacheHit) {
+ current = undefined;
+ } else if (current === undefined) {
+ current = { title: 'Established chat' };
+ }
+ await handler(
+ {
+ body: req.body,
+ user: options.authenticated === false ? undefined : { id: 'owner', tenantId: 'tenant' },
+ config,
+ resolvedConversation: current,
+ },
+ res,
+ );
+ });
+ return { app, deps, config };
+}
+
+const arg = { conversationId: 'chat', title: 'New Chat' };
+
+describe('rename conversation', () => {
+ it('claims an unchanged placeholder without rewriting messages or upserting', async () => {
+ const { app, deps } = setup({ current: { title: 'New Chat' } });
+ const response = await request(app).post('/rename').send({ arg });
+ expect(response.status).toBe(201);
+ expect(response.body.titleSetByUser).toBe(true);
+ expect(deps.saveConvo).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'owner' }),
+ arg,
+ expect.objectContaining({ titleSource: 'manual', appendMessageIds: [], noUpsert: true }),
+ );
+ expect(deps.getActiveRunIds).not.toHaveBeenCalled();
+ });
+ it.each([{ title: 'New Chat' }, { title: '' }])(
+ 'fences unowned pending-title records during rollout: %j',
+ async (current) => {
+ const { app, deps } = setup({ enabled: false, current });
+ expect((await request(app).post('/rename').send({ arg })).status).toBe(409);
+ expect(deps.saveConvo).not.toHaveBeenCalled();
+ },
+ );
+ it('loads the record on access-cache hits and retains default-off settled rename', async () => {
+ const expiredAt = new Date('2027-01-01');
+ const { app, deps } = setup({ enabled: false, accessCacheHit: true });
+ deps.getConvo.mockResolvedValue({ title: 'Established chat', isTemporary: true, expiredAt });
+ const response = await request(app).post('/rename').send({ arg });
+ expect(response.status).toBe(201);
+ expect(deps.getConvo).toHaveBeenCalledWith('owner', 'chat');
+ expect(deps.saveConvo).toHaveBeenCalledWith(
+ expect.objectContaining({ isTemporary: true, expiredAt }),
+ arg,
+ expect.anything(),
+ );
+ });
+ it('reuses middleware-loaded records without another database lookup', async () => {
+ const { app, deps } = setup({ enabled: false });
+ expect((await request(app).post('/rename').send({ arg })).status).toBe(201);
+ expect(deps.getConvo).not.toHaveBeenCalled();
+ });
+ it('still fences pending titles and active writers on access-cache hits', async () => {
+ const { app, deps } = setup({ enabled: false, accessCacheHit: true });
+ deps.getConvo.mockResolvedValueOnce({ title: 'New Chat' });
+ expect((await request(app).post('/rename').send({ arg })).status).toBe(409);
+ deps.getActiveRunIds.mockResolvedValueOnce(['old-run']);
+ expect((await request(app).post('/rename').send({ arg })).status).toBe(409);
+ expect(deps.saveConvo).not.toHaveBeenCalled();
+ });
+ it('distinguishes missing records from failed lookups on access-cache hits', async () => {
+ const { app, deps } = setup({ enabled: false, accessCacheHit: true });
+ deps.getConvo.mockResolvedValueOnce(null);
+ expect((await request(app).post('/rename').send({ arg })).status).toBe(404);
+ deps.getConvo.mockRejectedValueOnce(new Error('private-storage-content'));
+ const response = await request(app).post('/rename').send({ arg });
+ expect(response.status).toBe(500);
+ expect(response.text).toBe('Error updating conversation');
+ expect(deps.saveConvo).not.toHaveBeenCalled();
+ });
+ it('fences an older active writer even if its row already has a real title', async () => {
+ const { app, deps } = setup({ enabled: false });
+ deps.getActiveRunIds.mockResolvedValue(['old-replica-run']);
+ const response = await request(app).post('/rename').send({ arg });
+ expect(response.status).toBe(409);
+ expect(deps.getActiveRunIds).toHaveBeenCalledWith('owner', ['chat'], 'tenant');
+ expect(deps.saveConvo).not.toHaveBeenCalled();
+ });
+ it('retains rename for a settled titled conversation before the rollout fence opens', async () => {
+ const { app, deps } = setup({ enabled: false });
+ expect((await request(app).post('/rename').send({ arg })).status).toBe(201);
+ expect(deps.saveConvo).toHaveBeenCalledTimes(1);
+ });
+ it('allows a settled owned placeholder while the rollout fence is off', async () => {
+ const { app } = setup({ enabled: false, current: { title: 'New Chat', titleSetByUser: true } });
+ expect((await request(app).post('/rename').send({ arg })).status).toBe(201);
+ });
+ it.each([
+ {},
+ { conversationId: 'chat' },
+ { conversationId: 1, title: 'x' },
+ { conversationId: 'chat', title: 1 },
+ ])('rejects malformed title writes %j', async (arg) => {
+ const { app, deps } = setup();
+ expect((await request(app).post('/rename').send({ arg })).status).toBe(400);
+ expect(deps.saveConvo).not.toHaveBeenCalled();
+ });
+ it('does not write without an authenticated owner', async () => {
+ const { app, deps } = setup({ authenticated: false });
+ expect((await request(app).post('/rename').send({ arg })).status).toBe(401);
+ expect(deps.saveConvo).not.toHaveBeenCalled();
+ });
+ it('trims and bounds titles while preserving the resolved retention context', async () => {
+ const expiredAt = new Date('2027-01-01');
+ const { app, deps } = setup({ current: { title: 'Chat', isTemporary: true, expiredAt } });
+ await request(app)
+ .post('/rename')
+ .send({ arg: { ...arg, title: ` ${'x'.repeat(1100)} ` } });
+ expect(deps.saveConvo).toHaveBeenCalledWith(
+ expect.objectContaining({ isTemporary: true, expiredAt }),
+ { ...arg, title: 'x'.repeat(1024) },
+ expect.anything(),
+ );
+ });
+ it('blocks protected title content without publishing or saving it', async () => {
+ const { app, config, deps } = setup();
+ config.filters = {
+ conversationTitles: {
+ pii: {
+ starterPatterns: [],
+ customPatterns: [{ id: 'blocked', label: 'blocked', regex: 'BLOCKED' }],
+ },
+ },
+ };
+ const response = await request(app)
+ .post('/rename')
+ .send({ arg: { ...arg, title: 'BLOCKED-TITLE' } });
+ expect(response.status).toBe(400);
+ expect(deps.saveConvo).not.toHaveBeenCalled();
+ expect(JSON.stringify(response.body)).not.toContain('BLOCKED-TITLE');
+ });
+ it.each([null, { message: 'private-storage-failure' }])(
+ 'distinguishes absence from failed persistence',
+ async (saved) => {
+ const { app, deps } = setup();
+ deps.saveConvo.mockResolvedValue(saved);
+ const response = await request(app).post('/rename').send({ arg });
+ expect(response.status).toBe(saved === null ? 404 : 500);
+ expect(JSON.stringify(response.body)).not.toContain('private-storage-failure');
+ },
+ );
+ it('owns active-run lookup failures without writing or exposing diagnostics', async () => {
+ const { app, deps } = setup({ enabled: false });
+ deps.getActiveRunIds.mockRejectedValue(new Error('secret-worker-payload'));
+ const response = await request(app).post('/rename').send({ arg });
+ expect(response.status).toBe(500);
+ expect(response.text).toBe('Error updating conversation');
+ expect(deps.logger.error).toHaveBeenCalledWith('[rename] Conversation title update failed', {
+ type: 'Error',
+ });
+ expect(deps.saveConvo).not.toHaveBeenCalled();
+ });
+});
+
+describe('title ownership capability', () => {
+ it('advertises the protocol only after deployment opt-in', () => {
+ expect(getConversationTitleCapabilities(undefined)).toEqual({});
+ expect(
+ getConversationTitleCapabilities({
+ runningChatRename: false,
+ } as AppConfig['interfaceConfig']),
+ ).toEqual({});
+ expect(
+ getConversationTitleCapabilities({ runningChatRename: true } as AppConfig['interfaceConfig']),
+ ).toEqual({ conversationTitleOwnershipVersion: 1 });
+ });
+});
diff --git a/packages/api/src/conversations/rename.ts b/packages/api/src/conversations/rename.ts
new file mode 100644
index 0000000000..f7cd2217cb
--- /dev/null
+++ b/packages/api/src/conversations/rename.ts
@@ -0,0 +1,98 @@
+import { CONVERSATION_TITLE_OWNERSHIP_VERSION } from 'librechat-data-provider';
+import type { AppConfig, ConversationMethods } from '@librechat/data-schemas';
+import type { TStartupConfig } from 'librechat-data-provider';
+import type { Response } from 'express';
+import { extractConversationTitleContent } from '~/protection/adapters/submissions';
+import { contentFilterBlockResponse } from '~/middleware/contentFilter';
+import { inspectContent } from '~/protection/runtime';
+import { getSafeErrorMetadata } from '~/utils/errors';
+
+export function getConversationTitleCapabilities(
+ config?: AppConfig['interfaceConfig'],
+): Pick<TStartupConfig, 'conversationTitleOwnershipVersion'> {
+ return config?.runningChatRename === true
+ ? { conversationTitleOwnershipVersion: CONVERSATION_TITLE_OWNERSHIP_VERSION }
+ : {};
+}
+
+type RenameRequest = {
+ body?: { arg?: { conversationId?: unknown; title?: unknown } };
+ user?: { id: string; tenantId?: string };
+ config?: Pick<AppConfig, 'filters' | 'interfaceConfig'>;
+ resolvedConversation?: {
+ title?: string;
+ titleSetByUser?: boolean;
+ isTemporary?: boolean;
+ expiredAt?: Date;
+ } | null;
+};
+
+type RenameDependencies = Pick<ConversationMethods, 'saveConvo' | 'getConvo'> & {
+ getActiveRunIds: (
+ user: string,
+ conversations: readonly string[],
+ tenantId?: string,
+ ) => Promise<string[]>;
+ logger: { error: (message: string, metadata: ReturnType<typeof getSafeErrorMetadata>) => void };
+};
+
+/** Explicit saves claim title ownership, even when the text has not changed. */
+export function createRenameConversationHandler(
+ deps: RenameDependencies,
+): (req: RenameRequest, res: Response) => Promise<Response> {
+ return async (req, res) => {
+ const { conversationId, title } = req.body?.arg ?? {};
+ if (typeof conversationId !== 'string' || !conversationId) {
+ return res.status(400).json({ error: 'conversationId is required' });
+ }
+ if (title === undefined) return res.status(400).json({ error: 'title is required' });
+ if (typeof title !== 'string') return res.status(400).json({ error: 'title must be a string' });
+ if (!req.user?.id) return res.status(401).json({ error: 'unauthorized' });
+
+ try {
+ const current =
+ req.resolvedConversation === undefined
+ ? await deps.getConvo(req.user.id, conversationId)
+ : req.resolvedConversation;
+ if (current == null) return res.status(404).json({ error: 'conversation_not_found' });
+ if (req.config?.interfaceConfig?.runningChatRename !== true) {
+ // A final-timing title can still be pending after the stream becomes terminal.
+ if (
+ (!current.titleSetByUser &&
+ (current.title == null || current.title === '' || current.title === 'New Chat')) ||
+ (await deps.getActiveRunIds(req.user.id, [conversationId], req.user.tenantId)).length > 0
+ ) {
+ return res.status(409).json({ error: 'conversation_title_ownership_not_ready' });
+ }
+ }
+ const sanitizedTitle = title.trim().slice(0, 1024);
+ if (req.config?.filters != null) {
+ const finding = inspectContent(extractConversationTitleContent({ title: sanitizedTitle }), {
+ filters: req.config.filters,
+ });
+ if (finding) return res.status(400).json(contentFilterBlockResponse(finding));
+ }
+ const saved = await deps.saveConvo(
+ {
+ userId: req.user.id,
+ isTemporary: current.isTemporary,
+ expiredAt: current.expiredAt,
+ interfaceConfig: req.config?.interfaceConfig,
+ },
+ { conversationId, title: sanitizedTitle },
+ {
+ context: 'POST /api/convos/update',
+ titleSource: 'manual',
+ appendMessageIds: [],
+ noUpsert: true,
+ },
+ );
+ if (saved == null) return res.status(404).json({ error: 'conversation_not_found' });
+ if ('message' in saved) throw new Error('Conversation rename persistence failed');
+ return res.status(201).json(saved);
+ } catch (error) {
+ deps.logger.error('[rename] Conversation title update failed', getSafeErrorMetadata(error));
+ return res.status(500).send('Error updating conversation');
+ }
+ };
+}
diff --git a/packages/api/src/conversations/title.spec.ts b/packages/api/src/conversations/title.spec.ts
new file mode 100644
index 0000000000..e1d8ccac70
--- /dev/null
+++ b/packages/api/src/conversations/title.spec.ts
@@ -0,0 +1,75 @@
+import express from 'express';
+import request from 'supertest';
+import { createGeneratedTitleHandler } from './title';
+
+function setup(authenticated = true) {
+ const cache = {
+ get: jest.fn().mockResolvedValue('Generated'),
+ delete: jest.fn().mockResolvedValue(true),
+ set: jest.fn(),
+ };
+ const deps = {
+ getCache: () => cache,
+ getConvoTitleState: jest.fn().mockResolvedValue(null),
+ logger: { error: jest.fn() },
+ delay: jest.fn().mockResolvedValue(undefined),
+ };
+ const handler = createGeneratedTitleHandler(deps);
+ const app = express();
+ app.get<{ conversationId: string }>('/title/:conversationId', async (req, res) => {
+ await handler({ params: req.params, user: authenticated ? { id: 'user-1' } : undefined }, res);
+ });
+ return { app, cache, deps };
+}
+
+describe('generated title polling', () => {
+ it('keeps legacy string cache values and generated responses compatible', async () => {
+ const { app, cache, deps } = setup();
+ const response = await request(app).get('/title/chat');
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ title: 'Generated' });
+ expect(deps.getConvoTitleState).toHaveBeenCalledWith('user-1', 'chat');
+ expect(cache.delete).toHaveBeenCalledWith('user-1-chat');
+ });
+
+ it.each(['Newest rename', 'New Chat', ''])(
+ 'returns current manual authority for %s',
+ async (title) => {
+ const { app, deps } = setup();
+ deps.getConvoTitleState.mockResolvedValue({ title, titleSetByUser: true, titleRevision: 2 });
+ const response = await request(app).get('/title/chat');
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ title, titleSetByUser: true, titleRevision: 2 });
+ },
+ );
+
+ it('preserves the bounded not-ready polling delays without database reads', async () => {
+ const { app, cache, deps } = setup();
+ cache.get.mockResolvedValue(undefined);
+ const response = await request(app).get('/title/chat');
+ expect(response.status).toBe(404);
+ expect(deps.delay.mock.calls.map(([milliseconds]) => milliseconds)).toEqual([
+ 500, 1000, 2000, 4000, 8000,
+ ]);
+ expect(deps.getConvoTitleState).not.toHaveBeenCalled();
+ expect(cache.delete).not.toHaveBeenCalled();
+ });
+
+ it('does not consume the cache or expose diagnostics on a database failure', async () => {
+ const { app, cache, deps } = setup();
+ deps.getConvoTitleState.mockRejectedValue(new Error('secret-provider-payload'));
+ const response = await request(app).get('/title/chat');
+ expect(response.status).toBe(500);
+ expect(response.body).toEqual({ error: 'title_read_failed' });
+ expect(cache.delete).not.toHaveBeenCalled();
+ expect(deps.logger.error).toHaveBeenCalledWith('[gen_title] Title lookup failed', {
+ type: 'Error',
+ });
+ });
+
+ it('does not read cache state without an authenticated owner', async () => {
+ const { app, cache } = setup(false);
+ expect((await request(app).get('/title/chat')).status).toBe(401);
+ expect(cache.get).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/conversations/title.ts b/packages/api/src/conversations/title.ts
new file mode 100644
index 0000000000..a95fab23b4
--- /dev/null
+++ b/packages/api/src/conversations/title.ts
@@ -0,0 +1,167 @@
+import { setTimeout as delay } from 'node:timers/promises';
+import type { ConversationMethods } from '@librechat/data-schemas';
+import type { Response } from 'express';
+import type { ConversationWriteContext } from './save';
+import { getSafeErrorMetadata } from '~/utils/errors';
+
+type TitleCache = {
+ get: (key: string) => Promise<string | undefined>;
+ set: (key: string, title: string, ttl: number) => Promise<boolean>;
+ delete: (key: string) => Promise<boolean>;
+};
+
+type TitlePublication = {
+ ctx: ConversationWriteContext;
+ conversationId: string;
+ title: string;
+ convoReady?: Promise<void>;
+ signal?: AbortSignal;
+ discardSignal?: AbortSignal;
+ onTitleGenerated?: (event: { conversationId: string; title: string }) => Promise<void> | void;
+};
+
+/** Explicit renames own persisted titles; an unsaved first turn can still publish eagerly. */
+export async function publishConversationTitle(
+ {
+ saveConvo,
+ getConvo,
+ titleCache,
+ }: Pick<ConversationMethods, 'saveConvo' | 'getConvo'> & {
+ titleCache: TitleCache;
+ },
+ {
+ ctx,
+ conversationId,
+ title,
+ convoReady,
+ signal,
+ discardSignal,
+ onTitleGenerated,
+ }: TitlePublication,
+): Promise<void> {
+ if (discardSignal?.aborted) {
+ return;
+ }
+ const key = `${ctx.userId}-${conversationId}`;
+ const commit = async () => {
+ const saved = await saveConvo(
+ ctx,
+ { conversationId, title },
+ {
+ context: 'publishConversationTitle',
+ titleSource: 'generated',
+ noUpsert: true,
+ preserveUpdatedAt: true,
+ appendMessageIds: [],
+ },
+ );
+ if (saved != null && 'message' in saved) {
+ throw new Error('Conversation title persistence failed');
+ }
+ return saved;
+ };
+ let publishedEarly = false;
+ if (convoReady != null) {
+ const initial = await getConvo(ctx.userId, conversationId);
+ if (
+ !discardSignal?.aborted &&
+ (initial == null ||
+ (!initial.titleSetByUser &&
+ (initial.title == null || initial.title === '' || initial.title === 'New Chat')))
+ ) {
+ await titleCache.set(key, title, 120000);
+ if (!signal?.aborted) {
+ await onTitleGenerated?.({ conversationId, title });
+ }
+ publishedEarly = true;
+ }
+ await convoReady;
+ }
+ if (discardSignal?.aborted) {
+ if (publishedEarly && (await titleCache.get(key)) === title) {
+ await titleCache.delete(key);
+ }
+ return;
+ }
+ let saved = await commit();
+ let current = saved ?? (await getConvo(ctx.userId, conversationId));
+ if (
+ saved == null &&
+ convoReady != null &&
+ current != null &&
+ !current.titleSetByUser &&
+ (current.title == null || current.title === '' || current.title === 'New Chat') &&
+ !discardSignal?.aborted
+ ) {
+ saved = await commit();
+ current = saved ?? (await getConvo(ctx.userId, conversationId));
+ }
+ if (current?.title == null || discardSignal?.aborted) {
+ return;
+ }
+ if (!publishedEarly || current.title !== title) {
+ await titleCache.set(key, current.title, 120000);
+ }
+ if (saved && !publishedEarly && !signal?.aborted) {
+ await onTitleGenerated?.({ conversationId, title: current.title });
+ }
+}
+
+/** Detached fallback publication owns its failure after the response has ended. */
+export async function publishFallbackConversationTitle(
+ deps: Parameters<typeof publishConversationTitle>[0] & {
+ logger: { error: (message: string, metadata: ReturnType<typeof getSafeErrorMetadata>) => void };
+ },
+ publication: TitlePublication,
+): Promise<void> {
+ try {
+ await publishConversationTitle(deps, publication);
+ } catch (error) {
+ deps.logger.error('[addTitle] Fallback publication failed', getSafeErrorMetadata(error));
+ }
+}
+
+type GeneratedTitleRequest = { params: { conversationId: string }; user?: { id: string } };
+
+type GeneratedTitleDependencies = Pick<ConversationMethods, 'getConvoTitleState'> & {
+ getCache: () => TitleCache;
+ logger: { error: (message: string, metadata: ReturnType<typeof getSafeErrorMetadata>) => void };
+ delay?: (milliseconds: number) => Promise<void>;
+};
+
+/** Keep the shared cache string-compatible with legacy replicas; project authority at read time. */
+export function createGeneratedTitleHandler(
+ deps: GeneratedTitleDependencies,
+): (req: GeneratedTitleRequest, res: Response) => Promise<Response> {
+ return async function generatedTitleHandler(req, res) {
+ const { conversationId } = req.params;
+ const userId = req.user?.id;
+ if (!userId) return res.status(401).json({ error: 'unauthorized' });
+ try {
+ const cache = deps.getCache();
+ const key = `${userId}-${conversationId}`;
+ let title = await cache.get(key);
+ if (title == null) {
+ for (const milliseconds of [500, 1000, 2000, 4000, 8000]) {
+ await (deps.delay ?? delay)(milliseconds);
+ title = await cache.get(key);
+ if (title != null) break;
+ }
+ }
+ if (title == null)
+ return res.status(404).json({
+ message: "Title not found or method not implemented for the conversation's endpoint",
+ });
+ const current = await deps.getConvoTitleState(userId, conversationId);
+ const result =
+ current?.titleSetByUser && current.title != null
+ ? { title: current.title, titleSetByUser: true, titleRevision: current.titleRevision }
+ : { title };
+ await cache.delete(key);
+ return res.status(200).json(result);
+ } catch (error) {
+ deps.logger.error('[gen_title] Title lookup failed', getSafeErrorMetadata(error));
+ return res.status(500).json({ error: 'title_read_failed' });
+ }
+ };
+}
diff --git a/packages/client/src/components/DropdownPopup.spec.tsx b/packages/client/src/components/DropdownPopup.spec.tsx
index 01b2f54f6d..5fe9f47875 100644
--- a/packages/client/src/components/DropdownPopup.spec.tsx
+++ b/packages/client/src/components/DropdownPopup.spec.tsx
@@ -1,6 +1,6 @@
-import React from 'react';
+import React, { useRef, useState } from 'react';
import * as Ariakit from '@ariakit/react';
-import { render } from '@testing-library/react';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import DropdownPopup from './DropdownPopup';
describe('DropdownPopup', () => {
@@ -10,7 +10,7 @@ describe('DropdownPopup', () => {
// would inherit `none`, making every item hit-transparent (#14487).
document.body.style.pointerEvents = 'none';
- render(
+ const { unmount } = render(
<DropdownPopup
menuId="portal-click-test-menu"
isOpen={true}
@@ -30,6 +30,34 @@ describe('DropdownPopup', () => {
expect(menu).not.toBeNull();
expect(menu).toHaveClass('pointer-events-auto');
+ unmount();
document.body.style.pointerEvents = '';
});
+ it('focuses an externally opened menu', async () => {
+ function Example() {
+ const [open, setOpen] = useState(false);
+ const trigger = useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <button onClick={() => setOpen(true)}>Open externally</button>
+ <DropdownPopup
+ menuId="external-menu"
+ isOpen={open}
+ setIsOpen={setOpen}
+ autoFocusOnShow={true}
+ unmountOnHide={true}
+ finalFocus={trigger}
+ trigger={<Ariakit.MenuButton ref={trigger}>Options</Ariakit.MenuButton>}
+ items={[{ label: 'Rename', onClick: jest.fn() }]}
+ />
+ </>
+ );
+ }
+ render(<Example />);
+ fireEvent.click(screen.getByRole('button', { name: 'Open externally' }));
+ const menu = await screen.findByRole('menu');
+ await waitFor(() => expect(menu).toHaveFocus());
+ fireEvent.keyDown(menu, { key: 'Escape' });
+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument());
+ });
});
diff --git a/packages/client/src/components/DropdownPopup.tsx b/packages/client/src/components/DropdownPopup.tsx
index 0da9a37edd..08c27d5bb1 100644
--- a/packages/client/src/components/DropdownPopup.tsx
+++ b/packages/client/src/components/DropdownPopup.tsx
@@ -1,4 +1,4 @@
-import React from 'react';
+import React, { useEffect } from 'react';
import * as Ariakit from '@ariakit/react';
import type * as t from '~/common';
import { usePopoverZIndex } from './OriginalDialog';
@@ -26,6 +26,8 @@ interface DropdownProps {
mountByState?: boolean;
unmountOnHide?: boolean;
finalFocus?: React.RefObject<HTMLElement>;
+ autoFocusOnShow?: Ariakit.MenuProps['autoFocusOnShow'];
+ getAnchorRect?: Ariakit.MenuProps['getAnchorRect'];
}
type MenuProps = Omit<
@@ -40,21 +42,27 @@ const DropdownPopup: React.FC<DropdownProps> = ({
setIsOpen,
focusLoop,
mountByState,
+ autoFocusOnShow,
...props
}) => {
const menu = Ariakit.useMenuStore({ open: isOpen, setOpen: setIsOpen, focusLoop });
+ useEffect(() => {
+ if (isOpen && autoFocusOnShow === true) {
+ menu.setAutoFocusOnShow(true);
+ }
+ }, [isOpen, autoFocusOnShow, menu]);
if (mountByState) {
return (
<Ariakit.MenuProvider store={menu}>
{trigger}
- {isOpen && <Menu {...props} />}
+ {isOpen && <Menu {...props} autoFocusOnShow={autoFocusOnShow} />}
</Ariakit.MenuProvider>
);
}
return (
<Ariakit.MenuProvider store={menu}>
{trigger}
- <Menu {...props} />
+ <Menu {...props} autoFocusOnShow={autoFocusOnShow} />
</Ariakit.MenuProvider>
);
};
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index addf042c7b..95c4aa3260 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -10,6 +10,7 @@ import {
DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS,
codeEnvironmentUserConfigSchema,
interfaceSchema,
+ supportsConversationTitleOwnership,
CODE_ENVIRONMENT_ADMISSION_MAX_MS,
excludedKeys,
DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
@@ -2519,6 +2520,29 @@ describe('subagent activity policy', () => {
});
});
+describe('conversation title ownership rollout', () => {
+ it('defaults running rename off and accepts only an explicit deployment opt-in', () => {
+ expect(interfaceSchema.parse({}).runningChatRename).toBe(false);
+ expect(interfaceSchema.parse(undefined).runningChatRename).toBe(false);
+ expect(interfaceSchema.parse({ runningChatRename: true }).runningChatRename).toBe(true);
+ });
+ it('fails closed when an old replica omits the version or the operator leaves the fence off', () => {
+ expect(supportsConversationTitleOwnership(undefined)).toBe(false);
+ expect(supportsConversationTitleOwnership({ interface: { runningChatRename: true } })).toBe(
+ false,
+ );
+ expect(supportsConversationTitleOwnership({ conversationTitleOwnershipVersion: 1 })).toBe(
+ false,
+ );
+ expect(
+ supportsConversationTitleOwnership({
+ conversationTitleOwnershipVersion: 1,
+ interface: { runningChatRename: true },
+ }),
+ ).toBe(true);
+ });
+});
+
describe('workspace admission configuration', () => {
it('preserves absent defaults and resolves an explicit admission policy', () => {
expect(codeEnvironmentUserConfigSchema.parse({})).toEqual({});
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index bdd91bbffa..6b983c6ea9 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -139,6 +139,8 @@ export const excludedKeys = new Set([
'agentEventActorLegacyTurn',
'subagentThread',
'title',
+ 'titleSetByUser',
+ 'titleRevision',
'iconURL',
'greeting',
'endpoint',
@@ -2540,6 +2542,8 @@ export const interfaceSchema = z
customWelcome: z.string().optional(),
mcpServers: mcpServersSchema.optional(),
modelSelect: z.boolean().optional(),
+ /** Enable only after every API replica supports title ownership and old title jobs drain. */
+ runningChatRename: z.boolean().default(false),
/** Milliseconds between syntax highlights while a code block streams. */
codeHighlightThrottleMs: z.number().int().min(0).max(60_000).default(300),
/** Most agents the agents panel selector lists before a search term is
@@ -2764,6 +2768,7 @@ export const interfaceSchema = z
})
.default({
modelSelect: true,
+ runningChatRename: false,
codeHighlightThrottleMs: 300,
agentSelectorLimit: DEFAULT_AGENT_SELECTOR_LIMIT,
parameters: true,
@@ -2973,7 +2978,21 @@ export function resolveMCPAppsPolicy(
};
}
+export const CONVERSATION_TITLE_OWNERSHIP_VERSION = 1 as const;
+
+/** Missing capability means an older replica, even when its YAML has the new option. */
+export function supportsConversationTitleOwnership(config?: {
+ conversationTitleOwnershipVersion?: typeof CONVERSATION_TITLE_OWNERSHIP_VERSION;
+ interface?: Pick<TInterfaceConfig, 'runningChatRename'>;
+}): boolean {
+ return (
+ config?.conversationTitleOwnershipVersion === CONVERSATION_TITLE_OWNERSHIP_VERSION &&
+ config.interface?.runningChatRename === true
+ );
+}
+
export type TStartupConfig = {
+ conversationTitleOwnershipVersion?: typeof CONVERSATION_TITLE_OWNERSHIP_VERSION;
appTitle: string;
socialLogins?: string[];
langfuseFanoutEnabled?: boolean;
diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.ts
index cc2d11e708..375de52efa 100644
--- a/packages/data-provider/src/schemas.ts
+++ b/packages/data-provider/src/schemas.ts
@@ -1214,6 +1214,9 @@ export const tConversationSchema = z.object({
)
.optional(),
title: z.string().nullable().or(z.literal('New Chat')).default('New Chat'),
+ /** Server-owned title authority; ordinary chat saves cannot set or clear it. */
+ titleSetByUser: z.boolean().optional(),
+ titleRevision: z.number().int().nonnegative().optional(),
user: z.string().optional(),
messages: z.array(z.string()).optional(),
tools: z.union([z.array(tPluginSchema), z.array(z.string())]).optional(),
@@ -1323,6 +1326,8 @@ export const tPresetSchema = tConversationSchema
createdAt: true,
updatedAt: true,
title: true,
+ titleSetByUser: true,
+ titleRevision: true,
/* Runtime unseen-reply state must not ride into presets: applying one would stamp
stale timestamps back onto conversations. */
lastResponseAt: true,
diff --git a/packages/data-provider/src/types/mutations.ts b/packages/data-provider/src/types/mutations.ts
index a99e5a45e7..15f14a17d7 100644
--- a/packages/data-provider/src/types/mutations.ts
+++ b/packages/data-provider/src/types/mutations.ts
@@ -47,6 +47,8 @@ export type TGenTitleRequest = {
export type TGenTitleResponse = {
title: string;
+ titleSetByUser?: boolean;
+ titleRevision?: number;
};
export type PresetDeleteResponse = {
diff --git a/packages/data-schemas/src/app/interface.spec.ts b/packages/data-schemas/src/app/interface.spec.ts
index 6f00713121..f546f8d9d0 100644
--- a/packages/data-schemas/src/app/interface.spec.ts
+++ b/packages/data-schemas/src/app/interface.spec.ts
@@ -427,3 +427,17 @@ describe('loadDefaultInterface', () => {
expect(interfaceConfig).not.toHaveProperty('theme');
});
});
+
+describe('running chat rename deployment fence', () => {
+ it.each([undefined, false, true])(
+ 'forwards operator opt-in without enabling it by default: %s',
+ async (enabled) => {
+ const configDefaults = getConfigDefaults();
+ const interfaceConfig = await loadDefaultInterface({
+ config: { interface: enabled === undefined ? {} : { runningChatRename: enabled } },
+ configDefaults,
+ });
+ expect(interfaceConfig?.runningChatRename).toBe(enabled === true);
+ },
+ );
+});
diff --git a/packages/data-schemas/src/app/interface.ts b/packages/data-schemas/src/app/interface.ts
index 96739f3cd4..8e4340c5d5 100644
--- a/packages/data-schemas/src/app/interface.ts
+++ b/packages/data-schemas/src/app/interface.ts
@@ -32,6 +32,7 @@ export async function loadDefaultInterface({
modelSelect:
interfaceConfig?.modelSelect ??
(hasModelSpecs ? includesAddedEndpoints : defaults.modelSelect),
+ runningChatRename: interfaceConfig?.runningChatRename ?? defaults.runningChatRename,
codeHighlightThrottleMs:
interfaceConfig?.codeHighlightThrottleMs ?? defaults.codeHighlightThrottleMs,
agentSelectorLimit: interfaceConfig?.agentSelectorLimit ?? defaults.agentSelectorLimit,
diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.ts
index 60d3b37f49..3498cf9e7f 100644
--- a/packages/data-schemas/src/methods/conversation.spec.ts
+++ b/packages/data-schemas/src/methods/conversation.spec.ts
@@ -655,6 +655,143 @@ describe('Conversation Operations', () => {
expect(result?.conversationId).toBe(mockConversationData.conversationId);
});
+ describe('generated title ownership', () => {
+ const generated = { titleSource: 'generated' as const, appendMessageIds: [] };
+ const manual = { titleSource: 'manual' as const, appendMessageIds: [] };
+
+ it('does not upsert a missing conversation', async () => {
+ const conversationId = uuidv4();
+ expect(
+ await saveConvo(mockCtx, { conversationId, title: 'Generated' }, generated),
+ ).toBeNull();
+ expect(await Conversation.countDocuments({ conversationId })).toBe(0);
+ });
+
+ it.each(['Renamed', 'New Chat', ''])('preserves an explicit rename to %s', async (title) => {
+ const conversationId = uuidv4();
+ await saveConvo(mockCtx, { conversationId });
+ await saveConvo(mockCtx, { conversationId, title }, manual);
+ expect(
+ await saveConvo(mockCtx, { conversationId, title: 'Generated' }, generated),
+ ).toBeNull();
+ expect((await getConvo(mockCtx.userId, conversationId))?.title).toBe(title);
+ await saveConvo(mockCtx, { conversationId, titleSetByUser: false });
+ expect(await saveConvo(mockCtx, { conversationId, title: 'Later' }, generated)).toBeNull();
+ });
+
+ it('projects manual title authority and unread intent while ordering repeated renames', async () => {
+ const conversationId = uuidv4();
+ await saveConvo(mockCtx, { conversationId });
+ await methods.markConvoUnread(mockCtx.userId, conversationId);
+ await Promise.all([
+ saveConvo(mockCtx, { conversationId, title: 'First' }, manual),
+ saveConvo(mockCtx, { conversationId, title: 'New Chat' }, manual),
+ ]);
+ const current = await getConvo(mockCtx.userId, conversationId);
+ expect(current?.titleRevision).toBe(2);
+ expect(await methods.getConvoTitleState(mockCtx.userId, conversationId)).toEqual({
+ title: current?.title,
+ titleSetByUser: true,
+ titleRevision: 2,
+ });
+ expect(await methods.getConvoTitleState('another-owner', conversationId)).toBeNull();
+
+ const page = await getConvosByCursor(mockCtx.userId);
+ expect(page.conversations.find((row) => row.conversationId === conversationId)).toEqual(
+ expect.objectContaining({ titleSetByUser: true, titleRevision: 2, isMarkedUnread: true }),
+ );
+ await saveConvo(
+ mockCtx,
+ { conversationId, titleRevision: 99, titleSetByUser: false },
+ {
+ unsetFields: { titleRevision: 1, titleSetByUser: 1 },
+ appendMessageIds: [],
+ },
+ );
+ expect(await getConvo(mockCtx.userId, conversationId)).toEqual(
+ expect.objectContaining({
+ titleSetByUser: true,
+ titleRevision: 2,
+ }),
+ );
+ });
+
+ it('preserves remembered approvals while claiming manual title ownership', async () => {
+ const conversationId = uuidv4();
+ await saveConvo(mockCtx, { conversationId });
+ await methods.addConvoToolApprovalAllows({
+ user: mockCtx.userId,
+ conversationId,
+ toolNames: ['kept'],
+ max: 64,
+ });
+ const stale = {
+ conversationId,
+ toolApprovalAllows: ['*'],
+ titleSetByUser: false,
+ titleRevision: 99,
+ };
+ const unsetFields = { toolApprovalAllows: 1, titleSetByUser: 1, titleRevision: 1 };
+ const saved = await saveConvo(
+ mockCtx,
+ { ...stale, title: 'Renamed' },
+ { ...manual, unsetFields },
+ );
+ expect(saved).toEqual(
+ expect.objectContaining({
+ title: 'Renamed',
+ titleSetByUser: true,
+ titleRevision: 1,
+ toolApprovalAllows: ['kept'],
+ }),
+ );
+ expect(
+ await saveConvo(mockCtx, { ...stale, title: 'Generated' }, { ...generated, unsetFields }),
+ ).toBeNull();
+ expect(await getConvo(mockCtx.userId, conversationId)).toEqual(
+ expect.objectContaining({
+ title: 'Renamed',
+ titleSetByUser: true,
+ titleRevision: 1,
+ toolApprovalAllows: ['kept'],
+ }),
+ );
+ });
+
+ it('preserves renamed legacy rows without an ownership flag', async () => {
+ await saveConvo(mockCtx, mockConversationData);
+ expect(
+ await saveConvo(mockCtx, { ...mockConversationData, title: 'Generated' }, generated),
+ ).toBeNull();
+ });
+
+ it('atomically preserves a rename that races generation', async () => {
+ const conversationId = uuidv4();
+ await saveConvo(mockCtx, { conversationId });
+ await Promise.all([
+ saveConvo(mockCtx, { conversationId, title: 'Generated' }, generated),
+ saveConvo(mockCtx, { conversationId, title: 'Renamed' }, manual),
+ ]);
+ expect((await getConvo(mockCtx.userId, conversationId))?.title).toBe('Renamed');
+ });
+
+ it('publishes a generated title without moving activity or messages', async () => {
+ const conversationId = uuidv4();
+ const initial = await saveConvo(mockCtx, { conversationId });
+ const saved = await saveConvo(
+ mockCtx,
+ { conversationId, title: 'Generated' },
+ {
+ ...generated,
+ preserveUpdatedAt: true,
+ },
+ );
+ expect(saved?.title).toBe('Generated');
+ expect(saved?.updatedAt).toEqual(initial?.updatedAt);
+ expect(saved?.messages).toEqual(initial?.messages);
+ });
+ });
+
it('should still upsert by default when noUpsert is not provided', async () => {
const newId = uuidv4();
const result = await saveConvo(mockCtx, {
@@ -1823,6 +1960,27 @@ describe('Conversation Operations', () => {
expect(stored?.messages?.map(String)).toEqual([...seeded, appended].map(String));
});
+ it('keeps response references when an explicit rename lands concurrently', async () => {
+ const userMessage = new mongoose.Types.ObjectId();
+ const responseMessage = new mongoose.Types.ObjectId();
+ await saveConvo(ctx, { conversationId }, { appendMessageIds: [userMessage] });
+ await Promise.all([
+ saveConvo(
+ ctx,
+ { conversationId, title: 'Renamed while running' },
+ {
+ titleSource: 'manual',
+ appendMessageIds: [],
+ },
+ ),
+ saveConvo(ctx, { conversationId }, { appendMessageIds: [responseMessage] }),
+ ]);
+ const stored = await getConvo(ctx.userId, conversationId);
+ expect(stored?.messages?.map(String)).toEqual([userMessage, responseMessage].map(String));
+ expect(stored?.title).toBe('Renamed while running');
+ expect(getMessages).not.toHaveBeenCalled();
+ });
+
it('does not duplicate an id that is already recorded', async () => {
const id = new mongoose.Types.ObjectId();
await saveConvo(ctx, { conversationId }, { appendMessageIds: [id] });
diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.ts
index d151393bee..074e5ea8c3 100644
--- a/packages/data-schemas/src/methods/conversation.ts
+++ b/packages/data-schemas/src/methods/conversation.ts
@@ -259,6 +259,11 @@ async function refreshChatProjectStatsInBatches(
}
}
+export type ConversationTitleState = Pick<
+ IConversation,
+ 'title' | 'titleSetByUser' | 'titleRevision'
+>;
+
export interface ConversationMethods {
getConvoFiles(conversationId: string): Promise<string[]>;
searchConversation(
@@ -283,6 +288,7 @@ export interface ConversationMethods {
noUpsert?: boolean;
createdAtOnInsert?: Date;
preserveUpdatedAt?: boolean;
+ titleSource?: 'manual' | 'generated';
/** Same-tenant persisted agent already resolved by the request layer. */
initialAgentId?: string | null;
/** `_id`s of messages this save just wrote. When present, they are appended with
@@ -383,6 +389,7 @@ export interface ConversationMethods {
convoMap: Record<string, unknown>;
}>;
getConvo(user: string, conversationId: string): Promise<IConversation | null>;
+ getConvoTitleState(user: string, conversationId: string): Promise<ConversationTitleState | null>;
getSubagentThreadForParent(input: {
user: string;
parentConversationId: string;
@@ -719,6 +726,16 @@ export function createConversationMethods(
}
}
+ async function getConvoTitleState(
+ user: string,
+ conversationId: string,
+ ): Promise<ConversationTitleState | null> {
+ const Conversation = mongoose.models.Conversation as Model<IConversation>;
+ return Conversation.findOne({ user, conversationId })
+ .select('title titleSetByUser titleRevision -_id')
+ .lean<ConversationTitleState>();
+ }
+
/** Resolves a child only through its owning parent and includes its private live lease. */
async function getSubagentThreadForParent(input: {
user: string;
@@ -2399,6 +2416,7 @@ export function createConversationMethods(
noUpsert?: boolean;
createdAtOnInsert?: Date;
preserveUpdatedAt?: boolean;
+ titleSource?: 'manual' | 'generated';
initialAgentId?: string | null;
/** Casts plain string ids, so callers outside this package need not name the id type. */
appendMessageIds?: Array<Types.ObjectId | string>;
@@ -2427,6 +2445,11 @@ export function createConversationMethods(
delete update.lastResponseAt;
delete update.lastResponseMessageId;
delete update.initial_agent_id;
+ delete update.titleSetByUser;
+ delete update.titleRevision;
+ if (metadata?.titleSource === 'manual') {
+ update.titleSetByUser = true;
+ }
/* Remembered tool approvals are granted only by a validated resume. */
delete update.toolApprovalAllows;
/** Ordinary saves may seed a decision, but only an explicit move may replace it. */
@@ -2451,6 +2474,8 @@ export function createConversationMethods(
delete unsetFields.lastResponseMessageId;
delete unsetFields.lastResponseAt;
delete unsetFields.initial_agent_id;
+ delete unsetFields.titleSetByUser;
+ delete unsetFields.titleRevision;
delete unsetFields.toolApprovalAllows;
delete unsetFields.codeEnvironmentRevision;
delete unsetFields.codeEnvironmentMode;
@@ -2560,7 +2585,7 @@ export function createConversationMethods(
timestampOptions.timestamps = false;
}
- const canUpsert = metadata?.noUpsert !== true;
+ const canUpsert = metadata?.noUpsert !== true && metadata?.titleSource !== 'generated';
const initialAgentId =
canUpsert &&
typeof metadata?.initialAgentId === 'string' &&
@@ -2570,6 +2595,9 @@ export function createConversationMethods(
const buildOperation = (setFields: Record<string, unknown>) => {
const operation: Record<string, unknown> = { $set: setFields };
+ if (metadata?.titleSource === 'manual') {
+ operation.$inc = { titleRevision: 1 };
+ }
if (appendMessageIds != null && appendMessageIds.length > 0) {
operation.$addToSet = { messages: { $each: appendMessageIds } };
}
@@ -2606,7 +2634,14 @@ export function createConversationMethods(
return operation;
};
- const baseFilter = { conversationId, user: userId };
+ const baseFilter = {
+ conversationId,
+ user: userId,
+ ...(metadata?.titleSource === 'generated' && {
+ titleSetByUser: { $ne: true },
+ title: { $in: [null, '', 'New Chat'] },
+ }),
+ };
const runUpdate = (
filter: Record<string, unknown>,
operation: Record<string, unknown>,
@@ -3532,7 +3567,7 @@ export function createConversationMethods(
the sidebar lists archived and unarchived chats in the same session, and the
active list also carries the unarchived pins beside them. */
.select(
- 'conversationId endpoint title createdAt updatedAt archivedAt isArchived user model agent_id assistant_id spec iconURL chatProjectId pinned lastResponseAt lastResponseMessageId lastResponseIsManual isMarkedUnread lastSeenAt',
+ 'conversationId endpoint title titleSetByUser titleRevision createdAt updatedAt archivedAt isArchived user model agent_id assistant_id spec iconURL chatProjectId pinned lastResponseAt lastResponseMessageId lastResponseIsManual isMarkedUnread lastSeenAt',
)
.sort(sortObj)
.limit(pageSize + 1)
@@ -4194,6 +4229,7 @@ export function createConversationMethods(
getConvosByCursor,
getConvosQueried,
getConvo,
+ getConvoTitleState,
getSubagentThreadForParent,
listSubagentThreadsForParent,
getAgentEventBinding,
diff --git a/packages/data-schemas/src/schema/convo.ts b/packages/data-schemas/src/schema/convo.ts
index 44c1349e30..c0d940bbcf 100644
--- a/packages/data-schemas/src/schema/convo.ts
+++ b/packages/data-schemas/src/schema/convo.ts
@@ -30,6 +30,8 @@ const convoSchema: Schema<IConversation> = new Schema(
default: 'New Chat',
meiliIndex: true,
},
+ titleSetByUser: { type: Boolean },
+ titleRevision: { type: Number },
user: {
type: String,
index: true,
diff --git a/packages/data-schemas/src/types/convo.ts b/packages/data-schemas/src/types/convo.ts
index ed2a5bd713..66b0b21dd7 100644
--- a/packages/data-schemas/src/types/convo.ts
+++ b/packages/data-schemas/src/types/convo.ts
@@ -250,6 +250,8 @@ export interface ISubagentThreadReservation {
export interface IConversation extends Document {
conversationId: string;
title?: string;
+ titleSetByUser?: boolean;
+ titleRevision?: number;
user?: string;
messages?: Types.ObjectId[];
isTemporary?: boolean;