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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🔔 feat: Unseen Reply Indicators, Reply Notifications, and Mark as Unread (#15025)
Marco Berettacd4434464715
diff --git a/.gitignore b/.gitignoreindex 517f332fcf..007e0c297d 100644--- a/.gitignore+++ b/.gitignore@@ -193,3 +193,6 @@ scripts/activity-labels/results/!e2e/lighthouse/librechat.yaml/.lighthouse//e2e/lighthouse/.test-results/+# Chrome user-data directories a Lighthouse run leaves in the repository root when the browser+# is handed a Windows profile path from WSL: the whole path arrives as one directory name.+/*lighthouse.[0-9]*/diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.jsindex 643fd796ec..c00ed262fe 100644--- a/api/app/clients/BaseClient.js+++ b/api/app/clients/BaseClient.js@@ -29,6 +29,7 @@ const {runAfterSeed,saveTurnConversation,seedTurnConversation,+ announceReply,needsRetentionConversation,getConversationWriteContext,} = require('@librechat/api');@@ -1362,7 +1363,32 @@ class BaseClient {{ context: 'api/app/clients/BaseClient.js - saveMessageToDatabase #saveMessage' },);+ /** Only a reply that is actually in the message history may light an indicator: a write+ * that resolved empty (duplicate-key recovery that could not re-read the row) would+ * otherwise announce a reply nobody can open. */+ const persistedReply = savedMessage != null && message.isCreatedByUser === false;+if (this.skipSaveConvo) {+ /* The secondary response of an override pair persists its message but deliberately skips+ the conversation-field save, so the stamp below is never reached. The reply still has+ to light the indicator: the primary response's stamp is older whenever this one+ finishes later, and absent altogether when the primary failed. Best effort, because a+ missed indicator must not fail a reply that is already persisted. */+ /* `user` is the same id the message was just saved under; `reqCtx` carries an empty+ string when no request object is present, which the direct-save paths do not+ guarantee, so the fallback turns on truthiness rather than on nullishness. */+ await announceReply(db, {+ userId: reqCtx.userId || user || this.user,+ conversationId: message.conversationId,+ reply: {+ messageId: persistedReply ? savedMessage.messageId : undefined,+ content: message.content,+ text: message.text,+ attachments: message.attachments,+ isTemporary: reqCtx.isTemporary,+ },+ context: 'BaseClient - skipped conversation save',+ });return { message: savedMessage };}@@ -1376,6 +1402,14 @@ class BaseClient {ctx: reqCtx,initialized: this.fetchedConvo === true,savedMessageId: savedMessage?._id,+ reply: persistedReply+ ? {+ messageId: savedMessage.messageId,+ content: message.content,+ text: message.text,+ attachments: message.attachments,+ }+ : undefined,});if (initialized) {this.fetchedConvo = true;diff --git a/api/app/clients/specs/BaseClient.test.js b/api/app/clients/specs/BaseClient.test.jsindex 375f5f2d27..bf74718b09 100644--- a/api/app/clients/specs/BaseClient.test.js+++ b/api/app/clients/specs/BaseClient.test.js@@ -41,6 +41,7 @@ jest.mock('~/models', () => ({getConvoTitle: jest.fn(),getConvo: jest.fn(),saveConvo: jest.fn(),+ stampConvoLastResponse: jest.fn(),deleteConvos: jest.fn(),getPreset: jest.fn(),getPresets: jest.fn(),@@ -68,6 +69,7 @@ const {saveConvo,getFiles,getConvo,+ stampConvoLastResponse,} = require('~/models');jest.mock('@librechat/agents', () => {@@ -1765,6 +1767,123 @@ describe('BaseClient', () => {);});+ test('asks saveConvo to stamp the assistant reply but never the user turn', async () => {+ /* The timestamp itself is assigned inside `saveConvo`, past its own awaited reads, so a+ catch-up recorded while one of them is in flight cannot outrank the reply. */+ saveMessage.mockImplementation(async (_ctx, message) => message);+ const saveOptions = TestClient.getSaveOptions();+ TestClient.skipSaveConvo = false;+ saveConvo.mockClear();++ await TestClient.saveMessageToDatabase(+ { conversationId: 'convo-unseen', messageId: 'm1', isCreatedByUser: true, text: 'hi' },+ saveOptions,+ TestClient.user,+ );+ await TestClient.saveMessageToDatabase(+ { conversationId: 'convo-unseen', messageId: 'm2', isCreatedByUser: false, text: 'hello' },+ saveOptions,+ TestClient.user,+ );++ const [userTurn, reply] = saveConvo.mock.calls;+ /* A user turn stamping this would light the unseen dot the moment they press Enter. */+ expect(userTurn[1].lastResponseAt).toBeUndefined();+ expect(userTurn[2].stampReply).toBeUndefined();+ expect(reply[2].stampReply).toBe(true);+ expect(reply[2].replyMessageId).toBe('m2');+ });++ test('never stamps a reply whose message write resolved empty', async () => {+ /* Duplicate-key recovery that cannot re-read the row leaves no message to open, so an+ indicator would point at a reply that is not in the history. */+ saveMessage.mockResolvedValueOnce(undefined);+ const saveOptions = TestClient.getSaveOptions();+ TestClient.skipSaveConvo = false;+ saveConvo.mockClear();++ await TestClient.saveMessageToDatabase(+ { conversationId: 'convo-unseen', messageId: 'm7', isCreatedByUser: false, text: 'hello' },+ saveOptions,+ TestClient.user,+ );++ expect(saveConvo.mock.calls[0][2].stampReply).toBeUndefined();+ });++ test('stamps the reply of a response that skips the conversation save', async () => {+ /* The secondary response of an override pair persists its message and returns before the+ conversation-field save. Without its own stamp, a reply that finishes after the primary+ one, or is the only one that persisted, would never light an indicator. */+ saveMessage.mockImplementation(async (_ctx, message) => message);+ const saveOptions = TestClient.getSaveOptions();+ TestClient.skipSaveConvo = true;+ saveConvo.mockClear();+ stampConvoLastResponse.mockClear();++ await TestClient.saveMessageToDatabase(+ { conversationId: 'convo-override', messageId: 'm4', isCreatedByUser: true, text: 'hi' },+ saveOptions,+ 'user-override',+ );+ await TestClient.saveMessageToDatabase(+ { conversationId: 'convo-override', messageId: 'm5', isCreatedByUser: false, text: 'yo' },+ saveOptions,+ 'user-override',+ );++ TestClient.skipSaveConvo = false;+ expect(saveConvo).not.toHaveBeenCalled();+ expect(stampConvoLastResponse).toHaveBeenCalledTimes(1);+ expect(stampConvoLastResponse).toHaveBeenCalledWith('user-override', 'convo-override', 'm5');+ });++ test('never fails a persisted reply because its indicator stamp failed', async () => {+ saveMessage.mockImplementation(async (_ctx, message) => message);+ const saveOptions = TestClient.getSaveOptions();+ TestClient.skipSaveConvo = true;+ stampConvoLastResponse.mockClear();+ stampConvoLastResponse.mockRejectedValueOnce(new Error('mongo is down'));++ await expect(+ TestClient.saveMessageToDatabase(+ { conversationId: 'convo-override', messageId: 'm6', isCreatedByUser: false, text: 'yo' },+ saveOptions,+ 'user-override',+ ),+ ).resolves.toBeDefined();+ expect(stampConvoLastResponse).toHaveBeenCalledTimes(1);++ TestClient.skipSaveConvo = false;+ });++ test('keeps the unseen timestamps out of the user turn’s unsetFields', async () => {+ /* The real wipe threat: a user turn whose endpointOptions omit these fields builds an+ unsetFields list from the fetched conversation. excludedKeys must keep them out. */+ getConvo.mockResolvedValue({+ conversationId: 'convo-unseen',+ endpoint: 'openai',+ model: 'gpt-3.5-turbo',+ lastResponseAt: new Date(),+ lastResponseMessageId: 'reply-unseen',+ lastSeenAt: new Date(),+ });+ const saveOptions = TestClient.getSaveOptions();+ TestClient.skipSaveConvo = false;+ saveConvo.mockClear();++ await TestClient.saveMessageToDatabase(+ { conversationId: 'convo-unseen', messageId: 'm3', isCreatedByUser: true, text: 'again' },+ saveOptions,+ TestClient.user,+ );++ const [, , convoOptions] = saveConvo.mock.calls[0];+ expect(convoOptions.unsetFields).not.toHaveProperty('lastResponseAt');+ expect(convoOptions.unsetFields).not.toHaveProperty('lastSeenAt');+ expect(convoOptions.unsetFields).not.toHaveProperty('lastResponseMessageId');+ });+test('does not start the completed response write when terminal ownership is denied', async () => {const hookStarted = deferred();const terminalDecision = deferred();diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.jsindex ef482d04ae..14ecdf1908 100644--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js@@ -68,6 +68,7 @@ const mockFilterPersistableAbortContent = jest.fn((content) =>);const mockGetConvo = jest.fn();const mockGetMessages = jest.fn();+const mockStampConvoLastResponse = jest.fn().mockResolvedValue(undefined);const mockSaveMessage = jest.fn();const mockSaveConvo = jest.fn();const mockAppendConvoMessageReference = jest.fn();@@ -258,6 +259,10 @@ jest.mock('@librechat/api', () => ({getAgentErrorMetadata: (...args) =>jest.requireActual('@librechat/api').getAgentErrorMetadata(...args),sendEvent: jest.fn(),+ /** Real, because whether a skipped-persistence turn may raise an indicator is under test. */+ isAnnounceableReply: jest.requireActual('@librechat/api').isAnnounceableReply,+ announceReply: jest.requireActual('@librechat/api').announceReply,+ announceErrorTurn: jest.requireActual('@librechat/api').announceErrorTurn,logAgentMemorySnapshot: jest.fn(),isScheduleFireRequest: (...args) => mockIsScheduleFireRequest(...args),exemptFromConcurrencyLimiter: (...args) => mockExemptFromConcurrencyLimiter(...args),@@ -401,6 +406,7 @@ jest.mock('~/models', () => ({getAgentEventActorDetachedAction: (...args) => mockGetAgentEventActorDetachedAction(...args),claimAgentEventActorSuspension: (...args) => mockClaimAgentEventActorSuspension(...args),settleAgentEventActorSuspension: (...args) => mockSettleAgentEventActorSuspension(...args),+ stampConvoLastResponse: (...args) => mockStampConvoLastResponse(...args),isAgentTriggerPrincipalActive: (...args) => mockIsAgentTriggerPrincipalActive(...args),isSubagentOwnerAdmissible: (...args) => mockIsSubagentOwnerAdmissible(...args),}));@@ -6302,7 +6308,13 @@ describe('ResumableAgentController resume metadata', () => {getHaltReason: () => 'preempt_incomplete',};- const runFirstTurn = async ({ run, addTitle: suppliedAddTitle, clientOverrides } = {}) => {+ const runFirstTurn = async ({+ run,+ addTitle: suppliedAddTitle,+ clientOverrides,+ databaseResult,+ responseContent = [{ type: 'text', text: 'Truncated answer' }],+ } = {}) => {let signalFinished;const finished = new Promise((resolve) => {signalFinished = resolve;@@ -6334,10 +6346,12 @@ describe('ResumableAgentController resume metadata', () => {messageId: 'response-msg',parentMessageId: 'user-msg',conversationId: options.conversationId,- content: [{ type: 'text', text: 'Truncated answer' }],- databasePromise: Promise.resolve({- conversation: { conversationId: options.conversationId, title: null },- }),+ content: responseContent,+ databasePromise: Promise.resolve(+ databaseResult ?? {+ conversation: { conversationId: options.conversationId, title: null },+ },+ ),};}),};@@ -6374,6 +6388,69 @@ describe('ResumableAgentController resume metadata', () => {expect(addTitle).not.toHaveBeenCalled();});+ it('does not re-stamp an unfinished response already persisted by BaseClient', async () => {+ const stampedAt = new Date('2026-09-07T12:00:00.000Z');++ await runFirstTurn({+ run: preemptIncompleteRun,+ databaseResult: {+ conversation: {+ conversationId: 'new',+ title: null,+ lastResponseAt: stampedAt,+ },+ },+ });++ expect(mockStampConvoLastResponse).not.toHaveBeenCalled();+ const finalEvent = mockGenerationJobManager.publishTerminalClaim.mock.calls.at(-1)[1];+ expect(finalEvent.conversation.lastResponseAt).toEqual(stampedAt);+ });++ it('stamps and acknowledges the fallback conversation when BaseClient persistence is skipped', async () => {+ const stampedAt = new Date('2026-09-07T12:00:00.000Z');+ mockSaveMessage.mockImplementation(async (_ctx, message) => message);+ mockGetConvo.mockResolvedValue({+ conversationId: 'new',+ title: null,+ createdAt: '2026-06-07T00:00:00.000Z',+ lastResponseAt: stampedAt,+ });++ await runFirstTurn({+ run: preemptIncompleteRun,+ databaseResult: {+ persistenceSkipped: true,+ conversation: {+ conversationId: 'new',+ title: null,+ lastResponseAt: new Date('2026-09-07T11:59:00.000Z'),+ },+ },+ });++ expect(mockStampConvoLastResponse).toHaveBeenCalledTimes(1);+ const finalEvent = mockGenerationJobManager.publishTerminalClaim.mock.calls.at(-1)[1];+ expect(finalEvent.conversation.lastResponseAt).toEqual(stampedAt);+ });++ /* A preempted turn can persist its row before the model produced anything readable. A dot+ raised for that row could never be acknowledged, because acknowledgement requires the+ stamped reply to be on screen. */+ it('does not stamp a skipped-persistence turn that persisted nothing to read', async () => {+ mockSaveMessage.mockImplementation(async (_ctx, message) => message);++ await runFirstTurn({+ run: preemptIncompleteRun,+ responseContent: [],+ databaseResult: {+ persistenceSkipped: true,+ conversation: { conversationId: 'new', title: null },+ },+ });++ expect(mockStampConvoLastResponse).not.toHaveBeenCalled();+ });it('still generates a deferred title for a completed first turn', async () => {resolveTitleTiming.mockReturnValueOnce('final');diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.jsindex 33ff36bc5d..a01d9802eb 100644--- a/api/server/controllers/agents/__tests__/resume.spec.js+++ b/api/server/controllers/agents/__tests__/resume.spec.js@@ -93,6 +93,7 @@ const mockGetRoleByName = jest.fn();const mockCheckAccess = jest.fn();const mockCheckPermission = jest.fn();const mockDecryptMetadata = jest.fn();+const mockStampConvoLastResponse = jest.fn().mockResolvedValue(undefined);const mockDisposeClient = jest.fn();const mockGetMCPRequestContext = jest.fn();const mockCleanupMCPRequestContextForReq = jest.fn();@@ -172,6 +173,7 @@ jest.mock('~/models', () => ({mockMarkAgentEventActorDetachedActionRunning(...args),settleAgentEventActorDetachedAction: (...args) =>mockSettleAgentEventActorDetachedAction(...args),+ stampConvoLastResponse: (...args) => mockStampConvoLastResponse(...args),}));jest.mock('~/server/services/Endpoints/agents/eventChildLease', () => ({diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.jsindex 7135ca4113..ae7dbaeabf 100644--- a/api/server/controllers/agents/request.js+++ b/api/server/controllers/agents/request.js@@ -52,6 +52,8 @@ const {resolvePersistableCodeEnvironmentDecision,getFailedTurnTraceFields,resolveFailedTurnContent,+ announceReply,+ announceErrorTurn,} = require('@librechat/api');const { disposeClient } = require('~/server/cleanup');const {@@ -83,6 +85,7 @@ const {settleAgentEventActorDetachedAction,claimAgentEventActorSuspension,settleAgentEventActorSuspension,+ stampConvoLastResponse,isAgentTriggerPrincipalActive,isSubagentOwnerAdmissible,appendConvoMessageReference,@@ -544,6 +547,18 @@ async function saveErrorTurn(}: { context, noUpsert: true },);+ /* A failed run still persisted an assistant message, and a user on another device has no+ other way to learn the turn ended. */+ await announceErrorTurn(+ { stampConvoLastResponse },+ {+ userId,+ conversationId,+ messageId: savedErrorMessage.messageId,+ isTemporary: reqCtx.isTemporary,+ context: 'AgentController - persisted error turn',+ },+ );} catch (err) {logger.error('[AgentController] Failed to persist error turn', err);throw err;@@ -2901,11 +2916,12 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit* message's write is observed: the retry below cannot tell on its own* whether the conversation already references what it just re-saved. */convoSignal.observeMessageWrite(databasePromise);- const { conversation: convoData = {} } = await databasePromise;- const conversation = { ...convoData };+ const databaseResult = await databasePromise;+ const { conversation: convoData = {}, persistenceSkipped = false } = databaseResult;+ const responsePersistenceWasSkipped = persistenceSkipped === true;+ let conversation = { ...convoData };conversation.title =conversation && !conversation.title ? null : conversation?.title || 'New Chat';-if (!terminalClaim) {/** Stop/replacement won before the response persistence hook. The* BaseClient contract skipped its completed response write; cancel@@ -3064,6 +3080,37 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTitawait eventActorTurn?.historyPersisted();eventActorPersistenceComplete = true;+ /** A persisted BaseClient response already advanced lastResponseAt. Re-stamp only+ * when its terminal persistence was explicitly skipped, then refresh the payload's+ * conversation snapshot so it acknowledges the durable timestamp. */+ if (responseIsUnfinished && responsePersistenceWasSkipped) {+ const announced = await announceReply(+ { stampConvoLastResponse },+ {+ userId: reqCtx.userId,+ conversationId: response.conversationId,+ reply: {+ messageId: savedResponseMessage.messageId,+ content: response.content,+ text: response.text,+ attachments: response.attachments,+ isTemporary: reqCtx.isTemporary,+ },+ context: 'AgentController - skipped terminal persistence',+ },+ );+ if (announced) {+ try {+ const stampedConversation = await getConvo(reqCtx.userId, response.conversationId);+ if (stampedConversation) {+ conversation = { ...conversation, ...stampedConversation };+ }+ } catch (error) {+ logger.warn('[AgentController] Failed to read back the stamped conversation', error);+ }+ }+ }+// If the user stopped this turn — or an empty preempt boundary truncated// it, which persists under the same honest `unfinished` contract — cancel// the title still being generated, which never reaches its save. A titlediff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.jsindex 64f64237a0..016ee1d10a 100644--- a/api/server/controllers/agents/responses.js+++ b/api/server/controllers/agents/responses.js@@ -88,6 +88,7 @@ const {resolveAdmittedCodeEnvironmentDecision,resolvePersistableCodeEnvironmentDecision,createTerminalRunErrorObserver,+ announceReply,} = require('@librechat/api');const {createResponsesToolEndCallback,@@ -423,7 +424,7 @@ async function saveResponseOutput(const langfuseTraceFields = await getLangfuseTraceMessageFields(req.config, responseId);// Save the assistant message- await db.saveMessage(+ return db.saveMessage(req,{messageId: responseId,@@ -1415,7 +1416,7 @@ const executeResponse = async (envelope, { req, res }) => {// Build response for saving (use tracker with buildResponse for streaming)const finalResponse = buildResponse(context, tracker, 'completed');- await saveResponseOutput(+ const savedResponse = await saveResponseOutput(req,conversationId,responseId,@@ -1423,6 +1424,15 @@ const executeResponse = async (envelope, { req, res }) => {agentId,tracker.usage.outputTokens,);+ await announceReply(db, {+ userId: req?.user?.id,+ conversationId,+ reply: {+ ...savedResponse,+ isTemporary: req?.resolvedConversation?.isTemporary ?? req?.body?.isTemporary,+ },+ context: 'Responses API - announce stored reply',+ });logger.debug(`[Responses API] Stored response ${responseId} in conversation ${conversationId}`,@@ -1649,7 +1659,7 @@ const executeResponse = async (envelope, { req, res }) => {await saveInputMessages(req, conversationId, inputMessages, agentId);- await saveResponseOutput(+ const savedResponse = await saveResponseOutput(req,conversationId,responseId,@@ -1657,6 +1667,15 @@ const executeResponse = async (envelope, { req, res }) => {agentId,aggregator.usage.outputTokens,);+ await announceReply(db, {+ userId: req?.user?.id,+ conversationId,+ reply: {+ ...savedResponse,+ isTemporary: req?.resolvedConversation?.isTemporary ?? req?.body?.isTemporary,+ },+ context: 'Responses API - announce stored reply',+ });logger.debug(`[Responses API] Stored response ${responseId} in conversation ${conversationId}`,diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.jsindex fe4e200798..3fe3d6f372 100644--- a/api/server/controllers/agents/resume.js+++ b/api/server/controllers/agents/resume.js@@ -49,6 +49,7 @@ const {collectReachableAgents,restoreScheduledTokenContext,recoverTurnMessageReference,+ announceReply,} = require('@librechat/api');const { disposeClient } = require('~/server/cleanup');const { decryptMetadata } = require('~/server/services/ActionService');@@ -79,6 +80,7 @@ const {markAgentEventActorDetachedActionRunning,settleAgentEventActorDetachedAction,appendConvoMessageReference,+ stampConvoLastResponse,} = require('~/models');const {acquireEventChildGenerationLease,@@ -590,6 +592,24 @@ async function finalizeResumedTurn({metadata: meta,});+ /* This path saves the message directly, so nothing else stamps the unseen-reply+ indicator. Best-effort: a missed stamp must not fail the resumed turn. */+ await announceReply(+ { stampConvoLastResponse },+ {+ userId,+ conversationId,+ reply: {+ messageId: savedResponseMessage.messageId,+ content: responseMessage.content,+ text: responseMessage.text,+ attachments: responseMessage.attachments,+ isTemporary,+ },+ context: 'ResumeAgentController - resumed response end',+ },+ );+const convo = await getConvo(userId, conversationId);const conversation = { ...(convo ?? {}), conversationId };diff --git a/api/server/controllers/assistants/chat.contentFilter.spec.js b/api/server/controllers/assistants/chat.contentFilter.spec.jsindex f5f9ccc7e8..fe3fb8cf91 100644--- a/api/server/controllers/assistants/chat.contentFilter.spec.js+++ b/api/server/controllers/assistants/chat.contentFilter.spec.js@@ -5,6 +5,8 @@ const mockCreateRun = jest.fn();const mockStreamRunManager = jest.fn();const mockSendEvent = jest.fn();const mockSaveUserMessage = jest.fn();+const mockSaveAssistantMessage = jest.fn();+const mockCreateRunBody = jest.fn();const mockSendResponse = jest.fn();const mockHandleError = jest.fn();const mockRetrieveAssistant = jest.fn();@@ -66,7 +68,7 @@ jest.mock('~/server/services/Threads', () => ({saveUserMessage: (...args) => mockSaveUserMessage(...args),checkMessageGaps: jest.fn(),addThreadMetadata: jest.fn(),- saveAssistantMessage: jest.fn(),+ saveAssistantMessage: (...args) => mockSaveAssistantMessage(...args),}));jest.mock('~/server/services/AssistantService', () => ({@@ -104,7 +106,7 @@ jest.mock('~/server/services/Endpoints/assistants', () => ({}));jest.mock('~/server/services/createRunBody', () => ({- createRunBody: jest.fn(),+ createRunBody: (...args) => mockCreateRunBody(...args),}));jest.mock('~/server/middleware/error', () => ({@@ -163,6 +165,24 @@ describe.each([mockGetConvo.mockReset().mockResolvedValue(null);mockEncodeAndFormat.mockReset().mockResolvedValue({ files: [], image_urls: [] });mockInitThread.mockReset();+ mockCreateRun.mockReset();+ mockRunAssistant.mockReset();+ mockCreateRunBody.mockReset();+ /* Every run that reaches FINAL has persisted its assistant row: the controller publishes+ the conversation snapshot the client acknowledges, so a test that does not care about+ the write still needs one. Tests asserting on the stamp override this. */+ mockSaveAssistantMessage.mockReset().mockResolvedValue({+ message: { messageId: 'assistant-msg' },+ conversation: { conversationId: 'convo-1' },+ });+ mockGetOpenAIClient.mockReset().mockResolvedValue({+ openai: {+ beta: {+ assistants: { retrieve: mockRetrieveAssistant },+ threads: { messages: { list: mockListThreadMessages }, runs: {} },+ },+ },+ });closeHandler = undefined;req = {config: {@@ -237,6 +257,67 @@ describe.each([expect(mockHandleError).not.toHaveBeenCalled();expect(mockSendResponse).not.toHaveBeenCalled();}+ it('persists the assistant before FINAL and forwards the settled read-state stamp', async () => {+ const stamp = new Date('2026-09-08T12:00:00.000Z');+ const settledConversation = {+ conversationId: 'generated-id',+ endpoint: 'azureAssistants',+ lastResponseAt: stamp,+ lastSeenAt: undefined,+ lastResponseIsManual: undefined,+ title: 'Existing title',+ };+ mockCreateRunBody.mockReturnValue({});+ mockInitThread.mockResolvedValue({ thread_id: 'thread-new' });+ mockCreateRun.mockResolvedValue({ id: 'run-1' });+ mockRunAssistant.mockResolvedValue({+ run: { status: 'completed', usage: {} },+ responseMessage: { messageId: 'assistant-msg' },+ text: 'done',+ messages: [],+ steps: [],+ });+ mockSaveUserMessage.mockResolvedValue({ messageId: 'user-msg' });+ mockSaveAssistantMessage.mockResolvedValue({+ message: { messageId: 'assistant-msg' },+ conversation: settledConversation,+ });+ mockGetOpenAIClient.mockResolvedValue({+ openai: {+ _options: { model: 'gpt-4' },+ responseMessage: { messageId: 'assistant-msg' },+ beta: {+ assistants: { retrieve: mockRetrieveAssistant },+ threads: {+ messages: {+ list: mockListThreadMessages,+ update: jest.fn().mockResolvedValue({}),+ },+ runs: {},+ },+ },+ },+ });+ req.body.endpoint = 'azureAssistants';++ await chatController(req, res);++ const finalCall = mockSendEvent.mock.calls.find(([, event]) => event.final === true);+ expect(finalCall?.[1]).toEqual(+ expect.objectContaining({+ final: true,+ conversation: expect.objectContaining(settledConversation),+ }),+ );+ expect(mockSaveAssistantMessage.mock.invocationCallOrder[0]).toBeLessThan(+ mockSendEvent.mock.invocationCallOrder.at(-1),+ );+ expect(mockSaveAssistantMessage).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ messageId: 'assistant-msg' }),+ );+ expect(res.end).toHaveBeenCalledTimes(1);+ });it('releases a balance reservation that settles after thread initialization fails', async () => {req.config.filters = {};diff --git a/api/server/controllers/assistants/chatV1.js b/api/server/controllers/assistants/chatV1.jsindex a185e544c9..0f66c07154 100644--- a/api/server/controllers/assistants/chatV1.js+++ b/api/server/controllers/assistants/chatV1.js@@ -16,6 +16,7 @@ const {preflightAssistantRunContent,reportLocatorTraversalFailure,preflightAssistantUserMessageContent,+ settleAssistantFinal,} = require('@librechat/api');const {Time,@@ -704,9 +705,17 @@ const chatV1 = async (req, res) => {iconURL: endpointOption.iconURL,};+ if (userMessagePromise) {+ await userMessagePromise;+ }++ const settledConversation = await settleAssistantFinal(() =>+ saveAssistantMessage(req, { ...responseMessage, model }),+ );+sendEvent(res, {final: true,- conversation,+ conversation: { ...conversation, ...settledConversation },requestMessage: {parentMessageId,thread_id,@@ -714,11 +723,6 @@ const chatV1 = async (req, res) => {});res.end();- if (userMessagePromise) {- await userMessagePromise;- }- await saveAssistantMessage(req, { ...responseMessage, model });-if (parentMessageId === Constants.NO_PARENT && !_thread_id) {addTitle(req, {text,diff --git a/api/server/controllers/assistants/chatV2.js b/api/server/controllers/assistants/chatV2.jsindex 24f3b97691..d573b50b32 100644--- a/api/server/controllers/assistants/chatV2.js+++ b/api/server/controllers/assistants/chatV2.js@@ -15,6 +15,7 @@ const {preflightAssistantRunContent,reportLocatorTraversalFailure,preflightAssistantUserMessageContent,+ settleAssistantFinal,} = require('@librechat/api');const {Time,@@ -542,9 +543,17 @@ const chatV2 = async (req, res) => {iconURL: endpointOption.iconURL,};+ if (userMessagePromise) {+ await userMessagePromise;+ }++ const settledConversation = await settleAssistantFinal(() =>+ saveAssistantMessage(req, { ...responseMessage, model }),+ );+sendEvent(res, {final: true,- conversation,+ conversation: { ...conversation, ...settledConversation },requestMessage: {parentMessageId,thread_id,@@ -552,11 +561,6 @@ const chatV2 = async (req, res) => {});res.end();- if (userMessagePromise) {- await userMessagePromise;- }- await saveAssistantMessage(req, { ...responseMessage, model });-if (parentMessageId === Constants.NO_PARENT && !_thread_id) {addTitle(req, {text,diff --git a/api/server/middleware/abortMiddleware.js b/api/server/middleware/abortMiddleware.jsindex 532c748a7a..f4a22087ff 100644--- a/api/server/middleware/abortMiddleware.js+++ b/api/server/middleware/abortMiddleware.js@@ -8,6 +8,7 @@ const {GenerationJobManager,sanitizeMessageForTransmit,buildAbortedResponseMetadata,+ announceReply,} = require('@librechat/api');const { truncateText, smartTruncateText } = require('~/app/clients/prompts');const clearPendingReq = require('~/cache/clearPendingReq');@@ -78,7 +79,7 @@ async function abortMessage(req, res) {* (`AgentClient` labels a stopped turn `'abort'`), so billing here would* charge it a second time. This route only stops and persists. */- await db.saveMessage(+ const savedMessage = await db.saveMessage({userId: req?.user?.id,isTemporary: req?.resolvedConversation?.isTemporary ?? req?.body?.isTemporary,@@ -89,6 +90,28 @@ async function abortMessage(req, res) {{ context: 'api/server/middleware/abortMiddleware.js' },);+ /* Mirrors the agents abort route: when Stop wins the terminal claim, the request controller+ can return before its own save, making this direct write the only one that could reach+ the unseen-reply indicator. The assistants path stamps inside `syncMessages`; this one+ saves the message directly, so the stamp rides along here. Best-effort: the row is+ already durable, and a missed stamp must not suppress the final event.+ The temporary flag comes from the job: the client's abort request carries only the abort+ key and endpoint, so the request body alone would stamp a stopped temporary chat.+ An interrupt before the first real token still persists the unfinished assistant row, but+ that row renders nothing: stamping it would raise a dot for a reply with nothing to read,+ and opening the conversation could never clear it. */+ await announceReply(db, {+ userId,+ conversationId: jobData?.conversationId,+ reply: {+ messageId: savedMessage?.messageId,+ content,+ text,+ isTemporary: (jobData?.isTemporary ?? req?.body?.isTemporary) === true,+ },+ context: 'abortMessage',+ });+// Get conversation for titleconst conversation = await db.getConvo(userId, conversationId);diff --git a/api/server/middleware/abortMiddleware.spec.js b/api/server/middleware/abortMiddleware.spec.jsindex ee7ec98c20..b5f73b8397 100644--- a/api/server/middleware/abortMiddleware.spec.js+++ b/api/server/middleware/abortMiddleware.spec.js@@ -26,9 +26,12 @@ jest.mock('@librechat/data-schemas', () => ({}));jest.mock('@librechat/api', () => ({- /** Real implementation: these tests exist to verify abort classification- * itself, so mocking it would assert the mock rather than the behavior. */+ /** Real implementations: these tests exist to verify abort classification and the+ * readable-reply gate themselves, so mocking them would assert the mock rather than the+ * behavior. */isAbortError: jest.requireActual('@librechat/api').isAbortError,+ hasPersistableAbortContent: jest.requireActual('@librechat/api').hasPersistableAbortContent,+ announceReply: jest.requireActual('@librechat/api').announceReply,countTokens: jest.fn().mockResolvedValue(100),isEnabled: jest.fn().mockReturnValue(false),sendEvent: jest.fn(),@@ -64,6 +67,7 @@ const mockUpdateBalance = jest.fn().mockResolvedValue({});const mockBulkInsertTransactions = jest.fn().mockResolvedValue(undefined);jest.mock('~/models', () => ({saveMessage: jest.fn().mockResolvedValue(),+ stampConvoLastResponse: jest.fn().mockResolvedValue(),getConvo: jest.fn().mockResolvedValue({ title: 'Test Chat' }),updateBalance: mockUpdateBalance,bulkInsertTransactions: mockBulkInsertTransactions,@@ -195,6 +199,68 @@ describe('abortMiddleware - handleAbort billing', () => {db.getConvo.mockResolvedValue({ title: 'Test Chat' });});+ it.each([null, undefined])(+ 'keeps read state unchanged when the abort save returns %s',+ async (saved) => {+ const conversation = {+ title: 'Test Chat',+ lastResponseAt: '2026-09-01T10:00:00.000Z',+ lastSeenAt: '2026-09-01T10:01:00.000Z',+ };+ db.saveMessage.mockResolvedValueOnce(saved);+ db.getConvo.mockResolvedValueOnce(conversation);+ GenerationJobManager.abortJob.mockResolvedValue({+ success: true,+ jobData: buildJobData(),+ content: [],+ text: 'partial',+ collectedUsage: [],+ });+ const res = buildRes();++ await handleAbort()(buildReq(), res);++ expect(db.stampConvoLastResponse).not.toHaveBeenCalled();+ expect(JSON.parse(res.send.mock.calls[0][0]).conversation).toEqual(conversation);+ },+ );++ it('announces a persisted stopped reply', async () => {+ db.saveMessage.mockResolvedValueOnce({ messageId: 'msg-123' });+ GenerationJobManager.abortJob.mockResolvedValue({+ success: true,+ jobData: buildJobData(),+ content: [],+ text: 'partial',+ collectedUsage: [],+ });+ const res = buildRes();++ await handleAbort()(buildReq(), res);++ expect(db.stampConvoLastResponse).toHaveBeenCalledWith('user-123', 'convo-123', 'msg-123');+ expect(JSON.parse(res.send.mock.calls[0][0]).final).toBe(true);+ });++ it('does not announce a stopped turn that produced nothing to read', async () => {+ /* An interrupt before the model's first real token still persists the unfinished+ assistant row; a dot raised for it names a reply the user can never open. */+ db.saveMessage.mockResolvedValueOnce({ messageId: 'msg-empty' });+ GenerationJobManager.abortJob.mockResolvedValue({+ success: true,+ jobData: buildJobData(),+ content: [{ type: 'text', text: ' ' }],+ text: ' ',+ collectedUsage: [],+ });+ const res = buildRes();++ await handleAbort()(buildReq(), res);++ expect(db.stampConvoLastResponse).not.toHaveBeenCalled();+ expect(JSON.parse(res.send.mock.calls[0][0]).final).toBe(true);+ });+it('leaves billing to the run even when the stopped job collected usage', async () => {const collectedUsage = [{ input_tokens: 100, output_tokens: 50, model: 'gpt-4' }];GenerationJobManager.abortJob.mockResolvedValue({diff --git a/api/server/middleware/error.js b/api/server/middleware/error.jsindex ceb7c90b74..f3dfdf901d 100644--- a/api/server/middleware/error.js+++ b/api/server/middleware/error.js@@ -1,8 +1,13 @@const crypto = require('crypto');const { logger } = require('@librechat/data-schemas');const { parseConvo } = require('librechat-data-provider');-const { sendEvent, handleError, sanitizeMessageForTransmit } = require('@librechat/api');-const { saveMessage, getMessages, getConvo } = require('~/models');+const {+ sendEvent,+ handleError,+ announceErrorTurn,+ sanitizeMessageForTransmit,+} = require('@librechat/api');+const { saveMessage, getMessages, getConvo, stampConvoLastResponse } = require('~/models');/*** Processes an error with provided options, saves the error message and sends a corresponding SSE response@@ -47,10 +52,11 @@ const sendError = async (req, res, options, callback) => {}if (shouldSaveMessage) {- await saveMessage(+ const isTemporary = req?.resolvedConversation?.isTemporary ?? req?.body?.isTemporary;+ const savedError = await saveMessage({userId: req?.user?.id,- isTemporary: req?.resolvedConversation?.isTemporary ?? req?.body?.isTemporary,+ isTemporary,expiredAt: req?.resolvedConversation?.expiredAt,interfaceConfig: req?.config?.interfaceConfig,},@@ -59,6 +65,19 @@ const sendError = async (req, res, options, callback) => {context: 'api/server/utils/streamResponse.js - sendError',},);+ const conversation = await announceErrorTurn(+ { stampConvoLastResponse },+ {+ userId: req?.user?.id ?? user,+ conversationId,+ messageId: savedError?.messageId,+ isTemporary: isTemporary === true,+ context: 'sendError',+ },+ );+ if (conversation) {+ errorMessage.conversation = conversation;+ }}if (!errorMessage.error) {diff --git a/api/server/middleware/error.spec.js b/api/server/middleware/error.spec.jsnew file mode 100644index 0000000000..94872b32db--- /dev/null+++ b/api/server/middleware/error.spec.js@@ -0,0 +1,132 @@+/**+ * Tests for sendError's reply stamping.+ *+ * A terminal error is a persisted assistant turn, and on the fallback paths that reach here it+ * is the only one written: without a stamp another device never learns the run ended.+ */++const mockSaveMessage = jest.fn();+const mockStampConvoLastResponse = jest.fn();+const mockHandleError = jest.fn();++jest.mock('@librechat/data-schemas', () => ({+ logger: { debug: jest.fn(), error: jest.fn(), warn: jest.fn(), info: jest.fn() },+}));++jest.mock('@librechat/api', () => ({+ sendEvent: jest.fn(),+ handleError: (...args) => mockHandleError(...args),+ sanitizeMessageForTransmit: jest.fn((message) => message),+ /** Real, because when an error turn is stamped and what its event carries is under test. */+ announceErrorTurn: jest.requireActual('@librechat/api').announceErrorTurn,+}));++jest.mock('~/models', () => ({+ saveMessage: (...args) => mockSaveMessage(...args),+ getMessages: jest.fn().mockResolvedValue([]),+ getConvo: jest.fn().mockResolvedValue({}),+ stampConvoLastResponse: (...args) => mockStampConvoLastResponse(...args),+}));++const { sendError } = require('./error');++const CONVO_ID = 'convo-errored';++const options = {+ user: 'user-123',+ sender: 'AI',+ conversationId: CONVO_ID,+ messageId: 'error-msg',+ parentMessageId: 'user-msg',+ text: 'Something went wrong',+ shouldSaveMessage: true,+};++const reqWith = (body = {}) => ({ user: { id: 'user-123' }, body, config: {} });++describe('sendError', () => {+ const stampedAt = new Date('2026-08-16T10:00:00.000Z');+ const updatedAt = new Date('2026-08-16T10:00:00.001Z');++ beforeEach(() => {+ mockSaveMessage.mockReset();+ mockSaveMessage.mockImplementation(async (_ctx, message) => message);+ mockStampConvoLastResponse.mockReset();+ mockStampConvoLastResponse.mockResolvedValue({+ lastResponseAt: stampedAt,+ lastResponseMessageId: 'error-msg',+ updatedAt,+ });+ mockHandleError.mockReset();+ });++ it('stamps the conversation once the error reply is durable and emits that settled read state', async () => {+ await sendError(reqWith(), {}, options);++ expect(mockStampConvoLastResponse).toHaveBeenCalledWith('user-123', CONVO_ID, 'error-msg');+ expect(mockHandleError).toHaveBeenCalledWith(+ {},+ expect.objectContaining({+ conversation: {+ conversationId: CONVO_ID,+ lastResponseAt: stampedAt,+ lastResponseMessageId: 'error-msg',+ updatedAt,+ },+ }),+ );+ });++ it('never stamps or exposes a temporary conversation', async () => {+ await sendError(reqWith({ isTemporary: true }), {}, options);++ expect(mockStampConvoLastResponse).not.toHaveBeenCalled();+ expect(mockHandleError).toHaveBeenCalledWith(+ {},+ expect.not.objectContaining({ conversation: expect.anything() }),+ );+ });++ it('never stamps or exposes a reply the message write did not persist', async () => {+ /* Announcing a reply that is absent from message history would show a dot for a message+ nobody can open. */+ mockSaveMessage.mockResolvedValue(null);++ await sendError(reqWith(), {}, options);++ expect(mockStampConvoLastResponse).not.toHaveBeenCalled();+ expect(mockHandleError).toHaveBeenCalledWith(+ {},+ expect.not.objectContaining({ conversation: expect.anything() }),+ );+ });++ it('never exposes a read stamp when the indicator write fails', async () => {+ mockStampConvoLastResponse.mockRejectedValue(new Error('mongo is down'));++ await expect(sendError(reqWith(), {}, options)).resolves.toBeUndefined();++ expect(mockHandleError).toHaveBeenCalledWith(+ {},+ expect.not.objectContaining({ conversation: expect.anything() }),+ );+ });++ it('does not expose a stamp when the conversation cannot be settled', async () => {+ mockStampConvoLastResponse.mockResolvedValue(null);++ await sendError(reqWith(), {}, options);++ expect(mockHandleError).toHaveBeenCalledWith(+ {},+ expect.not.objectContaining({ conversation: expect.anything() }),+ );+ });++ it('leaves the stamp alone when the caller does not persist the message', async () => {+ await sendError(reqWith(), {}, { ...options, shouldSaveMessage: false });++ expect(mockSaveMessage).not.toHaveBeenCalled();+ expect(mockStampConvoLastResponse).not.toHaveBeenCalled();+ });+});diff --git a/api/server/routes/__test-utils__/convos-route-mocks.js b/api/server/routes/__test-utils__/convos-route-mocks.jsindex 1498f62b0e..2738e44959 100644--- a/api/server/routes/__test-utils__/convos-route-mocks.js+++ b/api/server/routes/__test-utils__/convos-route-mocks.js@@ -55,6 +55,8 @@ function resetCheckpointRows(rows = []) {checkpointRows.splice(0, checkpointRows.length, ...rows);deletionTargets.clear();}+const markConvoSeenHandler = jest.fn();+const markConvoUnreadHandler = jest.fn();module.exports = {archiveAllHandler,@@ -67,6 +69,8 @@ module.exports = {messageUserLimiter,checkpointRows,resetCheckpointRows,+ markConvoSeenHandler,+ markConvoUnreadHandler,agents: () => ({ sleep: jest.fn() }),@@ -173,6 +177,23 @@ module.exports = {subagentActivityHandlerInputs.push({ deps, stream });return (_req, res) => res.status(200).end();}),+ /* Wiring only. The handlers' own validation and error mapping are covered against the+ real implementations in `packages/api/src/conversations/read.spec.ts`; mirroring them+ here would leave the route suite asserting against a copy. */+ createMarkConvoSeenHandler: jest.fn(({ markConvoSeen }) => {+ markConvoSeenHandler.mockImplementation(async (req, res) => {+ const result = await markConvoSeen(req.user.id, req.body?.arg?.conversationId);+ return res.status(200).json(result);+ });+ return markConvoSeenHandler;+ }),+ createMarkConvoUnreadHandler: jest.fn(({ markConvoUnread }) => {+ markConvoUnreadHandler.mockImplementation(async (req, res) => {+ const result = await markConvoUnread(req.user.id, req.body?.arg?.conversationId);+ return res.status(200).json(result);+ });+ return markConvoUnreadHandler;+ }),deleteConvoSharedLinksWithCleanup: jest.fn(),deleteAllSharedLinksWithCleanup: jest.fn(),deleteAgentCheckpoints,@@ -224,6 +245,8 @@ module.exports = {archiveAllConvos: jest.fn(),saveConvo: jest.fn(),setConvoPinned: jest.fn(),+ markConvoSeen: jest.fn(),+ markConvoUnread: jest.fn(),deleteAllSharedLinks: jest.fn(),deleteConvoSharedLink: jest.fn(),deleteToolCalls: jest.fn(),diff --git a/api/server/routes/__tests__/convos.spec.js b/api/server/routes/__tests__/convos.spec.jsindex 46a76a3146..83f8421042 100644--- a/api/server/routes/__tests__/convos.spec.js+++ b/api/server/routes/__tests__/convos.spec.js@@ -68,6 +68,8 @@ describe('Convos Routes', () => {deleteMessages,getConvo,saveConvo,+ markConvoSeen,+ markConvoUnread,} = require('~/models');const {deleteOwnedAgentCheckpoints,@@ -1910,6 +1912,37 @@ describe('Convos Routes', () => {});});+ describe('POST /seen', () => {+ /* The handler's own validation and error mapping live in `packages/api` and are covered+ against the real implementation there; what matters here is that the route reaches it+ with the authenticated user. */+ it('routes to the handler for the authenticated user', async () => {+ markConvoSeen.mockResolvedValue({ modified: true });++ const response = await request(app)+ .post('/api/convos/seen')+ .send({ arg: { conversationId: 'conv-seen-1' } });++ expect(response.status).toBe(200);+ expect(response.body).toEqual({ modified: true });+ expect(markConvoSeen).toHaveBeenCalledWith('test-user-123', 'conv-seen-1');+ });+ });++ describe('POST /unread', () => {+ it('routes to the handler for the authenticated user', async () => {+ markConvoUnread.mockResolvedValue({ modified: true });++ const response = await request(app)+ .post('/api/convos/unread')+ .send({ arg: { conversationId: 'conv-unread-1' } });++ expect(response.status).toBe(200);+ expect(response.body).toEqual({ modified: true });+ expect(markConvoUnread).toHaveBeenCalledWith('test-user-123', 'conv-unread-1');+ });+ });+describe('POST /archive', () => {it('should archive a conversation successfully', async () => {const mockConversationId = 'conv-123';diff --git a/api/server/routes/agents/__tests__/abort.spec.js b/api/server/routes/agents/__tests__/abort.spec.jsindex e31bdc95c7..71faa5dbdb 100644--- a/api/server/routes/agents/__tests__/abort.spec.js+++ b/api/server/routes/agents/__tests__/abort.spec.js@@ -24,6 +24,7 @@ const mockGenerationJobManager = {};const mockSaveMessage = jest.fn();+const mockSaveConvo = jest.fn();const mockRecordScheduleOutcome = jest.fn();const mockBeginScheduledStop = jest.fn();@@ -47,6 +48,7 @@ jest.mock('@librechat/api', () => ({jest.mock('~/models', () => ({saveMessage: (...args) => mockSaveMessage(...args),+ saveConvo: (...args) => mockSaveConvo(...args),}));jest.mock('~/server/services/Schedules', () => ({@@ -99,6 +101,8 @@ describe('Agent Abort Endpoint', () => {mockGenerationJobManager.getActiveJobIdsForUser.mockReset();mockSaveMessage.mockReset();mockSaveMessage.mockImplementation(async (_context, message) => message);+ mockSaveConvo.mockReset();+ mockSaveConvo.mockResolvedValue({});mockRecordScheduleOutcome.mockReset();mockRecordScheduleOutcome.mockResolvedValue(true);mockBeginScheduledStop.mockReset();@@ -343,6 +347,14 @@ describe('Agent Abort Endpoint', () => {expect.objectContaining({ context: expect.stringContaining('abort endpoint') }),);+ /** The row renders nothing, so a dot raised for it names a reply the user can never+ * open and no acknowledgement could clear. */+ expect(mockSaveConvo).not.toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.objectContaining({ stampReply: true }),+ );+/** This is the exact server-side fence hit by the queued submission* after the abort FINAL. It must observe the row written above rather* than reject the drain solely because the stable id ends in `_`. */@@ -494,6 +506,52 @@ describe('Agent Abort Endpoint', () => {expect(savedResponse.contextMeta).toBeNull();});+ it('stamps the aborted reply through an upsert so an early stop still lights the dot', async () => {+ const jobStreamId = 'test-stream-123';+ mockGenerationJobManager.getJob.mockResolvedValue({+ metadata: { userId: 'test-user-123' },+ });+ const abortResult = {+ success: true,+ jobData: {+ userMessage: { messageId: 'user-msg-123' },+ responseMessageId: 'response-msg-456',+ conversationId: jobStreamId,+ endpoint: 'anthropic',+ model: 'claude-3',+ },+ content: [{ type: 'text', text: 'Partial response...' }],+ text: 'Partial response...',+ };+ mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {+ await options.beforePublish(abortResult);+ return abortResult;+ });+ mockSaveMessage.mockImplementation(async (_context, message) => ({+ ...message,+ _id: `oid-${message.messageId}`,+ }));+ const response = await request(app)+ .post('/api/agents/chat/abort')+ .send({ conversationId: jobStreamId });++ expect(response.status).toBe(200);+ expect(mockSaveConvo).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ conversationId: jobStreamId,+ endpoint: 'anthropic',+ model: 'claude-3',+ }),+ expect.objectContaining({+ stampReply: true,+ replyMessageId: 'response-msg-456',+ /* Without these `saveConvo` reloads the whole history inside the abort barrier. */+ appendMessageIds: ['oid-user-msg-123', 'oid-response-msg-456'],+ }),+ );+ });+it('saves the aborted partial as temporary from job metadata, not the request body', async () => {const jobStreamId = 'test-stream-123';const expiredAt = new Date('2030-01-01T00:00:00.000Z');diff --git a/api/server/routes/agents/index.js b/api/server/routes/agents/index.jsindex 52a4c34eeb..0a4cb3290d 100644--- a/api/server/routes/agents/index.js+++ b/api/server/routes/agents/index.js@@ -5,6 +5,7 @@ const {GenerationJobManager,TERMINAL_PUBLICATION_RECONNECT_ERROR,hasPersistableAbortContent,+ announceStoppedReply,buildAbortedResponseMetadata,isPendingActionStale,toClientPendingAction,@@ -49,7 +50,7 @@ const {getServerGenerationProtocol,negotiateExistingGenerationProtocol,} = require('~/server/controllers/agents/protocol');-const { getFiles, saveMessage } = require('~/models');+const { getFiles, saveConvo, saveMessage } = require('~/models');const {recordScheduleOutcome,beginScheduledStop,@@ -828,6 +829,7 @@ router.post('/chat/abort', configMiddleware, async (req, res, next) => {* await the user prerequisite first, but still attempt the child* write and checkpoint cleanup so every independently useful* operation gets a chance to succeed. */+ let persistedRequestId;try {const persistedRequest = await saveMessage(messageContext, requestMessage, {context: 'api/server/routes/agents/index.js - abort user prerequisite',@@ -835,6 +837,7 @@ router.post('/chat/abort', configMiddleware, async (req, res, next) => {if (!persistedRequest) {throw new Error('Abort user prerequisite was not persisted');}+ persistedRequestId = persistedRequest._id;} catch (error) {persistenceErrors.push(error);}@@ -847,6 +850,28 @@ router.post('/chat/abort', configMiddleware, async (req, res, next) => {throw new Error('Abort response was not persisted');}logger.debug(`[AgentStream] Saved partial response for: ${jobStreamId}`);+ /* When Stop wins the terminal claim the request controller returns before its+ own stamp, so this is the only place a stopped turn's reply reaches the+ unseen-reply indicator.+ The two rows this barrier just wrote are handed over directly: without them+ the conversation write reloads the entire message list to rebuild `messages`,+ and that serial read sits between Stop and the FINAL event. */+ await announceStoppedReply(+ { saveConvo },+ {+ ctx: messageContext,+ conversationId: jobData.conversationId,+ endpoint: jobData.endpoint,+ model: jobData.model,+ reply: {+ messageId: persistedResponse.messageId,+ content,+ attachments: responseMessage.attachments,+ },+ appendMessageIds: [persistedRequestId, persistedResponse._id],+ context: 'api/server/routes/agents/index.js - abort reply stamp',+ },+ );} catch (error) {persistenceErrors.push(error);}diff --git a/api/server/routes/convos.js b/api/server/routes/convos.jsindex dac0f10ff2..b46c9952fd 100644--- a/api/server/routes/convos.js+++ b/api/server/routes/convos.js@@ -21,6 +21,8 @@ const {createBackgroundTaskPolicyMiddleware,backgroundTaskRegistry,createSubagentThreadViewHandler,+ createMarkConvoSeenHandler,+ createMarkConvoUnreadHandler,resolveImportMaxFileSize,restoreTenantContextFromReq,deleteAllSharedLinksWithCleanup,@@ -152,13 +154,9 @@ const subagentControlHandler = createSubagentControlHandler({getSubagentTaskControlReceipt: db.getSubagentTaskControlReceipt,store: subagentThreadTaskStore,});-const backgroundTaskPolicy = createBackgroundTaskPolicyMiddleware({ getAppConfig });-const backgroundTaskIndexHandler = createBackgroundTaskIndexHandler({- registry: backgroundTaskRegistry,- pending: pendingBackgroundToolCompletions,-});-const backgroundTaskCancelHandler = createBackgroundTaskCancelHandler({- registry: backgroundTaskRegistry,+const markConvoSeenHandler = createMarkConvoSeenHandler({ markConvoSeen: db.markConvoSeen });+const markConvoUnreadHandler = createMarkConvoUnreadHandler({+ markConvoUnread: db.markConvoUnread,});router.use(requireJwtAuth);@@ -695,6 +693,10 @@ router.post('/pin', validateConvoAccess, async (req, res) => {}});+router.post('/seen', validateConvoAccess, markConvoSeenHandler);++router.post('/unread', validateConvoAccess, markConvoUnreadHandler);+/** Maximum allowed length for conversation titles */const MAX_CONVO_TITLE_LENGTH = 1024;diff --git a/api/server/services/Endpoints/agents/title.js b/api/server/services/Endpoints/agents/title.jsindex cdb2a62c83..bdbc9c3eec 100644--- a/api/server/services/Endpoints/agents/title.js+++ b/api/server/services/Endpoints/agents/title.js@@ -172,6 +172,7 @@ const addTitle = async ({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 responsediff --git a/api/server/services/Endpoints/assistants/title.js b/api/server/services/Endpoints/assistants/title.jsindex 98b4d76e84..4ca54910cd 100644--- a/api/server/services/Endpoints/assistants/title.js+++ b/api/server/services/Endpoints/assistants/title.js@@ -80,7 +80,12 @@ const addTitle = async (req, { text, responseText, conversationId }) => {conversationId,title,},- { context: 'api/server/services/Endpoints/assistants/addTitle.js', noUpsert: true },+ {+ context: 'api/server/services/Endpoints/assistants/addTitle.js',+ noUpsert: true,+ preserveUpdatedAt: true,+ appendMessageIds: [],+ },);} catch (error) {logger.error('[addTitle] Error generating title:', error);@@ -112,7 +117,12 @@ const addTitle = async (req, { text, responseText, conversationId }) => {conversationId,title: fallbackTitle,},- { context: 'api/server/services/Endpoints/assistants/addTitle.js', noUpsert: true },+ {+ context: 'api/server/services/Endpoints/assistants/addTitle.js',+ noUpsert: true,+ preserveUpdatedAt: true,+ appendMessageIds: [],+ },);}};diff --git a/api/server/services/Endpoints/title.spec.js b/api/server/services/Endpoints/title.spec.jsnew file mode 100644index 0000000000..17f66b4318--- /dev/null+++ b/api/server/services/Endpoints/title.spec.js@@ -0,0 +1,88 @@+const mongoose = require('mongoose');+const { MongoMemoryServer } = require('mongodb-memory-server');++const mockTitles = new Map();+const mockInitializeClient = jest.fn();+jest.mock('~/cache/getLogStores', () => () => ({+ get: async (key) => mockTitles.get(key),+ set: async (key, value) => mockTitles.set(key, value),+ delete: async (key) => mockTitles.delete(key),+}));+jest.mock(+ './assistants/initalize',+ () =>+ (...args) =>+ mockInitializeClient(...args),+);++const { Conversation, Message } = require('~/db/models');+const addAssistantTitle = require('./assistants/title');+const addAgentTitle = require('./agents/title');++describe('generated title reply provenance', () => {+ let mongo;+ beforeAll(async () => {+ mongo = await MongoMemoryServer.create();+ await mongoose.connect(mongo.getUri());+ });+ afterAll(async () => {+ await mongoose.disconnect();+ await mongo.stop();+ });+ beforeEach(async () => {+ await Conversation.deleteMany({});+ mockTitles.clear();+ mockInitializeClient.mockReset();+ });++ it.each(['assistant', 'assistant fallback', 'agent'])(+ 'preserves reply activity through an automatic %s title without loading history',+ async (mode) => {+ const conversationId = 'automatic-title';+ const replyAt = new Date('2026-08-16T10:00:00.000Z');+ await Conversation.create({+ conversationId,+ user: 'title-user',+ endpoint: 'assistants',+ title: 'New Chat',+ createdAt: replyAt,+ updatedAt: replyAt,+ lastResponseAt: replyAt,+ });+ const create = jest.fn();+ if (mode === 'assistant fallback') {+ create.mockRejectedValue(new Error('title service unavailable'));+ } else {+ create.mockResolvedValue({ choices: [{ message: { content: 'Automatic title' } }] });+ }+ mockInitializeClient.mockResolvedValue({ openai: { chat: { completions: { create } } } });+ const req = { user: { id: 'title-user' }, body: {}, config: {} };+ const history = jest.spyOn(Message, 'find');+ try {+ if (mode === 'agent') {+ await addAgentTitle(req, {+ text: 'Automatic title',+ response: { conversationId },+ client: {+ options: { titleConvo: true },+ titleConvo: async () => 'Automatic title',+ },+ });+ } else {+ await addAssistantTitle(req, {+ text: 'Automatic title',+ responseText: 'Assistant reply',+ conversationId,+ });+ }+ expect(history).not.toHaveBeenCalled();+ const saved = await Conversation.findOne({ conversationId }).lean();+ expect(saved.title).toBe('Automatic title');+ expect(saved.lastResponseAt).toEqual(replyAt);+ expect(saved.updatedAt).toEqual(replyAt);+ } finally {+ history.mockRestore();+ }+ },+ );+});diff --git a/api/server/services/Threads/manage.js b/api/server/services/Threads/manage.jsindex ac5e2f12ba..29a0d502a4 100644--- a/api/server/services/Threads/manage.js+++ b/api/server/services/Threads/manage.js@@ -1,6 +1,6 @@const path = require('path');const { v4 } = require('uuid');-const { countTokens } = require('@librechat/api');+const { countTokens, announceReply, isAnnounceableReply } = require('@librechat/api');const { escapeRegExp } = require('@librechat/data-schemas');const {Constants,@@ -8,7 +8,13 @@ const {AnnotationTypes,defaultOrderQuery,} = require('librechat-data-provider');-const { saveMessage, getMessages, spendTokens, saveConvo } = require('~/models');+const {+ saveConvo,+ getMessages,+ spendTokens,+ saveMessage,+ stampConvoLastResponse,+} = require('~/models');const { retrieveAndProcessFile } = require('~/server/services/Files/process');/**@@ -100,7 +106,10 @@ async function saveUserMessage(req, params) {const savedConvo = await saveConvo({ ...ctx, expiredAt: message?.expiredAt ?? ctx.expiredAt },convo,- { context: 'api/server/services/Threads/manage.js #saveUserMessage' },+ {+ context: 'api/server/services/Threads/manage.js #saveUserMessage',+ ...(message?._id != null ? { appendMessageIds: [message._id] } : {}),+ },);if (savedConvo != null) {req.resolvedConversation = savedConvo;@@ -128,7 +137,8 @@ async function saveUserMessage(req, params) {* @param {string} [params.iconURL]* Overrides the instructions of the assistant.* @param {string} [params.promptPrefix] - Optional: from preset for `additional_instructions` field.- * @return {Promise<Run>} A promise that resolves to the created run object.+ * @return {Promise<{message: Object|null, conversation: Object|null}>} The persisted assistant+ * message and the conversation snapshot settled by the same write.*/async function saveAssistantMessage(req, params) {// const tokenCount = // TODO: need to count each content part@@ -158,6 +168,13 @@ async function saveAssistantMessage(req, params) {spec: params.spec,});+ const announceable = isAnnounceableReply({+ messageId: message?.messageId,+ content: params.content,+ text: params.text,+ isTemporary: ctx.isTemporary,+ });+const savedConvo = await saveConvo({ ...ctx, expiredAt: message?.expiredAt ?? ctx.expiredAt },{@@ -170,14 +187,23 @@ async function saveAssistantMessage(req, params) {iconURL: params.iconURL,spec: params.spec,},- { context: 'api/server/services/Threads/manage.js #saveAssistantMessage' },+ {+ context: 'api/server/services/Threads/manage.js #saveAssistantMessage',+ /** Judged by the same predicate every other persistence path asks, so an assistant row+ * that renders nothing cannot raise a dot here that opening the chat can never clear.+ * `saveConvo` assigns the timestamp past its own awaited reads, so a catch-up recorded+ * while one of them is in flight cannot outrank this reply. */+ stampReply: announceable,+ ...(announceable ? { replyMessageId: message.messageId } : {}),+ ...(message?._id != null ? { appendMessageIds: [message._id] } : {}),+ },);if (savedConvo != null) {req.resolvedConversation = savedConvo;}- return message;+ return { message, conversation: savedConvo };}/**@@ -243,6 +269,9 @@ async function syncMessages({expiredAt: openai.req?.resolvedConversation?.expiredAt,interfaceConfig: openai.req?.config?.interfaceConfig,};+ /** The assistant writes this synchronization performed. Their results decide whether a reply+ * is actually in the history: a write that resolved empty must not raise an indicator. */+ const assistantRecordPromises = [];/***@@ -253,7 +282,11 @@ async function syncMessages({* @param {dbMessage} params.apiMessage*/const processNewMessage = async ({ dbMessage, apiMessage }) => {- recordPromises.push(saveMessage(ctx, { ...dbMessage, user: openai.req.user.id }));+ const recorded = saveMessage(ctx, { ...dbMessage, user: openai.req.user.id });+ recordPromises.push(recorded);+ if (dbMessage.role === 'assistant') {+ assistantRecordPromises.push(recorded);+ }if (!apiMessage.id.includes('msg_')) {return;@@ -358,6 +391,7 @@ async function syncMessages({}, []);await Promise.all(modifyPromises);+ const recordedAssistantReplies = await Promise.all(assistantRecordPromises);await Promise.all(recordPromises);const savedConvo = await saveConvo(@@ -372,6 +406,26 @@ async function syncMessages({openai.req.resolvedConversation = savedConvo;}+ /* Every caller that reaches here recovers assistant output the normal save path never wrote:+ a cancelled run, or one that errored after the model had already produced content. The+ `saveConvo` above carries no reply stamp, so without this the recovered reply would never+ raise its unseen indicator. Only a write that actually persisted counts, and it is+ best-effort, since those messages are already durable.+ A run cancelled before any output still persists the synthetic row `checkMessageGaps`+ built, and the error handlers add their visible content to the returned object rather+ than to that row: stamping it would raise a dot for a message that renders nothing, and+ acknowledgement requires the stamped reply to be on screen. */+ const persistedAssistantReply = recordedAssistantReplies.findLast((message) => message != null);+ await announceReply(+ { stampConvoLastResponse },+ {+ userId: openai.req.user.id,+ conversationId,+ reply: { ...persistedAssistantReply, isTemporary: ctx.isTemporary },+ context: 'syncMessages',+ },+ );+return result;}diff --git a/api/server/services/Threads/manage.retention.spec.js b/api/server/services/Threads/manage.retention.spec.jsindex 7fae744288..b16f2092ea 100644--- a/api/server/services/Threads/manage.retention.spec.js+++ b/api/server/services/Threads/manage.retention.spec.js@@ -94,6 +94,38 @@ describe('Assistants message retention', () => {expect(row.isTemporary).toBe(isTemporary);expect(row.expiredAt).toEqual(userMessage.expiredAt);}+ expect(convo.lastResponseAt != null).toBe(!isTemporary);},);++ it('appends the saved turn IDs without reloading message history', async () => {+ const user = new mongoose.Types.ObjectId().toString();+ const conversationId = v4();+ const req = { user: { id: user }, body: {}, config: {} };+ const params = {+ user,+ conversationId,+ endpoint: 'assistants',+ assistant_id: 'asst_test',+ thread_id: 'thread_test',+ text: 'hello',+ };+ const history = jest.spyOn(Message, 'find');+ try {+ const userMessage = await saveUserMessage(req, { ...params, messageId: v4() });+ const { message, conversation } = await saveAssistantMessage(req, {+ ...params,+ messageId: v4(),+ parentMessageId: userMessage.messageId,+ content: [],+ });++ expect(history).not.toHaveBeenCalled();+ expect(new Set(conversation.messages.map(String))).toEqual(+ new Set([String(userMessage._id), String(message._id)]),+ );+ } finally {+ history.mockRestore();+ }+ });});diff --git a/api/server/services/Threads/manage.spec.js b/api/server/services/Threads/manage.spec.jsindex 2d36ce3624..a201fa601b 100644--- a/api/server/services/Threads/manage.spec.js+++ b/api/server/services/Threads/manage.spec.js@@ -10,6 +10,10 @@ const mockSpendTokens = jest.fn().mockResolvedValue();jest.mock('@librechat/api', () => ({countTokens: jest.fn().mockResolvedValue(0),+ /* The real predicate, because what may raise an unseen indicator is the behaviour under test+ here; a stub would assert only that this file calls something. */+ isAnnounceableReply: jest.requireActual('@librechat/api').isAnnounceableReply,+ announceReply: jest.fn().mockResolvedValue(false),}));jest.mock('@librechat/data-schemas', () => ({@@ -27,7 +31,8 @@ jest.mock('~/server/services/Files/process', () => ({retrieveAndProcessFile: jest.fn(),}));-const { recordUsage } = require('./manage');+const { recordUsage, saveAssistantMessage } = require('./manage');+const { saveConvo, saveMessage } = require('~/models');describe('recordUsage', () => {beforeEach(() => {@@ -89,3 +94,59 @@ describe('recordUsage', () => {);});});++describe('saveAssistantMessage', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ saveMessage.mockResolvedValue({ messageId: 'assistant-msg' });+ saveConvo.mockResolvedValue({});+ });++ const params = {+ endpoint: 'assistants',+ conversationId: 'convo-123',+ messageId: 'assistant-msg',+ parentMessageId: 'user-msg',+ text: 'done',+ model: 'gpt-4',+ };++ it('asks saveConvo to stamp the reply at write time', async () => {+ /* A precomputed stamp can be outranked by a catch-up recorded while saveConvo's own reads+ are in flight, which would leave the persisted reply reading as already seen. */+ await saveAssistantMessage({ user: { id: 'user-123' }, body: {} }, params);++ expect(saveConvo).toHaveBeenCalledWith(+ expect.objectContaining({ userId: 'user-123' }),+ expect.not.objectContaining({ lastResponseAt: expect.anything() }),+ expect.objectContaining({ stampReply: true }),+ );+ });++ it.each([+ ['no content and no text', { ...params, text: undefined, content: undefined }],+ ['an empty content array', { ...params, text: undefined, content: [] }],+ ['whitespace-only text', { ...params, text: ' ' }],+ ])('does not stamp an assistant row with %s', async (_case, emptyParams) => {+ /* Acknowledging a reply needs the stamped message on screen, so a row that renders nothing+ would leave a dot that opening the conversation could never clear. */+ await saveAssistantMessage({ user: { id: 'user-123' }, body: {} }, emptyParams);++ expect(saveConvo).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.objectContaining({ stampReply: false }),+ );+ expect(saveConvo.mock.calls[0][2]).not.toHaveProperty('replyMessageId');+ });++ it('never stamps a temporary conversation', async () => {+ await saveAssistantMessage({ user: { id: 'user-123' }, body: { isTemporary: true } }, params);++ expect(saveConvo).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.objectContaining({ stampReply: false }),+ );+ });+});diff --git a/api/server/utils/import/importBatchBuilder.js b/api/server/utils/import/importBatchBuilder.jsindex afbd5d3281..50e05a0a3d 100644--- a/api/server/utils/import/importBatchBuilder.js+++ b/api/server/utils/import/importBatchBuilder.js@@ -177,6 +177,12 @@ class ImportBatchBuilder {};convo._id && delete convo._id;delete convo.subagentThread;+ /* A fork or duplicate starts its own unread history; carrying the source+ conversation's catch-up state over would light a dot on a never-read copy. */+ delete convo.lastResponseAt;+ delete convo.lastResponseMessageId;+ delete convo.lastResponseIsManual;+ delete convo.lastSeenAt;this.conversations.push(convo);return { conversation: convo, messages: this.messages };diff --git a/client/src/components/Chat/Messages/MessagesView.tsx b/client/src/components/Chat/Messages/MessagesView.tsxindex f104d1a1b2..58e76476af 100644--- a/client/src/components/Chat/Messages/MessagesView.tsx+++ b/client/src/components/Chat/Messages/MessagesView.tsx@@ -1,9 +1,15 @@-import { useState } from 'react';+import { useState, useCallback, useEffect } from 'react';import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';import { Constants } from 'librechat-data-provider';import type { TMessage } from 'librechat-data-provider';-import { useScreenshot, useMessageScrolling, useScrollbarGutter, useLocalize } from '~/hooks';+import {+ useLocalize,+ useScreenshot,+ useScrollbarGutter,+ useMessageScrolling,+ useConversationSeen,+} from '~/hooks';import { MessagesViewProvider, useChatContext, useFileMapContext } from '~/Providers';import { RowMountProvider, useProgressiveRowMount } from '~/hooks/Messages';import { useChatSurface } from '~/components/Chat/Subagents/surface';@@ -46,11 +52,58 @@ function MessagesViewContent({const { conversationId } = conversation ?? {};const fileMap = useFileMapContext();const threadRows = useThreadRows(FLAT_THREAD ? messages : null, conversationId, fileMap);-- const { index, latestMessageDepth } = useChatContext();+ const { index, latestMessageId, latestMessageDepth } = useChatContext();const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));const { showScrollButton, maximizeChatSpace } = useChatSurface();const autoScroll = useAtomValue(autoScrollAtom);++ /** Direct measurement for the one trigger the observer cannot serve: after a messages+ * revalidation commits, the end marker may sit where no threshold was crossed, so no+ * report comes; the seen hook re-measures the committed tree instead. Mirrors the+ * observer's near-bottom meaning: the end marker inside the scrollable viewport. */+ const measureNearBottom = useCallback(() => {+ const end = messagesEndRef.current;+ const scrollable = scrollableRef.current;+ if (!end || !scrollable) {+ return null;+ }+ return end.getBoundingClientRect().top <= scrollable.getBoundingClientRect().bottom + 1;+ }, [messagesEndRef, scrollableRef]);++ /** MessageRow owns the durable DOM id. Scoping the lookup to this content root prevents a stale+ * row in another mounted surface from proving a hidden sibling branch visible. A body child is+ * required because progressive mounting can expose the row shell before its body commits. */+ const isResponseRendered = useCallback(+ (messageId: string) => {+ const content = contentRef.current;+ const row = document.getElementById(messageId);+ if (!content || !row || !content.contains(row)) {+ return false;+ }+ const body = row.querySelector('[data-testid="message-body"]');+ return (+ body != null && (body.childElementCount > 0 || (body.textContent?.trim().length ?? 0) > 0)+ );+ },+ [contentRef],+ );++ /** Piggybacks the messages-end observer rather than adding a second one, and stays a plain+ * callback so intersection flips keep re-rendering only `ScrollButton`. */+ const reportNearBottom = useConversationSeen(+ conversationId ?? undefined,+ isSubmitting,+ measureNearBottom,+ isResponseRendered,+ );+ const handleNearBottom = useCallback(+ (isNearBottom: boolean) => {+ handleNearBottomChange(isNearBottom);+ reportNearBottom(isNearBottom);+ },+ [handleNearBottomChange, reportNearBottom],+ );+/** Re-arm from the conversation that owns the RENDERED tree: the Recoil* conversation id lags the route during warm-cache navigation, and keying* off it would first mount the new tree unwindowed, then narrow it after@@ -63,6 +116,12 @@ function MessagesViewContent({conversationId: treeConversationId,scrollableRef,});+ useEffect(() => {+ const isNearBottom = measureNearBottom();+ if (isNearBottom != null) {+ reportNearBottom(isNearBottom);+ }+ }, [latestMessageId, measureNearBottom, mountWindow, reportNearBottom, _messagesTree]);/** The in-flight steer overlay floats above the composer over the bottom of* the thread (see `InFlightSteers`); reserve an equal band here so the@@ -144,7 +203,7 @@ function MessagesViewContent({scrollableRef={scrollableRef}messagesEndRef={messagesEndRef}scrollHandler={handleSmoothToRef}- onNearBottomChange={handleNearBottomChange}+ onNearBottomChange={handleNearBottom}overlayHeight={steerOverlayHeight}/>diff --git a/client/src/components/Conversations/Convo.tsx b/client/src/components/Conversations/Convo.tsxindex 192612685e..30b8cd21cc 100644--- a/client/src/components/Conversations/Convo.tsx+++ b/client/src/components/Conversations/Convo.tsx@@ -12,11 +12,11 @@ import {usePinConversationMutation,useUpdateConversationMutation,} from '~/data-provider';+import { cn, logger, setDocumentTitle, isConversationUnseen } from '~/utils';import { useNavigateToConvo, useLocalize, useShiftKey } from '~/hooks';import ConversationEndpointIcon from './ConversationEndpointIcon';import { focusableInRow, resolveRowBeside } from './focus';import { areConversationRenderPropsEqual } from './utils';-import { cn, logger, setDocumentTitle } from '~/utils';import { NotificationSeverity } from '~/common';import { CONVERSATION_DRAG_TYPE } from './dnd';import ConvoActions from './ConvoActions';@@ -64,6 +64,7 @@ function Conversation({const { data: startupConfig } = useGetStartupConfig();const sharedLinksEnabled = startupConfig?.sharedLinksEnabled === true;const isSharedBadgeVisible = conversation.isShared === true && sharedLinksEnabled;+ const isUnseen = isConversationUnseen(conversation);const isShiftHeld = useShiftKey();const { conversationId, title = '' } = conversation;@@ -263,6 +264,7 @@ function Conversation({retainView,renameHandler: handleRename,isActiveConvo,+ isUnseen,conversationId,chatProjectId: conversation.chatProjectId,isPopoverActive,@@ -351,6 +353,7 @@ function Conversation({isPopoverActive={isPopoverActive}isHovered={isHovered}isSharedBadgeVisible={isSharedBadgeVisible}+ isUnseen={isUnseen}title={title}onRename={handleRename}isSmallScreen={isSmallScreen}@@ -360,6 +363,11 @@ function Conversation({<ConversationEndpointIcon conversation={conversation} size={20} context="menu-item" /></ConvoLink>)}+ {isUnseen && (+ /* `ConvoLink`'s aria-label carries the text equivalent, so the dot itself stays+ decorative rather than announcing a second time outside the row's button. */+ <span className="bg-status-info mr-1 size-2 shrink-0 rounded-full" aria-hidden="true" />+ )}{isSharedBadgeVisible && (<Link2 className="icon-sm text-text-secondary mr-1 shrink-0" aria-hidden="true" />)}diff --git a/client/src/components/Conversations/ConvoActions.tsx b/client/src/components/Conversations/ConvoActions.tsxindex 9c1131e600..20c194ed79 100644--- a/client/src/components/Conversations/ConvoActions.tsx+++ b/client/src/components/Conversations/ConvoActions.tsx@@ -11,6 +11,7 @@ export type ConvoActionsProps = {title: string | null;isPinned?: boolean;isArchived?: boolean;+ isUnseen?: boolean;isActiveConvo: boolean;isShiftHeld?: boolean;isPopoverActive: boolean;@@ -91,7 +92,7 @@ function ConvoActions({variant="ghost"aria-label={localize('com_nav_convo_menu_options')}data-testid="convo-options-trigger"- className="size-9 text-text-secondary"+ className="text-text-secondary size-9"onClick={(event) => {event.stopPropagation();handleOpenChange(true);diff --git a/client/src/components/Conversations/ConvoLink.tsx b/client/src/components/Conversations/ConvoLink.tsxindex f4524e429a..bed937532b 100644--- a/client/src/components/Conversations/ConvoLink.tsx+++ b/client/src/components/Conversations/ConvoLink.tsx@@ -8,6 +8,7 @@ interface ConvoLinkProps {isPopoverActive: boolean;isHovered: boolean;isSharedBadgeVisible: boolean;+ isUnseen: boolean;title: string | null;onRename: () => void;isSmallScreen: boolean;@@ -38,6 +39,7 @@ const ConvoLink: React.FC<ConvoLinkProps> = ({isPopoverActive,isHovered,isSharedBadgeVisible,+ isUnseen,title,onRename,isSmallScreen,@@ -132,13 +134,13 @@ const ConvoLink: React.FC<ConvoLinkProps> = ({aria-current={isActiveConvo ? 'page' : undefined}aria-keyshortcuts={keyShortcuts}aria-label={- isSharedBadgeVisible+ (isSharedBadgeVisible? localize('com_ui_conversation_label_shared', {title: title || localize('com_ui_untitled'),}): localize('com_ui_conversation_label', {title: title || localize('com_ui_untitled'),- })+ })) + (isUnseen ? `, ${localize('com_ui_unread')}` : '')}>{children}diff --git a/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx b/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsxindex 5f6d729a6d..a4a7dfff1c 100644--- a/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx+++ b/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx@@ -18,6 +18,7 @@ import {ArchiveRestore,FolderInput,FolderX,+ Mail,Pen,Pin,Trash,@@ -31,6 +32,7 @@ import {useGetStartupConfig,useArchiveConvoMutation,usePinConversationMutation,+ useMarkConversationUnreadMutation,} from '~/data-provider';import { useHasAccess, useLocalize, useNavigateToConvo, useNewConvo } from '~/hooks';import { useChatContext, useLiveAnnouncer } from '~/Providers';@@ -57,6 +59,7 @@ function ConvoOptions({title,isPinned = false,isArchived = false,+ isUnseen = false,retainView,renameHandler,isPopoverActive,@@ -70,6 +73,7 @@ function ConvoOptions({isPinned?: boolean;/** This row's own archive state, which the sidebar filter does not stand in for. */isArchived?: boolean;+ isUnseen?: boolean;retainView: () => void;renameHandler: (e: MouseEvent) => void;isPopoverActive: boolean;@@ -114,6 +118,7 @@ function ConvoOptions({const archiveConvoMutation = useArchiveConvoMutation();const assignConversationToProject = useAssignConversationToProjectMutation();const pinConvoMutation = usePinConversationMutation();+ const markUnreadMutation = useMarkConversationUnreadMutation();const deleteMutation = useDeleteConversationMutation({onSuccess: () => {@@ -294,6 +299,26 @@ function ConvoOptions({);}, [conversationId, isPinned, pinConvoMutation, setIsPopoverActive, showToast, localize]);+ const handleMarkUnreadClick = useCallback(() => {+ const convoId = conversationId ?? '';+ if (!convoId) {+ return;+ }+ markUnreadMutation.mutate(+ { conversationId: convoId },+ {+ onSuccess: () => setIsPopoverActive(false),+ onError: () => {+ showToast({+ message: localize('com_ui_mark_unread_error'),+ severity: NotificationSeverity.ERROR,+ showIcon: true,+ });+ },+ },+ );+ }, [conversationId, markUnreadMutation, setIsPopoverActive, showToast, localize]);+const handleDuplicateClick = useCallback(() => {duplicateConversation.mutate({conversationId: conversationId ?? '',@@ -305,7 +330,7 @@ function ConvoOptions({{label: localize('com_ui_share'),onClick: shareHandler,- icon: <Share2 className="icon-sm mr-2 text-text-primary" aria-hidden="true" />,+ icon: <Share2 className="icon-sm text-text-primary mr-2" aria-hidden="true" />,show: startupConfig && startupConfig.sharedLinksEnabled && canCreateSharedLinks,ariaHasPopup: 'dialog' as const,ariaControls: 'share-conversation-dialog',@@ -321,13 +346,21 @@ function ConvoOptions({icon: isPinLoading ? (<Spinner className="size-4" />) : (- <Pin className="icon-sm mr-2 text-text-primary" aria-hidden="true" />+ <Pin className="icon-sm text-text-primary mr-2" aria-hidden="true" />),},+ {+ label: localize('com_ui_mark_unread'),+ onClick: handleMarkUnreadClick,+ /* The conversation on screen is definitionally read: its own seen triggers would+ clear the flag the moment it is set. */+ show: !isActiveConvo && !isUnseen,+ icon: <Mail className="icon-sm text-text-primary mr-2" aria-hidden="true" />,+ },{label: localize('com_ui_rename'),onClick: renameHandler,- icon: <Pen className="icon-sm mr-2 text-text-primary" aria-hidden="true" />,+ icon: <Pen className="icon-sm text-text-primary mr-2" aria-hidden="true" />,},{label: localize('com_ui_duplicate'),@@ -336,13 +369,13 @@ function ConvoOptions({icon: isDuplicateLoading ? (<Spinner className="size-4" />) : (- <CopyPlus className="icon-sm mr-2 text-text-primary" aria-hidden="true" />+ <CopyPlus className="icon-sm text-text-primary mr-2" aria-hidden="true" />),},{label: localize('com_ui_change_project'),onClick: projectHandler,- icon: <FolderInput className="icon-sm mr-2 text-text-primary" aria-hidden="true" />,+ icon: <FolderInput className="icon-sm text-text-primary mr-2" aria-hidden="true" />,ariaHasPopup: 'dialog' as const,ariaControls: 'project-conversation-dialog',hideOnClick: false,@@ -357,7 +390,7 @@ function ConvoOptions({icon: assignConversationToProject.isLoading ? (<Spinner className="size-4" />) : (- <FolderX className="icon-sm mr-2 text-text-primary" aria-hidden="true" />+ <FolderX className="icon-sm text-text-primary mr-2" aria-hidden="true" />),},{@@ -369,7 +402,7 @@ function ConvoOptions({{label: localize('com_ui_delete'),onClick: deleteHandler,- icon: <Trash className="icon-sm mr-2 text-text-primary" aria-hidden="true" />,+ icon: <Trash className="icon-sm text-text-primary mr-2" aria-hidden="true" />,ariaHasPopup: 'dialog' as const,ariaControls: 'delete-conversation-dialog',/** NOTE: THE FOLLOWING PROPS ARE REQUIRED FOR MENU ITEMS THAT OPEN DIALOGS */@@ -381,6 +414,8 @@ function ConvoOptions({[localize,isPinned,+ isUnseen,+ isActiveConvo,isPinLoading,shareHandler,startupConfig,@@ -390,6 +425,7 @@ function ConvoOptions({isArchived,isDuplicateLoading,handlePinClick,+ handleMarkUnreadClick,handleArchiveClick,canCreateSharedLinks,handleDuplicateClick,@@ -524,6 +560,7 @@ export default memo(ConvoOptions, (prevProps, nextProps) => {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.isShiftHelddiff --git a/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx b/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsxindex 177f00e686..f590a41143 100644--- a/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx+++ b/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx@@ -67,6 +67,7 @@ jest.mock('~/data-provider', () => ({useGetStartupConfig: () => ({ data: { sharedLinksEnabled: false } }),useArchiveConvoMutation: () => ({ mutate: mockArchiveMutate, isLoading: false }),usePinConversationMutation: () => ({ mutate: jest.fn(), isLoading: false }),+ useMarkConversationUnreadMutation: () => ({ mutate: jest.fn(), isLoading: false }),}));jest.mock('~/hooks', () => ({diff --git a/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx b/client/src/components/Conversations/__tests__/Convo.touch.spec.tsxindex 72b8703012..d921e383b4 100644--- a/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx+++ b/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx@@ -44,6 +44,7 @@ jest.mock('~/store', () => ({jest.mock('~/utils', () => ({cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),logger: { error: jest.fn() },+ isConversationUnseen: () => false,}));jest.mock('../ConvoOptions', () => ({diff --git a/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx b/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsxindex af24941d98..54c3117b76 100644--- a/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx+++ b/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx@@ -60,6 +60,7 @@ jest.mock('~/utils', () => ({cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),logger: { error: jest.fn() },setDocumentTitle: jest.fn(),+ isConversationUnseen: () => false,}));jest.mock('../ConvoOptions', () => ({diff --git a/client/src/components/Conversations/utils.ts b/client/src/components/Conversations/utils.tsindex f66141aa6d..d95c8f5a99 100644--- a/client/src/components/Conversations/utils.ts+++ b/client/src/components/Conversations/utils.ts@@ -38,7 +38,12 @@ export function areConversationListItemFieldsEqual(prevConversation.isArchived === nextConversation.isArchived &&prevConversation.isShared === nextConversation.isShared &&prevConversation.createdAt === nextConversation.createdAt &&- prevConversation.updatedAt === nextConversation.updatedAt+ prevConversation.updatedAt === nextConversation.updatedAt &&+ /* Marking a conversation seen deliberately leaves `updatedAt` alone so the sidebar order+ holds, which means these have to be compared in their own right. */+ prevConversation.lastResponseAt === nextConversation.lastResponseAt &&+ prevConversation.lastResponseIsManual === nextConversation.lastResponseIsManual &&+ prevConversation.lastSeenAt === nextConversation.lastSeenAt);}diff --git a/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx b/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsxindex b05254326c..81c68fd833 100644--- a/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx+++ b/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx@@ -23,6 +23,9 @@ const ctx: SettingsContextValue = {engineTTS: 'browser',langfuseConnectionAccess: false,adminPanelURL: '',+ replyTabBadgeAllowed: true,+ replyNotificationsAllowed: true,+ replyNotificationSoundAllowed: true,};function setup(extra: Partial<SettingsContextValue> = {}, query = '') {diff --git a/client/src/components/Nav/Settings/__tests__/registry.spec.ts b/client/src/components/Nav/Settings/__tests__/registry.spec.tsindex 59240449bd..dbd4388e5a 100644--- a/client/src/components/Nav/Settings/__tests__/registry.spec.ts+++ b/client/src/components/Nav/Settings/__tests__/registry.spec.ts@@ -25,6 +25,9 @@ const settingsContext: SettingsContextValue = {engineTTS: 'browser',langfuseConnectionAccess: false,adminPanelURL: '',+ replyTabBadgeAllowed: true,+ replyNotificationsAllowed: true,+ replyNotificationSoundAllowed: true,};describe('settings registry', () => {diff --git a/client/src/components/Nav/Settings/context.tsx b/client/src/components/Nav/Settings/context.tsxindex 6a54bdc58d..3f56491db4 100644--- a/client/src/components/Nav/Settings/context.tsx+++ b/client/src/components/Nav/Settings/context.tsx@@ -36,6 +36,16 @@ export function useSettingsContext(): SettingsContextValue {const twoFactorEnabled = user?.twoFactorEnabled === true;const allowAccountDeletion = startupConfig?.allowAccountDeletion !== false;const aboutEnabled = startupConfig?.interface?.buildInfo !== false;+ /* Offered only once the deployment has answered, matching the capability hook the alerts+ read: before then a toggle could store a preference, or raise the browser's permission+ prompt, for a capability the operator turns off. */+ const replyConfigLoaded = startupConfig != null;+ const replyNotificationsConfig = startupConfig?.interface?.replyNotifications;+ const replyTabBadgeAllowed = replyConfigLoaded && replyNotificationsConfig?.tabBadge !== false;+ const replyNotificationsAllowed =+ replyConfigLoaded && replyNotificationsConfig?.desktop !== false;+ const replyNotificationSoundAllowed =+ replyConfigLoaded && replyNotificationsConfig?.sound !== false;const hasRemoteAgentsBool = hasRemoteAgents === true;const hasMultiConvoBool = hasMultiConvo === true;const hasPromptsBool = hasPrompts === true;@@ -63,6 +73,9 @@ export function useSettingsContext(): SettingsContextValue {engineTTS,langfuseConnectionAccess,adminPanelURL,+ replyTabBadgeAllowed,+ replyNotificationsAllowed,+ replyNotificationSoundAllowed,}),[balanceEnabled,@@ -82,6 +95,9 @@ export function useSettingsContext(): SettingsContextValue {engineTTS,langfuseConnectionAccess,adminPanelURL,+ replyTabBadgeAllowed,+ replyNotificationsAllowed,+ replyNotificationSoundAllowed,],);}diff --git a/client/src/components/Nav/Settings/controls.tsx b/client/src/components/Nav/Settings/controls.tsxindex 22d9ef4cfd..ef989c887d 100644--- a/client/src/components/Nav/Settings/controls.tsx+++ b/client/src/components/Nav/Settings/controls.tsx@@ -13,6 +13,7 @@ export function toggleControl(opts: {localizationKey: TranslationKeys;switchId: string;hoverCardText?: TranslationKeys;+ onCheckedChange?: (value: boolean) => void;}): ComponentType {const Control = () => (<ToggleSwitch@@ -20,6 +21,7 @@ export function toggleControl(opts: {localizationKey={opts.localizationKey}switchId={opts.switchId}hoverCardText={opts.hoverCardText}+ onCheckedChange={opts.onCheckedChange}/>);Control.displayName = `Toggle(${opts.switchId})`;diff --git a/client/src/components/Nav/Settings/registry.tsx b/client/src/components/Nav/Settings/registry.tsxindex 1e2b14df0d..4c7aaa7210 100644--- a/client/src/components/Nav/Settings/registry.tsx+++ b/client/src/components/Nav/Settings/registry.tsx@@ -1,5 +1,12 @@import { SettingsTabValues } from 'librechat-data-provider';import type { SettingEntry } from './types';+import {+ unseenTabBadgeAtom,+ replyNotificationsAtom,+ replyNotificationSoundAtom,+ unlockReplyNotificationSound,+ requestReplyNotificationPermission,+} from '~/hooks';import {TextToSpeechSwitch,VoiceDropdown,@@ -170,6 +177,60 @@ export const registry: SettingEntry[] = [keywords: ['tab', 'title', 'browser', 'window'],Component: ChatTitleInTab,},+ // General · Notifications+ {+ id: 'unseenTabBadge',+ tab: GENERAL,+ section: 'notifications',+ show: (ctx) => ctx.replyTabBadgeAllowed,+ labelKey: 'com_nav_unseen_tab_badge',+ Component: toggleControl({+ stateAtom: unseenTabBadgeAtom,+ localizationKey: 'com_nav_unseen_tab_badge',+ switchId: 'unseenTabBadge',+ hoverCardText: 'com_nav_info_unseen_tab_badge',+ }),+ },+ {+ id: 'replyNotifications',+ tab: GENERAL,+ section: 'notifications',+ show: (ctx) => ctx.replyNotificationsAllowed,+ labelKey: 'com_nav_reply_notifications',+ Component: toggleControl({+ stateAtom: replyNotificationsAtom,+ localizationKey: 'com_nav_reply_notifications',+ switchId: 'replyNotifications',+ hoverCardText: 'com_nav_info_reply_notifications',+ /* The toggle click is the user gesture browsers require before asking for+ desktop-notification permission. */+ onCheckedChange: (value) => {+ if (value) {+ requestReplyNotificationPermission();+ }+ },+ }),+ },+ {+ id: 'replyNotificationSound',+ tab: GENERAL,+ section: 'notifications',+ show: (ctx) => ctx.replyNotificationSoundAllowed,+ labelKey: 'com_nav_reply_notification_sound',+ Component: toggleControl({+ stateAtom: replyNotificationSoundAtom,+ localizationKey: 'com_nav_reply_notification_sound',+ switchId: 'replyNotificationSound',+ hoverCardText: 'com_nav_info_reply_notification_sound',+ /* Browsers only let an audio output open behind a user gesture, and alerts fire while+ the tab is unfocused; this click is the gesture that unlocks it. */+ onCheckedChange: (value) => {+ if (value) {+ unlockReplyNotificationSound();+ }+ },+ }),+ },// General · Accessibility{id: 'keepScreenAwake',diff --git a/client/src/components/Nav/Settings/types.ts b/client/src/components/Nav/Settings/types.tsindex 3f981ae924..13263e7179 100644--- a/client/src/components/Nav/Settings/types.ts+++ b/client/src/components/Nav/Settings/types.ts@@ -17,6 +17,7 @@ export type SettingsTab =export type SectionId =| 'appearance'| 'layout'+ | 'notifications'| 'accessibility'| 'admin'| 'sending'@@ -55,6 +56,9 @@ export interface SettingsContextValue {engineTTS: string;langfuseConnectionAccess: boolean;adminPanelURL: string;+ replyTabBadgeAllowed: boolean;+ replyNotificationsAllowed: boolean;+ replyNotificationSoundAllowed: boolean;}export interface SettingEntry {@@ -101,6 +105,7 @@ export const TABS: TabMeta[] = [sections: [{ id: 'appearance', labelKey: 'com_ui_settings_section_appearance' },{ id: 'layout', labelKey: 'com_ui_settings_section_layout' },+ { id: 'notifications', labelKey: 'com_ui_settings_section_notifications' },{ id: 'accessibility', labelKey: 'com_ui_settings_section_accessibility' },{ id: 'admin', labelKey: 'com_ui_settings_section_admin' },],diff --git a/client/src/data-provider/Messages/queries.ts b/client/src/data-provider/Messages/queries.tsindex 248a9776f0..d02bc06137 100644--- a/client/src/data-provider/Messages/queries.ts+++ b/client/src/data-provider/Messages/queries.ts@@ -4,7 +4,13 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';import { Constants, QueryKeys, dataService } from 'librechat-data-provider';import type { UseQueryOptions, QueryObserverResult, QueryClient } from '@tanstack/react-query';import type * as t from 'librechat-data-provider';-import { isNotFoundError, logger } from '~/utils';+import {+ beginMessagesReplyFetch,+ completeMessagesReplyFetch,+ findConvoInAllQueries,+ isNotFoundError,+ logger,+} from '~/utils';type StableMessagesParams = {pathname: string;@@ -106,6 +112,11 @@ export const useGetMessagesByConvoId = <TData = t.TMessage[]>(return messagesAtRequestStart ?? [];}+ const request = beginMessagesReplyFetch(+ queryClient,+ id,+ findConvoInAllQueries(queryClient, id)?.lastResponseAt,+ );let result: t.TMessage[];try {result = await dataService.getMessagesByConvoId(id);@@ -116,6 +127,7 @@ export const useGetMessagesByConvoId = <TData = t.TMessage[]>(currentMessages != null &¤tMessages !== messagesAtRequestStart) {+ completeMessagesReplyFetch(queryClient, id, request, false);return currentMessages;}@@ -134,9 +146,11 @@ export const useGetMessagesByConvoId = <TData = t.TMessage[]>(`Messages query for convo ${id} returned 404 while cache has a pending assistant tail; path: "${location.pathname}"`,currentMessages,);+ completeMessagesReplyFetch(queryClient, id, request, false);return currentMessages;}+ completeMessagesReplyFetch(queryClient, id, request, false);throw error;}@@ -146,6 +160,7 @@ export const useGetMessagesByConvoId = <TData = t.TMessage[]>(currentMessages != null &¤tMessages !== messagesAtRequestStart) {+ completeMessagesReplyFetch(queryClient, id, request, false);return currentMessages;}@@ -165,6 +180,7 @@ export const useGetMessagesByConvoId = <TData = t.TMessage[]>();}+ completeMessagesReplyFetch(queryClient, id, request, stableMessages === result);return stableMessages;},{diff --git a/client/src/data-provider/__tests__/pinnedConversations.test.tsx b/client/src/data-provider/__tests__/pinnedConversations.test.tsxindex aa44a16756..627d3d29d2 100644--- a/client/src/data-provider/__tests__/pinnedConversations.test.tsx+++ b/client/src/data-provider/__tests__/pinnedConversations.test.tsx@@ -435,15 +435,23 @@ describe('pinned list cache synchronization', () => {);});- it('withoutListFlags drops only the sidebar-owned flags', () => {+ it('withoutListFlags drops the sidebar-owned flags and read state', () => {+ /* The chat's own state snapshots both when the chat is opened: writing them back would+ drop the chat out of Pinned, or relight a dot the user has already cleared. */const stripped = withoutListFlags({...pinnedConvo,pinned: false,isShared: true,+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastResponseIsManual: true,+ lastSeenAt: '2026-08-16T10:01:00.000Z',} as TConversation);expect('pinned' in stripped).toBe(false);expect('isShared' in stripped).toBe(false);+ expect('lastResponseAt' in stripped).toBe(false);+ expect('lastResponseIsManual' in stripped).toBe(false);+ expect('lastSeenAt' in stripped).toBe(false);expect(stripped.conversationId).toBe(pinnedConversationId);expect(stripped.title).toBe(pinnedConvo.title);});diff --git a/client/src/data-provider/__tests__/useMarkConversationSeenMutation.test.tsx b/client/src/data-provider/__tests__/useMarkConversationSeenMutation.test.tsxnew file mode 100644index 0000000000..0d2234943e--- /dev/null+++ b/client/src/data-provider/__tests__/useMarkConversationSeenMutation.test.tsx@@ -0,0 +1,348 @@+import React from 'react';+import { act, renderHook, waitFor } from '@testing-library/react';+import { EModelEndpoint, QueryKeys } from 'librechat-data-provider';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { InfiniteData } from '@tanstack/react-query';+import type { ConversationCursorData } from '~/utils/convos';+import { useMarkConversationSeenMutation, useMarkConversationUnreadMutation } from '../mutations';+import { isConversationUnseen, updateConvoInAllQueries } from '~/utils';++const mockMarkSeen = jest.fn();+const mockMarkUnread = jest.fn();+jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ markConversationSeen: (...args: unknown[]) => mockMarkSeen(...args),+ markConversationUnread: (...args: unknown[]) => mockMarkUnread(...args),+ },+ };+});++const CONVO_ID = 'convo-mark';+const listKey = [QueryKeys.allConversations, { isArchived: false }];+const RESPONDED_AT = '2026-08-16T10:00:00.000Z';+const SEEN_AT = '2026-08-16T09:00:00.000Z';++/** Stands in for a list refetch committing whatever the server last told it. */+function seedList(queryClient: QueryClient, lastResponseAt = RESPONDED_AT, lastSeenAt?: string) {+ queryClient.setQueryData<InfiniteData<ConversationCursorData>>(listKey, {+ pages: [+ {+ conversations: [+ {+ conversationId: CONVO_ID,+ title: 'Marked',+ endpoint: EModelEndpoint.openAI,+ createdAt: SEEN_AT,+ updatedAt: SEEN_AT,+ lastResponseAt,+ lastSeenAt,+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });+}++function setup(lastSeenAt?: string) {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ seedList(queryClient, RESPONDED_AT, lastSeenAt);++ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );++ const view = renderHook(() => useMarkConversationSeenMutation(), { wrapper });+ const cached = () =>+ queryClient.getQueryData<InfiniteData<ConversationCursorData>>(listKey)?.pages[0]+ .conversations[0];++ return { ...view, cached, queryClient, wrapper };+}++describe('useMarkConversationSeenMutation', () => {+ beforeEach(() => {+ mockMarkSeen.mockReset();+ mockMarkUnread.mockReset();+ });++ it('optimistically marks the conversation seen while the request is in flight', async () => {+ mockMarkSeen.mockReturnValue(new Promise(() => undefined));+ const { result, cached } = setup();++ await act(async () => {+ result.current.mutate({ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT });+ });++ expect(cached()?.lastSeenAt).toBeDefined();+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ });++ it('acknowledges the observed reply rather than the browser clock', async () => {+ /* A clock behind the server would leave the row unseen, and the cache write feeding the+ seen triggers would restart the mutation on every pass. */+ mockMarkSeen.mockReturnValue(new Promise(() => undefined));+ const { result, cached } = setup();++ await act(async () => {+ result.current.mutate({ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT });+ });++ expect(cached()?.lastSeenAt).toBe(RESPONDED_AT);+ expect(isConversationUnseen(cached())).toBe(false);+ });++ it('falls back to the cached reply stamp when the caller names none', async () => {+ mockMarkSeen.mockReturnValue(new Promise(() => undefined));+ const { result, cached } = setup();++ await act(async () => {+ result.current.mutate({ conversationId: CONVO_ID });+ });++ expect(cached()?.lastSeenAt).toBe(RESPONDED_AT);+ });++ it('does not reapply a stale seen acknowledgement after a later unread write clears it', async () => {+ const seenRequest = deferred();+ mockMarkSeen.mockReturnValue(seenRequest.promise);+ mockMarkUnread.mockResolvedValue({ modified: true, lastResponseAt: RESPONDED_AT });+ const { result, cached, queryClient, wrapper } = setup(SEEN_AT);+ const unread = renderHook(() => useMarkConversationUnreadMutation(), { wrapper });++ await act(async () => {+ const seenPending = result.current.mutateAsync({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ await flush();+ await unread.result.current.mutateAsync({ conversationId: CONVO_ID });+ /* A server refresh after the unread settles carries the cleared catch-up. */+ seedList(queryClient, RESPONDED_AT);+ seenRequest.resolve({ modified: true });+ await seenPending;+ });++ expect(cached()?.lastSeenAt).toBeUndefined();+ expect(isConversationUnseen(cached())).toBe(true);+ });++ it('cancels list fetches already reading the old catch-up', async () => {+ /* One of them can deliver after the acknowledgement has settled and put the stale value+ back, and the caller's attempt guard would not send it again. */+ const request = deferred();+ mockMarkSeen.mockReturnValue(request.promise);+ const { result, queryClient } = setup(SEEN_AT);+ const cancel = jest.spyOn(queryClient, 'cancelQueries');++ await act(async () => {+ const pending = result.current.mutateAsync({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ await flush();+ request.resolve({ modified: true });+ await pending;+ });++ expect(cancel).toHaveBeenCalledWith([QueryKeys.allConversations]);+ expect(cancel).toHaveBeenCalledWith([QueryKeys.pinnedConversations]);+ });++ it('cancels a point-query fetch already reading the old catch-up', async () => {+ /* A conversation opened by URL resolves into its own point query, which the read and+ write helpers both consult. A refetch delivering after settlement would land the stale+ row as the freshest copy and read as unseen again. */+ const request = deferred();+ mockMarkSeen.mockReturnValue(request.promise);+ const { result, queryClient } = setup(SEEN_AT);+ queryClient.setQueryData([QueryKeys.conversation, CONVO_ID], {+ conversationId: CONVO_ID,+ title: 'Marked',+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: SEEN_AT,+ });+ const cancel = jest.spyOn(queryClient, 'cancelQueries');++ await act(async () => {+ const pending = result.current.mutateAsync({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ await flush();+ request.resolve({ modified: true });+ await pending;+ });++ expect(cancel).toHaveBeenCalledWith([QueryKeys.conversation, CONVO_ID]);+ });++ it('leaves an unloaded point query alone so its initial load can deliver', async () => {+ /* Cancelling ChatRoute's first conversation fetch would revert it to empty with its+ refetches disabled, leaving the route waiting on data nothing restarts. */+ const request = deferred();+ mockMarkSeen.mockReturnValue(request.promise);+ const { result, queryClient } = setup(SEEN_AT);+ const cancel = jest.spyOn(queryClient, 'cancelQueries');++ await act(async () => {+ const pending = result.current.mutateAsync({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ await flush();+ request.resolve({ modified: true });+ await pending;+ });++ expect(cancel).not.toHaveBeenCalledWith([QueryKeys.conversation, CONVO_ID]);+ });++ it('restores the real state when the server declines the observed reply', async () => {+ /* A newer reply landed mid-flight, so the acknowledgement did not apply and the row is+ genuinely still unseen. */+ mockMarkSeen.mockResolvedValue({ modified: false });+ const { result, cached } = setup(SEEN_AT);++ await act(async () => {+ await result.current.mutateAsync({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ });++ await waitFor(() => expect(cached()?.lastSeenAt).toBe(SEEN_AT));+ });++ it('restarts the reads it cancelled when the server declines the acknowledgement', async () => {+ /* The rejection means the server holds a reply this tab has not read, and the refetch that+ would have delivered it was cancelled on the way in. The optimistic write refreshed+ `dataUpdatedAt`, so nothing refetches on its own and the newer reply would stay out of+ the dot, the badge and the alerts. */+ mockMarkSeen.mockResolvedValue({ modified: false });+ const { result, queryClient } = setup(SEEN_AT);+ queryClient.setQueryData([QueryKeys.conversation, CONVO_ID], {+ conversationId: CONVO_ID,+ title: 'Marked',+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: SEEN_AT,+ });+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries');++ await act(async () => {+ await result.current.mutateAsync({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ });++ expect(invalidate).toHaveBeenCalledWith([QueryKeys.allConversations]);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.pinnedConversations]);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversation, CONVO_ID]);+ });++ it('leaves untouched caches alone when the acknowledgement is accepted', async () => {+ mockMarkSeen.mockResolvedValue({ modified: true });+ const { result, queryClient } = setup(SEEN_AT);+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries');++ await act(async () => {+ await result.current.mutateAsync({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ });++ expect(invalidate).not.toHaveBeenCalled();+ });++ it('restarts a read it interrupted even when the acknowledgement is accepted', async () => {+ /* The cancelled response was carrying rows this mutation never asked about, and the+ optimistic write refreshed `dataUpdatedAt`, so nothing would refetch it. */+ mockMarkSeen.mockResolvedValue({ modified: true });+ const { result, queryClient } = setup(SEEN_AT);+ const listQuery = queryClient.getQueryCache().find(listKey);+ listQuery?.setState({ fetchStatus: 'fetching' } as never);+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries');++ await act(async () => {+ await result.current.mutateAsync({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ });++ expect(invalidate).toHaveBeenCalledWith(listKey, { exact: true, refetchType: 'all' });+ });++ it('does not undo a newer acknowledgement when an older request fails last', async () => {+ /* Same ordering hazard as the success path: reply A's request can fail after reply B has+ already been acknowledged, and an unconditional rollback would take B with it. */+ const NEWER_RESPONDED_AT = '2026-08-16T10:05:00.000Z';+ const request = deferred();+ mockMarkSeen.mockReturnValue(request.promise);+ const { result, cached, queryClient } = setup(SEEN_AT);++ await act(async () => {+ const stale = result.current+ .mutateAsync({ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT })+ .catch(() => undefined);+ await flush();+ seedList(queryClient, NEWER_RESPONDED_AT);+ updateConvoInAllQueries(queryClient, CONVO_ID, (convo) => ({+ ...convo,+ lastSeenAt: NEWER_RESPONDED_AT,+ }));+ request.reject(new Error('network down'));+ await stale;+ });++ expect(cached()?.lastSeenAt).toBe(NEWER_RESPONDED_AT);+ });++ it('restores the previous catch-up state when the request fails', async () => {+ mockMarkSeen.mockRejectedValue(new Error('network down'));+ const { result, cached } = setup(SEEN_AT);++ await act(async () => {+ await result.current.mutateAsync({ conversationId: CONVO_ID }).catch(() => undefined);+ });++ /* Restoring the old value re-arms the seen triggers, which gate on the cache. */+ await waitFor(() => expect(cached()?.lastSeenAt).toBe(SEEN_AT));+ });++ it('restores never-seen when a first catch-up fails', async () => {+ mockMarkSeen.mockRejectedValue(new Error('network down'));+ const { result, cached } = setup();++ await act(async () => {+ await result.current.mutateAsync({ conversationId: CONVO_ID }).catch(() => undefined);+ });++ await waitFor(() => expect(cached()?.lastSeenAt).toBeUndefined());+ });+});++/** Lets a test place work between the optimistic pass and the response callback. */+function deferred() {+ let resolve!: (value: unknown) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise((res, rej) => {+ resolve = res;+ reject = rej;+ });+ /* Swallowed here so a rejection scheduled for the mutation does not surface as unhandled. */+ promise.catch(() => undefined);+ return { promise, resolve, reject };+}++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));diff --git a/client/src/data-provider/__tests__/useMarkConversationUnreadMutation.test.tsx b/client/src/data-provider/__tests__/useMarkConversationUnreadMutation.test.tsxnew file mode 100644index 0000000000..4684f538e3--- /dev/null+++ b/client/src/data-provider/__tests__/useMarkConversationUnreadMutation.test.tsx@@ -0,0 +1,517 @@+import React from 'react';+import { act, renderHook, waitFor } from '@testing-library/react';+import { EModelEndpoint, QueryKeys } from 'librechat-data-provider';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { InfiniteData } from '@tanstack/react-query';+import type { ConversationCursorData } from '~/utils/convos';+import { useMarkConversationSeenMutation, useMarkConversationUnreadMutation } from '../mutations';+import { isConversationUnseen, updateConvoInAllQueries } from '~/utils';++const mockMarkUnread = jest.fn();+const mockMarkSeen = jest.fn();+jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ markConversationUnread: (...args: unknown[]) => mockMarkUnread(...args),+ markConversationSeen: (...args: unknown[]) => mockMarkSeen(...args),+ },+ };+});++const CONVO_ID = 'convo-unread';+const listKey = [QueryKeys.allConversations, { isArchived: false }];+const archivedKey = [QueryKeys.archivedConversations, { isArchived: true }];+const RESPONDED_AT = '2026-08-16T10:00:00.000Z';+const SEEN_AT = '2026-08-16T11:00:00.000Z';++/** Stands in for a list refetch committing whatever the server last told it. */+function seedList(queryClient: QueryClient, lastResponseAt?: string, lastSeenAt?: string) {+ queryClient.setQueryData<InfiniteData<ConversationCursorData>>(listKey, {+ pages: [+ {+ conversations: [+ {+ conversationId: CONVO_ID,+ title: 'Flagged',+ endpoint: EModelEndpoint.openAI,+ createdAt: RESPONDED_AT,+ updatedAt: SEEN_AT,+ lastResponseAt,+ lastResponseMessageId: lastResponseAt == null ? undefined : 'original-reply',+ lastSeenAt,+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });+}++function setup(lastResponseAt?: string, lastSeenAt?: string) {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ seedList(queryClient, lastResponseAt, lastSeenAt);++ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );++ const view = renderHook(() => useMarkConversationUnreadMutation(), { wrapper });+ const cached = () =>+ queryClient.getQueryData<InfiniteData<ConversationCursorData>>(listKey)?.pages[0]+ .conversations[0];++ return { ...view, cached, queryClient, wrapper };+}++describe('useMarkConversationUnreadMutation', () => {+ beforeEach(() => {+ mockMarkUnread.mockReset();+ mockMarkSeen.mockReset();+ });++ it('reasserts the unread state when a refetch lands on top of it', async () => {+ /* A list refetch already in flight can have read the old catch-up and commit after the+ optimistic clear, quietly taking the dot back off a conversation the server did flag. */+ mockMarkUnread.mockResolvedValue({ modified: true, lastResponseAt: RESPONDED_AT });+ const { result, cached, queryClient } = setup(RESPONDED_AT, SEEN_AT);++ await act(async () => {+ const pending = result.current.mutateAsync({ conversationId: CONVO_ID });+ seedList(queryClient, RESPONDED_AT, SEEN_AT);+ await pending;+ });++ await waitFor(() => expect(isConversationUnseen(cached())).toBe(true));+ expect(cached()?.lastSeenAt).toBeUndefined();+ });++ it('preserves a later seen operation even when its stamp equals the original catch-up', async () => {+ const request = deferred();+ mockMarkUnread.mockReturnValue(request.promise);+ mockMarkSeen.mockResolvedValue({ modified: true });+ const { result, cached, wrapper } = setup(RESPONDED_AT, RESPONDED_AT);+ const seen = renderHook(() => useMarkConversationSeenMutation(), { wrapper });++ await act(async () => {+ const unread = result.current.mutateAsync({ conversationId: CONVO_ID });+ await flush();+ await seen.result.current.mutateAsync({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ request.resolve({ modified: true, lastResponseAt: RESPONDED_AT });+ await unread;+ });++ expect(cached()?.lastSeenAt).toBe(RESPONDED_AT);+ expect(isConversationUnseen(cached())).toBe(false);+ });++ it('preserves an acknowledgement that landed while the unread request was open', async () => {+ /* The user flags the conversation, then opens and reads the reply before the request+ settles. Clearing that newer catch-up would show a dot the server no longer backs,+ with the seen trigger's attempt guard suppressing the re-send. */+ const request = deferred();+ mockMarkUnread.mockReturnValue(request.promise);+ const { result, cached, queryClient } = setup(RESPONDED_AT, SEEN_AT);++ await act(async () => {+ const pending = result.current.mutateAsync({ conversationId: CONVO_ID });+ /* After the optimistic clear: the seen mutation acknowledges the observed reply. */+ await flush();+ updateConvoInAllQueries(queryClient, CONVO_ID, (convo) => ({+ ...convo,+ lastSeenAt: RESPONDED_AT,+ }));+ request.resolve({ modified: true, lastResponseAt: RESPONDED_AT });+ await pending;+ });++ expect(cached()?.lastSeenAt).toBe(RESPONDED_AT);+ expect(isConversationUnseen(cached())).toBe(false);+ });++ it('refetches when a catch-up it did not write settles alongside the unread', async () => {+ /* The read may have been accepted before the unread write, in which case the server holds+ the conversation unread while this tab shows it read; the cache alone cannot tell, so+ the row is refetched rather than guessed at. */+ const request = deferred();+ mockMarkUnread.mockReturnValue(request.promise);+ const { result, queryClient } = setup(RESPONDED_AT, SEEN_AT);+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries');++ await act(async () => {+ const pending = result.current.mutateAsync({ conversationId: CONVO_ID });+ await flush();+ updateConvoInAllQueries(queryClient, CONVO_ID, (convo) => ({+ ...convo,+ lastSeenAt: RESPONDED_AT,+ }));+ request.resolve({ modified: true, lastResponseAt: RESPONDED_AT });+ await pending;+ });++ expect(invalidate).toHaveBeenCalledWith([QueryKeys.allConversations]);+ });++ it('keeps a newer reply that arrived while the unread request was open', async () => {+ /* The server read the marker on the way in; a reply landing after that is newer than what+ it can return, and overwriting it would strand the dot behind a spent completion. */+ const NEWER_RESPONDED_AT = '2026-08-16T12:00:00.000Z';+ const request = deferred();+ mockMarkUnread.mockReturnValue(request.promise);+ const { result, cached, queryClient } = setup(RESPONDED_AT, SEEN_AT);++ await act(async () => {+ const pending = result.current.mutateAsync({ conversationId: CONVO_ID });+ /* After the optimistic pass, so the merge is genuinely a later arrival. */+ await flush();+ updateConvoInAllQueries(queryClient, CONVO_ID, (convo) => ({+ ...convo,+ lastResponseAt: NEWER_RESPONDED_AT,+ lastResponseMessageId: 'newer-reply',+ }));+ request.resolve({ modified: true, lastResponseAt: RESPONDED_AT });+ await pending;+ });++ expect(cached()?.lastResponseAt).toBe(NEWER_RESPONDED_AT);+ expect(cached()?.lastResponseMessageId).toBe('newer-reply');+ expect(isConversationUnseen(cached())).toBe(true);+ });++ it('does not roll back over a newer reply that arrived mid-flight', async () => {+ /* The watcher or the SSE path can merge a newer reply while the request is open; restoring+ the pre-mutation stamps over it would make that reply read as seen with its completion+ signal already spent. */+ const NEWER_RESPONDED_AT = '2026-08-16T12:00:00.000Z';+ const request = deferred();+ mockMarkUnread.mockReturnValue(request.promise);+ const { result, cached, queryClient } = setup(RESPONDED_AT, SEEN_AT);++ await act(async () => {+ const pending = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ await flush();+ updateConvoInAllQueries(queryClient, CONVO_ID, (convo) => ({+ ...convo,+ lastResponseAt: NEWER_RESPONDED_AT,+ lastResponseMessageId: 'newer-reply',+ }));+ request.reject(new Error('network down'));+ await pending;+ });++ expect(cached()?.lastResponseAt).toBe(NEWER_RESPONDED_AT);+ expect(cached()?.lastResponseMessageId).toBe('newer-reply');+ expect(isConversationUnseen(cached())).toBe(true);+ });++ it('removes a conversation the server no longer has', async () => {+ /* Deleted on another device, or between the access check and the write. The server's+ owner-scoped update returns the row even when it changes nothing, so no match means the+ row is gone: rolling back its read state would keep a conversation that does not exist in+ the sidebar and the badge. */+ mockMarkUnread.mockResolvedValue({ modified: false });+ const { result, queryClient } = setup(RESPONDED_AT, SEEN_AT);+ const listed = () =>+ (+ queryClient.getQueryData<InfiniteData<ConversationCursorData>>(listKey)?.pages ?? []+ ).flatMap((page) => page.conversations.map((convo) => convo.conversationId));++ await act(async () => {+ await result.current.mutateAsync({ conversationId: CONVO_ID });+ });++ await waitFor(() => expect(listed()).not.toContain(CONVO_ID));+ });++ it('caches the server marker for a conversation that had no reply', async () => {+ const serverStamp = '2026-08-16T12:00:00.000Z';+ mockMarkUnread.mockResolvedValue({ modified: true, lastResponseAt: serverStamp });+ const { result, cached } = setup(undefined, undefined);++ await act(async () => {+ await result.current.mutateAsync({ conversationId: CONVO_ID });+ });++ await waitFor(() => expect(cached()?.lastResponseAt).toBe(serverStamp));+ expect(isConversationUnseen(cached())).toBe(true);+ });++ it('settles a concurrently discovered real reply with its server message identity', async () => {+ const serverStamp = '2026-08-16T12:00:00.000Z';+ mockMarkUnread.mockResolvedValue({+ modified: true,+ lastResponseAt: serverStamp,+ lastResponseMessageId: 'server-reply',+ lastResponseIsManual: false,+ });+ const { result, cached } = setup();+ await act(async () => {+ await result.current.mutateAsync({ conversationId: CONVO_ID });+ });++ expect(cached()?.lastResponseAt).toBe(serverStamp);+ expect(cached()?.lastResponseMessageId).toBe('server-reply');+ expect(isConversationUnseen(cached())).toBe(true);+ });++ it('optimistically flags a read conversation unread while the request is in flight', async () => {+ mockMarkUnread.mockReturnValue(new Promise(() => undefined));+ const { result, cached } = setup(RESPONDED_AT, SEEN_AT);++ await act(async () => {+ result.current.mutate({ conversationId: CONVO_ID });+ });++ expect(isConversationUnseen(cached())).toBe(true);+ expect(mockMarkUnread).toHaveBeenCalledWith({ conversationId: CONVO_ID });+ });++ it('stamps lastResponseAt for a never-replied conversation so the dot lights', async () => {+ mockMarkUnread.mockReturnValue(new Promise(() => undefined));+ const { result, cached } = setup();++ await act(async () => {+ result.current.mutate({ conversationId: CONVO_ID });+ });++ expect(cached()?.lastResponseAt).toBeDefined();+ expect(isConversationUnseen(cached())).toBe(true);+ });++ it('restores the previous state when the request fails', async () => {+ mockMarkUnread.mockRejectedValue(new Error('network down'));+ const { result, cached } = setup(RESPONDED_AT, SEEN_AT);++ await act(async () => {+ await result.current.mutateAsync({ conversationId: CONVO_ID }).catch(() => undefined);+ });++ await waitFor(() => expect(cached()?.lastSeenAt).toBe(SEEN_AT));+ await waitFor(() => expect(isConversationUnseen(cached())).toBe(false));+ });++ it('keeps the row unread when an earlier request fails and the later one succeeds', async () => {+ /* Activating the menu action twice before the first request settles: both write the same+ optimistic state, so only the later request owns the row. A rollback from the first would+ restore the catch-up, and the second's settlement would read that as a newer+ acknowledgement and leave the row seen although the server marked it unread. */+ const first = deferred();+ const second = deferred();+ mockMarkUnread.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ const { result, cached } = setup(RESPONDED_AT, SEEN_AT);++ await act(async () => {+ const firstPending = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ await flush();+ const secondPending = result.current.mutateAsync({ conversationId: CONVO_ID });+ await flush();+ first.reject(new Error('network down'));+ second.resolve({ modified: true, lastResponseAt: RESPONDED_AT });+ await Promise.all([firstPending, secondPending]);+ });++ expect(cached()?.lastSeenAt).toBeUndefined();+ expect(isConversationUnseen(cached())).toBe(true);+ });+ it('keeps an accepted unread when the successor request fails', async () => {+ const first = deferred();+ const second = deferred();+ mockMarkUnread.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ const { result, cached } = setup(RESPONDED_AT, SEEN_AT);++ await act(async () => {+ const firstPending = result.current.mutateAsync({ conversationId: CONVO_ID });+ await flush();+ const secondPending = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ await flush();+ first.resolve({ modified: true, lastResponseAt: RESPONDED_AT });+ await firstPending;+ second.reject(new Error('network down'));+ await secondPending;+ });++ expect(cached()?.lastSeenAt).toBeUndefined();+ expect(isConversationUnseen(cached())).toBe(true);+ });++ it('reasserts an earlier accepted unread when the failed successor settles first', async () => {+ const first = deferred();+ const second = deferred();+ mockMarkUnread.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ const { result, cached } = setup(RESPONDED_AT, SEEN_AT);++ await act(async () => {+ const firstPending = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ await flush();+ const secondPending = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ await flush();+ second.reject(new Error('network down'));+ await secondPending;+ first.resolve({ modified: true, lastResponseAt: RESPONDED_AT });+ await firstPending;+ });++ expect(cached()?.lastSeenAt).toBeUndefined();+ expect(isConversationUnseen(cached())).toBe(true);+ });++ it('restores the original read state when overlapping unread requests both fail', async () => {+ const first = deferred();+ const second = deferred();+ mockMarkUnread.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ const { result, cached } = setup();++ await act(async () => {+ const firstPending = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ await flush();+ const secondPending = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ await flush();+ /* The successor owns the optimistic row but must still roll back to the first baseline. */+ second.reject(new Error('network down'));+ first.reject(new Error('network down'));+ await Promise.all([firstPending, secondPending]);+ });++ expect(cached()?.lastResponseAt).toBeUndefined();+ expect(cached()?.lastResponseIsManual).toBeUndefined();+ expect(cached()?.lastSeenAt).toBeUndefined();+ expect(isConversationUnseen(cached())).toBe(false);+ });++ /* The older call no longer owns the row once a newer one has started, but its no-match is+ still the server saying the conversation is gone. Dropping it with the other non-owning+ answers would leave a deleted conversation restored to the list by the newer failure. */+ it('removes the conversation when an older overlapping call reports no match', async () => {+ const first = deferred();+ const second = deferred();+ mockMarkUnread.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ const { result, queryClient } = setup(RESPONDED_AT, SEEN_AT);+ const listed = () =>+ (+ queryClient.getQueryData<InfiniteData<ConversationCursorData>>(listKey)?.pages ?? []+ ).flatMap((page) => page.conversations.map((convo) => convo.conversationId));++ await act(async () => {+ const firstPending = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ await flush();+ const secondPending = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ await flush();+ second.reject(new Error('network down'));+ first.resolve({ modified: false });+ await Promise.all([firstPending, secondPending]);+ });++ expect(listed()).not.toContain(CONVO_ID);+ });++ it('rolls an archived row back when the server refuses the unread write', async () => {+ /* Mark as unread is offered from the archived view, where the row lives in its own list+ cache: a baseline read that skipped it left the failed write's dot on screen. */+ const request = deferred();+ mockMarkUnread.mockReturnValue(request.promise);+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ queryClient.setQueryData<InfiniteData<ConversationCursorData>>(archivedKey, {+ pages: [+ {+ conversations: [+ {+ conversationId: CONVO_ID,+ title: 'Archived',+ endpoint: EModelEndpoint.openAI,+ createdAt: RESPONDED_AT,+ updatedAt: SEEN_AT,+ isArchived: true,+ lastResponseAt: RESPONDED_AT,+ lastResponseMessageId: 'original-reply',+ lastSeenAt: SEEN_AT,+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ const { result } = renderHook(() => useMarkConversationUnreadMutation(), { wrapper });+ const archived = () =>+ queryClient.getQueryData<InfiniteData<ConversationCursorData>>(archivedKey)?.pages[0]+ .conversations[0];++ await act(async () => {+ const pending = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ await flush();+ expect(isConversationUnseen(archived())).toBe(true);+ request.reject(new Error('network down'));+ await pending;+ });++ expect(archived()?.lastSeenAt).toBe(SEEN_AT);+ expect(isConversationUnseen(archived())).toBe(false);+ });++ it('abandons an unread write that the user superseded by opening the conversation', async () => {+ /* The unread write suspends while list fetches are cancelled; the read that starts in that+ window is the newer intent, and sending the unread request afterwards would leave the+ server flagged against it. */+ mockMarkSeen.mockResolvedValue({ modified: true });+ const { result, cached, wrapper } = setup(RESPONDED_AT, SEEN_AT);+ const seen = renderHook(() => useMarkConversationSeenMutation(), { wrapper });++ await act(async () => {+ const unread = result.current+ .mutateAsync({ conversationId: CONVO_ID })+ .catch(() => undefined);+ const read = seen.result.current+ .mutateAsync({ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT })+ .catch(() => undefined);+ await Promise.all([unread, read]);+ });++ expect(mockMarkUnread).not.toHaveBeenCalled();+ expect(mockMarkSeen).toHaveBeenCalledTimes(1);+ expect(isConversationUnseen(cached())).toBe(false);+ });+});++/** Lets a test place work between the optimistic pass and the response callback. */+function deferred() {+ let resolve!: (value: unknown) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise((res, rej) => {+ resolve = res;+ reject = rej;+ });+ /* Swallowed here so a rejection scheduled for the mutation does not surface as unhandled. */+ promise.catch(() => undefined);+ return { promise, resolve, reject };+}++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));diff --git a/client/src/data-provider/mutations.ts b/client/src/data-provider/mutations.tsindex 97193a4137..665f8bbee6 100644--- a/client/src/data-provider/mutations.ts+++ b/client/src/data-provider/mutations.ts@@ -6,16 +6,18 @@ import {defaultAssistantsVersion,ConversationListResponse,} from 'librechat-data-provider';-import type { InfiniteData, QueryClient, UseMutationResult } from '@tanstack/react-query';+import type { InfiniteData, QueryClient, QueryKey, UseMutationResult } from '@tanstack/react-query';import type * as t from 'librechat-data-provider';import {logger,/* Conversations */addConvoToAllQueries,findPinnedConversation,+ findConvoInAllQueries,findConversationInInfinite,updateConvoInAllQueries,removeConvoFromAllQueries,+ CONVERSATION_LIST_KEYS,clearArchivedConversationMessagesCache,clearDeletedConversationMessagesCache,} from '~/utils';@@ -266,6 +268,615 @@ export const usePinConversationMutation = ();};+/**+ * Stops fetches that are already reading the old read state.+ *+ * One of them can have read the row before the write lands and deliver afterwards, putting the+ * stale catch-up back over a settled acknowledgement. Cancelling is the cheap half of React+ * Query's optimistic recipe: no request is issued, and whatever triggered the fetch (a focus,+ * a mount) triggers it again once the mutation has settled.+ *+ * The point query is covered too, because the read and write helpers both resolve it: left+ * running, its stale payload would land after settlement as the freshest copy and read as+ * unseen again, with the caller's attempt guard suppressing the re-acknowledgement. Only once+ * it holds data, though: cancelling ChatRoute's initial load would revert it to empty, and+ * with its refetches disabled nothing would ever restart that fetch.+ *+ * The roots are the ones the optimistic write reaches, archive included: Mark as unread is+ * offered from the archived view, and an archived list fetch left running would commit the+ * read state it read before the write and never be restarted.+ */+const cancelConvoReadFetches = async (+ queryClient: QueryClient,+ conversationId: string,+): Promise<QueryKey[]> => {+ const pointKey = [QueryKeys.conversation, conversationId];+ const roots = [+ ...CONVERSATION_LIST_KEYS.map((listKey) => [listKey]),+ [QueryKeys.pinnedConversations],+ ];+ const cache = queryClient.getQueryCache();+ /* Recorded before the cancellation, because a cancelled fetch was carrying rows this+ mutation never asked about: other conversations' replies, renames, a page that had not+ landed yet. Its own trigger is gone once it is cancelled, so settlement has to restart+ exactly these. */+ const interrupted = roots+ .flatMap((root) => cache.findAll(root, { exact: false }))+ .filter((query) => query.state.fetchStatus === 'fetching')+ .map((query) => query.queryKey);++ const cancellations = roots.map((root) => queryClient.cancelQueries(root));+ if (queryClient.getQueryData(pointKey) !== undefined) {+ if (cache.find(pointKey)?.state.fetchStatus === 'fetching') {+ interrupted.push(pointKey);+ }+ cancellations.push(queryClient.cancelQueries(pointKey));+ }+ await Promise.all(cancellations);+ return interrupted;+};++/**+ * Restarts exactly the reads this mutation interrupted.+ *+ * "Whatever triggered the fetch triggers it again" only holds while something still asks, and+ * nothing does: the optimistic write refreshed `dataUpdatedAt` on its way through, so the list+ * reads as fresh for the rest of its stale window. Whatever the cancelled response carried,+ * this conversation's newer reply or another one's, would stay missing until an unrelated+ * refetch happened to run.+ */+const restartInterruptedReads = (queryClient: QueryClient, keys: QueryKey[] | undefined): void => {+ for (const key of keys ?? []) {+ /* Every key here was already in flight when this mutation cancelled it, so restarting it+ costs nothing it was not already spending. The default refetches observed queries only,+ and a reply-discovery snapshot has no observer: it would be marked stale and never run+ again, leaving whatever it carried missing until the next focused refresh. */+ queryClient.invalidateQueries(key, { exact: true, refetchType: 'all' });+ }+};++/**+ * Refreshes the read caches wholesale, for a settlement that knows they are behind rather than+ * merely interrupted: a rejected acknowledgement means the server has since stamped a reply+ * this tab has not seen.+ */+const refreshConvoReadCaches = (queryClient: QueryClient, conversationId: string): void => {+ for (const listKey of CONVERSATION_LIST_KEYS) {+ queryClient.invalidateQueries([listKey]);+ }+ queryClient.invalidateQueries([QueryKeys.pinnedConversations]);+ const pointKey = [QueryKeys.conversation, conversationId];+ if (queryClient.getQueryData(pointKey) !== undefined) {+ queryClient.invalidateQueries(pointKey);+ }+};++/**+ * Orders local read-state intent across seen and unread writes.+ *+ * A stale seen response can arrive after a later unread write (or its refetch) has cleared+ * `lastSeenAt`. Keeping the latest operation id outside the query data lets settlement distinguish+ * that clear from an old catch-up, even when the unread request has already settled.+ */+type ReadWriteState = {+ next: number;+ latest: Map<string, number>;+ unreadOwners?: Map<string, UnreadWriteOwner>;+ unreadChains?: Map<string, UnreadWriteChain>;+};++const readWriteStates = new WeakMap<QueryClient, ReadWriteState>();++const getReadWriteState = (queryClient: QueryClient): ReadWriteState => {+ let state = readWriteStates.get(queryClient);+ if (!state) {+ state = { next: 0, latest: new Map() };+ readWriteStates.set(queryClient, state);+ }+ return state;+};++const claimReadWrite = (queryClient: QueryClient, conversationId: string): number => {+ const state = getReadWriteState(queryClient);+ state.next += 1;+ state.latest.set(conversationId, state.next);+ return state.next;+};++const isLatestReadWrite = (+ queryClient: QueryClient,+ conversationId: string,+ token: number | undefined,+): boolean =>+ token !== undefined && getReadWriteState(queryClient).latest.get(conversationId) === token;++const releaseReadWrite = (+ queryClient: QueryClient,+ conversationId: string,+ token: number | undefined,+): void => {+ if (isLatestReadWrite(queryClient, conversationId, token)) {+ getReadWriteState(queryClient).latest.delete(conversationId);+ }+};++/**+ * Cancelling the in-flight list fetches is awaited, and the user can act again inside that+ * window: Mark as unread, then open the conversation. The later intent claims the token while+ * this one is suspended, so a write that resumes without owning the conversation any more has+ * to abandon — its optimistic write and its request would both land after the newer one.+ *+ * Keyed by the variables object, which is the same reference `onMutate` and the request+ * function receive for one call, so concurrent writes cannot read each other's verdict.+ */+const supersededReadWrites = new WeakSet<object>();++const abandonWhenSuperseded = (+ queryClient: QueryClient,+ vars: { conversationId: string },+ token: number,+): boolean => {+ if (isLatestReadWrite(queryClient, vars.conversationId, token)) {+ return false;+ }+ supersededReadWrites.add(vars);+ return true;+};++/**+ * Requests for two replies can be in flight at once, and the first to return is not always the+ * first sent. Settlement is safe only for the latest local read-state operation, while the cache+ * still holds this mutation's own acknowledgement or while it moves the catch-up forward;+ * anything else would undo newer intent that has already landed.+ */+const settleCatchUp = (+ queryClient: QueryClient,+ conversationId: string,+ settled: string | undefined,+ acknowledged: string | undefined,+ operationToken: number | undefined,+): void => {+ if (!isLatestReadWrite(queryClient, conversationId, operationToken)) {+ return;+ }+ const cached = findConvoInAllQueries(queryClient, conversationId);+ if (!cached || cached.lastSeenAt === settled) {+ return;+ }+ const current = cached.lastSeenAt;+ const isOwnWrite = current === acknowledged;+ const movesForward = settled != null && current != null && settled > current;+ if (!isOwnWrite && !movesForward) {+ return;+ }+ updateConvoInAllQueries(queryClient, conversationId, (convo) => ({+ ...convo,+ lastSeenAt: settled,+ }));+};++/**+ * Records that the user has caught up with a conversation's newest message.+ *+ * The cache is updated optimistically so the unseen dot clears on the spot rather than after+ * the round trip. The server stamps its own timestamp; only the ordering against+ * `lastResponseAt` matters, so the brief client/server drift is immaterial.+ */+export const useMarkConversationSeenMutation = (): UseMutationResult<+ t.TMarkConversationSeenResponse,+ unknown,+ t.TMarkConversationSeenRequest,+ unknown+> => {+ const queryClient = useQueryClient();++ return useMutation(+ [MutationKeys.convoSeen],+ (payload: t.TMarkConversationSeenRequest) =>+ supersededReadWrites.delete(payload)+ ? Promise.resolve({ modified: false })+ : dataService.markConversationSeen(payload),+ {+ onMutate: async (vars) => {+ const operationToken = claimReadWrite(queryClient, vars.conversationId);+ const interrupted = await cancelConvoReadFetches(queryClient, vars.conversationId);+ if (abandonWhenSuperseded(queryClient, vars, operationToken)) {+ return {+ previous: undefined,+ acknowledged: undefined,+ operationToken,+ interrupted,+ superseded: true,+ };+ }+ const cached = findConvoInAllQueries(queryClient, vars.conversationId);+ /* Acknowledging exactly the observed reply, rather than the browser's idea of "now":+ a clock running behind the server would leave the row still unseen, and the cache+ write feeding the seen triggers would restart this mutation on every pass. Equality+ reads as caught up. */+ const acknowledged: string | undefined =+ vars.lastResponseAt ?? cached?.lastResponseAt ?? new Date().toISOString();+ updateConvoInAllQueries(queryClient, vars.conversationId, (convo) => ({+ ...convo,+ lastSeenAt: acknowledged,+ }));+ return {+ previous: cached?.lastSeenAt,+ acknowledged,+ operationToken,+ interrupted,+ superseded: false,+ };+ },+ onSuccess: (data, vars, context) => {+ if (context?.superseded === true) {+ return;+ }+ /* A list refetch already in flight can have read the old catch-up before this write+ and commit afterwards, putting it back. Settle against the server's answer once it+ is known: re-apply what it accepted, or restore the real state when the observed+ reply was no longer the newest. The caller's attempt guard keeps either from+ re-arming the same request. */+ const settled = data.modified ? context?.acknowledged : context?.previous;+ settleCatchUp(+ queryClient,+ vars.conversationId,+ settled,+ context?.acknowledged,+ context?.operationToken,+ );+ if (!data.modified) {+ /* Rejected means the server has since stamped a reply this tab has not read, so the+ cache it just restored is known to be behind. */+ refreshConvoReadCaches(queryClient, vars.conversationId);+ }+ },+ onError: (_error, vars, context) => {+ /* The seen triggers gate on the cache, so a failed request has to put the old+ state back, "never caught up" included, or the dot stays cleared until an+ unrelated refetch. Same ownership guard as the success path: a request for an+ older reply can fail after a newer one was acknowledged, and rolling back+ unconditionally would take that newer acknowledgement with it. */+ settleCatchUp(+ queryClient,+ vars.conversationId,+ context?.previous,+ context?.acknowledged,+ context?.operationToken,+ );+ },+ onSettled: (_data, _error, vars, context) => {+ restartInterruptedReads(queryClient, context?.interrupted);+ releaseReadWrite(queryClient, vars.conversationId, context?.operationToken);+ },+ },+ );+};++/**+ * Two clicks before the first request settles both write the same optimistic state, so value+ * comparison alone cannot tell whose write the cache holds. The latest write owns the cache, but+ * every successor carries the original pre-chain baseline so an all-failure chain restores the+ * state from before the first click; an accepted predecessor keeps a later failure unread.+ */+type UnreadWriteBaseline = Pick<+ t.TConversation,+ 'lastResponseAt' | 'lastResponseMessageId' | 'lastResponseIsManual' | 'lastSeenAt'+>;++const resolveReplyIdentity = (+ cached: Partial<t.TConversation> | undefined,+ next:+ | Pick<t.TConversation, 'lastResponseAt' | 'lastResponseMessageId' | 'lastResponseIsManual'>+ | undefined,+): string | undefined => {+ if (!next?.lastResponseAt || next.lastResponseIsManual === true) {+ return undefined;+ }+ return (+ next.lastResponseMessageId ??+ (next.lastResponseAt === cached?.lastResponseAt ? cached?.lastResponseMessageId : undefined)+ );+};++type UnreadWriteChain = {+ baseline: UnreadWriteBaseline;+ latestToken: number;+ pending: number;+ accepted: boolean;+ latestFailureSettled: boolean;+};++type UnreadWriteOwner = {+ token: number;+ chain: UnreadWriteChain;+};++const claimUnreadWrite = (+ queryClient: QueryClient,+ conversationId: string,+ baseline: UnreadWriteBaseline,+): UnreadWriteOwner => {+ const state = getReadWriteState(queryClient);+ const owners = (state.unreadOwners ??= new Map());+ const chains = (state.unreadChains ??= new Map());+ const chain = owners.get(conversationId)?.chain ??+ chains.get(conversationId) ?? {+ baseline,+ latestToken: 0,+ pending: 0,+ accepted: false,+ latestFailureSettled: false,+ };+ const token = claimReadWrite(queryClient, conversationId);+ chain.latestToken = token;+ chain.pending += 1;+ chains.set(conversationId, chain);+ const owner = { token, chain };+ owners.set(conversationId, owner);+ return owner;+};++const ownsUnreadWrite = (+ queryClient: QueryClient,+ conversationId: string,+ token: number | undefined,+): boolean =>+ token !== undefined &&+ getReadWriteState(queryClient).unreadOwners?.get(conversationId)?.token === token;++const releaseUnreadWrite = (+ queryClient: QueryClient,+ conversationId: string,+ token: number | undefined,+): void => {+ if (ownsUnreadWrite(queryClient, conversationId, token)) {+ getReadWriteState(queryClient).unreadOwners?.delete(conversationId);+ }+};++const reassertAcceptedUnread = (+ queryClient: QueryClient,+ conversationId: string,+ chain: UnreadWriteChain | undefined,+ data: t.TMarkConversationUnreadResponse,+): void => {+ if (!chain || !isLatestReadWrite(queryClient, conversationId, chain.latestToken)) {+ return;+ }+ const cached = findConvoInAllQueries(queryClient, conversationId);+ if (!cached || cached.lastSeenAt !== chain.baseline.lastSeenAt) {+ return;+ }+ const serverResponseAt = data.lastResponseAt;+ if (+ cached.lastResponseAt != null &&+ serverResponseAt != null &&+ cached.lastResponseAt > serverResponseAt+ ) {+ return;+ }+ updateConvoInAllQueries(queryClient, conversationId, (convo) => ({+ ...convo,+ lastResponseAt: serverResponseAt ?? convo.lastResponseAt,+ lastResponseMessageId:+ serverResponseAt == null ? convo.lastResponseMessageId : resolveReplyIdentity(convo, data),+ lastResponseIsManual:+ serverResponseAt == null ? convo.lastResponseIsManual : data.lastResponseIsManual,+ lastSeenAt: undefined,+ }));+};++/**+ * Flags a conversation as unread again.+ *+ * Optimistically mirrors what the server does: the catch-up is cleared, and a conversation+ * with no reply yet gets `lastResponseAt` stamped so the flag itself lights the dot.+ */+export const useMarkConversationUnreadMutation = (): UseMutationResult<+ t.TMarkConversationUnreadResponse,+ unknown,+ t.TMarkConversationUnreadRequest,+ unknown+> => {+ const queryClient = useQueryClient();++ return useMutation(+ [MutationKeys.convoUnread],+ (payload: t.TMarkConversationUnreadRequest) =>+ supersededReadWrites.delete(payload)+ ? Promise.resolve({ modified: false })+ : dataService.markConversationUnread(payload),+ {+ onMutate: async (vars) => {+ const observed = findConvoInAllQueries(queryClient, vars.conversationId);+ const owner = claimUnreadWrite(queryClient, vars.conversationId, {+ lastResponseAt: observed?.lastResponseAt,+ lastResponseMessageId: observed?.lastResponseMessageId,+ lastResponseIsManual: observed?.lastResponseIsManual,+ lastSeenAt: observed?.lastSeenAt,+ });+ const interrupted = await cancelConvoReadFetches(queryClient, vars.conversationId);+ const baseline = {+ chain: owner.chain,+ lastResponseAt: owner.chain.baseline.lastResponseAt,+ lastResponseMessageId: owner.chain.baseline.lastResponseMessageId,+ lastResponseIsManual: owner.chain.baseline.lastResponseIsManual,+ lastSeenAt: owner.chain.baseline.lastSeenAt,+ token: owner.token,+ interrupted,+ };+ if (abandonWhenSuperseded(queryClient, vars, owner.token)) {+ return { ...baseline, optimisticResponseAt: undefined, superseded: true };+ }+ const previous = findConvoInAllQueries(queryClient, vars.conversationId);+ /* The marker the optimistic pass writes, remembered so a rollback can tell its own+ state apart from a newer reply that arrived while the request was open. A never-+ replied conversation gets an explicit manual marker; replied conversations retain+ their real stamp but are still made unread. */+ const optimisticResponseAt: string | undefined =+ previous?.lastResponseAt ?? previous?.updatedAt ?? new Date().toISOString();+ const context = { ...baseline, optimisticResponseAt, superseded: false };+ updateConvoInAllQueries(queryClient, vars.conversationId, (convo) => ({+ ...convo,+ lastResponseAt: convo.lastResponseAt ?? optimisticResponseAt,+ lastResponseMessageId:+ convo.lastResponseAt == null || convo.lastResponseIsManual === true+ ? undefined+ : convo.lastResponseMessageId,+ lastResponseIsManual:+ convo.lastResponseAt == null || convo.lastResponseIsManual === true ? true : undefined,+ lastSeenAt: undefined,+ }));+ return context;+ },+ onSuccess: (data, vars, context) => {+ /* A superseded call never reached the server: the mutation function resolves a+ synthetic `modified: false` for it, which is not a no-match and must not be read+ as one. */+ if (context?.superseded === true) {+ return;+ }+ /* Nothing matched: the conversation is gone, deleted on another device or between the+ access check and the write. The server's second update is owner-scoped and returns+ the row even when it changes nothing, so no match proves the row no longer exists+ rather than that nothing needed doing. That holds whoever owns the latest intent, so+ it is settled before ownership is consulted: a non-owning call is exactly the one whose+ answer would otherwise be dropped, leaving a conversation that does not exist in the+ sidebar and the badge. An accepted unread cannot bring it back, because the cache+ writers only update rows they still hold. */+ if (!data.modified) {+ if (context?.chain && !context.chain.accepted) {+ context.chain.latestFailureSettled = true;+ }+ removeConvoFromAllQueries(queryClient, vars.conversationId);+ queryClient.removeQueries([QueryKeys.conversation, vars.conversationId]);+ clearDeletedConversationMessagesCache(queryClient, vars.conversationId);+ return;+ }+ if (data.modified && context?.chain) {+ context.chain.accepted = true;+ }+ const owns = ownsUnreadWrite(queryClient, vars.conversationId, context?.token);+ if (!owns) {+ if (data.modified && context?.chain?.latestFailureSettled) {+ reassertAcceptedUnread(queryClient, vars.conversationId, context.chain, data);+ }+ return;+ }+ const cached = findConvoInAllQueries(queryClient, vars.conversationId);+ /* Two things settle here. A conversation with no reply yet gets its marker stamped+ server-side and the optimistic guess above is necessarily earlier, so leaving the+ guess cached would send it to `/seen`, where the observed-reply filter cannot match+ the real stamp. And the catch-up has to be reasserted, not just left alone: a list+ refetch already in flight can have read the old `lastSeenAt` and commit after the+ optimistic clear, which would quietly take the dot back off a conversation the+ server did mark unread.+ While the cache still holds what this pass wrote, the server's answer wins: for a+ conversation with no reply the optimistic marker is a client guess, and replacing it+ is the whole point of returning one. Anything else in the cache came from a reply+ that landed while the request was open, which is newer than the server read on the+ way in and has to survive. */+ /* A catch-up in the cache that is not the one this mutation cleared is an+ acknowledgement this pass did not make, and the cache alone cannot say which write+ the server settled on: the read may have been accepted after the unread write, or+ before it, in which case the server holds the conversation unread while this tab+ shows it read. Neither guess is safe, so the row is refetched and the server+ decides. */+ if (+ !isLatestReadWrite(queryClient, vars.conversationId, context?.token) ||+ (cached?.lastSeenAt !== undefined && cached.lastSeenAt !== context?.lastSeenAt)+ ) {+ refreshConvoReadCaches(queryClient, vars.conversationId);+ return;+ }+ const cachedResponseAt = cached?.lastResponseAt;+ const serverResponseAt = data.lastResponseAt;+ const holdsOwnWrite =+ cached?.lastSeenAt === undefined && cachedResponseAt === context?.optimisticResponseAt;+ const keepsCached =+ !holdsOwnWrite &&+ cachedResponseAt != null &&+ (serverResponseAt == null || cachedResponseAt > serverResponseAt);+ const lastResponseAt = keepsCached+ ? cachedResponseAt+ : (serverResponseAt ?? cachedResponseAt);+ const lastResponseIsManual = keepsCached+ ? cached?.lastResponseIsManual+ : data.lastResponseIsManual;+ const lastResponseMessageId =+ keepsCached || serverResponseAt == null+ ? cached?.lastResponseMessageId+ : resolveReplyIdentity(cached, data);+ if (+ cached?.lastSeenAt === undefined &&+ cachedResponseAt === lastResponseAt &&+ cached?.lastResponseIsManual === lastResponseIsManual &&+ cached?.lastResponseMessageId === lastResponseMessageId+ ) {+ return;+ }+ updateConvoInAllQueries(queryClient, vars.conversationId, (convo) => ({+ ...convo,+ lastResponseAt,+ lastResponseMessageId,+ lastResponseIsManual,+ lastSeenAt: undefined,+ }));+ },+ onError: (_error, vars, context) => {+ if (context?.superseded === true) {+ return;+ }+ /* A later click owns the row once it has captured this pass's optimistic state as its+ own baseline: rolling back here would restore a catch-up the newer request is about+ to be judged against, and its settlement would then read the restored value as a+ newer acknowledgement and leave the row seen although the server marked it unread. */+ if (!ownsUnreadWrite(queryClient, vars.conversationId, context?.token)) {+ return;+ }+ if (context?.chain?.accepted) {+ return;+ }+ if (context?.chain) {+ context.chain.latestFailureSettled = true;+ }+ /* Only while the cache still holds what this mutation wrote. A newer reply can be+ merged by the watcher or the SSE path while the request is open, and restoring the+ pre-mutation stamps over it would make that genuinely new reply read as seen with+ its completion signal already spent. */+ const cached = findConvoInAllQueries(queryClient, vars.conversationId);+ const isOwnWrite =+ cached?.lastSeenAt === undefined &&+ cached?.lastResponseAt === context?.optimisticResponseAt;+ if (!isOwnWrite) {+ return;+ }+ updateConvoInAllQueries(queryClient, vars.conversationId, (convo) => ({+ ...convo,+ lastResponseAt: context?.lastResponseAt,+ lastResponseMessageId: resolveReplyIdentity(convo, context),+ lastResponseIsManual: context?.lastResponseIsManual,+ lastSeenAt: context?.lastSeenAt,+ }));+ },+ onSettled: (_data, _error, vars, context) => {+ releaseUnreadWrite(queryClient, vars.conversationId, context?.token);+ const chain = context?.chain;+ if (chain) {+ chain.pending -= 1;+ const chains = getReadWriteState(queryClient).unreadChains;+ if (chain.pending === 0 && chains?.get(vars.conversationId) === chain) {+ chains.delete(vars.conversationId);+ releaseReadWrite(queryClient, vars.conversationId, chain.latestToken);+ }+ }+ restartInterruptedReads(queryClient, context?.interrupted);+ },+ },+ );+};+/*** The sidebar badge reads `isShared` off the conversation list, which the server derives* from a different collection. Share mutations therefore have to flip it locally, or thediff --git a/client/src/hooks/Config/useAppStartup.ts b/client/src/hooks/Config/useAppStartup.tsindex 15392dce65..8027a09903 100644--- a/client/src/hooks/Config/useAppStartup.ts+++ b/client/src/hooks/Config/useAppStartup.ts@@ -14,6 +14,7 @@ import { cleanupTimestampedStorage } from '~/utils/timestamps';import useSpeechSettingsInit from './useSpeechSettingsInit';import { useHasAccess, useCatalogReady } from '~/hooks';import { useMCPServersQuery } from '~/data-provider';+import { setDocumentTitle } from '~/utils';import store from '~/store';export default function useAppStartup({@@ -46,7 +47,7 @@ export default function useAppStartup({if (!appTitle) {return;}- document.title = appTitle;+ setDocumentTitle(appTitle, true);localStorage.setItem(LocalStorageKeys.APP_TITLE, appTitle);}, [startupConfig]);diff --git a/client/src/hooks/Conversations/__tests__/useConversationSeen.spec.tsx b/client/src/hooks/Conversations/__tests__/useConversationSeen.spec.tsxnew file mode 100644index 0000000000..458555ee73--- /dev/null+++ b/client/src/hooks/Conversations/__tests__/useConversationSeen.spec.tsx@@ -0,0 +1,840 @@+import React from 'react';+import { MemoryRouter } from 'react-router-dom';+import { act, renderHook, waitFor } from '@testing-library/react';+import { QueryKeys, tMessageSchema } from 'librechat-data-provider';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { TMessage } from 'librechat-data-provider';+import {+ markLocallyCommittedReply,+ markServerFetchedReply,+ updateConvoInAllQueries,+} from '~/utils';+import { useGetMessagesByConvoId } from '~/data-provider/Messages/queries';+import { suppressFocusAcknowledgement } from '../notificationNavigation';+import useConversationSeen from '../useConversationSeen';++const mockMarkSeen = jest.fn();+const mockGetMessages = jest.fn();+jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ getMessagesByConvoId: (...args: string[]) => mockGetMessages(...args),+ },+ };+});+jest.mock('~/data-provider', () => ({+ ...jest.requireActual('~/data-provider'),+ useMarkConversationSeenMutation: () => ({ mutate: mockMarkSeen }),+}));++const CONVO_ID = 'convo-seen';+const OTHER_CONVO_ID = 'convo-other';+const RESPONDED_AT = '2026-08-16T10:00:00.000Z';+const RESPONDED_LATER_AT = '2026-08-16T10:05:00.000Z';++type ConvoFixture = {+ lastResponseAt?: string;+ lastResponseMessageId?: string;+ lastResponseIsManual?: boolean;+ lastSeenAt?: string;+};++type SeededConvo = {+ conversationId: string;+ title: string;+ lastResponseAt?: string;+ lastResponseMessageId?: string;+ lastResponseIsManual?: boolean;+ lastSeenAt?: string;+};++type SeenProps = { id: string; submitting: boolean };++function createClient() {+ return new QueryClient({ defaultOptions: { queries: { retry: false } } });+}++function seedUnseen(+ queryClient: QueryClient,+ lastResponseAt = RESPONDED_AT,+ conversationId = CONVO_ID,+) {+ queryClient.setQueryData([QueryKeys.allConversations, { isArchived: false }], {+ pages: [+ {+ conversations: [+ {+ conversationId,+ title: 'Test',+ lastResponseAt,+ lastResponseMessageId: 'server-reply',+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });+}++function setup(+ fixture: ConvoFixture | null,+ initialProps: SeenProps = { id: CONVO_ID, submitting: false },+ measureNearBottom?: () => boolean | null,+ isResponseRendered?: (messageId: string) => boolean,+) {+ const queryClient = createClient();+ if (fixture !== null) {+ const conversations: SeededConvo[] = [+ {+ conversationId: initialProps.id,+ title: 'Test',+ lastResponseAt: fixture.lastResponseAt,+ lastResponseMessageId: fixture.lastResponseMessageId ?? 'server-reply',+ lastResponseIsManual: fixture.lastResponseIsManual,+ lastSeenAt: fixture.lastSeenAt,+ },+ ];+ if (initialProps.id !== OTHER_CONVO_ID) {+ conversations.push({+ conversationId: OTHER_CONVO_ID,+ title: 'Other',+ lastResponseAt: RESPONDED_AT,+ });+ }+ queryClient.setQueryData([QueryKeys.allConversations, { isArchived: false }], {+ pages: [{ conversations, nextCursor: null }],+ pageParams: [null],+ });+ }++ const renderedResponseId = fixture?.lastResponseMessageId ?? 'server-reply';+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <div id={renderedResponseId}>+ <div data-testid="message-body">{renderedResponseId}</div>+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ </div>+ );++ const view = renderHook(+ ({ id, submitting }: SeenProps) =>+ useConversationSeen(id, submitting, measureNearBottom, isResponseRendered),+ {+ initialProps,+ wrapper,+ },+ );++ return { ...view, queryClient };+}++async function renderMessages(queryClient: QueryClient, conversationId = CONVO_ID) {+ await act(async () => {+ await queryClient.fetchQuery([QueryKeys.messages, conversationId], async () => []);+ });+}++describe('useConversationSeen', () => {+ let hasFocus: jest.SpyInstance;++ beforeEach(() => {+ mockMarkSeen.mockClear();+ hasFocus = jest.spyOn(document, 'hasFocus').mockReturnValue(true);+ });++ afterEach(() => {+ hasFocus.mockRestore();+ });++ it('records the conversation as seen once the newest message is reached', async () => {+ const { result, queryClient } = setup({ lastResponseAt: RESPONDED_AT });+ mockMarkSeen.mockClear();++ act(() => result.current(true));+ expect(mockMarkSeen).not.toHaveBeenCalled();++ await renderMessages(queryClient);+ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ });+ it.each([false, true])(+ 'reuses a cold fetch only for the reply known when it started (newer reply: %s)',+ async (newerReply) => {+ const queryClient = createClient();+ seedUnseen(queryClient);+ const history = [+ tMessageSchema.parse({+ messageId: 'server-reply',+ conversationId: CONVO_ID,+ parentMessageId: 'server-user',+ sender: 'Assistant',+ text: 'Server reply',+ isCreatedByUser: false,+ }),+ ];+ let resolveInitial!: (messages: typeof history) => void;+ let resolveLatest!: (messages: typeof history) => void;+ const initial = new Promise<typeof history>((resolve) => {+ resolveInitial = resolve;+ });+ const latest = new Promise<typeof history>((resolve) => {+ resolveLatest = resolve;+ });+ const getMessages = mockGetMessages+ .mockReset()+ .mockRejectedValue(new Error('unexpected history request'))+ .mockReturnValueOnce(initial)+ .mockReturnValueOnce(latest);+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <MemoryRouter initialEntries={[`/c/${CONVO_ID}`]}>+ <div id="server-reply">+ <div data-testid="message-body">{history[0].text}</div>+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ </div>+ </MemoryRouter>+ );+ try {+ const messages = renderHook(() => useGetMessagesByConvoId(CONVO_ID), { wrapper });+ await waitFor(() => expect(getMessages).toHaveBeenCalledTimes(1));+ await act(async () => {+ if (newerReply) {+ seedUnseen(queryClient, RESPONDED_LATER_AT);+ }+ resolveInitial(history);+ });+ await waitFor(() => expect(messages.result.current.isSuccess).toBe(true));++ const seen = renderHook(() => useConversationSeen(CONVO_ID, false), { wrapper });+ act(() => seen.result.current(true));+ if (newerReply) {+ await waitFor(() => expect(getMessages).toHaveBeenCalledTimes(2));+ expect(mockMarkSeen).not.toHaveBeenCalled();+ await act(async () => {+ resolveLatest([...history, { ...history[0], messageId: 'newer-reply' }]);+ });+ }+ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: newerReply ? RESPONDED_LATER_AT : RESPONDED_AT,+ }),+ );+ expect(getMessages).toHaveBeenCalledTimes(newerReply ? 2 : 1);+ } finally {+ getMessages.mockReset();+ }+ },+ );++ it('acknowledges a locally committed final without refetching message history', async () => {+ const { result, queryClient } = setup({ lastResponseAt: RESPONDED_AT });+ queryClient.setQueryData([QueryKeys.messages, CONVO_ID], [{ messageId: 'final-reply' }]);+ markLocallyCommittedReply(queryClient, CONVO_ID, RESPONDED_AT);+ const invalidateMessages = jest.spyOn(queryClient, 'invalidateQueries');++ act(() => result.current(true));++ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ expect(invalidateMessages).not.toHaveBeenCalled();+ });+ it('does not acknowledge a fetched hidden sibling until that response branch is visible', async () => {+ let responseVisible = false;+ const { result, queryClient } = setup(+ { lastResponseAt: RESPONDED_AT, lastResponseMessageId: 'hidden-reply' },+ { id: CONVO_ID, submitting: false },+ undefined,+ () => responseVisible,+ );+ const hiddenReply = tMessageSchema.parse({+ messageId: 'hidden-reply',+ conversationId: CONVO_ID,+ parentMessageId: 'hidden-user',+ sender: 'Assistant',+ text: 'Hidden reply',+ isCreatedByUser: false,+ }) as TMessage;+ const stored = queryClient.setQueryData([QueryKeys.messages, CONVO_ID], [hiddenReply]);+ markServerFetchedReply(queryClient, CONVO_ID, RESPONDED_AT, stored!);++ act(() => result.current(true));+ expect(mockMarkSeen).not.toHaveBeenCalled();++ responseVisible = true;+ act(() => result.current(true));+ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ });++ it('acknowledges a synthetic manual marker from the settled route without refetching history', async () => {+ const queryClient = createClient();+ seedUnseen(queryClient);+ updateConvoInAllQueries(queryClient, CONVO_ID, (convo) => ({+ ...convo,+ lastResponseIsManual: true,+ lastResponseMessageId: undefined,+ }));+ const getHistory = jest.fn(async () => []);+ await queryClient.fetchQuery({+ queryKey: [QueryKeys.messages, CONVO_ID],+ queryFn: getHistory,+ });+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ const invalidateMessages = jest.spyOn(queryClient, 'invalidateQueries');+ const { result } = renderHook(() => useConversationSeen(CONVO_ID, false), { wrapper });+ act(() => result.current(true));+ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ expect(invalidateMessages).not.toHaveBeenCalled();+ expect(getHistory).toHaveBeenCalledTimes(1);+ });++ it('acknowledges a warm synthetic manual marker without a metadata refetch', async () => {+ const { result, queryClient } = setup({+ lastResponseAt: RESPONDED_AT,+ lastResponseIsManual: true,+ });+ queryClient.setQueryData([QueryKeys.messages, CONVO_ID], [{ messageId: 'existing-reply' }]);+ const invalidateMessages = jest.spyOn(queryClient, 'invalidateQueries');++ act(() => result.current(true));++ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ expect(invalidateMessages).not.toHaveBeenCalled();+ });++ it('acknowledges a real reply stamped before reply identity existed', async () => {+ /* A row written by an older server carries no `lastResponseMessageId`; requiring one would+ leave its dot unclearable for the life of the conversation. */+ const queryClient = createClient();+ seedUnseen(queryClient);+ updateConvoInAllQueries(queryClient, CONVO_ID, (convo) => ({+ ...convo,+ lastResponseMessageId: undefined,+ }));+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ const { result } = renderHook(() => useConversationSeen(CONVO_ID, false), { wrapper });+ await renderMessages(queryClient);++ act(() => result.current(true));++ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ });++ it('sends nothing while the user is scrolled away from the newest message', () => {+ const { result } = setup({ lastResponseAt: RESPONDED_AT });+ mockMarkSeen.mockClear();++ act(() => result.current(false));++ expect(mockMarkSeen).not.toHaveBeenCalled();+ });++ it('sends nothing when the tab is not focused', () => {+ hasFocus.mockReturnValue(false);+ const { result } = setup({ lastResponseAt: RESPONDED_AT });+ mockMarkSeen.mockClear();++ act(() => result.current(true));++ expect(mockMarkSeen).not.toHaveBeenCalled();+ });++ it('sends nothing when the conversation is already caught up', () => {+ const { result } = setup({+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: '2026-08-16T11:00:00.000Z',+ });+ mockMarkSeen.mockClear();++ act(() => result.current(true));++ /* The cost guard: re-reading an already-seen conversation must not issue a write. */+ expect(mockMarkSeen).not.toHaveBeenCalled();+ });++ it('sends nothing for a conversation that has never been replied to', () => {+ const { result } = setup({});+ mockMarkSeen.mockClear();++ act(() => result.current(true));++ expect(mockMarkSeen).not.toHaveBeenCalled();+ });++ it('marks seen when a reply lands while the user sits at the newest message', async () => {+ /* Mirrors the real order: the user is at the bottom of a conversation with no reply yet,+ the run finishes and stamps the list cache, then the submission flips. The conversation+ the user is actively watching must not sprout a dot, and the reply is acknowledged+ exactly once rather than again on the flip. */+ const { result, rerender, queryClient } = setup(+ {},+ {+ id: CONVO_ID,+ submitting: true,+ },+ );++ act(() => result.current(true));+ expect(mockMarkSeen).not.toHaveBeenCalled();++ act(() => {+ seedUnseen(queryClient);+ });+ rerender({ id: CONVO_ID, submitting: false });+ expect(mockMarkSeen).not.toHaveBeenCalled();++ await renderMessages(queryClient);+ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ expect(mockMarkSeen).toHaveBeenCalledTimes(1);+ });++ it('marks seen once the list cache loads with the conversation still unread', async () => {+ /* Direct-URL open: the initial intersection fires before the list query resolves,+ so nothing marks seen until both the message tree and list cache report the conversation. */+ const { result, queryClient } = setup(null);++ act(() => result.current(true));+ mockMarkSeen.mockClear();++ act(() => {+ seedUnseen(queryClient);+ });+ expect(mockMarkSeen).not.toHaveBeenCalled();++ await renderMessages(queryClient);+ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ });++ it('refreshes idle messages before acknowledging a list-only remote reply', async () => {+ /* A focused list refetch can discover a reply while the active messages query still reports+ successful old data. The old end marker must not be enough to acknowledge that stamp. */+ const { result, queryClient } = setup({+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: RESPONDED_AT,+ });+ queryClient.setQueryData([QueryKeys.messages, CONVO_ID], [{ messageId: 'old-reply' }]);+ act(() => result.current(true));+ mockMarkSeen.mockClear();++ const invalidateMessages = jest.spyOn(queryClient, 'invalidateQueries');+ act(() => {+ seedUnseen(queryClient, RESPONDED_LATER_AT);+ });++ expect(mockMarkSeen).not.toHaveBeenCalled();+ expect(invalidateMessages).toHaveBeenCalledWith([QueryKeys.messages, CONVO_ID]);++ await act(async () => {+ await queryClient.fetchQuery([QueryKeys.messages, CONVO_ID], async () => [+ { messageId: 'new-reply' },+ ]);+ });++ /* The successful fetch is not enough by itself: acknowledgement waits for the post-render+ measurement scheduled by the messages cache event. */+ expect(mockMarkSeen).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_LATER_AT,+ }),+ );+ expect(invalidateMessages).toHaveBeenCalledTimes(1);++ /* Repeated list notifications for the same stamp do not start another messages request. */+ act(() => {+ seedUnseen(queryClient, RESPONDED_LATER_AT);+ });+ expect(invalidateMessages).toHaveBeenCalledTimes(1);+ });++ it('ignores a successful messages event for another conversation', async () => {+ const { result, queryClient } = setup({+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: RESPONDED_AT,+ });+ queryClient.setQueryData([QueryKeys.messages, CONVO_ID], [{ messageId: 'old-reply' }]);+ act(() => result.current(true));+ mockMarkSeen.mockClear();++ act(() => {+ seedUnseen(queryClient, RESPONDED_LATER_AT);+ });++ await act(async () => {+ await queryClient.fetchQuery([QueryKeys.messages, OTHER_CONVO_ID], async () => [+ { messageId: 'other-reply' },+ ]);+ });++ expect(mockMarkSeen).not.toHaveBeenCalled();+ });++ it('keeps a list-only reply unseen when its messages refresh fails', async () => {+ const { result, queryClient } = setup({+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: RESPONDED_AT,+ });+ queryClient.setQueryData([QueryKeys.messages, CONVO_ID], [{ messageId: 'old-reply' }]);+ act(() => result.current(true));+ mockMarkSeen.mockClear();++ const invalidateMessages = jest.spyOn(queryClient, 'invalidateQueries');+ act(() => {+ seedUnseen(queryClient, RESPONDED_LATER_AT);+ });++ await act(async () => {+ await expect(+ queryClient.fetchQuery([QueryKeys.messages, CONVO_ID], () =>+ Promise.reject(new Error('network down')),+ ),+ ).rejects.toThrow('network down');+ });++ expect(invalidateMessages).toHaveBeenCalledTimes(1);+ expect(mockMarkSeen).not.toHaveBeenCalled();+ act(() => {+ seedUnseen(queryClient, RESPONDED_LATER_AT);+ });+ expect(invalidateMessages).toHaveBeenCalledTimes(1);+ });++ it('waits out a messages revalidation before acknowledging', async () => {+ /* A warm-cache open renders the old tree and reports its bottom while the messages query+ refetches in the background; acknowledging then would clear the indicator for a reply+ that has not rendered. The fetch settling is itself a cache event, so the reply is+ credited once it has actually arrived. */+ const { result, queryClient } = setup({ lastResponseAt: RESPONDED_AT });+ mockMarkSeen.mockClear();++ let resolveFetch!: (messages: unknown[]) => void;+ const fetching = queryClient.prefetchQuery(+ [QueryKeys.messages, CONVO_ID],+ () =>+ new Promise<unknown[]>((resolve) => {+ resolveFetch = resolve;+ }),+ );++ act(() => result.current(true));+ expect(mockMarkSeen).not.toHaveBeenCalled();++ await act(async () => {+ resolveFetch([]);+ await fetching;+ });++ /* The re-check is deferred past the commit, so it lands a couple of frames later. */+ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ });++ it('withholds the acknowledgement when the messages revalidation failed', async () => {+ /* A failed refetch returns the query to `idle` while the stale tree stays on screen, so+ waiting only for the fetch to stop would credit a reply that never loaded. */+ const { result, queryClient } = setup({ lastResponseAt: RESPONDED_AT });+ mockMarkSeen.mockClear();++ await act(async () => {+ await queryClient+ .prefetchQuery([QueryKeys.messages, CONVO_ID], () =>+ Promise.reject(new Error('network down')),+ )+ .catch(() => undefined);+ });++ expect(queryClient.getQueryState([QueryKeys.messages, CONVO_ID])?.status).toBe('error');++ act(() => result.current(true));++ expect(mockMarkSeen).not.toHaveBeenCalled();+ });++ it('re-measures the committed tree instead of trusting the old bottom report', async () => {+ /* The revalidated reply can extend past the viewport, and the fetch settles before React+ commits it: the stale near-bottom flag belongs to the old tree and must not acknowledge+ a reply whose end the user has not reached. */+ const measure = jest.fn<boolean | null, []>(() => false);+ const { result, queryClient } = setup(+ { lastResponseAt: RESPONDED_AT },+ { id: CONVO_ID, submitting: false },+ measure,+ );+ mockMarkSeen.mockClear();++ let resolveFetch!: (messages: unknown[]) => void;+ const fetching = queryClient.prefetchQuery(+ [QueryKeys.messages, CONVO_ID],+ () =>+ new Promise<unknown[]>((resolve) => {+ resolveFetch = resolve;+ }),+ );++ act(() => result.current(true));++ await act(async () => {+ resolveFetch([]);+ await fetching;+ });++ await waitFor(() => expect(measure).toHaveBeenCalled());+ expect(mockMarkSeen).not.toHaveBeenCalled();+ });++ it('does not re-send the same acknowledgement when a failed write re-arms the cache', async () => {+ /* A rejected `/seen` rolls the row back to unseen, and that rollback is itself a cache+ event this hook listens to. Without a guard an offline tab would spin requests for as+ long as the network keeps refusing them. */+ const { result, queryClient } = setup({ lastResponseAt: RESPONDED_AT });++ act(() => result.current(true));+ await renderMessages(queryClient);+ await waitFor(() => expect(mockMarkSeen).toHaveBeenCalledTimes(1));+ mockMarkSeen.mockClear();++ act(() => {+ seedUnseen(queryClient);+ });++ expect(mockMarkSeen).not.toHaveBeenCalled();+ });++ it('acknowledges again once a genuinely newer reply arrives', async () => {+ const { result, queryClient } = setup({ lastResponseAt: RESPONDED_AT });++ act(() => result.current(true));+ await renderMessages(queryClient);+ await waitFor(() => expect(mockMarkSeen).toHaveBeenCalledTimes(1));+ mockMarkSeen.mockClear();++ act(() => {+ seedUnseen(queryClient, RESPONDED_LATER_AT);+ });+ expect(mockMarkSeen).not.toHaveBeenCalled();++ await renderMessages(queryClient);+ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_LATER_AT,+ }),+ );+ });++ it('acknowledges once the point query for a directly opened conversation resolves', async () => {+ /* An old conversation opened by URL can be in neither list; the initial intersection and+ point query can both arrive before the messages query, so acknowledgement waits for the+ rendered tree. */+ const { result, queryClient } = setup(null);++ act(() => result.current(true));+ mockMarkSeen.mockClear();++ act(() => {+ queryClient.setQueryData([QueryKeys.conversation, CONVO_ID], {+ conversationId: CONVO_ID,+ title: 'Test',+ lastResponseAt: RESPONDED_AT,+ lastResponseMessageId: 'server-reply',+ });+ });++ expect(mockMarkSeen).not.toHaveBeenCalled();+ await renderMessages(queryClient);+ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ });++ it('re-arms a failed acknowledgement when the route leaves and returns', async () => {+ /* The hook outlives the route, so without this a write that failed here would stay+ suppressed until the window happened to blur and refocus. */+ const { result, rerender, queryClient } = setup({ lastResponseAt: RESPONDED_AT });++ act(() => result.current(true));+ await renderMessages(queryClient);+ await waitFor(() => expect(mockMarkSeen).toHaveBeenCalledTimes(1));+ mockMarkSeen.mockClear();++ rerender({ id: OTHER_CONVO_ID, submitting: false });+ rerender({ id: CONVO_ID, submitting: false });+ act(() => result.current(true));+ await renderMessages(queryClient);++ await waitFor(() =>+ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ }),+ );+ });++ it('ignores the focus a notification click raises on its way elsewhere', async () => {+ /* The click is navigation to another conversation; the one still open behind it was never+ read and must keep its indicator. */+ const { result, queryClient } = setup({ lastResponseAt: RESPONDED_AT });++ act(() => result.current(true));+ await renderMessages(queryClient);+ await waitFor(() => expect(mockMarkSeen).toHaveBeenCalledTimes(1));+ mockMarkSeen.mockClear();++ act(() => {+ hasFocus.mockReturnValue(false);+ suppressFocusAcknowledgement();+ hasFocus.mockReturnValue(true);+ window.dispatchEvent(new Event('focus'));+ });++ expect(mockMarkSeen).not.toHaveBeenCalled();+ });++ it('acknowledges on the next genuine focus after a suppressed one', async () => {+ const { result, queryClient } = setup({ lastResponseAt: RESPONDED_AT });++ act(() => result.current(true));+ await renderMessages(queryClient);+ await waitFor(() => expect(mockMarkSeen).toHaveBeenCalledTimes(1));+ mockMarkSeen.mockClear();++ act(() => {+ hasFocus.mockReturnValue(false);+ suppressFocusAcknowledgement();+ hasFocus.mockReturnValue(true);+ window.dispatchEvent(new Event('focus'));+ });+ act(() => {+ window.dispatchEvent(new Event('focus'));+ });++ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ });++ it('expires a suppression whose focus event never arrived', async () => {+ /* `window.focus()` is a request: a browser that leaves the window in the background raises+ no focus event, and an unbounded flag would then be spent on the next genuine focus,+ withholding that conversation's acknowledgement for no reason. */+ const { result, queryClient } = setup({ lastResponseAt: RESPONDED_AT });++ act(() => result.current(true));+ await renderMessages(queryClient);+ await waitFor(() => expect(mockMarkSeen).toHaveBeenCalledTimes(1));+ mockMarkSeen.mockClear();++ const now = jest.spyOn(Date, 'now');+ try {+ now.mockReturnValue(1_000);+ act(() => {+ hasFocus.mockReturnValue(false);+ suppressFocusAcknowledgement();+ });+ now.mockReturnValue(1_000 + 5_000);+ act(() => {+ hasFocus.mockReturnValue(true);+ window.dispatchEvent(new Event('focus'));+ });+ } finally {+ now.mockRestore();+ }++ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ });++ it('retries a failed acknowledgement when the user returns to the tab', async () => {+ const { result, queryClient } = setup({ lastResponseAt: RESPONDED_AT });++ act(() => result.current(true));+ await renderMessages(queryClient);+ await waitFor(() => expect(mockMarkSeen).toHaveBeenCalledTimes(1));+ mockMarkSeen.mockClear();++ act(() => {+ window.dispatchEvent(new Event('focus'));+ });++ expect(mockMarkSeen).toHaveBeenCalledWith({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ });++ it('does not carry the previous conversation’s scroll position into a new one', () => {+ const { result, rerender } = setup(+ { lastResponseAt: RESPONDED_AT },+ {+ id: CONVO_ID,+ submitting: false,+ },+ );++ act(() => result.current(true));+ mockMarkSeen.mockClear();++ /* Switching conversations recreates the observer; until it reports, the new+ conversation's position is unknown and must not inherit "near bottom". */+ rerender({ id: OTHER_CONVO_ID, submitting: false });++ expect(mockMarkSeen).not.toHaveBeenCalledWith(+ expect.objectContaining({ conversationId: OTHER_CONVO_ID }),+ );+ });+});diff --git a/client/src/hooks/Conversations/__tests__/useReplyAlerts.spec.tsx b/client/src/hooks/Conversations/__tests__/useReplyAlerts.spec.tsxnew file mode 100644index 0000000000..38ac2b5075--- /dev/null+++ b/client/src/hooks/Conversations/__tests__/useReplyAlerts.spec.tsx@@ -0,0 +1,741 @@+import React from 'react';+import { RecoilRoot } from 'recoil';+import { QueryKeys } from 'librechat-data-provider';+import { MemoryRouter, useLocation } from 'react-router-dom';+import { Provider as JotaiProvider, createStore } from 'jotai';+import { renderHook, waitFor, act } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { ReplyReadState, UnseenConversation } from '../useUnseenConversations';+import { replyNotificationsAtom, replyNotificationSoundAtom } from '../replyNotificationSettings';+import useReplyAlerts, { requestReplyNotificationPermission } from '../useReplyAlerts';+import { consumeFocusSuppression } from '../notificationNavigation';+import useUnseenConversations from '../useUnseenConversations';+import { startupConfigKey } from '~/data-provider';+import { applyServerReplyStamp } from '~/utils';++/* The hooks barrel is circular with ~/data-provider; mocking it wholesale keeps the+ suite off that cycle while still exercising the hook's real diff/notify logic. */+jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++/* The alert capabilities stay off until the deployment has answered, so every render starts+ from a loaded startup config that restricts none of them. */+const withLoadedConfig = (client: QueryClient): QueryClient => {+ client.setQueryData(startupConfigKey(false), { interface: {} });+ return client;+};++const permissionRequest = jest.fn();++class FakeNotification {+ static permission: NotificationPermission = 'granted';+ static requestPermission = permissionRequest;+ onclick: (() => void) | null = null;+ close = jest.fn();++ constructor(+ public title: string,+ public options?: { body?: string; tag?: string },+ ) {+ createdNotifications.push(this);+ }+}++const createdNotifications: FakeNotification[] = [];++const createOscillator = jest.fn();+const createGain = jest.fn();+let audioState: AudioContextState = 'running';+const resumeAudio = jest.fn().mockResolvedValue(undefined);++class FakeAudioContext {+ get state() {+ return audioState;+ }++ currentTime = 0;+ destination = {};+ resume = resumeAudio;+ createOscillator = createOscillator;+ createGain = createGain;+}++function stubOscillator() {+ createOscillator.mockImplementation(() => ({+ type: '',+ frequency: { value: 0 },+ connect: jest.fn(() => ({ connect: jest.fn() })),+ start: jest.fn(),+ stop: jest.fn(),+ }));+ createGain.mockImplementation(() => ({+ gain: {+ setValueAtTime: jest.fn(),+ exponentialRampToValueAtTime: jest.fn(),+ },+ connect: jest.fn(),+ }));+}++type Toggles = { notifications?: boolean; sound?: boolean };++const row = (+ conversationId: string,+ title: string,+ lastResponseAt = '2026-08-16T10:00:00.000Z',+ flagged = false,+): UnseenConversation => ({ conversationId, title, lastResponseAt, flagged });++/** Mirrors the hook's real feed: every unseen row's stamp is in the baseline, and seen+ * conversations contribute stamps without appearing in the unseen set. */+const stateOf = (+ unseen: UnseenConversation[] | null,+ seenStamps: Array<[string, string]> = [],+ arrivalStamps = unseen?.map((c): [string, string] => [c.conversationId, c.lastResponseAt]) ?? [],+): ReplyReadState | null =>+ unseen === null+ ? null+ : {+ unseen,+ arrivalStamps,+ stamps: [+ ...seenStamps,+ ...unseen.map((c): [string, string] => [c.conversationId, c.lastResponseAt]),+ ],+ };++function setup(+ toggles: Toggles = {},+ initialState: ReplyReadState | null = stateOf([]),+ initialRoute = '/',+) {+ const { notifications = false, sound = false } = toggles;+ const pathnameRef = { current: initialRoute };++ const Probe = () => {+ const location = useLocation();+ pathnameRef.current = location.pathname;+ return null;+ };++ const settings = createStore();+ settings.set(replyNotificationsAtom, notifications);+ settings.set(replyNotificationSoundAtom, sound);++ const configClient = withLoadedConfig(new QueryClient());+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <RecoilRoot>+ <QueryClientProvider client={configClient}>+ <JotaiProvider store={settings}>+ <MemoryRouter initialEntries={[initialRoute]}>+ {children}+ <Probe />+ </MemoryRouter>+ </JotaiProvider>+ </QueryClientProvider>+ </RecoilRoot>+ );++ return {+ ...renderHook((state: ReplyReadState | null) => useReplyAlerts(state), {+ initialProps: initialState,+ wrapper,+ }),+ pathnameRef,+ };+}+function setupWithAggregate(toggles: Toggles = {}) {+ const { notifications = false, sound = false } = toggles;+ const settings = createStore();+ settings.set(replyNotificationsAtom, notifications);+ settings.set(replyNotificationSoundAtom, sound);++ const queryClient = withLoadedConfig(+ new QueryClient({ defaultOptions: { queries: { retry: false } } }),+ );+ queryClient.setQueryData([QueryKeys.allConversations, { isArchived: false }], {+ pages: [+ {+ conversations: [{ conversationId: 'user-only', title: 'User only' }],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });++ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <RecoilRoot>+ <QueryClientProvider client={queryClient}>+ <JotaiProvider store={settings}>+ <MemoryRouter>{children}</MemoryRouter>+ </JotaiProvider>+ </QueryClientProvider>+ </RecoilRoot>+ );++ return {+ ...renderHook(+ () => {+ const state = useUnseenConversations();+ useReplyAlerts(state);+ return state;+ },+ { wrapper },+ ),+ queryClient,+ };+}++describe('useReplyAlerts', () => {+ let hasFocus: jest.SpyInstance;++ beforeEach(() => {+ window.localStorage.clear();+ createdNotifications.length = 0;+ permissionRequest.mockReset();+ createOscillator.mockReset();+ createGain.mockReset();+ audioState = 'running';+ resumeAudio.mockReset().mockResolvedValue(undefined);+ stubOscillator();+ FakeNotification.permission = 'granted';+ /* jsdom ships neither API; the narrowest honest stand-ins are constructor shims. */+ window.Notification = FakeNotification as unknown as typeof Notification;+ window.AudioContext = FakeAudioContext as unknown as typeof AudioContext;+ hasFocus = jest.spyOn(document, 'hasFocus').mockReturnValue(false);+ });++ afterEach(() => {+ hasFocus.mockRestore();+ Reflect.deleteProperty(window, 'Notification');+ Reflect.deleteProperty(window, 'AudioContext');+ });++ it('does not fire a burst for a backlog that predates the session', () => {+ /* Signing in with unread conversations: the first pass only records them. */+ setup({ notifications: true }, stateOf([row('convo-backlog', 'Backlog')]));++ expect(createdNotifications).toHaveLength(0);+ });++ it('waits for a resolved list before recording the backlog', async () => {+ /* A tab restored in the background renders before the conversation query settles; taking+ that empty pass as the baseline turns the whole backlog into arrivals. */+ const { rerender } = setup({ notifications: true }, null);++ act(() => {+ rerender(stateOf([row('convo-backlog', 'Backlog')]));+ });++ expect(createdNotifications).toHaveLength(0);+ });++ it('alerts again when an already-unseen conversation gets another reply', async () => {+ const { rerender } = setup(+ { notifications: true },+ stateOf([row('convo-b', 'Beta', '2026-08-16T10:00:00.000Z')]),+ );++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta', '2026-08-16T10:05:00.000Z')]));+ });++ await waitFor(() => expect(createdNotifications).toHaveLength(1));+ expect(createdNotifications[0].options?.tag).toBe('convo-b');+ });++ it('stays quiet when only the title of an unseen conversation changes', () => {+ const { rerender } = setup({ notifications: true }, stateOf([row('convo-b', 'Untitled')]));++ act(() => {+ rerender(stateOf([row('convo-b', 'Auto Titled')]));+ });++ expect(createdNotifications).toHaveLength(0);+ });++ it('stays quiet when a read conversation is marked unread from another device', () => {+ /* It re-enters the unseen set carrying the same reply stamp it always had, even when the+ row has meanwhile left the cache entirely. Only a stamp that actually moved is a new+ reply. */+ const { rerender } = setup({ notifications: true }, stateOf([row('convo-b', 'Beta')]));++ act(() => {+ rerender(stateOf([]));+ });+ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });++ expect(createdNotifications).toHaveLength(0);+ });++ it('stays quiet when a never-replied conversation is flagged unread elsewhere', () => {+ /* The manual flag manufactures a reply stamp the baseline has never seen; the dot and the+ badge carry it, but "Reply ready" would name a reply that does not exist. */+ const { rerender } = setup({ notifications: true }, stateOf([]));++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta', '2026-08-16T10:05:00.000Z', true)]));+ });++ expect(createdNotifications).toHaveLength(0);+ });++ it('stays quiet when a conversation seen since sign-in is marked unread elsewhere', () => {+ /* This tab never saw the conversation unseen, so only the seen rows' baseline can tell+ its re-entry, carrying the stamp it always had, apart from a new reply. */+ const { rerender } = setup(+ { notifications: true },+ stateOf([], [['convo-b', '2026-08-16T10:00:00.000Z']]),+ );++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });++ expect(createdNotifications).toHaveLength(0);+ });++ it('still alerts for a reply to a conversation that had been read', () => {+ const { rerender } = setup({ notifications: true }, stateOf([row('convo-b', 'Beta')]));++ act(() => {+ rerender(stateOf([]));+ });+ act(() => {+ rerender(stateOf([row('convo-b', 'Beta', '2026-08-16T10:05:00.000Z')]));+ });++ expect(createdNotifications).toHaveLength(1);+ });++ it('does not claim a reply it has no enabled channel to announce', () => {+ /* Settings are per-tab snapshots; a badge-only tab claiming here would consume the reply+ while the tab that would chime or notify reads the claim and stays silent. */+ const { rerender } = setup({}, stateOf([]));++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });++ expect(window.localStorage.getItem('replyAlerts:announced:sound')).toBeNull();+ expect(window.localStorage.getItem('replyAlerts:announced:notification')).toBeNull();+ });++ it('stays quiet for a reply another tab has already announced', () => {+ /* Every open tab polls on its own timer; without the shared claim the same reply would+ chime once per tab, seconds apart. */+ window.localStorage.setItem(+ 'replyAlerts:announced:notification',+ JSON.stringify([['convo-b', '2026-08-16T10:05:00.000Z']]),+ );+ const { rerender } = setup({ notifications: true }, stateOf([row('convo-b', 'Beta')]));++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta', '2026-08-16T10:05:00.000Z')]));+ });++ expect(createdNotifications).toHaveLength(0);+ });++ it('still notifies for a reply another tab has only claimed the chime for', async () => {+ /* The toggles are per-tab snapshots, so a sound-only tab and a notification-only tab can+ both be open: one channel's claim must not silence the other. */+ window.localStorage.setItem(+ 'replyAlerts:announced:sound',+ JSON.stringify([['convo-b', '2026-08-16T10:05:00.000Z']]),+ );+ const { rerender } = setup({ notifications: true }, stateOf([row('convo-b', 'Beta')]));++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta', '2026-08-16T10:05:00.000Z')]));+ });++ await waitFor(() => expect(createdNotifications).toHaveLength(1));+ });++ it('records its own announcement where the other tabs will look', async () => {+ const { rerender } = setup({ notifications: true }, stateOf([]));++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });+ await waitFor(() => expect(createdNotifications).toHaveLength(1));++ const raw = window.localStorage.getItem('replyAlerts:announced:notification');+ expect(raw).not.toBeNull();+ expect(JSON.parse(raw as string)).toEqual([['convo-b', '2026-08-16T10:00:00.000Z']]);+ });++ it('degrades quietly where the Notification constructor is unsupported', () => {+ /* Android Chrome exposes the API and grants permission, then throws here. */+ window.Notification = function () {+ throw new TypeError('Illegal constructor');+ } as unknown as typeof Notification;+ (window.Notification as unknown as { permission: string }).permission = 'granted';+ const { rerender } = setup({ notifications: true });++ expect(() =>+ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ }),+ ).not.toThrow();+ });++ /* The claim is written before construction, so a throw must hand it back: otherwise every+ tab reads the reply as already announced and nobody ever delivers it. */+ it('leaves a reply claimable when its notification could not be created', () => {+ window.Notification = function () {+ throw new TypeError('Illegal constructor');+ } as unknown as typeof Notification;+ (window.Notification as unknown as { permission: string }).permission = 'granted';+ const { rerender } = setup({ notifications: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });++ const raw = window.localStorage.getItem('replyAlerts:announced:notification');+ const claims = raw == null ? [] : (JSON.parse(raw) as Array<[string, string]>);+ expect(claims.some(([id]) => id === 'convo-b')).toBe(false);+ });++ it('notifies for arrivals while the user is away', async () => {+ const { rerender } = setup({ notifications: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });++ await waitFor(() => expect(createdNotifications).toHaveLength(1));+ expect(createdNotifications[0].title).toBe('com_ui_reply_ready');+ expect(createdNotifications[0].options?.body).toBe('Beta');+ expect(createdNotifications[0].options?.tag).toBe('convo-b');+ });+ it('notifies for the first reply merged into a known user-only conversation', async () => {+ const { queryClient } = setupWithAggregate({ notifications: true });++ act(() => {+ applyServerReplyStamp(queryClient, 'user-only', {+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ });+ });++ await waitFor(() => expect(createdNotifications).toHaveLength(1));+ expect(createdNotifications[0].options?.tag).toBe('user-only');+ });++ const otherTabLease = (at = Date.now()) =>+ window.localStorage.setItem(+ 'replyAlerts:focusedAt',+ JSON.stringify({ owner: 'other-tab', at }),+ );++ it('stays quiet while another tab of the app holds focus', () => {+ /* `document.hasFocus()` answers only for this tab, so without the shared lease a+ background tab would chime over the one the user is reading. */+ otherTabLease();+ const { rerender } = setup({ notifications: true, sound: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });++ expect(createdNotifications).toHaveLength(0);+ expect(createOscillator).not.toHaveBeenCalled();+ /* Unclaimed, so the tab the user later leaves can still announce the reply. */+ expect(window.localStorage.getItem('replyAlerts:announced:notification')).toBeNull();+ });++ it('announces again once a stale focus lease has expired', async () => {+ otherTabLease(Date.now() - 120_000);+ const { rerender } = setup({ notifications: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });++ await waitFor(() => expect(createdNotifications).toHaveLength(1));+ });++ it('announces a reply held back by a lease its tab never released once it lapses', async () => {+ /* A tab killed without firing blur or pagehide leaves its lease behind. The reply that+ arrived under it is already in the baseline, so only a recheck at the lapse delivers it. */+ jest.useFakeTimers();+ try {+ otherTabLease();+ const { rerender } = setup({ notifications: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });+ expect(createdNotifications).toHaveLength(0);++ await act(async () => {+ jest.advanceTimersByTime(60_001);+ });++ expect(createdNotifications).toHaveLength(1);+ expect(createdNotifications[0].options?.tag).toBe('convo-b');+ } finally {+ jest.useRealTimers();+ }+ });++ it('announces a held reply as soon as the focused tab releases its lease', async () => {+ otherTabLease();+ const { rerender } = setup({ notifications: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });+ expect(createdNotifications).toHaveLength(0);++ act(() => {+ window.localStorage.removeItem('replyAlerts:focusedAt');+ window.dispatchEvent(new StorageEvent('storage', { key: 'replyAlerts:focusedAt' }));+ });++ await waitFor(() => expect(createdNotifications).toHaveLength(1));+ });++ it('keeps holding the reply while the focused tab keeps its lease alive', async () => {+ jest.useFakeTimers();+ try {+ otherTabLease();+ const { rerender } = setup({ notifications: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });+ await act(async () => {+ jest.advanceTimersByTime(40_000);+ otherTabLease();+ jest.advanceTimersByTime(20_001);+ });++ expect(createdNotifications).toHaveLength(0);+ } finally {+ jest.useRealTimers();+ }+ });++ it('leaves a lease this tab does not own in place when it unmounts', () => {+ /* Focus reaches the winning tab before the losing tab's blur handler runs, so a release+ that did not check ownership would delete the lease that tab had just written. */+ otherTabLease();+ const { unmount } = setup({ notifications: true });++ unmount();++ expect(window.localStorage.getItem('replyAlerts:focusedAt')).not.toBeNull();+ });++ it.each(['promise', 'callback', 'both'] as const)(+ 'announces a pending reply after a %s permission grant',+ async (api) => {+ FakeNotification.permission = 'default';+ let grant!: (value: NotificationPermission) => void;+ permissionRequest.mockImplementation((callback?: NotificationPermissionCallback) => {+ if (api === 'callback') {+ grant = (permission) => callback?.(permission);+ return undefined;+ }+ return new Promise<NotificationPermission>((resolve) => {+ grant = (permission) => {+ if (api === 'both') {+ callback?.(permission);+ }+ resolve(permission);+ };+ });+ });++ const { rerender } = setup({ notifications: true });+ await act(async () => {+ requestReplyNotificationPermission();+ });+ rerender(stateOf([row('convo-b', 'Beta')]));+ expect(createdNotifications).toHaveLength(0);++ await act(async () => {+ FakeNotification.permission = 'granted';+ grant('granted');+ });++ await waitFor(() => expect(createdNotifications).toHaveLength(1));+ expect(createdNotifications[0].options?.tag).toBe('convo-b');+ },+ );++ it('stays quiet for paginated backlog even when its server clock is ahead', async () => {+ const { rerender } = setup(+ { notifications: true },+ stateOf([row('convo-b', 'Beta', '2026-08-16T10:00:00.000Z')]),+ );++ act(() => {+ rerender(+ stateOf(+ [+ row('convo-b', 'Beta', '2026-08-16T10:00:00.000Z'),+ row('convo-old', 'Backlog', '2026-09-01T09:00:00.000Z'),+ ],+ [],+ [],+ ),+ );+ });++ expect(createdNotifications).toHaveLength(0);+ });++ it('announces a newly discovered reply even when its server clock is behind', () => {+ const { rerender } = setup(+ { notifications: true },+ stateOf([row('convo-b', 'Beta', '2026-08-16T10:00:00.000Z')]),+ );++ act(() => {+ rerender(+ stateOf([+ row('convo-b', 'Beta', '2026-08-16T10:00:00.000Z'),+ row('convo-new', 'Remote', '2026-08-16T09:00:00.000Z'),+ ]),+ );+ });++ expect(createdNotifications).toHaveLength(1);+ expect(createdNotifications[0].options?.tag).toBe('convo-new');+ });++ it('falls back to the untitled label when the conversation has no title', async () => {+ const { rerender } = setup({ notifications: true });++ act(() => {+ rerender(stateOf([row('convo-c', '')]));+ });++ await waitFor(() => expect(createdNotifications).toHaveLength(1));+ expect(createdNotifications[0].options?.body).toBe('com_ui_untitled');+ });++ it('stays quiet while the user is looking at the app', () => {+ hasFocus.mockReturnValue(true);+ const { rerender } = setup({ notifications: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });++ expect(createdNotifications).toHaveLength(0);+ });++ it('plays the chime for sound-only users without desktop notifications', () => {+ const { rerender } = setup({ sound: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });++ expect(createdNotifications).toHaveLength(0);+ expect(createOscillator).toHaveBeenCalledTimes(2);+ });++ /* A running context can still throw while the tones are being built. Nothing played, so the+ claim is handed back instead of silencing the reply in every tab. */+ it('leaves a reply claimable when its chime could not be scheduled', () => {+ createOscillator.mockImplementation(() => {+ throw new Error('output device lost');+ });+ const { rerender } = setup({ sound: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });++ const raw = window.localStorage.getItem('replyAlerts:announced:sound');+ const claims = raw == null ? [] : (JSON.parse(raw) as Array<[string, string]>);+ expect(claims.some(([id]) => id === 'convo-b')).toBe(false);+ });++ it('leaves a suspended tab’s chime claim available to a usable audio context', async () => {+ audioState = 'suspended';+ resumeAudio.mockReturnValue(Promise.withResolvers<void>().promise);+ const locked = setup({ sound: true }, stateOf([]));+ await act(async () => {+ locked.rerender(stateOf([row('shared-reply', 'Reply')]));+ });+ expect(window.localStorage.getItem('replyAlerts:announced:sound')).toBeNull();+ expect(createOscillator).not.toHaveBeenCalled();++ audioState = 'running';+ const ready = setup({ sound: true }, stateOf([]));+ act(() => {+ ready.rerender(stateOf([row('shared-reply', 'Reply')]));+ });+ expect(createOscillator).toHaveBeenCalledTimes(2);+ expect(JSON.parse(window.localStorage.getItem('replyAlerts:announced:sound') ?? '[]')).toEqual([+ ['shared-reply', '2026-08-16T10:00:00.000Z'],+ ]);+ });++ it('leaves the focus trigger alone for the conversation already on screen', async () => {+ /* That click navigates nowhere, so suppressing would swallow the one trigger that+ acknowledges the reply the user is looking at. */+ const windowFocus = jest.spyOn(window, 'focus').mockImplementation(() => undefined);+ const { rerender } = setup({ notifications: true }, stateOf([]), '/c/convo-b');++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });+ await waitFor(() => expect(createdNotifications).toHaveLength(1));++ hasFocus.mockReturnValue(false);+ act(() => {+ createdNotifications[0].onclick?.();+ });++ expect(consumeFocusSuppression()).toBe(false);+ windowFocus.mockRestore();+ });++ it('suppresses the focus trigger when the notification leads elsewhere', async () => {+ const windowFocus = jest.spyOn(window, 'focus').mockImplementation(() => undefined);+ const { rerender } = setup({ notifications: true }, stateOf([]), '/c/convo-open');++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });+ await waitFor(() => expect(createdNotifications).toHaveLength(1));++ hasFocus.mockReturnValue(false);+ act(() => {+ createdNotifications[0].onclick?.();+ });++ expect(consumeFocusSuppression()).toBe(true);+ windowFocus.mockRestore();+ });++ it('navigates to the conversation when the notification is clicked', async () => {+ const windowFocus = jest.spyOn(window, 'focus').mockImplementation(() => undefined);+ const { rerender, pathnameRef } = setup({ notifications: true });++ act(() => {+ rerender(stateOf([row('convo-b', 'Beta')]));+ });+ await waitFor(() => expect(createdNotifications).toHaveLength(1));++ act(() => {+ createdNotifications[0].onclick?.();+ });++ await waitFor(() => expect(pathnameRef.current).toBe('/c/convo-b'));+ expect(windowFocus).toHaveBeenCalled();+ expect(createdNotifications[0].close).toHaveBeenCalled();+ windowFocus.mockRestore();+ });+});diff --git a/client/src/hooks/Conversations/__tests__/useReplyWatcher.spec.tsx b/client/src/hooks/Conversations/__tests__/useReplyWatcher.spec.tsxnew file mode 100644index 0000000000..8dd69711f0--- /dev/null+++ b/client/src/hooks/Conversations/__tests__/useReplyWatcher.spec.tsx@@ -0,0 +1,1011 @@+import React from 'react';+import { RecoilRoot } from 'recoil';+import { Provider as JotaiProvider, createStore } from 'jotai';+import { act, renderHook, waitFor } from '@testing-library/react';+import { EModelEndpoint, QueryKeys } from 'librechat-data-provider';+import {+ QueryClient,+ QueryObserver,+ InfiniteQueryObserver,+ QueryClientProvider,+} from '@tanstack/react-query';+import type { ConversationListParams } from 'librechat-data-provider';+import type { InfiniteData } from '@tanstack/react-query';+import type { ConversationCursorData } from '~/utils/convos';+import {+ unseenTabBadgeAtom,+ replyNotificationsAtom,+ replyNotificationSoundAtom,+} from '../replyNotificationSettings';+import useUnseenConversations from '../useUnseenConversations';+import { startupConfigKey } from '~/data-provider';+import useReplyWatcher from '../useReplyWatcher';+import { isConversationUnseen } from '~/utils';++const mockGetConversationById = jest.fn();+const mockListConversations = jest.fn();+jest.mock('librechat-data-provider', () => ({+ ...jest.requireActual('librechat-data-provider'),+ dataService: {+ getConversationById: (...args: unknown[]) => mockGetConversationById(...args),+ listConversations: (...args: unknown[]) => mockListConversations(...args),+ },+}));++let mockActiveJobIds: string[] | undefined = [];+jest.mock('~/data-provider', () => ({+ ...jest.requireActual('~/data-provider'),+ useActiveJobs: () => ({ data: { activeJobIds: mockActiveJobIds } }),+}));++const CONVO_ID = 'convo-watched';+const RESPONDED_AT = '2026-08-16T10:00:00.000Z';++const listKey = [QueryKeys.allConversations, { isArchived: false }];++/* The alert capabilities stay off until the deployment has answered, so every render starts+ from a loaded startup config that restricts none of them. */+const withLoadedConfig = (client: QueryClient): QueryClient => {+ client.setQueryData(startupConfigKey(false), { interface: {} });+ return client;+};++type Toggles = { notifications?: boolean; sound?: boolean; badge?: boolean };++function setup(toggles: Toggles = {}, replyNotifications?: Record<string, number | boolean>) {+ const { notifications = false, sound = false, badge = false } = toggles;+ const queryClient = withLoadedConfig(+ new QueryClient({ defaultOptions: { queries: { retry: false } } }),+ );+ if (replyNotifications) {+ queryClient.setQueryData(startupConfigKey(false), { interface: { replyNotifications } });+ }+ queryClient.setQueryData(listKey, {+ pages: [+ {+ conversations: [+ {+ conversationId: CONVO_ID,+ title: 'Watched',+ endpoint: 'openAI',+ lastResponseMessageId: 'reply-id',+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });++ const settings = createStore();+ settings.set(replyNotificationsAtom, notifications);+ settings.set(replyNotificationSoundAtom, sound);+ settings.set(unseenTabBadgeAtom, badge);++ /* The alert capabilities are gated by `interface.replyNotifications`, which the hooks read+ through the startup-config query, so these specs need the app's providers around them. */+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <RecoilRoot>+ <QueryClientProvider client={queryClient}>+ <JotaiProvider store={settings}>{children}</JotaiProvider>+ </QueryClientProvider>+ </RecoilRoot>+ );++ const view = renderHook(+ () => {+ useReplyWatcher();+ return useUnseenConversations();+ },+ { wrapper },+ );+ const cachedConvo = () =>+ queryClient.getQueryData<InfiniteData<ConversationCursorData>>(listKey)?.pages[0]+ .conversations[0];++ return { ...view, cachedConvo, queryClient };+}++describe('useReplyWatcher', () => {+ beforeEach(() => {+ jest.useFakeTimers();+ mockActiveJobIds = [];+ mockGetConversationById.mockReset();+ mockListConversations.mockReset();+ jest.spyOn(document, 'hasFocus').mockReturnValue(false);+ });++ afterEach(() => {+ jest.useRealTimers();+ jest.restoreAllMocks();+ });++ it('pulls the reply timestamp in when a tracked job stops running', async () => {+ mockGetConversationById.mockResolvedValue({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });++ mockActiveJobIds = [CONVO_ID];+ const { rerender, cachedConvo } = setup();++ mockActiveJobIds = [];+ rerender();++ await waitFor(() => expect(mockGetConversationById).toHaveBeenCalledWith(CONVO_ID));+ await waitFor(() => expect(isConversationUnseen(cachedConvo())).toBe(true));+ });++ /* Signing out or switching accounts unmounts the watcher while a completion fetch can still+ be in flight; its answer belongs to the previous session and must not reach the caches. */+ it('discards a completion that resolves after the watcher has gone', async () => {+ let resolveFetch: (value: unknown) => void = () => undefined;+ mockGetConversationById.mockReturnValue(+ new Promise((resolve) => {+ resolveFetch = resolve;+ }),+ );++ mockActiveJobIds = [CONVO_ID];+ const { rerender, unmount, cachedConvo } = setup();++ mockActiveJobIds = [];+ rerender();+ await waitFor(() => expect(mockGetConversationById).toHaveBeenCalledWith(CONVO_ID));++ unmount();+ await act(async () => {+ resolveFetch({ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT });+ });++ expect(isConversationUnseen(cachedConvo())).toBe(false);+ });++ it('does not treat the first observation of a running job as a completion', () => {+ mockActiveJobIds = [CONVO_ID];+ setup();++ expect(mockGetConversationById).not.toHaveBeenCalled();+ });++ it('treats a failed jobs poll as no information rather than mass completion', async () => {+ mockActiveJobIds = [CONVO_ID];+ const { rerender } = setup();++ mockActiveJobIds = undefined;+ rerender();++ expect(mockGetConversationById).not.toHaveBeenCalled();+ });++ it('fetches the successor reply when consecutive jobs keep the same conversation active', async () => {+ (document.hasFocus as jest.Mock).mockReturnValue(true);+ mockActiveJobIds = [CONVO_ID];+ const { rerender, queryClient, cachedConvo } = setup();+ act(() => {+ updateCachedTimestamps(queryClient);+ });+ mockActiveJobIds = [CONVO_ID];+ rerender();+ const successorStamp = '2026-08-16T12:00:00.000Z';+ mockGetConversationById.mockResolvedValue({+ conversationId: CONVO_ID,+ lastResponseAt: successorStamp,+ lastResponseMessageId: 'successor-reply',+ });++ mockActiveJobIds = [];+ rerender();++ await waitFor(() => expect(cachedConvo()?.lastResponseAt).toBe(successorStamp));+ expect(isConversationUnseen(cachedConvo())).toBe(true);+ });+ it('merges an equal-stamp response identity without clearing newer read state', async () => {+ (document.hasFocus as jest.Mock).mockReturnValue(true);+ mockActiveJobIds = [CONVO_ID];+ const { rerender, queryClient, cachedConvo } = setup();+ updateCachedTimestamps(queryClient);+ queryClient.setQueryData(+ listKey,+ (current: InfiniteData<ConversationCursorData> | undefined) => {+ if (!current) {+ return current;+ }+ return {+ ...current,+ pages: current.pages.map((page) => ({+ ...page,+ conversations: page.conversations.map((conversation) => ({+ ...conversation,+ lastResponseMessageId: undefined,+ lastSeenAt: RESPONDED_AT,+ })),+ })),+ };+ },+ );+ mockGetConversationById.mockResolvedValue({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ lastResponseMessageId: 'reply-id',+ lastSeenAt: undefined,+ });+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries');++ mockActiveJobIds = [];+ rerender();++ await waitFor(() => expect(cachedConvo()?.lastResponseMessageId).toBe('reply-id'));+ expect(invalidate).not.toHaveBeenCalledWith([QueryKeys.messages, CONVO_ID]);+ });++ it('polls the conversation list while away once notifications are enabled', async () => {+ mockListConversations.mockResolvedValue({+ conversations: [{ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT }],+ nextCursor: null,+ });++ const { cachedConvo } = setup({ notifications: true });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });++ expect(mockListConversations).toHaveBeenCalled();+ await waitFor(() => expect(isConversationUnseen(cachedConvo())).toBe(true));+ });++ it('polls away at the cadence the deployment configured', async () => {+ mockListConversations.mockResolvedValue({ conversations: [], nextCursor: null });++ setup({ notifications: true }, { pollIntervalMs: 10_000 });++ await act(async () => {+ jest.advanceTimersByTime(9_999);+ });+ expect(mockListConversations).not.toHaveBeenCalled();++ await act(async () => {+ jest.advanceTimersByTime(1);+ });+ expect(mockListConversations).toHaveBeenCalledTimes(1);+ });++ it('polls while away when only the notification sound is enabled', async () => {+ mockListConversations.mockResolvedValue({ conversations: [], nextCursor: null });++ setup({ sound: true });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });++ expect(mockListConversations).toHaveBeenCalled();+ });++ it('polls while away when only the tab badge is enabled', async () => {+ mockListConversations.mockResolvedValue({ conversations: [], nextCursor: null });++ setup({ badge: true });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });++ expect(mockListConversations).toHaveBeenCalled();+ });++ it('does not poll while the user is looking at the app', async () => {+ (document.hasFocus as jest.Mock).mockReturnValue(true);+ setup({ notifications: true, sound: true, badge: true });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });++ expect(mockListConversations).not.toHaveBeenCalled();+ });++ it('does not poll when every away feature is off', async () => {+ setup();++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });++ expect(mockListConversations).not.toHaveBeenCalled();+ });++ it('does not refresh the list query when the poll finds nothing new', async () => {+ /* An unchanged write would bump dataUpdatedAt and keep the sidebar's list query+ permanently fresh, silently disabling its refetch on window focus. */+ mockListConversations.mockResolvedValue({+ conversations: [{ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT }],+ nextCursor: null,+ });++ const { queryClient, cachedConvo } = setup({ notifications: true });+ updateCachedTimestamps(queryClient);+ const before = queryClient.getQueryState(listKey)?.dataUpdatedAt;++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });+ await waitFor(() => expect(isConversationUnseen(cachedConvo())).toBe(true));++ const after = queryClient.getQueryState(listKey)?.dataUpdatedAt;+ expect(after).toBe(before);+ });++ it('ignores a poll snapshot that would walk the read state backwards', async () => {+ /* Overlapping polls can resolve out of order; taking the older payload would drop a dot+ or bring one back until the next poll repaired it. */+ const newer = '2026-08-16T12:00:00.000Z';+ const { queryClient, cachedConvo } = setup({ notifications: true });++ act(() => {+ queryClient.setQueryData<InfiniteData<ConversationCursorData>>(listKey, {+ pages: [+ {+ conversations: [+ {+ conversationId: CONVO_ID,+ title: 'Watched',+ endpoint: EModelEndpoint.openAI,+ createdAt: RESPONDED_AT,+ updatedAt: RESPONDED_AT,+ lastResponseAt: newer,+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });+ });++ mockListConversations.mockResolvedValue({+ conversations: [{ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT }],+ nextCursor: null,+ });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });++ expect(cachedConvo()?.lastResponseAt).toBe(newer);+ });++ it.each([true, false])(+ 'keeps the newest equal-stamp poll read state (seen: %s)',+ async (seen) => {+ const { queryClient, cachedConvo } = setup({ notifications: true });+ updateCachedTimestamps(queryClient);+ const older = Promise.withResolvers<{+ conversations: Array<{+ conversationId: string;+ lastResponseAt: string;+ lastSeenAt?: string;+ }>;+ }>();+ mockListConversations.mockReturnValueOnce(older.promise).mockResolvedValueOnce({+ conversations: [+ {+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: seen ? RESPONDED_AT : undefined,+ },+ ],+ });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });+ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });+ expect(isConversationUnseen(cachedConvo())).toBe(!seen);++ await act(async () => {+ older.resolve({+ conversations: [+ {+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: seen ? undefined : RESPONDED_AT,+ },+ ],+ });+ });++ expect(isConversationUnseen(cachedConvo())).toBe(!seen);+ },+ );++ it('rejects an equal-stamp poll superseded during message invalidation', async () => {+ const { queryClient, cachedConvo } = setup({ notifications: true });+ updateCachedTimestamps(queryClient);+ const messages = Promise.withResolvers<void>();+ const invalidate = queryClient.invalidateQueries.bind(queryClient);+ jest+ .spyOn(queryClient, 'invalidateQueries')+ .mockImplementationOnce(() => messages.promise)+ .mockImplementation(invalidate);+ mockListConversations+ .mockResolvedValueOnce({+ conversations: [+ { conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT, lastSeenAt: RESPONDED_AT },+ ],+ })+ .mockResolvedValueOnce({+ conversations: [{ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT }],+ });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });+ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });+ await act(async () => {+ messages.resolve();+ });++ expect(isConversationUnseen(cachedConvo())).toBe(true);+ });++ it('drops a completion snapshot outrun while its messages refetched', async () => {+ /* The freshness guard runs before a real network wait; the SSE final handler can stamp a+ newer reply during it, and writing the older snapshot back would walk the read state+ backwards after that reply's signal was already consumed. */+ const newer = '2026-08-16T12:00:00.000Z';+ mockActiveJobIds = [CONVO_ID];+ const { rerender, queryClient, cachedConvo } = setup();++ const realInvalidate = queryClient.invalidateQueries.bind(queryClient);+ const invalidate = jest+ .spyOn(queryClient, 'invalidateQueries')+ .mockImplementation((filters?: unknown) => {+ if (Array.isArray(filters) && filters[0] === QueryKeys.messages) {+ act(() => {+ queryClient.setQueryData<InfiniteData<ConversationCursorData>>(listKey, {+ pages: [+ {+ conversations: [+ {+ conversationId: CONVO_ID,+ title: 'Watched',+ endpoint: EModelEndpoint.openAI,+ createdAt: RESPONDED_AT,+ updatedAt: RESPONDED_AT,+ lastResponseAt: newer,+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });+ });+ }+ return realInvalidate(filters as Parameters<typeof realInvalidate>[0]);+ });++ mockGetConversationById.mockResolvedValue({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ mockActiveJobIds = [];+ rerender();++ await waitFor(() => expect(invalidate).toHaveBeenCalledWith([QueryKeys.messages, CONVO_ID]));+ await act(async () => {+ await Promise.resolve();+ });++ expect(cachedConvo()?.lastResponseAt).toBe(newer);+ });++ it('recovers a completion lost to a transient fetch failure through the list', async () => {+ /* The failed fetch has consumed the only completion transition, and the away poll is gated+ on the document being unfocused; without a fallback the reply would stay invisible for+ as long as the user kept the app focused. */+ jest.spyOn(document, 'hasFocus').mockReturnValue(true);+ mockActiveJobIds = [CONVO_ID];+ const { rerender, queryClient, result } = setup();+ const observer = new QueryObserver(queryClient, {+ queryKey: listKey,+ staleTime: Infinity,+ queryFn: async () => ({+ pages: [+ {+ conversations: [{ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT }],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ }),+ });+ const unsubscribe = observer.subscribe(() => {});++ mockGetConversationById.mockRejectedValue(new Error('network down'));+ mockActiveJobIds = [];+ rerender();++ await waitFor(() =>+ expect(result.current?.unseen).toEqual([+ expect.objectContaining({ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT }),+ ]),+ );+ unsubscribe();+ });++ it('lets a conversation deleted while it generated stay gone', async () => {+ mockActiveJobIds = [CONVO_ID];+ const { rerender, queryClient } = setup();+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries');++ mockGetConversationById.mockRejectedValue({ status: 404 });+ mockActiveJobIds = [];+ rerender();++ await act(async () => {+ await Promise.resolve();+ });++ expect(invalidate).not.toHaveBeenCalled();+ });++ it('discards an away snapshot that resolves after the user returns', async () => {+ /* The poll's request bypasses React Query, so the seen mutation's cancellation cannot+ reach it: a snapshot read before the focus-triggered acknowledgement settled carries+ the same reply stamp with the older catch-up, and writing it back would re-light a dot+ the server no longer backs. */+ const { queryClient, cachedConvo } = setup({ notifications: true });++ act(() => {+ queryClient.setQueryData<InfiniteData<ConversationCursorData>>(listKey, {+ pages: [+ {+ conversations: [+ {+ conversationId: CONVO_ID,+ title: 'Watched',+ endpoint: EModelEndpoint.openAI,+ createdAt: RESPONDED_AT,+ updatedAt: RESPONDED_AT,+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: RESPONDED_AT,+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });+ });++ mockListConversations.mockImplementation(async () => {+ (document.hasFocus as jest.Mock).mockReturnValue(true);+ return {+ conversations: [{ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT }],+ nextCursor: null,+ };+ });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });++ expect(cachedConvo()?.lastSeenAt).toBe(RESPONDED_AT);+ });++ it('withholds the stamp when the open conversation failed to reload its messages', async () => {+ /* Invalidation settles rather than throwing, so the failure has to be read off the query.+ Exposing the stamp would credit a reply the tab never managed to load. */+ const { queryClient, cachedConvo } = setup({ notifications: true });+ const failed = failMessagesQuery(queryClient, { observed: true });+ expect(failed).toBeDefined();++ mockListConversations.mockResolvedValue({+ conversations: [{ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT }],+ nextCursor: null,+ });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });++ expect(cachedConvo()?.lastResponseAt).toBeUndefined();+ });++ it('ignores a stale error left by a conversation the user has since closed', async () => {+ /* An unobserved query is never refetched by the invalidation, so its cached error is not+ this attempt's and never clears; reading it would mute that conversation for the+ rest of the session. */+ const { queryClient, cachedConvo } = setup({ notifications: true });+ failMessagesQuery(queryClient, { observed: false });++ mockListConversations.mockResolvedValue({+ conversations: [{ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT }],+ nextCursor: null,+ });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });++ await waitFor(() => expect(cachedConvo()?.lastResponseAt).toBe(RESPONDED_AT));+ });++ it('marks the messages stale so a reply this tab never streamed is rendered', async () => {+ /* Without it the stamp alone would let the seen trigger credit a reply from a scroll+ position that belongs to the previous message. */+ mockActiveJobIds = [CONVO_ID];+ const { rerender, queryClient } = setup();+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries');++ mockGetConversationById.mockResolvedValue({+ conversationId: CONVO_ID,+ lastResponseAt: new Date(Date.now() + 60_000).toISOString(),+ });+ mockActiveJobIds = [];+ rerender();++ await waitFor(() => expect(invalidate).toHaveBeenCalledWith([QueryKeys.messages, CONVO_ID]));+ });++ it('reveals a point-only conversation to the unread aggregate', async () => {+ /* Opened by URL, so it sits in its own point query: enough for the lookup, invisible to+ the badge and the alerts, which read the lists only. */+ mockActiveJobIds = [CONVO_ID];+ const { rerender, queryClient, result } = setup();+ queryClient.removeQueries(listKey);+ queryClient.setQueryData([QueryKeys.conversation, CONVO_ID], {+ conversationId: CONVO_ID,+ title: 'Opened by URL',+ });+ mockListConversations.mockResolvedValue({+ conversations: [+ { conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT, updatedAt: RESPONDED_AT },+ ],+ nextCursor: null,+ });++ mockGetConversationById.mockResolvedValue({+ conversationId: CONVO_ID,+ lastResponseAt: RESPONDED_AT,+ });+ mockActiveJobIds = [];+ rerender();++ await waitFor(() =>+ expect(result.current?.unseen).toEqual([+ expect.objectContaining({ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT }),+ ]),+ );+ });++ it('asks for more than one default page while away', async () => {+ /* A batch of scheduled runs can reply to more conversations than the server's default page+ holds, and anything past it would never reach the badge or the alerts. */+ mockListConversations.mockResolvedValue({ conversations: [], nextCursor: null });+ setup({ notifications: true });++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });++ expect(mockListConversations).toHaveBeenCalledWith(+ expect.objectContaining({ limit: expect.any(Number) }),+ );+ expect(mockListConversations.mock.calls[0][0].limit).toBeGreaterThan(25);+ });++ it('reads a full page on the focused refresh when the operator lowered the away limit', async () => {+ /* The poll limit bounds the away poll. Reusing it for the focused refresh would let a+ lowered limit keep older replies out of the unseen count behind a filtered list. */+ (document.hasFocus as jest.Mock).mockReturnValue(true);+ mockListConversations.mockResolvedValue({ conversations: [], nextCursor: null });+ setup({}, { pollLimit: 10 });++ await act(async () => {+ jest.advanceTimersByTime(5 * 60_000);+ });++ await waitFor(() => expect(mockListConversations).toHaveBeenCalled());+ expect(mockListConversations.mock.calls.map(([params]) => params.limit)).toContain(100);+ expect(mockListConversations.mock.calls.map(([params]) => params.limit)).not.toContain(10);+ });++ it('refreshes only the newest page while preserving scrolled rows and cursors', async () => {+ (document.hasFocus as jest.Mock).mockReturnValue(true);+ const { queryClient, unmount } = setup();+ const older = {+ conversationId: 'older',+ title: 'Older',+ endpoint: EModelEndpoint.openAI,+ };+ const promoted = {+ conversationId: 'promoted',+ title: 'Promoted',+ endpoint: EModelEndpoint.openAI,+ };+ const middle = {+ conversationId: 'middle',+ title: 'Middle',+ endpoint: EModelEndpoint.openAI,+ };+ const tail = {+ conversationId: 'tail',+ title: 'Tail',+ endpoint: EModelEndpoint.openAI,+ };+ queryClient.setQueryData(listKey, {+ pages: [+ {+ conversations: [older, { conversationId: 'newest', endpoint: EModelEndpoint.openAI }],+ nextCursor: 'old-1',+ },+ { conversations: [promoted, middle], nextCursor: 'old-2' },+ { conversations: [tail], nextCursor: 'old-3' },+ ],+ pageParams: [null, 'old-1', 'old-2'],+ });+ mockListConversations.mockResolvedValue({+ conversations: [{ ...promoted, lastResponseAt: RESPONDED_AT }, { conversationId: 'newest' }],+ nextCursor: 'fresh-1',+ });+ const observer = new InfiniteQueryObserver<ConversationCursorData>(queryClient, {+ queryKey: listKey,+ staleTime: 5 * 60_000,+ queryFn: ({ pageParam }) => mockListConversations({ cursor: pageParam }),+ getNextPageParam: (lastPage) => lastPage?.nextCursor ?? undefined,+ });+ const unsubscribe = observer.subscribe(() => {});++ await act(async () => {+ jest.advanceTimersByTime(5 * 60_000);+ });+ await waitFor(() => expect(mockListConversations.mock.calls).toHaveLength(2));+ expect(mockListConversations.mock.calls.every(([params]) => params.cursor == null)).toBe(true);+ const data = queryClient.getQueryData<InfiniteData<ConversationCursorData>>(listKey);+ expect(+ data?.pages.flatMap((page) => page.conversations).map((convo) => convo.conversationId),+ ).toEqual(['promoted', 'newest', 'older', 'middle', 'tail']);+ expect(data?.pageParams).toEqual([null, 'fresh-1', 'old-2']);+ expect(data?.pages[1].nextCursor).toBe('old-2');+ expect(observer.getCurrentResult().isStale).toBe(true);+ unsubscribe();+ unmount();+ });++ it('keeps a mid-merge acknowledgement over an equal-stamp completion snapshot', async () => {+ /* The completion fetch's one job is delivering a stamp the cache lacks; when the SSE+ final handler and the seen trigger land the same stamp and its acknowledgement while+ this merge awaits the messages refetch, the snapshot's older read state must not undo+ them. */+ const newer = '2026-08-16T12:00:00.000Z';+ mockActiveJobIds = [CONVO_ID];+ const { rerender, queryClient, cachedConvo } = setup();++ const realInvalidate = queryClient.invalidateQueries.bind(queryClient);+ const invalidate = jest+ .spyOn(queryClient, 'invalidateQueries')+ .mockImplementation((filters?: unknown) => {+ if (Array.isArray(filters) && filters[0] === QueryKeys.messages) {+ act(() => {+ queryClient.setQueryData<InfiniteData<ConversationCursorData>>(listKey, {+ pages: [+ {+ conversations: [+ {+ conversationId: CONVO_ID,+ title: 'Watched',+ endpoint: EModelEndpoint.openAI,+ createdAt: RESPONDED_AT,+ updatedAt: RESPONDED_AT,+ lastResponseAt: newer,+ lastSeenAt: newer,+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });+ });+ }+ return realInvalidate(filters as Parameters<typeof realInvalidate>[0]);+ });++ mockGetConversationById.mockResolvedValue({+ conversationId: CONVO_ID,+ lastResponseAt: newer,+ });+ mockActiveJobIds = [];+ rerender();++ await waitFor(() => expect(invalidate).toHaveBeenCalledWith([QueryKeys.messages, CONVO_ID]));+ await act(async () => {+ await Promise.resolve();+ });++ expect(cachedConvo()?.lastSeenAt).toBe(newer);+ });++ it.each([false, true])(+ 'reveals an away reply after the unfiltered refresh recovers (point-cached: %s)',+ async (pointCached) => {+ let offline = true;+ mockListConversations.mockImplementation(async ({ isArchived }: { isArchived?: boolean }) => {+ if (isArchived === false && offline) {+ throw new Error('offline');+ }+ return {+ conversations: [{ conversationId: 'elsewhere', lastResponseAt: RESPONDED_AT }],+ nextCursor: null,+ };+ });+ const { queryClient, result } = setup({ notifications: true });+ if (pointCached) {+ queryClient.setQueryData([QueryKeys.conversation, 'elsewhere'], {+ conversationId: 'elsewhere',+ title: 'Opened by URL',+ });+ }++ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });+ expect(result.current?.unseen).toEqual([]);++ offline = false;+ await act(async () => {+ jest.advanceTimersByTime(30_000);+ });+ await waitFor(() =>+ expect(result.current?.unseen).toEqual([+ expect.objectContaining({ conversationId: 'elsewhere', lastResponseAt: RESPONDED_AT }),+ ]),+ );+ },+ );++ it('reveals a completed job that belongs to no cached conversation', async () => {+ const conversation = {+ conversationId: 'started-on-phone',+ lastResponseAt: RESPONDED_AT,+ };+ mockGetConversationById.mockResolvedValue(conversation);+ mockListConversations.mockResolvedValue({ conversations: [conversation], nextCursor: null });+ mockActiveJobIds = [conversation.conversationId];+ const { rerender, result } = setup();++ mockActiveJobIds = [];+ rerender();++ await waitFor(() =>+ expect(result.current?.unseen).toEqual([expect.objectContaining(conversation)]),+ );+ });++ it.each([true, false])(+ 'refreshes replies outside the sidebar filter (focused: %s)',+ async (focused) => {+ (document.hasFocus as jest.Mock).mockReturnValue(focused);+ mockListConversations.mockImplementation(async ({ tags }: ConversationListParams) => ({+ conversations: tags?.length+ ? []+ : [+ {+ conversationId: 'outside-filter',+ title: 'Remote',+ lastResponseAt: RESPONDED_AT,+ updatedAt: RESPONDED_AT,+ },+ ],+ nextCursor: null,+ }));+ const { queryClient, result, unmount } = setup({ notifications: !focused });+ const filteredKey = [QueryKeys.allConversations, { isArchived: false, tags: ['work'] }];+ const filteredData = { pages: [{ conversations: [], nextCursor: null }], pageParams: [null] };+ queryClient.setQueryData(filteredKey, filteredData);+ queryClient.removeQueries({ queryKey: listKey, exact: true });+ const observer = new InfiniteQueryObserver<ConversationCursorData>(queryClient, {+ queryKey: filteredKey,+ staleTime: Infinity,+ queryFn: async () => filteredData.pages[0],+ getNextPageParam: (page) => page.nextCursor ?? undefined,+ });+ const unsubscribe = observer.subscribe(() => {});++ await act(async () => {+ jest.advanceTimersByTime(10_000);+ });+ expect(result.current?.unseen).toEqual([]);++ await act(async () => {+ jest.advanceTimersByTime((focused ? 5 * 60_000 : 30_000) - 10_000);+ });+ await waitFor(() =>+ expect(result.current?.unseen).toEqual([+ expect.objectContaining({+ conversationId: 'outside-filter',+ lastResponseAt: RESPONDED_AT,+ }),+ ]),+ );+ expect(queryClient.getQueryData(filteredKey)).toEqual(filteredData);+ /* The away poll names the conversation it discovered, so that refresh may announce it.+ The focused refresh names nothing: the canonical query it creates has never been+ observed, and treating its whole first page as arrivals would announce the backlog. */+ if (focused) {+ expect(result.current?.arrivalStamps).toEqual([]);+ } else {+ expect(result.current?.arrivalStamps).toContainEqual(['outside-filter', RESPONDED_AT]);+ }+ unsubscribe();+ unmount();+ },+ );++ it('refreshes a pinned unread row outside the canonical first page', async () => {+ (document.hasFocus as jest.Mock).mockReturnValue(true);+ mockListConversations.mockResolvedValue({ conversations: [], nextCursor: null });+ const { queryClient, result, unmount } = setup();+ const pinnedKey = [QueryKeys.pinnedConversations, {}];+ const pinned = { conversationId: 'old-pin', title: 'Old pin', lastResponseAt: RESPONDED_AT };+ queryClient.setQueryData(pinnedKey, {+ conversations: [{ ...pinned, lastSeenAt: RESPONDED_AT }],+ nextCursor: null,+ });+ const observer = new QueryObserver(queryClient, {+ queryKey: pinnedKey,+ staleTime: Infinity,+ queryFn: async () => ({ conversations: [pinned], nextCursor: null }),+ });+ const unsubscribe = observer.subscribe(() => {});++ await act(async () => {+ jest.advanceTimersByTime(5 * 60_000);+ });++ expect(isConversationUnseen(observer.getCurrentResult().data?.conversations[0])).toBe(true);+ expect(result.current?.unseen).toEqual([expect.objectContaining(pinned)]);+ unsubscribe();+ unmount();+ });+});++function updateCachedTimestamps(queryClient: QueryClient) {+ queryClient.setQueryData<InfiniteData<ConversationCursorData>>(listKey, {+ pages: [+ {+ conversations: [+ {+ conversationId: CONVO_ID,+ title: 'Watched',+ endpoint: EModelEndpoint.openAI,+ createdAt: RESPONDED_AT,+ updatedAt: RESPONDED_AT,+ lastResponseAt: RESPONDED_AT,+ lastResponseMessageId: 'reply-id',+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null],+ });+}++/** Leaves the conversation's messages query cached in an error state, optionally with an+ * observer so it counts as the one this attempt refetched. */+function failMessagesQuery(queryClient: QueryClient, { observed }: { observed: boolean }) {+ queryClient.setQueryData([QueryKeys.messages, CONVO_ID], []);+ const query = queryClient.getQueryCache().find([QueryKeys.messages, CONVO_ID]);+ query?.setState({ status: 'error', error: new Error('offline') } as never);+ jest.spyOn(query!, 'getObserversCount').mockReturnValue(observed ? 1 : 0);+ return query;+}diff --git a/client/src/hooks/Conversations/__tests__/useUnseenBadge.spec.tsx b/client/src/hooks/Conversations/__tests__/useUnseenBadge.spec.tsxnew file mode 100644index 0000000000..9f37736a5f--- /dev/null+++ b/client/src/hooks/Conversations/__tests__/useUnseenBadge.spec.tsx@@ -0,0 +1,164 @@+import React from 'react';+import { RecoilRoot } from 'recoil';+import { Provider as JotaiProvider, createStore } from 'jotai';+import { act, renderHook, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { unseenTabBadgeAtom } from '../replyNotificationSettings';+import { startupConfigKey } from '~/data-provider';+import useUnseenBadge from '../useUnseenBadge';+import { setDocumentTitle } from '~/utils';++/* The alert capabilities stay off until the deployment has answered, so every render starts+ from a loaded startup config that restricts none of them. */+const withLoadedConfig = (client: QueryClient): QueryClient => {+ client.setQueryData(startupConfigKey(false), { interface: {} });+ return client;+};++function mountIcons() {+ const icon32 = document.createElement('link');+ icon32.rel = 'icon';+ icon32.setAttribute('sizes', '32x32');+ icon32.href = 'assets/favicon-32x32.png';+ const icon16 = document.createElement('link');+ icon16.rel = 'icon';+ icon16.setAttribute('sizes', '16x16');+ icon16.href = 'assets/favicon-16x16.png';+ document.head.append(icon32, icon16);+ return { icon32, icon16 };+}++function mount(+ count: number,+ badgeEnabled = true,+ client: QueryClient = withLoadedConfig(new QueryClient()),+) {+ const settings = createStore();+ settings.set(unseenTabBadgeAtom, badgeEnabled);+ return renderHook((nextCount: number) => useUnseenBadge(nextCount), {+ initialProps: count,+ wrapper: ({ children }: { children: React.ReactNode }) => (+ <RecoilRoot>+ <QueryClientProvider client={client}>+ <JotaiProvider store={settings}>{children}</JotaiProvider>+ </QueryClientProvider>+ </RecoilRoot>+ ),+ });+}++describe('useUnseenBadge', () => {+ let icons: ReturnType<typeof mountIcons>;++ beforeEach(() => {+ document.title = 'LibreChat';+ icons = mountIcons();+ });++ afterEach(() => {+ icons.icon32.remove();+ icons.icon16.remove();+ });++ it('records the original href of every icon so each can be badged and restored', () => {+ mount(2);++ /* Firefox and 1x-DPI Chrome pick the 16x16 icon; badging only the 32x32 link+ leaves those browsers without a badge. `link.href` is the resolved original. */+ expect(icons.icon32.dataset.originalHref).toBe(icons.icon32.href);+ expect(icons.icon16.dataset.originalHref).toBe(icons.icon16.href);+ });++ /* A device that stored "on" must not badge in the window before an operator's `false` has+ arrived, so nothing is shown until the startup config has loaded. */+ it('shows no count until the deployment has answered', () => {+ const client = new QueryClient();+ const { rerender } = mount(3, true, client);++ expect(document.title).toBe('LibreChat');++ act(() => {+ client.setQueryData(startupConfigKey(false), { interface: {} });+ });+ rerender(3);++ expect(document.title).toBe('(3) LibreChat');+ });++ it('keeps the count off when the deployment disables the tab badge', () => {+ const client = new QueryClient();+ client.setQueryData(startupConfigKey(false), {+ interface: { replyNotifications: { tabBadge: false } },+ });+ mount(3, true, client);++ expect(document.title).toBe('LibreChat');+ });++ it('prefixes the title with the count and restores it at zero', () => {+ const { rerender } = mount(3);++ expect(document.title).toBe('(3) LibreChat');++ rerender(0);++ expect(document.title).toBe('LibreChat');+ });++ it('leaves a conversation title that legitimately starts with a count alone', () => {+ document.title = '(3) Notes';++ mount(0);++ expect(document.title).toBe('(3) Notes');+ });++ it('does not swallow a rename whose title starts with the active badge', async () => {+ /* Three unread and a conversation genuinely called "(3) Notes": matching on the prefix+ alone would mistake the user's own text for the badge and strip it later. */+ const { rerender } = mount(3);++ document.title = '(3) Notes';++ await waitFor(() => expect(document.title).toBe('(3) (3) Notes'));++ rerender(0);++ await waitFor(() => expect(document.title).toBe('(3) Notes'));+ });++ it('recomposes when another writer changes the title', async () => {+ const { rerender } = mount(1);++ document.title = 'Renamed Conversation';++ await waitFor(() => expect(document.title).toBe('(1) Renamed Conversation'));++ rerender(0);++ await waitFor(() => expect(document.title).toBe('Renamed Conversation'));+ });++ it('preserves an equal-valued canonical title write through count changes and unmount', () => {+ document.title = 'Notes';+ const { rerender, unmount } = mount(3);++ expect(document.title).toBe('(3) Notes');++ setDocumentTitle('(3) Notes', true);+ rerender(4);++ expect(document.title).toBe('(4) (3) Notes');++ unmount();++ expect(document.title).toBe('(3) Notes');+ });++ it('leaves the title and icons alone while the setting is off', async () => {+ mount(3, false);++ await waitFor(() => expect(document.title).toBe('LibreChat'));+ expect(icons.icon32.href).toContain('assets/favicon-32x32.png');+ });+});diff --git a/client/src/hooks/Conversations/__tests__/useUnseenConversations.spec.tsx b/client/src/hooks/Conversations/__tests__/useUnseenConversations.spec.tsxnew file mode 100644index 0000000000..17088a9b87--- /dev/null+++ b/client/src/hooks/Conversations/__tests__/useUnseenConversations.spec.tsx@@ -0,0 +1,694 @@+import React from 'react';+import { QueryKeys } from 'librechat-data-provider';+import { renderHook, act } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { TConversation } from 'librechat-data-provider';+import { applyServerReplyStamp, updateConvoInAllQueries } from '~/utils';+import useUnseenConversations from '../useUnseenConversations';++const listKeyActive = [QueryKeys.allConversations, { isArchived: false }];+const listKeyArchived = [QueryKeys.allConversations, { isArchived: true }];+const pinnedKey = [QueryKeys.pinnedConversations, { limit: 10 }];++const RESPONDED_AT = '2026-08-16T10:00:00.000Z';+const SEEN_AFTER = '2026-08-16T11:00:00.000Z';+const RESPONDED_AGAIN_AT = '2026-08-16T12:00:00.000Z';++function page(conversations: unknown[]) {+ return { pages: [{ conversations, nextCursor: null }], pageParams: [null] };+}++function setup() {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ return { ...renderHook(() => useUnseenConversations(), { wrapper }), queryClient };+}++describe('useUnseenConversations', () => {+ it('derives the unseen set from the cached lists', () => {+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([+ { conversationId: 'unseen-a', title: 'A', lastResponseAt: RESPONDED_AT },+ {+ conversationId: 'seen-a',+ title: 'S',+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: SEEN_AFTER,+ },+ { conversationId: 'never-replied', title: 'N' },+ ]),+ );+ });++ expect(result.current?.unseen).toEqual([+ { conversationId: 'unseen-a', title: 'A', lastResponseAt: RESPONDED_AT, flagged: false },+ ]);+ });++ it('records the reply stamps of seen conversations as the alerts baseline', () => {+ /* A seen conversation marked unread from another device re-enters the unseen set with the+ stamp it always had; only this record lets the alerts tell that from a new reply. */+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([+ { conversationId: 'unseen-a', title: 'A', lastResponseAt: RESPONDED_AT },+ {+ conversationId: 'seen-a',+ title: 'S',+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: SEEN_AFTER,+ },+ { conversationId: 'never-replied', title: 'N' },+ ]),+ );+ });++ expect(result.current?.stamps).toEqual([+ ['seen-a', RESPONDED_AT],+ ['unseen-a', RESPONDED_AT],+ ]);+ });++ it('dedupes a conversation cached in more than one list query', () => {+ const { result, queryClient } = setup();+ const convo = { conversationId: 'dup', title: 'D', lastResponseAt: RESPONDED_AT };++ act(() => {+ queryClient.setQueryData(listKeyActive, page([convo]));+ queryClient.setQueryData(listKeyArchived, page([convo]));+ });++ expect(result.current).toEqual({+ unseen: [{ conversationId: 'dup', title: 'D', lastResponseAt: RESPONDED_AT, flagged: false }],+ stamps: [['dup', RESPONDED_AT]],+ arrivalStamps: [],+ });+ });++ it('ignores cache events outside the conversation lists', () => {+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(listKeyActive, page([]));+ queryClient.setQueryData(+ [QueryKeys.messages, 'm1'],+ page([{ conversationId: 'not-a-list-row', title: 'M', lastResponseAt: RESPONDED_AT }]),+ );+ });++ expect(result.current).toEqual({ unseen: [], stamps: [], arrivalStamps: [] });+ });++ it('counts a pin that lives only in the pinned cache', () => {+ /* A pin older than the loaded chat pages is in no `allConversations` page, so leaving it+ out would show its dot while the tab count and the alerts never knew about it. */+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(listKeyActive, page([]));+ queryClient.setQueryData(pinnedKey, {+ conversations: [+ { conversationId: 'old-pin', title: 'Pinned', lastResponseAt: RESPONDED_AT },+ ],+ nextCursor: null,+ });+ });++ expect(result.current?.unseen).toEqual([+ { conversationId: 'old-pin', title: 'Pinned', lastResponseAt: RESPONDED_AT, flagged: false },+ ]);+ });++ it('records the first real reply to a conversation held only in the pinned cache', () => {+ const { result, queryClient } = setup();+ act(() => {+ queryClient.setQueryData(listKeyActive, page([]));+ queryClient.setQueryData(pinnedKey, {+ conversations: [{ conversationId: 'pin', title: 'Pinned' }],+ });+ });+ act(() => {+ queryClient.setQueryData(pinnedKey, {+ conversations: [{ conversationId: 'pin', title: 'Pinned', lastResponseAt: RESPONDED_AT }],+ });+ });+ expect(result.current?.arrivalStamps).toEqual([['pin', RESPONDED_AT]]);+ });+ it('records a first reply delivered by a local cache merge for a known user-only row', () => {+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([{ conversationId: 'user-only', title: 'User only' }]),+ );+ });+ expect(result.current?.unseen).toEqual([]);++ act(() => {+ applyServerReplyStamp(queryClient, 'user-only', { lastResponseAt: RESPONDED_AT });+ });++ expect(result.current?.arrivalStamps).toEqual([['user-only', RESPONDED_AT]]);+ expect(result.current?.unseen).toEqual([+ {+ conversationId: 'user-only',+ title: 'User only',+ lastResponseAt: RESPONDED_AT,+ flagged: false,+ },+ ]);+ });++ /* A title-sorted list leaves a replied row where it is, so a local merge can land its first+ reply on a later loaded page. Missing it there would add the stamp to the alerts baseline+ with no arrival behind it, and no later refresh could recover the chime. */+ it('records a first reply a local merge lands on a later loaded page', () => {+ const { result, queryClient } = setup();+ const titleSorted = [+ QueryKeys.allConversations,+ { isArchived: false, sortBy: 'title', sortDirection: 'asc' },+ ];++ act(() => {+ queryClient.setQueryData(titleSorted, {+ pages: [+ { conversations: [{ conversationId: 'first', title: 'A first' }], nextCursor: 'c1' },+ { conversations: [{ conversationId: 'later', title: 'Z later' }], nextCursor: null },+ ],+ pageParams: [null, 'c1'],+ });+ });++ act(() => {+ applyServerReplyStamp(queryClient, 'later', { lastResponseAt: RESPONDED_AT });+ });++ expect(result.current?.arrivalStamps).toEqual([['later', RESPONDED_AT]]);+ });++ it('does not record a stamp when a new cached row brings in backlog', () => {+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(listKeyActive, page([]));+ queryClient.setQueryData(+ listKeyActive,+ page([{ conversationId: 'backlog', title: 'Backlog', lastResponseAt: RESPONDED_AT }]),+ );+ });++ expect(result.current?.arrivalStamps).toEqual([]);+ });++ it('tags the explicit manual marker of a never-replied conversation', () => {+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([+ {+ conversationId: 'flagged-a',+ title: 'F',+ updatedAt: RESPONDED_AT,+ lastResponseAt: RESPONDED_AT,+ lastResponseIsManual: true,+ },+ {+ conversationId: 'replied-a',+ title: 'R',+ updatedAt: RESPONDED_AT,+ lastResponseAt: RESPONDED_AGAIN_AT,+ },+ ]),+ );+ });++ expect(result.current?.unseen).toEqual([+ {+ conversationId: 'flagged-a',+ title: 'F',+ lastResponseAt: RESPONDED_AT,+ flagged: true,+ },+ {+ conversationId: 'replied-a',+ title: 'R',+ lastResponseAt: RESPONDED_AGAIN_AT,+ flagged: false,+ },+ ]);+ });++ it('keeps a manual marker out of the alerts baseline', () => {+ /* A flagged row is not an arrival, and baselining its marker would make the reply that+ later lands look like a stamp the tab had already accounted for. */+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([+ {+ conversationId: 'flagged-a',+ title: 'F',+ updatedAt: RESPONDED_AT,+ lastResponseAt: RESPONDED_AT,+ lastResponseIsManual: true,+ },+ ]),+ );+ });++ expect(result.current?.unseen).toHaveLength(1);+ act(() => {+ updateConvoInAllQueries(+ queryClient,+ 'flagged-a',+ (convo) =>+ ({+ conversationId: convo.conversationId,+ title: 'Renamed',+ }) as TConversation,+ );+ });+ expect(result.current?.unseen[0]).toMatchObject({+ conversationId: 'flagged-a',+ flagged: true,+ });+ expect(result.current?.stamps).toEqual([]);++ /* The reply arrives, stamped apart from the activity date it moved. */+ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([+ {+ conversationId: 'flagged-a',+ title: 'F',+ updatedAt: RESPONDED_AT,+ lastResponseAt: RESPONDED_AGAIN_AT,+ },+ ]),+ );+ });++ expect(result.current?.unseen).toEqual([+ {+ conversationId: 'flagged-a',+ title: 'F',+ lastResponseAt: RESPONDED_AGAIN_AT,+ flagged: false,+ },+ ]);+ expect(result.current?.stamps).toEqual([['flagged-a', RESPONDED_AGAIN_AT]]);+ });++ it('stops counting an unmounted variant once it has gone unanswered too long', () => {+ /* Deleted or archived on another device: refetching the mounted list drops the row there,+ while the leftover variant keeps it. Absence never supersedes presence in the scan, so+ counting the leftover would keep a phantom dot in the badge. Local cache writes must not+ renew it either, which is why the age is measured from the variant's last answer. */+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyArchived,+ page([{ conversationId: 'gone', title: 'G', lastResponseAt: RESPONDED_AT }]),+ );+ queryClient.setQueryData(+ listKeyActive,+ page([{ conversationId: 'unseen-a', title: 'A', lastResponseAt: RESPONDED_AT }]),+ );+ });++ expect(result.current?.unseen.map((c) => c.conversationId).sort()).toEqual([+ 'gone',+ 'unseen-a',+ ]);++ /* The sidebar is looking at the active variant; only the other one is a leftover. */+ const mounted = queryClient.getQueryCache().find(listKeyActive);+ jest.spyOn(mounted!, 'getObserversCount').mockReturnValue(1);++ const now = jest.spyOn(Date, 'now');+ try {+ now.mockReturnValue(Date.now() + 6 * 60_000);+ act(() => {+ /* An unrelated local write touches every variant, including the leftover. */+ queryClient.setQueryData(+ listKeyActive,+ page([{ conversationId: 'unseen-a', title: 'A', lastResponseAt: RESPONDED_AGAIN_AT }]),+ );+ queryClient.setQueryData(+ listKeyArchived,+ page([{ conversationId: 'gone', title: 'G', lastResponseAt: RESPONDED_AT }]),+ );+ });++ expect(result.current?.unseen.map((c) => c.conversationId)).toEqual(['unseen-a']);+ } finally {+ now.mockRestore();+ }+ });++ it('counts a conversation held in both caches once', () => {+ const { result, queryClient } = setup();+ const convo = { conversationId: 'both', title: 'B', lastResponseAt: RESPONDED_AT };++ act(() => {+ queryClient.setQueryData(listKeyActive, page([convo]));+ queryClient.setQueryData(pinnedKey, { conversations: [convo], nextCursor: null });+ });++ expect(result.current?.unseen).toHaveLength(1);+ expect(result.current?.stamps).toHaveLength(1);+ });++ it('reports null until a conversation list has actually resolved', () => {+ /* An empty result and an unloaded one look the same from the outside; the alerts have to+ tell them apart or a backlog arriving late reads as a burst of new replies. */+ const { result, queryClient } = setup();++ expect(result.current).toBeNull();++ act(() => {+ queryClient.setQueryData(listKeyActive, page([]));+ });++ expect(result.current).toEqual({ unseen: [], stamps: [], arrivalStamps: [] });+ });+ it('keeps server mark-unread authority after a local chat update', async () => {+ const { result, queryClient } = setup();+ const seen = {+ conversationId: 'remote',+ title: 'Remote',+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: SEEN_AFTER,+ };+ const unread = { conversationId: 'remote', title: 'Remote', lastResponseAt: RESPONDED_AT };++ await act(async () => {+ await queryClient.fetchQuery({+ queryKey: listKeyActive,+ queryFn: async () => page([unread]),+ staleTime: Infinity,+ });+ queryClient.setQueryData(listKeyArchived, page([seen]));+ });++ act(() => {+ updateConvoInAllQueries(queryClient, 'remote', (convo) => ({ ...convo, title: 'Renamed' }));+ });++ expect(result.current?.unseen).toEqual([+ {+ conversationId: 'remote',+ title: 'Renamed',+ lastResponseAt: RESPONDED_AT,+ flagged: false,+ },+ ]);+ });++ it.each([true, false])(+ 'keeps the newer server read state when an older variant arrives last (seen: %s)',+ async (isSeen) => {+ const { result, queryClient } = setup();+ const row = { conversationId: 'remote', title: 'Remote', lastResponseAt: RESPONDED_AT };+ const seen = { ...row, lastSeenAt: SEEN_AFTER };+ const older = isSeen ? row : seen;+ const newer = isSeen ? seen : row;+ let resolveOlder!: () => void;+ const olderResponse = new Promise<void>((resolve) => {+ resolveOlder = resolve;+ });+ const now = jest.spyOn(Date, 'now').mockReturnValue(1_000);+ try {+ const olderFetch = queryClient.fetchQuery({+ queryKey: [QueryKeys.allConversations, { tags: ['work'] }],+ queryFn: async () => {+ await olderResponse;+ return page([older]);+ },+ });+ await act(async () => {+ await queryClient.fetchQuery({+ queryKey: listKeyActive,+ queryFn: async () => page([newer]),+ });+ });+ now.mockReturnValue(2_000);+ await act(async () => {+ resolveOlder();+ await olderFetch;+ });+ expect(result.current?.unseen.map((convo) => convo.conversationId)).toEqual(+ isSeen ? [] : ['remote'],+ );+ } finally {+ now.mockRestore();+ }+ },+ );++ it('reports a fresh reply to an already-unseen conversation', () => {+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([{ conversationId: 'unseen-a', title: 'A', lastResponseAt: RESPONDED_AT }]),+ );+ });+ const before = result.current;++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([{ conversationId: 'unseen-a', title: 'A', lastResponseAt: RESPONDED_AGAIN_AT }]),+ );+ });++ expect(result.current).not.toBe(before);+ expect(result.current?.unseen).toEqual([+ {+ conversationId: 'unseen-a',+ title: 'A',+ lastResponseAt: RESPONDED_AGAIN_AT,+ flagged: false,+ },+ ]);+ });+ it('records a first-page server reply arrival even when its clock is behind another row', async () => {+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([+ { conversationId: 'known', title: 'Known', lastResponseAt: RESPONDED_AGAIN_AT },+ { conversationId: 'new', title: 'New' },+ ]),+ );+ });++ await act(async () => {+ await queryClient.fetchQuery({+ queryKey: listKeyActive,+ queryFn: async () =>+ page([+ { conversationId: 'known', title: 'Known', lastResponseAt: RESPONDED_AGAIN_AT },+ { conversationId: 'new', title: 'New', lastResponseAt: RESPONDED_AT },+ ]),+ });+ });++ expect(result.current?.arrivalStamps).toEqual([['new', RESPONDED_AT]]);+ });+ it('records a reply to a newly discovered first-page row from a server refetch', async () => {+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([{ conversationId: 'known', title: 'Known', lastResponseAt: RESPONDED_AGAIN_AT }]),+ );+ });++ await act(async () => {+ await queryClient.fetchQuery({+ queryKey: listKeyActive,+ queryFn: async () =>+ page([+ { conversationId: 'known', title: 'Known', lastResponseAt: RESPONDED_AGAIN_AT },+ {+ conversationId: 'new',+ title: 'New',+ lastResponseAt: RESPONDED_AT,+ updatedAt: RESPONDED_AT,+ },+ ]),+ });+ });++ expect(result.current?.arrivalStamps).toEqual([['new', RESPONDED_AT]]);+ });++ it('keeps metadata-promoted unread backlog out of reply arrivals', async () => {+ const { result, queryClient } = setup();+ act(() => {+ queryClient.setQueryData(listKeyArchived, page([]));+ });+ await act(async () => {+ await queryClient.fetchQuery({+ queryKey: listKeyActive,+ meta: { replyDiscovery: ['renamed-backlog'] },+ queryFn: async () =>+ page([+ {+ conversationId: 'renamed-backlog',+ title: 'Renamed on another device',+ lastResponseAt: RESPONDED_AT,+ updatedAt: RESPONDED_AGAIN_AT,+ },+ ]),+ });+ });++ expect(result.current?.unseen.map((convo) => convo.conversationId)).toEqual([+ 'renamed-backlog',+ ]);+ expect(result.current?.arrivalStamps).toEqual([]);+ });++ it('announces only the named discovery on a query it has never observed', async () => {+ /* The watcher creates this query to reveal one conversation; the rest of its first page is+ backlog this session has never seen, and greeting the user with all of it is the bug. */+ const { result, queryClient } = setup();+ act(() => {+ queryClient.setQueryData(listKeyArchived, page([]));+ });++ await act(async () => {+ await queryClient.fetchQuery({+ queryKey: [...listKeyActive, 'reply-discovery'],+ meta: { replyDiscovery: ['discovered'] },+ queryFn: async () =>+ page([+ {+ conversationId: 'discovered',+ title: 'Discovered',+ lastResponseAt: RESPONDED_AGAIN_AT,+ updatedAt: RESPONDED_AGAIN_AT,+ },+ {+ conversationId: 'backlog',+ title: 'Old backlog',+ lastResponseAt: RESPONDED_AT,+ updatedAt: RESPONDED_AT,+ },+ ]),+ });+ });++ expect(result.current?.arrivalStamps).toEqual([['discovered', RESPONDED_AGAIN_AT]]);+ });++ it('does not treat pagination or a newly mounted variant as a reply arrival', () => {+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(listKeyActive, page([{ conversationId: 'known', title: 'Known' }]));+ });+ act(() => {+ queryClient.setQueryData(listKeyActive, {+ pages: [+ { conversations: [{ conversationId: 'known', title: 'Known' }], nextCursor: 'next' },+ {+ conversations: [+ { conversationId: 'backlog', title: 'Backlog', lastResponseAt: RESPONDED_AT },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [null, 'next'],+ });+ queryClient.setQueryData(+ listKeyArchived,+ page([{ conversationId: 'variant', title: 'Variant', lastResponseAt: RESPONDED_AT }]),+ );+ });++ expect(result.current?.arrivalStamps).toEqual([]);+ });++ it('reports a fresh reply that was caught up the moment it landed', () => {+ /* The row never turns unseen, but the alerts baseline still has to move with it, or a+ later mark-as-unread from another device would announce this reply as a new one. */+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([+ {+ conversationId: 'seen-a',+ title: 'S',+ lastResponseAt: RESPONDED_AT,+ lastSeenAt: SEEN_AFTER,+ },+ ]),+ );+ });+ const before = result.current;++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([+ {+ conversationId: 'seen-a',+ title: 'S',+ lastResponseAt: RESPONDED_AGAIN_AT,+ lastSeenAt: RESPONDED_AGAIN_AT,+ },+ ]),+ );+ });++ expect(result.current).not.toBe(before);+ expect(result.current?.stamps).toEqual([['seen-a', RESPONDED_AGAIN_AT]]);+ });++ it('keeps the state identity when nothing relevant changed', () => {+ const { result, queryClient } = setup();++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([{ conversationId: 'unseen-a', title: 'A', lastResponseAt: RESPONDED_AT }]),+ );+ });+ const before = result.current;++ act(() => {+ queryClient.setQueryData(+ listKeyActive,+ page([{ conversationId: 'unseen-a', title: 'A', lastResponseAt: RESPONDED_AT }]),+ );+ });++ expect(result.current).toBe(before);+ });+});diff --git a/client/src/hooks/Conversations/focusLease.ts b/client/src/hooks/Conversations/focusLease.tsnew file mode 100644index 0000000000..ccf5c86171--- /dev/null+++ b/client/src/hooks/Conversations/focusLease.ts@@ -0,0 +1,129 @@+/**+ * Tells every LibreChat tab whether the user is looking at one of them.+ *+ * `document.hasFocus()` only answers for the tab asking, so with two tabs open the unfocused one+ * would chime and post desktop notifications while the user reads the focused one, which is+ * exactly what the settings promise not to do. The focused tab publishes a lease through+ * localStorage, the one coordination channel already shared by these alerts, and the rest read it+ * before announcing.+ *+ * The lease is refreshed on a slow heartbeat and cleared on blur, so a tab that is killed without+ * running its cleanup stops suppressing the others within one heartbeat window rather than for+ * the rest of the session.+ */+const FOCUS_LEASE_KEY = 'replyAlerts:focusedAt';+const FOCUS_LEASE_HEARTBEAT_MS = 20_000;+const FOCUS_LEASE_TTL_MS = 60_000;++/** Identifies this tab's own lease. Focus moves before the losing tab's blur handler runs, so a+ * release that did not check ownership would delete the lease the newly focused tab had just+ * written, and every background tab would be free to announce until its next heartbeat. */+const tabId = Math.random().toString(36).slice(2);++type Lease = { owner: string; at: number };++const readLease = (): Lease | null => {+ try {+ const raw = window.localStorage.getItem(FOCUS_LEASE_KEY);+ if (raw == null) {+ return null;+ }+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed !== 'object' || parsed === null) {+ return null;+ }+ const { owner, at } = parsed as Partial<Lease>;+ return typeof owner === 'string' && typeof at === 'number' && Number.isFinite(at)+ ? { owner, at }+ : null;+ } catch {+ /* Private windows, quota failures and anything a previous version wrote: fall back to+ per-tab focus, which is what this tab did before the lease existed. */+ return null;+ }+};++const writeLease = (): void => {+ try {+ window.localStorage.setItem(FOCUS_LEASE_KEY, JSON.stringify({ owner: tabId, at: Date.now() }));+ } catch {+ /* See above. */+ }+};++const clearOwnLease = (): void => {+ if (readLease()?.owner !== tabId) {+ return;+ }+ try {+ window.localStorage.removeItem(FOCUS_LEASE_KEY);+ } catch {+ /* See above. */+ }+};++/**+ * How long another tab of this origin keeps focus by its lease, or null when none holds one. This+ * tab's own lease never counts: the caller checks its own focus first, so reading one here means+ * a release did not land. A tab killed without firing+ * blur or pagehide leaves its lease behind, and nothing announces its lapse, so a caller holding+ * an arrival back for it has to schedule its own recheck.+ */+export const anotherTabLeaseRemainingMs = (): number | null => {+ const lease = readLease();+ if (lease == null || lease.owner === tabId) {+ return null;+ }+ const remaining = FOCUS_LEASE_TTL_MS - (Date.now() - lease.at);+ return remaining > 0 ? remaining : null;+};++/** Calls back whenever another tab writes or clears the lease, such as on its blur. */+export const subscribeToFocusLease = (onChange: () => void): (() => void) => {+ const listener = (event: StorageEvent) => {+ if (event.key === FOCUS_LEASE_KEY || event.key === null) {+ onChange();+ }+ };+ window.addEventListener('storage', listener);+ return () => window.removeEventListener('storage', listener);+};++/** Publishes the lease for as long as this tab holds focus. */+export const startFocusLease = (): (() => void) => {+ let heartbeat: number | null = null;++ const stopHeartbeat = () => {+ if (heartbeat !== null) {+ window.clearInterval(heartbeat);+ heartbeat = null;+ }+ };++ const hold = () => {+ writeLease();+ if (heartbeat === null) {+ heartbeat = window.setInterval(writeLease, FOCUS_LEASE_HEARTBEAT_MS);+ }+ };++ const release = () => {+ stopHeartbeat();+ clearOwnLease();+ };++ if (document.hasFocus()) {+ hold();+ }++ window.addEventListener('focus', hold);+ window.addEventListener('blur', release);+ window.addEventListener('pagehide', release);++ return () => {+ window.removeEventListener('focus', hold);+ window.removeEventListener('blur', release);+ window.removeEventListener('pagehide', release);+ release();+ };+};diff --git a/client/src/hooks/Conversations/index.ts b/client/src/hooks/Conversations/index.tsindex 2659ace457..8b99b22fd4 100644--- a/client/src/hooks/Conversations/index.ts+++ b/client/src/hooks/Conversations/index.ts@@ -1,5 +1,17 @@export { default as usePresets } from './usePresets';export { default as useGetSender } from './useGetSender';+export { default as useUnseenBadge } from './useUnseenBadge';+export {+ default as useReplyAlerts,+ unlockReplyNotificationSound,+ requestReplyNotificationPermission,+} from './useReplyAlerts';+export {+ unseenTabBadgeAtom,+ replyNotificationsAtom,+ replyNotificationSoundAtom,+} from './replyNotificationSettings';+export { default as useReplyWatcher } from './useReplyWatcher';export { default as useDefaultConvo } from './useDefaultConvo';export { default as useSearchEnabled } from './useSearchEnabled';export { default as useGenerateConvo } from './useGenerateConvo';@@ -9,5 +21,7 @@ export { default as useBookmarkSuccess } from './useBookmarkSuccess';export { default as useNavigateToConvo } from './useNavigateToConvo';export { default as useSetIndexOptions } from './useSetIndexOptions';export { default as useParameterEffects } from './useParameterEffects';+export { default as useConversationSeen } from './useConversationSeen';export { default as useUpdateTagsInConvo } from './useUpdateTagsInConvo';export { default as useExportConversation } from './useExportConversation';+export { default as useUnseenConversations } from './useUnseenConversations';diff --git a/client/src/hooks/Conversations/notificationNavigation.ts b/client/src/hooks/Conversations/notificationNavigation.tsnew file mode 100644index 0000000000..09d901f1ea--- /dev/null+++ b/client/src/hooks/Conversations/notificationNavigation.ts@@ -0,0 +1,38 @@+/**+ * A desktop notification click focuses this window on its way to another conversation.+ *+ * That focus is not the user catching up on whatever happened to be open: they are leaving it+ * for the chat the notification named, and its reply was never on screen. The click flags the+ * focus event it is about to cause, and the seen trigger consumes the flag instead of+ * acknowledging a reply nobody read.+ */+let suppressedAt: number | null = null;++/**+ * How long the flag stays good for.+ *+ * `window.focus()` is a request, not a guarantee: a browser that refuses to raise the window+ * produces no focus event at all, and an unbounded flag would then be spent on the next genuine+ * focus, minutes later, silently withholding that conversation's acknowledgement. A focus the+ * click did cause arrives in the same task or the one after it, so anything beyond a couple of+ * seconds belongs to the user rather than to the notification.+ */+const SUPPRESSION_TTL_MS = 2_000;++/** Only meaningful while the window is unfocused, which is the only time alerts fire; a click+ * that raises no focus event would otherwise leave the flag set for a later, genuine one. */+export const suppressFocusAcknowledgement = (): void => {+ if (document.hasFocus()) {+ return;+ }+ suppressedAt = Date.now();+};++export const consumeFocusSuppression = (): boolean => {+ if (suppressedAt === null) {+ return false;+ }+ const isLive = Date.now() - suppressedAt < SUPPRESSION_TTL_MS;+ suppressedAt = null;+ return isLive;+};diff --git a/client/src/hooks/Conversations/replyNotificationSettings.ts b/client/src/hooks/Conversations/replyNotificationSettings.tsnew file mode 100644index 0000000000..97806a851f--- /dev/null+++ b/client/src/hooks/Conversations/replyNotificationSettings.ts@@ -0,0 +1,130 @@+import { useMemo } from 'react';+import { useAtomValue } from 'jotai';+import type { TReplyNotificationsConfig } from 'librechat-data-provider';+import { createStorageAtom } from '~/store/jotai-utils';+import { useGetStartupConfig } from '~/data-provider';++/**+ * Reply-notification preferences, owned by the hooks in this directory: the settings toggles+ * write them and `useReplyAlerts`, `useReplyWatcher` and `useUnseenBadge` are their only readers,+ * so they live with the feature rather than in the global store.+ *+ * Per device rather than per account: browser notification permission and audio output are+ * properties of the machine you are sitting at, so wanting a chime on a laptop implies nothing+ * about wanting one on a phone. The seen state they react to does sync.+ */+export const unseenTabBadgeAtom = createStorageAtom<boolean>('unseenTabBadge', true);+export const replyNotificationsAtom = createStorageAtom<boolean>('replyNotifications', false);+export const replyNotificationSoundAtom = createStorageAtom<boolean>(+ 'replyNotificationSound',+ false,+);++/**+ * What the deployment allows, independent of what this device prefers.+ *+ * Mirrors `interface.replyNotifications` in `librechat.yaml`. The fallbacks reproduce the+ * shipped behavior for a server that predates the setting or answers without it, so a client+ * held against an older backend behaves as it did before the gate existed.+ */+export const REPLY_NOTIFICATION_DEFAULTS: Required<TReplyNotificationsConfig> = {+ tabBadge: true,+ desktop: true,+ sound: true,+ pollLimit: 100,+ pollIntervalMs: 30_000,+ focusedRefreshMs: 300_000,+};++const isWithin =+ (min: number, max: number) =>+ (value: unknown): value is number =>+ typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max;++const isBounded = isWithin(1, 100);+const isPollInterval = isWithin(10_000, 600_000);+const isFocusedRefresh = isWithin(60_000, 300_000);++/** Nothing is permitted until the deployment has answered. */+const PENDING_CAPABILITIES: Required<TReplyNotificationsConfig> = {+ ...REPLY_NOTIFICATION_DEFAULTS,+ tabBadge: false,+ desktop: false,+ sound: false,+};++/**+ * The reply-alert capabilities this deployment permits.+ *+ * Off until the startup config has loaded: a device that stored "on" would otherwise badge,+ * poll or notify in the window before an operator's `false` arrives. Once a config is in hand,+ * a missing field means a backend that predates the setting, and reads as the shipped default.+ *+ * Every field is re-checked rather than trusted from the payload: a cached startup config can+ * outlive the schema that produced it, and an out-of-range poll limit would otherwise reach the+ * list request as a page size the server has to clamp.+ */+export function useReplyNotificationCapabilities(): Required<TReplyNotificationsConfig> {+ const { data: startupConfig } = useGetStartupConfig();+ const loaded = startupConfig != null;+ const configured = startupConfig?.interface?.replyNotifications;+ return useMemo(() => {+ if (!loaded) {+ return PENDING_CAPABILITIES;+ }+ return {+ tabBadge: configured?.tabBadge !== false,+ desktop: configured?.desktop !== false,+ sound: configured?.sound !== false,+ pollLimit: isBounded(configured?.pollLimit)+ ? configured.pollLimit+ : REPLY_NOTIFICATION_DEFAULTS.pollLimit,+ pollIntervalMs: isPollInterval(configured?.pollIntervalMs)+ ? configured.pollIntervalMs+ : REPLY_NOTIFICATION_DEFAULTS.pollIntervalMs,+ focusedRefreshMs: isFocusedRefresh(configured?.focusedRefreshMs)+ ? configured.focusedRefreshMs+ : REPLY_NOTIFICATION_DEFAULTS.focusedRefreshMs,+ };+ }, [+ loaded,+ configured?.tabBadge,+ configured?.desktop,+ configured?.sound,+ configured?.pollLimit,+ configured?.pollIntervalMs,+ configured?.focusedRefreshMs,+ ]);+}++/** What this device wants, once the deployment's gate has been applied to it. */+export interface ReplyAlertPreferences {+ badgeEnabled: boolean;+ notificationsEnabled: boolean;+ soundEnabled: boolean;+ pollLimit: number;+ pollIntervalMs: number;+ focusedRefreshMs: number;+}++/**+ * A capability the operator turned off reads as off here whatever this device stored, so a+ * preference saved before the gate closed cannot keep announcing replies.+ */+export function useReplyAlertPreferences(): ReplyAlertPreferences {+ const capabilities = useReplyNotificationCapabilities();+ const badgePreferred = useAtomValue(unseenTabBadgeAtom);+ const notificationsPreferred = useAtomValue(replyNotificationsAtom);+ const soundPreferred = useAtomValue(replyNotificationSoundAtom);+ return useMemo(+ () => ({+ badgeEnabled: capabilities.tabBadge && badgePreferred,+ notificationsEnabled: capabilities.desktop && notificationsPreferred,+ soundEnabled: capabilities.sound && soundPreferred,+ pollLimit: capabilities.pollLimit,+ pollIntervalMs: capabilities.pollIntervalMs,+ focusedRefreshMs: capabilities.focusedRefreshMs,+ }),+ [capabilities, badgePreferred, notificationsPreferred, soundPreferred],+ );+}diff --git a/client/src/hooks/Conversations/useConversationSeen.ts b/client/src/hooks/Conversations/useConversationSeen.tsnew file mode 100644index 0000000000..36601ea28b--- /dev/null+++ b/client/src/hooks/Conversations/useConversationSeen.ts@@ -0,0 +1,327 @@+import { useRef, useEffect, useCallback } from 'react';+import { useQueryClient } from '@tanstack/react-query';+import { Constants, QueryKeys } from 'librechat-data-provider';+import {+ findConvoInAllQueries,+ hasLocallyCommittedReply,+ hasServerFetchedReply,+ isConversationUnseen,+} from '~/utils';+import { consumeFocusSuppression } from './notificationNavigation';+import { useMarkConversationSeenMutation } from '~/data-provider';++/**+ * Records that the user has caught up with a conversation's newest message.+ *+ * "Seen" deliberately means the newest message reached the viewport while the tab was focused,+ * not merely that the route is open, so a backgrounded tab restoring on reload does not silently+ * clear every indicator.+ *+ * Five events can satisfy those conditions, and all five are already available without polling:+ * the messages-end intersection flipping, a response finishing while the user sits at the bottom,+ * the window regaining focus on a conversation left open, the list cache itself reporting the+ * conversation (a direct-URL open fires the initial intersection before the list query resolves),+ * and the messages query settling a revalidation (a warm-cache open reports the bottom of the+ * old tree before the reply it is acknowledging has rendered). Each one re-checks imperatively+ * against the cached list rather than subscribing to it, which keeps the check off the render+ * path.+ *+ * The unseen check is also the cost guard: re-reading a conversation already caught up sends+ * nothing.+ */+export default function useConversationSeen(+ conversationId: string | undefined,+ isSubmitting: boolean,+ measureNearBottom?: () => boolean | null,+ isResponseRendered?: (messageId: string) => boolean,+) {+ const queryClient = useQueryClient();+ const { mutate: markSeen } = useMarkConversationSeenMutation();+ const isNearBottomRef = useRef(false);+ /** Read from the deferred revalidation check, which outlives the render that created it. */+ const measureRef = useRef(measureNearBottom);+ measureRef.current = measureNearBottom;+ const pendingFrameRef = useRef<number | null>(null);+ /** The list stamp observed when the current messages fetch began. A later stamp must not be+ * credited by that fetch merely because it arrived before the success notification. */+ const fetchStartStampRef = useRef<Map<string, string | undefined>>(new Map());+ /** A list stamp can arrive after a successful, but stale, messages query. Keep one+ * revalidation in flight per stamp rather than starting another request for every cache event. */+ const requestedMessagesRef = useRef<Map<string, string>>(new Map());+ /** Set only after the messages success event has had two frames to commit and paint. */+ const renderedMessagesRef = useRef<Map<string, string>>(new Map());+ /** The last reply each conversation was acknowledged for. A failed write rolls the cache+ * back to unseen, which is itself a cache event this hook listens to, so without this the+ * rejection would immediately re-arm the trigger and spin requests for as long as the+ * network keeps refusing them. Re-armed by a genuinely newer reply, or by refocusing. */+ const attemptedRef = useRef<Map<string, string | undefined>>(new Map());+ const markSeenRef = useRef<() => void>(() => undefined);+ const isResponseRenderedRef = useRef(isResponseRendered);+ isResponseRenderedRef.current = isResponseRendered;+ /** Proof that the stamped reply is the one on screen. The active MessagesView scopes the+ * lookup to its rendered tree; the document fallback keeps the hook usable for callers that+ * own no content ref, while still requiring the row's committed body rather than a+ * progressive placeholder.+ *+ * Manual markers name no message, and a row stamped before reply identity existed cannot be+ * bound to a branch either; both fall back to the history-fetch proof rather than stranding a+ * dot no acknowledgement could ever clear. */+ const replyBranchIsVisible = useCallback(+ (convo: { lastResponseIsManual?: boolean; lastResponseMessageId?: string } | undefined) => {+ const messageId = convo?.lastResponseMessageId;+ if (convo?.lastResponseIsManual === true || !messageId) {+ return true;+ }+ if (isResponseRenderedRef.current) {+ return isResponseRenderedRef.current(messageId);+ }+ const body = document+ .getElementById(messageId)+ ?.querySelector('[data-testid="message-body"]');+ return (+ body != null && (body.childElementCount > 0 || (body.textContent?.trim().length ?? 0) > 0)+ );+ },+ [],+ );++ const scheduleRenderedCheck = useCallback(+ (expectedStamp: string | undefined, proofSource?: 'local' | 'server') => {+ if (!conversationId) {+ return;+ }+ if (pendingFrameRef.current != null) {+ window.cancelAnimationFrame(pendingFrameRef.current);+ }+ pendingFrameRef.current = window.requestAnimationFrame(() => {+ pendingFrameRef.current = window.requestAnimationFrame(() => {+ pendingFrameRef.current = null;+ const cached = findConvoInAllQueries(queryClient, conversationId);+ const messagesState = queryClient.getQueryState([QueryKeys.messages, conversationId]);+ const messagesReady =+ messagesState?.status === 'success' && messagesState.fetchStatus === 'idle';+ const proofStillHolds =+ expectedStamp != null &&+ ((proofSource === 'local' &&+ hasLocallyCommittedReply(queryClient, conversationId, expectedStamp)) ||+ (proofSource === 'server' &&+ hasServerFetchedReply(queryClient, conversationId, expectedStamp)));+ const responseIsRendered = replyBranchIsVisible(cached);+ if (+ expectedStamp != null &&+ messagesReady &&+ cached?.lastResponseAt === expectedStamp &&+ isConversationUnseen(cached) &&+ responseIsRendered &&+ (proofSource == null ? true : cached.lastResponseIsManual !== true && proofStillHolds)+ ) {+ renderedMessagesRef.current.set(conversationId, expectedStamp);+ }+ const measured = measureRef.current?.() ?? null;+ if (measured != null) {+ isNearBottomRef.current = measured;+ }+ markSeenRef.current();+ });+ });+ },+ [conversationId, queryClient, replyBranchIsVisible],+ );++ const markSeenIfCaughtUp = useCallback(+ (retryMessages = false) => {+ if (!conversationId || conversationId === Constants.NEW_CONVO) {+ return;+ }+ if (!isNearBottomRef.current || !document.hasFocus()) {+ return;+ }+ const cached = findConvoInAllQueries(queryClient, conversationId);+ if (!isConversationUnseen(cached)) {+ return;+ }+ const { lastResponseAt } = cached ?? {};+ if (!lastResponseAt) {+ return;+ }++ /* A list/point cache can resolve before the active messages query mounts, or after its+ * cached tree has gone stale. Neither case proves that the reply was rendered. Every real+ * reply therefore waits for a successful messages fetch and its post-render measurement. */+ const messagesKey = [QueryKeys.messages, conversationId];+ const messagesQueryState = queryClient.getQueryState(messagesKey);+ if (messagesQueryState == null) {+ return;+ }+ if (messagesQueryState.status === 'error') {+ if (retryMessages && requestedMessagesRef.current.get(conversationId) !== lastResponseAt) {+ requestedMessagesRef.current.set(conversationId, lastResponseAt);+ void queryClient.invalidateQueries(messagesKey).catch(() => undefined);+ }+ return;+ }+ if (messagesQueryState.fetchStatus !== 'idle') {+ return;+ }++ const renderedStamp = renderedMessagesRef.current.get(conversationId);+ const isManualMarker = cached?.lastResponseIsManual === true;+ const hasLocalProof = hasLocallyCommittedReply(queryClient, conversationId, lastResponseAt);+ const hasServerProof = hasServerFetchedReply(queryClient, conversationId, lastResponseAt);+ if (!isManualMarker && (hasLocalProof || hasServerProof) && !replyBranchIsVisible(cached)) {+ /* A stamped history cache can still describe a hidden sibling branch, or a progressive+ * row whose body has not committed. Neither is safe to acknowledge and neither should+ * trigger a second history request. */+ return;+ }+ if (isManualMarker && renderedStamp !== lastResponseAt) {+ /* Synthetic markers carry no message identity. The successful active history query and+ * the two-frame render gate are the route/scroll proof for these list-only events. */+ scheduleRenderedCheck(lastResponseAt);+ return;+ }+ if (+ renderedStamp !== lastResponseAt &&+ !isManualMarker &&+ (hasLocalProof || hasServerProof)+ ) {+ /* A terminal SSE event or a server fetch paired this exact cache object with the reply.+ * It is proof only after the same two-frame commit/paint delay as a fetch. */+ scheduleRenderedCheck(lastResponseAt, hasLocalProof ? 'local' : 'server');+ return;+ }++ if (renderedStamp !== lastResponseAt) {+ if (isManualMarker) {+ return;+ }+ if (requestedMessagesRef.current.get(conversationId) === lastResponseAt) {+ /* The requested fetch succeeded, but its cache event has not painted yet. */+ return;+ }+ requestedMessagesRef.current.set(conversationId, lastResponseAt);+ void queryClient.invalidateQueries(messagesKey).catch(() => undefined);+ return;+ }++ if (+ attemptedRef.current.has(conversationId) &&+ attemptedRef.current.get(conversationId) === lastResponseAt+ ) {+ return;+ }+ attemptedRef.current.set(conversationId, lastResponseAt);+ /* Names the reply that is actually on screen: the server acknowledges that one and no+ * newer, so a reply persisted from another device mid-request stays unseen. */+ markSeen({ conversationId, lastResponseAt });+ },+ [conversationId, queryClient, markSeen, scheduleRenderedCheck, replyBranchIsVisible],+ );++ markSeenRef.current = markSeenIfCaughtUp;++ /** Refocusing is a deliberate return to the conversation, and a human-paced one, so it is+ * the right moment to let a write or message refresh that failed while offline try again. */+ const retryOnFocus = useCallback(() => {+ if (consumeFocusSuppression()) {+ return;+ }+ attemptedRef.current.clear();+ if (conversationId) {+ requestedMessagesRef.current.delete(conversationId);+ fetchStartStampRef.current.delete(conversationId);+ }+ markSeenIfCaughtUp(true);+ }, [conversationId, markSeenIfCaughtUp]);++ /** Stable across renders so the memoized scroll observer is not torn down on every check. */+ const reportNearBottom = useCallback(+ (isNearBottom: boolean) => {+ isNearBottomRef.current = isNearBottom;+ markSeenIfCaughtUp();+ },+ [markSeenIfCaughtUp],+ );++ /* A fresh conversation's scroll position is unknown until its observer reports; inheriting+ * "near bottom" from the previous conversation would mark it seen sight unseen.+ * Arriving also re-arms the attempt guard for this conversation: leaving and coming back is+ * a deliberate, human-paced return, the same reason refocusing re-arms it, and the hook+ * outlives the route so a write that failed here would otherwise stay suppressed. */+ useEffect(() => {+ isNearBottomRef.current = false;+ if (conversationId) {+ attemptedRef.current.delete(conversationId);+ requestedMessagesRef.current.delete(conversationId);+ fetchStartStampRef.current.delete(conversationId);+ renderedMessagesRef.current.delete(conversationId);+ }+ }, [conversationId]);++ useEffect(() => {+ if (isSubmitting) {+ return;+ }+ markSeenIfCaughtUp();+ }, [isSubmitting, markSeenIfCaughtUp]);++ useEffect(() => {+ window.addEventListener('focus', retryOnFocus);+ return () => window.removeEventListener('focus', retryOnFocus);+ }, [retryOnFocus]);++ useEffect(() => {+ if (!conversationId || conversationId === Constants.NEW_CONVO) {+ return;+ }+ const unsubscribe = queryClient.getQueryCache().subscribe((event) => {+ /* Every root the lookup reads. An old pin lives only in the pinned cache, and a+ * conversation opened by URL can be in neither list, resolving into its own point query+ * after the messages have already reported the bottom; that arrival is then the last+ * trigger left to notice the conversation at all. */+ const root = event?.query?.queryKey?.[0];+ /* Only a messages fetch belonging to this conversation can establish that its reply+ * rendered. Streamed tokens also land in this cache, but through `setQueryData`, which+ * marks its success action manual; re-checking on each of those would scan the lists once+ * per token. */+ if (root === QueryKeys.messages) {+ const messageConversationId = event?.query?.queryKey?.[1];+ if (messageConversationId !== conversationId || event.type !== 'updated') {+ return;+ }+ if (event.action.type === 'fetch') {+ fetchStartStampRef.current.set(+ conversationId,+ findConvoInAllQueries(queryClient, conversationId)?.lastResponseAt,+ );+ return;+ }+ if (event.action.type !== 'success' || event.action.manual) {+ return;+ }+ const stampAtFetchStart = fetchStartStampRef.current.get(conversationId);+ /* Capture the stamp from fetch start, not success: a newer reply can reach the list while+ * this request is in flight, and that reply was not part of the fetched/rendered tree. */+ scheduleRenderedCheck(stampAtFetchStart);+ return;+ }+ if (+ root !== QueryKeys.allConversations &&+ root !== QueryKeys.pinnedConversations &&+ root !== QueryKeys.conversation+ ) {+ return;+ }+ markSeenIfCaughtUp(true);+ });+ return () => {+ unsubscribe();+ if (pendingFrameRef.current != null) {+ window.cancelAnimationFrame(pendingFrameRef.current);+ pendingFrameRef.current = null;+ }+ };+ }, [conversationId, queryClient, markSeenIfCaughtUp, scheduleRenderedCheck]);++ return reportNearBottom;+}diff --git a/client/src/hooks/Conversations/useReplyAlerts.ts b/client/src/hooks/Conversations/useReplyAlerts.tsnew file mode 100644index 0000000000..a3d34079b6--- /dev/null+++ b/client/src/hooks/Conversations/useReplyAlerts.ts@@ -0,0 +1,412 @@+import { useRef, useState, useEffect } from 'react';+import { useNavigate, useLocation } from 'react-router-dom';+import type { ReplyReadState } from './useUnseenConversations';+import { startFocusLease, subscribeToFocusLease, anotherTabLeaseRemainingMs } from './focusLease';+import { suppressFocusAcknowledgement } from './notificationNavigation';+import { useReplyAlertPreferences } from './replyNotificationSettings';+import { useLocalize } from '~/hooks';++let sharedContext: AudioContext | null = null;++/**+ * Opens the shared output, resuming it if the browser parked it.+ *+ * Alerts only fire while the document is unfocused, so a context first opened there has no user+ * activation behind it and browsers leave it suspended. The settings toggle calls this from its+ * change handler instead, which is a gesture, and every later chime reuses what it unlocked.+ */+const openAudioContext = (): AudioContext | null => {+ if (typeof window.AudioContext !== 'function') {+ return null;+ }+ sharedContext = sharedContext ?? new AudioContext();+ if (sharedContext.state === 'suspended') {+ void sharedContext.resume().catch(() => undefined);+ }+ return sharedContext;+};++/** Called from the sound toggle's change handler, the one gesture the audio output can use. */+export const unlockReplyNotificationSound = (): void => {+ try {+ openAudioContext();+ } catch {+ /* No output device, or the context limit is already reached. */+ }+};++/**+ * Synthesized rather than shipped as an asset: two short tones need no binary, no request, and+ * no cache entry. Failure is always silent, because a missed chime is not worth an error toast.+ */+const playChime = (arrivals: ReplyReadState['unseen']) => {+ const claimed: ReplyReadState['unseen'] = [];+ try {+ const context = openAudioContext();+ if (!context || context.state !== 'running') {+ return;+ }+ for (const conversation of arrivals) {+ if (+ claimReplyAnnouncement('sound', conversation.conversationId, conversation.lastResponseAt)+ ) {+ claimed.push(conversation);+ }+ }+ if (claimed.length === 0) {+ return;+ }+ const start = context.currentTime;+ const tones: Array<[number, number]> = [+ [880, 0],+ [1174.66, 0.12],+ ];++ for (const [frequency, offset] of tones) {+ const oscillator = context.createOscillator();+ const gain = context.createGain();+ oscillator.type = 'sine';+ oscillator.frequency.value = frequency;+ gain.gain.setValueAtTime(0.0001, start + offset);+ gain.gain.exponentialRampToValueAtTime(0.12, start + offset + 0.01);+ gain.gain.exponentialRampToValueAtTime(0.0001, start + offset + 0.25);+ oscillator.connect(gain).connect(context.destination);+ oscillator.start(start + offset);+ oscillator.stop(start + offset + 0.3);+ }+ } catch {+ /* Autoplay policy or an unavailable output device. Nothing played, so the claims taken+ above are handed back rather than left to silence these replies in every tab. */+ for (const conversation of claimed) {+ releaseReplyAnnouncement('sound', conversation.conversationId, conversation.lastResponseAt);+ }+ }+};++const canNotify = (): boolean => 'Notification' in window && Notification.permission === 'granted';++type AlertChannel = 'sound' | 'notification';++const ANNOUNCED_KEY: Record<AlertChannel, string> = {+ sound: 'replyAlerts:announced:sound',+ notification: 'replyAlerts:announced:notification',+};+const ANNOUNCED_LIMIT = 100;++/**+ * Claims one reply announcement for one channel across every open tab.+ *+ * Each tab polls on its own timer and keeps its own baseline, so without a shared record the+ * same reply would chime once per tab, seconds apart, and stack duplicate notifications.+ * localStorage is the coordination channel because it is synchronous and shared per origin:+ * the first tab to reach an arrival records its stamp and the rest read it before announcing.+ * A dead-heat between two timers can still double one alert, which was the failure mode+ * everywhere before; unavailable storage (private windows, quota) falls back to announcing+ * locally for the same reason.+ *+ * Per channel, because two tabs are not necessarily duplicates of each other: notification+ * permission is asked for per tab and can be granted in one and denied in another, and a+ * settings change reaches other tabs only once its storage event lands. A single shared claim+ * would let whichever tab reached the reply first silence the other channel entirely.+ */+const claimReplyAnnouncement = (+ channel: AlertChannel,+ conversationId: string,+ lastResponseAt: string,+): boolean => {+ try {+ const raw = window.localStorage.getItem(ANNOUNCED_KEY[channel]);+ const parsed: unknown = raw != null ? JSON.parse(raw) : [];+ const entries = (Array.isArray(parsed) ? parsed : []) as Array<[string, string]>;+ if (entries.some(([id, stamp]) => id === conversationId && stamp === lastResponseAt)) {+ return false;+ }+ const next: Array<[string, string]> = [+ [conversationId, lastResponseAt],+ ...entries.filter(([id]) => id !== conversationId),+ ];+ window.localStorage.setItem(+ ANNOUNCED_KEY[channel],+ JSON.stringify(next.slice(0, ANNOUNCED_LIMIT)),+ );+ return true;+ } catch {+ return true;+ }+};++/**+ * Gives back a claim whose announcement never happened, so another tab, or this one on a+ * later arrival pass, can still deliver it. Removes the entry only while it still names this+ * exact stamp: a newer reply claimed in the meantime belongs to whoever claimed it.+ */+const releaseReplyAnnouncement = (+ channel: AlertChannel,+ conversationId: string,+ lastResponseAt: string,+): void => {+ try {+ const raw = window.localStorage.getItem(ANNOUNCED_KEY[channel]);+ const parsed: unknown = raw != null ? JSON.parse(raw) : [];+ const entries = (Array.isArray(parsed) ? parsed : []) as Array<[string, string]>;+ const next = entries.filter(+ ([id, stamp]) => !(id === conversationId && stamp === lastResponseAt),+ );+ if (next.length !== entries.length) {+ window.localStorage.setItem(ANNOUNCED_KEY[channel], JSON.stringify(next));+ }+ } catch {+ /* Storage unavailable: the claim could not have been written either. */+ }+};++const notificationPermission = (): NotificationPermission | null =>+ 'Notification' in window ? Notification.permission : null;++/** Notified when a pending permission prompt settles; see `requestReplyNotificationPermission`. */+const permissionListeners = new Set<() => void>();++const subscribeToPermission = (listener: () => void): (() => void) => {+ permissionListeners.add(listener);+ return () => {+ permissionListeners.delete(listener);+ };+};++/**+ * Requests desktop-notification permission on behalf of the settings toggle.+ *+ * Must be called from the toggle's change handler: that is the user gesture browsers require.+ * An effect on the persisted toggle fires on load without one, and Chrome answers gestureless+ * requests by denying them, which locks the origin out of notifications until the user digs+ * into site settings.+ *+ * The answer is published rather than dropped: a reply can arrive while the prompt is still+ * open, and nothing else would tell the hook that this tab may now notify.+ */+export const requestReplyNotificationPermission = (): void => {+ if (!('Notification' in window) || Notification.permission !== 'default') {+ return;+ }+ let settled = false;+ const publishPermission = () => {+ if (settled) {+ return;+ }+ settled = true;+ for (const listener of permissionListeners) {+ listener();+ }+ };+ /* Callback-only browsers return undefined; dual implementations must publish only once. */+ const request = Notification.requestPermission(publishPermission);+ void request?.then(publishPermission, publishPermission);+};++/**+ * Announces replies that landed while the user was away.+ *+ * Alerts are suppressed whenever the document has focus: the sidebar dot already covers the case+ * where the user is looking at the app, and interrupting them there would be noise. The first+ * pass only records what is already unseen, so signing in with a backlog does not fire a burst.+ */+export default function useReplyAlerts(state: ReplyReadState | null) {+ const { notificationsEnabled, soundEnabled } = useReplyAlertPreferences();+ const localize = useLocalize();+ const navigate = useNavigate();+ const { pathname } = useLocation();+ /** Read from the click handler, which outlives the render that created it. */+ const locationRef = useRef(pathname);+ locationRef.current = pathname;+ /** Reply stamps, not just ids: a second reply to a chat that is already unseen is its own+ * arrival, and keying on membership alone would swallow it. */+ const knownRef = useRef<Map<string, string> | null>(null);+ const unlockedRef = useRef(false);+ /** Arrivals held back only by another tab's focus lease, keyed to the stamp they arrived with.+ * They are already in the baseline, so without this a lease left by a killed tab would retire+ * them unannounced; the recheck below replays them once that lease lapses. */+ const leaseHeldRef = useRef<Map<string, string>>(new Map());+ const leaseTimerRef = useRef<number | null>(null);+ const [leaseRecheck, setLeaseRecheck] = useState(0);+ useEffect(() => {+ /* A tab that blurs normally clears its lease well before the lapse, and the reply it held+ back is due as soon as nobody is looking. */+ const unsubscribe = subscribeToFocusLease(() => {+ if (leaseHeldRef.current.size > 0) {+ setLeaseRecheck((count) => count + 1);+ }+ });+ return () => {+ unsubscribe();+ if (leaseTimerRef.current !== null) {+ window.clearTimeout(leaseTimerRef.current);+ }+ };+ }, []);++ /* Published for the other tabs of this origin, and read by them below: a reply announced by+ a background tab while the user reads a focused one is exactly the interruption the focus+ guard exists to prevent, and `document.hasFocus()` cannot see across tabs. */+ useEffect(() => startFocusLease(), []);++ /* The prompt the settings toggle opens settles long after its click, and nothing else would+ tell this hook that the tab may now notify. */+ const [permission, setPermission] = useState(notificationPermission);+ useEffect(() => subscribeToPermission(() => setPermission(notificationPermission())), []);++ /* The setting survives a reload but the audio output does not, and the toggle gesture that+ opened it last session is not replayed. Without this the first chime of a restored session+ would try to open the output while the tab is unfocused, which browsers refuse, and every+ later one would stay silent until the user toggled the setting off and on. The first click+ or keystroke anywhere in the app is gesture enough. */+ useEffect(() => {+ if (!soundEnabled || unlockedRef.current) {+ return;+ }+ const unlock = () => {+ if (unlockedRef.current) {+ return;+ }+ unlockedRef.current = true;+ unlockReplyNotificationSound();+ };+ window.addEventListener('pointerdown', unlock);+ window.addEventListener('keydown', unlock);+ return () => {+ window.removeEventListener('pointerdown', unlock);+ window.removeEventListener('keydown', unlock);+ };+ }, [soundEnabled]);++ useEffect(() => {+ /* Null means no list has resolved yet, which is not an empty backlog. Initializing from it+ would let the real backlog arrive as a burst of alerts on a tab restored in the+ background, where the focus guard below never gets a chance to suppress them. */+ if (state === null) {+ return;+ }+ const { unseen, stamps, arrivalStamps } = state;++ const known = knownRef.current;+ const priorStamps = new Map(known ?? []);+ /* The baseline records the seen conversations too, and stamps are retained rather than+ replaced when a row leaves the cache. A conversation that has been read, whether during+ this session or before it started, keeps the reply stamp it always had, and if another+ device later marks it unread it re-enters the unseen set carrying that same stamp.+ Without the baseline that re-entry would look like a new reply and announce one that+ never happened. */+ const next = known === null ? new Map<string, string>() : known;+ /* A prompt this tab opened is still unanswered, so a reply arriving now cannot be+ announced yet. Baselining it would retire the arrival before the answer lands and lose+ the first notification the user enabled the setting for; the subscription below re-runs+ this pass once the prompt settles. */+ const awaitingPermission = notificationsEnabled && permission === 'default';+ if (!awaitingPermission) {+ for (const [conversationId, lastResponseAt] of stamps) {+ next.set(conversationId, lastResponseAt);+ }+ }+ knownRef.current = next;++ if (known === null) {+ return;+ }++ /* A local first-page merge must update a row already known without a reply stamp; a server+ first-page success may also provide evidence for a newly discovered reply. Pagination and+ newly mounted filter variants expose backlog rather than arrivals. */+ const discovered = new Map(arrivalStamps);+ const held = leaseHeldRef.current;+ const arrivals = unseen.filter(+ (conversation) =>+ conversation.conversationId &&+ !conversation.flagged &&+ (held.get(conversation.conversationId) === conversation.lastResponseAt ||+ (priorStamps.has(conversation.conversationId)+ ? priorStamps.get(conversation.conversationId) !== conversation.lastResponseAt+ : discovered.get(conversation.conversationId) === conversation.lastResponseAt)),+ );+ held.clear();+ if (arrivals.length === 0 || document.hasFocus()) {+ return;+ }+ /* "Away" means away from LibreChat, not away from this tab: a second tab holding focus is+ the user reading the app, and the sidebar dot already covers them there. */+ const leaseRemainingMs = anotherTabLeaseRemainingMs();+ if (leaseRemainingMs !== null) {+ for (const conversation of arrivals) {+ held.set(conversation.conversationId, conversation.lastResponseAt);+ }+ if (leaseTimerRef.current !== null) {+ window.clearTimeout(leaseTimerRef.current);+ }+ leaseTimerRef.current = window.setTimeout(() => {+ leaseTimerRef.current = null;+ setLeaseRecheck((count) => count + 1);+ }, leaseRemainingMs + 1);+ return;+ }++ /* Only a tab that will actually announce may claim, and only for the channel it will+ announce on. A tab with both channels off still runs this hook for the badge, and a tab+ whose notification permission was denied still holds the setting on; letting either+ claim would consume the reply while producing neither chime nor notification. The focus+ guard stays first, so a focused tab never claims a reply it would not announce either. */+ const willNotify = notificationsEnabled && canNotify();+ if (!soundEnabled && !willNotify) {+ return;+ }++ /* The usable audio context claims every covered arrival, so a suspended tab cannot silence+ the same reply in another tab that can actually schedule playback. */+ if (soundEnabled) {+ playChime(arrivals);+ }++ if (!willNotify) {+ return;+ }++ const announced = arrivals.filter((conversation) =>+ claimReplyAnnouncement(+ 'notification',+ conversation.conversationId,+ conversation.lastResponseAt,+ ),+ );++ for (const conversation of announced) {+ try {+ /* Android Chrome exposes the API and the permission but throws here: notifications+ have to come from the service worker there. A missed alert degrades quietly rather+ than throwing out of the effect. */+ const notification = new Notification(localize('com_ui_reply_ready'), {+ body: conversation.title || localize('com_ui_untitled'),+ tag: conversation.conversationId,+ });+ const target = `/c/${conversation.conversationId}`;+ notification.onclick = () => {+ /* Only when the click is leaving for a different conversation, where the focus would+ otherwise read as the user catching up on whatever is still open behind it. A+ notification for the conversation already on screen navigates nowhere, and+ suppressing there would swallow the one trigger that acknowledges it. */+ if (locationRef.current !== target) {+ suppressFocusAcknowledgement();+ }+ navigate(target);+ window.focus();+ notification.close();+ };+ } catch {+ /* Constructor unsupported on this platform, or the notification was rejected. The+ claim was taken before construction, so it is handed back rather than left to+ silence this reply in every tab for good. */+ releaseReplyAnnouncement(+ 'notification',+ conversation.conversationId,+ conversation.lastResponseAt,+ );+ }+ }+ }, [state, soundEnabled, notificationsEnabled, permission, leaseRecheck, localize, navigate]);+}diff --git a/client/src/hooks/Conversations/useReplyWatcher.ts b/client/src/hooks/Conversations/useReplyWatcher.tsnew file mode 100644index 0000000000..0f54eee2f5--- /dev/null+++ b/client/src/hooks/Conversations/useReplyWatcher.ts@@ -0,0 +1,618 @@+import { useRef, useEffect } from 'react';+import { QueryKeys, dataService } from 'librechat-data-provider';+import { useQueryClient, replaceEqualDeep } from '@tanstack/react-query';+import type { TConversation, ConversationListParams } from 'librechat-data-provider';+import type { InfiniteData, QueryClient } from '@tanstack/react-query';+import type { ConversationCursorData } from '~/utils/convos';+import {+ isNotFoundError,+ findConvoInAllQueries,+ updateConvoInAllQueries,+ isConvoInAggregateCaches,+} from '~/utils';+import { REPLY_NOTIFICATION_DEFAULTS, useReplyAlertPreferences } from './replyNotificationSettings';+import { useActiveJobs } from '~/data-provider';++/**+ * Timestamps are the only thing worth taking from a fresher copy; everything else in the row is+ * either already current or derived per list request.+ *+ * `updatedAt` rides along and the row moves to the top, because a reply now advances `updatedAt`+ * server-side: leaving the cached copy behind would show a conversation that just became active+ * still sitting at its old date and position. The same write also refreshes the list query's+ * `dataUpdatedAt`, so a stale row could otherwise survive the next focus refetch.+ *+ * Writes only when something actually differs: an unchanged `setQueryData` would still bump that+ * `dataUpdatedAt`, keeping the query permanently inside its stale window and silently disabling+ * the sidebar's refetch on window focus.+ */+const didListRefreshFail = (queryClient: QueryClient): boolean =>+ queryClient+ .getQueryCache()+ .findAll([QueryKeys.allConversations], { exact: false })+ .some((query) => query.getObserversCount() > 0 && query.state.status === 'error');++type ConversationPages = InfiniteData<ConversationCursorData>;++/**+ * A first-page refetch can promote a row out of a loaded page. Keep the old first-page rows that+ * were displaced, remove the promoted duplicates from later pages, and move the first page cursor+ * forward. This leaves the already-scrolled rows usable without asking the server for every page.+ */+const reconcileFirstPage = (+ previous: ConversationPages | undefined,+ current: ConversationPages | undefined,+): ConversationPages | undefined => {+ if (!previous || !current || previous.pages.length === 0 || current.pages.length === 0) {+ return current;+ }++ const freshFirst = replaceEqualDeep(previous.pages[0], current.pages[0]);+ if (freshFirst === previous.pages[0]) {+ return previous;+ }+ const freshIds = new Set<string>();+ const uniqueFirst = freshFirst.conversations.filter((convo) => {+ const id = convo.conversationId;+ if (!id) {+ return true;+ }+ if (freshIds.has(id)) {+ return false;+ }+ freshIds.add(id);+ return true;+ });++ if (freshFirst.nextCursor == null) {+ return {+ ...current,+ pages: [{ ...freshFirst, conversations: uniqueFirst }],+ pageParams: current.pageParams.slice(0, 1),+ };+ }++ /* Keep rows displaced into the loaded tail. A normal full revalidation still owns pruning+ historical rows, which is why the partial merge never refreshes the original query's age. */+ const displaced =+ current.pages.length > 1 && freshFirst.nextCursor != null+ ? previous.pages[0].conversations.filter(+ (convo) => convo.conversationId && !freshIds.has(convo.conversationId),+ )+ : [];+ const seen = new Set(freshIds);+ const pages = current.pages.map((page, pageIndex) => {+ if (pageIndex === 0) {+ return uniqueFirst.length === freshFirst.conversations.length+ ? freshFirst+ : { ...freshFirst, conversations: uniqueFirst };+ }++ const conversations = [...(pageIndex === 1 ? displaced : []), ...page.conversations].filter(+ (convo) => {+ const id = convo.conversationId;+ if (!id) {+ return true;+ }+ if (seen.has(id)) {+ return false;+ }+ seen.add(id);+ return true;+ },+ );+ if (+ conversations.length === page.conversations.length &&+ conversations.every((convo, index) => convo === page.conversations[index])+ ) {+ return page;+ }+ return { ...page, conversations };+ });++ const pageParams = [...current.pageParams];+ if (+ pages.length > 1 &&+ freshFirst.nextCursor != null &&+ pageParams[1] !== freshFirst.nextCursor+ ) {+ pageParams[1] = freshFirst.nextCursor;+ }+ const pagesChanged = pages.some((page, index) => page !== current.pages[index]);+ const pageParamsChanged = pageParams.some((param, index) => param !== current.pageParams[index]);+ return pagesChanged || pageParamsChanged ? { ...current, pages, pageParams } : current;+};++/**+ * Refresh the visible sidebar and the unfiltered cache read by global reply indicators.+ *+ * `discovered` names the conversations this refresh was started for. The queries it creates+ * have never been observed before, so the alert layer would otherwise have to choose between+ * treating their whole first page as new arrivals — announcing the user's entire unseen+ * backlog — and treating it as a quiet baseline, which would swallow the very reply that+ * triggered the refresh. Naming the ids keeps both from happening.+ */+const refreshConversationLists = async (+ queryClient: QueryClient,+ discovered: readonly string[] = [],+ /* How many rows the canonical discovery fetch reads. It is a ceiling rather than a+ guarantee: draining the cursor on a poll that repeats every thirty seconds is the wrong+ trade, and covering a deployment whose replies outpace it properly wants an unseen query+ on the server rather than a wider page here, which is why operators can raise it. */+ limit: number = REPLY_NOTIFICATION_DEFAULTS.pollLimit,+): Promise<void> => {+ const cache = queryClient.getQueryCache();+ const active = cache+ .findAll([QueryKeys.allConversations], { exact: false })+ .filter((query) => query.isActive());+ const invalidation = queryClient.invalidateQueries([QueryKeys.allConversations], {+ refetchType: 'none',+ });+ const refreshes = active.map(async (query) => {+ const queryFn = query.options.queryFn;+ const snapshot = await queryClient.fetchInfiniteQuery<ConversationCursorData>({+ queryKey: [...query.queryKey, 'reply-discovery'],+ meta: { replyDiscovery: discovered },+ queryFn: async ({ signal }) => {+ if (typeof queryFn !== 'function') {+ return dataService.listConversations({+ ...(query.queryKey[1] as ConversationListParams | undefined),+ cursor: undefined,+ });+ }+ return (await queryFn({+ queryKey: query.queryKey,+ pageParam: undefined,+ signal,+ meta: query.meta,+ })) as ConversationCursorData;+ },+ getNextPageParam: () => undefined,+ });+ if (cache.find(query.queryKey) !== query) {+ return;+ }+ const current = queryClient.getQueryData<ConversationPages>(query.queryKey);+ if (!current || !snapshot.pages[0]) {+ return;+ }+ const reconciled = reconcileFirstPage(current, {+ ...current,+ pages: [snapshot.pages[0], ...current.pages.slice(1)],+ });+ if (reconciled && reconciled !== current) {+ /* The snapshot owns the new first page, not the old loaded tail. Keep the original+ query's age so normal focus/mount revalidation can still refresh those older pages. */+ queryClient.setQueryData(query.queryKey, reconciled, {+ updatedAt: query.state.dataUpdatedAt,+ });+ }+ });++ await Promise.all([+ invalidation,+ ...refreshes,+ queryClient.invalidateQueries([QueryKeys.pinnedConversations]),+ queryClient.fetchInfiniteQuery({+ queryKey: [QueryKeys.allConversations, { isArchived: false, replyDiscovery: true }],+ meta: { replyDiscovery: discovered },+ queryFn: () => dataService.listConversations({ isArchived: false, limit }),+ getNextPageParam: () => undefined,+ }),+ ]);+};++const mergeTimestamps = async (+ queryClient: QueryClient,+ convo: Partial<TConversation>,+ aggregateRevealed: Map<string, string>,+ /** The completion fetch exists only to deliver a stamp the cache lacks. Once the cache+ * carries that stamp, the rest of its snapshot is a read from before the open conversation+ * acknowledged here, and merging it would clear the newer catch-up with the attempt guard+ * suppressing the re-send. The away poll keeps full-snapshot semantics: an equal-stamp row+ * with a cleared catch-up is how a remote mark-as-unread reaches this tab, and that path's+ * own stale reads are fenced by its arrival focus check. */+ stampDelivery = false,+ isCurrent: () => boolean = () => true,+): Promise<void> => {+ const {+ conversationId,+ lastResponseAt,+ lastResponseMessageId,+ lastResponseIsManual,+ lastSeenAt,+ updatedAt,+ } = convo;+ if (!conversationId || !lastResponseAt) {+ return;+ }+ let cached = findConvoInAllQueries(queryClient, conversationId);++ /* A job completing on another device can belong to a conversation the chats list has never+ loaded, and the writes below only reach rows that already exist. Hand-inserting one would+ fight the list's own ordering and pagination, so the list is refetched instead, exactly as+ the away poll does when it meets an id it does not know.+ Keyed on the caches the unseen aggregate actually reads: a conversation opened by URL sits+ in its own point query, which is enough for the lookup above but invisible to the badge and+ the alerts, so it still needs the list. Checked before the unchanged-row return, because a+ transiently failed refetch leaves the next snapshot looking identical: absence from the+ aggregate caches re-arms the attempt, and marking a stamp done only on a refetch that+ succeeded keeps a row that moved beyond the refreshed pages from causing a refetch loop. */+ if (!isConvoInAggregateCaches(queryClient, conversationId)) {+ if (aggregateRevealed.get(conversationId) !== lastResponseAt) {+ await refreshConversationLists(queryClient, [conversationId]);+ if (!isCurrent()) {+ return;+ }+ if (!didListRefreshFail(queryClient)) {+ aggregateRevealed.set(conversationId, lastResponseAt);+ }+ cached = findConvoInAllQueries(queryClient, conversationId);+ }+ if (!cached) {+ return;+ }+ }++ const incomingResponseMessageId =+ lastResponseIsManual === true ? undefined : lastResponseMessageId;+ if (+ cached &&+ cached.lastResponseAt === lastResponseAt &&+ cached.lastResponseIsManual === lastResponseIsManual &&+ cached.lastSeenAt === (lastSeenAt ?? undefined) &&+ (updatedAt === undefined || cached.updatedAt === updatedAt) &&+ (incomingResponseMessageId === undefined ||+ cached.lastResponseMessageId === incomingResponseMessageId)+ ) {+ return;+ }++ /* Two fetches for the same conversation can resolve out of order: overlapping away polls, or+ * completion fetches for concurrent jobs. Taking the older one would walk the read state+ * backwards and either drop a dot or bring one back. A snapshot is accepted whole or not at+ * all, since its two stamps come from one server read and `lastSeenAt` legitimately clears+ * when another device marks the conversation unread. */+ if (cached?.lastResponseAt != null && lastResponseAt < cached.lastResponseAt) {+ return;+ }++ /* An equal timestamp already names the same server reply. Identity can arrive after the+ * timestamp (especially from a completion point read), so merge it without refetching history.+ * Completion snapshots are intentionally read-state neutral: they must not clear a newer+ * catch-up that arrived while the point request was in flight. */+ if (cached?.lastResponseAt === lastResponseAt) {+ const nextLastResponseMessageId =+ lastResponseIsManual === true+ ? undefined+ : (incomingResponseMessageId ?? cached.lastResponseMessageId);+ const nextLastSeenAt = stampDelivery ? cached.lastSeenAt : lastSeenAt;+ const nextUpdatedAt = stampDelivery ? cached.updatedAt : (updatedAt ?? cached.updatedAt);+ if (+ cached.lastResponseMessageId !== nextLastResponseMessageId ||+ cached.lastResponseIsManual !== lastResponseIsManual ||+ cached.lastSeenAt !== nextLastSeenAt ||+ cached.updatedAt !== nextUpdatedAt+ ) {+ updateConvoInAllQueries(queryClient, conversationId, (current) => ({+ ...current,+ lastResponseMessageId: nextLastResponseMessageId,+ lastResponseIsManual,+ lastSeenAt: nextLastSeenAt,+ updatedAt: nextUpdatedAt,+ }));+ }+ return;+ }++ /* Awaited, and before the stamp. A reply this tab never streamed is not in the rendered+ * tree, and exposing the stamp first would let the seen trigger acknowledge it from a scroll+ * position that belongs to the previous message. Invalidation resolves once the active+ * refetch has landed, so the conversation the user is looking at is showing the reply by the+ * time it can be credited; anywhere else the query is unmounted, nothing is fetched and this+ * resolves immediately. */+ const messagesKey = [QueryKeys.messages, conversationId];+ await queryClient.invalidateQueries(messagesKey);+ if (!isCurrent()) {+ return;+ }+ /* Invalidation settles rather than throwing when the refetch fails, so the failure has to be+ * read off the query itself. Exposing the stamp anyway would let the seen trigger credit a+ * reply the tab never managed to load; the next poll retries.+ * Only an observed query counts: invalidation refetches those, so its error is this attempt's.+ * A cached error left behind by a conversation the user has since closed never clears, and+ * reading it would withhold that conversation's stamp for the rest of the session. */+ const messagesQuery = queryClient.getQueryCache().find(messagesKey);+ const isObserved = (messagesQuery?.getObserversCount() ?? 0) > 0;+ if (isObserved && messagesQuery?.state.status === 'error') {+ return;+ }++ /* The await above is a real network wait while the conversation is open, and a newer stamp+ * can land during it: the SSE final handler, or a fresher overlapping fetch. Writing this+ * snapshot over that would walk the read state backwards after the newer reply's signal was+ * already consumed, so the ordering guard runs again against what the cache holds now, and+ * an unchanged row is left alone for the same `dataUpdatedAt` reason as above. */+ const fresh = findConvoInAllQueries(queryClient, conversationId);+ if (fresh?.lastResponseAt != null && lastResponseAt < fresh.lastResponseAt) {+ return;+ }+ if (stampDelivery && fresh?.lastResponseAt === lastResponseAt) {+ if (+ fresh.lastResponseMessageId !== incomingResponseMessageId ||+ fresh.lastResponseIsManual !== lastResponseIsManual+ ) {+ updateConvoInAllQueries(queryClient, conversationId, (current) => ({+ ...current,+ lastResponseMessageId: incomingResponseMessageId,+ lastResponseIsManual,+ }));+ }+ return;+ }+ if (+ fresh &&+ fresh.lastResponseAt === lastResponseAt &&+ fresh.lastResponseMessageId === (incomingResponseMessageId ?? fresh.lastResponseMessageId) &&+ fresh.lastResponseIsManual === lastResponseIsManual &&+ fresh.lastSeenAt === (lastSeenAt ?? undefined) &&+ (updatedAt === undefined || fresh.updatedAt === updatedAt)+ ) {+ return;+ }++ updateConvoInAllQueries(+ queryClient,+ conversationId,+ (current) => ({+ ...current,+ lastResponseAt,+ lastResponseMessageId: incomingResponseMessageId ?? current.lastResponseMessageId,+ lastResponseIsManual,+ lastSeenAt,+ updatedAt: updatedAt ?? current.updatedAt,+ }),+ /* Reordering only when the server says the conversation moved; a bare read-state merge+ * must not jump the row. */+ updatedAt !== undefined && fresh?.updatedAt !== updatedAt,+ );+};++/**+ * Notices replies that finish without this tab holding the stream.+ *+ * `finalHandler` covers the tab that is sitting on the conversation, but navigating elsewhere+ * closes the SSE connection by design, and a run started on another device was never attached+ * here at all. Both cases feed the same unseen pipeline once the timestamps reach the cache, so+ * this hook only has to get them there.+ *+ * Two paths, because one signal cannot cover both cheaply:+ *+ * - **Foreground.** `useActiveJobs` is already mounted by the sidebar and already polls while any+ * job runs, so watching an id leave that set costs no extra request. Completion then fetches+ * just that conversation rather than refetching the whole list.+ * - **Away.** Job-set watching is unreliable here: a short run can start and finish between two+ * polls, leaving no transition to observe. Polling the first page of the list instead reports+ * the reply whether or not the job was ever seen running. Gated on any of the three away+ * features (notifications, sound, tab badge), so the request only exists for someone who+ * asked to be told or shown something while away.+ */+export default function useReplyWatcher() {+ const queryClient = useQueryClient();+ /* Both cadences come from `interface.replyNotifications`. The focused refresh is deliberately+ far slower than the away poll: the user is looking at the sidebar, alerts are suppressed+ there anyway, and it exists only so a reply produced elsewhere eventually shows its dot. */+ const {+ notificationsEnabled,+ soundEnabled,+ badgeEnabled,+ pollLimit,+ pollIntervalMs,+ focusedRefreshMs,+ } = useReplyAlertPreferences();+ const { data: activeJobsData } = useActiveJobs();+ const activeJobIds = activeJobsData?.activeJobIds;+ /** A completion fetch can outlive the watcher. Signing out or switching accounts unmounts+ * it, and a response for the previous session must not write into the caches the next+ * one reads. Tracked on unmount rather than in the jobs effect's cleanup: that effect+ * re-runs on every change to the running set, and the completions it started are still+ * wanted. */+ const mountedRef = useRef(true);+ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);+ const runningRef = useRef<Set<string> | null>(null);+ /** Reply stamps whose list refetch has already been attempted for a conversation no cache+ * knows, keyed by id. Keyed on the stamp rather than the id alone so a later reply to the+ * same conversation earns a fresh attempt, while repeated polls carrying the same reply do+ * not refetch the list on every tick. */+ const unknownIdsRef = useRef<Map<string, string>>(new Map());+ /** Reply stamps whose aggregate-cache reveal has already succeeded; see `mergeTimestamps`. */+ const aggregateRevealedRef = useRef<Map<string, string>>(new Map());++ useEffect(() => {+ /* `useActiveJobs` does not retry: a failed poll reads as no information, not as+ every running job having finished. */+ if (activeJobIds === undefined) {+ return;+ }+ const running = new Set(activeJobIds);+ const previous = runningRef.current;+ runningRef.current = running;++ if (previous === null) {+ return;+ }++ for (const conversationId of previous) {+ if (running.has(conversationId)) {+ continue;+ }+ /* Successive jobs can keep the same conversation continuously active. A stamp delivered+ during that interval may belong to an earlier run, so only a completion fetch can+ establish the final reply. The merge leaves already-delivered stamps alone. */+ dataService+ .getConversationById(conversationId)+ .then((convo) => {+ if (!mountedRef.current) {+ return;+ }+ return mergeTimestamps(+ queryClient,+ convo,+ aggregateRevealedRef.current,+ true,+ () => mountedRef.current,+ );+ })+ .catch((error: unknown) => {+ /* Deleted while it generated is the only terminal answer. Anything else has+ consumed the one completion transition this tab will see, and with the away poll+ gated on the document being unfocused, nothing would deliver the reply's stamp+ while the user stays here; the list refetch is the same recovery the poll uses+ for an unknown id. The messages go stale first so an open conversation refetches+ the reply and the seen trigger holds until it has rendered. */+ if (!mountedRef.current || isNotFoundError(error)) {+ return;+ }+ queryClient.invalidateQueries([QueryKeys.messages, conversationId]);+ queryClient.invalidateQueries([QueryKeys.allConversations]);+ });+ }+ }, [activeJobIds, queryClient]);++ useEffect(() => {+ /* Sidebar dots are unconditional, even when every optional away alert is disabled. The+ operator's poll limit bounds the away poll only; the focused refresh reads a full server+ page, so a lowered limit cannot starve the unseen count behind a filtered list. */+ const timer = window.setInterval(() => {+ if (document.hasFocus()) {+ void refreshConversationLists(queryClient, []).catch(() => {});+ }+ }, focusedRefreshMs);+ return () => window.clearInterval(timer);+ }, [queryClient, focusedRefreshMs]);++ useEffect(() => {+ if (!notificationsEnabled && !soundEnabled && !badgeEnabled) {+ return;+ }++ let active = true;+ let generation = 0;++ const poll = async () => {+ if (document.hasFocus()) {+ return;+ }+ const requestGeneration = ++generation;+ const isCurrent = () => active && generation === requestGeneration && !document.hasFocus();+ try {+ /* The default page is the newest conversations, which is where an unseen reply always+ lands: the list sorts by `updatedAt` descending. */+ const { conversations } = await dataService.listConversations({+ limit: pollLimit,+ });+ /* Re-checked at arrival, not only at issue: the user can return while the request is+ in flight, and this fetch bypasses React Query, so the seen mutation's cancellation+ cannot reach it. A snapshot read before their focus-triggered acknowledgement+ settled carries the same reply stamp with the older catch-up, which the merge+ cannot tell from a remote mark-as-unread and would write back with the attempt+ guard suppressing the re-send. The poll serves the away features only; once the+ tab is focused the ordinary focus refetches own the cache, and the next unfocused+ tick re-reads anything a discarded snapshot carried. */+ if (!isCurrent()) {+ return;+ }+ const unknownStamps = new Map<string, string>();+ const unknownConvos: Array<Partial<TConversation>> = [];+ let hasNewlyUnknownConversation = false;++ for (const convo of conversations) {+ if (!isCurrent()) {+ return;+ }+ const { conversationId, lastResponseAt } = convo;+ if (!conversationId) {+ continue;+ }+ if (findConvoInAllQueries(queryClient, conversationId)) {+ await mergeTimestamps(+ queryClient,+ convo,+ aggregateRevealedRef.current,+ false,+ isCurrent,+ );+ continue;+ }+ /* A conversation started on another device has no row here to merge into, and hand-+ inserting one would fight the list's own ordering and pagination state, so the+ list is refetched instead. Nothing to reveal without a reply stamp. */+ if (!lastResponseAt) {+ continue;+ }+ unknownStamps.set(conversationId, lastResponseAt);+ unknownConvos.push(convo);+ if (unknownIdsRef.current.get(conversationId) !== lastResponseAt) {+ hasNewlyUnknownConversation = true;+ }+ }++ /* A conversation that dropped off the page, or that some other path has since cached,+ starts over: its next appearance here is worth an attempt again. */+ for (const conversationId of [...unknownIdsRef.current.keys()]) {+ if (!unknownStamps.has(conversationId)) {+ unknownIdsRef.current.delete(conversationId);+ }+ }++ if (!isCurrent() || !hasNewlyUnknownConversation) {+ return;+ }+ /* Attempts are recorded only once the refetch meant to reveal them has succeeded.+ Recording them first would let a transient list failure mute those conversations for+ good: every later poll would read them as already attempted and never invalidate+ again, even after the network recovered. */+ await refreshConversationLists(queryClient, [...unknownStamps.keys()], pollLimit);+ if (!isCurrent() || didListRefreshFail(queryClient)) {+ return;+ }++ for (const convo of unknownConvos) {+ if (!isCurrent()) {+ return;+ }+ const conversationId = convo.conversationId as string;+ if (findConvoInAllQueries(queryClient, conversationId)) {+ /* Revealed: merge it now rather than waiting a tick, and forget the attempt. */+ unknownIdsRef.current.delete(conversationId);+ await mergeTimestamps(+ queryClient,+ convo,+ aggregateRevealedRef.current,+ false,+ isCurrent,+ );+ continue;+ }+ /* The row moved beyond the refreshed pages. Retry a new reply stamp without+ refetching on every tick for this one; covering larger batches needs an unseen+ query rather than repeatedly widening the list. */+ unknownIdsRef.current.set(conversationId, unknownStamps.get(conversationId) as string);+ }+ } catch {+ /* Offline or a dropped connection; the next tick retries. */+ }+ };++ const timer = window.setInterval(poll, pollIntervalMs);+ return () => {+ active = false;+ window.clearInterval(timer);+ };+ }, [notificationsEnabled, soundEnabled, badgeEnabled, pollLimit, pollIntervalMs, queryClient]);+}diff --git a/client/src/hooks/Conversations/useUnseenBadge.ts b/client/src/hooks/Conversations/useUnseenBadge.tsnew file mode 100644index 0000000000..b8f4389d6a--- /dev/null+++ b/client/src/hooks/Conversations/useUnseenBadge.ts@@ -0,0 +1,178 @@+import { useEffect } from 'react';+import { useReplyAlertPreferences } from './replyNotificationSettings';+import { getDocumentTitleRevision } from '~/utils';++const FAVICON_SELECTOR = 'link[rel="icon"]';+const FALLBACK_ICON_SIZE = 32;++/**+ * Reads the badge colour from the live theme so the favicon dot tracks the same semantic role+ * as the sidebar indicator. Returns null when the role cannot be read, which leaves the plain+ * favicon in place rather than painting a colour the active theme never chose.+ */+const badgeColor = (): string | null => {+ const value = getComputedStyle(document.documentElement).getPropertyValue('--status-info').trim();+ return value === '' ? null : `rgb(${value})`;+};++const drawBadgedFavicon = (+ source: string,+ color: string,+ onReady: (dataUrl: string) => void,+): (() => void) => {+ const image = new Image();+ let cancelled = false;++ image.onload = () => {+ if (cancelled) {+ return;+ }+ /* The icon's own resolution: upscaling the 16x16 link to 32 would soften it for exactly+ the browsers that pick it. Sizeless sources (an SVG icon) fall back to 32. */+ const size = image.naturalWidth || FALLBACK_ICON_SIZE;+ const canvas = document.createElement('canvas');+ canvas.width = size;+ canvas.height = size;+ const context = canvas.getContext('2d');+ if (!context) {+ return;+ }+ context.drawImage(image, 0, 0, size, size);+ const radius = size * 0.28;+ const center = size - radius - 1;+ context.beginPath();+ context.arc(center, center, radius, 0, Math.PI * 2);+ context.fillStyle = color;+ context.fill();+ try {+ onReady(canvas.toDataURL('image/png'));+ } catch {+ /* A cross-origin icon taints the canvas; the unbadged favicon is the only way out. */+ }+ };++ image.src = source;+ return () => {+ cancelled = true;+ };+};++/**+ * Reflects the unseen count in the tab title and favicon.+ *+ * The title has another canonical writer: `setDocumentTitle` updates it whenever+ * the active conversation or page changes. Its revision signal lets this hook+ * distinguish a canonical write that happens to leave the same title string,+ * while the `MutationObserver` still preserves compatibility with direct DOM+ * writers. Recomputing from the current value, rather than from a remembered+ * base, lets the two compose instead of clobbering each other.+ *+ * Every declared icon is badged, not just the 32x32 one: Firefox and 1x-DPI Chrome pick+ * the 16x16 link, and a single-link badge would leave them without one.+ */+export default function useUnseenBadge(count: number) {+ const { badgeEnabled } = useReplyAlertPreferences();+ const activeCount = badgeEnabled ? count : 0;++ useEffect(() => {+ const titleElement = document.querySelector('title');+ if (!titleElement) {+ return;+ }++ let writtenBadge = '';+ let writtenTitle = '';+ let seenTitleRevision = getDocumentTitleRevision();+ const apply = () => {+ const titleRevision = getDocumentTitleRevision();+ if (titleRevision !== seenTitleRevision) {+ writtenBadge = '';+ seenTitleRevision = titleRevision;+ }++ const badge = activeCount > 0 ? `(${activeCount}) ` : '';+ const isOurs = writtenBadge !== '' && document.title === writtenTitle;+ const base = isOurs ? document.title.slice(writtenBadge.length) : document.title;+ const next = `${badge}${base}`;+ if (document.title !== next) {+ document.title = next;+ }+ writtenBadge = badge;+ writtenTitle = next;+ };++ apply();+ const observer = new MutationObserver(apply);+ observer.observe(titleElement, { childList: true, characterData: true, subtree: true });++ return () => {+ observer.disconnect();+ if (+ seenTitleRevision === getDocumentTitleRevision() &&+ writtenBadge !== '' &&+ document.title === writtenTitle+ ) {+ document.title = document.title.slice(writtenBadge.length);+ }+ };+ }, [activeCount]);++ useEffect(() => {+ const links = Array.from(document.querySelectorAll<HTMLLinkElement>(FAVICON_SELECTOR));+ if (links.length === 0) {+ return;+ }++ /* Recorded once per link on first run; the dataset entry survives effect re-runs and+ can never capture an already-badged data URL. */+ for (const link of links) {+ link.dataset.originalHref ??= link.href;+ }+ const originals = links.map((link) => link.dataset.originalHref ?? link.href);+ let cancellations: Array<() => void> = [];++ const restore = () => {+ for (const [index, link] of links.entries()) {+ link.href = originals[index];+ }+ };++ const paint = () => {+ for (const cancel of cancellations) {+ cancel();+ }+ const color = badgeColor();+ if (activeCount === 0 || color == null) {+ cancellations = [];+ restore();+ return;+ }+ cancellations = links.map((link, index) =>+ drawBadgedFavicon(originals[index], color, (dataUrl) => {+ link.href = dataUrl;+ }),+ );+ };++ paint();++ /* The badge colour is a theme role, and switching theme changes it without changing the+ count. Watching the root's theme attributes repaints on every theme, custom ones+ included, without coupling this to the theme provider's shape. */+ const themeObserver = new MutationObserver(paint);+ themeObserver.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['class', 'data-theme'],+ });++ return () => {+ themeObserver.disconnect();+ for (const cancel of cancellations) {+ cancel();+ }+ /* Signing out unmounts the host, and a badged data URL left behind would show the+ previous account's unread count on the login page. */+ restore();+ };+ }, [activeCount]);+}diff --git a/client/src/hooks/Conversations/useUnseenConversations.ts b/client/src/hooks/Conversations/useUnseenConversations.tsnew file mode 100644index 0000000000..9c7d11c2cd--- /dev/null+++ b/client/src/hooks/Conversations/useUnseenConversations.ts@@ -0,0 +1,356 @@+import { useRef, useState, useEffect, useCallback } from 'react';+import { QueryKeys } from 'librechat-data-provider';+import { useQueryClient } from '@tanstack/react-query';+import type { Query, QueryClient, InfiniteData } from '@tanstack/react-query';+import type { TConversation } from 'librechat-data-provider';+import type { ConversationCursorData, PinnedConversationsData } from '~/utils/convos';+import type { ConvoCandidate } from '~/utils';+import {+ convoQueryAuthority,+ freshestCandidate,+ isConversationUnseen,+ trackConvoQueryAuthority,+ isAggregateQueryAuthoritative,+} from '~/utils';++export type UnseenConversation = {+ conversationId: string;+ title: string;+ /** The reply that made it unseen; a later one to the same chat is its own arrival. */+ lastResponseAt: string;+ /** The indicator comes from "mark as unread" on a conversation that has never been replied+ * to, so the stamp is the manual flag rather than a reply the alerts should announce. */+ flagged: boolean;+};++export type ReplyReadState = {+ unseen: UnseenConversation[];+ /** The reply stamp of every replied-to conversation in cache, seen rows included. The alerts'+ * baseline on it: a seen conversation marked unread from another device re-enters `unseen`+ * carrying the stamp it always had, which only this record can tell from a new reply. */+ stamps: Array<[conversationId: string, lastResponseAt: string]>;+ /** Reply stamps observed when a known row changed through a local cache merge. */+ arrivalStamps: Array<[conversationId: string, lastResponseAt: string]>;+};++/** How often the aggregate re-checks that deadline on its own; see the effect below. */+const LEFTOVER_SWEEP_MS = 60_000;++/** Null until a conversation list has actually resolved, which is not the same as an empty+ * one: treating "not loaded yet" as "nothing unseen" makes the backlog look like arrivals. */+const readReplyState = (+ queryClient: QueryClient,+ arrivalStamps: ReplyReadState['arrivalStamps'],+): ReplyReadState | null => {+ /* Keyed rather than first-wins: the same row is cached once per list variant and only the+ mounted ones refetch, so an older copy would otherwise shadow a newer reply and drop it+ from the count. `freshestCandidate` settles which copy is actually current. */+ const byId = new Map<string, ConvoCandidate>();+ let hasList = false;++ const collect = (convo: TConversation, authority: Omit<ConvoCandidate, 'convo'>) => {+ const { conversationId } = convo;+ if (!conversationId) {+ return;+ }+ byId.set(+ conversationId,+ freshestCandidate(byId.get(conversationId), { convo, ...authority }) ?? {+ convo,+ ...authority,+ },+ );+ };++ const listQueries = queryClient+ .getQueryCache()+ .findAll([QueryKeys.allConversations], { exact: false });++ for (const query of listQueries) {+ const data = queryClient.getQueryData<InfiniteData<ConversationCursorData>>(query.queryKey);+ const authority = convoQueryAuthority(queryClient, query);+ if (!data || !isAggregateQueryAuthoritative(queryClient, query)) {+ continue;+ }+ hasList = true;+ for (const page of data.pages) {+ for (const convo of page.conversations) {+ collect(convo, authority);+ }+ }+ }++ /* The pinned section is fed by its own request, so a pin older than the loaded chat pages+ lives only here. Skipping it would show that row's dot while the tab count and the alerts+ never counted it. Readiness still keys on the chats list, which is the one the backlog+ arrives in. */+ const pinnedQueries = queryClient+ .getQueryCache()+ .findAll([QueryKeys.pinnedConversations], { exact: false });++ for (const query of pinnedQueries) {+ const data = queryClient.getQueryData<PinnedConversationsData>(query.queryKey);+ const authority = convoQueryAuthority(queryClient, query);+ if (!data || !isAggregateQueryAuthoritative(queryClient, query)) {+ continue;+ }+ for (const convo of data.conversations) {+ collect(convo, authority);+ }+ }++ if (!hasList) {+ return null;+ }++ const unseen: UnseenConversation[] = [];+ const stamps: ReplyReadState['stamps'] = [];+ for (const [conversationId, candidate] of byId) {+ const { convo } = candidate;+ const { lastResponseAt } = convo;+ if (!lastResponseAt) {+ continue;+ }+ const flagged = convo.lastResponseIsManual === true;+ /* Manual markers are state, not replies. Keep them out of the alert baseline so the first+ real reply after a mark-unread remains an arrival even when it shares a millisecond. */+ if (!flagged) {+ stamps.push([conversationId, lastResponseAt]);+ }+ if (isConversationUnseen(convo)) {+ unseen.push({+ conversationId,+ title: convo.title ?? '',+ lastResponseAt,+ flagged,+ });+ }+ }+ /* Ordered by id so the identity below does not depend on cache scan order. */+ stamps.sort(([a], [b]) => a.localeCompare(b));+ return { unseen, stamps, arrivalStamps };+};++type ArrivalSnapshot = Map<string, string | null>;+type ArrivalSnapshots = Map<string, ArrivalSnapshot | null>;+type ArrivalEvidence = Map<string, string>;+type ArrivalMode = 'server' | 'local' | 'none';++const snapshotForQuery = (query: Query): ArrivalSnapshot | null => {+ const data = query.state.data as+ | InfiniteData<ConversationCursorData>+ | PinnedConversationsData+ | undefined;+ if (!data) {+ return null;+ }+ const snapshot: ArrivalSnapshot = new Map();+ const pages = 'pages' in data ? data.pages : [data];+ for (const page of pages) {+ for (const convo of page.conversations) {+ if (convo.conversationId) {+ /* Keep user-only rows in the snapshot. A locally merged first reply must be distinguishable+ * from a conversation that was newly discovered by a later page or query variant. */+ snapshot.set(convo.conversationId, convo.lastResponseAt ?? null);+ }+ }+ }+ return snapshot;+};++const observeArrivalQuery = (+ query: Query,+ snapshots: ArrivalSnapshots,+ evidence: ArrivalEvidence,+ mode: ArrivalMode,+): void => {+ const current = snapshotForQuery(query);+ const previous = snapshots.get(query.queryHash);+ /* The watcher names the conversations a discovery refresh was started for. Those are live on+ the query it creates; every other row on that first page is backlog this session has never+ observed, and announcing it would greet the user with their whole unseen history. */+ const discovered = query.meta?.replyDiscovery;+ const discoveredIds = Array.isArray(discovered) ? new Set(discovered as string[]) : null;+ const isLiveDiscovery = mode === 'server' && (discoveredIds?.size ?? 0) > 0;+ if (current === null || (previous == null && !isLiveDiscovery)) {+ snapshots.set(query.queryHash, current);+ return;+ }+ if (mode !== 'none') {+ const data = query.state.data as InfiniteData<ConversationCursorData> | PinnedConversationsData;+ const pages = 'pages' in data ? data.pages : [data];+ /* A server response is read on its first page, where a reply lands and where discovery+ names what it found. A local merge can touch a row wherever the list holds it: a title+ or oldest-first sort leaves a replied row on a later page, and missing it there would add+ its stamp to the baseline with no arrival behind it. Only rows the previous snapshot+ already knew are considered below, so this cannot announce backlog. */+ const candidates =+ mode === 'local'+ ? pages.flatMap((page) => page.conversations)+ : (pages[0]?.conversations ?? []);+ for (const convo of candidates) {+ const { conversationId, lastResponseAt } = convo;+ if (+ !conversationId ||+ !lastResponseAt ||+ convo.lastResponseIsManual === true ||+ (mode === 'local' && !previous?.has(conversationId))+ ) {+ continue;+ }+ if (previous == null && discoveredIds?.has(conversationId) !== true) {+ continue;+ }+ /* An unknown row can enter this page because it was renamed. Real reply writes advance+ both stamps together; a later metadata-only update must not announce old backlog. */+ if (!previous?.has(conversationId) && convo.updatedAt !== lastResponseAt) {+ continue;+ }+ if (previous?.get(conversationId) === lastResponseAt) {+ continue;+ }+ const recorded = evidence.get(conversationId);+ if (recorded === undefined || lastResponseAt > recorded) {+ evidence.set(conversationId, lastResponseAt);+ }+ }+ }+ snapshots.set(query.queryHash, current);+};++/**+ * How many arrivals are remembered before the dead ones are swept.+ *+ * Every refresh copies and sorts this map into the state identity, so in a tab left open across+ * many replies its cost would otherwise grow with the lifetime number of arrivals rather than+ * with the live cache. The bound is generous enough that an ordinary session never sweeps.+ */+const ARRIVAL_EVIDENCE_BOUND = 500;++/**+ * Drops evidence for conversations no observed snapshot still holds.+ *+ * An entry earns its place by baselining a row the alerts may still meet again; once the row+ * has left every list the cache knows, nothing can consult it, and a deleted or evicted+ * conversation would otherwise be remembered for the life of the tab.+ */+const pruneArrivalEvidence = (snapshots: ArrivalSnapshots, evidence: ArrivalEvidence): void => {+ const live = new Set<string>();+ for (const snapshot of snapshots.values()) {+ if (snapshot === null) {+ continue;+ }+ for (const conversationId of snapshot.keys()) {+ live.add(conversationId);+ }+ }+ for (const conversationId of evidence.keys()) {+ if (!live.has(conversationId)) {+ evidence.delete(conversationId);+ }+ }+};++const readArrivalStamps = (evidence: ArrivalEvidence): ReplyReadState['arrivalStamps'] =>+ [...evidence.entries()].sort(([a], [b]) => a.localeCompare(b));++/* Title and reply stamp are part of the identity, not just the id: a conversation is auto-titled+ moments after the reply that made it unseen, and a second reply to an already-unseen chat has+ to reach the alerts as its own arrival. The seen rows' stamps count too, so the alerts'+ baseline keeps up with replies that were caught up the moment they landed. */+const identityOf = (state: ReplyReadState | null): string =>+ state === null+ ? 'pending'+ : JSON.stringify([+ state.unseen+ .map((c): [string, string, string] => [c.conversationId, c.title, c.lastResponseAt])+ .sort(([a], [b]) => a.localeCompare(b)),+ state.stamps,+ state.arrivalStamps,+ ]);++/**+ * The set of conversations that have replied since the user last caught up with them, alongside+ * the reply stamps of everything the cache knows.+ *+ * Derived from the conversation list already in cache, so it costs no request of its own and+ * needs no count endpoint. A reply lifts its conversation, so an unseen one normally sits on the+ * first page. "Mark as unread" is the exception: it deliberately leaves `updatedAt` alone, and+ * its explicit manual marker is counted only once its page is loaded. Its own row still shows the+ * indicator; only this aggregate waits.+ *+ * Subscribing to the query cache (rather than mounting a second list query) avoids duplicating+ * the sidebar's fetch. Cache events are filtered by key before any recomputation, because they+ * also fire for message updates on every streamed token.+ *+ * Returns null while no list has resolved yet, so callers can tell "nothing is unseen" apart+ * from "nothing is known".+ */+export default function useUnseenConversations(): ReplyReadState | null {+ const queryClient = useQueryClient();+ const arrivalSnapshots = useRef<ArrivalSnapshots>(new Map());+ const arrivalEvidence = useRef<ArrivalEvidence>(new Map());+ const [state, setState] = useState<ReplyReadState | null>(() => readReplyState(queryClient, []));++ const refresh = useCallback(() => {+ const next = readReplyState(queryClient, readArrivalStamps(arrivalEvidence.current));+ setState((current) => (identityOf(current) === identityOf(next) ? current : next));+ }, [queryClient]);++ useEffect(() => {+ const cache = queryClient.getQueryCache();+ trackConvoQueryAuthority(queryClient);++ for (const query of cache.getAll()) {+ const root = query.queryKey?.[0];+ if (+ root === QueryKeys.allConversations ||+ root === QueryKeys.pinnedConversations ||+ root === QueryKeys.conversation+ ) {+ convoQueryAuthority(queryClient, query);+ if (root === QueryKeys.allConversations || root === QueryKeys.pinnedConversations) {+ observeArrivalQuery(query, arrivalSnapshots.current, arrivalEvidence.current, 'none');+ }+ }+ }++ const unsubscribe = cache.subscribe((event) => {+ const { query } = event;+ const root = query.queryKey?.[0];+ if (+ root !== QueryKeys.allConversations &&+ root !== QueryKeys.pinnedConversations &&+ root !== QueryKeys.conversation+ ) {+ return;+ }+ convoQueryAuthority(queryClient, query);+ if (event.type === 'removed') {+ arrivalSnapshots.current.delete(query.queryHash);+ pruneArrivalEvidence(arrivalSnapshots.current, arrivalEvidence.current);+ } else if (root === QueryKeys.allConversations || root === QueryKeys.pinnedConversations) {+ let mode: ArrivalMode = 'none';+ if (event.type === 'updated' && event.action.type === 'success') {+ mode = event.action.manual === true ? 'local' : 'server';+ }+ observeArrivalQuery(query, arrivalSnapshots.current, arrivalEvidence.current, mode);+ if (arrivalEvidence.current.size > ARRIVAL_EVIDENCE_BOUND) {+ pruneArrivalEvidence(arrivalSnapshots.current, arrivalEvidence.current);+ }+ }+ refresh();+ });+ refresh();+ /* Crossing the leftover deadline is not a cache event, so an otherwise idle tab would keep+ * counting a phantom row until something else happened to touch the caches. Recomputing on+ * a slow tick costs a scan of what is already in memory and no request. */+ const tick = window.setInterval(refresh, LEFTOVER_SWEEP_MS);+ return () => {+ window.clearInterval(tick);+ unsubscribe();+ };+ }, [queryClient, refresh]);++ return state;+}diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.tsindex b1d1bf6dec..55b3193467 100644--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts@@ -1,4 +1,5 @@import { getDefaultStore } from 'jotai';+import { QueryClient } from '@tanstack/react-query';import { renderHook, act, waitFor } from '@testing-library/react';import {Constants,@@ -10,7 +11,7 @@ import {request,} from 'librechat-data-provider';import type { TMessage, TSubmission } from 'librechat-data-provider';-import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';+import type { Query, QueryKey } from '@tanstack/react-query';import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';type SSEEventListener = (e: Partial<MessageEvent> & { responseCode?: number }) => void;@@ -65,7 +66,9 @@ const mockGetQueryData = jest.fn();const mockFetchQuery = jest.fn();const mockInvalidateQueries = jest.fn();const mockRemoveQueries = jest.fn();-const mockFindAll = jest.fn((_queryKey?: unknown): Array<{ queryKey: unknown[] }> => []);+const mockBackingQueryClient = new QueryClient();+const mockQueryCache = mockBackingQueryClient.getQueryCache();+const mockFindAll = jest.fn((_queryKey?: QueryKey): Query[] => []);const mockQueryClient = {setQueryData: mockSetQueryData,getQueryData: mockGetQueryData,@@ -74,6 +77,9 @@ const mockQueryClient = {removeQueries: mockRemoveQueries,getQueryCache: () => ({findAll: mockFindAll,+ getAll: mockQueryCache.getAll.bind(mockQueryCache),+ find: mockQueryCache.find.bind(mockQueryCache),+ subscribe: mockQueryCache.subscribe.bind(mockQueryCache),}),};@@ -378,7 +384,9 @@ describe('useResumableSSE', () => {);mockInvalidateQueries.mockClear();mockRemoveQueries.mockClear();- mockFindAll.mockClear();+ mockFindAll.mockReset();+ mockFindAll.mockReturnValue([]);+ mockBackingQueryClient.clear();mockUseSetRecoilStateMock.mockClear();mockSetActiveRun.mockClear();mockSetAbortScroll.mockClear();@@ -507,8 +515,8 @@ describe('useResumableSSE', () => {mockGetConversationById.mockRejectedValueOnce({ response: { status: 404 } });/* Key-aware: the conversation cache helpers now run a second, pinned-keyed pass,and a fixed return value would attribute those writes to allConversations. */- mockFindAll.mockImplementation((queryKey?: unknown) => [- { queryKey: [(queryKey as unknown[])[0]] },+ mockFindAll.mockImplementation((queryKey?: QueryKey) => [+ mockQueryCache.build(mockBackingQueryClient, { queryKey: [queryKey![0]] as QueryKey }),]);const submission = buildSubmission({conversation: {},@@ -650,8 +658,8 @@ describe('useResumableSSE', () => {it('reconciles conversations via refetch instead of removing them on a resume 404', async () => {/* Key-aware: the conversation cache helpers now run a second, pinned-keyed pass,and a fixed return value would attribute those writes to allConversations. */- mockFindAll.mockImplementation((queryKey?: unknown) => [- { queryKey: [(queryKey as unknown[])[0]] },+ mockFindAll.mockImplementation((queryKey?: QueryKey) => [+ mockQueryCache.build(mockBackingQueryClient, { queryKey: [queryKey![0]] as QueryKey }),]);// A deduped start returns status: 'resumed', so the client subscribes with resume=true.(request.post as jest.Mock).mockResolvedValue({ streamId: 'stream-123', status: 'resumed' });@@ -4983,8 +4991,8 @@ describe('useResumableSSE', () => {it('removes the optimistic sidebar row when a new conversation errors before created', async () => {/* Key-aware: the conversation cache helpers now run a second, pinned-keyed pass,and a fixed return value would attribute those writes to allConversations. */- mockFindAll.mockImplementation((queryKey?: unknown) => [- { queryKey: [(queryKey as unknown[])[0]] },+ mockFindAll.mockImplementation((queryKey?: QueryKey) => [+ mockQueryCache.build(mockBackingQueryClient, { queryKey: [queryKey![0]] as QueryKey }),]);const submission = buildSubmission({conversation: {},diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.tsindex e202d545ff..f40b60d3f5 100644--- a/client/src/hooks/SSE/useEventHandlers.ts+++ b/client/src/hooks/SSE/useEventHandlers.ts@@ -37,6 +37,8 @@ import {getAllContentText,upsertConvoInAllQueries,updateConvoInAllQueries,+ applyServerReplyStamp,+ markLocallyCommittedReply,removeConvoFromAllQueries,findConversationInInfinite,preserveStreamedContentIdentity,@@ -370,6 +372,46 @@ export interface ErrorTurn {}/** Builds the row a failed turn leaves in the transcript and names the conversation it belongs to. */+type SettledErrorReadState = {+ lastResponseAt: string;+ lastResponseMessageId?: string;+ updatedAt?: string;+};++/**+ * A persisted terminal error still carries the server's winning reply stamp in its nested+ * conversation snapshot. Pairing the error messages cache object with that stamp before the list+ * update lets `useConversationSeen` acknowledge the reply the user just watched fail, instead of+ * leaving a dot on a conversation they are looking at.+ */+const resolveSettledErrorReadState = ({+ data,+ submission,+ conversationId,+}: {+ data?: TResData;+ submission: EventSubmission;+ conversationId: string;+}): SettledErrorReadState | undefined => {+ if (submission.isTemporary === true || !data || !conversationId) {+ return undefined;+ }+ const settledConversation = data.conversation;+ const lastResponseAt = settledConversation?.lastResponseAt;+ if (typeof lastResponseAt !== 'string' || lastResponseAt.length === 0) {+ return undefined;+ }+ return {+ lastResponseAt,+ lastResponseMessageId:+ typeof settledConversation.lastResponseMessageId === 'string'+ ? settledConversation.lastResponseMessageId+ : undefined,+ updatedAt:+ typeof settledConversation.updatedAt === 'string' ? settledConversation.updatedAt : undefined,+ };+};+export const resolveErrorTurn = ({data,submission,@@ -1162,6 +1204,21 @@ export default function useEventHandlers({* holds for a stopped turn too: the server persists a title that finished* generating before the Stop, so the local one stays in sync. */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. */+ const serverLastResponseAt = serverConversation.lastResponseAt;+ if (conversation.conversationId && !_isTemporary && serverLastResponseAt) {+ markLocallyCommittedReply(+ queryClient,+ conversation.conversationId,+ serverLastResponseAt,+ );+ applyServerReplyStamp(queryClient, conversation.conversationId, {+ lastResponseAt: serverLastResponseAt,+ lastResponseMessageId: serverConversation.lastResponseMessageId,+ updatedAt: serverConversation.updatedAt,+ });+ }setConversation((prevState) => {const update = keepLocalCodeApprovalMode({ ...prevState, ...(conversation as TConversation) },@@ -1257,6 +1314,11 @@ export default function useEventHandlers({const finalMessages = mergeErrorMessages({ ...submission, errorMessage: errorResponse });setMessages(finalMessages);queryClient.setQueryData<TMessage[]>([QueryKeys.messages, conversationId], finalMessages);+ const settled = resolveSettledErrorReadState({ data, submission, conversationId });+ if (settled) {+ markLocallyCommittedReply(queryClient, conversationId, settled.lastResponseAt);+ applyServerReplyStamp(queryClient, conversationId, settled);+ }if (recover) {recoverConversation(conversationId, submission);}diff --git a/client/src/hooks/useDocumentTitle.ts b/client/src/hooks/useDocumentTitle.tsindex 3e2bc3a2ec..23e817c8fb 100644--- a/client/src/hooks/useDocumentTitle.ts+++ b/client/src/hooks/useDocumentTitle.ts@@ -1,20 +1,10 @@-// useDocumentTitle.jsimport { useEffect } from 'react';+import { setDocumentTitle } from '~/utils';-// function useDocumentTitle(title, prevailOnUnmount = false) {-// const defaultTitle = useRef(document.title);function useDocumentTitle(title: string) {useEffect(() => {- document.title = title;+ setDocumentTitle(title, true);}, [title]);-- // useEffect(- // () => () => {- // if (!prevailOnUnmount) {- // document.title = defaultTitle.current;- // }- // }, []- // );}export default useDocumentTitle;diff --git a/client/src/hooks/useNewConvo.ts b/client/src/hooks/useNewConvo.tsindex 8424dd2954..05ad4a9b12 100644--- a/client/src/hooks/useNewConvo.ts+++ b/client/src/hooks/useNewConvo.ts@@ -45,6 +45,7 @@ import {retainFileDeletion,failedFileIdsFrom,logger,+ setDocumentTitle,} from '~/utils';import { useDeleteFilesMutation, useGetEndpointsQuery, useGetStartupConfig } from '~/data-provider';import { supersedeNavigation } from './Conversations/useNavigateToConvo';@@ -288,7 +289,7 @@ const useNewConvo = (index = 0) => {if (conversation.conversationId === Constants.NEW_CONVO && !modelsData) {const appTitle = localStorage.getItem(LocalStorageKeys.APP_TITLE) ?? '';if (appTitle) {- document.title = appTitle;+ setDocumentTitle(appTitle, true);}const path = `/c/${Constants.NEW_CONVO}${getParams(conversation)}`;/** Honor disableFocus here too: the transient focus intent survivesdiff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 4ebd5b733e..7b39d8b810 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -775,6 +775,8 @@"com_nav_info_fork_split_target_setting": "When enabled, forking will commence from the target message to the latest message in the conversation, according to the behavior selected.","com_nav_info_latex_parsing": "When enabled, LaTeX code in messages will be rendered as mathematical equations. Disabling this may improve performance if you don't need LaTeX rendering.","com_nav_info_paste_long_text_as_file": "When enabled, pasting very long text attaches it as a text file instead of filling the message box. File processing limits may apply.",+ "com_nav_info_reply_notification_sound": "Play a short chime when a reply arrives while you are away from LibreChat. Browsers block audio until you have interacted with the page, so the first chime after opening a tab may not play.",+ "com_nav_info_reply_notifications": "Show a desktop notification when a reply arrives while you are away from LibreChat. Your browser will ask for permission the first time you enable this. Notifications are not shown while you are looking at LibreChat, since the conversation list already marks the reply.","com_nav_info_save_badges_state": "When enabled, the state of the chat badges will be saved. This means that if you create a new chat, the badges will remain in the same state as the previous chat. If you disable this option, the badges will reset to their default state every time you create a new chat","com_nav_info_save_draft": "When enabled, the text and attachments you enter in the chat form will be automatically saved locally as drafts. These drafts will be available even if you reload the page or switch to a different conversation. Drafts are stored locally on your device and are deleted once the message is sent.","com_nav_info_show_thinking": "When enabled, the chat will display the thinking dropdowns open by default, allowing you to view the AI's reasoning in real-time. When disabled, the thinking dropdowns will remain closed by default for a cleaner and more streamlined interface",@@ -782,6 +784,7 @@"com_nav_info_stateful_sessions": "When enabled, this agent uses the dedicated stateful Code API instead of the default stateless service. Retained files under /mnt/data carry across runs, but each run starts a fresh process. Shell variables, the working directory, $HOME, temporary files, global installs, and background processes are not durable. The runtime may reset, so keep anything important under /mnt/data. Requires Code Interpreter and the app-level stateful sessions capability.","com_nav_info_stateful_code_environment": "Choose who shares this agent's stateful workspace. This does not share live files with stateless code sessions.","com_nav_info_tool_background": "When enabled, the model can run this tool in the background: the conversation continues immediately while the tool runs, and the model retrieves the result later with the background task tool. Requires the app-level background tools capability.",+ "com_nav_info_unseen_tab_badge": "Show the number of conversations with unread replies in the browser tab title and icon.","com_nav_info_user_name_display": "When enabled, the username of the sender will be shown above each message you send. When disabled, you will only see \"You\" above your messages.","com_nav_keep_screen_awake": "Keep screen awake during response generation","com_nav_lang_arabic": "العربية",@@ -857,6 +860,8 @@"com_nav_plus_command": "+-Command","com_nav_plus_command_description": "Toggle command \"+\" for adding a multi-response setting","com_nav_profile_picture": "Profile Picture",+ "com_nav_reply_notification_sound": "Play a sound for new replies",+ "com_nav_reply_notifications": "Notify me when a reply arrives","com_nav_save_badges_state": "Save badges state","com_nav_save_drafts": "Save drafts locally","com_nav_scroll_button": "Scroll to the end button",@@ -889,6 +894,7 @@"com_nav_tool_dialog_description": "Assistant must be saved to persist tool selections.","com_nav_tool_remove": "Remove","com_nav_tool_search": "Search tools",+ "com_nav_unseen_tab_badge": "Show unread count in the tab title","com_nav_user": "USER","com_nav_user_msg_markdown": "Render user messages as markdown","com_nav_user_name_display": "Display username in messages",@@ -1771,6 +1777,8 @@"com_ui_make_production": "Make Production","com_ui_manage": "Manage","com_ui_manage_web_search_api_keys": "Manage Web Search API Keys",+ "com_ui_mark_unread": "Mark as unread",+ "com_ui_mark_unread_error": "Failed to mark conversation as unread","com_ui_marketplace": "Marketplace","com_ui_marketplace_allow_use": "Allow using Marketplace","com_ui_max": "Max",@@ -2108,6 +2116,7 @@"com_ui_reference_saved_memories": "Reference saved memories","com_ui_reference_saved_memories_description": "Allow the assistant to reference and use your saved memories when responding","com_ui_referenced_quotes": "Referenced quotes",+ "com_ui_reply_ready": "Your reply is ready","com_ui_refresh": "Refresh","com_ui_refresh_page": "Refresh page","com_ui_regenerate": "Regenerate",@@ -2359,6 +2368,7 @@"com_ui_settings_section_memory": "Memory","com_ui_settings_section_code_execution": "Code execution","com_ui_settings_section_messages": "Messages",+ "com_ui_settings_section_notifications": "Notifications","com_ui_settings_section_profile": "Profile","com_ui_settings_section_prompts": "Prompts","com_ui_settings_section_security": "Security",@@ -2925,6 +2935,7 @@"com_ui_unknown_file_type": "Unknown file type","com_ui_unpin": "Unpin","com_ui_unpin_error": "Failed to unpin conversation",+ "com_ui_unread": "Unread","com_ui_unset": "Unset","com_ui_untitled": "Untitled","com_ui_unsaved_changes": "Unsaved changes",diff --git a/client/src/routes/Layouts/Startup.tsx b/client/src/routes/Layouts/Startup.tsxindex 16e5d6f1d4..d9c3ee819f 100644--- a/client/src/routes/Layouts/Startup.tsx+++ b/client/src/routes/Layouts/Startup.tsx@@ -1,7 +1,7 @@import { useEffect, useState } from 'react';import { Outlet, useNavigate, useLocation } from 'react-router-dom';import type { TStartupConfig } from 'librechat-data-provider';-import { REDIRECT_PARAM, hasStoredRedirect } from '~/utils';+import { DEFAULT_APP_TITLE, REDIRECT_PARAM, SESSION_KEY, setDocumentTitle } from '~/utils';import { TranslationKeys, useLocalize } from '~/hooks';import { useGetStartupConfig } from '~/data-provider';import AuthLayout from '~/components/Auth/AuthLayout';@@ -43,7 +43,7 @@ export default function StartupLayout({ isAuthenticated }: { isAuthenticated?: b}, [isAuthenticated, navigate, data]);useEffect(() => {- document.title = startupConfig?.appTitle || 'LibreChat';+ setDocumentTitle(startupConfig?.appTitle || DEFAULT_APP_TITLE, true);}, [startupConfig?.appTitle]);useEffect(() => {diff --git a/client/src/routes/Root.tsx b/client/src/routes/Root.tsxindex 263d53747f..19c7a82f1d 100644--- a/client/src/routes/Root.tsx+++ b/client/src/routes/Root.tsx@@ -2,6 +2,18 @@ import { useState, useEffect, useRef, useCallback, startTransition } from 'reactimport { useRecoilValue } from 'recoil';import { Outlet } from 'react-router-dom';import { useMediaQuery } from '@librechat/client';+import {+ useFileMap,+ useAgentsMap,+ useAuthContext,+ useReplyAlerts,+ useUnseenBadge,+ useReplyWatcher,+ useSearchEnabled,+ useCatalogWarmup,+ useAssistantsMap,+ useUnseenConversations,+} from '~/hooks';import {UnifiedSidebar,SIDEBAR_TRANSITION,@@ -21,14 +33,6 @@ import {SetConvoProvider,FileMapContext,} from '~/Providers';-import {- useSearchEnabled,- useAssistantsMap,- useAuthContext,- useCatalogWarmup,- useAgentsMap,- useFileMap,-} from '~/hooks';import KeyboardShortcutsDialog from '~/components/Nav/KeyboardShortcutsDialog';import KeyboardDeleteDialog from '~/components/Nav/KeyboardDeleteDialog';import { useUserTermsQuery, useGetStartupConfig } from '~/data-provider';@@ -43,6 +47,15 @@ import { useHealthCheck } from '~/data-provider';import { Banner } from '~/components/Banners';import store from '~/store';+/** Isolates the unseen-reply subscription so its updates re-render only this node, not `Root`. */+function ReplyNotifications() {+ const replyState = useUnseenConversations();+ useReplyWatcher();+ useUnseenBadge(replyState?.unseen.length ?? 0);+ useReplyAlerts(replyState);+ return null;+}+/** Isolates keyboard shortcut listeners so they only mount after auth. */function KeyboardShortcutsProvider() {useKeyboardShortcuts();@@ -207,6 +220,7 @@ export default function Root() {</div></PromptGroupsProvider><KeyboardShortcutsProvider />+ <ReplyNotifications /></AgentsMapContext.Provider>{config?.interface?.termsOfService?.modalAcceptance === true && (<TermsAndConditionsModaldiff --git a/client/src/utils/convos.spec.ts b/client/src/utils/convos.spec.tsindex 544ffcd4e3..0e0dd5bfa2 100644--- a/client/src/utils/convos.spec.ts+++ b/client/src/utils/convos.spec.ts@@ -14,6 +14,10 @@ import {collectPinnedConversations,upsertConvoInAllQueries,updateConvoInAllQueries,+ findConvoInAllQueries,+ isConvoInAggregateCaches,+ isConversationUnseen,+ applyServerReplyStamp,removeConvoFromAllQueries,addConversationToAllConversationsQueries,invalidateConversationLists,@@ -759,6 +763,48 @@ describe('Conversation Utilities', () => {});});+ describe('isConversationUnseen', () => {+ it('treats a conversation with no reply as seen', () => {+ expect(isConversationUnseen({})).toBe(false);+ });++ it('treats a reply with no catch-up as unseen', () => {+ expect(isConversationUnseen({ lastResponseAt: '2026-08-16T10:00:00.000Z' })).toBe(true);+ });++ it('treats a catch-up older than the reply as unseen', () => {+ expect(+ isConversationUnseen({+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastSeenAt: '2026-08-16T09:00:00.000Z',+ }),+ ).toBe(true);+ });++ it('treats equal timestamps as seen, the fail-safe direction', () => {+ expect(+ isConversationUnseen({+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastSeenAt: '2026-08-16T10:00:00.000Z',+ }),+ ).toBe(false);+ });++ it('treats a catch-up newer than the reply as seen', () => {+ expect(+ isConversationUnseen({+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastSeenAt: '2026-08-16T11:00:00.000Z',+ }),+ ).toBe(false);+ });++ it('handles null and undefined conversations', () => {+ expect(isConversationUnseen(undefined)).toBe(false);+ expect(isConversationUnseen(null)).toBe(false);+ });+ });+describe('QueryClient helpers', () => {let queryClient: QueryClient;let convoA: TConversation;@@ -786,6 +832,67 @@ describe('Conversation Utilities', () => {});});+ describe('applyServerReplyStamp', () => {+ const REPLY_AT = '2024-01-03T12:00:00Z';+ const NEWER_REPLY_AT = '2024-01-04T12:00:00Z';++ beforeEach(() => {+ queryClient.setQueryData(['allConversations'], {+ pages: [{ conversations: [convoB, convoA], nextCursor: null }],+ pageParams: [],+ });+ });++ const rows = () =>+ queryClient.getQueryData<InfiniteData<any>>(['allConversations'])!.pages[0].conversations;++ it('carries the row to the top when the reply advanced its activity date', () => {+ /* Another conversation took the top while this one streamed; leaving the completed+ one behind would show it at its run-start date and position. */+ applyServerReplyStamp(queryClient, 'a', {+ lastResponseAt: REPLY_AT,+ updatedAt: REPLY_AT,+ });++ expect(rows()[0]).toMatchObject({+ conversationId: 'a',+ lastResponseAt: REPLY_AT,+ updatedAt: REPLY_AT,+ });+ });++ it('leaves the order alone when the payload carries no activity date', () => {+ applyServerReplyStamp(queryClient, 'a', { lastResponseAt: REPLY_AT });++ expect(rows()[0].conversationId).toBe('b');+ expect(rows()[1]).toMatchObject({+ conversationId: 'a',+ lastResponseAt: REPLY_AT,+ updatedAt: convoA.updatedAt,+ });+ });++ it('drops a stamp older than the one already cached', () => {+ /* Two responses finishing out of order: the newer stamp is already in the cache from+ an away poll or a completion merge, and writing the older one back would let that+ newer reply arrive a second time. */+ applyServerReplyStamp(queryClient, 'a', {+ lastResponseAt: NEWER_REPLY_AT,+ updatedAt: NEWER_REPLY_AT,+ });+ applyServerReplyStamp(queryClient, 'a', {+ lastResponseAt: REPLY_AT,+ updatedAt: REPLY_AT,+ });++ expect(rows()[0]).toMatchObject({+ conversationId: 'a',+ lastResponseAt: NEWER_REPLY_AT,+ updatedAt: NEWER_REPLY_AT,+ });+ });+ });+it('addConvoToAllQueries adds new on top if not present', () => {addConvoToAllQueries(queryClient, convoB);const data = queryClient.getQueryData<InfiniteData<any>>(['allConversations']);@@ -1047,6 +1154,303 @@ describe('Conversation Utilities', () => {expect(data!.pages[0].conversations[0].isShared).toBe(false);});+ it('updateConvoInAllQueries keeps the unseen fields when a caller replaces the convo', () => {+ updateConvoInAllQueries(queryClient, 'a', (c) => ({+ ...c,+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastResponseMessageId: 'reply-a',+ lastResponseIsManual: true,+ lastSeenAt: '2026-08-16T09:00:00.000Z',+ }));+ // SSE/rename style update that swaps in a payload without the unseen fields.+ updateConvoInAllQueries(+ queryClient,+ 'a',+ () =>+ ({+ conversationId: 'a',+ title: 'Renamed',+ }) as TConversation,+ );++ const data = queryClient.getQueryData<InfiniteData<any>>(['allConversations']);+ expect(data!.pages[0].conversations[0].lastResponseAt).toBe('2026-08-16T10:00:00.000Z');+ expect(data!.pages[0].conversations[0].lastResponseIsManual).toBe(true);+ expect(data!.pages[0].conversations[0].lastSeenAt).toBe('2026-08-16T09:00:00.000Z');+ /* The reply's identity is what ties the dot to the branch it landed on; dropping it+ reads as "visible", which can acknowledge a reply on a hidden sibling branch. */+ expect(data!.pages[0].conversations[0].lastResponseMessageId).toBe('reply-a');+ });++ it('updateConvoInAllQueries lets an explicit lastSeenAt win over the cached one', () => {+ updateConvoInAllQueries(queryClient, 'a', (c) => ({+ ...c,+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastSeenAt: '2026-08-16T09:00:00.000Z',+ }));+ updateConvoInAllQueries(queryClient, 'a', (c) => ({+ ...c,+ lastSeenAt: '2026-08-16T11:00:00.000Z',+ }));++ const data = queryClient.getQueryData<InfiniteData<any>>(['allConversations']);+ expect(data!.pages[0].conversations[0].lastSeenAt).toBe('2026-08-16T11:00:00.000Z');+ });++ it('updateConvoInAllQueries clears lastSeenAt when the updater says so explicitly', () => {+ /* Mark-unread needs to express "not caught up", which an undefined value+ carries forward only when the key itself is absent. */+ updateConvoInAllQueries(queryClient, 'a', (c) => ({+ ...c,+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastSeenAt: '2026-08-16T11:00:00.000Z',+ }));+ updateConvoInAllQueries(queryClient, 'a', (c) => ({+ ...c,+ lastSeenAt: undefined,+ }));++ const data = queryClient.getQueryData<InfiniteData<any>>(['allConversations']);+ expect(data!.pages[0].conversations[0].lastSeenAt).toBeUndefined();+ expect(data!.pages[0].conversations[0].lastResponseAt).toBe('2026-08-16T10:00:00.000Z');+ });++ it('findConvoInAllQueries reads from whichever cached list query holds the conversation', () => {+ queryClient.setQueryData(['allConversations', { isArchived: true }], {+ pages: [{ conversations: [convoB], nextCursor: null }],+ pageParams: [],+ });++ expect(findConvoInAllQueries(queryClient, 'a')?.conversationId).toBe('a');+ expect(findConvoInAllQueries(queryClient, 'b')?.conversationId).toBe('b');+ expect(findConvoInAllQueries(queryClient, 'missing')).toBeUndefined();+ });++ it('findConvoInAllQueries prefers the copy carrying the newest reply', () => {+ /* The same row is cached once per list variant and only the mounted ones refetch, so an+ older copy must not shadow a newer reply and read as caught up. */+ queryClient.setQueryData(['allConversations'], {+ pages: [+ {+ conversations: [+ {+ ...convoA,+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastSeenAt: '2026-08-16T10:00:00.000Z',+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [],+ });+ queryClient.setQueryData(['allConversations', { tag: 'work' }], {+ pages: [+ {+ conversations: [+ {+ ...convoA,+ lastResponseAt: '2026-08-16T10:05:00.000Z',+ lastSeenAt: '2026-08-16T10:00:00.000Z',+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [],+ });++ const found = findConvoInAllQueries(queryClient, 'a');+ expect(found?.lastResponseAt).toBe('2026-08-16T10:05:00.000Z');+ expect(isConversationUnseen(found)).toBe(true);+ });++ it('updateConvoInAllQueries reaches a conversation held only in the point query', () => {+ /* Reads resolve the point query, so a write that skipped it would discard the update+ for a conversation opened by URL and absent from every loaded page. */+ queryClient.removeQueries(['allConversations']);+ queryClient.setQueryData(['conversation', 'a'], {+ ...convoA,+ messages: ['m1'],+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ });++ updateConvoInAllQueries(queryClient, 'a', (c) => ({+ ...c,+ lastSeenAt: '2026-08-16T10:00:00.000Z',+ }));++ const point = queryClient.getQueryData<TConversation & { messages: string[] }>([+ 'conversation',+ 'a',+ ]);+ expect(point?.lastSeenAt).toBe('2026-08-16T10:00:00.000Z');+ /* The point copy carries fields the list rows do not; the updater is applied to it+ rather than a list row being written over it. */+ expect(point?.messages).toEqual(['m1']);+ expect(isConversationUnseen(point)).toBe(false);+ });++ it('findConvoInAllQueries falls back to the open conversation point query', () => {+ /* An old conversation opened by URL need not be in any loaded list page; reading it as+ absent would read as caught up and never acknowledge the reply on screen. */+ queryClient.removeQueries(['allConversations']);+ queryClient.setQueryData(['conversation', 'a'], {+ ...convoA,+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ });++ const found = findConvoInAllQueries(queryClient, 'a');+ expect(found?.lastResponseAt).toBe('2026-08-16T10:00:00.000Z');+ expect(isConversationUnseen(found)).toBe(true);+ });++ it('findConvoInAllQueries keeps the list copy when it carries the newer reply', () => {+ queryClient.setQueryData(['allConversations'], {+ pages: [+ {+ conversations: [{ ...convoA, lastResponseAt: '2026-08-16T10:05:00.000Z' }],+ nextCursor: null,+ },+ ],+ pageParams: [],+ });+ queryClient.setQueryData(['conversation', 'a'], {+ ...convoA,+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ });++ expect(findConvoInAllQueries(queryClient, 'a')?.lastResponseAt).toBe(+ '2026-08-16T10:05:00.000Z',+ );+ });++ it('findConvoInAllQueries prefers the freshest pinned variant', () => {+ /* A pin is cached once per bookmark filter and only the mounted variants refetch, so+ first-wins there would shadow a newer reply exactly as it would in the chats list. */+ queryClient.setQueryData(['pinnedConversations', { tag: 'a' }], {+ conversations: [+ {+ ...convoA,+ pinned: true,+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastSeenAt: '2026-08-16T10:00:00.000Z',+ },+ ],+ nextCursor: null,+ });+ queryClient.setQueryData(['pinnedConversations', { tag: 'b' }], {+ conversations: [+ {+ ...convoA,+ pinned: true,+ lastResponseAt: '2026-08-16T10:05:00.000Z',+ lastSeenAt: '2026-08-16T10:00:00.000Z',+ },+ ],+ nextCursor: null,+ });+ queryClient.removeQueries(['allConversations']);++ const found = findConvoInAllQueries(queryClient, 'a');+ expect(found?.lastResponseAt).toBe('2026-08-16T10:05:00.000Z');+ expect(isConversationUnseen(found)).toBe(true);+ });++ it('findConvoInAllQueries preserves server read state after local chat updates', async () => {+ const lastResponseAt = '2026-08-16T10:00:00.000Z';+ await queryClient.fetchQuery({+ queryKey: ['allConversations'],+ queryFn: async () => ({+ pages: [{ conversations: [{ ...convoA, lastResponseAt, lastSeenAt: lastResponseAt }] }],+ pageParams: [],+ }),+ });+ expect(isConversationUnseen(findConvoInAllQueries(queryClient, 'a'))).toBe(false);+ await queryClient.fetchQuery({+ queryKey: ['allConversations', { tag: 'work' }],+ queryFn: async () => ({+ pages: [{ conversations: [{ ...convoA, lastResponseAt }] }],+ pageParams: [],+ }),+ });+ updateConvoInAllQueries(queryClient, 'a', (convo) => ({ ...convo, title: 'Renamed' }));++ const found = findConvoInAllQueries(queryClient, 'a');+ expect(found?.lastSeenAt).toBeUndefined();+ expect(isConversationUnseen(found)).toBe(true);+ });+ it('isConvoInAggregateCaches ignores expired unobserved list and pinned variants', () => {+ const now = Date.now();+ queryClient.removeQueries(['allConversations']);+ queryClient.setQueryData(+ ['allConversations', { isArchived: true }],+ {+ pages: [{ conversations: [{ ...convoA, lastResponseAt: '2026-08-16T10:00:00.000Z' }] }],+ pageParams: [],+ },+ { updatedAt: now - 6 * 60_000 },+ );+ queryClient.setQueryData(+ ['pinnedConversations', { tag: 'old' }],+ {+ conversations: [+ { ...convoA, pinned: true, lastResponseAt: '2026-08-16T10:00:00.000Z' },+ ],+ nextCursor: null,+ },+ { updatedAt: now - 6 * 60_000 },+ );++ const clock = jest.spyOn(Date, 'now').mockReturnValue(now);+ try {+ expect(isConvoInAggregateCaches(queryClient, 'a')).toBe(false);+ } finally {+ clock.mockRestore();+ }+ });++ it('findConvoInAllQueries keeps a catch-up the freshest variant still carries', () => {+ const now = Date.now();+ queryClient.setQueryData(+ ['allConversations'],+ {+ pages: [+ {+ conversations: [{ ...convoA, lastResponseAt: '2026-08-16T10:00:00.000Z' }],+ nextCursor: null,+ },+ ],+ pageParams: [],+ },+ { updatedAt: now - 2000 },+ );+ queryClient.setQueryData(+ ['allConversations', { tag: 'work' }],+ {+ pages: [+ {+ conversations: [+ {+ ...convoA,+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastSeenAt: '2026-08-16T10:01:00.000Z',+ },+ ],+ nextCursor: null,+ },+ ],+ pageParams: [],+ },+ { updatedAt: now - 1000 },+ );++ expect(findConvoInAllQueries(queryClient, 'a')?.lastSeenAt).toBe(+ '2026-08-16T10:01:00.000Z',+ );+ expect(isConversationUnseen(findConvoInAllQueries(queryClient, 'a'))).toBe(false);+ });+it('updateConvoInAllQueries with moveToTop moves convo to front and updates updatedAt', () => {// Add more conversations so 'a' is not at position 0const convoC = { conversationId: 'c', updatedAt: '2024-01-03T12:00:00Z' } as TConversation;diff --git a/client/src/utils/convos.ts b/client/src/utils/convos.tsindex 19ef1399c6..66cb9e137d 100644--- a/client/src/utils/convos.ts+++ b/client/src/utils/convos.ts@@ -10,11 +10,32 @@ import {startOfYear,isWithinInterval,} from 'date-fns';-import type { TConversation, GroupedConversations } from 'librechat-data-provider';+import type { TConversation, TMessage, GroupedConversations } from 'librechat-data-provider';import type { InvalidateQueryFilters } from '@tanstack/react-query';-import type { InfiniteData } from '@tanstack/react-query';+import type { InfiniteData, Query } from '@tanstack/react-query';import { isTemporaryConversation } from './conversation';+/**+ * A conversation is unseen when a reply landed after the user last caught up with it.+ *+ * Both timestamps ride in the conversation list payload, so this stays a pure comparison and+ * costs no extra request. Conversations predating the feature have no `lastResponseAt` and are+ * therefore treated as seen, which is what keeps the sidebar quiet after deploy.+ */+export const isConversationUnseen = (+ conversation: Pick<TConversation, 'lastResponseAt' | 'lastSeenAt'> | undefined | null,+): boolean => {+ const lastResponseAt = conversation?.lastResponseAt;+ if (!lastResponseAt) {+ return false;+ }+ const lastSeenAt = conversation?.lastSeenAt;+ if (!lastSeenAt) {+ return true;+ }+ return new Date(lastSeenAt).getTime() < new Date(lastResponseAt).getTime();+};+// Date group helpersexport const dateKeys = {today: 'com_ui_date_today',@@ -633,7 +654,9 @@ export function upsertConvoInAllQueries(}const cachedPin = findPinnedConversation(queryClient, conversationId);- const listConvo = cachedPin ? preserveListFlags(nextConvo, cachedPin) : nextConvo;+ const listConvo = cachedPin+ ? preserveReadState(preserveListFlags(nextConvo, cachedPin), cachedPin)+ : nextConvo;/* Root-level SSE updates and resumable settlement go through upsert, notupdate. Merge into any already-cached pin so that path cannot leave the@@ -754,6 +777,138 @@ export type PinnedConversationsData = {nextCursor?: string | null;};+/** A cached copy of a conversation together with when its query last heard from the server. */+export type ConvoCandidate = ConvoQueryAuthority & { convo: TConversation };++export type ConvoQueryAuthority = {+ heardAt: number;+ fromServer: boolean;+ requestOrder: number;+};++const convoQueryServerFetchedAt = new WeakMap<QueryClient, WeakMap<Query, ConvoQueryAuthority>>();++export const trackConvoQueryAuthority = (+ queryClient: QueryClient,+): WeakMap<Query, ConvoQueryAuthority> => {+ const existing = convoQueryServerFetchedAt.get(queryClient);+ if (existing) {+ return existing;+ }+ const fetchedAt = new WeakMap<Query, ConvoQueryAuthority>();+ const requestOrders = new WeakMap<Query, number>();+ let nextRequestOrder = 0;+ convoQueryServerFetchedAt.set(queryClient, fetchedAt);+ const cache = queryClient.getQueryCache();+ for (const query of cache.getAll()) {+ fetchedAt.set(query, {+ heardAt: query.state.dataUpdatedAt || Date.now(),+ fromServer: false,+ requestOrder: 0,+ });+ }+ cache.subscribe((event) => {+ const { query } = event;+ const root = query.queryKey[0];+ if (+ root !== QueryKeys.allConversations &&+ root !== QueryKeys.pinnedConversations &&+ root !== QueryKeys.conversation+ ) {+ return;+ }+ if (event.type === 'updated' && event.action.type === 'fetch') {+ requestOrders.set(query, ++nextRequestOrder);+ }+ const fromServer =+ event.type === 'updated' && event.action.type === 'success' && event.action.manual !== true;+ if (fromServer || !fetchedAt.has(query)) {+ fetchedAt.set(query, {+ heardAt: query.state.dataUpdatedAt || Date.now(),+ fromServer,+ requestOrder: fromServer ? (requestOrders.get(query) ?? 0) : 0,+ });+ }+ });+ return fetchedAt;+};++/**+ * Returns the authority timestamp for a cached conversation query.+ *+ * The cache subscription is shared by all selectors and lives with the QueryClient, not a+ * mounted component. Local cache writes never advance authority; weak query keys prevent a+ * removed variant from lending its authority to a later query with the same hash.+ */+export const convoQueryAuthority = (+ queryClient: QueryClient,+ query: Query,+): ConvoQueryAuthority => {+ const fetchedAt = trackConvoQueryAuthority(queryClient);+ if (!fetchedAt.has(query)) {+ fetchedAt.set(query, {+ heardAt: query.state.dataUpdatedAt || Date.now(),+ fromServer: false,+ requestOrder: 0,+ });+ }+ return fetchedAt.get(query)!;+};++/** Also the ceiling on `interface.replyNotifications.focusedRefreshMs`, the refresh that renews+ * the discovery snapshot; the two have to move together. */+const AGGREGATE_CACHE_AUTHORITY_AGE_MS = 5 * 60_000;++export const isAggregateQueryAuthoritative = (queryClient: QueryClient, query: Query): boolean => {+ if (query.getObserversCount() > 0) {+ return true;+ }+ return (+ Date.now() - convoQueryAuthority(queryClient, query).heardAt <= AGGREGATE_CACHE_AUTHORITY_AGE_MS+ );+};+/**+ * Picks whichever cached copy of a conversation carries the newest read state.+ *+ * The same row is cached once per list variant (unfiltered, per project, per tag, pinned, plus+ * the point query for the open conversation), and only the mounted ones refetch. Taking the+ * first copy found would let an older variant shadow a newer reply, and the caller would read a+ * conversation as caught up while the visible row still shows its dot.+ *+ * The reply stamp decides, since that one only moves forward. The catch-up cannot break the tie:+ * "mark as unread" clears it outright, so a fresh `undefined` is newer than a stale stamp and+ * comparing the values would pick the stale copy. Server reads are ordered by when their+ * requests started, not when they completed; a delayed older response must not win the tie.+ */+export const freshestCandidate = (+ a: ConvoCandidate | undefined,+ b: ConvoCandidate | undefined,+): ConvoCandidate | undefined => {+ if (!a) {+ return b;+ }+ if (!b) {+ return a;+ }+ const responseDelta = (b.convo.lastResponseAt ?? '').localeCompare(a.convo.lastResponseAt ?? '');+ if (responseDelta !== 0) {+ return responseDelta > 0 ? b : a;+ }+ if (b.fromServer !== a.fromServer) {+ return b.fromServer ? b : a;+ }+ if (b.requestOrder !== a.requestOrder) {+ return b.requestOrder > a.requestOrder ? b : a;+ }+ return b.heardAt > a.heardAt ? b : a;+};++const candidateFrom = (+ queryClient: QueryClient,+ query: Query,+ convo: TConversation | undefined,+): ConvoCandidate | undefined =>+ convo ? { convo, ...convoQueryAuthority(queryClient, query) } : undefined;/** Reads a pin out of whichever cached bookmark variant holds it. Single-conversation* responses omit server-derived fields like `isShared`, so callers that insert one* elsewhere need the cached row to carry them over. */@@ -761,18 +916,263 @@ export function findPinnedConversation(queryClient: QueryClient,conversationId: string,): TConversation | undefined {+ return findPinnedCandidate(queryClient, conversationId)?.convo;+}++/** Keyed by the active bookmark filter, so a pin is cached once per variant and only the+ * mounted ones refetch; reduced for the same reason the chats list is. */+function findPinnedCandidate(+ queryClient: QueryClient,+ conversationId: string,+): ConvoCandidate | undefined {const queries = queryClient.getQueryCache().findAll([QueryKeys.pinnedConversations], { exact: false });-+ let freshest: ConvoCandidate | undefined;for (const query of queries) {+ if (!isAggregateQueryAuthoritative(queryClient, query)) {+ continue;+ }const data = queryClient.getQueryData<PinnedConversationsData>(query.queryKey);const found = data?.conversations.find((c) => c.conversationId === conversationId);- if (found) {- return found;+ freshest = freshestCandidate(freshest, candidateFrom(queryClient, query, found));+ }+ return freshest;+}+type ReplyProof = {+ conversationId: string;+ lastResponseAt: string;+ locallyCommitted?: boolean;+ serverFetched?: boolean;+};++const messagesReplyProofs = new WeakMap<QueryClient, WeakMap<TMessage[], ReplyProof>>();++function markReplyProof(+ queryClient: QueryClient,+ conversationId: string,+ lastResponseAt: string,+ source: 'local' | 'server',+ messages: TMessage[] | undefined = queryClient.getQueryData<TMessage[]>([+ QueryKeys.messages,+ conversationId,+ ]),+): void {+ if (messages == null) {+ return;+ }+ let commits = messagesReplyProofs.get(queryClient);+ if (commits == null) {+ commits = new WeakMap();+ messagesReplyProofs.set(queryClient, commits);+ }+ const previous = commits.get(messages);+ const proof =+ previous?.conversationId === conversationId && previous.lastResponseAt === lastResponseAt+ ? previous+ : { conversationId, lastResponseAt };+ if (source === 'local') {+ proof.locallyCommitted = true;+ } else {+ proof.serverFetched = true;+ }+ commits.set(messages, proof);+}++/**+ * Records the exact messages cache object written by a durable SSE terminal event. The marker is+ * intentionally explicit: arbitrary manual cache writes (streaming tokens, optimistic user+ * messages, or list merges) are not evidence that the stamped reply has rendered.+ */+export function markLocallyCommittedReply(+ queryClient: QueryClient,+ conversationId: string,+ lastResponseAt: string,+): void {+ markReplyProof(queryClient, conversationId, lastResponseAt, 'local');+}++/** Records a successful server messages fetch against the exact cache object it committed. */+export function markServerFetchedReply(+ queryClient: QueryClient,+ conversationId: string,+ lastResponseAt: string,+ messages: TMessage[],+): void {+ markReplyProof(queryClient, conversationId, lastResponseAt, 'server', messages);+}++function hasReplyProof(+ queryClient: QueryClient,+ conversationId: string,+ lastResponseAt: string,+ source: 'local' | 'server',+): boolean {+ const messages = queryClient.getQueryData<TMessage[]>([QueryKeys.messages, conversationId]);+ if (messages == null) {+ return false;+ }+ const proof = messagesReplyProofs.get(queryClient)?.get(messages);+ return (+ proof?.conversationId === conversationId &&+ proof.lastResponseAt === lastResponseAt &&+ (source === 'local' ? proof.locallyCommitted === true : proof.serverFetched === true)+ );+}++/** Confirms that the terminal event's exact messages cache entry still owns this stamp. */+export function hasLocallyCommittedReply(+ queryClient: QueryClient,+ conversationId: string,+ lastResponseAt: string,+): boolean {+ return hasReplyProof(queryClient, conversationId, lastResponseAt, 'local');+}++/** Confirms that a successful server fetch's exact messages cache entry still owns this stamp. */+export function hasServerFetchedReply(+ queryClient: QueryClient,+ conversationId: string,+ lastResponseAt: string,+): boolean {+ return hasReplyProof(queryClient, conversationId, lastResponseAt, 'server');+}+type MessagesReplyFetch = {+ stamp: string;+ acceptedServerResult: boolean;+};++const messagesReplyFetches = new WeakMap<Query, MessagesReplyFetch>();+const messagesReplyTracking = new WeakSet<QueryClient>();++function trackMessagesReplyFetches(queryClient: QueryClient): void {+ if (messagesReplyTracking.has(queryClient)) {+ return;+ }+ messagesReplyTracking.add(queryClient);+ queryClient.getQueryCache().subscribe((event) => {+ if (event.type !== 'updated' || event.query.queryKey[0] !== QueryKeys.messages) {+ return;+ }+ const action = event.action;+ const pending = messagesReplyFetches.get(event.query);+ if (pending == null) {+ return;+ }+ if (action.type === 'error') {+ messagesReplyFetches.delete(event.query);+ return;}+ if (action.type !== 'success' || action.manual === true) {+ pending.acceptedServerResult = false;+ return;+ }+ messagesReplyFetches.delete(event.query);+ if (!pending.acceptedServerResult) {+ return;+ }+ const committedMessages = event.query.state.data;+ if (Array.isArray(committedMessages)) {+ markServerFetchedReply(+ queryClient,+ event.query.queryKey[1] as string,+ pending.stamp,+ committedMessages as TMessage[],+ );+ }+ });+}++/**+ * Captures the list reply stamp before a messages request crosses its loading gate. The returned+ * request record is weakly tied to the query so an abandoned conversation cannot retain history.+ */+export function beginMessagesReplyFetch(+ queryClient: QueryClient,+ conversationId: string,+ stamp: string | undefined,+): MessagesReplyFetch | undefined {+ if (stamp == null) {+ return undefined;}- return undefined;+ trackMessagesReplyFetches(queryClient);+ const query = queryClient.getQueryCache().find([QueryKeys.messages, conversationId]);+ if (query == null) {+ return undefined;+ }+ const request: MessagesReplyFetch = { stamp, acceptedServerResult: false };+ messagesReplyFetches.set(query, request);+ return request;+}++/** Arms a request record only when its server result won the concurrent-cache race. */+export function completeMessagesReplyFetch(+ queryClient: QueryClient,+ conversationId: string,+ request: MessagesReplyFetch | undefined,+ acceptedServerResult: boolean,+): void {+ if (request == null) {+ return;+ }+ const query = queryClient.getQueryCache().find([QueryKeys.messages, conversationId]);+ if (query == null || messagesReplyFetches.get(query) !== request) {+ return;+ }+ if (!acceptedServerResult) {+ messagesReplyFetches.delete(query);+ return;+ }+ request.acceptedServerResult = true;+}++/**+ * Applies the stamps a completed run reported to the sidebar caches.+ *+ * The list is a separate cache from the conversation the chat itself holds, and nothing else+ * writes to it once a run completes. Only the server's own values are written: the seen+ * acknowledgement is bound to whatever stamp the client observed, so inventing one from the+ * browser clock would offer the server a value it cannot match.+ *+ * Two responses to one conversation can finish out of order, and an away poll or a completion+ * merge can have delivered the newer stamp already, so an older one is dropped rather than+ * written: walking the read state backwards would let the newer reply arrive a second time.+ * The reply also moved `updatedAt` server-side, and another conversation can have taken the top+ * of the list while this one streamed, so the row is carried to its new position rather than+ * left at the date and place its run started with.+ *+ * A stamp that genuinely advances also clears the catch-up it outranks, mirroring the write the+ * server made: a cached acknowledgement dated ahead of the new reply, which replica clock skew+ * can produce, would otherwise classify a reply nobody has read as seen, and the completion+ * watcher skips its own fetch precisely because this handler already moved the stamp.+ */+export function applyServerReplyStamp(+ queryClient: QueryClient,+ conversationId: string,+ {+ lastResponseAt,+ lastResponseMessageId,+ updatedAt,+ }: { lastResponseAt: string; lastResponseMessageId?: string; updatedAt?: string },+): void {+ const cached = findConvoInAllQueries(queryClient, conversationId);+ if (cached?.lastResponseAt != null && lastResponseAt < cached.lastResponseAt) {+ return;+ }+ const advances = cached?.lastResponseAt == null || lastResponseAt > cached.lastResponseAt;+ updateConvoInAllQueries(+ queryClient,+ conversationId,+ (convo) => ({+ ...convo,+ lastResponseAt,+ lastResponseMessageId: lastResponseMessageId ?? convo.lastResponseMessageId,+ lastResponseIsManual: undefined,+ lastSeenAt: advances ? undefined : convo.lastSeenAt,+ updatedAt: updatedAt ?? convo.updatedAt,+ }),+ updatedAt != null && updatedAt > (cached?.updatedAt ?? ''),+ );}/**@@ -795,19 +1195,52 @@ function preserveListFlags(next: TConversation, found: TConversation): TConversareturn merged;}+const preserveReadState = (next: TConversation, found: TConversation): TConversation => {+ const merged = { ...next };+ if (!('lastResponseAt' in next)) {+ merged.lastResponseAt = found.lastResponseAt;+ }+ if (!('lastResponseMessageId' in next)) {+ merged.lastResponseMessageId = found.lastResponseMessageId;+ }+ if (!('lastResponseIsManual' in next)) {+ merged.lastResponseIsManual = found.lastResponseIsManual;+ }+ if (!('lastSeenAt' in next)) {+ merged.lastSeenAt = found.lastSeenAt;+ }+ return merged;+};+/**- * A chat's conversation state snapshots the sidebar flags when the chat is opened and never- * hears about a later change, so pinning an open chat leaves a stale `pinned: false` on it.- * Strip them before that state reaches the list caches, or the next message would write the- * stale value back over the sidebar and drop the chat out of Pinned.+ * Read state the sidebar owns for the same reason: `lastResponseAt` is stamped by the server as+ * a reply persists, `lastResponseMessageId` identifies the stamped reply, `lastResponseIsManual`+ * records synthetic unread markers, and `lastSeenAt` by the seen mutation, none of which reaches+ * the chat's own conversation state. Stripped rather than carried, so `updateConvoInAllQueries`+ * falls back to whatever the list caches already hold.+ */+const chatOwnedStaleFields = [+ ...listFlags,+ 'lastResponseAt',+ 'lastResponseMessageId',+ 'lastResponseIsManual',+ 'lastSeenAt',+] as const;++/**+ * A chat's conversation state snapshots the sidebar's fields when the chat is opened and never+ * hears about a later change: pinning an open chat leaves a stale `pinned: false` on it, and+ * reading a reply leaves the catch-up it was opened with. Strip them before that state reaches+ * the list caches, or the next message would write the stale values back over the sidebar,+ * dropping the chat out of Pinned or lighting an unread dot the user has already cleared.*/export function withoutListFlags(conversation: TConversation): TConversation {- if (listFlags.every((flag) => conversation[flag] === undefined)) {+ if (chatOwnedStaleFields.every((field) => conversation[field] === undefined)) {return conversation;}const stripped = { ...conversation };- for (const flag of listFlags) {- delete stripped[flag];+ for (const field of chatOwnedStaleFields) {+ delete stripped[field];}return stripped;}@@ -840,7 +1273,7 @@ function updatePinnedConvosQuery(}const found = oldData.conversations[index];const updated = updater(found);- const merged = updated && preserveListFlags(updated, found);+ const merged = updated && preserveReadState(preserveListFlags(updated, found), found);if (!merged || merged.pinned !== true) {return {...oldData,@@ -855,9 +1288,11 @@ function updatePinnedConvosQuery(stale value and undo the move. */if (moveToTop) {const rest = oldData.conversations.filter((_, i) => i !== index);+ const updatedAt =+ merged.updatedAt !== found.updatedAt ? merged.updatedAt : new Date().toISOString();return {...oldData,- conversations: [{ ...merged, updatedAt: new Date().toISOString() }, ...rest],+ conversations: [{ ...merged, updatedAt }, ...rest],};}@@ -870,12 +1305,88 @@ function updatePinnedConvosQuery(}// Update+/**+ * Whether any cache the unseen aggregate reads holds this conversation.+ *+ * The point query is deliberately excluded: it holds the conversation the user opened by URL,+ * which `useUnseenConversations` neither scans nor subscribes to, so a row present only there+ * still needs the chats list refetched before it can reach the badge or the alerts.+ */+export function isConvoInAggregateCaches(+ queryClient: QueryClient,+ conversationId: string,+): boolean {+ const queries = queryClient+ .getQueryCache()+ .findAll([QueryKeys.allConversations], { exact: false });++ for (const query of queries) {+ if (!isAggregateQueryAuthoritative(queryClient, query)) {+ continue;+ }+ const data = queryClient.getQueryData<InfiniteData<ConversationCursorData>>(query.queryKey);+ if (findConversationInInfinite(data, conversationId)) {+ return true;+ }+ }+ return findPinnedConversation(queryClient, conversationId) !== undefined;+}++/**+ * Reads a conversation out of the cached queries that hold it.+ *+ * Callers that only need a point-in-time answer use this instead of subscribing to the list,+ * which keeps event-driven checks off the render path.+ *+ * Every list prefix `updateConvoInAllQueries` writes is read here, archive included: a row the+ * user reached from the archived view lives only in that cache, and a lookup that missed it+ * would take no baseline for an optimistic write and find nothing to roll back afterwards.+ *+ * The pinned section is fed by its own request, so a pin older than the loaded chat pages lives+ * only there. Missing it would leave such a row's unseen dot stuck: the caller would read the+ * conversation as absent, and absent reads as caught up.+ */+export function findConvoInAllQueries(+ queryClient: QueryClient,+ conversationId: string,+): TConversation | undefined {+ const queries = findConversationListQueries(queryClient);++ let freshest: ConvoCandidate | undefined;+ for (const query of queries) {+ if (!isAggregateQueryAuthoritative(queryClient, query)) {+ continue;+ }+ const data = queryClient.getQueryData<InfiniteData<ConversationCursorData>>(query.queryKey);+ freshest = freshestCandidate(+ freshest,+ candidateFrom(queryClient, query, findConversationInInfinite(data, conversationId)),+ );+ }+ freshest = freshestCandidate(freshest, findPinnedCandidate(queryClient, conversationId));++ /* The conversation opened by URL is loaded into its own point query, and an old one need not+ appear in any loaded list page at all. Without this it would read as absent, absent reads+ as caught up, and the reply the user is looking at would never be acknowledged. */+ const pointKey = [QueryKeys.conversation, conversationId];+ const pointQuery = queryClient.getQueryCache().find(pointKey);+ return freshestCandidate(+ freshest,+ pointQuery+ ? candidateFrom(queryClient, pointQuery, queryClient.getQueryData<TConversation>(pointKey))+ : undefined,+ )?.convo;+}+export function updateConvoInAllQueries(queryClient: QueryClient,conversationId: string,updater: (c: TConversation) => TConversation,moveToTop = false,) {+ queryClient.setQueryData<TConversation>([QueryKeys.conversation, conversationId], (current) =>+ current ? updater(current) : current,+ );updatePinnedConvosQuery(queryClient, conversationId, updater, moveToTop);const queries = findConversationListQueries(queryClient);@@ -910,9 +1421,21 @@ export function updateConvoInAllQueries(const found = oldData.pages[pageIdx].conversations[convoIdx];/** Callers that swap in a server response or the chat's own state wholesale (rename,* pin, SSE updates) omit the sidebar-only flags, which would otherwise drop the- * shared badge and push a pinned chat back into the date groups. */- const merged = preserveListFlags(updater(found), found);- const updated = moveToTop ? { ...merged, updatedAt: new Date().toISOString() } : merged;+ * shared badge and push a pinned chat back into the date groups. The unseen-reply+ * fields are absent from those payloads too, but they are carried on key presence rather+ * than on value: a present-but-undefined field is an explicit clear. */+ const next = updater(found);+ const merged: TConversation = preserveReadState(preserveListFlags(next, found), found);+ /* `moveToTop` normally refreshes the date itself, because callers that swap in an SSE+ payload can carry the previous turn's `updatedAt`. A caller that deliberately changed+ it is naming the server's own value, which is the more accurate one to keep. */+ const updated = moveToTop+ ? {+ ...merged,+ updatedAt:+ merged.updatedAt !== found.updatedAt ? merged.updatedAt : new Date().toISOString(),+ }+ : merged;if (!conversationBelongsToListQuery(query.queryKey, updated)) {return removeConvoFromInfinitePages(oldData, conversationId);diff --git a/client/src/utils/documentTitle.ts b/client/src/utils/documentTitle.tsindex 322ade24bc..13ae8be9bf 100644--- a/client/src/utils/documentTitle.ts+++ b/client/src/utils/documentTitle.ts@@ -2,6 +2,9 @@ import { LocalStorageKeys } from 'librechat-data-provider';export const CHAT_TITLE_IN_TAB_KEY = 'chatTitleInTab';export const DEFAULT_APP_TITLE = 'LibreChat';+let documentTitleRevision = 0;++export const getDocumentTitleRevision = (): number => documentTitleRevision;export const hasRealTitle = (title?: string | null): title is string =>title != null && title !== '' && title !== 'New Chat';@@ -26,11 +29,13 @@ export const isChatTitleInTabEnabled = (): boolean => {/*** Sets the tab title to the conversation title, or to the app title when the- * conversation title is empty or the user opted out.+ * conversation title is empty or the user opted out. The revision signal lets+ * title decorators observe a write even when the resulting string is unchanged.* Pass `enabled` when the atom's value is already known, since Recoil writes to* localStorage after the change handler runs.*/export const setDocumentTitle = (title?: string | null, enabled?: boolean): void => {const showChatTitle = enabled ?? isChatTitleInTabEnabled();document.title = showChatTitle && title != null && title !== '' ? title : getAppTitle();+ documentTitleRevision += 1;};diff --git a/e2e/bombadil/specification.ts b/e2e/bombadil/specification.tsindex 7b27eb9822..be49a185c8 100644--- a/e2e/bombadil/specification.ts+++ b/e2e/bombadil/specification.ts@@ -438,14 +438,25 @@ export const multiConversationAlwaysRendersTwoColumns = always(() =>export const sidebarNavigationEventuallySelectsTarget = always(() => {const expectedIndex = clickedConversationIndex(ui.current.lastAction);return now(() => expectedIndex !== null).implies(- eventually(- () =>+ eventually(() => {+ const action = ui.current.lastAction;+ const newerIndex = clickedConversationIndex(action);+ const startsNewConversation =+ typeof action === 'object' &&+ action !== null &&+ 'Click' in action &&+ action.Click.name === 'New conversation';+ if (startsNewConversation || (newerIndex !== null && newerIndex !== expectedIndex)) {+ return true;+ }+ return (expectedIndex !== null &&isPersistedConversation(ui.current.path) &&ui.current.activeConversationIndexes.length === 1 &&ui.current.activeConversationIndexes[0] === expectedIndex &&- ui.current.messageIds.length > 0,- ).within(10, 'seconds'),+ ui.current.messageIds.length > 0+ );+ }).within(10, 'seconds'),);});diff --git a/e2e/specs/mock/scenarios/reply-read-state.spec.ts b/e2e/specs/mock/scenarios/reply-read-state.spec.tsnew file mode 100644index 0000000000..b42d2177fc--- /dev/null+++ b/e2e/specs/mock/scenarios/reply-read-state.spec.ts@@ -0,0 +1,326 @@+import fs from 'node:fs';+import { randomUUID } from 'node:crypto';+import mongoose from 'mongoose';+import { expect, test } from '@playwright/test';+import { createMethods, createModels } from '@librechat/data-schemas';+import { Constants } from 'librechat-data-provider';+import type { TMarkConversationUnreadResponse as MutationResult } from 'librechat-data-provider';+import type { AllMethods, IConversation } from '@librechat/data-schemas';+import { getRuntimeEnvPath } from '../../../setup/env';+import { getE2EUser } from '../../../setup/user';+import {+ deleteConversations,+ deleteMessagesByConversation,+ seedConversations,+ seedMessages,+ withMongo,+} from '../db';+import { getAccessToken, requestJson } from '../helpers';+import { openConversationMenu, openSidebar } from './sidebar';++type ReadState = Pick<+ IConversation,+ 'conversationId' | 'lastResponseAt' | 'lastSeenAt' | 'lastResponseMessageId'+>;+const NO_PARENT = Constants.NO_PARENT;+let methods: AllMethods;+let userId: string;+const createdConversationIds: string[] = [];++async function readState(conversationId: string) {+ return withMongo((db) => db.collection<ReadState>('conversations').findOne({ conversationId }));+}++test.beforeAll(async () => {+ const runtime = JSON.parse(fs.readFileSync(getRuntimeEnvPath(), 'utf8')) as {+ MONGO_URI?: string;+ };+ /* Both harnesses provision a throwaway database: the local mock run uses LibreChat-e2e, the+ * verification runner a per-run lc_verify_* database on the lab host. Anything else is a real+ * deployment, and this spec writes conversations and messages directly. */+ if (+ !runtime.MONGO_URI ||+ !/\/(LibreChat-e2e|lc_verify_[A-Za-z0-9_]+)(?:\?|$)/.test(runtime.MONGO_URI)+ ) {+ throw new Error('Reply ordering acceptance requires a disposable E2E Mongo database');+ }+ await mongoose.connect(runtime.MONGO_URI);+ createModels(mongoose);+ methods = createMethods(mongoose);+ const user = await withMongo((db) =>+ db.collection<{ email: string }>('users').findOne({ email: getE2EUser().email }),+ );+ if (!user) throw new Error('E2E user was not initialized');+ userId = user._id.toString();+});++/* These fixtures share one database with every other spec in the run, and an abandoned unread+ * conversation inflates the tab count that other scenarios assert. Removed after each test,+ * including a failing one. */+test.afterEach(async () => {+ const ids = createdConversationIds.splice(0, createdConversationIds.length);+ if (ids.length === 0) {+ return;+ }+ await deleteMessagesByConversation(ids);+ await deleteConversations(ids);+});++test.afterAll(async () => {+ await mongoose.disconnect();+});++test('later visible read wins over a delayed unread response, and stale seen cannot clear a new reply @scenario:later-read-wins-over-delayed-unread', async ({+ page,+}, testInfo) => {+ test.setTimeout(120_000);+ const conversationId = randomUUID();+ createdConversationIds.push(conversationId);+ const userMessageId = randomUUID();+ const replyId = randomUUID();+ const title = `Read ordering acceptance ${conversationId.slice(0, 8)}`;+ await seedConversations(getE2EUser().email, [{ conversationId, title, updatedAt: new Date() }]);+ await seedMessages(getE2EUser().email, conversationId, [+ {+ messageId: userMessageId,+ parentMessageId: NO_PARENT,+ text: 'Ordering request',+ isCreatedByUser: true,+ sender: 'User',+ },+ {+ messageId: replyId,+ parentMessageId: userMessageId,+ text: 'Ordering reply',+ isCreatedByUser: false,+ sender: 'Assistant',+ },+ ]);+ const initial = await methods.stampConvoLastResponse(userId, conversationId, replyId);+ expect(initial?.lastResponseMessageId).toBe(replyId);+ const initialStamp = initial!.lastResponseAt.toISOString();+ await page.goto(`/c/${conversationId}`);+ await expect(page.locator(`[id="${replyId}"]`)).toBeVisible();+ await expect+ .poll(async () => (await readState(conversationId))?.lastSeenAt?.getTime() ?? 0)+ .toBeGreaterThanOrEqual(initial!.lastResponseAt.getTime());+ const token = await getAccessToken(page);+ await page.goto('/c/new');++ const committed = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ await page.route('**/api/convos/unread', async (route) => {+ const response = await route.fetch();+ if (!response.ok()) throw new Error(`Unread request failed: ${response.status()}`);+ committed.resolve();+ await release.promise;+ await route.fulfill({ response });+ });+ const unreadDelivered = page.waitForResponse(+ (response) => new URL(response.url()).pathname === '/api/convos/unread',+ );+ const row = page.getByTestId('convo-item').filter({ hasText: title });+ try {+ await openSidebar(page);+ await openConversationMenu(row);+ /* Dispatched rather than clicked, as the row's own controls are: the menu is portaled, and+ behind the mobile drawer's scrim it inherits `pointer-events: none` and goes click-dead. */+ await page+ .getByRole('menuitem', { name: 'Mark as unread', exact: true })+ .dispatchEvent('click');+ await committed.promise;+ expect((await readState(conversationId))?.lastSeenAt).toBeUndefined();+ await page.keyboard.press('Escape');+ await openSidebar(page);+ await row+ .getByRole('button', { name: `${title} conversation, Unread`, exact: true })+ .dispatchEvent('click');+ await expect(page).toHaveURL(new RegExp(`/c/${conversationId}$`));+ await expect(page.locator(`[id="${replyId}"]`)).toBeVisible();+ await expect+ .poll(async () => (await readState(conversationId))?.lastSeenAt?.getTime() ?? 0)+ .toBeGreaterThanOrEqual(initial!.lastResponseAt.getTime());+ release.resolve();+ expect((await unreadDelivered).ok()).toBe(true);+ /* Opening the chat closed the drawer on the mobile project, which is what it does for a+ reader too, so the list is opened again to read the row's settled name. */+ await openSidebar(page);+ await expect(+ row.getByRole('button', { name: `${title} conversation`, exact: true }),+ ).toBeVisible();+ expect((await readState(conversationId))?.lastSeenAt?.getTime()).toBeGreaterThanOrEqual(+ initial!.lastResponseAt.getTime(),+ );+ await page.screenshot({ path: testInfo.outputPath('read-ordering.png') });+ } finally {+ release.resolve();+ await page.unroute('**/api/convos/unread');+ }++ await page.goto('/c/new');+ const nextReplyId = randomUUID();+ await seedMessages(getE2EUser().email, conversationId, [+ {+ messageId: nextReplyId,+ parentMessageId: userMessageId,+ text: 'New reply version',+ isCreatedByUser: false,+ sender: 'Assistant',+ },+ ]);+ const next = await methods.stampConvoLastResponse(userId, conversationId, nextReplyId);+ expect(next!.lastResponseAt.getTime()).toBeGreaterThan(initial!.lastResponseAt.getTime());+ const stale = await requestJson<MutationResult>(page, {+ path: '/api/convos/seen',+ token,+ method: 'POST',+ body: { arg: { conversationId, lastResponseAt: initialStamp } },+ });+ expect(stale.modified).toBe(false);+ expect((await readState(conversationId))?.lastSeenAt).toBeUndefined();+ const read = await requestJson<MutationResult>(page, {+ path: '/api/convos/seen',+ token,+ method: 'POST',+ body: { arg: { conversationId, lastResponseAt: next!.lastResponseAt.toISOString() } },+ });+ expect(read.modified).toBe(true);+ const unread = await requestJson<MutationResult>(page, {+ path: '/api/convos/unread',+ token,+ method: 'POST',+ body: { arg: { conversationId } },+ });+ expect(unread.modified).toBe(true);+ expect(unread.lastResponseMessageId).toBe(nextReplyId);+ expect((await readState(conversationId))?.lastSeenAt).toBeUndefined();+});++test('a hidden sibling reply stays unread until its actual branch is rendered @scenario:hidden-sibling-reply-stays-unread-until-rendered', async ({+ page,+}, testInfo) => {+ test.setTimeout(120_000);+ const conversationId = randomUUID();+ createdConversationIds.push(conversationId);+ const [root, older, visible, followup, hidden] = Array.from({ length: 5 }, () => randomUUID());+ await seedConversations(getE2EUser().email, [+ {+ conversationId,+ title: `Visible branch acceptance ${conversationId.slice(0, 8)}`,+ updatedAt: new Date(),+ },+ ]);+ await seedMessages(getE2EUser().email, conversationId, [+ {+ messageId: root,+ parentMessageId: NO_PARENT,+ text: 'Choose a branch',+ isCreatedByUser: true,+ sender: 'User',+ },+ {+ messageId: older,+ parentMessageId: root,+ text: 'Older branch',+ isCreatedByUser: false,+ sender: 'Assistant',+ },+ {+ messageId: visible,+ parentMessageId: root,+ text: 'Visible alternative',+ isCreatedByUser: false,+ sender: 'Assistant',+ },+ {+ messageId: followup,+ parentMessageId: older,+ text: 'Remote follow-up',+ isCreatedByUser: true,+ sender: 'User',+ },+ {+ messageId: hidden,+ parentMessageId: followup,+ text: 'Hidden branch reply',+ isCreatedByUser: false,+ sender: 'Assistant',+ },+ ]);+ const stamp = await methods.stampConvoLastResponse(userId, conversationId, hidden);+ let seenRequests = 0;+ let historyRequests = 0;+ page.on('request', (request) => {+ const path = new URL(request.url()).pathname;+ if (path === '/api/convos/seen' && request.postData()?.includes(conversationId))+ seenRequests += 1;+ if (path === `/api/messages/${conversationId}`) historyRequests += 1;+ });+ await page.goto(`/c/${conversationId}`);+ const visibleRow = page.locator(`[id="${visible}"]`);+ await expect(visibleRow).toBeVisible();+ await expect(page.locator(`[id="${hidden}"]`)).toHaveCount(0);+ await page.evaluate(async () => {+ const { promise, resolve } = Promise.withResolvers<void>();+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ await promise;+ });+ expect(seenRequests).toBe(0);+ expect((await readState(conversationId))?.lastSeenAt).toBeUndefined();+ await page.screenshot({ path: testInfo.outputPath('reply-hidden.png') });++ await visibleRow.hover();+ await visibleRow.getByRole('button', { name: 'Previous sibling message' }).click();+ await expect(page.locator(`[id="${hidden}"]`)).toBeVisible();+ await expect+ .poll(async () => (await readState(conversationId))?.lastSeenAt?.getTime() ?? 0)+ .toBeGreaterThanOrEqual(stamp!.lastResponseAt.getTime());+ expect(seenRequests).toBe(1);+ expect(historyRequests).toBe(1);+ await page.screenshot({ path: testInfo.outputPath('reply-visible.png') });+});++test('a synthetic unread marker clears on a cold open with one history request @scenario:manual-unread-clears-without-extra-history-fetch', async ({+ page,+}) => {+ test.setTimeout(120_000);+ const conversationId = randomUUID();+ createdConversationIds.push(conversationId);+ const noteId = randomUUID();+ await seedConversations(getE2EUser().email, [+ {+ conversationId,+ title: `Manual unread acceptance ${conversationId.slice(0, 8)}`,+ updatedAt: new Date(),+ },+ ]);+ await seedMessages(getE2EUser().email, conversationId, [+ {+ messageId: noteId,+ parentMessageId: NO_PARENT,+ text: 'User-only note',+ isCreatedByUser: true,+ sender: 'User',+ },+ ]);+ await page.goto('/c/new');+ const token = await getAccessToken(page);+ const marked = await requestJson<MutationResult>(page, {+ path: '/api/convos/unread',+ token,+ method: 'POST',+ body: { arg: { conversationId } },+ });+ expect(marked.lastResponseIsManual).toBe(true);+ expect(marked.lastResponseMessageId).toBeUndefined();+ let historyRequests = 0;+ page.on('request', (request) => {+ if (new URL(request.url()).pathname === `/api/messages/${conversationId}`) historyRequests += 1;+ });+ await page.goto(`/c/${conversationId}`);+ await expect(page.locator(`[id="${noteId}"]`)).toBeVisible();+ await expect+ .poll(async () => (await readState(conversationId))?.lastSeenAt?.getTime() ?? 0)+ .toBeGreaterThanOrEqual(new Date(marked.lastResponseAt!).getTime());+ expect(historyRequests).toBe(1);+});diff --git a/e2e/specs/mock/scenarios/sidebar.ts b/e2e/specs/mock/scenarios/sidebar.tsnew file mode 100644index 0000000000..b165f17bae--- /dev/null+++ b/e2e/specs/mock/scenarios/sidebar.ts@@ -0,0 +1,71 @@+import { expect } from '@playwright/test';+import type { Locator, Page } from '@playwright/test';++/** The first candidate that is actually painted, since the rail and the drawer publish the+ * same controls and the off-canvas copy answers a plain locator first. */+async function firstVisible(candidates: Locator): Promise<Locator | null> {+ const count = await candidates.count();+ for (let index = 0; index < count; index++) {+ const candidate = candidates.nth(index);+ if (await candidate.isVisible().catch(() => false)) {+ return candidate;+ }+ }+ return null;+}++/**+ * Mobile keeps the conversation list in a drawer; desktop has it expanded already.+ *+ * Settled on the close control being painted, by its accessible name rather than a test id.+ * The mobile drawer stays mounted and slides, so a test id read reports the off-canvas copy as+ * present before the expanded state commits, and both earlier readings sent this helper back+ * with the list still hidden behind the pane.+ */+export async function openSidebar(page: Page) {+ const isOpen = async () =>+ (await firstVisible(page.getByRole('button', { name: 'Close sidebar' }))) !== null;+ const settles = async (budgetMs: number) => {+ const deadline = Date.now() + budgetMs;+ while (Date.now() < deadline) {+ if (await isOpen()) {+ return true;+ }+ await page.waitForTimeout(100);+ }+ return isOpen();+ };++ /* One click is one toggle, and the opener sits in the pane the drawer marks inert for the+ whole of its travel: clicking again before that travel finishes either lands on an inert+ pane and is swallowed, or closes the drawer that was just opening. So each attempt gets the+ transition to itself, and a second one exists only because the very first click of a run+ can arrive while the shell is still settling. */+ for (let attempt = 0; attempt < 3; attempt++) {+ if (await isOpen()) {+ return;+ }+ const opener = await firstVisible(page.getByRole('button', { name: 'Open sidebar' }));+ await opener?.click({ timeout: 2_000 }).catch(() => undefined);+ if (await settles(5_000)) {+ return;+ }+ }+ await expect.poll(isOpen, { timeout: 5_000 }).toBe(true);+}++/** The row mounts its real menu on the first mouse enter (`Convo.tsx`). Hovering is what a+ * pointer device does, but the mobile drawer cannot always offer a hoverable row, and a real+ * `hover()` then waits out the whole budget. The fallback dispatches `mouseover`, which is the+ * native event React derives `onMouseEnter` from, and needs the row only to be attached. */+export async function openConversationMenu(row: Locator) {+ const menu = row.getByRole('button', { name: 'Conversation Menu Options' });+ if (!(await menu.isVisible().catch(() => false))) {+ await row.hover({ timeout: 5_000 }).catch(() => undefined);+ }+ if (!(await menu.isVisible().catch(() => false))) {+ await row.dispatchEvent('mouseover');+ }+ await expect(menu).toBeAttached();+ await menu.dispatchEvent('click');+}diff --git a/e2e/specs/mock/scenarios/unseen-replies.spec.ts b/e2e/specs/mock/scenarios/unseen-replies.spec.tsnew file mode 100644index 0000000000..33bb19ef0c--- /dev/null+++ b/e2e/specs/mock/scenarios/unseen-replies.spec.ts@@ -0,0 +1,711 @@+import { expect, test } from '@playwright/test';+import type { Page } from '@playwright/test';+import { randomUUID } from 'node:crypto';+import { getE2EUser } from '../../../setup/user';+import {+ deleteConversations,+ deleteMessagesByConversation,+ seedConversations,+ seedMessages,+ withMongo,+} from '../db';+import {+ getAccessToken,+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ requestJson,+ selectMockEndpoint,+ sendMessageAndWaitForCompletion,+} from '../helpers';+import { openConversationMenu, openSidebar } from './sidebar';++const userEmail = getE2EUser().email;+const now = () => new Date();++function conversationId() {+ return randomUUID();+}++async function seedConversation(+ id: string,+ title: string,+ fields: { lastResponseAt?: Date; lastSeenAt?: Date; lastResponseIsManual?: boolean } = {},+) {+ const updatedAt = fields.lastResponseAt ?? fields.lastSeenAt ?? now();+ await seedConversations(userEmail, [{ conversationId: id, title, updatedAt }]);+ await withMongo(async (db) => {+ const user = await db.collection('users').findOne({ email: userEmail });+ if (!user) throw new Error(`E2E user ${userEmail} does not exist`);+ const $set: Record<string, unknown> = {};+ const $unset: Record<string, ''> = {};+ if (fields.lastResponseAt) $set.lastResponseAt = fields.lastResponseAt;+ else $unset.lastResponseAt = '';+ if (fields.lastSeenAt) $set.lastSeenAt = fields.lastSeenAt;+ else $unset.lastSeenAt = '';+ if (fields.lastResponseIsManual !== undefined)+ $set.lastResponseIsManual = fields.lastResponseIsManual;+ await db.collection('conversations').updateOne(+ { user: user._id.toString(), conversationId: id },+ {+ ...(Object.keys($set).length ? { $set } : {}),+ ...(Object.keys($unset).length ? { $unset } : {}),+ },+ );+ });+}++async function readConversation(id: string) {+ return withMongo(async (db) => {+ const user = await db.collection('users').findOne({ email: userEmail });+ if (!user) throw new Error(`E2E user ${userEmail} does not exist`);+ return db+ .collection('conversations')+ .findOne({ user: user._id.toString(), conversationId: id });+ });+}+async function restoreUnreadBaseline(id: string, lastResponseAt: Date, lastSeenAt: Date) {+ await withMongo(async (db) => {+ const user = await db.collection('users').findOne({ email: userEmail });+ if (!user) throw new Error(`E2E user ${userEmail} does not exist`);+ await db+ .collection('conversations')+ .updateOne(+ { user: user._id.toString(), conversationId: id },+ { $set: { lastResponseAt, lastSeenAt } },+ );+ });+}++async function cleanup(id: string) {+ await deleteMessagesByConversation([id]);+ await deleteConversations([id]);+}++async function enableUnseenBadge(page: Page) {+ await page.addInitScript(() => localStorage.setItem('unseenTabBadge', 'true'));+}++/** Serves `interface.replyNotifications` as an operator would have set it in `librechat.yaml`. */+async function serveReplyNotificationConfig(+ page: Page,+ replyNotifications: Record<string, boolean | number>,+) {+ await page.route('**/api/config*', async (route) => {+ const response = await route.fetch();+ const config = await response.json();+ /* Fulfilled with a fresh body and headers rather than the upstream response: reusing its+ encoding headers for a re-serialized body leaves the client unable to read the config,+ which reads here exactly like an operator who configured nothing. */+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ ...config,+ interface: { ...config.interface, replyNotifications },+ }),+ });+ });+}++async function unfocus(page: Page) {+ await page.evaluate(() => {+ Object.defineProperty(document, 'hasFocus', {+ configurable: true,+ value: () => false,+ });+ window.dispatchEvent(new Event('blur'));+ });+}++async function seedReplyMessage(id: string, label: string) {+ const userMessageId = randomUUID();+ await seedMessages(userEmail, id, [+ {+ messageId: userMessageId,+ parentMessageId: '00000000-0000-0000-0000-000000000000',+ text: `Earlier prompt ${label}`,+ isCreatedByUser: true,+ sender: 'User',+ },+ {+ messageId: randomUUID(),+ parentMessageId: userMessageId,+ text: `Earlier reply ${label}`,+ isCreatedByUser: false,+ sender: 'OpenAI',+ },+ ]);+}++test.describe('unseen replies', () => {+ test('opening a conversation clears its dot and the title count @scenario:open-conversation-clears-dot-and-title-count', async ({+ page,+ }) => {+ const first = conversationId();+ const second = conversationId();+ const firstTitle = `Unseen first ${first.slice(0, 8)}`;+ const secondTitle = `Unseen second ${second.slice(0, 8)}`;+ const replyAt = new Date(Date.now() - 2_000);+ const seenAt = new Date(replyAt.getTime() - 1_000);+ try {+ await seedConversation(first, firstTitle, { lastResponseAt: replyAt, lastSeenAt: seenAt });+ await seedConversation(second, secondTitle, { lastResponseAt: replyAt, lastSeenAt: seenAt });+ await seedReplyMessage(first, firstTitle);+ await enableUnseenBadge(page);+ await page.goto(NEW_CHAT_PATH);+ await openSidebar(page);+ await expect(page.getByTestId('convo-item').filter({ hasText: firstTitle })).toBeVisible();+ await expect(+ page+ .getByTestId('convo-item')+ .filter({ hasText: firstTitle })+ .locator('span[aria-hidden="true"].bg-status-info'),+ ).toBeVisible();+ await expect.poll(() => page.title()).toMatch(/^\(2\)/);+ await page+ .getByTestId('convo-item')+ .filter({ hasText: firstTitle })+ .getByRole('button', { name: new RegExp(`^${firstTitle} conversation`) })+ .dispatchEvent('click');+ await expect(page).toHaveURL(new RegExp(`/c/${first}$`));+ await expect(+ page.getByTestId('messages-view').getByText(`Earlier reply ${firstTitle}`),+ ).toBeVisible();+ await expect(+ page+ .getByTestId('convo-item')+ .filter({ hasText: firstTitle })+ .locator('span[aria-hidden="true"].bg-status-info'),+ ).toHaveCount(0);+ await expect.poll(() => page.title()).toMatch(/^\(1\)/);+ } finally {+ await cleanup(first);+ await cleanup(second);+ }+ });++ /* The three alert capabilities are per device, but whether a device may have them at all is+ the deployment's call. A preference stored before the operator closed the gate must not keep+ announcing replies, and the toggle that wrote it has nothing left to offer. */+ test('an operator who disables the tab badge leaves no count and no toggle @scenario:operator-disabled-tab-badge-shows-no-count-or-toggle', async ({+ page,+ }) => {+ const id = conversationId();+ const title = `Gated badge ${id.slice(0, 8)}`;+ const replyAt = new Date(Date.now() - 2_000);+ const seenAt = new Date(replyAt.getTime() - 1_000);+ try {+ await seedConversation(id, title, { lastResponseAt: replyAt, lastSeenAt: seenAt });+ await seedReplyMessage(id, title);+ await enableUnseenBadge(page);+ await serveReplyNotificationConfig(page, { tabBadge: false });+ await page.goto(NEW_CHAT_PATH);+ await openSidebar(page);+ const row = page.getByTestId('convo-item').filter({ hasText: title });+ await expect(row).toBeVisible();+ /* The dot belongs to the conversation list, not to the away alerts, so the gate leaves it. */+ await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toBeVisible();+ await expect.poll(() => page.title()).not.toMatch(/^\(\d+\)/);+ await page.getByTestId('nav-user').click();+ await page.getByRole('menuitem', { name: 'Settings' }).click();+ /* The settings dialog's outer node carries the role while the panel inside it is what is+ painted, so the General tab is what says the settings are on screen. */+ await expect(page.getByRole('tab', { name: 'General' })).toBeVisible({ timeout: 15000 });+ await expect(page.getByTestId('unseenTabBadge')).toHaveCount(0);+ } finally {+ await cleanup(id);+ }+ });++ test('marking a read conversation unread restores its dot and title count @scenario:mark-as-unread-restores-dot', async ({+ page,+ }) => {+ const id = conversationId();+ const title = `Mark unread ${id.slice(0, 8)}`;+ const replyAt = new Date(Date.now() - 2_000);+ try {+ await seedConversation(id, title, { lastResponseAt: replyAt, lastSeenAt: replyAt });+ await seedReplyMessage(id, title);+ await enableUnseenBadge(page);+ await page.goto(NEW_CHAT_PATH);+ await openSidebar(page);+ const row = page.getByTestId('convo-item').filter({ hasText: title });+ await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toHaveCount(0);+ await openConversationMenu(row);+ /* Dispatched rather than clicked, like the row controls around it: the menu is portaled,+ and on the mobile project the drawer's scrim sits over it and intercepts the pointer. */+ await page.getByRole('menuitem', { name: 'Mark as unread' }).dispatchEvent('click');+ await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toBeVisible();+ await expect.poll(() => page.title()).toMatch(/^\(1\)/);++ const token = await getAccessToken(page);+ const neverReplied = conversationId();+ try {+ await seedConversation(neverReplied, `Never replied ${neverReplied.slice(0, 8)}`);+ const response = await requestJson<{+ modified: boolean;+ lastResponseAt?: string;+ lastResponseIsManual?: boolean;+ }>(page, {+ path: '/api/convos/unread',+ token,+ method: 'POST',+ body: { arg: { conversationId: neverReplied } },+ });+ expect(response.modified).toBe(true);+ expect(response.lastResponseAt).toBeTruthy();+ expect(response.lastResponseIsManual).toBe(true);+ const stored = await readConversation(neverReplied);+ expect(stored?.lastResponseIsManual).toBe(true);+ expect(stored?.lastResponseAt).toBeInstanceOf(Date);+ } finally {+ await cleanup(neverReplied);+ }+ } finally {+ await cleanup(id);+ }+ });++ test('conversation accessible name announces unread reply with the dot @scenario:accessible-name-announces-unread', async ({+ page,+ }) => {+ const id = conversationId();+ const title = `Accessible unread ${id.slice(0, 8)}`;+ const replyAt = new Date(Date.now() - 2_000);+ try {+ await seedConversation(id, title, { lastResponseAt: replyAt, lastSeenAt: replyAt });+ await seedReplyMessage(id, title);+ await page.goto(NEW_CHAT_PATH);+ await openSidebar(page);+ const row = page.getByTestId('convo-item').filter({ hasText: title });+ const button = row.getByRole('button').first();+ await expect(button).toHaveAccessibleName(`${title} conversation`);+ await openConversationMenu(row);+ /* Dispatched rather than clicked, like the row controls around it: the menu is portaled,+ and on the mobile project the drawer's scrim sits over it and intercepts the pointer. */+ await page.getByRole('menuitem', { name: 'Mark as unread' }).dispatchEvent('click');+ await expect(button).toHaveAccessibleName(`${title} conversation, Unread`);+ await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toBeVisible();+ } finally {+ await cleanup(id);+ }+ });++ test('a reply completing in another tab lights the first tab without reload @scenario:reply-finishing-in-another-tab-lights-dot', async ({+ page,+ context,+ }) => {+ /* Setup on the mobile project (drawer, endpoint picker, streamed reply) plus a full+ 30-second away-poll interval and its list refresh can exceed 90 seconds. */+ test.setTimeout(150_000);+ const id = conversationId();+ const title = `Other tab reply ${id.slice(0, 8)}`;+ const replyAt = new Date(Date.now() - 2_000);+ try {+ await seedConversation(id, title, { lastResponseAt: replyAt, lastSeenAt: replyAt });+ await seedReplyMessage(id, title);+ await enableUnseenBadge(page);+ await page.goto(NEW_CHAT_PATH);+ await openSidebar(page);+ const row = page.getByTestId('convo-item').filter({ hasText: title });+ await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toHaveCount(0);+ await unfocus(page);++ const second = await context.newPage();+ try {+ await second.goto(`/c/${id}`);+ /* This page only ever sends a reply, so it wants the composer rather than the list. On+ the mobile project an open drawer sits over the composer and marks the pane inert,+ which is the reader's own experience of it and would leave nothing here to type in. */+ await expect(second.getByRole('textbox', { name: 'Message input' })).toBeVisible();+ await selectMockEndpoint(second, MOCK_ENDPOINTS[0]);+ await second.bringToFront();+ await unfocus(page);+ const acknowledged = second.waitForResponse(+ (response) =>+ new URL(response.url()).pathname === '/api/convos/seen' &&+ response.request().method() === 'POST',+ );+ await sendMessageAndWaitForCompletion(second, `E2E_REPLY:other-tab-${id.slice(0, 8)}`);+ /* The reply tab acknowledges the reply it just rendered. Restoring the unread baseline+ * before that write lands would simply be overwritten by it, and the first tab would+ * then poll a conversation the server considers read. */+ await acknowledged;+ await second.goto(NEW_CHAT_PATH);+ /* Back to the front, still away: a backgrounded tab has its timers throttled, so the+ * 30-second away poll this scenario is about may simply never run inside the budget.+ * `unfocus` keeps the app in away mode while the browser keeps the page live. */+ await page.bringToFront();+ await unfocus(page);+ await restoreUnreadBaseline(id, now(), replyAt);+ await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toBeVisible({+ timeout: 75_000,+ });+ await expect.poll(() => page.title()).toMatch(/^\(1\)/);+ } finally {+ await second.close();+ }+ } finally {+ await cleanup(id);+ }+ });++ test('notification permission is requested from the toggle click, not load @scenario:notification-permission-from-toggle-click', async ({+ page,+ }) => {+ await page.addInitScript(() => {+ const calls: string[] = [];+ class TestNotification {+ static permission = 'default';+ static requestPermission() {+ calls.push('request');+ TestNotification.permission = 'granted';+ return Promise.resolve('granted');+ }+ }+ Object.defineProperty(window, 'Notification', {+ configurable: true,+ value: TestNotification,+ });+ Object.defineProperty(window, '__notificationPermissionCalls', {+ configurable: true,+ value: calls,+ });+ });+ await page.goto(NEW_CHAT_PATH);+ await openSidebar(page);+ await expect+ .poll(() =>+ page.evaluate(+ () =>+ (window as Window & { __notificationPermissionCalls: string[] })+ .__notificationPermissionCalls,+ ),+ )+ .toEqual([]);+ await page.getByTestId('nav-user').dispatchEvent('click');+ await page.getByTestId('nav-settings').dispatchEvent('click');+ await page.getByRole('tab', { name: 'General' }).dispatchEvent('click');+ const toggle = page.getByTestId('replyNotifications');+ await expect(toggle).toBeVisible();+ await toggle.click();+ await expect+ .poll(() =>+ page.evaluate(+ () =>+ (window as Window & { __notificationPermissionCalls: string[] })+ .__notificationPermissionCalls,+ ),+ )+ .toEqual(['request']);+ });++ test('replies withheld by a pending permission prompt are released once with one notification @scenario:withheld-replies-released-after-grant', async ({+ page,+ context,+ }) => {+ test.setTimeout(90_000);+ const id = conversationId();+ const title = `Withheld reply ${id.slice(0, 8)}`;+ const replyAt = new Date(Date.now() - 2_000);+ await page.addInitScript(() => {+ const constructions: string[] = [];+ const calls: string[] = [];+ let resolvePermission: ((permission: NotificationPermission) => void) | undefined;+ const pending = new Promise<NotificationPermission>((resolve) => {+ resolvePermission = resolve;+ });+ class TestNotification {+ static permission: NotificationPermission = 'default';+ static requestPermission() {+ calls.push('request');+ return pending;+ }+ close() {}+ onclick: (() => void) | null = null;+ constructor() {+ constructions.push('notification');+ }+ }+ Object.defineProperty(window, 'Notification', {+ configurable: true,+ value: TestNotification,+ });+ Object.defineProperty(window, '__notificationPermissionCalls', {+ configurable: true,+ value: calls,+ });+ Object.defineProperty(window, '__notificationConstructions', {+ configurable: true,+ value: constructions,+ });+ Object.defineProperty(window, '__grantNotificationPermission', {+ configurable: true,+ value: () => {+ TestNotification.permission = 'granted';+ resolvePermission?.('granted');+ },+ });+ });+ try {+ await seedConversation(id, title, { lastResponseAt: replyAt, lastSeenAt: replyAt });+ await seedReplyMessage(id, title);+ await page.goto(NEW_CHAT_PATH);+ await openSidebar(page);+ await page.getByTestId('nav-user').dispatchEvent('click');+ await page.getByTestId('nav-settings').dispatchEvent('click');+ await page.getByRole('tab', { name: 'General' }).dispatchEvent('click');+ const toggle = page.getByTestId('replyNotifications');+ await expect(toggle).toBeVisible();+ await toggle.click();+ await expect+ .poll(() =>+ page.evaluate(+ () =>+ (window as Window & { __notificationPermissionCalls: string[] })+ .__notificationPermissionCalls,+ ),+ )+ .toEqual(['request']);++ /* Stay on this page: a reload would re-run the init script with a fresh pending+ promise that the hook never requested, and the grant below would resolve nothing. */+ await page.keyboard.press('Escape');+ await expect(toggle).toBeHidden();+ await openSidebar(page);+ await unfocus(page);+ const row = page.getByTestId('convo-item').filter({ hasText: title });+ const second = await context.newPage();+ try {+ await second.goto(`/c/${id}`);+ /* This page only ever sends a reply, so it wants the composer rather than the list. On+ the mobile project an open drawer sits over the composer and marks the pane inert,+ which is the reader's own experience of it and would leave nothing here to type in. */+ await expect(second.getByRole('textbox', { name: 'Message input' })).toBeVisible();+ await selectMockEndpoint(second, MOCK_ENDPOINTS[0]);+ await second.bringToFront();+ await unfocus(page);+ await sendMessageAndWaitForCompletion(second, `E2E_REPLY:withheld-${id.slice(0, 8)}`);+ await restoreUnreadBaseline(id, now(), replyAt);+ } finally {+ await second.evaluate(() => window.dispatchEvent(new Event('blur'))).catch(() => {});+ await second.close();+ }+ await expect+ .poll(() =>+ page.evaluate(+ () =>+ (window as Window & { __notificationConstructions: string[] })+ .__notificationConstructions,+ ),+ )+ .toEqual([]);++ await page.evaluate(() => {+ (+ window as Window & { __grantNotificationPermission: () => void }+ ).__grantNotificationPermission();+ });+ await restoreUnreadBaseline(id, now(), replyAt);+ /* `sidebarExpanded` is stored per browser, so the reply tab's own mobile shell closed this+ list while it was open. Looking at the list again is what a reader does, and it is where+ the dot has to show. */+ await openSidebar(page);+ await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toBeVisible({+ timeout: 45_000,+ });+ await expect+ .poll(() =>+ page.evaluate(+ () =>+ (window as Window & { __notificationConstructions: string[] })+ .__notificationConstructions,+ ),+ )+ .toEqual(['notification']);+ } finally {+ await cleanup(id);+ }+ });++ test('concurrent reply stamps remain monotonic under an older wall clock @scenario:clock-skewed-concurrent-stamps', async ({+ context,+ }) => {+ const id = conversationId();+ const title = `Clock skew ${id.slice(0, 8)}`;+ const baseline = new Date(Date.now() - 10_000);+ const observations: number[] = [baseline.getTime()];+ try {+ await seedConversation(id, title, { lastResponseAt: baseline, lastSeenAt: baseline });+ await seedReplyMessage(id, title);+ const pages = await Promise.all([context.newPage(), context.newPage(), context.newPage()]);+ try {+ for (const [index, otherPage] of pages.entries()) {+ await otherPage.goto(`/c/${id}`);+ /* Only the composer is used here; see the note on the reply page above. */+ await expect(otherPage.getByRole('textbox', { name: 'Message input' })).toBeVisible();+ await selectMockEndpoint(otherPage, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(+ otherPage,+ `E2E_REPLY:clock-${index}-${id.slice(0, 8)}`,+ );+ const observed = await readConversation(id);+ if (observed?.lastResponseAt) observations.push(observed.lastResponseAt.getTime());+ }+ } finally {+ await Promise.all(pages.map((otherPage) => otherPage.close()));+ }+ const stored = await readConversation(id);+ expect(stored?.lastResponseAt).toBeInstanceOf(Date);+ const finalStamp = (stored?.lastResponseAt as Date).getTime();+ expect(finalStamp).toBe(Math.max(...observations));+ } finally {+ await cleanup(id);+ }+ });++ test('a stale seen acknowledgement is rejected without regressing read state or updatedAt @scenario:stale-seen-ack-rejected', async ({+ page,+ }) => {+ const id = conversationId();+ const title = `Stale seen ${id.slice(0, 8)}`;+ const oldReplyAt = new Date(Date.now() - 4_000);+ const newReplyAt = new Date(Date.now() - 2_000);+ const seenAt = new Date(Date.now() - 3_000);+ const updatedAt = new Date(Date.now() - 1_000);+ try {+ await seedConversation(id, title, { lastResponseAt: newReplyAt, lastSeenAt: seenAt });+ await withMongo(async (db) => {+ const user = await db.collection('users').findOne({ email: userEmail });+ if (!user) throw new Error(`E2E user ${userEmail} does not exist`);+ await db+ .collection('conversations')+ .updateOne({ user: user._id.toString(), conversationId: id }, { $set: { updatedAt } });+ });+ await page.goto(NEW_CHAT_PATH);+ const token = await getAccessToken(page);+ const response = await requestJson<{ modified: boolean }>(page, {+ path: '/api/convos/seen',+ token,+ method: 'POST',+ body: { arg: { conversationId: id, lastResponseAt: oldReplyAt.toISOString() } },+ });+ expect(response.modified).toBe(false);+ const stored = await readConversation(id);+ expect(stored?.lastResponseAt?.getTime()).toBe(newReplyAt.getTime());+ expect(stored?.lastSeenAt?.getTime()).toBe(seenAt.getTime());+ expect(stored?.updatedAt?.getTime()).toBe(updatedAt.getTime());+ } finally {+ await cleanup(id);+ }+ });++ test('metadata edits preserve a manual unread flag and a real reply clears it @scenario:metadata-edit-preserves-manual-unread', async ({+ page,+ }) => {+ const id = conversationId();+ const title = `Manual unread ${id.slice(0, 8)}`;+ const renamed = `${title} renamed`;+ try {+ await seedConversation(id, title);+ await page.goto(NEW_CHAT_PATH);+ const token = await getAccessToken(page);+ const unread = await requestJson<{ modified: boolean; lastResponseIsManual?: boolean }>(+ page,+ {+ path: '/api/convos/unread',+ token,+ method: 'POST',+ body: { arg: { conversationId: id } },+ },+ );+ expect(unread.modified).toBe(true);+ expect(unread.lastResponseIsManual).toBe(true);+ await requestJson(page, {+ path: '/api/convos/update',+ token,+ method: 'POST',+ body: { arg: { conversationId: id, title: renamed } },+ });+ let stored = await readConversation(id);+ expect(stored?.title).toBe(renamed);+ expect(stored?.lastResponseIsManual).toBe(true);++ await page.goto(`/c/${id}`);+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible();+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, `E2E_REPLY:clears-manual-${id.slice(0, 8)}`);+ stored = await readConversation(id);+ expect(stored?.lastResponseIsManual).toBeUndefined();+ } finally {+ await cleanup(id);+ }+ });++ test('applying a preset does not fabricate or clear conversation read-state fields @scenario:preset-apply-cannot-fabricate-unread', async ({+ page,+ }) => {+ const id = conversationId();+ const title = `Preset read state ${id.slice(0, 8)}`;+ const replyAt = new Date(Date.now() - 4_000);+ const seenAt = new Date(Date.now() - 3_000);+ try {+ await seedConversation(id, title, {+ lastResponseAt: replyAt,+ lastSeenAt: seenAt,+ lastResponseIsManual: true,+ });+ const before = await readConversation(id);+ await page.goto(NEW_CHAT_PATH);+ const token = await getAccessToken(page);+ await requestJson(page, {+ path: '/api/convos/update',+ token,+ method: 'POST',+ body: {+ arg: {+ conversationId: id,+ title,+ endpoint: MOCK_ENDPOINTS[0].model,+ model: MOCK_ENDPOINTS[0].model,+ modelLabel: 'Preset applied',+ },+ },+ });+ const after = await readConversation(id);+ expect(after?.lastResponseAt?.toISOString()).toBe(before?.lastResponseAt?.toISOString());+ expect(after?.lastSeenAt?.toISOString()).toBe(before?.lastSeenAt?.toISOString());+ expect(after?.lastResponseIsManual).toBe(before?.lastResponseIsManual);+ } finally {+ await cleanup(id);+ }+ });++ test('aborting an empty generation does not stamp lastResponseAt @scenario:abort-null-save-does-not-stamp', async ({+ page,+ }) => {+ test.setTimeout(90_000);+ const id = conversationId();+ const title = `Abort empty ${id.slice(0, 8)}`;+ const replyAt = new Date(Date.now() - 2_000);+ try {+ await seedConversation(id, title, { lastResponseAt: replyAt, lastSeenAt: replyAt });+ await seedReplyMessage(id, title);+ await page.goto(`/c/${id}`);+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible();+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ const input = page.getByRole('textbox', { name: 'Message input' });+ await input.fill(`E2E_EMPTY_SLOW_REPLY:${id.slice(0, 8)}`);+ await input.press('Enter');+ const stop = page.getByRole('button', { name: 'Stop generating' });+ await expect(stop).toBeVisible({ timeout: 15_000 });+ await stop.click();+ await expect(stop).toBeHidden({ timeout: 30_000 });+ await expect+ .poll(async () => (await readConversation(id))?.lastResponseAt?.getTime())+ .toBe(replyAt.getTime());+ } finally {+ await cleanup(id);+ }+ });+});diff --git a/librechat.example.yaml b/librechat.example.yamlindex edccfcd874..8519982b92 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -249,6 +249,23 @@ interface:fileCitations: true# Show the thumbs up/thumbs down feedback buttons on responses (default: true)feedback: true+ # Unseen-reply alerts: what this deployment lets a reader turn on. Each field gates a+ # capability; the preference itself stays per device, because notification permission and+ # audio output belong to the machine the reader is sitting at. Sidebar unread dots and+ # Mark as unread are not gated here, they are part of the conversation list.+ # replyNotifications:+ # tabBadge: true # Allow the unseen count in the tab title and favicon (default: true)+ # desktop: true # Allow readers to turn on desktop notifications for replies (default: true)+ # sound: true # Allow readers to turn on the reply chime (default: true)+ # # How many conversations one background poll looks at (1-100, default: 100). The list's+ # # own maximum page is the ceiling, so covering a deployment whose replies outpace one+ # # page is not a matter of raising this.+ # pollLimit: 100+ # # Milliseconds between list checks while a tab is away (10000-600000, default: 30000).+ # pollIntervalMs: 30000+ # # Milliseconds between list refreshes while a tab is focused (60000-300000, default: 300000).+ # # It renews the snapshot the unread count reads, so it cannot be slower than five minutes.+ # focusedRefreshMs: 300000# Conversation trace viewer: a waterfall of the model calls and tool spans behind# each response, read from the deployment's Langfuse project. The control only# appears on the requesting user's own conversations with a sampled trace, anddiff --git a/packages/api/src/conversations/announce.spec.ts b/packages/api/src/conversations/announce.spec.tsnew file mode 100644index 0000000000..433fd30513--- /dev/null+++ b/packages/api/src/conversations/announce.spec.ts@@ -0,0 +1,302 @@+import { Types } from 'mongoose';+import {+ announceReply,+ announceErrorTurn,+ announceStoppedReply,+ isAnnounceableReply,+ settleAssistantFinal,+} from './announce';++const readable = [{ type: 'text', text: 'here is the answer' }];+const rowA = new Types.ObjectId().toString();+const rowB = new Types.ObjectId().toString();++describe('isAnnounceableReply', () => {+ it('announces a persisted reply that has something to read', () => {+ expect(isAnnounceableReply({ messageId: 'msg-1', content: readable })).toBe(true);+ expect(isAnnounceableReply({ messageId: 'msg-1', text: 'plain answer' })).toBe(true);+ });++ it('refuses a reply whose write resolved empty', () => {+ expect(isAnnounceableReply({ messageId: null, content: readable })).toBe(false);+ expect(isAnnounceableReply({ messageId: '', content: readable })).toBe(false);+ });++ /* A run cancelled before any output still persists the synthetic row the gap check built, and+ a Responses API completion carrying only reasoning or tool calls persists an empty `text`.+ Both render nothing, so a dot raised for them could never be cleared by opening the chat. */+ it('refuses a reply with nothing a reader could open', () => {+ expect(isAnnounceableReply({ messageId: 'msg-1', content: [] })).toBe(false);+ expect(isAnnounceableReply({ messageId: 'msg-1', text: '' })).toBe(false);+ expect(isAnnounceableReply({ messageId: 'msg-1', text: ' ' })).toBe(false);+ expect(+ isAnnounceableReply({ messageId: 'msg-1', content: [{ type: 'text', text: ' ' }] }),+ ).toBe(false);+ });++ it('refuses a temporary chat, which holds no row in the lists the indicator reads', () => {+ expect(isAnnounceableReply({ messageId: 'msg-1', content: readable, isTemporary: true })).toBe(+ false,+ );+ });+});++describe('announceReply', () => {+ it('stamps the persisted reply on its conversation', async () => {+ const stampConvoLastResponse = jest.fn().mockResolvedValue(undefined);+ const announced = await announceReply(+ { stampConvoLastResponse },+ {+ userId: 'user-1',+ conversationId: 'convo-1',+ reply: { messageId: 'msg-1', content: readable },+ context: 'spec',+ },+ );+ expect(announced).toBe(true);+ expect(stampConvoLastResponse).toHaveBeenCalledWith('user-1', 'convo-1', 'msg-1');+ });++ it.each([+ ['an unreadable reply', { messageId: 'msg-1', content: [] }],+ ['a temporary chat', { messageId: 'msg-1', content: readable, isTemporary: true }],+ ['an empty message write', { messageId: undefined, content: readable }],+ ])('writes nothing for %s', async (_case, reply) => {+ const stampConvoLastResponse = jest.fn();+ const announced = await announceReply(+ { stampConvoLastResponse },+ { userId: 'user-1', conversationId: 'convo-1', reply, context: 'spec' },+ );+ expect(announced).toBe(false);+ expect(stampConvoLastResponse).not.toHaveBeenCalled();+ });++ it('writes nothing without an owner or a conversation to stamp', async () => {+ const stampConvoLastResponse = jest.fn();+ const reply = { messageId: 'msg-1', content: readable };+ await announceReply(+ { stampConvoLastResponse },+ { userId: undefined, conversationId: 'convo-1', reply, context: 'spec' },+ );+ await announceReply(+ { stampConvoLastResponse },+ { userId: 'user-1', conversationId: '', reply, context: 'spec' },+ );+ expect(stampConvoLastResponse).not.toHaveBeenCalled();+ });++ /* The messages are already durable; failing a reply over its indicator would trade a missed+ dot for a lost response. */+ it('survives a failing stamp write', async () => {+ const stampConvoLastResponse = jest.fn().mockRejectedValue(new Error('mongo is away'));+ await expect(+ announceReply(+ { stampConvoLastResponse },+ {+ userId: 'user-1',+ conversationId: 'convo-1',+ reply: { messageId: 'msg-1', content: readable },+ context: 'spec',+ },+ ),+ ).resolves.toBe(false);+ });+});++describe('announceStoppedReply', () => {+ const ctx = { userId: 'user-1' };++ it('carries the stamp and the rows already written on the conversation upsert', async () => {+ const saveConvo = jest.fn().mockResolvedValue({ conversationId: 'convo-1' });+ const announced = await announceStoppedReply(+ { saveConvo },+ {+ ctx,+ conversationId: 'convo-1',+ endpoint: 'agents',+ model: 'gpt-5',+ reply: { messageId: 'msg-1', content: readable },+ appendMessageIds: [rowA, rowB],+ context: 'spec',+ },+ );+ expect(announced).toBe(true);+ expect(saveConvo).toHaveBeenCalledWith(+ ctx,+ { conversationId: 'convo-1', endpoint: 'agents', model: 'gpt-5' },+ expect.objectContaining({+ stampReply: true,+ replyMessageId: 'msg-1',+ appendMessageIds: [rowA, rowB],+ }),+ );+ });++ /* An interrupt before the model's first real token still persists the unfinished assistant+ row; a dot raised for it names a reply the user can never open. */+ it('leaves a stopped turn that produced nothing to read alone', async () => {+ const saveConvo = jest.fn();+ const announced = await announceStoppedReply(+ { saveConvo },+ {+ ctx,+ conversationId: 'convo-1',+ reply: { messageId: 'msg-1', content: [] },+ context: 'spec',+ },+ );+ expect(announced).toBe(false);+ expect(saveConvo).not.toHaveBeenCalled();+ });++ it('takes the temporary flag from the write context the turn runs under', async () => {+ const saveConvo = jest.fn();+ await announceStoppedReply(+ { saveConvo },+ {+ ctx: { userId: 'user-1', isTemporary: true },+ conversationId: 'convo-1',+ reply: { messageId: 'msg-1', content: readable },+ context: 'spec',+ },+ );+ expect(saveConvo).not.toHaveBeenCalled();+ });++ it('normalizes the ids the caller holds and drops rows that were never written', async () => {+ const saveConvo = jest.fn().mockResolvedValue({ conversationId: 'convo-1' });+ await announceStoppedReply(+ { saveConvo },+ {+ ctx,+ conversationId: 'convo-1',+ reply: { messageId: 'msg-1', content: readable },+ appendMessageIds: [null, new Types.ObjectId(rowA), undefined, rowB],+ context: 'spec',+ },+ );+ expect(saveConvo.mock.calls[0][2]).toMatchObject({ appendMessageIds: [rowA, rowB] });+ });++ it('omits an empty append set rather than sending one', async () => {+ const saveConvo = jest.fn().mockResolvedValue({ conversationId: 'convo-1' });+ await announceStoppedReply(+ { saveConvo },+ {+ ctx,+ conversationId: 'convo-1',+ reply: { messageId: 'msg-1', content: readable },+ context: 'spec',+ },+ );+ expect(saveConvo.mock.calls[0][2]).not.toHaveProperty('appendMessageIds');+ });++ it('survives a failing conversation write', async () => {+ const saveConvo = jest.fn().mockRejectedValue(new Error('mongo is away'));+ await expect(+ announceStoppedReply(+ { saveConvo },+ {+ ctx,+ conversationId: 'convo-1',+ reply: { messageId: 'msg-1', content: readable },+ context: 'spec',+ },+ ),+ ).resolves.toBe(false);+ });+});++describe('announceErrorTurn', () => {+ const settled = {+ lastResponseAt: '2026-09-22T12:00:00.000Z',+ lastResponseMessageId: 'err-1',+ updatedAt: '2026-09-22T12:00:00.000Z',+ };++ it('stamps a persisted error turn and returns the snapshot its event carries', async () => {+ const stampConvoLastResponse = jest.fn().mockResolvedValue(settled);+ const snapshot = await announceErrorTurn(+ { stampConvoLastResponse },+ { userId: 'user-1', conversationId: 'convo-1', messageId: 'err-1', context: 'spec' },+ );++ expect(stampConvoLastResponse).toHaveBeenCalledWith('user-1', 'convo-1', 'err-1');+ expect(snapshot).toEqual({ conversationId: 'convo-1', ...settled });+ });++ it.each([+ ['a temporary chat', { isTemporary: true }],+ ['an error write that resolved empty', { messageId: undefined }],+ ['a request without a user', { userId: undefined }],+ ])('writes nothing for %s', async (_case, override) => {+ const stampConvoLastResponse = jest.fn();+ const snapshot = await announceErrorTurn(+ { stampConvoLastResponse },+ {+ userId: 'user-1',+ conversationId: 'convo-1',+ messageId: 'err-1',+ context: 'spec',+ ...override,+ },+ );++ expect(snapshot).toBeUndefined();+ expect(stampConvoLastResponse).not.toHaveBeenCalled();+ });++ /* The error row is already durable; a failed stamp must not turn a handled error into a thrown one. */+ it('returns no snapshot, rather than throwing, when the stamp fails', async () => {+ const stampConvoLastResponse = jest.fn().mockRejectedValue(new Error('mongo is away'));+ await expect(+ announceErrorTurn(+ { stampConvoLastResponse },+ { userId: 'user-1', conversationId: 'convo-1', messageId: 'err-1', context: 'spec' },+ ),+ ).resolves.toBeUndefined();+ });+});++describe('settleAssistantFinal', () => {+ it('returns the plain settled conversation for the final event', async () => {+ const settled = { conversationId: 'convo-1', lastResponseAt: '2026-09-23T10:00:00.000Z' };+ const conversation = await settleAssistantFinal(async () => ({+ message: { messageId: 'msg-1' },+ conversation: { ...settled, toObject: () => settled },+ }));++ expect(conversation).toEqual(settled);+ });++ /* A save that persisted nothing is not a snapshot, so nothing may be published from it. */+ it('refuses to publish when the response row was not persisted', async () => {+ await expect(+ settleAssistantFinal(async () => ({ message: null, conversation: { conversationId: 'c' } })),+ ).rejects.toThrow('Assistant response could not be persisted before final publication');+ });++ it('refuses to publish when the conversation write returned its error shape', async () => {+ await expect(+ settleAssistantFinal(async () => ({+ message: { messageId: 'msg-1' },+ conversation: { message: 'Error saving conversation' },+ })),+ ).rejects.toThrow('Assistant conversation could not be persisted before final publication');+ });+});++describe('isAnnounceableReply attachments', () => {+ /* The message body renders attachments, and acknowledgement checks the body, so a reply made+ only of files can be both announced and cleared. */+ it('announces a reply made only of attachments', () => {+ expect(+ isAnnounceableReply({ messageId: 'msg-1', content: [], text: '', attachments: [{}] }),+ ).toBe(true);+ });++ it('does not treat an empty attachment list as something to read', () => {+ expect(isAnnounceableReply({ messageId: 'msg-1', content: [], attachments: [] })).toBe(false);+ });+});diff --git a/packages/api/src/conversations/announce.ts b/packages/api/src/conversations/announce.tsnew file mode 100644index 0000000000..67b76be6c2--- /dev/null+++ b/packages/api/src/conversations/announce.ts@@ -0,0 +1,259 @@+import { logger } from '@librechat/data-schemas';+import type { ConversationMethods } from '@librechat/data-schemas';+import { hasPersistableAbortContent } from '../stream/abortContent';++type SaveConvo = ConversationMethods['saveConvo'];+/** Derived here rather than imported from `./save`, which depends on this module. */+type ConversationWriteContext = Parameters<SaveConvo>[0];++/** Declared structurally so a caller hands over its store rather than this module reaching for one. */+export interface ReplyStampStore {+ stampConvoLastResponse(user: string, conversationId: string, messageId: string): Promise<unknown>;+}++export interface ReplyConversationStore {+ saveConvo: SaveConvo;+}++/** What a turn knows about the assistant row it just persisted. */+export interface PersistedReply {+ /** Absent when the write resolved empty, which is a reply nobody can open. */+ messageId?: string | null;+ /** The content parts persisted with it. */+ content?: unknown;+ /** Plain text, for the paths that persist text instead of content parts. */+ text?: string | null;+ /** Files the reply produced; a reply made only of them still renders in the message body. */+ attachments?: readonly object[] | null;+ /** A temporary chat holds no row in the lists the indicator is read from. */+ isTemporary?: boolean;+}++/**+ * Whether a persisted assistant turn may raise the unseen-reply indicator.+ *+ * Acknowledgement requires the stamped reply to be on screen, so a row that renders nothing+ * would leave a dot the reader can never clear by opening the conversation. Every path that+ * persists an assistant row asks here: a stopped turn interrupted before its first token, a+ * run cancelled before any output, and a Responses API completion whose output carried only+ * reasoning or tool calls all persist a row with nothing readable in it. A reply made only of+ * attachments is readable: the message body renders them, which is what acknowledgement checks.+ */+export function isAnnounceableReply(reply: PersistedReply): boolean {+ if (reply.isTemporary === true) {+ return false;+ }+ const { messageId } = reply;+ if (typeof messageId !== 'string' || messageId.length === 0) {+ return false;+ }+ return (+ hasPersistableAbortContent(reply.content) ||+ (typeof reply.text === 'string' && reply.text.trim().length > 0) ||+ (Array.isArray(reply.attachments) && reply.attachments.length > 0)+ );+}++export interface ReplyAnnouncement {+ userId?: string | null;+ conversationId?: string | null;+ reply: PersistedReply;+ /** Names the caller in the failure log. */+ context: string;+}++/**+ * Stamps a persisted reply on its conversation, for the paths whose row already exists.+ *+ * Best effort, and it never throws: the messages are already durable, and failing a reply over+ * its indicator would trade a missed dot for a lost response. Returns whether it stamped.+ */+export async function announceReply(+ deps: ReplyStampStore,+ { userId, conversationId, reply, context }: ReplyAnnouncement,+): Promise<boolean> {+ if (userId == null || userId === '' || conversationId == null || conversationId === '') {+ return false;+ }+ if (!isAnnounceableReply(reply)) {+ return false;+ }+ try {+ await deps.stampConvoLastResponse(userId, conversationId, reply.messageId as string);+ return true;+ } catch (error) {+ logger.warn(`[announceReply] ${context}`, error);+ return false;+ }+}++export interface StoppedReplyAnnouncement {+ ctx: ConversationWriteContext;+ conversationId: string;+ endpoint?: string | null;+ model?: string | null;+ reply: PersistedReply;+ /**+ * The rows this turn already wrote, so the stamp write does not reload the whole history.+ * Taken as the caller holds them and normalized to plain ids here: the storage engine's own+ * id type stays behind `saveConvo`, which casts them back. Unwritten rows arrive as null.+ */+ appendMessageIds?: ReadonlyArray<string | { toString(): string } | null | undefined>;+ context: string;+}++/**+ * Announces a stopped turn's reply through the conversation write itself.+ *+ * A very early interrupt can arrive before the conversation row exists, so the same upsert that+ * creates it carries the stamp, assigned at write time. Best effort for the same reason as+ * `announceReply`: a missed stamp must not suppress the turn's own terminal event.+ */+export async function announceStoppedReply(+ deps: ReplyConversationStore,+ {+ ctx,+ conversationId,+ endpoint,+ model,+ reply,+ appendMessageIds = [],+ context,+ }: StoppedReplyAnnouncement,+): Promise<boolean> {+ if (!isAnnounceableReply({ ...reply, isTemporary: ctx.isTemporary ?? reply.isTemporary })) {+ return false;+ }+ const writtenIds = appendMessageIds.flatMap((id) => (id == null ? [] : [String(id)]));+ try {+ await deps.saveConvo(+ ctx,+ {+ conversationId,+ ...(endpoint != null ? { endpoint } : {}),+ ...(model != null ? { model } : {}),+ },+ {+ context,+ stampReply: true,+ replyMessageId: reply.messageId as string,+ ...(writtenIds.length > 0 ? { appendMessageIds: writtenIds } : {}),+ },+ );+ return true;+ } catch (error) {+ logger.warn(`[announceStoppedReply] ${context}`, error);+ return false;+ }+}++/** What a durable reply stamp settled to, as the stamping write reports it. */+export interface SettledReplyStamp {+ lastResponseAt?: Date | string | null;+ lastResponseMessageId?: string | null;+ updatedAt?: Date | string | null;+}++export interface ErrorTurnStampStore {+ stampConvoLastResponse(+ user: string,+ conversationId: string,+ messageId: string,+ ): Promise<SettledReplyStamp | null | undefined>;+}++/** The conversation snapshot an error event carries so the client can acknowledge it. */+export interface ErrorTurnSnapshot {+ conversationId: string;+ lastResponseAt: Date | string;+ lastResponseMessageId?: string;+ updatedAt?: Date | string;+}++export interface ErrorTurnAnnouncement {+ userId?: string | null;+ conversationId?: string | null;+ /** The persisted error row; absent when its write resolved empty. */+ messageId?: string | null;+ isTemporary?: boolean;+ context: string;+}++/**+ * Stamps a persisted error turn and returns the snapshot its terminal event should carry.+ *+ * A failed run is still a persisted assistant turn, and on the fallback paths it is the only one:+ * without a stamp another device never learns the run ended. Error turns are not judged by+ * `isAnnounceableReply`, because the error card is what renders them. Best effort, and it never+ * throws: the error row is already durable, and a failed stamp must not turn a handled error into+ * an unhandled one. The snapshot is what the client acknowledges, so no browser-generated time can+ * stand in for it.+ */+export async function announceErrorTurn(+ deps: ErrorTurnStampStore,+ { userId, conversationId, messageId, isTemporary, context }: ErrorTurnAnnouncement,+): Promise<ErrorTurnSnapshot | undefined> {+ if (+ isTemporary === true ||+ userId == null ||+ userId === '' ||+ conversationId == null ||+ conversationId === '' ||+ messageId == null ||+ messageId === ''+ ) {+ return undefined;+ }+ try {+ const settled = await deps.stampConvoLastResponse(userId, conversationId, messageId);+ if (settled?.lastResponseAt == null) {+ return undefined;+ }+ return {+ conversationId,+ lastResponseAt: settled.lastResponseAt,+ ...(settled.lastResponseMessageId != null+ ? { lastResponseMessageId: settled.lastResponseMessageId }+ : {}),+ ...(settled.updatedAt != null ? { updatedAt: settled.updatedAt } : {}),+ };+ } catch (error) {+ logger.error(`[announceErrorTurn] ${context}`, error);+ return undefined;+ }+}++/** The conversation a save settled, as the conversation write returns it. */+interface SettledConversationDocument<TConversation> {+ /** Present on the error shape a failed conversation write returns in place of the row. */+ message?: string;+ toObject?: () => TConversation;+}++/** What the assistant save reports: the persisted row and the conversation it settled. */+export interface AssistantFinalSave<TConversation extends object> {+ message?: object | null;+ conversation?: (TConversation & SettledConversationDocument<TConversation>) | null;+}++/**+ * Persists an assistant response ahead of its final event and returns the conversation that+ * event must carry.+ *+ * The final event is the history barrier for active clients, so the response is written first+ * and the snapshot carries the server-owned read-state stamp the client has to acknowledge,+ * rather than a timestamp invented from the response. A save that persisted nothing is not a+ * snapshot at all, so either failure throws before anything is published.+ */+export async function settleAssistantFinal<TConversation extends object>(+ save: () => Promise<AssistantFinalSave<TConversation>>,+): Promise<TConversation> {+ const { message, conversation } = await save();+ if (!message) {+ throw new Error('Assistant response could not be persisted before final publication');+ }+ if (!conversation || conversation.message) {+ throw new Error('Assistant conversation could not be persisted before final publication');+ }+ return typeof conversation.toObject === 'function' ? conversation.toObject() : conversation;+}diff --git a/packages/api/src/conversations/index.ts b/packages/api/src/conversations/index.tsindex 35c0db3f92..535f017835 100644--- a/packages/api/src/conversations/index.ts+++ b/packages/api/src/conversations/index.ts@@ -1,5 +1,7 @@+export * from './announce';export * from './archive';export * from './chatgpt';export * from './import';export * from './lineage';+export * from './read';export * from './save';diff --git a/packages/api/src/conversations/read.spec.ts b/packages/api/src/conversations/read.spec.tsnew file mode 100644index 0000000000..6819569bf5--- /dev/null+++ b/packages/api/src/conversations/read.spec.ts@@ -0,0 +1,184 @@+import { logger } from '@librechat/data-schemas';++import type { Response } from 'express';+import type { ServerRequest } from '~/types';+import { createMarkConvoSeenHandler, createMarkConvoUnreadHandler } from './read';++jest.mock('@librechat/data-schemas', () => ({+ logger: {+ error: jest.fn(),+ },+}));++interface MockResponse {+ statusCode: number;+ body: unknown;+ status: jest.Mock;+ json: jest.Mock;+ send: jest.Mock;+}++function mockRequest(arg?: Record<string, unknown>): ServerRequest {+ return {+ user: { id: 'user-123' },+ body: arg === undefined ? undefined : { arg },+ } as Partial<ServerRequest> as ServerRequest;+}++function mockResponse(): Response & MockResponse {+ const res: MockResponse = {+ statusCode: 200,+ body: undefined,+ status: jest.fn((statusCode: number) => {+ res.statusCode = statusCode;+ return res;+ }),+ json: jest.fn((body: unknown) => {+ res.body = body;+ return res;+ }),+ send: jest.fn((body: unknown) => {+ res.body = body;+ return res;+ }),+ };+ return res as Response & MockResponse;+}++describe('createMarkConvoSeenHandler', () => {+ beforeEach(() => {+ (logger.error as jest.Mock).mockClear();+ });++ it('records the catch-up for the authenticated user', async () => {+ const markConvoSeen = jest.fn().mockResolvedValue({ modified: true });+ const res = mockResponse();++ await createMarkConvoSeenHandler({ markConvoSeen })(+ mockRequest({ conversationId: 'conv-1' }),+ res,+ );++ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({ modified: true });+ expect(markConvoSeen).toHaveBeenCalledWith('user-123', 'conv-1', undefined);+ });++ it('forwards the observed reply so a newer one is not acknowledged with it', async () => {+ const markConvoSeen = jest.fn().mockResolvedValue({ modified: false });+ const res = mockResponse();++ await createMarkConvoSeenHandler({ markConvoSeen })(+ mockRequest({ conversationId: 'conv-1', lastResponseAt: '2026-08-16T10:00:00.000Z' }),+ res,+ );++ expect(markConvoSeen).toHaveBeenCalledWith(+ 'user-123',+ 'conv-1',+ new Date('2026-08-16T10:00:00.000Z'),+ );+ });++ it('rejects a missing conversationId without touching the database', async () => {+ const markConvoSeen = jest.fn();+ const res = mockResponse();++ await createMarkConvoSeenHandler({ markConvoSeen })(mockRequest({}), res);++ expect(res.statusCode).toBe(400);+ expect(res.body).toEqual({ error: 'conversationId is required' });+ expect(markConvoSeen).not.toHaveBeenCalled();+ });++ it('rejects an unparseable lastResponseAt without touching the database', async () => {+ const markConvoSeen = jest.fn();+ const res = mockResponse();++ await createMarkConvoSeenHandler({ markConvoSeen })(+ mockRequest({ conversationId: 'conv-1', lastResponseAt: 'not-a-date' }),+ res,+ );++ expect(res.statusCode).toBe(400);+ expect(res.body).toEqual({ error: 'lastResponseAt must be a valid date' });+ expect(markConvoSeen).not.toHaveBeenCalled();+ });++ it('tolerates a request with no arg at all', async () => {+ const markConvoSeen = jest.fn();+ const res = mockResponse();++ await createMarkConvoSeenHandler({ markConvoSeen })(mockRequest(), res);++ expect(res.statusCode).toBe(400);+ expect(markConvoSeen).not.toHaveBeenCalled();+ });++ it('returns 500 when the database write fails', async () => {+ const markConvoSeen = jest.fn().mockRejectedValue(new Error('db unavailable'));+ const res = mockResponse();++ await createMarkConvoSeenHandler({ markConvoSeen })(+ mockRequest({ conversationId: 'conv-1' }),+ res,+ );++ expect(res.statusCode).toBe(500);+ expect(res.body).toBe('Error marking conversation seen');+ expect(logger.error).toHaveBeenCalled();+ });+});++describe('createMarkConvoUnreadHandler', () => {+ beforeEach(() => {+ (logger.error as jest.Mock).mockClear();+ });++ it('flags the conversation and returns the marker the server settled on', async () => {+ const markConvoUnread = jest.fn().mockResolvedValue({+ modified: true,+ lastResponseAt: new Date('2026-08-16T10:00:00.000Z'),+ lastResponseMessageId: 'reply-1',+ });+ const res = mockResponse();++ await createMarkConvoUnreadHandler({ markConvoUnread })(+ mockRequest({ conversationId: 'conv-1' }),+ res,+ );++ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({+ modified: true,+ lastResponseAt: new Date('2026-08-16T10:00:00.000Z'),+ lastResponseMessageId: 'reply-1',+ });+ expect(markConvoUnread).toHaveBeenCalledWith('user-123', 'conv-1');+ });++ it('rejects a missing conversationId without touching the database', async () => {+ const markConvoUnread = jest.fn();+ const res = mockResponse();++ await createMarkConvoUnreadHandler({ markConvoUnread })(mockRequest({}), res);++ expect(res.statusCode).toBe(400);+ expect(res.body).toEqual({ error: 'conversationId is required' });+ expect(markConvoUnread).not.toHaveBeenCalled();+ });++ it('returns 500 when the database write fails', async () => {+ const markConvoUnread = jest.fn().mockRejectedValue(new Error('db unavailable'));+ const res = mockResponse();++ await createMarkConvoUnreadHandler({ markConvoUnread })(+ mockRequest({ conversationId: 'conv-1' }),+ res,+ );++ expect(res.statusCode).toBe(500);+ expect(res.body).toBe('Error marking conversation unread');+ expect(logger.error).toHaveBeenCalled();+ });+});diff --git a/packages/api/src/conversations/read.ts b/packages/api/src/conversations/read.tsnew file mode 100644index 0000000000..44bf399293--- /dev/null+++ b/packages/api/src/conversations/read.ts@@ -0,0 +1,75 @@+import { logger } from '@librechat/data-schemas';++import type { ConversationMethods } from '@librechat/data-schemas';+import type { Response } from 'express';+import type { ServerRequest } from '~/types';++type SeenHandlerDependencies = Pick<ConversationMethods, 'markConvoSeen'>;+type UnreadHandlerDependencies = Pick<ConversationMethods, 'markConvoUnread'>;++type ReadStateArg = {+ conversationId?: string;+ lastResponseAt?: string;+};++const readArg = (req: ServerRequest): ReadStateArg =>+ (req.body as { arg?: ReadStateArg } | undefined)?.arg ?? {};++/**+ * Records that the user has caught up with a conversation's newest message.+ *+ * The catch-up itself is server-stamped, which keeps this idempotent and independent of client+ * clocks. `lastResponseAt` names the reply the client actually had on screen, so a newer one+ * persisted from another device in the meantime is not acknowledged along with it.+ */+export function createMarkConvoSeenHandler(+ deps: SeenHandlerDependencies,+): (req: ServerRequest, res: Response) => Promise<Response> {+ return async function markConvoSeenHandler(req: ServerRequest, res: Response) {+ const { conversationId, lastResponseAt } = readArg(req);++ if (!conversationId) {+ return res.status(400).json({ error: 'conversationId is required' });+ }++ const observedResponseAt = lastResponseAt != null ? new Date(lastResponseAt) : undefined;+ if (observedResponseAt && Number.isNaN(observedResponseAt.getTime())) {+ return res.status(400).json({ error: 'lastResponseAt must be a valid date' });+ }++ try {+ const result = await deps.markConvoSeen(req.user!.id, conversationId, observedResponseAt);+ return res.status(200).json(result);+ } catch (error) {+ logger.error('Error marking conversation seen', error);+ return res.status(500).send('Error marking conversation seen');+ }+ };+}++/**+ * Flags a conversation as unread again for this user.+ *+ * The server clears the catch-up and, for a conversation without a reply yet, treats the flag+ * itself as the unread marker, so no client timestamp is trusted. The resulting `lastResponseAt`+ * comes back with it, which is what the next acknowledgement has to name.+ */+export function createMarkConvoUnreadHandler(+ deps: UnreadHandlerDependencies,+): (req: ServerRequest, res: Response) => Promise<Response> {+ return async function markConvoUnreadHandler(req: ServerRequest, res: Response) {+ const { conversationId } = readArg(req);++ if (!conversationId) {+ return res.status(400).json({ error: 'conversationId is required' });+ }++ try {+ const result = await deps.markConvoUnread(req.user!.id, conversationId);+ return res.status(200).json(result);+ } catch (error) {+ logger.error('Error marking conversation unread', error);+ return res.status(500).send('Error marking conversation unread');+ }+ };+}diff --git a/packages/api/src/conversations/save.spec.ts b/packages/api/src/conversations/save.spec.tsindex 6edc25832e..e510117d17 100644--- a/packages/api/src/conversations/save.spec.ts+++ b/packages/api/src/conversations/save.spec.ts@@ -182,6 +182,39 @@ describe('seedTurnConversation', () => {});});+describe('saveTurnConversation reply stamp', () => {+ const saveReply = async (reply: { content?: unknown; text?: string }) => {+ const userId = new mongoose.Types.ObjectId().toString();+ const conversationId = randomUUID();+ const req = createRequest(userId);+ const ctx = getConversationWriteContext(req);+ const messageId = randomUUID();+ await saveTurnConversation(store, {+ ...seedFields(req, conversationId),+ context: 'save.spec reply',+ ctx,+ reply: { messageId, ...reply },+ });+ return { row: await store.getConvo(userId, conversationId), messageId };+ };++ it('stamps a reply a reader can open', async () => {+ const { row, messageId } = await saveReply({ content: [{ type: 'text', text: 'Done.' }] });++ expect(row?.lastResponseAt).toBeInstanceOf(Date);+ expect(row?.lastResponseMessageId).toBe(messageId);+ });++ /* Acknowledgement requires the stamped reply to be on screen, so a row that renders nothing+ would leave a dot that opening the conversation could never clear. */+ it('does not stamp a reply that persisted nothing to read', async () => {+ const { row } = await saveReply({ content: [], text: ' ' });++ expect(row?.lastResponseAt).toBeUndefined();+ expect(row?.lastResponseMessageId).toBeUndefined();+ });+});+describe('recoverTurnMessageReference', () => {/** The whole failure path, in order: the user-message write fails and is swallowed, the* response's write creates the row referencing only itself, the terminal retries the userdiff --git a/packages/api/src/conversations/save.ts b/packages/api/src/conversations/save.tsindex 1d85a2e118..e2bd3d6a21 100644--- a/packages/api/src/conversations/save.ts+++ b/packages/api/src/conversations/save.ts@@ -2,6 +2,8 @@ import { logger } from '@librechat/data-schemas';import { excludedKeys, isAgentsEndpoint, isEphemeralAgentId } from 'librechat-data-provider';import type { AppConfig, ConversationMethods, IConversation } from '@librechat/data-schemas';import type { TConversation } from 'librechat-data-provider';+import type { PersistedReply } from './announce';+import { isAnnounceableReply } from './announce';type SaveConvo = ConversationMethods['saveConvo'];type SaveConvoOptions = NonNullable<Parameters<SaveConvo>[2]>;@@ -44,6 +46,12 @@ export interface TurnConversationWrite extends TurnConversationFields {initialized?: boolean;/** The message this write just saved, appended to the conversation's message list. */savedMessageId?: SavedMessageId;+ /**+ * The assistant reply this write persisted, if any. Absent for the user's own turn and for a+ * reply whose message write resolved empty; whether it may raise an indicator is decided by+ * `isAnnounceableReply`, the same predicate every other persistence path asks.+ */+ reply?: PersistedReply;}export interface TurnConversationResult {@@ -135,6 +143,24 @@ async function loadExistingConversation(return deps.getConvo(write.ctx.userId, write.conversationId);}+/**+ * The reply stamp a write carries, and nothing when it carries none.+ *+ * `saveConvo` assigns the timestamp itself, past its own awaited reads and against the write, so+ * a catch-up recorded by `/seen` while one of those reads is in flight cannot outrank this reply+ * and leave it reading as already seen. A temporary chat is never announced: it has no row in the+ * lists the indicator is read from, and a row with nothing a reader can open is not either.+ */+function getReplyStamp(+ write: TurnConversationWrite,+): { stampReply: true; replyMessageId: string } | Record<string, never> {+ const { reply } = write;+ if (reply == null || !isAnnounceableReply({ ...reply, isTemporary: write.ctx.isTemporary })) {+ return {};+ }+ return { stampReply: true, replyMessageId: reply.messageId as string };+}+async function writeConversation(deps: ConversationStore,write: TurnConversationWrite,@@ -159,6 +185,7 @@ async function writeConversation(createdAtOnInsert:write.initialized !== true && existing == null ? getCreatedAtOnInsert(req) : undefined,...(appendMessageIds != null ? { appendMessageIds } : {}),+ ...getReplyStamp(write),},);if (req != null && conversation != null && 'conversationId' in conversation) {diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex 5f4adc5593..f2c3a3bfcf 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -155,6 +155,8 @@ export const updateConversation = () => `${conversationsRoot}/update`;export const archiveConversation = () => `${conversationsRoot}/archive`;export const archiveAllConversations = () => `${conversationsRoot}/archive/all`;export const pinConversation = () => `${conversationsRoot}/pin`;+export const markConversationSeen = () => `${conversationsRoot}/seen`;+export const markConversationUnread = () => `${conversationsRoot}/unread`;export const deleteConversation = () => `${conversationsRoot}`;diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.tsindex 4d0c2648e3..c6c0cbd262 100644--- a/packages/data-provider/src/config.spec.ts+++ b/packages/data-provider/src/config.spec.ts@@ -312,6 +312,7 @@ describe('excludedKeys', () => {'agentEventActorCleanup','agentEventActorSuspension','agentEventActorReconciliations',+ 'lastResponseMessageId','__v',])('excludes system field "%s"', (field) => {expect(excludedKeys.has(field)).toBe(true);diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex ab9ffab513..ad77537b1b 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -123,6 +123,10 @@ export const excludedKeys = new Set(['spec','disableParams','chatProjectId',+ 'lastResponseAt',+ 'lastResponseMessageId',+ 'lastResponseIsManual',+ 'lastSeenAt',]);export enum SettingsViews {@@ -2409,6 +2413,50 @@ export const interfaceSchema = z}),]).optional(),+ /**+ * What the reply-alert capabilities may do on this deployment. Each field gates a+ * capability rather than setting it: the preferences themselves stay per device, because+ * notification permission and audio output belong to the machine the reader sits at.+ */+ replyNotifications: z+ .object({+ /** Whether an unseen count may reach the tab title and favicon. */+ tabBadge: z.boolean().optional(),+ /** Whether readers may turn on desktop notifications for replies. */+ desktop: z.boolean().optional(),+ /** Whether readers may turn on the reply chime. */+ sound: z.boolean().optional(),+ /**+ * How many conversations one away poll looks at. A reply lifts its conversation, so the+ * newest activity is what the first page holds.+ *+ * Bounded by the conversation list's own maximum page, which the server clamps every+ * request to: advertising a wider range here would accept a number the read silently+ * truncates. Covering a deployment whose replies outpace a single page wants the+ * server-side unseen query rather than a larger page.+ */+ pollLimit: z.number().int().min(1).max(100).optional(),+ /** Milliseconds between list checks while the tab is unfocused and an away alert is on. */+ pollIntervalMs: z.number().int().min(10_000).max(600_000).optional(),+ /**+ * Milliseconds between list refreshes while the tab is focused, so a reply produced+ * elsewhere eventually shows its dot. Deliberately far slower than the away poll.+ *+ * Capped at five minutes because this refresh is what renews the unfiltered discovery+ * snapshot, and the client holds an unobserved snapshot authoritative for five minutes:+ * a slower refresh would let it lapse, dropping its unseen rows from the count until the+ * next one.+ */+ focusedRefreshMs: z.number().int().min(60_000).max(300_000).optional(),+ })+ .default({+ tabBadge: true,+ desktop: true,+ sound: true,+ pollLimit: 100,+ pollIntervalMs: 30_000,+ focusedRefreshMs: 300_000,+ }),schedules: z.union([z.boolean(),@@ -2499,6 +2547,14 @@ export const interfaceSchema = zpublic: true,snapshotFiles: true,},+ replyNotifications: {+ tabBadge: true,+ desktop: true,+ sound: true,+ pollLimit: 100,+ pollIntervalMs: 30_000,+ focusedRefreshMs: 300_000,+ },// `schedules` is deliberately ABSENT from this default. It is experimental and// default-off in v1, and zod applies this whole object when `interface` is omitted// from librechat.yaml — including it would silently enable the feature (and permit@@ -2507,6 +2563,7 @@ export const interfaceSchema = z});export type TInterfaceConfig = z.infer<typeof interfaceSchema>;+export type TReplyNotificationsConfig = TInterfaceConfig['replyNotifications'];export type TBalanceConfig = z.infer<typeof balanceSchema>;export type TTransactionsConfig = z.infer<typeof transactionsSchema>;diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex df56867589..e143943468 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -1054,6 +1054,18 @@ export function pinConversation(return request.post(endpoints.pinConversation(), { arg: payload });}+export function markConversationSeen(+ payload: t.TMarkConversationSeenRequest,+): Promise<t.TMarkConversationSeenResponse> {+ return request.post(endpoints.markConversationSeen(), { arg: payload });+}++export function markConversationUnread(+ payload: t.TMarkConversationUnreadRequest,+): Promise<t.TMarkConversationUnreadResponse> {+ return request.post(endpoints.markConversationUnread(), { arg: payload });+}+export function genTitle(payload: m.TGenTitleRequest): Promise<m.TGenTitleResponse> {return request.get(endpoints.genTitle(payload.conversationId));}diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex 5e1e728807..985251ef53 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -169,4 +169,6 @@ export enum MutationKeys {updateCodeEnvironmentSettings = 'updateCodeEnvironmentSettings',deleteCodeEnvironment = 'deleteCodeEnvironment',moveConversationCodeEnvironment = 'moveConversationCodeEnvironment',+ convoSeen = 'convoSeen',+ convoUnread = 'convoUnread',}diff --git a/packages/data-provider/src/schemas.spec.ts b/packages/data-provider/src/schemas.spec.tsindex 874f752220..0acd30f303 100644--- a/packages/data-provider/src/schemas.spec.ts+++ b/packages/data-provider/src/schemas.spec.ts@@ -13,6 +13,7 @@ import {eReasoningContextSchema,subagentThreadLineageSchema,getGoogleThinkingBudgetBounds,+ tPresetSchema,} from './schemas';describe('anthropicSettings', () => {@@ -760,3 +761,35 @@ describe('tMessageSchema user-submitted provenance', () => {expect(() => tMessageSchema.parse({ ...message, userSubmittedMessageFieldPaths })).toThrow();});});++describe('tPresetSchema', () => {+ it('strips all unseen-reply state from preset payloads', () => {+ /* Saving a preset off a live conversation captures read-state fields; none may stamp stale+ state back onto every conversation it is applied to. */+ const parsed = tPresetSchema.parse({+ conversationId: null,+ endpoint: 'openAI',+ lastResponseAt: '2026-08-16T10:00:00.000Z',+ lastResponseMessageId: 'reply-1',+ lastResponseIsManual: true,+ lastSeenAt: '2026-08-16T09:00:00.000Z',+ });++ expect(parsed).not.toHaveProperty('lastResponseAt');+ expect(parsed).not.toHaveProperty('lastResponseMessageId');+ expect(parsed).not.toHaveProperty('lastResponseIsManual');+ expect(parsed).not.toHaveProperty('lastSeenAt');+ });++ it('keeps stripping the runtime timestamps presets never carry', () => {+ const parsed = tPresetSchema.parse({+ conversationId: null,+ endpoint: 'openAI',+ createdAt: '2026-08-16T10:00:00.000Z',+ updatedAt: '2026-08-16T10:00:00.000Z',+ });++ expect(parsed).not.toHaveProperty('createdAt');+ expect(parsed).not.toHaveProperty('updatedAt');+ });+});diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.tsindex ea8b1c0015..d6d6ea7017 100644--- a/packages/data-provider/src/schemas.ts+++ b/packages/data-provider/src/schemas.ts@@ -1179,6 +1179,14 @@ export const tConversationSchema = z.object({chatProjectId: z.string().nullable().optional(),createdAt: z.string(),updatedAt: z.string(),+ /** Set only when an assistant message is persisted; drives the unseen-reply indicator. */+ lastResponseAt: z.string().optional(),+ /** Durable messageId of the assistant reply named by `lastResponseAt`. */+ lastResponseMessageId: z.string().optional(),+ /** True only while `lastResponseAt` is the synthetic marker from "mark unread". */+ lastResponseIsManual: z.boolean().optional(),+ /** Set when the user has the newest message on screen; compared against `lastResponseAt`. */+ lastSeenAt: z.string().optional(),/* Files */resendFiles: z.boolean().optional(),file_ids: z.array(z.string()).optional(),@@ -1243,6 +1251,12 @@ export const tPresetSchema = tConversationSchemacreatedAt: true,updatedAt: true,title: true,+ /* Runtime unseen-reply state must not ride into presets: applying one would stamp+ stale timestamps back onto conversations. */+ lastResponseAt: true,+ lastResponseMessageId: true,+ lastResponseIsManual: true,+ lastSeenAt: true,}).merge(z.object({diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.tsindex 2f3cba38ab..c5ee47d802 100644--- a/packages/data-provider/src/types.ts+++ b/packages/data-provider/src/types.ts@@ -475,6 +475,30 @@ export type TPinConversationRequest = {export type TPinConversationResponse = TConversation;+export type TMarkConversationSeenRequest = {+ conversationId: string;+ /** The reply the client had on screen; the server acknowledges no newer one. */+ lastResponseAt?: string;+};++export type TMarkConversationSeenResponse = {+ modified: boolean;+};++export type TMarkConversationUnreadRequest = {+ conversationId: string;+};++export type TMarkConversationUnreadResponse = {+ modified: boolean;+ /** The stamp the server settled on, so the client never has to invent its own marker. */+ lastResponseAt?: string;+ /** Durable messageId paired with a real reply stamp; absent for synthetic markers. */+ lastResponseMessageId?: string;+ /** True only when the settled stamp is the synthetic mark-unread marker. */+ lastResponseIsManual?: boolean;+};+export type TSharedMessagesResponse = Omit<TSharedLink, 'messages'> & {messages: TMessage[];langfuseSessionUrl?: string;diff --git a/packages/data-provider/src/types/queries.ts b/packages/data-provider/src/types/queries.tsindex 73bbf447d6..20d1911622 100644--- a/packages/data-provider/src/types/queries.ts+++ b/packages/data-provider/src/types/queries.ts@@ -37,6 +37,10 @@ export type MinimalConversation = Pick<| 'user'| 'chatProjectId'| 'pinned'+ | 'lastResponseAt'+ | 'lastResponseMessageId'+ | 'lastResponseIsManual'+ | 'lastSeenAt'>;export type ConversationListResponse = {diff --git a/packages/data-schemas/src/app/interface.ts b/packages/data-schemas/src/app/interface.tsindex db451f1de1..e0dee79d25 100644--- a/packages/data-schemas/src/app/interface.ts+++ b/packages/data-schemas/src/app/interface.ts@@ -71,6 +71,13 @@ export async function loadDefaultInterface({skills: interfaceConfig?.skills,sharedLinks: interfaceConfig?.sharedLinks,schedules: interfaceConfig?.schedules,++ /* Merged per field rather than taken whole, so an operator who sets one capability keeps+ the defaults for the rest instead of silently turning the others off. */+ replyNotifications: {+ ...defaults.replyNotifications,+ ...interfaceConfig?.replyNotifications,+ },});return loadedInterface;diff --git a/packages/data-schemas/src/methods/chatProject.spec.ts b/packages/data-schemas/src/methods/chatProject.spec.tsindex 78ff257dea..818d5aea28 100644--- a/packages/data-schemas/src/methods/chatProject.spec.ts+++ b/packages/data-schemas/src/methods/chatProject.spec.ts@@ -436,6 +436,48 @@ describe('ChatProject methods', () => {expect(persisted?.lastConversationId).toBe('new-convo');});+ it.each([false, true])(+ 'keeps newer project activity when an older update arrives last (increment: %s)',+ async (incrementCount) => {+ const project = await methods.createChatProject(user, { name: 'Concurrent Replies' });+ const chatProjectId = project._id!.toString();+ const olderAt = new Date('2026-04-01T00:00:00.000Z');+ const newerAt = new Date('2026-04-02T00:00:00.000Z');+ await Conversation.create([+ {+ user,+ chatProjectId,+ endpoint: 'openAI',+ conversationId: 'older-reply',+ createdAt: olderAt,+ updatedAt: olderAt,+ },+ {+ user,+ chatProjectId,+ endpoint: 'openAI',+ conversationId: 'newer-reply',+ createdAt: newerAt,+ updatedAt: newerAt,+ },+ ]);+ await methods.refreshChatProjectStats(user, chatProjectId);++ await updateChatProjectLastConversationForUser(+ mongoose,+ user,+ chatProjectId,+ { conversationId: 'older-reply', createdAt: olderAt, updatedAt: olderAt },+ incrementCount,+ );++ const persisted = await methods.getChatProject(user, chatProjectId);+ expect(persisted?.lastConversationId).toBe('newer-reply');+ expect(persisted?.lastConversationAt).toEqual(newerAt);+ expect(persisted?.conversationCount).toBe(2);+ },+ );+it('enforces one project per chat when moving conversations', async () => {const firstProject = await methods.createChatProject(user, { name: 'First' });const secondProject = await methods.createChatProject(user, { name: 'Second' });diff --git a/packages/data-schemas/src/methods/chatProject.ts b/packages/data-schemas/src/methods/chatProject.tsindex aa77df2ad9..1e926b5d58 100644--- a/packages/data-schemas/src/methods/chatProject.ts+++ b/packages/data-schemas/src/methods/chatProject.ts@@ -284,21 +284,26 @@ export async function updateChatProjectLastConversationForUser(};const ChatProject = mongoose.models.ChatProject as Model<IChatProjectDocument>;const projectFilter = { _id: new mongoose.Types.ObjectId(projectId), user };+ const activityFilter = {+ ...projectFilter,+ $or: [{ lastConversationAt: null }, { lastConversationAt: { $lte: lastConversationAt } }],+ };if (!incrementCount) {- await ChatProject.updateOne(projectFilter, { $set: lastConversationFields });+ await ChatProject.updateOne(activityFilter, { $set: lastConversationFields });} else {/**- * Skip `$inc` when a concurrent refresh already recorded this conversation as- * `lastConversationId`. The conversation is visible to countDocuments as soon- * as it is persisted, so a later increment would double-count it.+ * A refresh may already have counted this conversation, or a newer reply may own the+ * activity pointer. Recount after a lost conditional update rather than double-counting+ * membership or walking the pointer backwards.*/const incremented = await ChatProject.updateOne(- { ...projectFilter, lastConversationId: { $ne: conversation.conversationId } },+ { ...activityFilter, lastConversationId: { $ne: conversation.conversationId } },{ $set: lastConversationFields, $inc: { conversationCount: 1 } },);if ((incremented.matchedCount ?? 0) === 0) {- await ChatProject.updateOne(projectFilter, { $set: lastConversationFields });+ await refreshChatProjectStatsForUser(mongoose, user, projectId);+ return;}}diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.tsindex a465c769dd..a75eafba1e 100644--- a/packages/data-schemas/src/methods/conversation.spec.ts+++ b/packages/data-schemas/src/methods/conversation.spec.ts@@ -208,6 +208,9 @@ describe('Conversation Operations', () => {checkpointNs: 'event-actor/other',checkpointId: 'other',},+ lastResponseAt: new Date('2026-08-16T10:00:00.000Z'),+ lastResponseMessageId: 'forged-reply',+ lastResponseIsManual: true,};await saveConvo(mockCtx, { ...mockConversationData, ...forged });await methods.bulkSaveConvos([{ ...mockConversationData, user: mockCtx.userId, ...forged }]);@@ -280,6 +283,125 @@ describe('Conversation Operations', () => {);});+ it('does not let metadata forge a reply timestamp or identity', async () => {+ const replyAt = new Date('2026-08-16T10:05:00.000Z');+ await saveConvo(+ mockCtx,+ { ...mockConversationData },+ { stampReply: true, replyMessageId: 'reply-newer' },+ );+ await saveConvo(mockCtx, {+ ...mockConversationData,+ lastResponseAt: new Date('2026-08-16T11:00:00.000Z'),+ lastResponseMessageId: 'forged',+ });++ const convo = await Conversation.findOne<IConversation>({+ conversationId: mockConversationData.conversationId,+ });+ expect(convo?.lastResponseAt?.getTime()).toBeGreaterThanOrEqual(replyAt.getTime());+ expect(convo?.lastResponseMessageId).toBe('reply-newer');+ });++ it('stamps a first reply through the monotonic path', async () => {+ await saveConvo(+ mockCtx,+ { ...mockConversationData },+ { stampReply: true, replyMessageId: 'reply-first' },+ );++ const convo = await Conversation.findOne<IConversation>({+ conversationId: mockConversationData.conversationId,+ });+ expect(convo?.lastResponseAt).toBeInstanceOf(Date);+ expect(convo?.lastResponseMessageId).toBe('reply-first');+ });++ it('stamps the reply at write time and clears the catch-up it outranks', async () => {+ /* `/seen` can match the previous reply while this save is in flight and record a+ catch-up later than any timestamp the caller could hold. The stamp and the clear are+ one conditional write, so the reply this save persists is never born seen. */+ const before = new Date();+ await saveConvo(mockCtx, { ...mockConversationData });+ await Conversation.updateOne(+ { conversationId: mockConversationData.conversationId },+ { $set: { lastSeenAt: new Date(Date.now() + 5_000) } },+ );++ await saveConvo(+ mockCtx,+ { ...mockConversationData },+ { stampReply: true, replyMessageId: 'reply-write-time' },+ );++ const convo = await Conversation.findOne<IConversation>({+ conversationId: mockConversationData.conversationId,+ });+ expect(convo?.lastResponseAt).toBeInstanceOf(Date);+ expect(convo?.lastResponseAt?.getTime()).toBeGreaterThanOrEqual(before.getTime());+ expect(convo?.lastSeenAt == null).toBe(true);+ });++ it('returns the durable conversation when the optional reply stamp fails', async () => {+ const find = jest.spyOn(Conversation, 'findOne').mockImplementationOnce(() => {+ throw new Error('reply stamp read unavailable');+ });+ let result;+ try {+ result = await saveConvo(mockCtx, mockConversationData, {+ stampReply: true,+ replyMessageId: 'reply-failed-read',+ });+ } finally {+ find.mockRestore();+ }++ expect(result).toMatchObject({+ conversationId: mockConversationData.conversationId,+ title: mockConversationData.title,+ });+ const saved = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(saved?.title).toBe(mockConversationData.title);+ expect(saved?.lastResponseAt).toBeUndefined();+ });++ it('advances past a future stamp when a save host clock is behind', async () => {+ await saveConvo(+ mockCtx,+ { ...mockConversationData },+ { stampReply: true, replyMessageId: 'reply-before-future' },+ );+ const newer = new Date(Date.now() + 60_000);+ const seenAt = new Date(Date.now() + 90_000);+ await Conversation.updateOne(+ { conversationId: mockConversationData.conversationId },+ { $set: { lastResponseAt: newer, lastSeenAt: seenAt } },+ );++ await saveConvo(+ mockCtx,+ { ...mockConversationData },+ { stampReply: true, replyMessageId: 'reply-after-future' },+ );++ const convo = await Conversation.findOne<IConversation>({+ conversationId: mockConversationData.conversationId,+ });+ expect(convo?.lastResponseAt?.getTime()).toBeGreaterThan(newer.getTime());+ expect(convo?.lastSeenAt).toBeUndefined();+ });++ it('leaves the reply stamp alone for a save that does not carry one', async () => {+ await saveConvo(mockCtx, { ...mockConversationData });++ const convo = await Conversation.findOne<IConversation>({+ conversationId: mockConversationData.conversationId,+ });+ expect(convo?.lastResponseAt).toBeUndefined();+ });+it('should handle newConversationId when provided', async () => {const newConversationId = uuidv4();const result = await saveConvo(mockCtx, {@@ -2548,6 +2670,555 @@ describe('Conversation Operations', () => {});});+ describe('markConvoSeen', () => {+ const markConvoSeen = (...args: Parameters<ConversationMethods['markConvoSeen']>) =>+ methods.markConvoSeen(...args);++ it('records lastSeenAt for the owning user', async () => {+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: new Date(),+ });++ const result = await markConvoSeen('user123', mockConversationData.conversationId);+ expect(result.modified).toBe(true);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastSeenAt).toBeInstanceOf(Date);+ });++ it('acknowledges only the reply the client observed', async () => {+ /* Another device persists a newer reply while the seen write is in flight; stamping+ "now" would clear an indicator for a message nobody has read. */+ const observed = new Date('2026-08-16T10:00:00.000Z');+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: new Date('2026-08-16T10:05:00.000Z'),+ });++ const result = await markConvoSeen('user123', mockConversationData.conversationId, observed);+ expect(result.modified).toBe(false);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastSeenAt).toBeUndefined();+ });++ it('never writes a catch-up older than the reply it acknowledges', async () => {+ /* Across replicas the node handling this can be behind the one that stamped the reply;+ a catch-up earlier than that reply would read as unseen again on the next refetch. */+ const observed = new Date(Date.now() + 60_000);+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: observed,+ });++ const result = await markConvoSeen('user123', mockConversationData.conversationId, observed);+ expect(result.modified).toBe(true);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastSeenAt?.getTime()).toBeGreaterThanOrEqual(observed.getTime());+ });++ it('records the catch-up when the observed reply is still the newest', async () => {+ const observed = new Date('2026-08-16T10:00:00.000Z');+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: observed,+ });++ const result = await markConvoSeen('user123', mockConversationData.conversationId, observed);+ expect(result.modified).toBe(true);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastSeenAt).toBeInstanceOf(Date);+ });++ it('reports success when a retried acknowledgement changes nothing', async () => {+ /* A future-dated observed reply is stored verbatim, so a retry after a lost response+ writes the identical value: zero documents modified, but the database is already+ caught up. Reporting failure would make the client roll back to unseen. */+ const observed = new Date(Date.now() + 60_000);+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: observed,+ });++ const first = await markConvoSeen('user123', mockConversationData.conversationId, observed);+ expect(first.modified).toBe(true);++ const retry = await markConvoSeen('user123', mockConversationData.conversationId, observed);+ expect(retry.modified).toBe(true);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastSeenAt?.getTime()).toBe(observed.getTime());+ });++ it('leaves updatedAt alone so reading a conversation does not reorder the sidebar', async () => {+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: new Date(),+ });++ const before = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();++ await markConvoSeen('user123', mockConversationData.conversationId);++ const after = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();++ expect(after?.updatedAt?.toISOString()).toBe(before?.updatedAt?.toISOString());+ });++ it('does not touch another user’s conversation', async () => {+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ });++ const result = await markConvoSeen('someone-else', mockConversationData.conversationId);+ expect(result.modified).toBe(false);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastSeenAt).toBeUndefined();+ });+ });++ describe('stampConvoLastResponse', () => {+ const stampConvoLastResponse = (+ ...args: Parameters<ConversationMethods['stampConvoLastResponse']>+ ) => methods.stampConvoLastResponse(...args);++ it('carries the project activity forward with the conversation', async () => {+ /* The workspace sorts on `ChatProject.lastConversationAt`, so lifting the conversation+ without it would leave the project sitting at its old position. */+ const ChatProject = mongoose.models.ChatProject;+ const project = await ChatProject.create({+ name: 'Stamped',+ user: 'user123',+ lastConversationAt: new Date('2026-08-16T09:00:00.000Z'),+ });+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ chatProjectId: project._id.toString(),+ createdAt: new Date('2026-08-16T09:00:00.000Z'),+ updatedAt: new Date('2026-08-16T09:00:00.000Z'),+ });++ await stampConvoLastResponse('user123', mockConversationData.conversationId, 'reply-project');++ const refreshed = await ChatProject.findById(project._id).lean<{+ lastConversationAt?: Date;+ }>();+ expect(refreshed?.lastConversationAt).toBeDefined();+ expect(new Date(refreshed?.lastConversationAt as Date).getTime()).toBeGreaterThan(+ new Date('2026-08-16T09:00:00.000Z').getTime(),+ );+ });++ it('returns the durable reply stamp when project maintenance fails', async () => {+ const project = await ChatProject.create({+ name: 'Unavailable project update',+ user: 'user123',+ });+ await Conversation.create({+ ...mockConversationData,+ user: 'user123',+ chatProjectId: project._id.toString(),+ });+ const update = jest.spyOn(ChatProject, 'updateOne').mockImplementationOnce(() => {+ throw new Error('project update unavailable');+ });+ try {+ const settled = await stampConvoLastResponse(+ 'user123',+ mockConversationData.conversationId,+ 'reply-project-failure',+ );+ const saved = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(settled?.lastResponseAt).toBeInstanceOf(Date);+ expect(settled?.lastResponseAt).toEqual(saved?.lastResponseAt);+ expect(settled?.updatedAt).toEqual(saved?.updatedAt);+ } finally {+ update.mockRestore();+ }+ });++ it('keeps a saved reply stamp when project maintenance fails', async () => {+ /* The caller hands this document to the client as the turn's conversation. Answering a+ durable save with an error would drop the stamp from the terminal event, and the next+ list refresh would present a reply the user watched arrive as unread. */+ const project = await ChatProject.create({+ name: 'Unavailable project stats',+ user: 'user123',+ });+ await Conversation.create({+ ...mockConversationData,+ user: 'user123',+ chatProjectId: project._id.toString(),+ });+ const update = jest.spyOn(ChatProject, 'updateOne').mockImplementation(() => {+ throw new Error('project update unavailable');+ });+ try {+ const saved = await saveConvo(+ mockCtx,+ { ...mockConversationData, chatProjectId: project._id.toString() },+ { stampReply: true, replyMessageId: 'reply-project-tail' },+ );+ expect(saved).not.toMatchObject({ message: 'Error saving conversation' });+ expect((saved as IConversation).lastResponseMessageId).toBe('reply-project-tail');+ const stored = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(stored?.lastResponseMessageId).toBe('reply-project-tail');+ } finally {+ update.mockRestore();+ }+ });++ it('stamps lastResponseAt and lifts the conversation like any other reply', async () => {+ /* The away poll pages by `updatedAt`, so a reply that left the order alone would be+ invisible on any conversation that had fallen past the first page. BaseClient's own+ reply path moves it too. */+ const createdAt = new Date('2026-08-16T09:00:00.000Z');+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ createdAt,+ updatedAt: createdAt,+ });++ const settled = await stampConvoLastResponse(+ 'user123',+ mockConversationData.conversationId,+ 'reply-latest',+ );++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(settled?.lastResponseAt).toBeInstanceOf(Date);+ expect(settled?.lastResponseMessageId).toBe('reply-latest');+ expect(settled?.updatedAt).toBeInstanceOf(Date);+ expect(settled?.lastResponseAt?.getTime()).toBe(convo?.lastResponseAt?.getTime());+ expect(settled?.updatedAt?.getTime()).toBe(convo?.updatedAt?.getTime());+ expect(convo?.lastResponseAt).toBeInstanceOf(Date);+ expect(convo?.lastResponseAt?.getTime()).toBeGreaterThanOrEqual(createdAt.getTime());+ expect(convo?.updatedAt?.getTime()).toBeGreaterThan(createdAt.getTime());+ });++ it('makes a new reply the latest activity even after a future-dated metadata update', async () => {+ const metadataAt = new Date(Date.now() + 60_000);+ await Conversation.create({+ ...mockConversationData,+ user: 'user123',+ });+ await Conversation.updateOne(+ { conversationId: mockConversationData.conversationId },+ { $set: { updatedAt: metadataAt } },+ { timestamps: false },+ );++ const settled = await stampConvoLastResponse(+ 'user123',+ mockConversationData.conversationId,+ 'reply-future',+ );++ expect(settled?.lastResponseAt?.getTime()).toBeGreaterThan(metadataAt.getTime());+ expect(settled?.updatedAt).toEqual(settled?.lastResponseAt);+ });++ it('clears a catch-up and manual marker when the real reply advances the stamp', async () => {+ /* `/seen` can accept the previous reply while this one is being persisted, and a+ replica's clock can date that catch-up ahead: the stamp and the clear are one write. */+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: new Date('2026-08-16T09:00:00.000Z'),+ lastResponseIsManual: true,+ lastSeenAt: new Date(Date.now() + 5_000),+ });++ await stampConvoLastResponse(+ 'user123',+ mockConversationData.conversationId,+ 'reply-manual-clear',+ );++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastResponseAt).toBeInstanceOf(Date);+ expect(convo?.lastResponseIsManual).toBeUndefined();+ expect(convo?.lastSeenAt == null).toBe(true);+ });+ it('advances past a future reply stamp when this host clock is behind', async () => {+ const newer = new Date(Date.now() + 60_000);+ const seenAt = new Date(Date.now() + 90_000);+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: newer,+ lastSeenAt: seenAt,+ });++ await stampConvoLastResponse('user123', mockConversationData.conversationId, 'reply-future');++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastResponseAt?.getTime()).toBeGreaterThan(newer.getTime());+ expect(convo?.lastSeenAt).toBeUndefined();+ });++ it('does not stamp another user’s conversation', async () => {+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ });++ const settled = await stampConvoLastResponse(+ 'someone-else',+ mockConversationData.conversationId,+ 'reply-other-user',+ );++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(settled).toBeNull();+ expect(convo?.lastResponseAt).toBeUndefined();+ });++ it('does not expose a reply stamp for a stored temporary conversation', async () => {+ const original = await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ isTemporary: true,+ });++ const settled = await stampConvoLastResponse(+ 'user123',+ original.conversationId,+ 'reply-temporary',+ );+ const current = await Conversation.findById(original._id).lean<IConversation>();++ expect(settled).toBeNull();+ expect(current?.lastResponseAt).toBeUndefined();+ expect(current?.updatedAt).toEqual(original.updatedAt);+ });+ });++ describe('markConvoUnread', () => {+ const markConvoUnread = (...args: Parameters<ConversationMethods['markConvoUnread']>) =>+ methods.markConvoUnread(...args);++ it('clears the catch-up on a read conversation, restoring the unread state', async () => {+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: new Date('2026-08-16T10:00:00.000Z'),+ lastSeenAt: new Date('2026-08-16T11:00:00.000Z'),+ });++ const result = await markConvoUnread('user123', mockConversationData.conversationId);+ expect(result.modified).toBe(true);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastSeenAt).toBeUndefined();+ expect(convo?.lastResponseAt?.toISOString()).toBe('2026-08-16T10:00:00.000Z');+ expect(convo?.lastResponseIsManual).toBeUndefined();+ });++ it('returns the stamp it settled on so the client never invents one', async () => {+ /* The optimistic marker the client guesses is necessarily earlier than the server's;+ sending that guess to /seen would miss the observed-reply filter. */+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ });+ const result = await markConvoUnread('user123', mockConversationData.conversationId);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(result.lastResponseAt?.toISOString()).toBe(convo?.lastResponseAt?.toISOString());+ expect(result.lastResponseMessageId).toBeUndefined();+ expect(result.lastResponseIsManual).toBe(true);+ });++ it('reports nothing modified for a conversation the user does not own', async () => {+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'someone-else',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: new Date('2026-08-16T10:00:00.000Z'),+ });++ const result = await markConvoUnread('user123', mockConversationData.conversationId);+ expect(result.modified).toBe(false);+ });++ it('keeps the existing reply stamp rather than restamping it', async () => {+ const responded = new Date('2026-08-16T10:00:00.000Z');+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: responded,+ lastResponseMessageId: 'reply-existing',+ });++ const result = await markConvoUnread('user123', mockConversationData.conversationId);++ expect(result.lastResponseAt?.toISOString()).toBe(responded.toISOString());+ expect(result.lastResponseMessageId).toBe('reply-existing');+ expect(result.lastResponseIsManual).toBe(false);+ });+ it('marks a never-replied conversation with a monotonic manual marker so the dot lights', async () => {+ const created = await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ });++ await markConvoUnread('user123', mockConversationData.conversationId);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastResponseAt?.getTime()).toBeGreaterThanOrEqual(+ created.updatedAt?.getTime() ?? 0,+ );+ expect(convo?.lastResponseIsManual).toBe(true);+ expect(convo?.lastSeenAt).toBeUndefined();+ });++ it('leaves updatedAt alone so flagging does not reorder the sidebar', async () => {+ const createdAt = new Date('2026-08-16T09:00:00.000Z');+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: new Date('2026-08-16T10:00:00.000Z'),+ lastSeenAt: new Date('2026-08-16T11:00:00.000Z'),+ createdAt,+ updatedAt: createdAt,+ });++ await markConvoUnread('user123', mockConversationData.conversationId);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.updatedAt?.toISOString()).toBe(createdAt.toISOString());+ });++ it('does not touch another user’s conversation', async () => {+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt: new Date('2026-08-16T10:00:00.000Z'),+ lastSeenAt: new Date('2026-08-16T11:00:00.000Z'),+ });++ const result = await markConvoUnread('someone-else', mockConversationData.conversationId);+ expect(result.modified).toBe(false);++ const convo = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ }).lean<IConversation>();+ expect(convo?.lastSeenAt).toBeInstanceOf(Date);+ });+ });+ describe('unseen-reply fields', () => {+ it('returns lastResponseAt, manual marker, and lastSeenAt from the cursor listing', async () => {+ const lastResponseAt = new Date('2026-08-16T10:00:00.000Z');+ const lastSeenAt = new Date('2026-08-16T09:00:00.000Z');+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt,+ lastResponseMessageId: 'reply-listed',+ lastResponseIsManual: true,+ lastSeenAt,+ });++ const { conversations } = await getConvosByCursor('user123');+ expect(conversations).toHaveLength(1);+ expect(conversations[0].lastResponseAt?.toISOString()).toBe(lastResponseAt.toISOString());+ expect(conversations[0].lastResponseMessageId).toBe('reply-listed');+ expect(conversations[0].lastResponseIsManual).toBe(true);+ expect(conversations[0].lastSeenAt?.toISOString()).toBe(lastSeenAt.toISOString());+ });++ it('keeps them through a title-only saveConvo, whose partial $set leaves absent fields alone', async () => {+ /* saveConvo never $unsets fields it is not given; the wipe threat lives in BaseClient's+ unsetFields loop, which excludedKeys guards (covered in the api BaseClient spec). */+ const lastResponseAt = new Date('2026-08-16T10:00:00.000Z');+ await Conversation.create({+ conversationId: mockConversationData.conversationId,+ user: 'user123',+ endpoint: EModelEndpoint.openAI,+ lastResponseAt,+ });++ await saveConvo(mockCtx, {+ conversationId: mockConversationData.conversationId,+ title: 'Generated title',+ });++ const convo = await getConvo('user123', mockConversationData.conversationId);+ expect(convo?.title).toBe('Generated title');+ expect(convo?.lastResponseAt?.toISOString()).toBe(lastResponseAt.toISOString());+ });+ });+describe('getConvoFiles', () => {it('should return conversation files', async () => {const files = ['file1', 'file2'];diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.tsindex 70139b1a9a..e527a0b134 100644--- a/packages/data-schemas/src/methods/conversation.ts+++ b/packages/data-schemas/src/methods/conversation.ts@@ -73,6 +73,11 @@ const MEILI_SEARCH_LIMIT = 1000;/** Ceiling for a single conversation page; the sidebar's largest request is 100. */const MAX_CONVO_PAGE_SIZE = 100;const DEFAULT_CONVO_PAGE_SIZE = 25;+const nextMonotonicStamp = (previous?: Date): Date => {+ const previousMs = previous?.getTime() ?? 0;+ return new Date(Math.max(Date.now(), Number.isFinite(previousMs) ? previousMs + 1 : 0));+};+const escapeMeiliFilterValue = (value: string): string =>value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');@@ -278,7 +283,12 @@ export interface ConversationMethods {/** `_id`s of messages this save just wrote. When present, they are appended with* `$addToSet` and the O(n) read-and-rewrite of the `messages` array is skipped;* every save without this option still rebuilds the array from the database. */- appendMessageIds?: Types.ObjectId[];+ /** Casts plain string ids, so callers outside this package need not name the id type. */+ appendMessageIds?: Array<Types.ObjectId | string>;+ /** Advance the reply version and clear the catch-up after persisting an assistant reply. */+ stampReply?: boolean;+ /** Durable messageId paired atomically with a reply stamp. */+ replyMessageId?: string;},): Promise<IConversation | { message: string } | null>;setConvoPinned(@@ -528,6 +538,25 @@ export interface ConversationMethods {conversationId: string,): Promise<Pick<IConversation, 'expiredAt' | 'isTemporary'> | null>;getConvoTitle(user: string, conversationId: string): Promise<string | null>;+ markConvoSeen(+ user: string,+ conversationId: string,+ observedResponseAt?: Date,+ ): Promise<{ modified: boolean }>;+ markConvoUnread(+ user: string,+ conversationId: string,+ ): Promise<{+ modified: boolean;+ lastResponseAt?: Date;+ lastResponseMessageId?: string;+ lastResponseIsManual?: boolean;+ }>;+ stampConvoLastResponse(+ user: string,+ conversationId: string,+ responseMessageId: string,+ ): Promise<{ lastResponseAt: Date; lastResponseMessageId: string; updatedAt?: Date } | null>;deleteConvos(user: string,filter: FilterQuery<IConversation>,@@ -562,6 +591,56 @@ export function createConversationMethods(): ConversationMethods {let legacyReceiptExpiryCursor: Types.ObjectId | undefined;+ /**+ * Stamps a real assistant reply with a strictly increasing server value.+ *+ * The read and write are a classic compare-and-set pair so this remains compatible with+ * DocumentDB: concurrent writers that read the same value retry against the winner and use+ * `max(now, previous + 1ms, updatedAt + 1ms)`. Advancing both versions makes the reply itself+ * distinguishable from a metadata-only promotion. Only a successful write supplies a stamp.+ */+ async function stampReplyWithCas(+ Conversation: Model<IConversation>,+ filter: FilterQuery<IConversation>,+ responseMessageId: string,+ projection?: Record<string, 0 | 1>,+ ): Promise<{ stamp: Date; conversation: Partial<IConversation> } | null> {+ const replyFilter = { ...filter, isTemporary: { $ne: true } };+ for (;;) {+ const current = await Conversation.findOne(replyFilter)+ .select({ lastResponseAt: 1, updatedAt: 1 })+ .lean<Pick<IConversation, 'lastResponseAt' | 'updatedAt'> | null>();+ if (!current) {+ return null;+ }+ const previous = current.lastResponseAt;+ const latestActivity =+ current.updatedAt && (!previous || current.updatedAt > previous)+ ? current.updatedAt+ : previous;+ const stamp = nextMonotonicStamp(latestActivity);+ const casFilter: FilterQuery<IConversation> =+ previous == null+ ? {+ ...replyFilter,+ updatedAt: current.updatedAt ?? null,+ $or: [{ lastResponseAt: null }, { lastResponseAt: { $exists: false } }],+ }+ : { ...replyFilter, lastResponseAt: previous, updatedAt: current.updatedAt ?? null };+ const stamped = await Conversation.findOneAndUpdate(+ casFilter,+ {+ $set: { lastResponseAt: stamp, lastResponseMessageId: responseMessageId },+ $unset: { lastSeenAt: '', lastResponseIsManual: '' },+ $max: { updatedAt: stamp },+ },+ { new: true, projection, timestamps: false },+ ).lean<Partial<IConversation> | null>();+ if (stamped) {+ return { stamp, conversation: stamped };+ }+ }+ }function getMessageMethods() {if (!deps) {throw new Error('Message methods not injected into conversation methods');@@ -2216,7 +2295,12 @@ export function createConversationMethods(createdAtOnInsert?: Date;preserveUpdatedAt?: boolean;initialAgentId?: string | null;- appendMessageIds?: Types.ObjectId[];+ /** Casts plain string ids, so callers outside this package need not name the id type. */+ appendMessageIds?: Array<Types.ObjectId | string>;+ /** Stamp `lastResponseAt` at write time: this save carries a persisted assistant reply. */+ stampReply?: boolean;+ /** Durable messageId paired atomically with a reply stamp. */+ replyMessageId?: string;},) {try {@@ -2231,6 +2315,11 @@ export function createConversationMethods(const update: Record<string, unknown> = { ...convo, user: userId };delete update.isTemporary;delete update.expiredAt;+ /* Read-state fields are server-owned. A stale marker must never be reintroduced by a+ * metadata save after a real reply cleared it. */+ delete update.lastResponseIsManual;+ delete update.lastResponseAt;+ delete update.lastResponseMessageId;delete update.initial_agent_id;/** Ordinary saves may seed a decision, but only an explicit move may replace it. */const decisionOnInsert = {@@ -2249,6 +2338,9 @@ export function createConversationMethods(delete update.messages;}const unsetFields: Record<string, number> = { ...(metadata?.unsetFields ?? {}) };+ delete unsetFields.lastResponseIsManual;+ delete unsetFields.lastResponseMessageId;+ delete unsetFields.lastResponseAt;delete unsetFields.initial_agent_id;delete unsetFields.codeEnvironmentRevision;delete unsetFields.codeEnvironmentMode;@@ -2373,8 +2465,20 @@ export function createConversationMethods(if (appendMessageIds != null && appendMessageIds.length > 0) {operation.$addToSet = { messages: { $each: appendMessageIds } };}+ /* Two responses can persist concurrently, and the older one can reach the write last.+ * `$max` keeps whichever stamp is later without a pipeline update, which the+ * DocumentDB targets rule out. */+ if (setFields.lastResponseAt instanceof Date) {+ const { lastResponseAt, ...withoutReplyStamp } = setFields;+ operation.$set = withoutReplyStamp;+ operation.$max = { lastResponseAt };+ operation.$unset = { lastResponseIsManual: '' };+ }if (Object.keys(unsetFields).length > 0) {- operation.$unset = unsetFields;+ operation.$unset = {+ ...(operation.$unset as Record<string, unknown> | undefined),+ ...unsetFields,+ };}const createdAtForInsert = updatesArchiveState? (createdAtOnInsert ??@@ -2520,6 +2624,42 @@ export function createConversationMethods(}}+ /* Advance the version and clear the previous catch-up atomically. The database CAS orders+ * concurrent replies even when their application hosts disagree about wall-clock time. */+ let replyStampApplied = false;+ if (metadata?.stampReply === true) {+ const responseMessageId = metadata.replyMessageId;+ if (typeof responseMessageId === 'string' && responseMessageId.length > 0) {+ try {+ const stamped = await stampReplyWithCas(+ Conversation,+ { _id: conversation._id },+ responseMessageId,+ {+ lastResponseAt: 1,+ lastResponseMessageId: 1,+ lastResponseIsManual: 1,+ updatedAt: 1,+ },+ );+ if (stamped) {+ /* The caller hands this document to the client as the turn's conversation, and the+ * seen acknowledgement is bound to the stamp it carries. */+ replyStampApplied = true;+ conversation.lastResponseAt = stamped.stamp;+ conversation.lastResponseMessageId = stamped.conversation.lastResponseMessageId;+ conversation.lastResponseIsManual = stamped.conversation.lastResponseIsManual;+ conversation.lastSeenAt = undefined;+ if (stamped.conversation.updatedAt) {+ conversation.updatedAt = stamped.conversation.updatedAt;+ }+ }+ } catch (error) {+ logger.error('[saveConvo] Failed to stamp persisted reply', error);+ }+ }+ }+if (interfaceConfig?.retentionMode === RetentionMode.ALL &&typeof isTemporary !== 'boolean' &&@@ -2528,11 +2668,15 @@ export function createConversationMethods() {/* This backfill runs after the main write, so it needs the same timestampsuppression: otherwise the first pin or archive of a legacy chat under- `RetentionMode.ALL` bumps `updatedAt` here and lands in Today anyway. */+ `RetentionMode.ALL` bumps `updatedAt` here and lands in Today anyway.+ A reply stamp is the same case for a different reason: the CAS above set `updatedAt`+ to the stamp deliberately, and an away tab that has never cached this conversation+ reads the two disagreeing as a metadata-only promotion, withholding the reply's+ chime and desktop notification. */await Conversation.updateOne({ _id: conversation._id, isTemporary: { $ne: false } },{ $set: { isTemporary: false } },- preserveUpdatedAt ? { timestamps: false } : {},+ preserveUpdatedAt || replyStampApplied ? { timestamps: false } : {},);conversation.isTemporary = false;}@@ -2540,56 +2684,65 @@ export function createConversationMethods(const newChatProjectId = conversation.chatProjectId ?? null;const projectMembershipChanged = previousChatProjectId !== newChatProjectId;- /**- * A chat that moved between projects (e.g. a stale tab re-submitting an- * older project id) must fully recompute the stats of the project it left;- * the incremental path only ever touches the project it now belongs to.- */- if (projectMembershipChanged && previousChatProjectId) {- await refreshChatProjectStatsForUser(mongoose, userId, previousChatProjectId);- }-- if (conversation.chatProjectId) {- const isRetentionVisibilityUpdate =- typeof update.isTemporary === 'boolean' ||- Object.prototype.hasOwnProperty.call(convo, 'expiredAt') ||- Object.prototype.hasOwnProperty.call(unsetFields, 'isTemporary') ||- Object.prototype.hasOwnProperty.call(unsetFields, 'expiredAt');- /**- * Saving a conversation that is itself archived or retention-hidden (e.g.- * renaming or title generation on an archived project chat) must recompute- * stats rather than take the incremental fast path, otherwise the project's- * lastConversationAt/Id would point at a chat the project workspace hides.- */- const isConversationHidden =- conversation.isArchived === true ||- conversation.isTemporary === true ||- (conversation.expiredAt != null &&- new Date(conversation.expiredAt).getTime() <= Date.now());+ /* The conversation and its reply stamp are durable by now, and the caller hands this+ document to the client as the turn's conversation. Project statistics are maintenance+ on a different collection: letting one of their failures reach the catch below would+ answer a successful save with an error, dropping the stamp from the terminal event and+ presenting a reply the user already watched arrive as unread on the next refresh. */+ try {/**- * A move into this project (projectMembershipChanged) also needs a full- * refresh: the incremental path only bumps the count for brand-new inserts,- * so a pre-existing chat joining the project would otherwise be uncounted.+ * A chat that moved between projects (e.g. a stale tab re-submitting an+ * older project id) must fully recompute the stats of the project it left;+ * the incremental path only ever touches the project it now belongs to.*/- const isNewConversation = conversationResult.lastErrorObject?.updatedExisting === false;- const shouldRefreshProjectStats =- projectMembershipChanged ||- isNewConversation ||- typeof update.isArchived === 'boolean' ||- Object.prototype.hasOwnProperty.call(unsetFields, 'isArchived') ||- isRetentionVisibilityUpdate ||- isConversationHidden;-- if (shouldRefreshProjectStats) {- await refreshChatProjectStatsForUser(mongoose, userId, conversation.chatProjectId);- } else {- await updateChatProjectLastConversationForUser(- mongoose,- userId,- conversation.chatProjectId,- conversation,- );+ if (projectMembershipChanged && previousChatProjectId) {+ await refreshChatProjectStatsForUser(mongoose, userId, previousChatProjectId);}++ if (conversation.chatProjectId) {+ const isRetentionVisibilityUpdate =+ typeof update.isTemporary === 'boolean' ||+ Object.prototype.hasOwnProperty.call(convo, 'expiredAt') ||+ Object.prototype.hasOwnProperty.call(unsetFields, 'isTemporary') ||+ Object.prototype.hasOwnProperty.call(unsetFields, 'expiredAt');+ /**+ * Saving a conversation that is itself archived or retention-hidden (e.g.+ * renaming or title generation on an archived project chat) must recompute+ * stats rather than take the incremental fast path, otherwise the project's+ * lastConversationAt/Id would point at a chat the project workspace hides.+ */+ const isConversationHidden =+ conversation.isArchived === true ||+ conversation.isTemporary === true ||+ (conversation.expiredAt != null &&+ new Date(conversation.expiredAt).getTime() <= Date.now());+ /**+ * A move into this project (projectMembershipChanged) also needs a full+ * refresh: the incremental path only bumps the count for brand-new inserts,+ * so a pre-existing chat joining the project would otherwise be uncounted.+ */+ const isNewConversation = conversationResult.lastErrorObject?.updatedExisting === false;+ const shouldRefreshProjectStats =+ projectMembershipChanged ||+ isNewConversation ||+ typeof update.isArchived === 'boolean' ||+ Object.prototype.hasOwnProperty.call(unsetFields, 'isArchived') ||+ isRetentionVisibilityUpdate ||+ isConversationHidden;++ if (shouldRefreshProjectStats) {+ await refreshChatProjectStatsForUser(mongoose, userId, conversation.chatProjectId);+ } else {+ await updateChatProjectLastConversationForUser(+ mongoose,+ userId,+ conversation.chatProjectId,+ conversation,+ );+ }+ }+ } catch (error) {+ logger.error('[saveConvo] Failed to maintain project statistics', error);}return conversation.toObject();@@ -2813,7 +2966,12 @@ export function createConversationMethods(const affectedProjectStats = new Map<string, { user: string; projectId: string }>();const bulkOps = conversations.map((convo) => {const { codeEnvironmentMode, codeWorkspaces, ...sanitized } = convo;- delete sanitized.codeApprovalMode;+ /* Read state belongs to the reader who lived through the replies, so an import never+ carries one in: the rows arrive unseen-free and unread-free. */+ delete sanitized.lastResponseAt;+ delete sanitized.lastResponseMessageId;+ delete sanitized.lastResponseIsManual;+ delete sanitized.lastSeenAt;delete sanitized.initial_agent_id;delete sanitized.codeEnvironmentRevision;stripActorCheckpointFields(sanitized);@@ -3117,7 +3275,7 @@ export function createConversationMethods(the sidebar lists archived and unarchived chats in the same session, and theactive 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',+ 'conversationId endpoint title createdAt updatedAt archivedAt isArchived user model agent_id assistant_id spec iconURL chatProjectId pinned lastResponseAt lastResponseMessageId lastResponseIsManual lastSeenAt',).sort(sortObj).limit(pageSize + 1)@@ -3575,6 +3733,175 @@ export function createConversationMethods(}}+ /**+ * Records that the user has caught up with a conversation's newest message.+ *+ * `observedResponseAt` is the reply the client actually had on screen. Filtering on it keeps+ * the acknowledgement bound to that reply: if another device persisted a newer one in the+ * meantime, nothing matches and the indicator survives instead of being cleared for a message+ * nobody read. The stamp itself stays server-side, so no client clock is trusted.+ *+ * Deliberately bypasses `saveConvo`: this needs neither the message lookup nor the upsert,+ * and `timestamps: false` keeps `updatedAt` untouched so reading a conversation does not+ * reorder the sidebar.+ */+ async function markConvoSeen(user: string, conversationId: string, observedResponseAt?: Date) {+ try {+ const Conversation = mongoose.models.Conversation as Model<IConversation>;+ const filter: FilterQuery<IConversation> = { conversationId, user };+ if (observedResponseAt) {+ filter.lastResponseAt = { $lte: observedResponseAt };+ }+ /* Never earlier than the reply being acknowledged. The filter guarantees the stored+ * response is no newer than what the client observed, but across replicas the node+ * writing this can be behind the one that stamped the reply, and a catch-up older than+ * the response it acknowledges would read as unseen again on the next refetch. */+ const now = new Date();+ const lastSeenAt = observedResponseAt && observedResponseAt > now ? observedResponseAt : now;+ const result = await Conversation.updateOne(+ filter,+ { $set: { lastSeenAt } },+ { timestamps: false },+ );+ /* Matched, not modified: a retry of an acknowledgement that already landed writes the+ * same value back, which MongoDB reports as zero documents modified. The client reads+ * `modified: false` as a rejected stale acknowledgement and rolls its cache back to+ * unseen, so success has to mean "the observed reply is still the newest", which is+ * exactly what the filter matching does. */+ return { modified: result.matchedCount > 0 };+ } catch (error) {+ logger.error('[markConvoSeen] Error marking conversation seen', error);+ throw new Error('Error marking conversation seen');+ }+ }++ /**+ * Flags a conversation as unread again: the user explicitly wants the indicator back.+ *+ * A conversation that has never been replied to has no stamp for the dot to compare against,+ * so the flag stamps a strictly monotonic server value and records its source explicitly.+ * A real reply racing this write either wins first (and the clear-only path preserves it) or+ * sees the synthetic stamp and advances past it while clearing the marker.+ *+ * Classic operators only. Pipeline-form updates (and `$$REMOVE`) are unsupported on every+ * DocumentDB engine this project targets.+ */+ async function markConvoUnread(user: string, conversationId: string) {+ try {+ const Conversation = mongoose.models.Conversation as Model<IConversation>;+ const projection = { lastResponseAt: 1, lastResponseMessageId: 1, lastResponseIsManual: 1 };+ const stamped = await Conversation.findOneAndUpdate(+ {+ conversationId,+ user,+ $or: [{ lastResponseAt: null }, { lastResponseAt: { $exists: false } }],+ },+ {+ $set: { lastResponseAt: new Date(), lastResponseIsManual: true },+ $unset: { lastSeenAt: '', lastResponseMessageId: '' },+ },+ { timestamps: false, new: true, projection },+ ).lean<+ Pick<IConversation, 'lastResponseAt' | 'lastResponseMessageId' | 'lastResponseIsManual'>+ >();+ if (stamped) {+ return {+ modified: true,+ lastResponseAt: stamped.lastResponseAt,+ lastResponseMessageId: stamped.lastResponseMessageId,+ lastResponseIsManual: stamped.lastResponseIsManual === true,+ };+ }++ const cleared = await Conversation.findOneAndUpdate(+ { conversationId, user },+ { $unset: { lastSeenAt: '' } },+ { timestamps: false, new: true, projection },+ ).lean<+ Pick<IConversation, 'lastResponseAt' | 'lastResponseMessageId' | 'lastResponseIsManual'>+ >();++ return cleared+ ? {+ modified: true,+ lastResponseAt: cleared.lastResponseAt,+ lastResponseMessageId: cleared.lastResponseMessageId,+ lastResponseIsManual: cleared.lastResponseIsManual === true,+ }+ : { modified: false };+ } catch (error) {+ logger.error('[markConvoUnread] Error marking conversation unread', error);+ throw new Error('Error marking conversation unread');+ }+ }++ /**+ * Stamps a persisted assistant reply for paths that save the message directly+ * (assistants threads, resumed runs, terminal abort re-saves) rather than through+ * BaseClient's saveConvo payload.+ *+ * The same compare-and-set write `saveConvo` uses advances the reply version and clears the+ * previous catch-up atomically. Every persisted reply advances beyond the stored version,+ * including concurrent replies and replies from hosts whose clocks are behind.+ *+ * `updatedAt` moves with it, exactly as BaseClient's reply path already does: a new reply is+ * real activity and belongs at the top of the sidebar. It is also what the away poll pages+ * by, so a stamp that left the order alone would hide replies to any conversation that had+ * fallen past the first page. Contrast `markConvoSeen`, where reading must not reorder.+ */+ async function stampConvoLastResponse(+ user: string,+ conversationId: string,+ responseMessageId: string,+ ) {+ try {+ const Conversation = mongoose.models.Conversation as Model<IConversation>;+ const stamped = await stampReplyWithCas(+ Conversation,+ { conversationId, user },+ responseMessageId,+ {+ conversationId: 1,+ chatProjectId: 1,+ createdAt: 1,+ updatedAt: 1,+ lastResponseMessageId: 1,+ },+ );++ /* Moving `updatedAt` is only half of what `saveConvo` does for a project chat: the+ * workspace sorts on `ChatProject.lastConversationAt`, so lifting the conversation+ * while leaving its project behind would make the two views disagree. */+ if (stamped?.conversation.chatProjectId) {+ try {+ await updateChatProjectLastConversationForUser(+ mongoose,+ user,+ stamped.conversation.chatProjectId,+ stamped.conversation as IConversation,+ );+ } catch (error) {+ logger.error('[stampConvoLastResponse] Failed to update project activity', error);+ }+ }++ /* Return the exact server-side stamp that won the CAS. Callers that deliver a terminal+ * event can merge this into their read-state cache without inventing a browser timestamp. */+ return stamped+ ? {+ lastResponseAt: stamped.stamp,+ lastResponseMessageId: responseMessageId,+ ...(stamped.conversation.updatedAt+ ? { updatedAt: stamped.conversation.updatedAt }+ : {}),+ }+ : null;+ } catch (error) {+ logger.error('[stampConvoLastResponse] Error stamping conversation reply', error);+ throw new Error('Error stamping conversation reply');+ }+ }+return {getConvoFiles,searchConversation,@@ -3614,6 +3941,9 @@ export function createConversationMethods(getConvoOwnership,getConvoRetention,getConvoTitle,+ markConvoSeen,+ markConvoUnread,+ stampConvoLastResponse,deleteConvos,archiveAllConvos,};diff --git a/packages/data-schemas/src/schema/convo.ts b/packages/data-schemas/src/schema/convo.tsindex 2488964a68..67aac88d3b 100644--- a/packages/data-schemas/src/schema/convo.ts+++ b/packages/data-schemas/src/schema/convo.ts@@ -386,6 +386,20 @@ const convoSchema: Schema<IConversation> = new Schema(archivedAt: {type: Date,},+ lastResponseAt: {+ type: Date,+ },+ /** Durable messageId of the assistant reply named by lastResponseAt. */+ lastResponseMessageId: {+ type: String,+ },+ /** True only for the synthetic unread marker; real replies clear this field. */+ lastResponseIsManual: {+ type: Boolean,+ },+ lastSeenAt: {+ type: Date,+ },},{ timestamps: true },);@@ -414,6 +428,12 @@ convoSchema.index({ user: 1, isArchived: 1, title: 1, updatedAt: 1, _id: 1 });/** The sidebar's pinned section filters on user + pinned and pages by `updatedAt`. */convoSchema.index({ user: 1, pinned: 1, updatedAt: -1, _id: -1 });+/** The default chats list, and the away poll that reads its first page every thirty seconds+ * for the unseen indicators, filter on user alone and page by `updatedAt`. Neither of the+ * `updatedAt` indexes above can serve them: a compound index only provides the sort when the+ * keys before it are pinned by equality, and those two pin `chatProjectId` and `pinned`. */+convoSchema.index({ user: 1, updatedAt: -1, _id: -1 });+convoSchema.index({ user: 1, isTemporary: 1, expiredAt: 1 });/** Owner-scoped child-thread cascade lookup used when a parent is deleted. */convoSchema.index({ user: 1, 'subagentThread.parentConversationId': 1 });diff --git a/packages/data-schemas/src/types/convo.ts b/packages/data-schemas/src/types/convo.tsindex 62d9a9a718..2232e8f187 100644--- a/packages/data-schemas/src/types/convo.ts+++ b/packages/data-schemas/src/types/convo.ts@@ -338,4 +338,12 @@ export interface IConversation extends Document {createdAt?: Date;updatedAt?: Date;tenantId?: string;+ /** Set only when an assistant message is persisted, never by title generation or metadata edits. */+ lastResponseAt?: Date;+ /** Durable messageId of the assistant reply named by `lastResponseAt`. */+ lastResponseMessageId?: string;+ /** True only while `lastResponseAt` is the synthetic marker from "mark unread". */+ lastResponseIsManual?: boolean;+ /** Set when the user has the newest message on screen; compared against `lastResponseAt`. */+ lastSeenAt?: Date;}