🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(chat): allow audio upload in agent mode and render audio with a waveform player (#16022)
Arvin Xu8b9fd761f6ee
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex bda52c337d9..abfa4f593a4 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -41,6 +41,8 @@"artifact.thinking": "Thinking","artifact.thought": "Thought process","artifact.unknownTitle": "Untitled Work",+ "audioPlayer.pause": "Pause audio",+ "audioPlayer.play": "Play audio","availableAgents": "Available Agents","backToBottom": "Jump to latest","beforeUnload.confirmLeave": "A request is still running. Leave anyway?",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 22d0215afe8..6ee4de66d93 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -41,6 +41,8 @@"artifact.thinking": "思考中","artifact.thought": "思考过程","artifact.unknownTitle": "未命名作品",+ "audioPlayer.pause": "暂停音频",+ "audioPlayer.play": "播放音频","availableAgents": "可用助理","backToBottom": "跳转到最新","beforeUnload.confirmLeave": "你有正在生成中的请求,确定要离开吗?",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 09990dff530..24e97fca7cb 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1,6 +1,8 @@export default {'ModelSwitch.title': 'Model','active': 'Active',+ 'audioPlayer.pause': 'Pause audio',+ 'audioPlayer.play': 'Play audio','agentBuilder.installPlugin.authRequired': 'Cloud MCP requires sign-in to continue','agentBuilder.installPlugin.cancel': 'Cancel','agentBuilder.installPlugin.clickApproveToConnect':diff --git a/src/components/DragUpload/useDragUpload.tsx b/src/components/DragUpload/useDragUpload.tsxindex 4301e2daf2b..8702444af39 100644--- a/src/components/DragUpload/useDragUpload.tsx+++ b/src/components/DragUpload/useDragUpload.tsx@@ -77,7 +77,8 @@ export const useDragUpload = (onUploadFiles: (files: File[]) => Promise<void>) =const model = useAgentStore(agentSelectors.currentAgentModel);const provider = useAgentStore(agentSelectors.currentAgentModelProvider);- const { canUploadImage, canUploadVideo } = useVisualMediaUploadAbility(model, provider);+ const agentId = useAgentStore((s) => s.activeAgentId ?? undefined);+ const { canUploadImage, canUploadVideo } = useVisualMediaUploadAbility(model, provider, agentId);const warnIfVisualUploadUnsupported = useCallback((files: File[]) => {diff --git a/src/components/DragUploadZone/useUploadFiles.ts b/src/components/DragUploadZone/useUploadFiles.tsindex 5085ec1dbfd..7773644842b 100644--- a/src/components/DragUploadZone/useUploadFiles.ts+++ b/src/components/DragUploadZone/useUploadFiles.ts@@ -24,6 +24,7 @@ export const useUploadFiles = (options: UseUploadFilesOptions) => {const { canUploadImage, canUploadVideo, canUploadAudio } = useVisualMediaUploadAbility(model,provider,+ agentId,);const uploadFiles = useFileStore((s) => s.uploadChatFiles);const { allowed: canUpload } = usePermission('create_content');diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsxindex a20423d9edd..857b9fe3a10 100644--- a/src/features/ChatInput/ActionBar/Plus/index.tsx+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx@@ -326,6 +326,7 @@ const PlusAction = memo(() => {const { canUploadImage, canUploadVideo, canUploadAudio } = useVisualMediaUploadAbility(model,provider,+ agentId,);const enableFC = useModelSupportToolUse(model, provider);const handleOpenKnowledge = useCallback(() => {diff --git a/src/features/ChatInput/ActionBar/Upload/index.tsx b/src/features/ChatInput/ActionBar/Upload/index.tsxindex 233c43f6d41..df4c42fd466 100644--- a/src/features/ChatInput/ActionBar/Upload/index.tsx+++ b/src/features/ChatInput/ActionBar/Upload/index.tsx@@ -59,6 +59,7 @@ const FileUpload = memo(() => {const { canUploadImage, canUploadVideo, canUploadAudio } = useVisualMediaUploadAbility(model,provider,+ agentId,);const [showTip, updateGuideState] = useUserStore((s) => [diff --git a/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx b/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsxindex 47e8c47a36b..7c1f9e16802 100644--- a/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx+++ b/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx@@ -3,6 +3,8 @@ import { memo } from 'react';import { type ChatAudioItem } from '@/types/index';+import AudioPlayer from './AudioPlayer';+interface AudioFileListViewerProps {items: ChatAudioItem[];}@@ -11,10 +13,7 @@ const AudioFileListViewer = memo<AudioFileListViewerProps>(({ items }) => {return (<Flexbox gap={8}>{items.map((item) => (- <audio controls key={item.id} style={{ maxWidth: '100%', width: 360 }}>- <source src={item.url} />- {item.alt}- </audio>+ <AudioPlayer alt={item.alt} key={item.id} url={item.url} />))}</Flexbox>);diff --git a/src/features/Conversation/Messages/User/components/AudioPlayer/index.tsx b/src/features/Conversation/Messages/User/components/AudioPlayer/index.tsxnew file mode 100644index 00000000000..4bdb4f55424--- /dev/null+++ b/src/features/Conversation/Messages/User/components/AudioPlayer/index.tsx@@ -0,0 +1,173 @@+'use client';++import { Icon } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { PauseIcon, PlayIcon } from 'lucide-react';+import { memo, type MouseEvent, useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useWaveform } from './useWaveform';++const styles = createStaticStyles(({ css, cssVar }) => ({+ bar: css`+ flex: 1;++ min-width: 2px;+ border-radius: 4px;++ background: ${cssVar.colorTextQuaternary};++ transition: background 120ms ease;+ `,+ barPlayed: css`+ background: ${cssVar.colorText};+ `,+ button: css`+ cursor: pointer;++ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 36px;+ height: 36px;+ border: none;+ border-radius: 8px;++ color: ${cssVar.colorBgContainer};++ background: ${cssVar.colorText};++ transition: opacity 120ms ease;++ &:hover {+ opacity: 0.8;+ }+ `,+ container: css`+ display: flex;+ gap: 12px;+ align-items: center;++ width: 360px;+ max-width: 100%;+ padding-block: 8px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 12px;++ background: ${cssVar.colorFillQuaternary};+ `,+ time: css`+ flex: none;++ min-width: 36px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ color: ${cssVar.colorTextSecondary};+ text-align: end;+ `,+ waveform: css`+ cursor: pointer;++ display: flex;+ flex: 1;+ gap: 2px;+ align-items: center;++ height: 32px;+ `,+}));++const formatTime = (seconds: number): string => {+ if (!Number.isFinite(seconds) || seconds < 0) return '0:00';+ const mins = Math.floor(seconds / 60);+ const secs = Math.floor(seconds % 60);+ return `${mins}:${secs.toString().padStart(2, '0')}`;+};++interface AudioPlayerProps {+ alt?: string;+ url: string;+}++const AudioPlayer = memo<AudioPlayerProps>(({ url, alt }) => {+ const { t } = useTranslation('chat');+ const audioRef = useRef<HTMLAudioElement>(null);+ const [isPlaying, setIsPlaying] = useState(false);+ const [currentTime, setCurrentTime] = useState(0);+ const [duration, setDuration] = useState(0);+ // Only fetch/decode the waveform once the user actually engages with the clip, so a conversation+ // full of audio attachments doesn't download every file just to draw decorative bars.+ const [waveformEnabled, setWaveformEnabled] = useState(false);++ const peaks = useWaveform(url, waveformEnabled);+ const progress = duration > 0 ? currentTime / duration : 0;++ const togglePlay = useCallback(() => {+ const audio = audioRef.current;+ if (!audio) return;+ setWaveformEnabled(true);+ if (audio.paused) void audio.play();+ else audio.pause();+ }, []);++ const handleSeek = useCallback(+ (e: MouseEvent<HTMLDivElement>) => {+ const audio = audioRef.current;+ if (!audio || !duration) return;+ setWaveformEnabled(true);+ const rect = e.currentTarget.getBoundingClientRect();+ const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width));+ audio.currentTime = ratio * duration;+ setCurrentTime(ratio * duration);+ },+ [duration],+ );++ return (+ <div className={styles.container}>+ <audio+ preload={'metadata'}+ ref={audioRef}+ src={url}+ onDurationChange={(e) => setDuration(e.currentTarget.duration)}+ onEnded={() => setIsPlaying(false)}+ onLoadedMetadata={(e) => setDuration(e.currentTarget.duration)}+ onPause={() => setIsPlaying(false)}+ onPlay={() => setIsPlaying(true)}+ onTimeUpdate={(e) => setCurrentTime(e.currentTarget.currentTime)}+ />+ <button+ aria-label={isPlaying ? t('audioPlayer.pause') : t('audioPlayer.play')}+ aria-pressed={isPlaying}+ className={styles.button}+ title={alt}+ type={'button'}+ onClick={togglePlay}+ >+ <Icon icon={isPlaying ? PauseIcon : PlayIcon} size={16} />+ </button>+ <div className={styles.waveform} onClick={handleSeek}>+ {peaks.map((peak, i) => {+ const played = peaks.length > 0 && i / peaks.length <= progress;+ return (+ <div+ className={played ? `${styles.bar} ${styles.barPlayed}` : styles.bar}+ key={i}+ style={{ height: `${Math.round(peak * 100)}%` }}+ />+ );+ })}+ </div>+ <span className={styles.time}>{formatTime(currentTime || duration)}</span>+ </div>+ );+});++AudioPlayer.displayName = 'AudioPlayer';++export default AudioPlayer;diff --git a/src/features/Conversation/Messages/User/components/AudioPlayer/useWaveform.ts b/src/features/Conversation/Messages/User/components/AudioPlayer/useWaveform.tsnew file mode 100644index 00000000000..80a966d0d47--- /dev/null+++ b/src/features/Conversation/Messages/User/components/AudioPlayer/useWaveform.ts@@ -0,0 +1,92 @@+import { useEffect, useRef, useState } from 'react';++export const BAR_COUNT = 56;++// Skip decoding files larger than this. decodeAudioData holds the full decoded PCM in memory, so+// big recordings would spike memory for what is only a decorative waveform — fall back instead.+const MAX_DECODE_BYTES = 20 * 1024 * 1024;++// Deterministic fallback bars when decoding isn't possible (unsupported codec, CORS, network+// error, oversized file, etc.) so the player still shows a stable, non-flat waveform shape.+const fallbackPeaks = (seed: string): number[] => {+ let hash = 0;+ for (let i = 0; i < seed.length; i += 1) hash = (hash * 31 + seed.charCodeAt(i)) >>> 0;++ return Array.from({ length: BAR_COUNT }, (_, i) => {+ hash = (hash * 1_103_515_245 + 12_345) & 0x7fff_ffff;+ const v = (hash % 1000) / 1000;+ // Taper the ends and bias toward mid heights so it reads as a waveform, not noise.+ const taper = Math.sin((i / (BAR_COUNT - 1)) * Math.PI);+ return 0.2 + v * 0.8 * (0.5 + 0.5 * taper);+ });+};++const extractPeaks = (buffer: AudioBuffer, bars: number): number[] => {+ const channel = buffer.getChannelData(0);+ const blockSize = Math.max(1, Math.floor(channel.length / bars));++ const peaks: number[] = [];+ for (let i = 0; i < bars; i += 1) {+ let sum = 0;+ const start = i * blockSize;+ for (let j = 0; j < blockSize; j += 1) sum += Math.abs(channel[start + j] || 0);+ peaks.push(sum / blockSize);+ }++ const max = Math.max(...peaks, 0.000_1);+ // Floor each bar so quiet sections stay visible.+ return peaks.map((p) => Math.max(0.08, p / max));+};++/**+ * Decode an audio url into normalized waveform peaks (0..1) for visualization. Falls back to a+ * deterministic shape if the audio can't be fetched/decoded (e.g. unsupported codec, oversized).+ *+ * The decode is lazy: it only runs once `enabled` is true (set on first playback) so opening a+ * conversation with many audio attachments doesn't download/decode every clip up front.+ */+export const useWaveform = (url: string, enabled: boolean): number[] => {+ const [peaks, setPeaks] = useState<number[]>(() => fallbackPeaks(url));+ const requestedUrl = useRef<string>('');++ useEffect(() => {+ if (!enabled) return;+ if (typeof window === 'undefined') return;+ // Avoid re-decoding the same url across re-renders.+ if (requestedUrl.current === url) return;+ requestedUrl.current = url;++ let cancelled = false;+ let ctx: AudioContext | undefined;++ const run = async () => {+ try {+ const Ctor = window.AudioContext || (window as any).webkitAudioContext;+ if (!Ctor) return;++ const res = await fetch(url);+ const arrayBuffer = await res.arrayBuffer();+ if (cancelled || arrayBuffer.byteLength > MAX_DECODE_BYTES) return;++ ctx = new Ctor();+ const audioBuffer = await ctx.decodeAudioData(arrayBuffer);+ if (cancelled) return;++ setPeaks(extractPeaks(audioBuffer, BAR_COUNT));+ } catch {+ // keep the fallback peaks+ } finally {+ await ctx?.close?.();+ }+ };++ void run();++ return () => {+ cancelled = true;+ void ctx?.close?.();+ };+ }, [url, enabled]);++ return peaks;+};diff --git a/src/hooks/useVisualMediaUploadAbility.test.ts b/src/hooks/useVisualMediaUploadAbility.test.tsindex 6a0f6d200e6..93d3547651d 100644--- a/src/hooks/useVisualMediaUploadAbility.test.ts+++ b/src/hooks/useVisualMediaUploadAbility.test.ts@@ -1,17 +1,28 @@import { renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { useModelSupportAudio } from '@/hooks/useModelSupportAudio';import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';import { useModelSupportVideo } from '@/hooks/useModelSupportVideo';import { useModelSupportVision } from '@/hooks/useModelSupportVision';+import { useAgentStore } from '@/store/agent';import { useAiInfraStore } from '@/store/aiInfra';import { useServerConfigStore } from '@/store/serverConfig';import { useVisualMediaUploadAbility } from './useVisualMediaUploadAbility';+vi.mock('@/hooks/useModelSupportAudio');vi.mock('@/hooks/useModelSupportToolUse');vi.mock('@/hooks/useModelSupportVideo');vi.mock('@/hooks/useModelSupportVision');+vi.mock('@/store/agent', () => ({ useAgentStore: vi.fn() }));+vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgentEnableModeById: (_id: string) => (s: { enableMode?: boolean }) => !!s.enableMode,+ isAgentHeterogeneousById: (_id: string) => (s: { heterogeneous?: boolean }) =>+ !!s.heterogeneous,+ },+}));vi.mock('@/store/aiInfra', () => ({aiModelSelectors: {getEnabledModelById:@@ -37,18 +48,25 @@ vi.mock('@/store/serverConfig', () => ({useServerConfigStore: vi.fn(),}));+const mockedUseModelSupportAudio = vi.mocked(useModelSupportAudio);const mockedUseModelSupportToolUse = vi.mocked(useModelSupportToolUse);const mockedUseModelSupportVideo = vi.mocked(useModelSupportVideo);const mockedUseModelSupportVision = vi.mocked(useModelSupportVision);+const mockedUseAgentStore = vi.mocked(useAgentStore);const mockedUseAiInfraStore = vi.mocked(useAiInfraStore);const mockedUseServerConfigStore = vi.mocked(useServerConfigStore);describe('useVisualMediaUploadAbility', () => {beforeEach(() => {vi.clearAllMocks();+ mockedUseModelSupportAudio.mockReturnValue(false);mockedUseModelSupportVision.mockReturnValue(false);mockedUseModelSupportVideo.mockReturnValue(false);mockedUseModelSupportToolUse.mockReturnValue(false);+ // Default: no agent-mode bypass (plain chat).+ mockedUseAgentStore.mockImplementation((selector: any) =>+ selector({ enableMode: false, heterogeneous: false } as any),+ );mockedUseAiInfraStore.mockImplementation((selector) =>selector({ enabledAiModels: [] } as any),);@@ -157,4 +175,47 @@ describe('useVisualMediaUploadAbility', () => {expect(result.current.canUploadImage).toBe(true);expect(result.current.canUploadVideo).toBe(false);});++ it('should bypass the media gate in agent mode regardless of model abilities', () => {+ mockedUseAgentStore.mockImplementation((selector: any) =>+ selector({ enableMode: true, heterogeneous: false } as any),+ );++ const { result } = renderHook(() =>+ useVisualMediaUploadAbility('model', 'provider', 'agent-1'),+ );++ expect(result.current.canUploadAudio).toBe(true);+ expect(result.current.canUploadImage).toBe(true);+ expect(result.current.canUploadVideo).toBe(true);+ });++ it('should bypass the media gate for heterogeneous agents', () => {+ mockedUseAgentStore.mockImplementation((selector: any) =>+ selector({ enableMode: false, heterogeneous: true } as any),+ );++ const { result } = renderHook(() =>+ useVisualMediaUploadAbility('model', 'provider', 'agent-1'),+ );++ expect(result.current.canUploadAudio).toBe(true);+ expect(result.current.canUploadImage).toBe(true);+ expect(result.current.canUploadVideo).toBe(true);+ });++ it('should not bypass the media gate when agent mode is explicitly disabled', () => {+ mockedUseModelSupportAudio.mockReturnValue(false);+ mockedUseAgentStore.mockImplementation((selector: any) =>+ selector({ enableMode: false, heterogeneous: false } as any),+ );++ const { result } = renderHook(() =>+ useVisualMediaUploadAbility('model', 'provider', 'agent-1'),+ );++ expect(result.current.canUploadAudio).toBe(false);+ expect(result.current.canUploadImage).toBe(false);+ expect(result.current.canUploadVideo).toBe(false);+ });});diff --git a/src/hooks/useVisualMediaUploadAbility.ts b/src/hooks/useVisualMediaUploadAbility.tsindex 6cc63e7a8b2..d90e1d3e481 100644--- a/src/hooks/useVisualMediaUploadAbility.ts+++ b/src/hooks/useVisualMediaUploadAbility.ts@@ -2,10 +2,12 @@ import { useModelSupportAudio } from '@/hooks/useModelSupportAudio';import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';import { useModelSupportVideo } from '@/hooks/useModelSupportVideo';import { useModelSupportVision } from '@/hooks/useModelSupportVision';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';-export const useVisualMediaUploadAbility = (model: string, provider: string) => {+export const useVisualMediaUploadAbility = (model: string, provider: string, agentId?: string) => {const supportVision = useModelSupportVision(model, provider);const supportVideo = useModelSupportVideo(model, provider);const supportAudio = useModelSupportAudio(model, provider);@@ -25,6 +27,22 @@ export const useVisualMediaUploadAbility = (model: string, provider: string) =>const fallbackSupportVideo = fallbackConfigured && fallbackModel?.abilities?.video !== false;const canUseVisualUnderstanding = enableVisualUnderstanding && supportToolUse;+ // In agent mode (tool calls) or heterogeneous agents (Claude Code / Codex, etc.) the agent+ // can parse any file via scripts/terminal, so the upload should not be gated on the model's+ // own multimodal ability. Mirror the store's `enforceFileTypeWhitelist` bypass in+ // `uploadChatFiles` so the input UI doesn't silently drop audio/video/image the agent could+ // still handle (e.g. .m4a on a non-audio model). See lobehub/lobehub#15770.+ const bypassMediaGate = useAgentStore(+ (s) =>+ !!agentId &&+ (agentByIdSelectors.getAgentEnableModeById(agentId)(s) ||+ agentByIdSelectors.isAgentHeterogeneousById(agentId)(s)),+ );++ if (bypassMediaGate) {+ return { canUploadAudio: true, canUploadImage: true, canUploadVideo: true };+ }+return {canUploadAudio: supportAudio,canUploadImage: supportVision || (canUseVisualUnderstanding && fallbackSupportVision),diff --git a/src/store/file/slices/chat/uploadGuard.test.ts b/src/store/file/slices/chat/uploadGuard.test.tsindex 6aed85ca1c1..585fb626bc7 100644--- a/src/store/file/slices/chat/uploadGuard.test.ts+++ b/src/store/file/slices/chat/uploadGuard.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from 'vitest';-import { filterSupportedChatUploadFiles, isSupportedChatUploadFile } from './uploadGuard';+import {+ audioMimeFromExtension,+ filterSupportedChatUploadFiles,+ isSupportedChatUploadFile,+} from './uploadGuard';describe('isSupportedChatUploadFile', () => {it('accepts supported chat image formats', () => {@@ -50,6 +54,21 @@ describe('isSupportedChatUploadFile', () => {});});+describe('audioMimeFromExtension', () => {+ it('maps known audio extensions to a canonical audio mime', () => {+ expect(audioMimeFromExtension('voice.m4a')).toBe('audio/mp4');+ expect(audioMimeFromExtension('song.mp3')).toBe('audio/mpeg');+ expect(audioMimeFromExtension('clip.WAV')).toBe('audio/wav');+ expect(audioMimeFromExtension('note.opus')).toBe('audio/opus');+ });++ it('returns undefined for non-audio extensions', () => {+ expect(audioMimeFromExtension('movie.mp4')).toBeUndefined();+ expect(audioMimeFromExtension('doc.pdf')).toBeUndefined();+ expect(audioMimeFromExtension('noext')).toBeUndefined();+ });+});+describe('filterSupportedChatUploadFiles', () => {it('splits supported and unsupported files by default', () => {const png = new File(['image'], 'image.png', { type: 'image/png' });diff --git a/src/store/file/slices/chat/uploadGuard.ts b/src/store/file/slices/chat/uploadGuard.tsindex 6502770bc6c..f22b64076aa 100644--- a/src/store/file/slices/chat/uploadGuard.ts+++ b/src/store/file/slices/chat/uploadGuard.ts@@ -103,6 +103,31 @@ const SUPPORTED_CHAT_DOCUMENT_MIME_TYPES = new Set([const getExtension = (filename: string) => filename.split('.').pop()?.toLowerCase() || '';+// Canonical audio mime for each supported extension. Audio containers like .m4a share the+// ISO-BMFF box layout with .mp4, so the browser often reports an empty mime and byte-sniffing+// (file-type) can report `video/mp4`. We trust the extension for these to keep them classified+// and rendered as audio.+const AUDIO_EXTENSION_MIME_TYPES: Record<string, string> = {+ aac: 'audio/aac',+ flac: 'audio/flac',+ m4a: 'audio/mp4',+ m4b: 'audio/mp4',+ mp3: 'audio/mpeg',+ oga: 'audio/ogg',+ ogg: 'audio/ogg',+ opus: 'audio/opus',+ wav: 'audio/wav',+ weba: 'audio/webm',+};++/**+ * Returns the canonical audio mime for a filename whose extension is a known audio container,+ * or `undefined` otherwise. Use this to backfill/override an empty or mis-detected mime so the+ * file is classified and rendered as audio. See lobehub/lobehub#15988.+ */+export const audioMimeFromExtension = (filename: string): string | undefined =>+ AUDIO_EXTENSION_MIME_TYPES[getExtension(filename)];+export const isSupportedChatUploadFile = (file: File) => {const fileType = file.type.toLowerCase();const extension = getExtension(file.name);diff --git a/src/store/file/slices/upload/action.test.ts b/src/store/file/slices/upload/action.test.tsindex 97d8991a45a..b4acb7c7773 100644--- a/src/store/file/slices/upload/action.test.ts+++ b/src/store/file/slices/upload/action.test.ts@@ -594,6 +594,74 @@ describe('FileUploadAction', () => {undefined,);});++ it('should backfill audio mime from extension when byte-sniffing reports video/mp4', async () => {+ const { result } = renderHook(() => useStore());++ // .m4a shares the ISO-BMFF container with mp4, so file-type may report video/mp4.+ const mockFile = new File(['test content'], 'voice.m4a', { type: '' });+ const mockMetadata = {+ date: '12345',+ dirname: '/uploads',+ filename: 'voice.m4a',+ path: '/uploads/voice.m4a',+ };++ vi.mocked(getImageDimensions).mockResolvedValue(undefined);+ vi.spyOn(fileService, 'checkFileHash').mockResolvedValue({ isExist: false });+ vi.spyOn(uploadService, 'uploadFileToS3').mockResolvedValue({+ data: mockMetadata,+ success: true,+ });+ vi.spyOn(fileService, 'createFile').mockResolvedValue({+ id: 'file-id-m4a',+ url: 'https://example.com/voice.m4a',+ });++ const { fileTypeFromBuffer } = await import('file-type');+ vi.mocked(fileTypeFromBuffer).mockResolvedValue({ ext: 'mp4', mime: 'video/mp4' } as any);++ await act(async () => {+ await result.current.uploadWithProgress({ file: mockFile });+ });++ expect(fileService.createFile).toHaveBeenCalledWith(+ expect.objectContaining({ fileType: 'audio/mp4' }),+ undefined,+ );+ });++ it('should keep a correct audio mime reported by the browser', async () => {+ const { result } = renderHook(() => useStore());++ const mockFile = new File(['test content'], 'voice.m4a', { type: 'audio/x-m4a' });+ const mockMetadata = {+ date: '12345',+ dirname: '/uploads',+ filename: 'voice.m4a',+ path: '/uploads/voice.m4a',+ };++ vi.mocked(getImageDimensions).mockResolvedValue(undefined);+ vi.spyOn(fileService, 'checkFileHash').mockResolvedValue({ isExist: false });+ vi.spyOn(uploadService, 'uploadFileToS3').mockResolvedValue({+ data: mockMetadata,+ success: true,+ });+ vi.spyOn(fileService, 'createFile').mockResolvedValue({+ id: 'file-id-m4a-2',+ url: 'https://example.com/voice.m4a',+ });++ await act(async () => {+ await result.current.uploadWithProgress({ file: mockFile });+ });++ expect(fileService.createFile).toHaveBeenCalledWith(+ expect.objectContaining({ fileType: 'audio/x-m4a' }),+ undefined,+ );+ });});describe('knowledge base integration', () => {diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.tsindex 4c2c1d35d4e..f266de7c797 100644--- a/src/store/file/slices/upload/action.ts+++ b/src/store/file/slices/upload/action.ts@@ -12,6 +12,7 @@ import { type FileMetadata, type UploadFileItem } from '@/types/files';import { getImageDimensions } from '@/utils/client/imageDimensions';import { type FileStore } from '../../store';+import { audioMimeFromExtension } from '../chat/uploadGuard';type OnStatusUpdate = (data:@@ -180,6 +181,12 @@ export class FileUploadActionImpl {fileType = type?.mime || 'text/plain';}+ // Audio containers like .m4a share the ISO-BMFF box with .mp4, so both the browser and+ // byte-sniffing may report an empty or `video/*` mime. Trust the extension to keep these+ // classified (and rendered) as audio.+ const audioMime = audioMimeFromExtension(normalizedFile.name);+ if (audioMime && !fileType.startsWith('audio/')) fileType = audioMime;+// 5. create file to dbconst data = await fileService.createFile({