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 sent file attachments on the user message immediately (#23476)

Rdmclin27b8bc57950bf
diff --git a/packages/types/src/files/upload.ts b/packages/types/src/files/upload.ts
index 4d700f86877..d49df0234a3 100644
--- a/packages/types/src/files/upload.ts
+++ b/packages/types/src/files/upload.ts
@@ -69,6 +69,12 @@ export interface UploadFileItem {
/** Stable business reason used to render an in-context remedy action. */
errorCode?: string;
file: File;
+ /**
+ * MIME type stored with the uploaded file. Set once the upload succeeds; it can
+ * differ from `file.type` (a blank or wrong browser type corrected by byte
+ * sniffing or the file extension), and decides how the sent message shows it.
+ */
+ fileType?: string;
/**
* the file url after upload,it will be s3 url
* if enable the S3 storage, or the data is same as base64Url
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index a351630ce82..5fced87d237 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -58,6 +58,7 @@ import { transcribeVoiceMessage } from './transcribeVoiceMessage';
import { useConversationChatInputUiState } from './useConversationChatInputUiState';
import { useRestoreServerQueue } from './useRestoreServerQueue';
import {
+ clearSentAttachments,
getContextWindow,
getConversationSendButtonProps,
partitionSendableUploads,
@@ -415,11 +416,7 @@ const ChatInput = memo<ChatInputProps>(
const clearComposer = () => {
clearContent();
- fileStore.clearChatUploadFileList(
- contextKey,
- currentFileList.map((file) => file.id),
- );
- fileStore.clearChatContextSelections(contextKey);
+ clearSentAttachments(fileStore, contextKey, currentFileList);
};
// A deferred send was armed from the composer (see `scheduledSendAt`):
@@ -455,8 +452,7 @@ const ChatInput = memo<ChatInputProps>(
stillHere: messageMapKey(storeApi.getState().context) === messageMapKey(sendContext),
});
if (handoff.clearEditor) clearContent();
- fileStore.clearChatUploadFileList(contextKey);
- fileStore.clearChatContextSelections(contextKey);
+ clearSentAttachments(fileStore, contextKey, currentFileList);
const { contextSelections, pageSelections } =
buildMessageContextSelections(currentContextList);
@@ -477,7 +473,12 @@ const ChatInput = memo<ChatInputProps>(
// message owned the content must hand every part of it back —
// uploads and context selections, not just the editor text the
// lifecycle restores on its own.
- store.restoreChatUploadFileList(contextKey, currentFileList);
+ // Back in their original places, around any failed upload that stayed.
+ store.restoreChatUploadFileList(
+ contextKey,
+ currentFileList,
+ uploadList.map((file) => file.id),
+ );
store.restoreChatContextSelections(contextKey, currentContextList);
},
pageSelections,
diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.ts
index 26fc51f523e..674800db228 100644
--- a/src/features/Conversation/ChatInput/utils.test.ts
+++ b/src/features/Conversation/ChatInput/utils.test.ts
@@ -3,8 +3,11 @@ import { describe, expect, it, vi } from 'vitest';
import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { fileChatSelectors, useFileStore } from '@/store/file';
+import type { UploadFileItem } from '@/types/files/upload';
import {
+ clearSentAttachments,
createQueueSendNowGate,
getContextWindow,
getConversationChatInputUiState,
@@ -290,6 +293,30 @@ describe('partitionSendableUploads', () => {
});
});
+describe('clearSentAttachments', () => {
+ it('keeps a failed upload in the composer and clears only what was sent', () => {
+ const contextKey = 'main_agent-1';
+ const chip = (id: string, status: UploadFileItem['status']) =>
+ ({ file: new File([], `${id}.zip`), id, status }) as UploadFileItem;
+ const uploads = [chip('sent', 'success'), chip('failed', 'error')];
+ useFileStore.setState({
+ chatContextSelectionsByContext: { [contextKey]: [{ id: 'sel' } as any] },
+ chatUploadFileListByContext: { [contextKey]: uploads },
+ });
+
+ const { sendable } = partitionSendableUploads(uploads);
+ clearSentAttachments(useFileStore.getState(), contextKey, sendable);
+
+ const state = useFileStore.getState();
+ expect(
+ fileChatSelectors
+ .chatUploadFileList(contextKey)(state)
+ .map((f) => f.id),
+ ).toEqual(['failed']);
+ expect(fileChatSelectors.chatContextSelections(contextKey)(state)).toEqual([]);
+ });
+});
+
describe('getConversationChatInputUiState', () => {
it('shows follow-up placeholder and only the stop button while loading with an empty composer', () => {
expect(
diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.ts
index 01dc6b052e5..57ec54a392c 100644
--- a/src/features/Conversation/ChatInput/utils.ts
+++ b/src/features/Conversation/ChatInput/utils.ts
@@ -18,6 +18,7 @@ import {
} 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 { FileStore } from '@/store/file/store';
import type { UploadFileItem } from '@/types/files/upload';
import { isMachineErrorMessage } from '@/utils/machineErrorMessage';
@@ -212,6 +213,22 @@ export const partitionSendableUploads = <T extends Pick<UploadFileItem, 'status'
return { failed, sendable };
};
+/**
+ * Empty the composer of what a send took: the sent attachments and the context
+ * selections. A failed or cancelled upload was not sent, so it stays to retry or remove.
+ */
+export const clearSentAttachments = (
+ fileStore: Pick<FileStore, 'clearChatContextSelections' | 'clearChatUploadFileList'>,
+ contextKey: string,
+ sentFiles: Pick<UploadFileItem, 'id'>[],
+) => {
+ fileStore.clearChatUploadFileList(
+ contextKey,
+ sentFiles.map((file) => file.id),
+ );
+ fileStore.clearChatContextSelections(contextKey);
+};
+
export interface ConversationChatInputUiState {
placeholderVariant: PlaceholderVariant;
/** Show Send beside Stop so a typed follow-up can be queued by click. */
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.optimisticFiles.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.optimisticFiles.test.ts
new file mode 100644
index 00000000000..e091a5e1643
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.optimisticFiles.test.ts
@@ -0,0 +1,107 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { aiChatService } from '@/services/aiChat';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { getSessionStoreState } from '@/store/session';
+import { useUserStore } from '@/store/user';
+
+import { useChatStore } from '../../../../store';
+import { createMockAgentConfig, TEST_IDS } from './fixtures';
+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },
+ },
+}));
+
+beforeEach(() => {
+ resetTestEnvironment();
+ setupMockSelectors();
+ spyOnMessageService();
+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);
+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);
+ useUserStore.setState({ workspaceUserPreference: {} });
+
+ act(() => {
+ useChatStore.setState({
+ executeClientAgent: vi.fn(),
+ mainInputEditor: null,
+ refreshMessages: vi.fn(),
+ refreshTopic: vi.fn(),
+ });
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('sendMessage optimistic attachments', () => {
+ it('renders every attached file on the sent bubble before the server answers', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = TEST_IDS.SESSION_ID;
+ const topicId = TEST_IDS.TOPIC_ID;
+ const key = messageMapKey({ agentId, topicId });
+ act(() => {
+ useChatStore.setState({ activeAgentId: agentId, activeTopicId: topicId });
+ });
+ // The send is still in flight: the bubble must already show the files.
+ let releaseServer!: () => void;
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ releaseServer = () => resolve(undefined as any);
+ }),
+ );
+ const zip = (id: string, name: string, size: number) =>
+ ({
+ file: Object.defineProperty(new File([], name, { type: 'application/zip' }), 'size', {
+ value: size,
+ }),
+ fileUrl: `https://example.com/${id}.zip`,
+ id,
+ status: 'success',
+ }) as any;
+
+ let sending!: Promise<unknown>;
+ act(() => {
+ sending = result.current.sendMessage({
+ context: { agentId, threadId: null, topicId },
+ files: [
+ zip('file-twitter', 'Twitter 配图.zip', 175_000_000),
+ zip('file-site', '官网与文章配图.zip', 177_500_000),
+ zip('file-mail', '邮件配图.zip', 6_400_000),
+ ],
+ message: '好,都给你',
+ });
+ });
+
+ await waitFor(() => {
+ const userMessage = useChatStore
+ .getState()
+ .dbMessagesMap[key]?.find((message) => message.role === 'user');
+ expect(userMessage?.fileList).toEqual([
+ expect.objectContaining({
+ fileType: 'application/zip',
+ id: 'file-twitter',
+ name: 'Twitter 配图.zip',
+ size: 175_000_000,
+ }),
+ expect.objectContaining({
+ id: 'file-site',
+ name: '官网与文章配图.zip',
+ size: 177_500_000,
+ }),
+ expect.objectContaining({ id: 'file-mail', name: '邮件配图.zip', size: 6_400_000 }),
+ ]);
+ });
+
+ await act(async () => {
+ releaseServer();
+ await sending;
+ });
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia.test.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia.test.ts
new file mode 100644
index 00000000000..ab8cbb9c733
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ reconstructUploadFilesFromQueue,
+ snapshotQueuedFiles,
+} from '@/store/chat/slices/operation/types';
+import type { UploadFileItem } from '@/types/files/upload';
+
+import { getOptimisticMessageMedia } from './optimisticMessageMedia';
+
+const upload = (id: string, name: string, type: string, size = 1024): UploadFileItem => ({
+ file: Object.defineProperty(new File([], name, { type }), 'size', { value: size }),
+ fileUrl: `https://example.com/${id}`,
+ id,
+ status: 'success',
+});
+
+describe('getOptimisticMessageMedia', () => {
+ it('turns non-media uploads into file cards with name, size and type, in send order', () => {
+ const media = getOptimisticMessageMedia([
+ upload('zip-1', 'a.zip', 'application/zip', 175_000_000),
+ upload('pdf-1', 'b.pdf', 'application/pdf', 2048),
+ ]);
+
+ expect(media.fileList).toEqual([
+ {
+ fileType: 'application/zip',
+ id: 'zip-1',
+ name: 'a.zip',
+ size: 175_000_000,
+ url: 'https://example.com/zip-1',
+ },
+ {
+ fileType: 'application/pdf',
+ id: 'pdf-1',
+ name: 'b.pdf',
+ size: 2048,
+ url: 'https://example.com/pdf-1',
+ },
+ ]);
+ expect(media.imageList).toBeUndefined();
+ });
+
+ it('groups attachments the way the persisted message does', () => {
+ const media = getOptimisticMessageMedia([
+ upload('png', 'p.png', 'image/png'),
+ upload('svg', 's.svg', 'image/svg+xml'),
+ upload('mp4', 'v.mp4', 'video/mp4'),
+ upload('mp3', 'a.mp3', 'audio/mpeg'),
+ {
+ ...upload('voice', 'voice.webm', 'video/webm'),
+ audioMetadata: { durationMs: 1, mimeType: 'audio/webm' },
+ },
+ upload('zip', 'z.zip', 'application/zip'),
+ ]);
+
+ expect(media.imageList?.map((item) => item.id)).toEqual(['png']);
+ expect(media.videoList?.map((item) => item.id)).toEqual(['mp4']);
+ expect(media.audioList?.map((item) => item.id)).toEqual(['mp3', 'voice']);
+ // Only model-readable image formats render as images; an SVG comes back as a file card.
+ expect(media.fileList?.map((item) => item.id)).toEqual(['svg', 'zip']);
+ });
+
+ it('leaves out id-only entries that carry no file to describe', () => {
+ const media = getOptimisticMessageMedia([{ id: 'legacy' } as UploadFileItem]);
+
+ expect(media.fileList).toBeUndefined();
+ });
+
+ it('classifies by the type the upload was stored with', () => {
+ const media = getOptimisticMessageMedia([
+ { ...upload('png', 'p', ''), fileType: 'image/png' },
+ { ...upload('m4a', 'a.m4a', 'video/mp4'), fileType: 'audio/mp4' },
+ { ...upload('bin', 'b.bin', ''), fileType: 'application/octet-stream' },
+ ]);
+
+ expect(media.imageList?.map((item) => item.id)).toEqual(['png']);
+ expect(media.audioList?.map((item) => item.id)).toEqual(['m4a']);
+ expect(media.fileList).toEqual([
+ expect.objectContaining({ fileType: 'application/octet-stream', id: 'bin' }),
+ ]);
+ });
+
+ it('keeps the stored type through a queued send', () => {
+ const queued = snapshotQueuedFiles([{ ...upload('png', 'p', ''), fileType: 'image/png' }]);
+ const media = getOptimisticMessageMedia(reconstructUploadFilesFromQueue(queued!));
+
+ expect(media.imageList?.map((item) => item.id)).toEqual(['png']);
+ });
+
+ it('shows no zero-byte card for a queued file saved without its size', () => {
+ const media = getOptimisticMessageMedia(
+ reconstructUploadFilesFromQueue([
+ { id: 'legacy', mimeType: 'application/zip', name: 'old.zip', url: '' },
+ ]),
+ );
+
+ expect(media.fileList).toBeUndefined();
+ });
+
+ it('keeps the file size through a queued send', () => {
+ const queued = snapshotQueuedFiles([upload('zip-1', 'a.zip', 'application/zip', 177_500_000)]);
+ const media = getOptimisticMessageMedia(reconstructUploadFilesFromQueue(queued!));
+
+ expect(media.fileList).toEqual([expect.objectContaining({ name: 'a.zip', size: 177_500_000 })]);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia.ts
index 0922fd3cf71..f59fec17ffc 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/optimisticMessageMedia.ts
@@ -1,11 +1,52 @@
-import type { ChatAudioItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
+import type { ChatAudioItem, ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
+import { isSizeUnknownPlaceholder } from '@/store/chat/slices/operation/types';
import type { UploadFileItem } from '@/types/files/upload';
import { rememberLocalImagePreview } from '@/utils/localImagePreview';
+/**
+ * Image formats the server renders as images (`groupMessageFilesByKind` in
+ * `packages/database/src/models/message/attachments.ts`). Any other `image/*`
+ * upload (SVG, TIFF, a CAD drawing) comes back as a file card, so the
+ * optimistic bubble shows it as one too and nothing moves once the persisted
+ * message replaces it.
+ */
+const MESSAGE_IMAGE_MIME_TYPES = new Set([
+ 'image/gif',
+ 'image/jpeg',
+ 'image/jpg',
+ 'image/png',
+ 'image/webp',
+]);
+
+/** The type the upload was stored with, else the browser's. */
+const fileTypeOf = (file: UploadFileItem) => file.fileType || file.file?.type || '';
+
+const mimeTypeOf = (file: UploadFileItem) => fileTypeOf(file).split(';')[0].trim().toLowerCase();
+
+type MediaKind = 'audio' | 'file' | 'image' | 'video';
+
+const kindOf = (file: UploadFileItem): MediaKind => {
+ // A voice recording is an audio message whatever container type it was saved in.
+ if (file.audioMetadata) return 'audio';
+ const mimeType = mimeTypeOf(file);
+ if (MESSAGE_IMAGE_MIME_TYPES.has(mimeType)) return 'image';
+ if (mimeType.startsWith('video')) return 'video';
+ if (mimeType.startsWith('audio')) return 'audio';
+ return 'file';
+};
+
+/**
+ * The attachments an optimistic user message renders with, built from what the
+ * composer already holds (name, size, type, local preview). Grouped and ordered
+ * the way the server returns them, so the sent bubble shows every attachment
+ * from the first paint and keeps them in place when the persisted row lands.
+ */
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'));
+ const byKind = (kind: MediaKind) => files.filter((file) => kindOf(file) === kind);
+
+ const imageFiles = byKind('image');
// Persisted images also use the local copy while the remote URL loads.
for (const file of imageFiles) {
if (file.status === 'success' && file.previewUrl)
@@ -17,20 +58,32 @@ export const getOptimisticMessageMedia = (files: UploadFileItem[] = []) => {
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'))
+ const videoList: ChatVideoItem[] = byKind('video').map((file) => ({
+ alt: file.file?.name || file.id,
+ id: file.id,
+ url: urlOf(file),
+ }));
+ const audioList: ChatAudioItem[] = byKind('audio').map((file) => ({
+ ...file.audioMetadata,
+ alt: file.file?.name || file.id,
+ id: file.id,
+ url: urlOf(file),
+ }));
+ // An id-only entry, or a queued one saved without its size by an older client,
+ // has no name or size to show; the persisted message brings its card.
+ const fileList: ChatFileItem[] = byKind('file')
+ .filter((file) => !!file.file && !isSizeUnknownPlaceholder(file.file))
.map((file) => ({
- ...file.audioMetadata,
- alt: file.file?.name || file.id,
+ fileType: fileTypeOf(file),
id: file.id,
+ name: file.file.name,
+ size: file.file.size,
url: urlOf(file),
}));
return {
audioList: audioList.length > 0 ? audioList : undefined,
+ fileList: fileList.length > 0 ? fileList : undefined,
imageList: imageList.length > 0 ? imageList : undefined,
videoList: videoList.length > 0 ? videoList : undefined,
};
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index d8e27a25cf7..0904eb35c39 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -285,6 +285,8 @@ export interface QueuedFile {
/** MIME type, e.g. `image/png`, `video/mp4`, `application/pdf` */
mimeType: string;
name: string;
+ /** Byte size, so the sent bubble's file card shows it before the server answers. */
+ size?: number;
/** Preview URL — S3 URL for uploaded files, blob/base64 for in-memory items */
url: string;
}
@@ -293,8 +295,9 @@ export interface QueuedFile {
* Rebuild `UploadFileItem`-shaped objects from queued previews so the resumed
* `sendMessage` can derive audioList/imageList/videoList AND so we can repopulate
* `chatUploadFileList` when the user edits a queued message. The synthesized
- * `File` carries only `name` + `type` (zero bytes) — the consumers we hit only
- * read `file.name`, `file.type`, plus the URL fields we set below.
+ * `File` carries only `name`, `type` and the snapshotted `size` (zero bytes of
+ * content) — the consumers we hit only read `file.name`, `file.type`,
+ * `file.size`, plus the URL fields we set below.
*
* We mirror the snapshotted `url` into both `fileUrl` and `previewUrl`: the
* optimistic-message path uses the `fileUrl || base64Url || previewUrl` fallback
@@ -311,17 +314,32 @@ export const snapshotQueuedFiles = (files?: UploadFileItem[]): QueuedFile[] | un
return files.map((f) => ({
audioMetadata: f.audioMetadata,
id: f.id,
- mimeType: f.file?.type ?? '',
+ mimeType: f.fileType || f.file?.type || '',
name: f.file?.name ?? f.id,
+ size: f.file?.size,
url: f.fileUrl || f.base64Url || f.previewUrl || '',
}));
};
+/** Placeholders rebuilt from a queued preview saved without its size (older clients). */
+const sizeUnknownPlaceholders = new WeakSet<File>();
+
+/** Whether `file` stands in for a queued upload whose real size was never recorded. */
+export const isSizeUnknownPlaceholder = (file: File) => sizeUnknownPlaceholders.has(file);
+
+/** A zero-byte `File` that reports the original upload's size. */
+const placeholderFile = ({ mimeType, name, size }: QueuedFile) => {
+ const file = new File([], name, { type: mimeType });
+ if (size === undefined) sizeUnknownPlaceholders.add(file);
+ else Object.defineProperty(file, 'size', { value: size });
+ return file;
+};
+
export const reconstructUploadFilesFromQueue = (files: QueuedFile[]): UploadFileItem[] =>
files.map((f) => ({
audioMetadata: f.audioMetadata,
id: f.id,
- file: new File([], f.name, { type: f.mimeType }),
+ file: placeholderFile(f),
fileUrl: f.url || undefined,
previewUrl: f.url || undefined,
status: 'success',
diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.ts
index d14de9325f3..5092e5ad4fd 100644
--- a/src/store/file/slices/chat/action.test.ts
+++ b/src/store/file/slices/chat/action.test.ts
@@ -266,6 +266,24 @@ describe('useFileStore:chat', () => {
expect(uploadList()).toEqual([newerFile, submittedFile]);
});
+ it('restoreChatUploadFileList puts restored uploads back around a retained failed one', () => {
+ const { result } = renderHook(() => useStore());
+ const a = { id: 'a', status: 'success' };
+ const failed = { id: 'b', status: 'error' };
+ const c = { id: 'c', status: 'success' };
+ const newer = { id: 'new', status: 'uploading' };
+
+ // The send took a and c; the failed b stayed, and a newer draft arrived meanwhile.
+ act(() => {
+ useStore.setState({
+ chatUploadFileListByContext: { [CONTEXT_KEY]: [failed, newer] } as any,
+ });
+ result.current.restoreChatUploadFileList(CONTEXT_KEY, [a, c] as any, ['a', 'b', 'c']);
+ });
+
+ expect(uploadList()).toEqual([a, failed, c, newer]);
+ });
+
// Regression: one global upload list showed a conversation's attachments in
// every other conversation, while its text draft stayed behind.
it('keeps the uploads of each conversation to itself', () => {
diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.ts
index 88285ae6208..b4ecee42770 100644
--- a/src/store/file/slices/chat/action.ts
+++ b/src/store/file/slices/chat/action.ts
@@ -267,15 +267,39 @@ export class FileActionImpl {
* rejected before any message owned them (e.g. the server refused the turn
* up front). Items already in the list are skipped by id so a concurrent
* draft does not end up with duplicates.
+ *
+ * `order` is the composer's id order before the send. When given, restored and
+ * retained items (e.g. a failed upload that never left) go back to those
+ * positions; anything newer keeps its place after them.
*/
- restoreChatUploadFileList = (contextKey: string, files: UploadFileItem[]): void => {
+ restoreChatUploadFileList = (
+ contextKey: string,
+ files: UploadFileItem[],
+ order?: string[],
+ ): void => {
if (files.length === 0) return;
- const currentIds = new Set(this.#getChatUploadFileList(contextKey).map((file) => file.id));
+ const current = this.#getChatUploadFileList(contextKey);
+ const currentIds = new Set(current.map((file) => file.id));
const restored = files.filter((file) => !currentIds.has(file.id));
if (restored.length === 0) return;
- this.#get().dispatchChatUploadFileList(contextKey, { files: restored, type: 'addFiles' });
+ if (!order) {
+ this.#get().dispatchChatUploadFileList(contextKey, { files: restored, type: 'addFiles' });
+ return;
+ }
+
+ const rank = new Map(order.map((id, index) => [id, index]));
+ const merged = [...current, ...restored];
+ const ranked = merged
+ .filter((file) => rank.has(file.id))
+ .sort((a, b) => rank.get(a.id)! - rank.get(b.id)!);
+ const unranked = merged.filter((file) => !rank.has(file.id));
+ this.#setChatUploadFileList(
+ contextKey,
+ [...ranked, ...unranked],
+ n('restoreChatUploadFileList'),
+ );
};
dispatchChatUploadFileList = (contextKey: string, payload: UploadFileListDispatch): void => {
diff --git a/src/store/file/slices/chat/shareVisitorUpload.test.ts b/src/store/file/slices/chat/shareVisitorUpload.test.ts
new file mode 100644
index 00000000000..f7fdd54f220
--- /dev/null
+++ b/src/store/file/slices/chat/shareVisitorUpload.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { shareChatService } from '@/services/shareChat';
+import { uploadService } from '@/services/upload';
+
+import { uploadShareVisitorFile } from './shareVisitorUpload';
+
+vi.mock('@/services/shareChat', () => ({
+ shareChatService: {
+ createFile: vi.fn(async () => ({ id: 'file-1', url: 'https://s3/file-1' })),
+ createUploadUrl: vi.fn(async () => ({ pathname: 'share/file-1', url: 'https://s3/put' })),
+ },
+}));
+vi.mock('@/services/upload', () => ({
+ uploadService: { uploadToPresignedUrl: vi.fn(async () => undefined) },
+}));
+vi.mock('@/utils/client/imageDimensions', () => ({
+ getImageDimensions: vi.fn(async () => undefined),
+}));
+vi.mock('@/utils/client/audioDuration', () => ({ getAudioDuration: vi.fn(async () => 1200) }));
+vi.mock('../upload/action', () => ({
+ normalizeUploadedFileType: vi.fn(async (file: File) => ({ file })),
+}));
+
+describe('uploadShareVisitorFile', () => {
+ it('reports the type the file was stored with on success', async () => {
+ // The browser calls an .m4a `video/mp4`; the upload stores it as audio.
+ const file = new File(['x'], 'voice.m4a', { type: 'video/mp4' });
+ const onStatusUpdate = vi.fn();
+
+ await uploadShareVisitorFile({ file, onStatusUpdate, shareId: 'share-1', uploadId: 'chip-1' });
+
+ const storedType = vi.mocked(shareChatService.createFile).mock.calls[0][0].fileType;
+ expect(storedType).toMatch(/^audio\//);
+ expect(uploadService.uploadToPresignedUrl).toHaveBeenCalled();
+ expect(onStatusUpdate).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ id: 'chip-1',
+ value: expect.objectContaining({ fileType: storedType, status: 'success' }),
+ }),
+ );
+ });
+});
diff --git a/src/store/file/slices/chat/shareVisitorUpload.ts b/src/store/file/slices/chat/shareVisitorUpload.ts
index 0ca98395f83..f461360337a 100644
--- a/src/store/file/slices/chat/shareVisitorUpload.ts
+++ b/src/store/file/slices/chat/shareVisitorUpload.ts
@@ -99,6 +99,7 @@ export const uploadShareVisitorFile = async ({
type: 'updateFile',
value: {
...(dimensions && { dimensions }),
+ fileType,
fileUrl: data.url,
id: data.id,
status: 'success',
diff --git a/src/store/file/slices/upload/action.test.ts b/src/store/file/slices/upload/action.test.ts
index 121ea2a314c..7cfdcc46944 100644
--- a/src/store/file/slices/upload/action.test.ts
+++ b/src/store/file/slices/upload/action.test.ts
@@ -374,6 +374,7 @@ describe('FileUploadAction', () => {
type: 'updateFile',
value: {
dimensions: mockDimensions,
+ fileType: 'image/jpeg',
fileUrl: mockFileResponse.url,
id: mockFileResponse.id,
status: 'success',
@@ -945,6 +946,7 @@ describe('FileUploadAction', () => {
type: 'updateFile',
value: {
dimensions: mockDimensions,
+ fileType: 'image/jpeg',
fileUrl: mockFileResponse.url,
id: mockFileResponse.id,
status: 'success',
diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.ts
index f3cd9e674f3..2d601b2ec44 100644
--- a/src/store/file/slices/upload/action.ts
+++ b/src/store/file/slices/upload/action.ts
@@ -266,6 +266,7 @@ export class FileUploadActionImpl {
type: 'updateFile',
value: {
...(dimensions && { dimensions }),
+ fileType,
fileUrl: data.url,
id: data.id,
status: 'success',