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): show force-steered messages while the previous run stops (#23296)

Bryan5145d221b5c5
diff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsx
index eda23c45a6a..c42b85de5b1 100644
--- a/src/features/Conversation/ChatInput/QueueTray.tsx
+++ b/src/features/Conversation/ChatInput/QueueTray.tsx
@@ -281,11 +281,9 @@ const QueueTray = memo(() => {
setSendingId(msg.id);
try {
const outcome = await sendQueuedMessageNow({
- chat: useChatStore.getState(),
context,
contextKey,
- isQueued: (id) =>
- !!useChatStore.getState().queuedMessages[contextKey]?.some((q) => q.id === id),
+ getChat: useChatStore.getState,
msg,
withdraw: (queued) => withdrawQueuedMessage(contextKey, queued.id),
});
diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.ts
index 0a896ed3e37..26fc51f523e 100644
--- a/src/features/Conversation/ChatInput/utils.test.ts
+++ b/src/features/Conversation/ChatInput/utils.test.ts
@@ -1,6 +1,7 @@
import type { UIChatMessage } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
+import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import {
@@ -398,6 +399,7 @@ describe('toDisplayableSendErrorMessage', () => {
describe('sendQueuedMessageNow', () => {
const context = { agentId: 'agt-1', topicId: 'tpc-1' };
+ const contextKey = messageMapKey(context);
const msg = {
content: 'now',
createdAt: 1,
@@ -407,6 +409,7 @@ describe('sendQueuedMessageNow', () => {
};
const chatWith = (cancelled: boolean | Error) => {
const order: string[] = [];
+ const dbMessagesMap: Record<string, UIChatMessage[]> = { [contextKey]: [] };
const chat = {
cancelOperation: vi.fn(async () => {
order.push('cancel');
@@ -414,6 +417,17 @@ describe('sendQueuedMessageNow', () => {
return cancelled;
}),
restoreQueuedMessage: vi.fn(),
+ dbMessagesMap,
+ internal_createClientMessage: vi.fn(
+ (id: string, value: Pick<UIChatMessage, 'content' | 'metadata' | 'role'>) => {
+ dbMessagesMap[contextKey].push({ ...value, createdAt: 1, id, updatedAt: 1 });
+ },
+ ),
+ internal_dispatchMessage: vi.fn(({ id }: { id: string }) => {
+ dbMessagesMap[contextKey] = dbMessagesMap[contextKey].filter(
+ (message) => message.id !== id,
+ );
+ }),
operations: {
'op-1': {
context,
@@ -431,13 +445,51 @@ describe('sendQueuedMessageNow', () => {
{ content: 'after', createdAt: 2, id: 'q2', interruptMode: 'soft' },
],
},
- sendMessage: vi.fn(async () => {
+ sendMessage: vi.fn(async ({ onMessageAccepted, optimisticUserMessageId }) => {
order.push('send');
+ const row = dbMessagesMap[contextKey].find(({ id }) => id === optimisticUserMessageId);
+ if (row) row.metadata = { steer: true };
+ onMessageAccepted();
}),
} as any;
return { chat, order };
};
+ it('shows a user bubble with the final message ID while the device is still stopping', async () => {
+ const { chat } = chatWith(true);
+ const cancellation = Promise.withResolvers<boolean>();
+ chat.cancelOperation.mockReturnValueOnce(cancellation.promise);
+
+ const sending = sendQueuedMessageNow({
+ context,
+ contextKey,
+ getChat: () => chat,
+ msg,
+ withdraw: async () => true,
+ });
+
+ await vi.waitFor(() => expect(chat.cancelOperation).toHaveBeenCalledOnce());
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ expect(chat.dbMessagesMap[contextKey]).toEqual([
+ expect.objectContaining({
+ content: 'now',
+ metadata: { scope: LOCAL_MESSAGE_SCOPE, steer: true },
+ role: 'user',
+ }),
+ ]);
+ const [{ id }] = chat.dbMessagesMap[contextKey];
+
+ cancellation.resolve(true);
+ await expect(sending).resolves.toBe('sent');
+ expect(chat.sendMessage).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ optimisticUserMessageId: id }),
+ );
+ expect(chat.dbMessagesMap[contextKey]).toEqual([
+ expect.objectContaining({ id, metadata: { steer: true } }),
+ ]);
+ expect(chat.restoreQueuedMessage).not.toHaveBeenCalled();
+ });
+
// ROOT CAUSE:
//
// Send now interrupted the run before withdrawing the item. When that run
@@ -454,10 +506,9 @@ describe('sendQueuedMessageNow', () => {
});
await sendQueuedMessageNow({
- chat,
+ getChat: () => chat,
context,
contextKey: messageMapKey(context),
- isQueued: () => true,
msg,
withdraw,
});
@@ -474,10 +525,9 @@ describe('sendQueuedMessageNow', () => {
const { chat } = chatWith(true);
await sendQueuedMessageNow({
- chat,
+ getChat: () => chat,
context,
contextKey: messageMapKey(context),
- isQueued: () => true,
msg: { ...msg, forceRuntime: 'gateway' },
withdraw: async () => true,
});
@@ -489,12 +539,12 @@ describe('sendQueuedMessageNow', () => {
it('stops nothing and sends nothing when the run already wrote it', async () => {
const { chat } = chatWith(true);
+ chat.queuedMessages[messageMapKey(context)] = [];
const outcome = await sendQueuedMessageNow({
- chat,
+ getChat: () => chat,
context,
contextKey: messageMapKey(context),
- isQueued: () => false,
msg,
withdraw: async () => false,
});
@@ -528,10 +578,9 @@ describe('sendQueuedMessageNow', () => {
});
const outcome = await sendQueuedMessageNow({
- chat,
+ getChat: () => chat,
context,
contextKey: messageMapKey(context),
- isQueued: () => true,
msg,
withdraw,
});
@@ -544,10 +593,9 @@ describe('sendQueuedMessageNow', () => {
const { chat } = chatWith(true);
const outcome = await sendQueuedMessageNow({
- chat,
+ getChat: () => chat,
context,
contextKey: messageMapKey(context),
- isQueued: () => true,
msg,
withdraw: async () => false,
});
@@ -555,6 +603,7 @@ describe('sendQueuedMessageNow', () => {
expect(outcome).toBe('delivered');
expect(chat.cancelOperation).toHaveBeenCalled();
expect(chat.sendMessage).not.toHaveBeenCalled();
+ expect(chat.dbMessagesMap[contextKey]).toEqual([]);
});
it('keeps an item the run holds in the tray when the interrupt fails', async () => {
@@ -562,10 +611,9 @@ describe('sendQueuedMessageNow', () => {
await expect(
sendQueuedMessageNow({
- chat,
+ getChat: () => chat,
context,
contextKey: messageMapKey(context),
- isQueued: () => true,
msg,
withdraw: async () => false,
}),
@@ -573,6 +621,52 @@ describe('sendQueuedMessageNow', () => {
expect(chat.restoreQueuedMessage).not.toHaveBeenCalled();
expect(chat.sendMessage).not.toHaveBeenCalled();
+ expect(chat.dbMessagesMap[contextKey]).toEqual([]);
+ });
+
+ it('restores the queue if the replacement send returns without accepting the message', async () => {
+ const { chat } = chatWith(true);
+ chat.sendMessage.mockResolvedValueOnce(undefined);
+
+ await expect(
+ sendQueuedMessageNow({
+ context,
+ contextKey,
+ getChat: () => chat,
+ msg,
+ withdraw: async () => true,
+ }),
+ ).rejects.toThrow('The queued message was not accepted');
+
+ expect(chat.restoreQueuedMessage).toHaveBeenCalledOnce();
+ expect(chat.dbMessagesMap[contextKey]).toEqual([]);
+ });
+
+ it('keeps the bubble when persistence is acknowledged ahead of the transcript', async () => {
+ const { chat } = chatWith(true);
+ chat.sendMessage.mockImplementationOnce(
+ async ({
+ onMessageAccepted,
+ onMessagePersisted,
+ }: {
+ onMessageAccepted: () => void;
+ onMessagePersisted: () => void;
+ }) => {
+ onMessageAccepted();
+ onMessagePersisted();
+ },
+ );
+
+ await expect(
+ sendQueuedMessageNow({
+ context,
+ contextKey,
+ getChat: () => chat,
+ msg,
+ withdraw: async () => true,
+ }),
+ ).resolves.toBe('sent');
+ expect(chat.dbMessagesMap[contextKey]).toEqual([expect.objectContaining({ content: 'now' })]);
});
it.each([
@@ -583,10 +677,9 @@ describe('sendQueuedMessageNow', () => {
await expect(
sendQueuedMessageNow({
- chat,
+ getChat: () => chat,
context,
contextKey: messageMapKey(context),
- isQueued: () => true,
msg,
withdraw: async () => true,
}),
@@ -595,7 +688,12 @@ describe('sendQueuedMessageNow', () => {
// Back at its own place (index 1), not at the tail, so the order holds.
expect(chat.restoreQueuedMessage).toHaveBeenCalledWith(
messageMapKey(context),
- { ...msg, serverDelivery: undefined, serverUnconfirmed: undefined },
+ {
+ ...msg,
+ serverDelivering: undefined,
+ serverDelivery: undefined,
+ serverUnconfirmed: undefined,
+ },
1,
);
expect(chat.sendMessage).not.toHaveBeenCalled();
diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.ts
index 89e3f73ea9f..01dc6b052e5 100644
--- a/src/features/Conversation/ChatInput/utils.ts
+++ b/src/features/Conversation/ChatInput/utils.ts
@@ -5,16 +5,19 @@ import type {
OpenAIChatMessage,
UIChatMessage,
} from '@lobechat/types';
+import { generateEntityId } from '@lobechat/utils';
import type { PlaceholderVariant } from '@/features/ChatInput/InputEditor/Placeholder';
import type { ContextWindow, SendButtonProps } from '@/features/ChatInput/store/initialState';
import { operationSelectors } from '@/store/chat/selectors';
+import { getOptimisticMessageMedia } from '@/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia';
import {
type QueuedMessage,
reconstructUploadFilesFromQueue,
SEND_NOW_CANCEL_REASON,
} from '@/store/chat/slices/operation/types';
import type { ChatStore } from '@/store/chat/store';
+import { isLocalOnlyMessage, LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
import type { UploadFileItem } from '@/types/files/upload';
import { isMachineErrorMessage } from '@/utils/machineErrorMessage';
@@ -283,75 +286,119 @@ export const toDisplayableSendErrorMessage = (message?: string): string | undefi
* @returns `'delivered'` when the run already has it, so nothing was sent
*/
export const sendQueuedMessageNow = async ({
- chat,
context,
contextKey,
- isQueued,
+ getChat,
msg,
withdraw,
}: {
- chat: ChatStore;
context: ConversationContext;
contextKey: string;
- /** Reads the live queue: `chat` is a snapshot taken before any await. */
- isQueued: (id: string) => boolean;
+ getChat: () => ChatStore;
msg: QueuedMessage;
/** Throws when the server cannot be asked; `false` means the run has it. */
withdraw: (msg: QueuedMessage) => Promise<boolean>;
}): Promise<'delivered' | 'sent'> => {
+ const chat = getChat();
+ const messageContext = { conversationContext: context };
const index = chat.queuedMessages[contextKey]?.findIndex((queued) => queued.id === msg.id) ?? -1;
- const withdrawn = await withdraw(msg);
- // A `false` that leaves it in the tray means "taken, not yet written".
- if (!withdrawn && !isQueued(msg.id)) return 'delivered';
- // Back where it was, so the order the user queued in holds.
- const putBack = () => {
- if (!withdrawn) return;
- chat.restoreQueuedMessage(
- contextKey,
- { ...msg, serverDelivery: undefined, serverUnconfirmed: undefined },
- index < 0 ? Number.MAX_SAFE_INTEGER : index,
- );
- };
-
- // Cancel EVERY running blocker the item could be queued behind, not just the
- // first: matching one op would miss an interim blocker or the second of the
- // two concurrent `regenerate` ops a delAndRegenerate/delAndResendThread retry
- // runs (outer wrapper + inner regenerateUserMessage). Leaving any blocker
- // running would make the sendMessage below re-enqueue the item, so "Send now"
- // becomes a no-op. The selector shares the queue-blocking predicate with the
- // enqueue check.
const runningOpIds = operationSelectors.getRunningQueueBlockingOperationIds(context)(chat);
- const cancellationConfirmed = await Promise.all(
- runningOpIds.map((id) => chat.cancelOperation(id, SEND_NOW_CANCEL_REASON)),
- ).catch((error: unknown) => {
- putBack();
- throw error;
- });
- if (cancellationConfirmed.some((confirmed) => !confirmed)) {
- putBack();
- throw new Error('Running agent cancellation was not confirmed');
- }
- // The stop handed it back unless the run wrote it first.
- if (!withdrawn && !(await withdraw(msg))) return 'delivered';
-
- // Reconstruct UploadFileItem-shaped objects so the optimistic temp message
- // can rebuild imageList/videoList from the snapshotted preview metadata.
const files = msg.filesPreview?.length
? reconstructUploadFilesFromQueue(msg.filesPreview)
: msg.files?.length
- ? (msg.files.map((id) => ({ id })) as any)
+ ? (msg.files.map((id) => ({ id })) as UploadFileItem[])
: undefined;
- await chat.sendMessage({
- context,
- editorData: msg.editorData,
- files,
- // Keep the runtime the item was queued for (a task-run drawer forces the
- // gateway), as the queue drain does.
- ...(msg.forceRuntime ? { forceRuntime: msg.forceRuntime } : {}),
- message: msg.content,
- metadata: { ...msg.metadata, steer: true },
- });
- return 'sent';
+ const metadata = { ...msg.metadata, steer: true };
+ let optimisticUserMessageId: string | undefined;
+ let accepted = false;
+ let persisted = false;
+ let withdrawn = await withdraw(msg);
+ // A `false` that leaves it in the tray means "taken, not yet written".
+ if (!withdrawn && !getChat().queuedMessages[contextKey]?.some((queued) => queued.id === msg.id))
+ return 'delivered';
+
+ const showPendingBubble = () => {
+ if (!context.topicId || context.isNew) return;
+ optimisticUserMessageId = generateEntityId('messages');
+ chat.internal_createClientMessage(
+ optimisticUserMessageId,
+ {
+ agentId: context.agentId,
+ content: msg.content,
+ editorData: msg.editorData,
+ files: msg.files,
+ groupId: context.groupId,
+ metadata: { ...metadata, scope: LOCAL_MESSAGE_SCOPE },
+ role: 'user',
+ threadId: context.threadId,
+ topicId: context.topicId,
+ ...getOptimisticMessageMedia(files),
+ },
+ messageContext,
+ );
+ };
+
+ try {
+ if (withdrawn) showPendingBubble();
+
+ // Cancel every blocker, including overlapping operations from a regenerate.
+ const cancellationConfirmed = await Promise.all(
+ runningOpIds.map((id) => chat.cancelOperation(id, SEND_NOW_CANCEL_REASON)),
+ );
+ if (cancellationConfirmed.some((confirmed) => !confirmed))
+ throw new Error('Running agent cancellation was not confirmed');
+
+ // The stop handed it back unless the run wrote it first.
+ if (!withdrawn) {
+ withdrawn = await withdraw(msg);
+ if (!withdrawn) return 'delivered';
+ showPendingBubble();
+ }
+
+ await chat.sendMessage({
+ context,
+ editorData: msg.editorData,
+ files,
+ ...(msg.forceRuntime ? { forceRuntime: msg.forceRuntime } : {}),
+ message: msg.content,
+ metadata,
+ onMessageAccepted: () => {
+ accepted = true;
+ },
+ onMessagePersisted: () => {
+ persisted = true;
+ },
+ optimisticUserMessageId,
+ preserveComposer: true,
+ });
+ if (!accepted) throw new Error('The queued message was not accepted');
+ return 'sent';
+ } finally {
+ if (withdrawn && !accepted) {
+ chat.restoreQueuedMessage(
+ contextKey,
+ {
+ ...msg,
+ serverDelivering: undefined,
+ serverDelivery: undefined,
+ serverUnconfirmed: undefined,
+ },
+ index < 0 ? Number.MAX_SAFE_INTEGER : index,
+ );
+ }
+ // The gateway may acknowledge persistence before its transcript catches up.
+ // Keep that bubble until the same ID arrives with the persisted row.
+ if (optimisticUserMessageId && !persisted) {
+ const preview = getChat().dbMessagesMap[contextKey]?.find(
+ (message) => message.id === optimisticUserMessageId,
+ );
+ if (isLocalOnlyMessage(preview))
+ chat.internal_dispatchMessage(
+ { id: optimisticUserMessageId, type: 'deleteMessage' },
+ messageContext,
+ );
+ }
+ }
};
/**
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
index 2d91fbb74e1..7cad3287823 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
@@ -5,10 +5,7 @@ import { isDesktop, isHeterogeneousAgentModelId, LOADING_FLAT } from '@lobechat/
import { formatSelectedSkillsContext, formatSelectedToolsContext } from '@lobechat/context-engine';
import { collectHeteroAttachedFiles } from '@lobechat/heterogeneous-agents';
import type {
- ChatAudioItem,
- ChatImageItem,
ChatTopicMetadata,
- ChatVideoItem,
ConversationContext,
MessageMetadata,
SendMessageParams,
@@ -109,7 +106,6 @@ import { type StoreSetter } from '@/store/types';
import { getUserStoreState } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import { useUserMemoryStore } from '@/store/userMemory';
-import { rememberLocalImagePreview } from '@/utils/localImagePreview';
import { toTitleText } from '@/utils/markdownToTxt';
import { aggregateSubagentMetrics } from '@/utils/subagentMetrics';
@@ -130,6 +126,7 @@ import { pageConversationNeedsGateway, preparePageConversation } from '../pageCo
import { mergePartialPersistedMessages, resolveSendResponseMessages } from '../persistedMessages';
import { resolveExistingTopicForRun } from '../resolveExistingTopic';
import { type ContextCompressionOptions, executeContextCompression } from './compression';
+import { getOptimisticMessageMedia } from './optimisticMessageMedia';
import { findRunningBlockingOp } from './queueBlockingOp';
import { resolveSendProjectRun, resolveSendRunCwd, type SourceTopicDirectory } from './runCwd';
import { showSendErrorInContext } from './sendErrorNotice';
@@ -924,38 +921,6 @@ export class ConversationLifecycleActionImpl {
runtimeType,
});
- // Construct local media preview for server-mode temporary messages (S3 URL takes priority).
- // Use the captured `files` param (not the global file store) so the optimistic preview
- // also works on the queue-drain path, where chatUploadFileList has already been cleared.
- const filesForPreview = files ?? [];
- const imageFiles = filesForPreview.filter((f) => f.file?.type?.startsWith('image'));
- // The message, optimistic and saved alike, shows these from the local copy (see
- // `localImagePreview`); an upload's id is its server file id once it has finished.
- for (const f of imageFiles) {
- if (f.status === 'success' && f.previewUrl) rememberLocalImagePreview(f.id, f.previewUrl);
- }
- const tempImages: ChatImageItem[] = imageFiles.map((f) => ({
- ...f.dimensions,
- id: f.id,
- url: f.fileUrl || f.base64Url || f.previewUrl || '',
- alt: f.file?.name || f.id,
- }));
- const tempVideos: ChatVideoItem[] = filesForPreview
- .filter((f) => f.file?.type?.startsWith('video'))
- .map((f) => ({
- id: f.id,
- url: f.fileUrl || f.base64Url || f.previewUrl || '',
- alt: f.file?.name || f.id,
- }));
- const tempAudios: ChatAudioItem[] = filesForPreview
- .filter((f) => f.audioMetadata || f.file?.type?.startsWith('audio'))
- .map((f) => ({
- ...f.audioMetadata,
- id: f.id,
- url: f.fileUrl || f.base64Url || f.previewUrl || '',
- alt: f.file?.name || f.id,
- }));
-
const optimisticUserMessage = {
content: message,
editorData: editorData ?? undefined,
@@ -966,9 +931,7 @@ export class ConversationLifecycleActionImpl {
// if there is topicId, then add topicId to message
topicId: operationContext.topicId ?? undefined,
threadId: operationContext.threadId ?? undefined,
- audioList: tempAudios.length > 0 ? tempAudios : undefined,
- imageList: tempImages.length > 0 ? tempImages : undefined,
- videoList: tempVideos.length > 0 ? tempVideos : undefined,
+ ...getOptimisticMessageMedia(files),
// Pass metadata for immediate display
metadata: userMessageMetadata,
};
@@ -979,8 +942,8 @@ export class ConversationLifecycleActionImpl {
(item) => item.id === tempId && item.role === 'user',
);
- // A voice message can render a local-only row before its binary upload finishes. Adopt that
- // row in place so the formal send lifecycle keeps its stable position and never duplicates it.
+ // Voice uploads and forced steers can render a local-only row before sending. Adopt
+ // that row in place so the formal send keeps its position and never duplicates it.
if (existingOptimisticUserMessage) {
this.#get().internal_dispatchMessage(
{
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia.ts
new file mode 100644
index 00000000000..0922fd3cf71
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia.ts
@@ -0,0 +1,37 @@
+import type { ChatAudioItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
+
+import type { UploadFileItem } from '@/types/files/upload';
+import { rememberLocalImagePreview } from '@/utils/localImagePreview';
+
+export const getOptimisticMessageMedia = (files: UploadFileItem[] = []) => {
+ const urlOf = (file: UploadFileItem) => file.fileUrl || file.base64Url || file.previewUrl || '';
+ const imageFiles = files.filter((file) => file.file?.type?.startsWith('image'));
+ // Persisted images also use the local copy while the remote URL loads.
+ for (const file of imageFiles) {
+ if (file.status === 'success' && file.previewUrl)
+ rememberLocalImagePreview(file.id, file.previewUrl);
+ }
+ const imageList: ChatImageItem[] = imageFiles.map((file) => ({
+ ...file.dimensions,
+ alt: file.file?.name || file.id,
+ id: file.id,
+ url: urlOf(file),
+ }));
+ const videoList: ChatVideoItem[] = files
+ .filter((file) => file.file?.type?.startsWith('video'))
+ .map((file) => ({ alt: file.file?.name || file.id, id: file.id, url: urlOf(file) }));
+ const audioList: ChatAudioItem[] = files
+ .filter((file) => file.audioMetadata || file.file?.type?.startsWith('audio'))
+ .map((file) => ({
+ ...file.audioMetadata,
+ alt: file.file?.name || file.id,
+ id: file.id,
+ url: urlOf(file),
+ }));
+
+ return {
+ audioList: audioList.length > 0 ? audioList : undefined,
+ imageList: imageList.length > 0 ? imageList : undefined,
+ videoList: videoList.length > 0 ? videoList : undefined,
+ };
+};
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index 9e58e0a8cee..a58c68d85bc 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -192,15 +192,14 @@ export class MessageQueryActionImpl {
const currentMessages = this.#get().dbMessagesMap[messagesKey] ?? [];
const voiceMessageUploadMap = this.#get().voiceMessageUploadMap;
const activeLocalMessagesById = new Map<string, UIChatMessage>();
+ const transcript = getMessageTranscript(this.#set, this.#get);
- // Server snapshots never contain the local voice placeholder. Keep it in the in-memory
- // transcript only while the owning upload transaction is still active. Consider both the
- // existing ChatStore bucket and the incoming ConversationStore snapshot: the latter can carry
- // the placeholder after another server replacement briefly removed it from ChatStore.
+ // Keep active voice uploads and pending client sends across unrelated server snapshots.
+ // The persisted row takes over as soon as a snapshot includes its ID.
for (const message of [...currentMessages, ...incoming]) {
if (
isLocalOnlyMessage(message) &&
- voiceMessageUploadMap[message.id] &&
+ (voiceMessageUploadMap[message.id] || transcript.isUnconfirmedClientRow(message.id)) &&
!persistedIds.has(message.id) &&
!activeLocalMessagesById.has(message.id)
) {
@@ -213,7 +212,6 @@ export class MessageQueryActionImpl {
mergeLocalMessagesByCreatedAt(persistedReconciled, [...activeLocalMessagesById.values()]),
);
- 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);
diff --git a/src/store/chat/slices/message/actions/transcript.persisted.test.ts b/src/store/chat/slices/message/actions/transcript.persisted.test.ts
index c34f5b4fa43..8812843f31e 100644
--- a/src/store/chat/slices/message/actions/transcript.persisted.test.ts
+++ b/src/store/chat/slices/message/actions/transcript.persisted.test.ts
@@ -6,6 +6,7 @@ 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 { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
import { resetTranscripts, rowsOf, seedRows, syncMessages } from './testUtils';
@@ -76,6 +77,24 @@ describe('quietly persisted client rows', () => {
resetTranscripts();
});
+ it('keeps a pending local user bubble until the same ID comes back from the server', () => {
+ seedRows(context, [previousReply]);
+ const chat = useChatStore.getState();
+ const sent = { ...created, content: 'Follow-up', role: 'user' as const };
+ chat.internal_createClientMessage(
+ sent.id,
+ { ...sent, metadata: { scope: LOCAL_MESSAGE_SCOPE, steer: true } },
+ { conversationContext: context },
+ );
+
+ chat.replaceMessages([previousReply], { context });
+ expect(rowsOf(context)?.map(({ id }) => id)).toEqual([previousReply.id, sent.id]);
+
+ const persisted = { ...sent, metadata: { steer: true }, parentId: previousReply.id };
+ chat.replaceMessages([previousReply, persisted], { context });
+ expect(rowsOf(context)).toEqual([previousReply, persisted]);
+ });
+
it('drops a persisted row omitted by a read issued after the acknowledgement', async () => {
seedRows(context, [previousReply]);
createClientRow();
diff --git a/src/store/chat/slices/message/transcript/index.ts b/src/store/chat/slices/message/transcript/index.ts
index 452ad226453..fb0930a0305 100644
--- a/src/store/chat/slices/message/transcript/index.ts
+++ b/src/store/chat/slices/message/transcript/index.ts
@@ -573,6 +573,7 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
forgetClientRows,
remapClientRows,
headResolutions,
+ isUnconfirmedClientRow: (id: string) => unconfirmedClientIds.has(id),
keyOf,
pendingInterventions,
/** The entry's current value, as the replica sees it. */