Skip to content

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

fix: Order Server Snapshots Against Pending Read Intent

Liaac2b51e98f47
diff --git a/client/src/data-provider/Schedules/admission.ts b/client/src/data-provider/Schedules/admission.ts
index 86fb1b65a9..61c2e089dd 100644
--- a/client/src/data-provider/Schedules/admission.ts
+++ b/client/src/data-provider/Schedules/admission.ts
@@ -1,3 +1,4 @@
+import { fetchConvoSnapshot } from '~/utils/convos';
/* Scheduled chats */
import { QueryKeys, dataService } from 'librechat-data-provider';
import type { TUser, TConversation } from 'librechat-data-provider';
@@ -111,7 +112,9 @@ async function admit(queryClient: QueryClient, conversationId: string): Promise<
}
let conversation: TConversation;
try {
- conversation = await dataService.getConversationById(conversationId);
+ conversation = await fetchConvoSnapshot(queryClient, conversationId, () =>
+ dataService.getConversationById(conversationId),
+ );
} catch (error) {
if (isTerminalProbeFailure(error)) {
return false;
diff --git a/client/src/data-provider/__tests__/pinnedConversations.test.tsx b/client/src/data-provider/__tests__/pinnedConversations.test.tsx
index 5c146ee031..525a6c59ce 100644
--- a/client/src/data-provider/__tests__/pinnedConversations.test.tsx
+++ b/client/src/data-provider/__tests__/pinnedConversations.test.tsx
@@ -9,6 +9,14 @@ import type {
TConversation,
} from 'librechat-data-provider';
import type { ReactNode } from 'react';
+import {
+ useConversationTagMutation,
+ useDeleteConversationMutation,
+ useDeleteConversationTagMutation,
+ usePinConversationMutation,
+ useMarkConversationSeenMutation,
+ useMarkConversationUnreadMutation,
+} from '../mutations';
import {
removeConvoFromAllQueries,
updateConvoInAllQueries,
@@ -16,12 +24,6 @@ import {
collectPinnedConversations,
withoutListFlags,
} from '~/utils/convos';
-import {
- useConversationTagMutation,
- useDeleteConversationMutation,
- useDeleteConversationTagMutation,
- usePinConversationMutation,
-} from '../mutations';
import {
pinnedConversationsPageSize,
useConversationsInfiniteQuery,
@@ -37,6 +39,8 @@ jest.mock('librechat-data-provider', () => {
...actual.dataService,
listConversations: jest.fn(),
pinConversation: jest.fn(),
+ markConversationSeen: jest.fn(),
+ markConversationUnread: jest.fn(),
deleteConversation: jest.fn(),
updateConversationTag: jest.fn(),
deleteConversationTag: jest.fn(),
@@ -304,6 +308,66 @@ describe('pinned list cache synchronization', () => {
},
);
+ it.each(['seen', 'unread'] as const)(
+ 'does not overwrite later %s intent when an old pin snapshot settles',
+ async (intent) => {
+ const queryClient = createQueryClient();
+ const repliedAt = '2026-08-16T10:00:00.000Z';
+ const confirmed = {
+ ...pinnedConvo,
+ lastResponseAt: repliedAt,
+ lastResponseMessageId: 'reply',
+ isMarkedUnread: false,
+ lastSeenAt: UNSEEN_REPLY_WATERMARK,
+ } as TConversation;
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([confirmed]));
+ queryClient.setQueryData([QueryKeys.allConversations], {
+ pages: [listResponse([confirmed])],
+ pageParams: [null],
+ });
+ let releasePin!: (value: TConversation) => void;
+ pinConversation.mockReturnValue(
+ new Promise((resolve) => {
+ releasePin = resolve;
+ }),
+ );
+ jest.mocked(dataService.markConversationSeen).mockResolvedValue({ modified: true });
+ jest.mocked(dataService.markConversationUnread).mockResolvedValue({
+ modified: true,
+ lastResponseAt: repliedAt,
+ isMarkedUnread: true,
+ });
+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries');
+ const { result } = renderHook(
+ () => ({
+ pin: usePinConversationMutation(),
+ seen: useMarkConversationSeenMutation(),
+ unread: useMarkConversationUnreadMutation(),
+ }),
+ { wrapper: createWrapper(queryClient) },
+ );
+ await act(async () => {
+ const pending = result.current.pin.mutateAsync({
+ conversationId: pinnedConversationId,
+ pinned: false,
+ });
+ await waitFor(() => expect(pinConversation).toHaveBeenCalledTimes(1));
+ await result.current[intent].mutateAsync({ conversationId: pinnedConversationId });
+ releasePin({ ...confirmed, pinned: false });
+ await pending;
+ });
+ const chats = queryClient.getQueryData<{ pages: ConversationListResponse[] }>([
+ QueryKeys.allConversations,
+ ]);
+ const row = chats?.pages[0].conversations[0];
+ expect(row?.pinned).toBe(false);
+ expect(row?.lastSeenAt).toBe(intent === 'seen' ? repliedAt : undefined);
+ expect(row?.isMarkedUnread).toBe(intent === 'unread');
+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.allConversations]);
+ queryClient.clear();
+ },
+ );
+
it('keeps a renamed pin in the section with its new title', () => {
const queryClient = createQueryClient();
queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
diff --git a/client/src/data-provider/mutations.ts b/client/src/data-provider/mutations.ts
index 0aa072af8f..2ece6b7749 100644
--- a/client/src/data-provider/mutations.ts
+++ b/client/src/data-provider/mutations.ts
@@ -14,6 +14,10 @@ import {
addConvoToAllQueries,
markRunningRemoval,
mergeConvoSnapshot,
+ beginConvoSnapshot,
+ endConvoSnapshot,
+ endConvoReadIntent,
+ supersedeConvoSnapshots,
findPinnedConversation,
findConvoInAllQueries,
findConversationInInfinite,
@@ -230,12 +234,22 @@ export const usePinConversationMutation = (
options?: t.PinConversationOptions,
): UseMutationResult<t.TPinConversationResponse, unknown, t.TPinConversationRequest, unknown> => {
const queryClient = useQueryClient();
- const { onSuccess, onError, ..._options } = options || {};
+ const { onSuccess, onError, onMutate, onSettled } = options || {};
return useMutation(
[MutationKeys.convoPin],
(payload: t.TPinConversationRequest) => dataService.pinConversation(payload),
{
+ onMutate: async (vars) => {
+ const fence = beginConvoSnapshot(queryClient, vars.conversationId);
+ try {
+ await onMutate?.(vars);
+ return fence;
+ } catch (error) {
+ endConvoSnapshot(queryClient, vars.conversationId, fence);
+ throw error;
+ }
+ },
onSuccess: async (data, vars, context) => {
/** A project drop can start a list refresh before its following unpin.
* Cancel that older snapshot before publishing the authoritative pin result. */
@@ -251,15 +265,13 @@ export const usePinConversationMutation = (
const snapshot = mergeConvoSnapshot(
data,
findConvoInAllQueries(queryClient, vars.conversationId),
+ context?.superseded === true,
);
const next =
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. */
- queryClient.invalidateQueries({ queryKey: [QueryKeys.archivedConversations] });
/** An older pin may exist only in the dedicated pinned cache. Unpinning
* it has to put the returned row onto the chats list; later pages
* cannot recover a conversation whose updatedAt just jumped ahead of
@@ -268,13 +280,20 @@ export const usePinConversationMutation = (
if (next.pinned !== true) {
addConvoToAllQueries(queryClient, next);
}
- /** The pinned section has its own fetch, so a new pin is only visible once
- * that list is refetched; unpins are already dropped from its cache above. */
- queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
- onSuccess?.(data, vars, context);
+ if (context?.superseded) {
+ refreshConvoReadCaches(queryClient, vars.conversationId);
+ } else {
+ /* Pinned state affects both views; invalidate archived variants by prefix. */
+ queryClient.invalidateQueries({ queryKey: [QueryKeys.archivedConversations] });
+ queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
+ }
+ onSuccess?.(data, vars);
+ },
+ onError: (error, vars) => onError?.(error, vars),
+ onSettled: (data, error, vars, context) => {
+ endConvoSnapshot(queryClient, vars.conversationId, context);
+ return onSettled?.(data, error, vars);
},
- onError,
- ..._options,
},
);
};
@@ -392,6 +411,7 @@ const getReadWriteState = (queryClient: QueryClient): ReadWriteState => {
const claimReadWrite = (queryClient: QueryClient, conversationId: string): number => {
const state = getReadWriteState(queryClient);
state.next += 1;
+ supersedeConvoSnapshots(queryClient, conversationId, state.next);
state.latest.set(conversationId, state.next);
return state.next;
};
@@ -411,6 +431,7 @@ const releaseReadWrite = (
if (isLatestReadWrite(queryClient, conversationId, token)) {
getReadWriteState(queryClient).latest.delete(conversationId);
}
+ endConvoReadIntent(queryClient, conversationId, token);
};
/**
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 7060021971..9ed757faa2 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -102,6 +102,7 @@ import { useChatTransport } from '~/Providers/ChatTransportContext';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
import { liveAppliedSteerIdsAtom } from '~/store/steer';
import { useAuthContext } from '~/hooks/AuthContext';
+import { fetchConvoSnapshot } from '~/utils/convos';
import { useFileMapContext } from '~/Providers';
import useUsageHandler from './useUsageHandler';
import useLocalize from '~/hooks/useLocalize';
@@ -3402,7 +3403,9 @@ export default function useResumableSSE(
// Both fresh and resumed subscriptions can miss every event of a fast turn.
// A missing job proves neither that the conversation was saved nor that it failed.
try {
- const persisted = await dataService.getConversationById(recoveryConvoId);
+ const persisted = await fetchConvoSnapshot(queryClient, recoveryConvoId, () =>
+ dataService.getConversationById(recoveryConvoId),
+ );
if (!isCurrentSubscription()) return;
if (persisted?.conversationId === recoveryConvoId) {
queryClient.setQueryData([QueryKeys.conversation, recoveryConvoId], persisted);
@@ -4615,7 +4618,11 @@ export default function useResumableSSE(
let persistedConversation: TConversation | undefined;
let conversationLookup: 'found' | 'not_found' | 'inconclusive' = 'inconclusive';
try {
- persistedConversation = await dataService.getConversationById(settledConversationId);
+ persistedConversation = await fetchConvoSnapshot(
+ queryClient,
+ settledConversationId,
+ () => dataService.getConversationById(settledConversationId),
+ );
if (!isCurrentEffect()) {
return;
}
diff --git a/client/src/utils/convos.spec.ts b/client/src/utils/convos.spec.ts
index f5ea302428..e8393a3aa2 100644
--- a/client/src/utils/convos.spec.ts
+++ b/client/src/utils/convos.spec.ts
@@ -5,6 +5,11 @@ import type { ConversationCursorData } from './convos';
import {
dateKeys,
mergeConvoSnapshot,
+ beginConvoSnapshot,
+ endConvoSnapshot,
+ endConvoReadIntent,
+ supersedeConvoSnapshots,
+ fetchConvoSnapshot,
storeEndpointSettings,
addConversationToInfinitePages,
updateInfiniteConvoPage,
@@ -1219,6 +1224,13 @@ describe('Conversation Utilities', () => {
expect(merged.lastResponseMessageId).toBe('reply');
const older = { ...server, lastResponseAt: '2026-08-16T09:00:00.000Z' };
expect(mergeConvoSnapshot(older, cached).lastSeenAt).toBe(UNSEEN_REPLY_WATERMARK);
+ const read = { ...cached, lastSeenAt: cached.lastResponseAt };
+ expect(mergeConvoSnapshot(cached, read, true).lastSeenAt).toBe(read.lastSeenAt);
+ expect(mergeConvoSnapshot(cached, read).lastSeenAt).toBe(read.lastSeenAt);
+ const reminder = { ...cached, lastSeenAt: undefined, isMarkedUnread: true };
+ expect(mergeConvoSnapshot(cached, reminder).isMarkedUnread).toBe(true);
+ const later = { ...cached, lastResponseAt: '2026-08-16T11:00:00.000Z' };
+ expect(mergeConvoSnapshot(later, read, true).lastSeenAt).toBe(UNSEEN_REPLY_WATERMARK);
});
it.each([true, false])(
@@ -1792,3 +1804,72 @@ describe('Conversation Utilities', () => {
});
});
});
+
+describe('conversation snapshot read authority', () => {
+ it('fences reads already pending at request start and drops settled records', () => {
+ const client = new QueryClient();
+ supersedeConvoSnapshots(client, 'convo', 1);
+ const fence = beginConvoSnapshot(client, 'convo');
+ expect(fence.superseded).toBe(true);
+ endConvoReadIntent(client, 'convo', 1);
+ endConvoSnapshot(client, 'convo', fence);
+ const fresh = beginConvoSnapshot(client, 'convo');
+ expect(fresh.superseded).toBe(false);
+ endConvoSnapshot(client, 'convo', fresh);
+ client.clear();
+ });
+
+ it('isolates concurrent snapshots by request, conversation and query client', () => {
+ const client = new QueryClient();
+ const other = new QueryClient();
+ const completed = beginConvoSnapshot(client, 'convo');
+ const pending = beginConvoSnapshot(client, 'convo');
+ endConvoSnapshot(client, 'convo', completed);
+ supersedeConvoSnapshots(other, 'convo', 1);
+ supersedeConvoSnapshots(client, 'another', 1);
+ expect(pending.superseded).toBe(false);
+ supersedeConvoSnapshots(client, 'convo', 2);
+ expect(completed.superseded).toBe(false);
+ expect(pending.superseded).toBe(true);
+ endConvoReadIntent(client, 'convo', 1);
+ const during = beginConvoSnapshot(client, 'convo');
+ expect(during.superseded).toBe(true);
+ endConvoReadIntent(client, 'convo', 2);
+ endConvoSnapshot(client, 'convo', pending);
+ endConvoSnapshot(client, 'convo', during);
+ endConvoReadIntent(client, 'another', 1);
+ endConvoReadIntent(other, 'convo', 1);
+ client.clear();
+ other.clear();
+ });
+
+ it('a snapshot fetch preserves same-reply read intent that settles during the request', async () => {
+ const client = new QueryClient();
+ const repliedAt = '2026-08-16T10:00:00.000Z';
+ const confirmed = {
+ conversationId: 'convo',
+ lastResponseAt: repliedAt,
+ lastSeenAt: UNSEEN_REPLY_WATERMARK,
+ isMarkedUnread: false,
+ } as TConversation;
+ client.setQueryData(['conversation', 'convo'], confirmed);
+ let complete!: (value: TConversation) => void;
+ const pending = fetchConvoSnapshot(
+ client,
+ 'convo',
+ () =>
+ new Promise((resolve) => {
+ complete = resolve;
+ }),
+ );
+ supersedeConvoSnapshots(client, 'convo', 1);
+ client.setQueryData(['conversation', 'convo'], { ...confirmed, lastSeenAt: repliedAt });
+ endConvoReadIntent(client, 'convo', 1);
+ complete(confirmed);
+ expect((await pending).lastSeenAt).toBe(repliedAt);
+ const fresh = beginConvoSnapshot(client, 'convo');
+ expect(fresh.superseded).toBe(false);
+ endConvoSnapshot(client, 'convo', fresh);
+ client.clear();
+ });
+});
diff --git a/client/src/utils/convos.ts b/client/src/utils/convos.ts
index 6995071421..4d9f44782c 100644
--- a/client/src/utils/convos.ts
+++ b/client/src/utils/convos.ts
@@ -1272,14 +1272,111 @@ function preserveListFlags(next: TConversation, found: TConversation): TConversa
return merged;
}
+export type ConvoSnapshotFence = { superseded: boolean };
+
+type ConvoReadAuthority = {
+ readToken?: number;
+ snapshots: Set<ConvoSnapshotFence>;
+};
+
+const convoReadAuthorities = new WeakMap<QueryClient, Map<string, ConvoReadAuthority>>();
+
+function convoReadAuthority(queryClient: QueryClient, conversationId: string): ConvoReadAuthority {
+ let records = convoReadAuthorities.get(queryClient);
+ if (!records) {
+ records = new Map();
+ convoReadAuthorities.set(queryClient, records);
+ }
+ let authority = records.get(conversationId);
+ if (!authority) {
+ authority = { snapshots: new Set() };
+ records.set(conversationId, authority);
+ }
+ return authority;
+}
+
+function releaseConvoReadAuthority(queryClient: QueryClient, conversationId: string): void {
+ const records = convoReadAuthorities.get(queryClient);
+ const authority = records?.get(conversationId);
+ if (authority?.readToken == null && authority?.snapshots.size === 0) {
+ records?.delete(conversationId);
+ }
+}
+
+/** Authority records live only while a read write or server snapshot is pending. */
+export function beginConvoSnapshot(
+ queryClient: QueryClient,
+ conversationId: string,
+): ConvoSnapshotFence {
+ const authority = convoReadAuthority(queryClient, conversationId);
+ const fence = { superseded: authority.readToken != null };
+ authority.snapshots.add(fence);
+ return fence;
+}
+
+export function endConvoSnapshot(
+ queryClient: QueryClient,
+ conversationId: string,
+ fence: ConvoSnapshotFence | undefined,
+): void {
+ if (fence) convoReadAuthorities.get(queryClient)?.get(conversationId)?.snapshots.delete(fence);
+ releaseConvoReadAuthority(queryClient, conversationId);
+}
+
+export function supersedeConvoSnapshots(
+ queryClient: QueryClient,
+ conversationId: string,
+ readToken: number,
+): void {
+ const authority = convoReadAuthority(queryClient, conversationId);
+ authority.readToken = readToken;
+ for (const fence of authority.snapshots) fence.superseded = true;
+}
+
+export function endConvoReadIntent(
+ queryClient: QueryClient,
+ conversationId: string,
+ readToken: number | undefined,
+): void {
+ const authority = convoReadAuthorities.get(queryClient)?.get(conversationId);
+ if (authority && authority.readToken === readToken) delete authority.readToken;
+ releaseConvoReadAuthority(queryClient, conversationId);
+}
+
+export async function fetchConvoSnapshot(
+ queryClient: QueryClient,
+ conversationId: string,
+ fetch: () => Promise<TConversation>,
+): Promise<TConversation> {
+ const fence = beginConvoSnapshot(queryClient, conversationId);
+ try {
+ const record = await fetch();
+ return record == null
+ ? record
+ : mergeConvoSnapshot(
+ record,
+ findConvoInAllQueries(queryClient, conversationId),
+ fence.superseded,
+ );
+ } finally {
+ endConvoSnapshot(queryClient, conversationId, fence);
+ }
+}
+
/** Full server snapshots clear omitted read fields; partial UI patches preserve them. */
export function mergeConvoSnapshot(
snapshot: TConversation,
cached?: TConversation,
+ preferCachedReadState = false,
): TConversation {
const state =
cached?.lastResponseAt != null &&
- (snapshot.lastResponseAt == null || snapshot.lastResponseAt < cached.lastResponseAt)
+ (snapshot.lastResponseAt == null ||
+ snapshot.lastResponseAt < cached.lastResponseAt ||
+ (snapshot.lastResponseAt === cached.lastResponseAt &&
+ (preferCachedReadState ||
+ (snapshot.lastSeenAt === UNSEEN_REPLY_WATERMARK &&
+ cached.lastSeenAt !== UNSEEN_REPLY_WATERMARK))))
? cached
: snapshot;
return {