From 19092e55bd205cc66e8d938f6b0f8e511d986db7 Mon Sep 17 00:00:00 2001 From: "lia-by-librechat[bot]" <328778573+lia-by-librechat[bot]@users.noreply.github.com> Date: Sat, 3 Oct 2026 23:17:15 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=96=B2=EF=B8=8F=20fix:=20Enable=20Running?= =?UTF-8?q?=20Chat=20Menus=20and=20Preserve=20Renamed=20Titles=20(#16697)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reconciles current dev while preserving manual title ownership, existing menus, and configuration regressions. Co-authored-by: Lia --- .github/workflows/playwright-mock.yml | 19 + .../__test-utils__/convos-route-mocks.js | 9 + api/server/routes/__tests__/convos.spec.js | 24 ++ api/server/routes/config.js | 2 + api/server/routes/convos.js | 104 +---- api/server/services/Endpoints/agents/title.js | 72 +--- .../services/Endpoints/agents/title.test.js | 147 ++++++- .../services/Endpoints/assistants/title.js | 49 +-- .../Endpoints/assistants/title.test.js | 28 ++ client/src/components/Conversations/Convo.tsx | 49 ++- .../components/Conversations/ConvoActions.tsx | 19 +- .../ConvoOptions/ConvoOptions.tsx | 20 +- .../__tests__/Convo.status.spec.tsx | 5 +- .../__tests__/Convo.touch.spec.tsx | 140 +++++- .../__tests__/Convo.unpin.spec.tsx | 1 + .../SSE/__tests__/useTitleGeneration.test.ts | 78 +++- client/src/data-provider/SSE/queries.ts | 27 +- .../__tests__/renameConversation.spec.tsx | 127 +++++- client/src/data-provider/mutations.ts | 28 +- .../Conversations/useNavigateToConvo.tsx | 26 +- .../src/hooks/SSE/__tests__/titles.spec.tsx | 407 ++++++++++++++++++ .../useEventHandlers.cancel.spec.tsx | 4 +- client/src/hooks/SSE/useEventHandlers.ts | 126 +++--- client/src/utils/convos.spec.ts | 125 ++++++ client/src/utils/convos.ts | 48 +++ e2e/README.md | 20 + e2e/config/librechat.e2e.yaml | 28 ++ e2e/setup/env.ts | 2 +- e2e/setup/fake-label-server.js | 25 +- .../mock/conversation-management.spec.ts | 361 +++++++++++++++- eslint-suppressions.json | 8 - librechat.example.yaml | 4 + packages/api/src/conversations/index.ts | 2 + packages/api/src/conversations/rename.spec.ts | 214 +++++++++ packages/api/src/conversations/rename.ts | 98 +++++ packages/api/src/conversations/title.spec.ts | 75 ++++ packages/api/src/conversations/title.ts | 167 +++++++ .../src/components/DropdownPopup.spec.tsx | 34 +- .../client/src/components/DropdownPopup.tsx | 14 +- packages/data-provider/src/config.spec.ts | 24 ++ packages/data-provider/src/config.ts | 19 + packages/data-provider/src/schemas.ts | 5 + packages/data-provider/src/types/mutations.ts | 2 + .../data-schemas/src/app/interface.spec.ts | 14 + packages/data-schemas/src/app/interface.ts | 1 + .../src/methods/conversation.spec.ts | 158 +++++++ .../data-schemas/src/methods/conversation.ts | 42 +- packages/data-schemas/src/schema/convo.ts | 2 + packages/data-schemas/src/types/convo.ts | 2 + 49 files changed, 2703 insertions(+), 302 deletions(-) create mode 100644 client/src/hooks/SSE/__tests__/titles.spec.tsx create mode 100644 packages/api/src/conversations/rename.spec.ts create mode 100644 packages/api/src/conversations/rename.ts create mode 100644 packages/api/src/conversations/title.spec.ts create mode 100644 packages/api/src/conversations/title.ts 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} [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 ? ( - ); + ) : null; return (
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 ( { 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: