fix: Fence Reply Read State and Preserve Snapshot Clears

This commit is contained in:
Lia 2026-10-03 16:10:04 +00:00 • committed by Danny Avila
parent 4bc9c9e5c0
commit c85795d08f
7 changed files with 174 additions and 14 deletions

View file

@ -138,7 +138,7 @@ async function admit(queryClient: QueryClient, conversationId: string): Promise<
[QueryKeys.conversation, conversationId],
(current) => current ?? conversation,
);
upsertConvoInAllQueries(queryClient, conversation);
upsertConvoInAllQueries(queryClient, conversation, true, 'snapshot');
/** The same bookkeeping the foreground path does when a chat lands in a
* project: the project's count and recent-activity ordering live on the
* project rows, which the conversation caches above do not touch. */

View file

@ -1,8 +1,8 @@
import { createElement } from 'react';
import { getDefaultStore } from 'jotai';
import { dataService, QueryKeys } from 'librechat-data-provider';
import { act, renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { dataService, QueryKeys, UNSEEN_REPLY_WATERMARK } from 'librechat-data-provider';
import type {
ConversationListResponse,
TConversationTag,
@ -269,6 +269,41 @@ describe('pinned list cache synchronization', () => {
expect(readPinnedCache(queryClient)?.conversations).toEqual([]);
});
it.each([true, false])(
'accepts an authoritative unread clear while unpinning (listed: %s)',
async (listed) => {
const queryClient = createQueryClient();
const confirmed = {
...pinnedConvo,
lastResponseAt: '2026-08-16T10:00:00.000Z',
lastResponseMessageId: 'reply',
isMarkedUnread: false,
lastSeenAt: UNSEEN_REPLY_WATERMARK,
} as TConversation;
queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([confirmed]));
queryClient.setQueryData([QueryKeys.allConversations], {
pages: [listResponse(listed ? [confirmed] : [])],
pageParams: [null],
});
const server = JSON.parse(
JSON.stringify({ ...confirmed, lastSeenAt: undefined }),
) as TConversation;
pinConversation.mockResolvedValue({ ...server, pinned: false } as TConversation);
const { result } = renderHook(() => usePinConversationMutation(), {
wrapper: createWrapper(queryClient),
});
await act(async () => {
await result.current.mutateAsync({ conversationId: pinnedConversationId, pinned: false });
});
const chats = queryClient.getQueryData<{ pages: ConversationListResponse[] }>([
QueryKeys.allConversations,
]);
expect(chats?.pages[0].conversations[0].lastSeenAt).toBeUndefined();
expect(chats?.pages[0].conversations[0].isMarkedUnread).toBe(false);
expect(readPinnedCache(queryClient)?.conversations).toEqual([]);
},
);
it('keeps a renamed pin in the section with its new title', () => {
const queryClient = createQueryClient();
queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));

View file

@ -1,11 +1,11 @@
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 { EModelEndpoint, QueryKeys, UNSEEN_REPLY_WATERMARK } from 'librechat-data-provider';
import type { InfiniteData } from '@tanstack/react-query';
import type { ConversationCursorData } from '~/utils/convos';
import { useMarkConversationSeenMutation, useMarkConversationUnreadMutation } from '../mutations';
import { isConversationUnseen, updateConvoInAllQueries } from '~/utils';
import { applyServerReplyStamp, isConversationUnseen, updateConvoInAllQueries } from '~/utils';
const mockMarkSeen = jest.fn();
const mockMarkUnread = jest.fn();
@ -135,6 +135,45 @@ describe('useMarkConversationSeenMutation', () => {
expect(isConversationUnseen(cached())).toBe(true);
});
it.each(['accepted', 'rejected', 'failed'])(
'keeps a newer unseen reply in Finished when an older acknowledgement is %s',
async (outcome) => {
const request = deferred();
mockMarkSeen.mockReturnValue(request.promise);
const { result, cached, queryClient } = setup(SEEN_AT);
await act(async () => {
const pending = result.current
.mutateAsync({ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT })
.catch(() => undefined);
await flush();
applyServerReplyStamp(queryClient, CONVO_ID, {
lastResponseAt: '2026-08-16T11:00:00.000Z',
lastResponseMessageId: 'newer-reply',
});
if (outcome === 'failed') request.reject(new Error('Unavailable'));
else request.resolve({ modified: outcome === 'accepted' });
await pending;
});
expect(cached()?.lastSeenAt).toBe(UNSEEN_REPLY_WATERMARK);
expect(cached()?.lastResponseMessageId).toBe('newer-reply');
expect(cached()?.isMarkedUnread).toBe(false);
expect(isConversationUnseen(cached())).toBe(true);
},
);
it('does not optimistically replace a newer reply watermark with an old observation', async () => {
mockMarkSeen.mockResolvedValue({ modified: false });
const { result, cached, queryClient } = setup(SEEN_AT);
applyServerReplyStamp(queryClient, CONVO_ID, {
lastResponseAt: '2026-08-16T11:00:00.000Z',
lastResponseMessageId: 'newer-reply',
});
await act(async () => {
await result.current.mutateAsync({ conversationId: CONVO_ID, lastResponseAt: RESPONDED_AT });
});
expect(cached()?.lastSeenAt).toBe(UNSEEN_REPLY_WATERMARK);
});
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. */

View file

@ -13,6 +13,7 @@ import {
/* Conversations */
addConvoToAllQueries,
markRunningRemoval,
mergeConvoSnapshot,
findPinnedConversation,
findConvoInAllQueries,
findConversationInInfinite,
@ -247,10 +248,14 @@ export const usePinConversationMutation = (
* read it off the cached pin before the update drops that row: the reinsert
* below has no existing chats row to carry the badge over from. */
const cachedPin = findPinnedConversation(queryClient, vars.conversationId);
const snapshot = mergeConvoSnapshot(
data,
findConvoInAllQueries(queryClient, vars.conversationId),
);
const next =
data.isShared === undefined && cachedPin?.isShared !== undefined
? { ...data, isShared: cachedPin.isShared }
: data;
snapshot.isShared === undefined && cachedPin?.isShared !== undefined
? { ...snapshot, isShared: cachedPin.isShared }
: snapshot;
updateConvoInAllQueries(queryClient, vars.conversationId, () => next);
/* Pinned state is list-relevant in both active and archived views. The
* archived variants carry filter/sort parameters, so invalidate by prefix. */
@ -448,7 +453,12 @@ const settleCatchUp = (
return;
}
const cached = findConvoInAllQueries(queryClient, conversationId);
if (!cached || cached.lastSeenAt === settled) {
if (
!cached ||
cached.lastSeenAt === settled ||
(cached.lastResponseAt != null &&
(acknowledged == null || cached.lastResponseAt > acknowledged))
) {
return;
}
const current = cached.lastSeenAt;
@ -504,10 +514,11 @@ export const useMarkConversationSeenMutation = (): UseMutationResult<
reads as caught up. */
const acknowledged: string | undefined =
vars.lastResponseAt ?? cached?.lastResponseAt ?? new Date().toISOString();
updateConvoInAllQueries(queryClient, vars.conversationId, (convo) => ({
...convo,
lastSeenAt: acknowledged,
}));
updateConvoInAllQueries(queryClient, vars.conversationId, (convo) =>
convo.lastResponseAt != null && convo.lastResponseAt > acknowledged
? convo
: { ...convo, lastSeenAt: acknowledged },
);
return {
previous: cached?.lastSeenAt,
acknowledged,

View file

@ -3406,7 +3406,7 @@ export default function useResumableSSE(
if (!isCurrentSubscription()) return;
if (persisted?.conversationId === recoveryConvoId) {
queryClient.setQueryData([QueryKeys.conversation, recoveryConvoId], persisted);
upsertConvoInAllQueries(queryClient, persisted);
upsertConvoInAllQueries(queryClient, persisted, true, 'snapshot');
if (!isAddedRequest) {
setConversation?.((current) => {
if (
@ -4656,7 +4656,7 @@ export default function useResumableSSE(
[QueryKeys.conversation, settledConversationId],
conversationRecord,
);
upsertConvoInAllQueries(queryClient, conversationRecord);
upsertConvoInAllQueries(queryClient, conversationRecord, true, 'snapshot');
setConversation?.((current) =>
keepLocalCodeApprovalMode(settledCopy, current, localConversationId),
);

View file

@ -4,6 +4,7 @@ import type { TConversation } from 'librechat-data-provider';
import type { ConversationCursorData } from './convos';
import {
dateKeys,
mergeConvoSnapshot,
storeEndpointSettings,
addConversationToInfinitePages,
updateInfiniteConvoPage,
@ -1201,6 +1202,56 @@ describe('Conversation Utilities', () => {
expect(data!.pages[0].conversations[0].lastResponseMessageId).toBe('reply-a');
});
it('snapshot merging distinguishes authoritative absence from partial UI updates', () => {
const cached = {
...convoA,
lastResponseAt: '2026-08-16T10:00:00.000Z',
lastResponseMessageId: 'reply',
isMarkedUnread: false,
lastSeenAt: UNSEEN_REPLY_WATERMARK,
} as TConversation;
const server = JSON.parse(
JSON.stringify({ ...cached, lastSeenAt: undefined }),
) as TConversation;
const merged = mergeConvoSnapshot(server, cached);
expect(merged.lastSeenAt).toBeUndefined();
expect('lastSeenAt' in merged).toBe(true);
expect(merged.lastResponseMessageId).toBe('reply');
const older = { ...server, lastResponseAt: '2026-08-16T09:00:00.000Z' };
expect(mergeConvoSnapshot(older, cached).lastSeenAt).toBe(UNSEEN_REPLY_WATERMARK);
});
it.each([true, false])(
'snapshot upserts clear an omitted watermark while partial updates preserve it (pinned: %s)',
(pinned) => {
updateConvoInAllQueries(queryClient, 'a', (c) => ({
...c,
pinned,
lastResponseAt: '2026-08-16T10:00:00.000Z',
isMarkedUnread: false,
lastSeenAt: UNSEEN_REPLY_WATERMARK,
}));
upsertConvoInAllQueries(
queryClient,
{ conversationId: 'a', title: 'Partial' } as TConversation,
false,
);
expect(findConvoInAllQueries(queryClient, 'a')?.lastSeenAt).toBe(UNSEEN_REPLY_WATERMARK);
upsertConvoInAllQueries(
queryClient,
{
conversationId: 'a',
title: 'Snapshot',
lastResponseAt: '2026-08-16T10:00:00.000Z',
isMarkedUnread: false,
} as TConversation,
false,
'snapshot',
);
expect(findConvoInAllQueries(queryClient, 'a')?.lastSeenAt).toBeUndefined();
},
);
it('does not invent reply eligibility for an unclassified backend snapshot', () => {
updateConvoInAllQueries(queryClient, 'a', (c) => ({
...c,

View file

@ -710,11 +710,15 @@ export function upsertConvoInAllQueries(
queryClient: QueryClient,
nextConvo: TConversation,
moveToTop = true,
readState: 'partial' | 'snapshot' = 'partial',
) {
if (!nextConvo.conversationId) {
return;
}
const conversationId = nextConvo.conversationId;
if (readState === 'snapshot') {
nextConvo = mergeConvoSnapshot(nextConvo, findConvoInAllQueries(queryClient, conversationId));
}
/* The history query excludes temporary conversations server-side, so seeding
one into the list caches would surface it in the sidebar until the next
@ -1268,6 +1272,26 @@ function preserveListFlags(next: TConversation, found: TConversation): TConversa
return merged;
}
/** Full server snapshots clear omitted read fields; partial UI patches preserve them. */
export function mergeConvoSnapshot(
snapshot: TConversation,
cached?: TConversation,
): TConversation {
const state =
cached?.lastResponseAt != null &&
(snapshot.lastResponseAt == null || snapshot.lastResponseAt < cached.lastResponseAt)
? cached
: snapshot;
return {
...snapshot,
lastResponseAt: state.lastResponseAt,
lastResponseMessageId: state.lastResponseMessageId,
lastResponseIsManual: state.lastResponseIsManual,
isMarkedUnread: state.isMarkedUnread,
lastSeenAt: state.lastSeenAt,
};
}
const preserveReadState = (next: TConversation, found: TConversation): TConversation => {
const merged = { ...next };
if (!('lastResponseAt' in next)) {