Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(chat): keep a just-sent message when a stale transcript read resolves (#21083)

Arvin Xu5d06c47ba982
diff --git a/packages/replica/src/zustand/createReplicaSlice.fetch.test.ts b/packages/replica/src/zustand/createReplicaSlice.fetch.test.ts
index accaf91332a..1f550cbca70 100644
--- a/packages/replica/src/zustand/createReplicaSlice.fetch.test.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.fetch.test.ts
@@ -108,6 +108,7 @@ const effectSpies = () => ({
onError: vi.fn(),
onMissing: vi.fn(),
onPurge: vi.fn(),
+ onSettled: vi.fn(),
});
beforeEach(() => {
@@ -160,6 +161,23 @@ describe('createReplicaSlice fetch', () => {
expect(effects.onApplied).not.toHaveBeenCalled();
});
+ it('settles a discarded response so per-request bookkeeping can be released', async () => {
+ const { calls, fetcher } = deferredFetcher();
+ const effects = effectSpies();
+ const { slice } = setup({ effects, fetcher });
+
+ const pending = slice.fetch({ id: 'a' });
+ slice.remove('a');
+ calls[0].resolve(['deleted on the server']);
+
+ await expect(pending).resolves.toMatchObject({ applied: false });
+ expect(effects.onSettled).toHaveBeenCalledWith(
+ ['deleted on the server'],
+ { id: 'a' },
+ { key: 'a', scope: 'user-1:personal', source: 'fetch' },
+ );
+ });
+
it('drops a response whose request started before a clear()', async () => {
const { calls, fetcher } = deferredFetcher();
const effects = effectSpies();
diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.ts
index 91a8fa981ae..9deb0903328 100644
--- a/packages/replica/src/zustand/createReplicaSlice.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.ts
@@ -120,6 +120,13 @@ export interface ReplicaEffects<TParams, TFetched> {
* keep of it there (a linked list row). Never touch the view on screen.
*/
onPurge?: (params: TParams, context: ReplicaSettleContext) => void;
+ /**
+ * Every successful response, including one the guards discard (cleared or
+ * removed entry, superseded query, off-scope) and one `prepareHead` drops.
+ * Use it for per-request bookkeeping that must be released even when the
+ * response is never folded. Not called for errors.
+ */
+ onSettled?: (data: TFetched, params: TParams, context: ReplicaSettleContext) => void;
}
export interface ReplicaFetchOptions {
@@ -525,8 +532,14 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
request.removalGeneration !== removalGeneration(scope, key) ||
request.seq <= (retiredThrough.get(request.requestId) ?? 0) ||
!isActiveQuery(request)
- )
+ ) {
+ if (!('error' in outcome)) {
+ // A discarded success still settles the request; release any
+ // per-request bookkeeping even though it is never folded.
+ effects?.onSettled?.(outcome.data, params, { key, scope, source: request.source });
+ }
return dropped;
+ }
if ('error' in outcome) {
// Forwarded even off-scope: the captured `key`/`scope` lets a consumer
@@ -537,6 +550,10 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
return { ...dropped, current: true };
}
+ // Every successful response releases per-request bookkeeping, including
+ // one that ends up off-scope or is dropped by `prepareHead` below.
+ effects?.onSettled?.(outcome.data, params, { key, scope, source: request.source });
+
if (!isActive) {
// Off-scope: never fold a value into the scope on screen. A terminal
// absence still purges its own scope's row (`remove` routes it there), so
diff --git a/src/features/AgentMockDevtools/hooks/createMockStoreInjector.ts b/src/features/AgentMockDevtools/hooks/createMockStoreInjector.ts
index 8c437bd645b..79bd78a1f0c 100644
--- a/src/features/AgentMockDevtools/hooks/createMockStoreInjector.ts
+++ b/src/features/AgentMockDevtools/hooks/createMockStoreInjector.ts
@@ -175,6 +175,7 @@ export const createMockStoreInjector = (get: () => ChatStore, params: MockStoreI
},
},
dispatchContext,
+ { creationOrigin: 'client' },
);
break;
}
@@ -265,6 +266,7 @@ export const createMockStoreInjector = (get: () => ChatStore, params: MockStoreI
value: { error: messageError },
},
dispatchContext,
+ { creationOrigin: 'client' },
);
break;
}
diff --git a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
index 62d7771b5c7..bb6090d7f69 100644
--- a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
+++ b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
@@ -494,6 +494,7 @@ describe('useAgentMockPlayer', () => {
},
},
{ operationId: secondOperationId },
+ { creationOrigin: 'client' },
);
expect(secondHandle.player.seekToEventIndex).toHaveBeenCalledWith(2);
expect(secondHandle.start).toHaveBeenCalledTimes(1);
diff --git a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts
index f25f8719375..c5d7a8b5782 100644
--- a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts
+++ b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts
@@ -169,6 +169,7 @@ const resetAssistantProjection = (
},
},
{ operationId },
+ { creationOrigin: 'client' },
);
}
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
index af7067d897a..4db407c86f4 100644
--- a/src/features/Conversation/store/slices/data/action.ts
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -81,7 +81,10 @@ export interface DataAction {
* Dispatch message updates for optimistic UI updates
* This method updates the frontend state without persisting to database
*/
- internal_dispatchMessage: (payload: MessageDispatch) => void;
+ internal_dispatchMessage: (
+ payload: MessageDispatch,
+ options?: { creationOrigin?: 'client' | 'server' },
+ ) => void;
/** Mirror the chat store bucket of the current context into this store. */
internal_syncChatTranscript: () => void;
@@ -170,7 +173,7 @@ export const dataSlice: StateCreator<
};
return {
- internal_dispatchMessage: (payload) => {
+ internal_dispatchMessage: (payload, options) => {
const { context, transcriptSource } = get();
log(
@@ -201,7 +204,9 @@ export const dataSlice: StateCreator<
}
if (transcriptSource === 'chat') {
- useChatStore.getState().internal_dispatchMessage(payload, { conversationContext: context });
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(payload, { conversationContext: context }, options);
// Read the write back now, whether or not a mounted mirror subscribes.
get().internal_syncChatTranscript();
return;
diff --git a/src/features/Conversation/store/slices/message/action/crud.contextSwitch.test.ts b/src/features/Conversation/store/slices/message/action/crud.contextSwitch.test.ts
new file mode 100644
index 00000000000..ff887a52b41
--- /dev/null
+++ b/src/features/Conversation/store/slices/message/action/crud.contextSwitch.test.ts
@@ -0,0 +1,219 @@
+import { type UIChatMessage } from '@lobechat/types';
+import { act } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import * as messageServiceModule from '@/services/message';
+import { useChatStore } from '@/store/chat';
+import { getMessageTranscript } from '@/store/chat/slices/message/transcript';
+import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { type ConversationContext } from '../../../../types';
+import { createStore } from '../../../index';
+
+// Mock conversation-flow parse so createStore initialization never reaches a real parser.
+vi.mock('@lobechat/conversation-flow', () => ({
+ parse: (messages: UIChatMessage[]) => {
+ const messageMap: Record<string, UIChatMessage> = {};
+ for (const msg of messages) messageMap[msg.id] = msg;
+ const flatList = [...messages].sort((a, b) => a.createdAt - b.createdAt);
+ return { flatList, messageMap };
+ },
+}));
+
+const createTestStore = (context?: Partial<ConversationContext>) =>
+ createStore({
+ context: {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ threadId: null,
+ ...context,
+ },
+ });
+
+describe('createMessage across a conversation switch', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('settles a late success in the context it was created in', async () => {
+ let resolveCreate!: (result: any) => void;
+ vi.spyOn(messageServiceModule.messageService, 'createMessage').mockReturnValue(
+ new Promise((resolve) => {
+ resolveCreate = resolve;
+ }),
+ );
+
+ const oldContext = {
+ agentId: 'test-session',
+ threadId: null,
+ topicId: 'topic-old',
+ };
+ const currentContext = {
+ agentId: 'test-session',
+ threadId: null,
+ topicId: 'topic-current',
+ };
+ const currentMessages: UIChatMessage[] = [
+ {
+ content: 'current topic',
+ createdAt: 2000,
+ id: 'msg-current',
+ role: 'user',
+ updatedAt: 2000,
+ },
+ ];
+ const store = createTestStore(oldContext);
+
+ const createPromise = store.getState().createMessage({
+ content: 'old topic message',
+ role: 'user',
+ });
+ const oldBucketKey = messageMapKey(oldContext);
+ const tempId = useChatStore.getState().dbMessagesMap[oldBucketKey]?.[0]?.id;
+ expect(tempId).toMatch(/^tmp_/);
+
+ store.setState({
+ context: currentContext,
+ dbMessages: currentMessages,
+ displayMessages: currentMessages,
+ messageLoadingIds: [],
+ messagesInit: true,
+ });
+
+ let result: string | undefined;
+ await act(async () => {
+ resolveCreate({
+ id: 'msg-old',
+ messages: [
+ {
+ content: 'late old topic result',
+ createdAt: 1000,
+ id: 'msg-old',
+ role: 'user',
+ updatedAt: 1000,
+ },
+ ],
+ });
+ result = await createPromise;
+ });
+
+ expect(result).toBeUndefined();
+ expect(store.getState().dbMessages).toEqual(currentMessages);
+
+ // The temp row lives in the context it was created in, so the late
+ // success settles that bucket instead of leaving a ghost behind.
+ const settled = useChatStore.getState().dbMessagesMap[oldBucketKey];
+ expect(settled?.map((message) => message.id)).toEqual(['msg-old']);
+ const transcript = getMessageTranscript(useChatStore.setState, useChatStore.getState);
+ expect(transcript.debugUnconfirmedClientIds()).not.toContain(tempId);
+ });
+
+ it('settles a late failure in the context it was created in', async () => {
+ let rejectCreate!: (error: Error) => void;
+ vi.spyOn(messageServiceModule.messageService, 'createMessage').mockReturnValue(
+ new Promise((_, reject) => {
+ rejectCreate = reject;
+ }) as any,
+ );
+
+ const oldContext = {
+ agentId: 'test-session',
+ threadId: null,
+ topicId: 'topic-old',
+ };
+ const currentContext = {
+ agentId: 'test-session',
+ threadId: null,
+ topicId: 'topic-current',
+ };
+ const store = createTestStore(oldContext);
+
+ const createPromise = store.getState().createMessage({
+ content: 'old topic message',
+ role: 'user',
+ });
+ const oldBucketKey = messageMapKey(oldContext);
+ const tempId = useChatStore.getState().dbMessagesMap[oldBucketKey]?.[0]?.id;
+
+ store.setState({
+ context: currentContext,
+ dbMessages: [],
+ displayMessages: [],
+ messageLoadingIds: [],
+ messagesInit: true,
+ });
+
+ await act(async () => {
+ rejectCreate(new Error('Creation failed'));
+ await createPromise;
+ });
+
+ // The failed row is settled where it lives, not left as a sending ghost.
+ const settled = useChatStore.getState().dbMessagesMap[oldBucketKey];
+ expect(settled?.[0].id).toBe(tempId);
+ expect(settled?.[0].error).toBeDefined();
+ });
+
+ it('does not restore a conversation evicted while a create was pending', async () => {
+ let resolveCreate!: (result: any) => void;
+ vi.spyOn(messageServiceModule.messageService, 'createMessage').mockReturnValue(
+ new Promise((resolve) => {
+ resolveCreate = resolve;
+ }),
+ );
+
+ const oldContext = {
+ agentId: 'test-session',
+ threadId: null,
+ topicId: 'topic-old',
+ };
+ const currentContext = {
+ agentId: 'test-session',
+ threadId: null,
+ topicId: 'topic-current',
+ };
+ const store = createTestStore(oldContext);
+
+ const createPromise = store.getState().createMessage({
+ content: 'old topic message',
+ role: 'user',
+ });
+ const oldBucketKey = messageMapKey(oldContext);
+ expect(useChatStore.getState().dbMessagesMap[oldBucketKey]).toBeDefined();
+
+ store.setState({
+ context: currentContext,
+ dbMessages: [],
+ displayMessages: [],
+ messageLoadingIds: [],
+ messagesInit: true,
+ });
+
+ await act(() => evictMessageCache((ctx) => ctx.topicId === 'topic-old'));
+ expect(useChatStore.getState().dbMessagesMap[oldBucketKey]).toBeUndefined();
+
+ await act(async () => {
+ resolveCreate({
+ id: 'msg-old',
+ messages: [
+ {
+ content: 'late old topic result',
+ createdAt: 1000,
+ id: 'msg-old',
+ role: 'user',
+ updatedAt: 1000,
+ },
+ ],
+ });
+ await createPromise;
+ });
+
+ // The late response must not recreate the deleted transcript.
+ expect(useChatStore.getState().dbMessagesMap[oldBucketKey]).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/store/slices/message/action/crud.test.ts b/src/features/Conversation/store/slices/message/action/crud.test.ts
index 52bce7a08ab..bf9e2cc9b2c 100644
--- a/src/features/Conversation/store/slices/message/action/crud.test.ts
+++ b/src/features/Conversation/store/slices/message/action/crud.test.ts
@@ -3,6 +3,7 @@ import { act } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as messageServiceModule from '@/services/message';
+import { useChatStore } from '@/store/chat';
import { type ConversationContext } from '../../../../types';
import { createStore } from '../../../index';
@@ -96,68 +97,6 @@ describe('Message CRUD Actions', () => {
expect(result).toBeUndefined();
});
-
- it('discards a create result that resolves after switching conversations', async () => {
- let resolveCreate!: (result: any) => void;
- vi.spyOn(messageServiceModule.messageService, 'createMessage').mockReturnValue(
- new Promise((resolve) => {
- resolveCreate = resolve;
- }),
- );
-
- const oldContext = {
- agentId: 'test-session',
- threadId: null,
- topicId: 'topic-old',
- };
- const currentContext = {
- agentId: 'test-session',
- threadId: null,
- topicId: 'topic-current',
- };
- const currentMessages: UIChatMessage[] = [
- {
- content: 'current topic',
- createdAt: 2000,
- id: 'msg-current',
- role: 'user',
- updatedAt: 2000,
- },
- ];
- const store = createTestStore(oldContext);
-
- const createPromise = store.getState().createMessage({
- content: 'old topic message',
- role: 'user',
- });
- store.setState({
- context: currentContext,
- dbMessages: currentMessages,
- displayMessages: currentMessages,
- messageLoadingIds: [],
- messagesInit: true,
- });
-
- let result: string | undefined;
- await act(async () => {
- resolveCreate({
- id: 'msg-old',
- messages: [
- {
- content: 'late old topic result',
- createdAt: 1000,
- id: 'msg-old',
- role: 'user',
- updatedAt: 1000,
- },
- ],
- });
- result = await createPromise;
- });
-
- expect(result).toBeUndefined();
- expect(store.getState().dbMessages).toEqual(currentMessages);
- });
});
describe('createTempMessage', () => {
@@ -179,6 +118,25 @@ describe('Message CRUD Actions', () => {
expect(state.displayMessages.length).toBe(1);
expect(state.displayMessages[0].content).toBe('Temp message');
});
+
+ it('marks the temp row as client-created when forwarding to the chat store', () => {
+ const store = createTestStore();
+ const dispatch = vi.spyOn(useChatStore.getState(), 'internal_dispatchMessage');
+
+ act(() => {
+ store.getState().createTempMessage({
+ content: 'Temp message',
+ role: 'user',
+ sessionId: 'test-session',
+ });
+ });
+
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'createMessage' }),
+ expect.any(Object),
+ { creationOrigin: 'client' },
+ );
+ });
});
describe('deleteMessage', () => {
diff --git a/src/features/Conversation/store/slices/message/action/crud.ts b/src/features/Conversation/store/slices/message/action/crud.ts
index f48f1f5eb06..ae907c3b746 100644
--- a/src/features/Conversation/store/slices/message/action/crud.ts
+++ b/src/features/Conversation/store/slices/message/action/crud.ts
@@ -17,6 +17,8 @@ import isEqual from 'fast-deep-equal';
import { type StateCreator } from 'zustand';
import { messageService } from '@/services/message';
+import { useChatStore } from '@/store/chat';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { type Store as ConversationStore } from '../../../action';
import { isSameConversationContext } from '../../../utils/contextGuard';
@@ -200,8 +202,13 @@ export const messageCRUDSlice: StateCreator<
// ===== Create ===== //
createMessage: async (params) => {
- const { context, internal_dispatchMessage, replaceMessages, internal_toggleMessageLoading } =
- get();
+ const {
+ context,
+ internal_dispatchMessage,
+ replaceMessages,
+ internal_toggleMessageLoading,
+ transcriptSource,
+ } = get();
// Create temp message for optimistic update
const tempId = get().createTempMessage(params);
@@ -214,30 +221,51 @@ export const messageCRUDSlice: StateCreator<
topicId: context.topicId ?? undefined,
});
- // Replace with server response
- if (!isSameConversationContext(context, get().context)) return undefined;
- replaceMessages(result.messages, { expectedContext: context });
-
+ // Settle in the context the temp row was created in, even if the user
+ // switched conversations while the request was in flight: the chat
+ // bucket for that context still holds the optimistic row.
+ const stillCurrent = isSameConversationContext(context, get().context);
+ // The conversation may have been deleted while the create was pending.
+ // A late response must not recreate its transcript.
+ const targetExists =
+ transcriptSource !== 'chat' ||
+ !!useChatStore.getState().dbMessagesMap[messageMapKey(context)];
+
+ if (targetExists) {
+ if (stillCurrent) {
+ replaceMessages(result.messages, { expectedContext: context });
+ } else if (transcriptSource === 'chat') {
+ // Don't route through the Conversation store here: it would sync the
+ // conversation now on screen from that other bucket.
+ useChatStore.getState().replaceMessages(result.messages, { context });
+ }
+ }
internal_toggleMessageLoading(false, tempId);
- return result.id;
+ return stillCurrent ? result.id : undefined;
} catch (e) {
- if (!isSameConversationContext(context, get().context)) return undefined;
-
internal_toggleMessageLoading(false, tempId);
- // Update temp message with error
- internal_dispatchMessage({
- id: tempId,
- type: 'updateMessage',
- value: {
- error: {
- body: e,
- message: (e as Error).message,
- type: ChatErrorType.CreateMessageError,
- },
+ const value = {
+ error: {
+ body: e,
+ message: (e as Error).message,
+ type: ChatErrorType.CreateMessageError,
},
- });
+ };
+
+ if (transcriptSource === 'chat') {
+ // Target the captured context directly: the Conversation store's
+ // dispatch would otherwise write the error into the new conversation.
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: tempId, type: 'updateMessage', value },
+ { conversationContext: context },
+ );
+ } else if (isSameConversationContext(context, get().context)) {
+ internal_dispatchMessage({ id: tempId, type: 'updateMessage', value });
+ }
return undefined;
}
@@ -247,11 +275,14 @@ export const messageCRUDSlice: StateCreator<
const { internal_dispatchMessage } = get();
const tempId = 'tmp_' + nanoid();
- internal_dispatchMessage({
- id: tempId,
- type: 'createMessage',
- value: params,
- });
+ internal_dispatchMessage(
+ {
+ id: tempId,
+ type: 'createMessage',
+ value: params,
+ },
+ { creationOrigin: 'client' },
+ );
return tempId;
},
diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts
index aaba19a3b49..bf7a5545af8 100644
--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts
+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts
@@ -61,6 +61,7 @@ const createStore = (messages: UIChatMessage[]) => {
associateMessageWithOperation: vi.fn(),
completeOperation: vi.fn(),
dbMessagesMap,
+ internal_confirmClientMessages: vi.fn(),
internal_dispatchMessage: vi.fn((action: any) => {
if (action.type === 'createMessage') {
dbMessagesMap[messageKey].push(action.value);
diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockStore.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockStore.ts
index 3aa90a963ce..6b658aede48 100644
--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockStore.ts
+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockStore.ts
@@ -58,6 +58,7 @@ export const createMockStore = (overrides: Partial<ChatStore> = {}): ChatStore =
}),
// AI chat methods
+ internal_confirmClientMessages: vi.fn(),
internal_dispatchMessage: vi.fn().mockImplementation((payload, context) => {
if (payload.type !== 'createMessage') return;
diff --git a/src/store/chat/agents/transports/ClientMessageTransport.test.ts b/src/store/chat/agents/transports/ClientMessageTransport.test.ts
index 97196055bcf..f6ba604b7e6 100644
--- a/src/store/chat/agents/transports/ClientMessageTransport.test.ts
+++ b/src/store/chat/agents/transports/ClientMessageTransport.test.ts
@@ -9,6 +9,7 @@ import { ClientMessageTransport } from './ClientMessageTransport';
const createStore = () =>
({
dbMessagesMap: { 'message-key': [] },
+ internal_confirmClientMessages: vi.fn(),
internal_dispatchMessage: vi.fn(),
operations: {
'operation-1': {
@@ -132,10 +133,13 @@ describe('ClientMessageTransport', () => {
expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
{ id: message.id, type: 'createMessage', value: { ...params, id: message.id } },
{ operationId: 'operation-1' },
+ { creationOrigin: 'client' },
);
expect(messageService.batchMutate).toHaveBeenCalledWith([
{ message: { ...params, id: message.id }, type: 'createMessage' },
]);
+ // The quiet write returns no snapshot, so the acknowledgement confirms the row.
+ expect(store.internal_confirmClientMessages).toHaveBeenCalledWith([message.id]);
expect(store.optimisticCreateMessage).not.toHaveBeenCalled();
expect(store.replaceMessages).not.toHaveBeenCalled();
});
@@ -200,6 +204,7 @@ describe('ClientMessageTransport', () => {
role: 'assistant',
}),
).rejects.toThrow('Failed to create assistant message');
+ expect(store.internal_confirmClientMessages).not.toHaveBeenCalled();
expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(
expect.objectContaining({
diff --git a/src/store/chat/agents/transports/ClientMessageTransport.ts b/src/store/chat/agents/transports/ClientMessageTransport.ts
index c2fcf5481f3..a128664e4e2 100644
--- a/src/store/chat/agents/transports/ClientMessageTransport.ts
+++ b/src/store/chat/agents/transports/ClientMessageTransport.ts
@@ -166,6 +166,7 @@ export class ClientMessageTransport implements MessageTransport {
store.internal_dispatchMessage(
{ id, type: 'createMessage', value: { ...message } },
optimisticContext,
+ { creationOrigin: 'client' },
);
try {
@@ -188,6 +189,7 @@ export class ClientMessageTransport implements MessageTransport {
);
throw createError;
}
+ store.internal_confirmClientMessages([id]);
return message;
}
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 5a08dd7fa6f..8039cf6eba8 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -318,6 +318,7 @@ describe('ConversationLifecycle actions', () => {
}),
}),
expect.any(Object),
+ { creationOrigin: 'client' },
);
expect(createCompressionGroupSpy).toHaveBeenCalledWith({
agentId,
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 1fc807c2ac8..f06b64957f3 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -2403,18 +2403,15 @@ export class ConversationLifecycleActionImpl {
});
// Immediate UI feedback: render a pending compressed group from the first frame
- this.#get().internal_dispatchMessage(
- {
+ this.#get().internal_createClientMessage(
+ tempId,
+ createPendingCompressedGroup({
+ agentId,
+ groupId: context.groupId,
id: tempId,
- type: 'createMessage',
- value: createPendingCompressedGroup({
- agentId,
- groupId: context.groupId,
- id: tempId,
- threadId: context.threadId,
- topicId,
- }) as any,
- },
+ threadId: context.threadId,
+ topicId,
+ }) as any,
{ operationId },
);
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index bcf3154da3c..cc405b4a398 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -103,6 +103,10 @@ import {
shouldHydrateResumeReplay,
} from './resumeReplay';
import { buildLobeHubSessionEnv } from './sessionEnv';
+import {
+ createSubagentStoreDispatcher,
+ type SubagentStoreDispatcher,
+} from './subagentStoreDispatcher';
/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */
const generateThreadId = () => `thd_${createNanoId(16)()}`;
@@ -373,36 +377,6 @@ const subscribeBroadcasts = (
};
};
-/**
- * Thread-scoped in-memory dispatcher for a single subagent run. The
- * caller binds it to a per-spawn sub-operation whose
- * `OperationContext.threadId` + `scope: 'thread'` cause
- * `internal_dispatchMessage` to route every create/update into the
- * Thread's `messagesMap` bucket through the SAME context-resolution
- * path the main agent uses β€” no special-cased threadId override on the
- * dispatch boundary.
- *
- * Subagent streaming mirrors the main agent's gateway-handler flow:
- * DB writes are authoritative (see `persistSubagent*Chunk` +
- * `persistToolBatch`) and these dispatches feed the UI the same content
- * as tokens arrive, so the Thread view streams with the same cadence as
- * the main bubble. `fetchAndReplaceMessages` (main-topic scoped) never
- * refreshes the thread bucket, so without these dispatches the Thread
- * would only show stale DB state until the user re-navigates.
- */
-interface SubagentStoreDispatcher {
- /** Push a new message into the thread bucket (user / assistant / tool). */
- create: (msg: UIChatMessage) => void;
- /** Atomically replace pluginState and advance its optimistic watermark. */
- replacePluginState: (
- id: string,
- pluginState: Record<string, unknown>,
- metadata: NonNullable<UIChatMessage['metadata']>,
- ) => void;
- /** Update a message already in the thread bucket by id. */
- update: (id: string, value: Partial<UIChatMessage>) => void;
-}
-
const HETERO_TERMINAL_PERSIST_DRAIN_TIMEOUT_MS = 10_000;
const HETERO_TERMINAL_EVENT_GRACE_TIMEOUT_MS = 3_000;
@@ -513,6 +487,13 @@ export const executeHeterogeneousAgent = async (
} = params;
// Navigation can move to another workspace during the awaits below.
const workspaceId = 'workspaceId' in params ? params.workspaceId : getActiveWorkspaceId();
+
+ /** Rows this executor creates; the write batcher persists them later. */
+ const createClientRow = (id: string, value: any, dispatchContext: { operationId: string }) =>
+ get().internal_dispatchMessage({ id, type: 'createMessage', value }, dispatchContext, {
+ creationOrigin: 'client',
+ });
+
let outcome: HeterogeneousAgentExecutionOutcome | undefined;
/** Set by `persistTerminalError`; surfaced on the outcome, see its doc. */
let terminalErrorPersisted = false;
@@ -988,6 +969,7 @@ export const executeHeterogeneousAgent = async (
messageService as { batchMutate?: (operations: MessageBatchOperation[]) => Promise<any> }
).batchMutate,
createMessage: messageService.createMessage,
+ onCreated: get().internal_confirmClientMessages,
updateMessage: messageService.updateMessage,
updateToolMessage: messageService.updateToolMessage,
});
@@ -1207,28 +1189,8 @@ export const executeHeterogeneousAgent = async (
parentOperationId: operationId,
type: 'subagentThread',
});
- const dispatchCtx = { operationId: subOp.operationId };
return {
- stream: {
- create(msg) {
- get().internal_dispatchMessage(
- { id: msg.id, type: 'createMessage', value: msg as any },
- dispatchCtx,
- );
- },
- replacePluginState(id, pluginState, metadata) {
- get().internal_dispatchMessage(
- { id, metadata, type: 'replaceMessagePluginState', value: pluginState },
- dispatchCtx,
- );
- },
- update(id, value) {
- get().internal_dispatchMessage(
- { id, type: 'updateMessage', value: value as any },
- dispatchCtx,
- );
- },
- },
+ stream: createSubagentStoreDispatcher(get, { operationId: subOp.operationId }),
subOperationId: subOp.operationId,
};
};
@@ -1640,10 +1602,7 @@ export const executeHeterogeneousAgent = async (
console.error('[HeterogeneousAgent] Failed to create step assistant:', err);
pendingCreateLedger.add(intent.messageId, messageToCreate);
});
- get().internal_dispatchMessage(
- { id: intent.messageId, type: 'createMessage', value: messageToCreate },
- { operationId },
- );
+ createClientRow(intent.messageId, messageToCreate, { operationId });
// Associate so cancellation / cleanup tracks the new step's message.
get().associateMessageWithOperation(intent.messageId, operationId);
return;
@@ -1759,10 +1718,7 @@ export const executeHeterogeneousAgent = async (
});
toolMsgIdByCallId.set(x.payload.id, x.toolMessageId);
mainToolCallIds.add(x.payload.id);
- get().internal_dispatchMessage(
- { id: x.toolMessageId, type: 'createMessage', value: toolMsg },
- { operationId },
- );
+ createClientRow(x.toolMessageId, toolMsg, { operationId });
}
// Phase 3: backfill result_msg_id on assistant.tools[].
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.test.ts
index 5c4da0fd903..ee0c7d7e6f3 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.test.ts
@@ -42,6 +42,32 @@ describe('createMessageWriteBatcher', () => {
expect(deps.batchMutate).not.toHaveBeenCalled();
});
+ it('reports the creates the server acknowledged, skipping failed ones', async () => {
+ const deps = { ...createDeps(), onCreated: vi.fn() };
+ deps.batchMutate.mockResolvedValue({
+ results: [{ index: 1, success: false }],
+ success: false,
+ });
+ const batcher = createMessageWriteBatcher(deps);
+
+ batcher.enqueueCreateMessage(createRow('msg-ok'));
+ batcher.enqueueCreateMessage(createRow('msg-failed'), vi.fn());
+ batcher.enqueueUpdateMessage('msg-ok', { content: 'x' });
+ await batcher.flush('test');
+
+ expect(deps.onCreated).toHaveBeenCalledWith(['msg-ok']);
+ });
+
+ it('reports an acknowledged create without batchMutate', async () => {
+ const deps = { ...createDeps(), batchMutate: undefined, onCreated: vi.fn() };
+ const batcher = createMessageWriteBatcher(deps);
+
+ batcher.enqueueCreateMessage(createRow('msg-a'));
+ await batcher.flush('test');
+
+ expect(deps.onCreated).toHaveBeenCalledWith(['msg-a']);
+ });
+
/**
* The semantic that made subagent rows die against `messages_parent_id_messages_id_fk`:
* a failed create is reported ONLY through `onFailure`, and `flush` still resolves.
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.ts
index 080429b1612..521c1087945 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.ts
@@ -58,6 +58,8 @@ const mergeMessageUpdateValue = (
export const createMessageWriteBatcher = (deps: {
batchMutate?: (operations: MessageBatchOperation[]) => Promise<any>;
createMessage: typeof messageService.createMessage;
+ /** Ids of rows whose create the server acknowledged. */
+ onCreated?: (ids: string[]) => void;
updateMessage: typeof messageService.updateMessage;
updateToolMessage: typeof messageService.updateToolMessage;
}) => {
@@ -75,9 +77,17 @@ export const createMessageWriteBatcher = (deps: {
operation.onFailure?.(error);
};
+ const reportCreated = (succeeded: QueuedMessageWriteOperation[]) => {
+ const ids = succeeded.flatMap((operation) =>
+ operation.type === 'createMessage' && operation.message.id ? [operation.message.id] : [],
+ );
+ if (ids.length > 0) deps.onCreated?.(ids);
+ };
+
const runIndividual = async (operation: QueuedMessageWriteOperation) => {
if (operation.type === 'createMessage') {
await deps.createMessage(operation.message);
+ reportCreated([operation]);
return;
}
@@ -108,6 +118,7 @@ export const createMessageWriteBatcher = (deps: {
for (const index of failedIndexes) {
notifyFailure(batch[index], result);
}
+ reportCreated(batch.filter((_, index) => !failedIndexes.has(index)));
return;
} catch (err) {
console.error('[HeterogeneousAgent] Failed to flush message write batch:', err);
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/subagentStoreDispatcher.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/subagentStoreDispatcher.test.ts
new file mode 100644
index 00000000000..f0652b846fe
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/subagentStoreDispatcher.test.ts
@@ -0,0 +1,51 @@
+import { type UIChatMessage } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat';
+import { getMessageTranscript } from '@/store/chat/slices/message/transcript';
+
+import { resetTranscripts } from '../../../../message/actions/testUtils';
+import { createSubagentStoreDispatcher } from './subagentStoreDispatcher';
+
+const threadContext = {
+ agentId: 'agent-1',
+ scope: 'thread' as const,
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+};
+
+const row: UIChatMessage = {
+ content: '',
+ createdAt: 1,
+ id: 'msg_subagent',
+ role: 'assistant',
+ threadId: 'thread-1',
+ updatedAt: 1,
+};
+
+describe('createSubagentStoreDispatcher', () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ resetTranscripts();
+ });
+
+ it('inserts already-persisted subagent rows as server-known', () => {
+ const { operationId } = useChatStore.getState().startOperation({
+ context: threadContext,
+ type: 'subagentThread',
+ });
+ const dispatch = vi.spyOn(useChatStore.getState(), 'internal_dispatchMessage');
+ const stream = createSubagentStoreDispatcher(useChatStore.getState, { operationId });
+
+ stream.create(row);
+
+ expect(dispatch).toHaveBeenCalledWith(
+ { id: row.id, type: 'createMessage', value: row },
+ { operationId },
+ { creationOrigin: 'server' },
+ );
+ // A later read that omits the row (a remote delete) stays authoritative.
+ const transcript = getMessageTranscript(useChatStore.setState, useChatStore.getState);
+ expect(transcript.debugUnconfirmedClientIds()).not.toContain(row.id);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/subagentStoreDispatcher.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/subagentStoreDispatcher.ts
new file mode 100644
index 00000000000..08efb3fd634
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/subagentStoreDispatcher.ts
@@ -0,0 +1,63 @@
+import { type UIChatMessage } from '@lobechat/types';
+
+import { type ChatStore } from '@/store/chat/store';
+
+/**
+ * Thread-scoped in-memory dispatcher for a single subagent run. The
+ * caller binds it to a per-spawn sub-operation whose
+ * `OperationContext.threadId` + `scope: 'thread'` cause
+ * `internal_dispatchMessage` to route every create/update into the
+ * Thread's `messagesMap` bucket through the SAME context-resolution
+ * path the main agent uses β€” no special-cased threadId override on the
+ * dispatch boundary.
+ *
+ * Subagent streaming mirrors the main agent's gateway-handler flow:
+ * DB writes are authoritative (see `persistSubagent*Chunk` +
+ * `persistToolBatch`) and these dispatches feed the UI the same content
+ * as tokens arrive, so the Thread view streams with the same cadence as
+ * the main bubble. `fetchAndReplaceMessages` (main-topic scoped) never
+ * refreshes the thread bucket, so without these dispatches the Thread
+ * would only show stale DB state until the user re-navigates.
+ */
+export interface SubagentStoreDispatcher {
+ /** Push a new message into the thread bucket (user / assistant / tool). */
+ create: (msg: UIChatMessage) => void;
+ /** Atomically replace pluginState and advance its optimistic watermark. */
+ replacePluginState: (
+ id: string,
+ pluginState: Record<string, unknown>,
+ metadata: NonNullable<UIChatMessage['metadata']>,
+ ) => void;
+ /** Update a message already in the thread bucket by id. */
+ update: (id: string, value: Partial<UIChatMessage>) => void;
+}
+
+/**
+ * Bind a subagent dispatcher to its sub-operation. Every row reaching
+ * `create` was already written by `mutateMessageBatch`, so it enters the
+ * transcript as server-known: a later read that omits it is authoritative.
+ */
+export const createSubagentStoreDispatcher = (
+ get: () => ChatStore,
+ dispatchContext: { operationId: string },
+): SubagentStoreDispatcher => ({
+ create(msg) {
+ get().internal_dispatchMessage(
+ { id: msg.id, type: 'createMessage', value: msg as any },
+ dispatchContext,
+ { creationOrigin: 'server' },
+ );
+ },
+ replacePluginState(id, pluginState, metadata) {
+ get().internal_dispatchMessage(
+ { id, metadata, type: 'replaceMessagePluginState', value: pluginState },
+ dispatchContext,
+ );
+ },
+ update(id, value) {
+ get().internal_dispatchMessage(
+ { id, type: 'updateMessage', value: value as any },
+ dispatchContext,
+ );
+ },
+});
diff --git a/src/store/chat/slices/message/actions/internals.ts b/src/store/chat/slices/message/actions/internals.ts
index de25db3b16c..d8a5129d10e 100644
--- a/src/store/chat/slices/message/actions/internals.ts
+++ b/src/store/chat/slices/message/actions/internals.ts
@@ -39,7 +39,17 @@ export class MessageInternalsActionImpl {
this.#get = get;
}
- internal_dispatchMessage = (payload: MessageDispatch, context?: MessageDispatchContext): void => {
+ internal_dispatchMessage = (
+ payload: MessageDispatch,
+ context?: MessageDispatchContext,
+ /**
+ * Where a `createMessage` row came from. Only a client-created row can be
+ * missing from a read that predates its server persistence; a server row
+ * (e.g. a gateway `stream_start` shell) is authoritative from the start.
+ * Defaults to `server` so an unlabelled insert is never preserved.
+ */
+ options?: { creationOrigin?: 'client' | 'server' },
+ ): void => {
// Get full conversation context (including scope) from operation or global state
const ctx =
context?.conversationContext ?? this.#get().internal_getConversationContext(context);
@@ -68,10 +78,39 @@ export class MessageInternalsActionImpl {
log('[internal_dispatchMessage] %s | key=%s', payload.type, messagesKey);
const transcript = getMessageTranscript(this.#set, this.#get);
- transcript.commit(ctx, reconciled, true);
+ transcript.commit(
+ ctx,
+ reconciled,
+ true,
+ payload.type === 'createMessage' && options?.creationOrigin === 'client'
+ ? payload.id
+ : undefined,
+ );
+
+ // A locally deleted client row can no longer be preserved. Its dispatch
+ // removes it before any server replacement can observe the removal.
+ if (payload.type === 'deleteMessage') transcript.forgetClientRows([payload.id]);
+ else if (payload.type === 'deleteMessages') transcript.forgetClientRows(payload.ids);
transcript.settle(ctx);
};
+ /** Insert a row this client created, so a stale read cannot drop it before it persists. */
+ internal_createClientMessage = (
+ id: string,
+ value: Extract<MessageDispatch, { type: 'createMessage' }>['value'],
+ context?: MessageDispatchContext,
+ ): void => {
+ this.#get().internal_dispatchMessage({ id, type: 'createMessage', value }, context, {
+ creationOrigin: 'client',
+ });
+ };
+
+ /** The server persisted these client-created rows (a quiet write, no snapshot back). */
+ internal_confirmClientMessages = (ids: string[]): void => {
+ if (ids.length === 0) return;
+ getMessageTranscript(this.#set, this.#get).confirmPersistedRows(ids);
+ };
+
internal_traceMessage = async (id: string, payload: TraceEventPayloads): Promise<void> => {
// tracing the diff of update
const message = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
diff --git a/src/store/chat/slices/message/actions/optimisticUpdate.ts b/src/store/chat/slices/message/actions/optimisticUpdate.ts
index 5b9b58b7b94..7e213dc30cc 100644
--- a/src/store/chat/slices/message/actions/optimisticUpdate.ts
+++ b/src/store/chat/slices/message/actions/optimisticUpdate.ts
@@ -99,7 +99,9 @@ export class MessageOptimisticUpdateActionImpl {
// use optimistic update to avoid the slow waiting
// use pre-generated tempMessageId if provided, otherwise generate a new one
const tempId = context?.tempMessageId || 'tmp_' + nanoid();
- internal_dispatchMessage({ id: tempId, type: 'createMessage', value: message }, context);
+ internal_dispatchMessage({ id: tempId, type: 'createMessage', value: message }, context, {
+ creationOrigin: 'client',
+ });
return tempId;
};
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index 2cf1acf8a86..27aed066497 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -214,6 +214,18 @@ export class MessageQueryActionImpl {
);
const transcript = getMessageTranscript(this.#set, this.#get);
+ // The server returned these rows, so their optimistic mark is settled even
+ // when the bucket already holds the same list (the commit below is skipped).
+ transcript.confirmServerRows(persistedIncoming);
+ // Rows this replacement removed or remapped (an optimistic `tmp_*` id
+ // replaced by the server id) can never be preserved again; reads issued
+ // before the remap keep protecting the rows that replaced them.
+ const currentIds = new Set(currentMessages.map((message) => message.id));
+ const nextIds = new Set(reconciled.map((message) => message.id));
+ transcript.remapClientRows(
+ [...currentIds].filter((id) => !nextIds.has(id)),
+ persistedIncoming.map((message) => message.id).filter((id) => !currentIds.has(id)),
+ );
// An unchanged bucket still settles: an optimistic dispatch may already
// have applied this exact state in memory while the stored copy is older.
if (!isEqual(reconciled, currentMessages) || !this.#get().dbMessagesMap[messagesKey]) {
diff --git a/src/store/chat/slices/message/actions/transcript.evict.test.ts b/src/store/chat/slices/message/actions/transcript.evict.test.ts
index 10cc41d5d78..c3c86c8afe8 100644
--- a/src/store/chat/slices/message/actions/transcript.evict.test.ts
+++ b/src/store/chat/slices/message/actions/transcript.evict.test.ts
@@ -8,6 +8,7 @@ import { messageListKey } from '@/services/message/cache';
import { conversationMessagesKey, conversationMessagesResource } from '@/services/message/replica';
import { topicService } from '@/services/topic';
import { useChatStore } from '@/store/chat';
+import { getMessageTranscript } from '@/store/chat/slices/message/transcript';
import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
import { resetTranscripts, rowsOf } from './testUtils';
@@ -78,6 +79,23 @@ describe('transcript eviction', () => {
expect(rowsOf(topicB)).toBeDefined();
});
+ it('forgets unconfirmed client rows of an evicted conversation', async () => {
+ // A send that never reached the server, e.g. its create failed.
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: 'tmp_unsent', type: 'createMessage', value: row('tmp_unsent') as any },
+ { conversationContext: topicA },
+ { creationOrigin: 'client' },
+ );
+ const transcript = getMessageTranscript(useChatStore.setState, useChatStore.getState);
+ expect(transcript.debugUnconfirmedClientIds()).toContain('tmp_unsent');
+
+ await act(() => evictMessageCache((ctx) => ctx.topicId === topicA.topicId));
+
+ expect(transcript.debugUnconfirmedClientIds()).not.toContain('tmp_unsent');
+ });
+
it('reaches rows only an earlier session persisted, so they never hydrate again', async () => {
await persist(topicA);
await persist(otherAgent);
diff --git a/src/store/chat/slices/message/actions/transcript.persisted.test.ts b/src/store/chat/slices/message/actions/transcript.persisted.test.ts
new file mode 100644
index 00000000000..c34f5b4fa43
--- /dev/null
+++ b/src/store/chat/slices/message/actions/transcript.persisted.test.ts
@@ -0,0 +1,118 @@
+import { type UIChatMessage } from '@lobechat/types';
+import { act, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { messageService } from '@/services/message';
+import { clearMessageListClientCacheState } from '@/services/message/cache';
+import { useChatStore } from '@/store/chat';
+import { getMessageTranscript } from '@/store/chat/slices/message/transcript';
+
+import { resetTranscripts, rowsOf, seedRows, syncMessages } from './testUtils';
+
+vi.mock('@lobechat/conversation-flow', () => ({
+ parse: (messages: UIChatMessage[]) => ({
+ flatList: [...messages].sort((a, b) => a.createdAt - b.createdAt),
+ messageMap: Object.fromEntries(messages.map((m) => [m.id, m])),
+ }),
+}));
+
+vi.mock('@/services/message', () => {
+ const getMessages = vi.fn();
+ return {
+ messageService: {
+ getEarlierMessages: vi.fn(),
+ getMessageListPage: vi.fn((params) => getMessages(params)),
+ getMessages,
+ },
+ };
+});
+
+vi.mock('@/services/topic', () => ({ topicService: { getTopicDetail: vi.fn() } }));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => undefined,
+ useActiveWorkspaceId: () => undefined,
+}));
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn((key, fetcher, options) => {
+ if (key) fetcher?.().then((data: unknown) => options?.onSuccess?.(data));
+ return { data: undefined, isValidating: true, mutate: vi.fn() };
+ }),
+}));
+
+const context = { agentId: 'test-session', threadId: null, topicId: 'test-topic' };
+
+const previousReply: UIChatMessage = {
+ id: 'previous-reply',
+ content: 'Previous reply',
+ role: 'assistant',
+ createdAt: 1000,
+ updatedAt: 1000,
+};
+const created: UIChatMessage = {
+ id: 'msg_client',
+ content: '',
+ role: 'assistant',
+ createdAt: 2000,
+ updatedAt: 2000,
+};
+
+/** A runtime row created on the client and written quietly (no snapshot back). */
+const createClientRow = () =>
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: created.id, type: 'createMessage', value: created as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+
+describe('quietly persisted client rows', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ clearMessageListClientCacheState();
+ resetTranscripts();
+ });
+
+ it('drops a persisted row omitted by a read issued after the acknowledgement', async () => {
+ seedRows(context, [previousReply]);
+ createClientRow();
+ useChatStore.getState().internal_confirmClientMessages([created.id]);
+
+ const transcript = getMessageTranscript(useChatStore.setState, useChatStore.getState);
+ expect(transcript.debugUnconfirmedClientIds()).not.toContain(created.id);
+
+ // Deleted on another device before any head read returned it.
+ vi.mocked(messageService.getMessages).mockResolvedValue([previousReply]);
+ syncMessages(context);
+
+ await waitFor(() =>
+ expect(rowsOf(context)?.map((message) => message.id)).toEqual([previousReply.id]),
+ );
+ });
+
+ it('keeps a persisted row for a read issued before the acknowledgement', async () => {
+ let resolveFetch!: (messages: UIChatMessage[]) => void;
+ vi.mocked(messageService.getMessages).mockReturnValue(
+ new Promise((resolve) => {
+ resolveFetch = resolve;
+ }) as Promise<UIChatMessage[]>,
+ );
+ seedRows(context, [previousReply]);
+ syncMessages(context);
+ await waitFor(() => expect(messageService.getMessages).toHaveBeenCalledTimes(1));
+
+ createClientRow();
+ useChatStore.getState().internal_confirmClientMessages([created.id]);
+
+ // That read's snapshot predates the write.
+ await act(async () => {
+ resolveFetch([{ ...previousReply, content: 'Previous reply (fetched)', updatedAt: 1500 }]);
+ });
+
+ await waitFor(() => expect(rowsOf(context)?.[0].content).toBe('Previous reply (fetched)'));
+ expect(rowsOf(context)?.map((message) => message.id)).toEqual([previousReply.id, created.id]);
+ });
+});
diff --git a/src/store/chat/slices/message/actions/transcript.sync.test.ts b/src/store/chat/slices/message/actions/transcript.sync.test.ts
index c0e7af78292..842b05d5a50 100644
--- a/src/store/chat/slices/message/actions/transcript.sync.test.ts
+++ b/src/store/chat/slices/message/actions/transcript.sync.test.ts
@@ -1,19 +1,27 @@
-import type { UIChatMessage } from '@lobechat/types';
+import { type UIChatMessage } from '@lobechat/types';
import { act, waitFor } from '@testing-library/react';
import { unstable_serialize } from 'swr';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { REPLICA_INDEX_KEY } from '@/libs/replica';
import { useClientDataSWR } from '@/libs/swr';
import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';
import { messageService } from '@/services/message';
import {
clearMessageListClientCacheState,
+ invalidateMessageListClientState,
MESSAGE_LIST_VERIFICATION_INTERVAL,
runMessageListQuery,
} from '@/services/message/cache';
-import { conversationMessagesKey } from '@/services/message/replica';
+import {
+ conversationMessagesKey,
+ conversationMessagesResource,
+ transcriptOf,
+} from '@/services/message/replica';
+import { topicService } from '@/services/topic';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
+import { getMessageTranscript } from '@/store/chat/slices/message/transcript';
import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
import { resetTranscripts, rowsOf, seedRows, syncMessages } from './testUtils';
@@ -37,6 +45,8 @@ vi.mock('@/services/message', () => {
};
});
+vi.mock('@/services/topic', () => ({ topicService: { getTopicDetail: vi.fn() } }));
+
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
getActiveWorkspaceId: () => undefined,
useActiveWorkspaceId: () => undefined,
@@ -545,5 +555,610 @@ describe('useFetchMessages', () => {
useChatStore.getState().completeOperation(operationId);
}
});
+
+ it('keeps optimistic rows that were already present when the read started', async () => {
+ const previousReply: UIChatMessage = {
+ id: 'previous-reply',
+ content: 'Previous reply',
+ role: 'assistant',
+ createdAt: 1000,
+ updatedAt: 1000,
+ };
+ const sentUser: UIChatMessage = {
+ id: 'msg_user',
+ content: 'Follow-up question',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+ const sentAssistant: UIChatMessage = {
+ id: 'msg_assistant',
+ content: '...',
+ role: 'assistant',
+ createdAt: 2001,
+ updatedAt: 2001,
+ };
+
+ // The server has not persisted the optimistic pair when a poll or focus
+ // read starts, so its snapshot omits them even though they exist locally.
+ vi.mocked(messageService.getMessages).mockResolvedValue([
+ { ...previousReply, content: 'Previous reply (fetched)', updatedAt: 1500 },
+ ]);
+ seedRows(context, [previousReply]);
+ for (const message of [sentUser, sentAssistant]) {
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: message.id, type: 'createMessage', value: message as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+ }
+
+ syncMessages(context);
+
+ // Wait for the fetched row to land, so the merge has run.
+ await waitFor(() => expect(rowsOf(context)?.[0].content).toBe('Previous reply (fetched)'));
+ expect(rowsOf(context)?.map((message) => message.id)).toEqual([
+ previousReply.id,
+ sentUser.id,
+ sentAssistant.id,
+ ]);
+ });
+
+ it('drops a client row after a server replacement confirms it', async () => {
+ const sent: UIChatMessage = {
+ id: 'msg_user',
+ content: 'Sent',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: sent.id, type: 'createMessage', value: sent as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+ // The server returns the exact list already in memory: the replacement
+ // is unchanged, but it still confirms the optimistic row.
+ const stored = rowsOf(context)!;
+ useChatStore.getState().replaceMessages(stored, { context });
+
+ // A later snapshot omits it (deleted on another device).
+ vi.mocked(messageService.getMessages).mockResolvedValue([]);
+ syncMessages(context);
+
+ await waitFor(() => expect(rowsOf(context)).toEqual([]));
+ });
+
+ it('does not preserve a server-created row omitted by a later read', async () => {
+ const serverShell: UIChatMessage = {
+ id: 'msg_server_shell',
+ content: '',
+ role: 'assistant',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+ // The gateway inserts a shell the server already created.
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: serverShell.id, type: 'createMessage', value: serverShell as any },
+ { conversationContext: context },
+ { creationOrigin: 'server' },
+ );
+
+ vi.mocked(messageService.getMessages).mockResolvedValue([]);
+ syncMessages(context);
+
+ await waitFor(() => expect(rowsOf(context)).toEqual([]));
+ });
+
+ it('forgets a temporary id once a server replacement remaps it', () => {
+ const temp: UIChatMessage = {
+ id: 'tmp_client',
+ content: 'Sent',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: temp.id, type: 'createMessage', value: temp as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+ const transcript = getMessageTranscript(useChatStore.setState, useChatStore.getState);
+ expect(transcript.debugUnconfirmedClientIds()).toContain('tmp_client');
+
+ useChatStore.getState().replaceMessages([{ ...temp, id: 'msg_server' }], { context });
+
+ expect(transcript.debugUnconfirmedClientIds()).not.toContain('tmp_client');
+ });
+
+ it('lets the forced reread drop a row confirmed while awaiting the topic decision', async () => {
+ const question: UIChatMessage = {
+ id: 'question',
+ content: '',
+ role: 'tool',
+ tool_call_id: 'call-1',
+ createdAt: 1,
+ updatedAt: 1,
+ pluginIntervention: { status: 'pending' },
+ };
+ const answered: UIChatMessage = { ...question, pluginIntervention: { status: 'approved' } };
+ const temp: UIChatMessage = {
+ id: 'tmp_client',
+ content: 'Sent',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+ const serverRow: UIChatMessage = { ...temp, id: 'msg_server' };
+
+ let calls = 0;
+ vi.mocked(messageService.getMessages).mockImplementation(() => {
+ calls += 1;
+ // The forced read is the second call; later reads stay in flight so
+ // they cannot repair the row for the assertion.
+ if (calls === 1) return Promise.resolve([answered]);
+ if (calls === 2) return Promise.resolve([]);
+ return new Promise(() => {});
+ });
+
+ let resolveTopic!: () => void;
+ vi.mocked(topicService.getTopicDetail).mockReturnValue(
+ new Promise((resolve) => {
+ resolveTopic = () => resolve(null);
+ }) as ReturnType<typeof topicService.getTopicDetail>,
+ );
+
+ seedRows(context, [question]);
+ syncMessages(context, { syncInterventions: true });
+ await waitFor(() => expect(topicService.getTopicDetail).toHaveBeenCalled());
+
+ // The optimistic row is confirmed and remapped while the fetch is
+ // waiting, so the forced read that starts afterwards can know it.
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: temp.id, type: 'createMessage', value: temp as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+ useChatStore.getState().replaceMessages([serverRow], { context });
+
+ await act(async () => {
+ resolveTopic();
+ });
+
+ // The forced read omits the row (deleted remotely); it is authoritative.
+ await waitFor(() => expect(rowsOf(context)).toEqual([]));
+ });
+
+ it('keeps a client row when two fetches share a result across the topic wait', async () => {
+ const question: UIChatMessage = {
+ id: 'question',
+ content: '',
+ role: 'tool',
+ tool_call_id: 'call-1',
+ createdAt: 1,
+ updatedAt: 1,
+ pluginIntervention: { status: 'pending' },
+ };
+ const answered: UIChatMessage = { ...question, pluginIntervention: { status: 'approved' } };
+ const sent: UIChatMessage = {
+ id: 'msg_user',
+ content: 'Created during the wait',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+
+ let resolveFetch!: (messages: UIChatMessage[]) => void;
+ vi.mocked(messageService.getMessages).mockReturnValue(
+ new Promise((resolve) => {
+ resolveFetch = resolve;
+ }) as Promise<UIChatMessage[]>,
+ );
+
+ let resolveTopic!: () => void;
+ vi.mocked(topicService.getTopicDetail).mockReturnValue(
+ new Promise((resolve) => {
+ resolveTopic = () => resolve({ id: context.topicId, status: 'running' });
+ }) as ReturnType<typeof topicService.getTopicDetail>,
+ );
+
+ seedRows(context, [question]);
+ // Two mounted syncs join the same restarted query result. One record is
+ // subsumed; its fetch must still use the surviving record after copying
+ // the shared array.
+ syncMessages(context, { syncInterventions: true });
+ syncMessages(context, { syncInterventions: true });
+
+ await waitFor(() => expect(messageService.getMessages).toHaveBeenCalled());
+ await act(async () => {
+ resolveFetch([answered]);
+ await Promise.resolve();
+ });
+ await waitFor(() => expect(topicService.getTopicDetail).toHaveBeenCalled());
+
+ // The row lands after registration, so only the surviving record sees it.
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: sent.id, type: 'createMessage', value: sent as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+
+ await act(async () => {
+ resolveTopic();
+ });
+
+ await waitFor(() => expect(rowsOf(context)?.map((message) => message.id)).toContain(sent.id));
+ });
+
+ it('forgets an unconfirmed id when the local row is deleted', () => {
+ const temp: UIChatMessage = {
+ id: 'tmp_deleted',
+ content: 'Failed send',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: temp.id, type: 'createMessage', value: temp as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+ const transcript = getMessageTranscript(useChatStore.setState, useChatStore.getState);
+ expect(transcript.debugUnconfirmedClientIds()).toContain('tmp_deleted');
+
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: temp.id, type: 'deleteMessage' },
+ { conversationContext: context },
+ );
+
+ expect(transcript.debugUnconfirmedClientIds()).not.toContain('tmp_deleted');
+ });
+
+ it('keeps a remapped row when a read issued before its temporary id resolves', async () => {
+ const previousReply: UIChatMessage = {
+ id: 'previous-reply',
+ content: 'Previous reply',
+ role: 'assistant',
+ createdAt: 1000,
+ updatedAt: 1000,
+ };
+ const temp: UIChatMessage = {
+ id: 'tmp_client',
+ content: 'Sent',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+ const persisted: UIChatMessage = { ...temp, id: 'msg_server' };
+
+ // The read starts before the optimistic create.
+ let resolveFetch!: (messages: UIChatMessage[]) => void;
+ vi.mocked(messageService.getMessages).mockReturnValue(
+ new Promise((resolve) => {
+ resolveFetch = resolve;
+ }) as Promise<UIChatMessage[]>,
+ );
+ seedRows(context, [previousReply]);
+ syncMessages(context);
+ await waitFor(() => expect(messageService.getMessages).toHaveBeenCalledTimes(1));
+
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: temp.id, type: 'createMessage', value: temp as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+ // The create succeeds and the server id replaces the temporary one.
+ useChatStore.getState().replaceMessages([previousReply, persisted], { context });
+
+ // The pre-create snapshot resolves without the persisted row.
+ await act(async () => {
+ resolveFetch([{ ...previousReply, content: 'Previous reply (fetched)', updatedAt: 1500 }]);
+ });
+
+ await waitFor(() => expect(rowsOf(context)?.[0].content).toBe('Previous reply (fetched)'));
+ expect(rowsOf(context)?.map((message) => message.id)).toEqual([
+ previousReply.id,
+ persisted.id,
+ ]);
+ });
+
+ it('drops a remapped row omitted by a generation restarted after the remap', async () => {
+ const previousReply: UIChatMessage = {
+ id: 'previous-reply',
+ content: 'Previous reply',
+ role: 'assistant',
+ createdAt: 1000,
+ updatedAt: 1000,
+ };
+ const temp: UIChatMessage = {
+ id: 'tmp_client',
+ content: 'Sent',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+ const persisted: UIChatMessage = { ...temp, id: 'msg_server' };
+
+ let resolveFirst!: (messages: UIChatMessage[]) => void;
+ let resolveRestarted!: (messages: UIChatMessage[]) => void;
+ vi.mocked(messageService.getMessages)
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveFirst = resolve;
+ }) as Promise<UIChatMessage[]>,
+ )
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveRestarted = resolve;
+ }) as Promise<UIChatMessage[]>,
+ );
+ seedRows(context, [previousReply]);
+ syncMessages(context);
+ await waitFor(() => expect(messageService.getMessages).toHaveBeenCalledTimes(1));
+
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: temp.id, type: 'createMessage', value: temp as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+ useChatStore.getState().replaceMessages([previousReply, persisted], { context });
+ // The cache re-issues the query after the remap.
+ invalidateMessageListClientState(() => true);
+
+ resolveFirst([previousReply]);
+ await waitFor(() => expect(messageService.getMessages).toHaveBeenCalledTimes(2));
+
+ // The restarted request knew the server id, so omitting it is a remote delete.
+ resolveRestarted([previousReply]);
+
+ await waitFor(() =>
+ expect(rowsOf(context)?.map((message) => message.id)).toEqual([previousReply.id]),
+ );
+ });
+
+ it('keeps a send whose stale fetch resolves after the send operation handed off', async () => {
+ const previousReply: UIChatMessage = {
+ id: 'previous-reply',
+ content: 'Previous reply',
+ role: 'assistant',
+ createdAt: 1000,
+ updatedAt: 1000,
+ };
+ const sentUser: UIChatMessage = {
+ id: 'msg_user',
+ content: 'Follow-up question',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+ const sentAssistant: UIChatMessage = {
+ id: 'msg_assistant',
+ content: '...',
+ role: 'assistant',
+ createdAt: 2001,
+ updatedAt: 2001,
+ };
+
+ // The topic's read is still in flight from before the send.
+ let resolveFetch!: (messages: UIChatMessage[]) => void;
+ vi.mocked(messageService.getMessages).mockReturnValue(
+ new Promise((resolve) => {
+ resolveFetch = resolve;
+ }) as Promise<UIChatMessage[]>,
+ );
+
+ // The conversation was opened with the previous turn already on screen.
+ seedRows(context, [previousReply]);
+ syncMessages(context);
+
+ // The send persists its pair and hands off to the runtime operation, so
+ // no `sendMessage` operation is running when the stale read resolves.
+ const { operationId } = useChatStore.getState().startOperation({
+ context: { ...context, messageId: sentUser.id },
+ type: 'sendMessage',
+ });
+ useChatStore.getState().associateMessageWithOperation(sentUser.id, operationId);
+ useChatStore.getState().associateMessageWithOperation(sentAssistant.id, operationId);
+ // The send path creates its optimistic rows through the message dispatch.
+ for (const message of [sentUser, sentAssistant]) {
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: message.id, type: 'createMessage', value: message as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+ }
+ useChatStore.getState().completeOperation(operationId);
+
+ resolveFetch([{ ...previousReply, content: 'Previous reply (fetched)', updatedAt: 1500 }]);
+
+ await waitFor(() => expect(rowsOf(context)?.[0].content).toBe('Previous reply (fetched)'));
+ expect(rowsOf(context)?.map((message) => message.id)).toEqual([
+ previousReply.id,
+ sentUser.id,
+ sentAssistant.id,
+ ]);
+ });
+
+ it('drops a row that only the hydrated page still has when a stale read resolves', async () => {
+ const persisted: UIChatMessage[] = [
+ {
+ id: 'remote-deleted',
+ content: 'Deleted on another device',
+ role: 'user',
+ createdAt: 1000,
+ updatedAt: 1000,
+ },
+ { id: 'kept', content: 'Kept', role: 'user', createdAt: 1001, updatedAt: 1001 },
+ ];
+
+ // The read is issued while the bucket is empty: neither row exists yet.
+ let resolveFetch!: (messages: UIChatMessage[]) => void;
+ vi.mocked(messageService.getMessages).mockReturnValue(
+ new Promise((resolve) => {
+ resolveFetch = resolve;
+ }) as Promise<UIChatMessage[]>,
+ );
+
+ // IndexedDB hydration is slower than issuing the read, then lands first.
+ // Its page still holds `remote-deleted`, which the server has since removed.
+ let resolveHydrate!: () => void;
+ const hydrated = new Promise((resolve) => {
+ resolveHydrate = () => resolve({ data: transcriptOf(persisted), updatedAt: 1 });
+ });
+ vi.spyOn(conversationMessagesResource.storage!, 'get').mockImplementation(async (key) =>
+ key.queryKey === REPLICA_INDEX_KEY ? undefined : hydrated,
+ );
+
+ syncMessages(context);
+ await waitFor(() => expect(messageService.getMessages).toHaveBeenCalled());
+
+ await act(async () => {
+ resolveHydrate();
+ await hydrated;
+ });
+ await waitFor(() =>
+ expect(rowsOf(context)?.map((message) => message.id)).toEqual(['remote-deleted', 'kept']),
+ );
+
+ await act(async () => {
+ resolveFetch([persisted[1]]);
+ });
+
+ // Hydration is not an in-memory write made after the read started, so the
+ // server snapshot wins. Before the fix every hydrated row was kept.
+ await waitFor(() => expect(rowsOf(context)?.map((message) => message.id)).toEqual(['kept']));
+ });
+
+ it('drops a server-applied row that a restarted read omits', async () => {
+ const kept: UIChatMessage = {
+ id: 'kept',
+ content: 'Kept',
+ role: 'user',
+ createdAt: 1000,
+ updatedAt: 1000,
+ };
+ const alreadyKnown: UIChatMessage = {
+ id: 'already-known',
+ content: 'Committed before the restarted read',
+ role: 'user',
+ createdAt: 1001,
+ updatedAt: 1001,
+ };
+
+ let resolveFirst!: (messages: UIChatMessage[]) => void;
+ let resolveRestarted!: (messages: UIChatMessage[]) => void;
+ vi.mocked(messageService.getMessages)
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveFirst = resolve;
+ }) as Promise<UIChatMessage[]>,
+ )
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveRestarted = resolve;
+ }) as Promise<UIChatMessage[]>,
+ );
+
+ seedRows(context, [kept]);
+ syncMessages(context);
+ await waitFor(() => expect(messageService.getMessages).toHaveBeenCalledTimes(1));
+
+ // The row lands in memory after the first read started, but before the
+ // generation is invalidated and the query is physically re-issued.
+ useChatStore.getState().replaceMessages([kept, alreadyKnown], { context });
+ invalidateMessageListClientState(() => true);
+
+ resolveFirst([kept]);
+ await waitFor(() => expect(messageService.getMessages).toHaveBeenCalledTimes(2));
+
+ // The restarted read started after the write, so its omission of the row
+ // is authoritative (it was deleted remotely).
+ resolveRestarted([kept]);
+
+ await waitFor(() => expect(rowsOf(context)?.map((message) => message.id)).toEqual(['kept']));
+ });
+
+ it('keeps a client row created while the fetch waits for the topic decision', async () => {
+ const question: UIChatMessage = {
+ id: 'question',
+ content: '',
+ role: 'tool',
+ tool_call_id: 'call-1',
+ createdAt: 1,
+ updatedAt: 1,
+ pluginIntervention: { status: 'pending' },
+ };
+ const answered: UIChatMessage = {
+ ...question,
+ pluginIntervention: { status: 'approved' },
+ };
+ const sent: UIChatMessage = {
+ id: 'msg_user',
+ content: 'Follow-up',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+
+ let calls = 0;
+ vi.mocked(messageService.getMessages).mockImplementation(() => {
+ calls += 1;
+ // The forced read is the second call; later reads stay in flight so
+ // they cannot repair the row for the assertion.
+ return calls <= 2 ? Promise.resolve([answered]) : new Promise(() => {});
+ });
+
+ let resolveTopic!: () => void;
+ vi.mocked(topicService.getTopicDetail).mockReturnValue(
+ new Promise((resolve) => {
+ resolveTopic = () => resolve(null);
+ }) as ReturnType<typeof topicService.getTopicDetail>,
+ );
+
+ seedRows(context, [question]);
+ syncMessages(context, { syncInterventions: true });
+ await waitFor(() => expect(topicService.getTopicDetail).toHaveBeenCalled());
+
+ // The send lands after the first read resolved but before the topic
+ // decision returns β€” the gap where a later read used to prune its mark.
+ useChatStore
+ .getState()
+ .internal_dispatchMessage(
+ { id: sent.id, type: 'createMessage', value: sent as any },
+ { conversationContext: context },
+ { creationOrigin: 'client' },
+ );
+
+ await act(async () => {
+ resolveTopic();
+ });
+
+ await waitFor(() =>
+ expect(rowsOf(context)?.map((message) => message.id)).toEqual(['question', 'msg_user']),
+ );
+ });
});
});
diff --git a/src/store/chat/slices/message/transcript/index.ts b/src/store/chat/slices/message/transcript/index.ts
index b4e3b06db13..356431de7f2 100644
--- a/src/store/chat/slices/message/transcript/index.ts
+++ b/src/store/chat/slices/message/transcript/index.ts
@@ -37,7 +37,7 @@ import {
import { type StoreSetter } from '@/store/types';
import { bucketOfKey, createTranscriptLens } from './lens';
-import { mergeFetchedMessagesWithLocalState } from './mergeFetched';
+import { type HeadRequestBoundary, mergeFetchedMessagesWithLocalState } from './mergeFetched';
const log = debug('lobe-store:message-transcript');
@@ -72,9 +72,165 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
const snapshots = new WeakMap<UIChatMessage[], InterventionSnapshot>();
/** Head responses resolved by `prepareHead`, read back by the sync's `onSuccess`. */
const headResolutions = new WeakMap<UIChatMessage[], HeadResolution>();
+ /**
+ * A read's own view of the writes that happened after it was issued. A read
+ * that is still in flight when a send lands resolves with the pre-send
+ * snapshot; the rows that send created must survive it even once the send
+ * operation has handed off to the runtime.
+ *
+ * Records are created when a read starts and released when the whole fetch
+ * settles β€” including the topic-detail wait and a forced re-read. Nothing is
+ * shared, pruned or capped across reads, so a later read can never discard
+ * what an earlier unfinished one still needs.
+ */
+ type HeadReadRecord = {
+ /** Client-created ids this read cannot treat as server-authoritative. */
+ clientIds: Set<string>;
+ /** Number of fetch responses that have not settled with this record yet. */
+ refs: number;
+ /**
+ * When the server came to know a protected id (confirmed it, or assigned
+ * it to a remapped row). A physical request issued after that point
+ * returns the row if it still exists, so omitting it is authoritative.
+ */
+ serverKnownAt: Map<string, number>;
+ };
+ const activeHeadReads = new Set<HeadReadRecord>();
+ const headReads = new WeakMap<UIChatMessage[], HeadReadRecord>();
+ /** Client-created rows a server snapshot has not returned yet. */
+ const unconfirmedClientIds = new Set<string>();
+ /** Orders physical requests against the moments ids became server-known. */
+ let clock = 0;
+ /**
+ * When the physical request behind each head result was issued. A logical
+ * read can issue several (a cache generation restart, a forced re-read), and
+ * only the one whose response is applied decides what it may omit.
+ */
+ const physicalStarts = new WeakMap<UIChatMessage[], number>();
/** The entry key each bucket was last written under. */
const bucketKeys = new Map<string, string>();
+ const createHeadRead = (): HeadReadRecord => {
+ // A row created before this read but not yet persisted is still missing
+ // from an authoritative snapshot, so it starts in the record too.
+ const record: HeadReadRecord = {
+ clientIds: new Set(unconfirmedClientIds),
+ refs: 1,
+ serverKnownAt: new Map(),
+ };
+ activeHeadReads.add(record);
+ return record;
+ };
+
+ const retainHeadRead = (record: HeadReadRecord) => {
+ record.refs += 1;
+ activeHeadReads.add(record);
+ };
+
+ /**
+ * Drop one fetch's reference. A shared record stays active until every
+ * response that uses it has settled, so no fetch can lose protection that
+ * another unfinished one still needs.
+ */
+ const releaseHeadRead = (record: HeadReadRecord) => {
+ if (record.refs <= 0) return;
+ record.refs -= 1;
+ if (record.refs === 0) activeHeadReads.delete(record);
+ };
+
+ /**
+ * A client mutation created this row. Only these rows may be missing from a
+ * read that predates their server persistence. Rows applied from a server
+ * response (`replaceMessages`) and rows painted from hydration are known to
+ * the server, so a snapshot that omits one stays authoritative.
+ */
+ const noteClientWrite = (id: string) => {
+ unconfirmedClientIds.add(id);
+ for (const record of activeHeadReads) record.clientIds.add(id);
+ };
+
+ /**
+ * The server knows these ids from now on. Active reads keep protecting them
+ * only against a response whose physical request was issued earlier.
+ */
+ const markServerKnown = (ids: Iterable<string>, at = ++clock) => {
+ for (const id of ids) {
+ for (const record of activeHeadReads) {
+ if (record.clientIds.has(id) && !record.serverKnownAt.has(id)) {
+ record.serverKnownAt.set(id, at);
+ }
+ }
+ }
+ };
+
+ /**
+ * A server snapshot returned these rows. Their client-side mark is settled,
+ * so a later snapshot that omits one is authoritative (a remote delete).
+ * Runs even when the replacement leaves the bucket unchanged.
+ */
+ const confirmServerRows = (messages: UIChatMessage[]) => {
+ markServerKnown(messages.map((message) => message.id));
+ for (const message of messages) unconfirmedClientIds.delete(message.id);
+ };
+
+ /**
+ * The server acknowledged persisting these client rows without returning a
+ * snapshot. Reads issued before the acknowledgement may still miss them; a
+ * later one that omits them is authoritative.
+ */
+ const confirmPersistedRows = (ids: string[]) => {
+ markServerKnown(ids);
+ forgetClientRows(ids);
+ };
+
+ /** Client rows that no longer exist locally (deleted, removed or remapped). */
+ const forgetClientRows = (ids: Iterable<string>) => {
+ for (const id of ids) unconfirmedClientIds.delete(id);
+ };
+
+ /**
+ * A server replacement removed or remapped client rows (an optimistic
+ * `tmp_*` id swapped for the server id). They can never be preserved again,
+ * but a read that was already protecting one predates the rows that replaced
+ * it, so those take over its protection in that read only.
+ */
+ const remapClientRows = (removedIds: string[], addedIds: string[]) => {
+ forgetClientRows(removedIds);
+ if (addedIds.length === 0) return;
+ const at = ++clock;
+ for (const record of activeHeadReads) {
+ if (!removedIds.some((id) => record.clientIds.has(id))) continue;
+ for (const id of addedIds) {
+ record.clientIds.add(id);
+ // The server assigned it just now: only a request issued earlier can
+ // be missing it.
+ if (!record.serverKnownAt.has(id)) record.serverKnownAt.set(id, at);
+ }
+ }
+ };
+
+ /**
+ * Issue one physical head request, stamping its result with the moment it
+ * was issued. The cache can call this again for a restarted generation.
+ */
+ const readHeadPage: typeof readConversationMessageListPage = async (context) => {
+ const startedAt = ++clock;
+ const result = await readConversationMessageListPage(context);
+ physicalStarts.set(Array.isArray(result) ? result : result.messages, startedAt);
+ return result;
+ };
+
+ /** Ids `record` still protects in a response issued at `startedAt`. */
+ const protectedIds = (record: HeadReadRecord, startedAt: number | undefined) => {
+ if (startedAt === undefined || record.serverKnownAt.size === 0) return record.clientIds;
+ const ids = new Set<string>();
+ for (const id of record.clientIds) {
+ const knownAt = record.serverKnownAt.get(id);
+ if (knownAt === undefined || knownAt > startedAt) ids.add(id);
+ }
+ return ids;
+ };
+
const lens = createTranscriptLens();
/**
@@ -89,6 +245,32 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
const bucketRows = (key: string) => get().dbMessagesMap[bucketOfKey(key).bucket];
+ /**
+ * Associate a fetch with the record that tracks a shared result, and return
+ * that record. Concurrent reads can join one query result; the first record
+ * registered for an array survives, the other one is folded into it and its
+ * reference transferred. Every copy of the result then keeps using a record
+ * that stays live until all of them settle.
+ */
+ const registerHeadRead = (messages: UIChatMessage[], record: HeadReadRecord): HeadReadRecord => {
+ const existing = headReads.get(messages);
+ if (!existing) {
+ headReads.set(messages, record);
+ return record;
+ }
+ if (existing === record) return record;
+
+ for (const id of record.clientIds) existing.clientIds.add(id);
+ for (const [id, at] of record.serverKnownAt) {
+ const existingAt = existing.serverKnownAt.get(id);
+ // The earliest observation is the authoritative one.
+ if (existingAt === undefined || at < existingAt) existing.serverKnownAt.set(id, at);
+ }
+ retainHeadRead(existing);
+ releaseHeadRead(record);
+ return existing;
+ };
+
// ---- reads ---------------------------------------------------------------
const fetchForward = async (
context: ConversationMessageParams,
@@ -103,28 +285,53 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
const fetchHead = async (context: ConversationMessageParams): Promise<UIChatMessage[]> => {
const syncKey = getMessageListCacheIdentity(context);
- const dbMessages = bucketRows(conversationMessagesKey(context)) ?? [];
- const topicAtRequest = context.topicId
- ? topicSelectors.getTopicById(context.topicId)(get())
- : undefined;
- const wasPending = hasPendingInterventions(dbMessages);
- let messages = await runMessageListQuery(context, readConversationMessageListPage);
- if (!context.syncInterventions || !context.topicId) return messages;
- if (wasPending || hasPendingInterventions(messages)) pendingInterventions.add(syncKey);
- if (!pendingInterventions.has(syncKey) || hasPendingInterventions(messages)) return messages;
-
- // The decision must precede the liveness read. A startup reservation is
- // still live even before runningOperation is published.
- const topic = await topicService.getTopicDetail(context.topicId);
- if (!isInterventionRunActive(topic)) {
- // Read after completion without dropping loaded history or its cursor.
- messages = await runMessageListQuery(context, readConversationMessageListPage, {
- force: true,
- });
+ const bucket = conversationMessagesKey(context);
+ /**
+ * The record for the read whose response will be applied. The forced
+ * re-read after an intervention replaces it, because rows confirmed or
+ * remapped while awaiting the topic decision become authoritative then.
+ */
+ let read = createHeadRead();
+ try {
+ const dbMessages = bucketRows(bucket) ?? [];
+ const topicAtRequest = context.topicId
+ ? topicSelectors.getTopicById(context.topicId)(get())
+ : undefined;
+ const wasPending = hasPendingInterventions(dbMessages);
+ let messages = await runMessageListQuery(context, readHeadPage);
+ read = registerHeadRead(messages, read);
+ if (!context.syncInterventions || !context.topicId) return messages;
+ if (wasPending || hasPendingInterventions(messages)) pendingInterventions.add(syncKey);
+ if (!pendingInterventions.has(syncKey) || hasPendingInterventions(messages)) return messages;
+
+ // The decision must precede the liveness read. A startup reservation is
+ // still live even before runningOperation is published.
+ const topic = await topicService.getTopicDetail(context.topicId);
+ if (!isInterventionRunActive(topic)) {
+ // This read starts after any confirmation or remap that happened while
+ // awaiting the topic decision, so its omission is authoritative. The
+ // first read's response is discarded, so its record can go with it.
+ releaseHeadRead(read);
+ read = createHeadRead();
+ // Read after completion without dropping loaded history or its cursor.
+ messages = await runMessageListQuery(context, readHeadPage, {
+ force: true,
+ });
+ read = registerHeadRead(messages, read);
+ }
+ const result = [...messages];
+ const startedAt = physicalStarts.get(messages);
+ if (startedAt !== undefined) physicalStarts.set(result, startedAt);
+ // The copy is what `prepareHead` receives. It must use the record that
+ // survived for the shared result, not one this fetch already released.
+ read = registerHeadRead(result, read);
+ snapshots.set(result, { dbMessages, topic, topicAtRequest });
+ return result;
+ } catch (error) {
+ // A rejected fetch never reaches `prepareHead`; drop its record here.
+ releaseHeadRead(read);
+ throw error;
}
- const result = [...messages];
- snapshots.set(result, { dbMessages, topic, topicAtRequest });
- return result;
};
const fetchOlder = async (
@@ -159,8 +366,22 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
context: ConversationMessageParams,
): ConversationMessageFetch | undefined => {
if (!Array.isArray(incoming)) return incoming;
+ // Several fetchers can join one result. The earliest request is the most
+ // conservative boundary for what any of their responses can be missing.
+ const read = headReads.get(incoming);
+ // The read record is released by `onSettled`, which runs for every success
+ // including the responses the replica discards before this point.
+
+ // A returned row is server-confirmed: a later snapshot may remove it.
+ confirmServerRows(incoming);
if (!context.topicId) return undefined;
+ // Client rows this read cannot treat as authoritative: unconfirmed when it
+ // was issued, or created while it was in flight.
+ const boundary: HeadRequestBoundary | undefined = read && {
+ unconfirmedClientIds: protectedIds(read, physicalStarts.get(incoming)),
+ };
+
// DB chunk writes can lag behind pushed content, even at an equal
// updatedAt. Keep streamed rows, but allow answers and unseen rows in.
// A parked run must not block the first load of the conversation.
@@ -188,6 +409,7 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
prevDbMessages,
activeVoiceMessageIds,
creatingMessageIds,
+ boundary,
);
const dropped = isStreaming && mergedMessages === prevDbMessages;
@@ -212,6 +434,16 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
const slice = createReplicaSlice(conversationMessagesResource, {
actionPrefix: 'messageTranscript',
+ effects: {
+ // Every settled success releases its read record, including responses
+ // the replica discards before `prepareHead` (off-scope, superseded,
+ // cleared, removed, or dropped by the merge).
+ onSettled: (data) => {
+ if (!Array.isArray(data)) return;
+ const record = headReads.get(data);
+ if (record) releaseHeadRead(record);
+ },
+ },
fetcher: (context, cursor) =>
context.messageReadMode === 'forward'
? fetchForward(context, cursor)
@@ -239,9 +471,19 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
* the entry's paging; so does `preservePaging` (a reducer edit of the same
* window). Anything else is a fresh, unpaged transcript.
*/
- const commit = (context: TranscriptContext, messages: UIChatMessage[], preservePaging = false) =>
- slice.update(
- keyOf(context),
+ const commit = (
+ context: TranscriptContext,
+ messages: UIChatMessage[],
+ preservePaging = false,
+ clientCreatedId?: string,
+ ) => {
+ const key = keyOf(context);
+ // Only a row a client mutation created can be missing from a read that
+ // predates its server persistence. Hydration writes through the replica
+ // slice and `replaceMessages` applies server data, so neither is tracked.
+ if (clientCreatedId) noteClientWrite(clientCreatedId);
+ return slice.update(
+ key,
(current) =>
current &&
(preservePaging ||
@@ -251,6 +493,7 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
: transcriptOf(messages),
{ persist: false },
);
+ };
/**
* Persist a conversation once it is settled β€” never per streamed chunk; the
@@ -274,6 +517,7 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
*/
const evict = async (predicate?: (context: ConversationContext) => boolean): Promise<void> => {
if (!predicate) {
+ unconfirmedClientIds.clear();
await slice.clear();
return;
}
@@ -283,7 +527,13 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
};
const scope = conversationMessagesResource.scope.get();
const loaded = new Set(lens.keys!(get()));
- for (const key of loaded) if (matches(key)) slice.remove(key);
+ for (const key of loaded) {
+ if (!matches(key)) continue;
+ // No later replacement or delete reaches an evicted conversation, so its
+ // client rows' marks go with it.
+ forgetClientRows((bucketRows(key) ?? []).map((message) => message.id));
+ slice.remove(key);
+ }
const persisted = await readReplicaStoredKeys(conversationMessagesResource);
// `remove` resolves against the active scope; another identity's rows are not ours.
@@ -293,7 +543,13 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
return {
commit,
+ confirmPersistedRows,
+ confirmServerRows,
+ /** @internal Test/debug view of the ids a stale read may still preserve. */
+ debugUnconfirmedClientIds: () => [...unconfirmedClientIds],
evict,
+ forgetClientRows,
+ remapClientRows,
headResolutions,
keyOf,
pendingInterventions,
diff --git a/src/store/chat/slices/message/transcript/mergeFetched.ts b/src/store/chat/slices/message/transcript/mergeFetched.ts
index c141c2c4895..f1bc98e1cd7 100644
--- a/src/store/chat/slices/message/transcript/mergeFetched.ts
+++ b/src/store/chat/slices/message/transcript/mergeFetched.ts
@@ -6,6 +6,20 @@ import {
mergeLocalMessagesByCreatedAt,
} from '@/store/chat/utils/localMessages';
+/** What a head read can legitimately be missing, captured when it was issued. */
+export interface HeadRequestBoundary {
+ /**
+ * Client-created rows this read cannot treat as server-authoritative: those
+ * still unconfirmed when it was issued, plus those created while it was in
+ * flight. A snapshot that omits one predates its persistence.
+ *
+ * Rows painted from storage hydration and rows applied from a server
+ * response are deliberately absent: the server already knows them, so a
+ * snapshot that omits one is authoritative (e.g. a remote delete).
+ */
+ unconfirmedClientIds: ReadonlySet<string>;
+}
+
/**
* Merge an idle head fetch into the shown transcript.
*
@@ -14,12 +28,19 @@ import {
* agent runtime, so the optimistic user and assistant rows must be kept
* explicitly until the server returns them; otherwise the just-sent message
* vanishes until the run settles and refetches.
+ *
+ * The send operation ends as soon as the runtime takes over, while a read that
+ * was already in flight can still resolve afterwards with the pre-send
+ * snapshot. `boundary` covers both orderings: a client row created after the
+ * read was issued, and one created before it but not yet confirmed by a
+ * server snapshot.
*/
export const mergeFetchedMessagesWithLocalState = (
fetchedMessages: UIChatMessage[],
localMessages: UIChatMessage[],
activeVoiceMessageIds: ReadonlySet<string>,
creatingMessageIds: ReadonlySet<string>,
+ boundary?: HeadRequestBoundary,
): UIChatMessage[] => {
if (localMessages.length === 0) return fetchedMessages;
@@ -45,7 +66,11 @@ export const mergeFetchedMessagesWithLocalState = (
(message) =>
!fetchedIds.has(message.id) &&
((isLocalOnlyMessage(message) && activeVoiceMessageIds.has(message.id)) ||
- creatingMessageIds.has(message.id)),
+ creatingMessageIds.has(message.id) ||
+ // Client-created and not yet confirmed by a server snapshot: this read
+ // predates its persistence. Hydrated and server-applied rows are never
+ // in this set, so an authoritative omission still removes them.
+ !!boundary?.unconfirmedClientIds.has(message.id)),
);
if (missingLocalMessages.length === 0) return changed ? mergedMessages : fetchedMessages;
diff --git a/src/store/chat/slices/voiceMessage/action.ts b/src/store/chat/slices/voiceMessage/action.ts
index b16b62032e8..db24b71fbdb 100644
--- a/src/store/chat/slices/voiceMessage/action.ts
+++ b/src/store/chat/slices/voiceMessage/action.ts
@@ -153,6 +153,7 @@ export class VoiceMessageActionImpl {
value: this.#createLocalMessage(transaction),
},
{ conversationContext: transaction.context },
+ { creationOrigin: 'client' },
);
};