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: keep just-sent message visible when a refetch lands mid-send (#20891)

YuTengjing3c3c1a207efc
diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.ts
index 0b603d89996..c93be3e2d90 100644
--- a/src/features/Conversation/store/slices/data/action.test.ts
+++ b/src/features/Conversation/store/slices/data/action.test.ts
@@ -1400,6 +1400,9 @@ describe('DataSlice', () => {
});
it('should use different SWR keys for different threadIds', () => {
+ // The SWR mock runs the fetcher; an unmocked list read rejects after the test.
+ vi.mocked(messageService.getMessages).mockResolvedValue([]);
+
const store1 = createStore({
context: { agentId: 'session-1', topicId: 'topic-1', threadId: 'thread-1' },
});
@@ -1431,6 +1434,9 @@ describe('DataSlice', () => {
});
it('should use same SWR key structure with Object containing sessionId, topicId, threadId', () => {
+ // The SWR mock runs the fetcher; an unmocked list read rejects after the test.
+ vi.mocked(messageService.getMessages).mockResolvedValue([]);
+
const store = createStore({
context: { agentId: 'test-session', topicId: 'test-topic', threadId: 'test-thread' },
});
@@ -1648,6 +1654,65 @@ describe('DataSlice', () => {
});
});
+ it('should keep optimistic send rows when a stale fetch resolves before the server run starts', async () => {
+ const context = { agentId: 'test-session', topicId: 'test-topic', threadId: null };
+ const previousReply: UIChatMessage = {
+ id: 'previous-reply',
+ content: 'Previous reply',
+ role: 'assistant',
+ createdAt: 1000,
+ updatedAt: 1000,
+ };
+ const optimisticUser: UIChatMessage = {
+ id: 'msg_user',
+ content: 'Follow-up question',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+ };
+ const optimisticAssistant: UIChatMessage = {
+ id: 'msg_assistant',
+ content: '...',
+ role: 'assistant',
+ createdAt: 2001,
+ updatedAt: 2001,
+ };
+
+ // The fetch was issued before the server persisted the new rows.
+ vi.mocked(messageService.getMessages).mockResolvedValue([
+ { ...previousReply, content: 'Previous reply (fetched)', updatedAt: 1500 },
+ ]);
+
+ const store = createStore({ context });
+ store.setState({
+ dbMessages: [previousReply, optimisticUser, optimisticAssistant],
+ messagesInit: true,
+ });
+
+ // `sendMessage` is still waiting for `execAgentTask`; no runtime operation exists yet.
+ const { operationId } = useChatStore.getState().startOperation({
+ context: { ...context, messageId: optimisticUser.id },
+ type: 'sendMessage',
+ });
+ useChatStore.getState().associateMessageWithOperation(optimisticUser.id, operationId);
+ useChatStore.getState().associateMessageWithOperation(optimisticAssistant.id, operationId);
+
+ try {
+ fetchMessagesOf(store)(context);
+
+ await waitFor(() => {
+ expect(store.getState().dbMessages[0].content).toBe('Previous reply (fetched)');
+ });
+ expect(store.getState().dbMessages.map((message) => message.id)).toEqual([
+ previousReply.id,
+ optimisticUser.id,
+ optimisticAssistant.id,
+ ]);
+ } finally {
+ useChatStore.getState().completeOperation(operationId);
+ }
+ });
+
it('should keep an earlier local-only voice row ahead of a later fetched message', async () => {
const localVoiceMessage: UIChatMessage = {
id: 'tmp-voice-message',
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
index f50d8e2e8f1..cb2580bce09 100644
--- a/src/features/Conversation/store/slices/data/action.ts
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -68,10 +68,20 @@ const getInterventionSync = (get: () => ConversationStore) => {
return sync;
};
+/**
+ * Merge an idle head fetch into the shown transcript.
+ *
+ * A fetch can be issued before a send persists its rows and resolve while
+ * `sendMessage` is still waiting for the server. That window is not a running
+ * 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.
+ */
const mergeFetchedMessagesWithLocalState = (
fetchedMessages: UIChatMessage[],
localMessages: UIChatMessage[],
activeVoiceMessageIds: ReadonlySet<string>,
+ creatingMessageIds: ReadonlySet<string>,
): UIChatMessage[] => {
if (localMessages.length === 0) return fetchedMessages;
@@ -93,16 +103,16 @@ const mergeFetchedMessagesWithLocalState = (
return localMessage;
});
- const missingLocalOnlyMessages = localMessages.filter(
+ const missingLocalMessages = localMessages.filter(
(message) =>
- isLocalOnlyMessage(message) &&
- activeVoiceMessageIds.has(message.id) &&
- !fetchedIds.has(message.id),
+ !fetchedIds.has(message.id) &&
+ ((isLocalOnlyMessage(message) && activeVoiceMessageIds.has(message.id)) ||
+ creatingMessageIds.has(message.id)),
);
- if (missingLocalOnlyMessages.length === 0) return changed ? mergedMessages : fetchedMessages;
+ if (missingLocalMessages.length === 0) return changed ? mergedMessages : fetchedMessages;
- return mergeLocalMessagesByCreatedAt(mergedMessages, missingLocalOnlyMessages);
+ return mergeLocalMessagesByCreatedAt(mergedMessages, missingLocalMessages);
};
/**
@@ -348,9 +358,19 @@ export const dataSlice: StateCreator<
operationSelectors.isAgentRuntimeRunningByContext(context)(chat) &&
!(completed && snapshot!.dbMessages === prevDbMessages);
const activeVoiceMessageIds = new Set(Object.keys(chat.voiceMessageUploadMap));
+ const creatingMessageIds = new Set(
+ prevDbMessages
+ .filter((message) => operationSelectors.isMessageCreating(message.id)(chat))
+ .map((message) => message.id),
+ );
const mergedMessages = isStreaming
? reconcileStreamingInterventions(prevDbMessages, incoming)
- : mergeFetchedMessagesWithLocalState(incoming, prevDbMessages, activeVoiceMessageIds);
+ : mergeFetchedMessagesWithLocalState(
+ incoming,
+ prevDbMessages,
+ activeVoiceMessageIds,
+ creatingMessageIds,
+ );
const dropped = isStreaming && mergedMessages === prevDbMessages;
headResolutions.set(incoming, {