🤯 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
✨ feat(chat): support web voice messages (#17744)
Tsukia58d1813096e
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.tsindex af8299ab16b..44004815e3f 100644--- a/apps/server/src/routers/lambda/__tests__/file.test.ts+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts@@ -41,6 +41,7 @@ function createCallerWithCtx(partialCtx: any = {}) {findByIds: vi.fn().mockResolvedValue([]),query: vi.fn().mockResolvedValue([]),delete: vi.fn().mockResolvedValue(undefined),+ deleteUnreferenced: vi.fn().mockResolvedValue(undefined),deleteMany: vi.fn().mockResolvedValue([]),updateGlobalFile: vi.fn().mockResolvedValue(undefined),clear: vi.fn().mockResolvedValue({} as any),@@ -152,6 +153,7 @@ vi.mock('@/database/models/chunk', () => ({const mockFileModelCheckHash = vi.fn();const mockFileModelCreate = vi.fn();const mockFileModelDelete = vi.fn();+const mockFileModelDeleteUnreferenced = vi.fn();const mockFileModelDeleteMany = vi.fn();const mockFileModelFindById = vi.fn();const mockFileModelFindByIds = vi.fn();@@ -166,6 +168,7 @@ vi.mock('@/database/models/file', () => ({checkHash: mockFileModelCheckHash,create: mockFileModelCreate,delete: mockFileModelDelete,+ deleteUnreferenced: mockFileModelDeleteUnreferenced,deleteMany: mockFileModelDeleteMany,findById: mockFileModelFindById,findByIds: mockFileModelFindByIds,@@ -188,10 +191,11 @@ vi.mock('@/database/models/knowledgeBase', () => ({const mockFileServiceGetFullFileUrl = vi.fn();const mockFileServiceGetFileAccessUrl = vi.fn();const mockFileServiceGetFileMetadata = vi.fn();+const mockFileServiceDeleteFile = vi.fn();vi.mock('@/server/services/file', () => ({FileService: vi.fn(() => ({- deleteFile: vi.fn(),+ deleteFile: mockFileServiceDeleteFile,deleteFiles: vi.fn(),getFileAccessUrl: mockFileServiceGetFileAccessUrl,getFullFileUrl: mockFileServiceGetFullFileUrl,@@ -826,6 +830,27 @@ describe('fileRouter', () => {});});+ describe('removeUnreferencedFile', () => {+ it('keeps object storage when the file became referenced before cleanup', async () => {+ mockFileModelFindById.mockResolvedValue({ id: 'voice-file', userId: 'test-user' });+ mockFileModelDeleteUnreferenced.mockResolvedValue(undefined);++ await caller.removeUnreferencedFile({ id: 'voice-file' });++ expect(mockFileModelDeleteUnreferenced).toHaveBeenCalledWith('voice-file', false);+ expect(mockFileServiceDeleteFile).not.toHaveBeenCalled();+ });++ it('removes object storage after the unreferenced database row is deleted', async () => {+ mockFileModelFindById.mockResolvedValue({ id: 'voice-file', userId: 'test-user' });+ mockFileModelDeleteUnreferenced.mockResolvedValue({ url: 'voice/file.webm' });++ await caller.removeUnreferencedFile({ id: 'voice-file' });++ expect(mockFileServiceDeleteFile).toHaveBeenCalledWith('voice/file.webm');+ });+ });+describe('removeFiles', () => {it('should do nothing when no files found', async () => {ctx.fileModel.deleteMany.mockResolvedValue([]);diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.tsindex c2e4d296b5f..f6dde618db7 100644--- a/apps/server/src/routers/lambda/file.ts+++ b/apps/server/src/routers/lambda/file.ts@@ -653,6 +653,20 @@ export const fileRouter = router({await ctx.fileService.deleteFile(file.url!);}),+ removeUnreferencedFile: fileProcedure+ .use(withScopedPermission('file:delete'))+ .input(z.object({ id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const existing = await ctx.fileModel.findById(input.id);+ if (!existing) return;+ assertWorkspaceRowManageable(ctx, existing.userId, 'file');++ const file = await ctx.fileModel.deleteUnreferenced(input.id, serverDBEnv.REMOVE_GLOBAL_FILE);+ if (!file) return;++ await ctx.fileService.deleteFile(file.url!);+ }),+removeFileAsyncTask: fileProcedure.use(withScopedPermission('file:update')).input(diff --git a/apps/server/src/services/file/resolveAttachments.ts b/apps/server/src/services/file/resolveAttachments.tsindex 8d831fe4ba3..07b9b3b058c 100644--- a/apps/server/src/services/file/resolveAttachments.ts+++ b/apps/server/src/services/file/resolveAttachments.ts@@ -32,6 +32,24 @@ interface ResolveArgs {const dedupe = (ids: string[]) => Array.from(new Set(ids));+const getAudioMetadata = (+ metadata: unknown,+ fileType: string,+): Pick<ChatAudioItem, 'codec' | 'durationMs' | 'mimeType'> => {+ const value =+ metadata && typeof metadata === 'object' && !Array.isArray(metadata)+ ? (metadata as Record<string, unknown>)+ : {};++ const durationMs = readAudioDurationMs(metadata);++ return {+ ...(typeof value.codec === 'string' ? { codec: value.codec } : undefined),+ ...(durationMs === undefined ? {} : { durationMs }),+ mimeType: typeof value.mimeType === 'string' ? value.mimeType : fileType,+ };+};+/*** Resolve fileIds into image/video/file lists for the LLM prompt layer.*@@ -114,10 +132,9 @@ export const resolveAttachmentsByFileIds = async ({continue;}if (fileType.startsWith('audio')) {- const durationMs = readAudioDurationMs(file.metadata);result.audioList.push({+ ...getAudioMetadata(file.metadata, fileType),alt: file.name || 'audio',- ...(durationMs === undefined ? {} : { durationMs }),id: file.id,url: resolvedUrl,});diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 949747af6e3..bf86b842f38 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -70,6 +70,7 @@"audioPlayer.download": "Download audio","audioPlayer.pause": "Pause audio","audioPlayer.play": "Play audio",+ "audioPlayer.seek": "Seek audio","availableAgents": "Available Agents","backToBottom": "Jump to latest","beforeUnload.confirmLeave": "A request is still running. Leave anyway?",@@ -1714,6 +1715,32 @@"viewSwitcher.chat": "Chat","viewSwitcher.page": "Page","viewSwitcher.task": "Task",+ "voiceMessage.action": "Send voice message",+ "voiceMessage.cancel": "Cancel recording",+ "voiceMessage.cancelUpload": "Cancel voice message upload",+ "voiceMessage.delete": "Delete recording",+ "voiceMessage.duration": "Recording duration: {{duration}}",+ "voiceMessage.error.not_supported": "Voice recording is not supported in this browser. Try the latest Chrome or Safari.",+ "voiceMessage.error.permission_denied": "Microphone access is blocked. Allow it in browser site settings, then retry.",+ "voiceMessage.error.recording_failed": "Recording failed. Check your microphone and retry.",+ "voiceMessage.otherAudioModeActive": "Finish the other microphone session first.",+ "voiceMessage.ready": "Recording ready to send",+ "voiceMessage.recording": "Recording voice message",+ "voiceMessage.replyInProgress": "Wait for the current response to finish before recording another voice message.",+ "voiceMessage.requesting": "Requesting microphone access…",+ "voiceMessage.retry": "Retry voice message",+ "voiceMessage.send": "Send voice message",+ "voiceMessage.status.sendFailed": "Send failed",+ "voiceMessage.status.sending": "Sending…",+ "voiceMessage.status.unsupported": "Switch models to retry",+ "voiceMessage.status.uploadFailed": "Upload failed",+ "voiceMessage.status.uploading": "Uploading… {{progress}}%",+ "voiceMessage.statusLabel": "Voice message recorder",+ "voiceMessage.stopping": "Finishing recording…",+ "voiceMessage.tooShort": "Record for at least {{duration}} ms",+ "voiceMessage.unsupported": "The current model or Agent cannot accept original audio. Switch to an audio-capable model.",+ "voiceMessage.uploadFailed": "Upload failed. The recording is kept locally.",+ "voiceMessage.uploading": "Uploading voice message…","workflow.awaitingConfirmation": "Awaiting your confirmation","workflow.collapse": "Collapse","workflow.expandFull": "Expand fully",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 77030b9338e..3d3876a460b 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -70,6 +70,7 @@"audioPlayer.download": "下载音频","audioPlayer.pause": "暂停音频","audioPlayer.play": "播放音频",+ "audioPlayer.seek": "跳转音频播放位置","availableAgents": "可用助理","backToBottom": "跳转到最新","beforeUnload.confirmLeave": "你有正在生成中的请求,确定要离开吗?",@@ -1714,6 +1715,32 @@"viewSwitcher.chat": "对话","viewSwitcher.page": "文稿","viewSwitcher.task": "任务",+ "voiceMessage.action": "发送语音消息",+ "voiceMessage.cancel": "取消录音",+ "voiceMessage.cancelUpload": "取消发送语音消息",+ "voiceMessage.delete": "删除录音",+ "voiceMessage.duration": "录音时长:{{duration}}",+ "voiceMessage.error.not_supported": "当前浏览器不支持语音录制,请使用最新版 Chrome 或 Safari",+ "voiceMessage.error.permission_denied": "麦克风权限已被阻止,请在浏览器网站设置中允许后重试",+ "voiceMessage.error.recording_failed": "录音失败,请检查麦克风后重试",+ "voiceMessage.otherAudioModeActive": "请先结束另一个麦克风会话",+ "voiceMessage.ready": "录音已就绪,可以发送",+ "voiceMessage.recording": "正在录制语音消息",+ "voiceMessage.replyInProgress": "请等待当前回复完成后再录制语音消息",+ "voiceMessage.requesting": "正在请求麦克风权限…",+ "voiceMessage.retry": "重试语音消息",+ "voiceMessage.send": "发送语音消息",+ "voiceMessage.status.sendFailed": "发送失败",+ "voiceMessage.status.sending": "正在发送…",+ "voiceMessage.status.unsupported": "切换模型后重试",+ "voiceMessage.status.uploadFailed": "上传失败",+ "voiceMessage.status.uploading": "正在上传… {{progress}}%",+ "voiceMessage.statusLabel": "语音消息录音器",+ "voiceMessage.stopping": "正在完成录音…",+ "voiceMessage.tooShort": "请至少录制 {{duration}} 毫秒",+ "voiceMessage.unsupported": "当前模型或 Agent 无法接收原始音频,请切换到支持音频的模型",+ "voiceMessage.uploadFailed": "上传失败,录音已保留在本地",+ "voiceMessage.uploading": "正在上传语音消息…","workflow.awaitingConfirmation": "需要你确认","workflow.collapse": "收起","workflow.expandFull": "全部展开",diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.tsindex 4776cb1dc14..e333809a3ed 100644--- a/packages/context-engine/src/processors/MessageContent.ts+++ b/packages/context-engine/src/processors/MessageContent.ts@@ -71,7 +71,9 @@ export interface MessageContentConfig {export interface UserMessageContentPart {audio_url?: {+ codec?: string;durationMs?: number;+ mimeType?: string;url: string;};googleThoughtSignature?: string;@@ -619,7 +621,9 @@ export class MessageContentProcessor extends BaseProcessor {return {audio_url: {+ ...(audio.codec ? { codec: audio.codec } : {}),...(durationMs === undefined ? {} : { durationMs }),+ ...(audio.mimeType ? { mimeType: audio.mimeType } : {}),url: audio.url,},type: 'audio_url',diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.tsindex a340c55dbf2..82bcb4a27f3 100644--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts@@ -992,6 +992,50 @@ describe('MessageContentProcessor', () => {expect(content[2].audio_url).not.toHaveProperty('durationMs');});+ it('should preserve audio metadata when converting audios to audio_url parts', async () => {+ mockIsCanUseAudio.mockReturnValue(true);++ const processor = new MessageContentProcessor({+ model: 'gpt-audio',+ provider: 'openai',+ isCanUseAudio: mockIsCanUseAudio,+ fileContext: { enabled: false },+ });++ const messages: UIChatMessage[] = [+ {+ id: 'test',+ role: 'user',+ content: 'Listen',+ audioList: [+ {+ alt: 'voice message',+ codec: 'pcm_s16le',+ durationMs: 3210,+ id: 'voice-1',+ mimeType: 'audio/wav',+ url: 'http://example.com/voice.wav',+ },+ ],+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ ];++ const result = await processor.process(createContext(messages));++ const content = result.messages[0].content as any[];+ expect(content[1]).toEqual({+ audio_url: {+ codec: 'pcm_s16le',+ durationMs: 3210,+ mimeType: 'audio/wav',+ url: 'http://example.com/voice.wav',+ },+ type: 'audio_url',+ });+ });+it('should include audios in file context when enabled even if audio not supported', async () => {mockIsCanUseAudio.mockReturnValue(false);diff --git a/packages/database/src/models/__tests__/file.test.ts b/packages/database/src/models/__tests__/file.test.tsindex 8eaf8947c40..fb535c1b50d 100644--- a/packages/database/src/models/__tests__/file.test.ts+++ b/packages/database/src/models/__tests__/file.test.ts@@ -291,6 +291,84 @@ describe('FileModel', () => {});});+ describe('deleteUnreferenced', () => {+ it('deletes an owned file that has no message or session references', async () => {+ await fileModel.createGlobalFile({+ creator: userId,+ fileType: 'audio/webm',+ hashId: 'voice-unreferenced',+ size: 100,+ url: 'voice/unreferenced.webm',+ });+ const { id } = await fileModel.create({+ fileHash: 'voice-unreferenced',+ fileType: 'audio/webm',+ name: 'voice.webm',+ size: 100,+ url: 'voice/unreferenced.webm',+ });++ const deleted = await fileModel.deleteUnreferenced(id);++ expect(deleted).toMatchObject({ id, url: 'voice/unreferenced.webm' });+ await expect(+ serverDB.query.files.findFirst({ where: eq(files.id, id) }),+ ).resolves.toBeUndefined();+ });++ it('preserves a file attached to a persisted message', async () => {+ const { id } = await fileModel.create({+ fileType: 'audio/webm',+ name: 'voice.webm',+ size: 100,+ url: 'voice/message.webm',+ });+ await serverDB.insert(messages).values({ id: 'voice-message', role: 'user', userId });+ await serverDB+ .insert(messagesFiles)+ .values({ fileId: id, messageId: 'voice-message', userId });++ await expect(fileModel.deleteUnreferenced(id)).resolves.toBeUndefined();+ await expect(+ serverDB.query.files.findFirst({ where: eq(files.id, id) }),+ ).resolves.toBeDefined();+ });++ it('preserves a file attached to a session', async () => {+ const { id } = await fileModel.create({+ fileType: 'audio/webm',+ name: 'voice.webm',+ size: 100,+ url: 'voice/session.webm',+ });+ await serverDB.insert(sessions).values({ id: 'voice-session', userId });+ await serverDB+ .insert(filesToSessions)+ .values({ fileId: id, sessionId: 'voice-session', userId });++ await expect(fileModel.deleteUnreferenced(id)).resolves.toBeUndefined();+ await expect(+ serverDB.query.files.findFirst({ where: eq(files.id, id) }),+ ).resolves.toBeDefined();+ });++ it("does not delete another user's unreferenced file", async () => {+ await serverDB.insert(files).values({+ fileType: 'audio/webm',+ id: 'other-user-voice',+ name: 'voice.webm',+ size: 100,+ url: 'voice/other.webm',+ userId: 'user2',+ });++ await expect(fileModel.deleteUnreferenced('other-user-voice')).resolves.toBeUndefined();+ await expect(+ serverDB.query.files.findFirst({ where: eq(files.id, 'other-user-voice') }),+ ).resolves.toBeDefined();+ });+ });+describe('deleteMany', () => {it('should delete multiple files', async () => {await fileModel.createGlobalFile({diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex 50864f43434..deee80ae752 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -388,7 +388,7 @@ describe('MessageModel Query Tests', () => {);});- it('materializes only validated audio duration metadata in both query paths', async () => {+ it('materializes safe audio metadata and only validated duration in both query paths', async () => {await serverDB.transaction(async (trx) => {await trx.insert(messages).values({content: 'message with audio',@@ -434,11 +434,13 @@ describe('MessageModel Query Tests', () => {alt: 'valid.mp3',durationMs: 2500,id: 'audio-duration-valid',+ mimeType: 'audio/mpeg',url: 'files/valid.mp3',});expect(message?.audioList?.find((audio) => audio.id === 'audio-duration-invalid')).toEqual({alt: 'invalid.mp3',id: 'audio-duration-invalid',+ mimeType: 'audio/mpeg',url: 'files/invalid.mp3',});}diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.tsindex dc301108480..0ffd3dc1f67 100644--- a/packages/database/src/models/file.ts+++ b/packages/database/src/models/file.ts@@ -224,6 +224,39 @@ export class FileModel {return await (trx ? executeInTransaction(trx) : this.db.transaction(executeInTransaction));};+ /**+ * Delete a transient upload only while no persisted message or session references it.+ * Locking the file row serializes this cleanup with foreign-key inserts, so a late send either+ * wins ownership and preserves the file or observes the deletion and fails atomically.+ */+ deleteUnreferenced = async (id: string, removeGlobalFile: boolean = true) => {+ return this.db.transaction(async (trx) => {+ const [file] = await trx+ .select({ id: files.id })+ .from(files)+ .where(and(eq(files.id, id), this.ownership()))+ .limit(1)+ .for('update');+ if (!file) return;++ const [messageReference] = await trx+ .select({ id: messagesFiles.fileId })+ .from(messagesFiles)+ .where(eq(messagesFiles.fileId, id))+ .limit(1);+ if (messageReference) return;++ const [sessionReference] = await trx+ .select({ id: filesToSessions.fileId })+ .from(filesToSessions)+ .where(eq(filesToSessions.fileId, id))+ .limit(1);+ if (sessionReference) return;++ return this.delete(id, removeGlobalFile, trx);+ });+ };+deleteGlobalFile = async (hashId: string) => {return this.db.delete(globalFiles).where(eq(globalFiles.hashId, hashId));};diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 4ae3c7e0851..a3dfd7b1ce7 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -165,17 +165,25 @@ interface MessageRelatedFile {}const materializeChatAudioItem = ({+ fileType,id,metadata,name,url,}: MessageRelatedFile): ChatAudioItem => {+ const value = isPlainRecord(metadata) ? metadata : {};const durationMs = readAudioDurationMs(metadata);return {alt: name!,+ ...(typeof value.codec === 'string' ? { codec: value.codec } : {}),...(durationMs === undefined ? {} : { durationMs }),id,+ ...(typeof value.mimeType === 'string'+ ? { mimeType: value.mimeType }+ : fileType+ ? { mimeType: fileType }+ : {}),url,};};diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 00a5e26c086..b85b57b7190 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -4,6 +4,7 @@ export default {'audioPlayer.download': 'Download audio','audioPlayer.pause': 'Pause audio','audioPlayer.play': 'Play audio',+ 'audioPlayer.seek': 'Seek audio','agentBuilder.installPlugin.authRequired': 'Cloud MCP requires sign-in to continue','agentBuilder.installPlugin.cancel': 'Cancel','agentBuilder.installPlugin.clickApproveToConnect':@@ -1908,6 +1909,36 @@ export default {'Unsupported file type: {{files}}. Supported images: JPG, PNG, GIF, WebP. Supported documents include PDF, Word, Excel, PowerPoint, Markdown, text, CSV, JSON, and code files.','upload.validation.videoSizeExceeded':'Video file size must not exceed {{maxSize}}. Current file size is {{actualSize}}.',+ 'voiceMessage.action': 'Send voice message',+ 'voiceMessage.cancel': 'Cancel recording',+ 'voiceMessage.cancelUpload': 'Cancel voice message upload',+ 'voiceMessage.delete': 'Delete recording',+ 'voiceMessage.duration': 'Recording duration: {{duration}}',+ 'voiceMessage.error.not_supported':+ 'Voice recording is not supported in this browser. Try the latest Chrome or Safari.',+ 'voiceMessage.error.permission_denied':+ 'Microphone access is blocked. Allow it in browser site settings, then retry.',+ 'voiceMessage.error.recording_failed': 'Recording failed. Check your microphone and retry.',+ 'voiceMessage.otherAudioModeActive': 'Finish the other microphone session first.',+ 'voiceMessage.ready': 'Recording ready to send',+ 'voiceMessage.recording': 'Recording voice message',+ 'voiceMessage.requesting': 'Requesting microphone access…',+ 'voiceMessage.replyInProgress':+ 'Wait for the current response to finish before recording another voice message.',+ 'voiceMessage.retry': 'Retry voice message',+ 'voiceMessage.send': 'Send voice message',+ 'voiceMessage.statusLabel': 'Voice message recorder',+ 'voiceMessage.status.sendFailed': 'Send failed',+ 'voiceMessage.status.sending': 'Sending…',+ 'voiceMessage.status.unsupported': 'Switch models to retry',+ 'voiceMessage.status.uploadFailed': 'Upload failed',+ 'voiceMessage.status.uploading': 'Uploading… {{progress}}%',+ 'voiceMessage.stopping': 'Finishing recording…',+ 'voiceMessage.tooShort': 'Record for at least {{duration}} ms',+ 'voiceMessage.unsupported':+ 'The current model or Agent cannot accept original audio. Switch to an audio-capable model.',+ 'voiceMessage.uploadFailed': 'Upload failed. The recording is kept locally.',+ 'voiceMessage.uploading': 'Uploading voice message…','viewMode.fullWidth': 'Full Width','viewMode.normal': 'Standard','viewMode.wideScreen': 'Widescreen',diff --git a/packages/model-bank/src/aiModels/__tests__/index.test.ts b/packages/model-bank/src/aiModels/__tests__/index.test.tsindex dd229f0dce3..42893ab99a8 100644--- a/packages/model-bank/src/aiModels/__tests__/index.test.ts+++ b/packages/model-bank/src/aiModels/__tests__/index.test.ts@@ -113,6 +113,16 @@ describe('ChatGPT subscription models', () => {});});+describe('OpenAI audio models', () => {+ it('advertises native audio support for gpt-audio', () => {+ const gptAudio = LOBE_DEFAULT_MODEL_LIST.find(+ (model) => model.providerId === ModelProvider.OpenAI && model.id === 'gpt-audio',+ );++ expect(gptAudio?.abilities.audio).toBe(true);+ });+});+describe('Moonshot models', () => {it('advertises Kimi K3 reasoning effort controls', () => {const kimiK3 = LOBE_DEFAULT_MODEL_LIST.find(diff --git a/packages/model-bank/src/aiModels/openai.ts b/packages/model-bank/src/aiModels/openai.tsindex 321bdba5f83..081653d1900 100644--- a/packages/model-bank/src/aiModels/openai.ts+++ b/packages/model-bank/src/aiModels/openai.ts@@ -1140,6 +1140,7 @@ export const openaiChatModels: AIChatModelCard[] = [},{abilities: {+ audio: true,functionCall: true,},contextWindowTokens: 128_000,diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.tsindex 8ba05f7ff65..9f3bc4240a1 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts@@ -1,6 +1,7 @@import { AgentRuntimeErrorType, RequestTrigger } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { LobeVertexAI } from '../../providers/vertexai';import { getRuntimeSignatureScopeSource } from '../../utils/signatureScope';import type { LobeRuntimeAI } from '../BaseAI';import { createRouterRuntime } from './createRuntime';@@ -13,6 +14,7 @@ describe('createRouterRuntime', () => {afterEach(() => {vi.restoreAllMocks();vi.unstubAllEnvs();+ vi.doUnmock('./baseRuntimeMap');});describe('initialization', () => {@@ -631,6 +633,163 @@ describe('createRouterRuntime', () => {});describe('fallback mechanism', () => {+ it('should only use raw-audio-compatible routes for audio messages', async () => {+ const attemptedRoutes: string[] = [];++ class CompatibleRuntime implements LobeRuntimeAI {+ private readonly apiKey: string;++ constructor(options: any) {+ this.apiKey = options.apiKey;+ }++ chat = vi.fn().mockImplementation(async () => {+ attemptedRoutes.push(this.apiKey);+ throw new Error(`${this.apiKey} failed`);+ });+ }++ vi.doMock('./baseRuntimeMap', () => ({+ baseRuntimeMap: {+ google: CompatibleRuntime,+ openai: CompatibleRuntime,+ },+ }));++ const vertexChat = vi.fn().mockImplementation(async () => {+ attemptedRoutes.push('vertexai');+ return 'vertex-response';+ });+ vi.spyOn(LobeVertexAI, 'initFromVertexAI').mockReturnValue({ chat: vertexChat } as any);++ const unsupportedChat = vi.fn();++ class UnsupportedRuntime implements LobeRuntimeAI {+ chat = unsupportedChat;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'anthropic',+ models: ['audio-model'],+ options: [+ { apiKey: 'anthropic-key', apiType: 'anthropic' },+ { apiKey: 'google-key', apiType: 'google' },+ { apiKey: 'xai-key', apiType: 'xai' },+ { apiKey: 'openai-key', apiType: 'openai' },+ { apiKey: 'vertex-key', apiType: 'vertexai' },+ ],+ runtime: UnsupportedRuntime as any,+ },+ ],+ });++ const runtime = new Runtime();+ const result = await runtime.chat({+ messages: [+ {+ content: [+ {+ audio_url: { mimeType: 'audio/wav', url: 'https://example.com/voice.wav' },+ type: 'audio_url',+ },+ ],+ role: 'user',+ },+ ],+ model: 'audio-model',+ });++ expect(result).toBe('vertex-response');+ expect(attemptedRoutes).toEqual(['google-key', 'openai-key', 'vertexai']);+ expect(unsupportedChat).not.toHaveBeenCalled();+ expect(vertexChat).toHaveBeenCalledTimes(1);+ });++ it('should fail closed when no route supports raw audio input', async () => {+ const unsupportedChat = vi.fn();++ class UnsupportedRuntime implements LobeRuntimeAI {+ chat = unsupportedChat;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'anthropic',+ models: ['audio-model'],+ options: [+ { apiKey: 'anthropic-key', apiType: 'anthropic' },+ { apiKey: 'xai-key', apiType: 'xai' },+ ],+ runtime: UnsupportedRuntime as any,+ },+ ],+ });++ const runtime = new Runtime();++ await expect(+ runtime.chat({+ messages: [+ {+ content: [+ {+ audio_url: { mimeType: 'audio/wav', url: 'https://example.com/voice.wav' },+ type: 'audio_url',+ },+ ],+ role: 'user',+ },+ ],+ model: 'audio-model',+ }),+ ).rejects.toThrow('No provider route supports raw audio input for model audio-model');+ expect(unsupportedChat).not.toHaveBeenCalled();+ });++ it('should preserve the original fallback order for text messages', async () => {+ const attemptedKeys: string[] = [];++ class TextRuntime implements LobeRuntimeAI {+ private readonly apiKey: string;++ constructor(options: any) {+ this.apiKey = options.apiKey;+ }++ chat = vi.fn().mockImplementation(async () => {+ attemptedKeys.push(this.apiKey);+ if (this.apiKey === 'key-1') throw new Error('first route failed');+ return 'text-response';+ });+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'anthropic',+ models: ['text-model'],+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],+ runtime: TextRuntime as any,+ },+ ],+ });++ const runtime = new Runtime();+ const result = await runtime.chat({+ messages: [{ content: 'hello', role: 'user' }],+ model: 'text-model',+ });++ expect(result).toBe('text-response');+ expect(attemptedKeys).toEqual(['key-1', 'key-2']);+ });+it('should fallback to next option when first option fails', async () => {// Test that errors are caught and re-thrown when all options failconst mockChatAlwaysFail = vi.fn().mockRejectedValue(new Error('All failed'));diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex 28f4e7b0e77..9fe5aa4d343 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -128,11 +128,20 @@ interface RouteAttemptMetadata {}interface RouteAttemptContext {+ allowedApiTypes?: ReadonlySet<ApiType>;metadata?: Record<string, unknown>;toolsCount?: number;user?: string;}+const RAW_AUDIO_API_TYPES = new Set<ApiType>(['google', 'openai', 'vertexai']);++const hasRawAudioInput = (payload: ChatStreamPayload) =>+ payload.messages.some(+ (message) =>+ Array.isArray(message.content) && message.content.some((part) => part.type === 'audio_url'),+ );+interface RouteAttemptContextValidationParams extends RouteAttemptContext {apiType: string;channelId?: string;@@ -580,15 +589,24 @@ export const createRouterRuntime = ({routeContext: RouteAttemptContext = {},): Promise<T> {const totalStartedAt = Date.now();- const { metadata, toolsCount, user } = routeContext;+ const { allowedApiTypes, metadata, toolsCount, user } = routeContext;const matchedRouter = await this.resolveMatchedRouter(model);- const routerOptions = await this.applySortRouterOptions(+ const sortedRouterOptions = await this.applySortRouterOptions(matchedRouter,model,this.normalizeRouterOptions(matchedRouter),);+ const routerOptions = allowedApiTypes+ ? sortedRouterOptions.filter((option) =>+ allowedApiTypes.has(option.apiType ?? matchedRouter.apiType),+ )+ : sortedRouterOptions;const totalOptions = routerOptions.length;+ if (totalOptions === 0) {+ throw new TypeError(`No provider route supports raw audio input for model ${model}`);+ }+if (this._id === 'lobehub') {timing('runWithFallback start model=%s routerId=%s apiType=%s options=%d traceId=%s',@@ -848,10 +866,13 @@ export const createRouterRuntime = ({*/async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {try {+ const containsRawAudio = hasRawAudioInput(payload);+return await this.runWithFallback(payload.model,(runtime) => runtime.chat!(payload, options),{+ allowedApiTypes: containsRawAudio ? RAW_AUDIO_API_TYPES : undefined,metadata: options?.metadata,toolsCount: payload.tools?.length ?? 0,user: options?.user,diff --git a/packages/model-runtime/src/core/contextBuilders/google.test.ts b/packages/model-runtime/src/core/contextBuilders/google.test.tsindex 93b93b4cbb0..3192175547a 100644--- a/packages/model-runtime/src/core/contextBuilders/google.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/google.test.ts@@ -434,6 +434,30 @@ describe('google contextBuilders', () => {});});+ it('should use persisted recorder metadata when base64 audio omits its MIME type', async () => {+ vi.mocked(parseDataUri).mockReturnValueOnce({+ base64: 'mockAudioBase64Data',+ mimeType: null,+ type: 'base64',+ });++ const content: UserMessageContentPart = {+ audio_url: {+ mimeType: 'audio/wav;codecs=pcm',+ url: 'data:;base64,mockAudioBase64Data',+ },+ type: 'audio_url',+ };++ await expect(buildGooglePart(content)).resolves.toEqual({+ inlineData: {+ data: 'mockAudioBase64Data',+ mimeType: 'audio/wav',+ },+ thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,+ });+ });+it('should use fileData for external URL audio on gemini-3+', async () => {const audioUrl = 'https://example.com/audio.mp3';@@ -474,6 +498,35 @@ describe('google contextBuilders', () => {expect(imageToBase64Spy).not.toHaveBeenCalled();});+ it('should use persisted recorder metadata when an external URL is octet-stream', async () => {+ const audioUrl = 'https://example.com/voice';++ vi.mocked(parseDataUri).mockReturnValueOnce({+ base64: null,+ mimeType: null,+ type: 'url',+ });+ vi.mocked(isPublicExternalUrl).mockReturnValueOnce(true);+ vi.mocked(validateExternalUrl).mockResolvedValueOnce({+ contentLength: 1024,+ contentType: 'application/octet-stream',+ isValid: true,+ });++ const content: UserMessageContentPart = {+ audio_url: { mimeType: 'audio/wav', url: audioUrl },+ type: 'audio_url',+ };++ await expect(buildGooglePart(content, { model: 'gemini-3-flash-preview' })).resolves.toEqual({+ fileData: {+ fileUri: audioUrl,+ mimeType: 'audio/wav',+ },+ thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,+ });+ });+it('should return undefined for unsupported SVG image (base64)', async () => {const svgBase64 ='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==';diff --git a/packages/model-runtime/src/core/contextBuilders/google.ts b/packages/model-runtime/src/core/contextBuilders/google.tsindex e1b4124eb4c..3fd347a2f24 100644--- a/packages/model-runtime/src/core/contextBuilders/google.ts+++ b/packages/model-runtime/src/core/contextBuilders/google.ts@@ -78,15 +78,21 @@ const supportsFunctionCallId = (model?: string) => {const buildExternalUrlFileDataPart = async (url: string,options?: GoogleMessageBuildOptions,+ fallbackMimeType?: string,): Promise<Part | undefined> => {if (!supportsExternalUrlFileData(options?.model) || !isPublicExternalUrl(url)) return undefined;const validation = await validateExternalUrl(url);if (validation.isValid) {+ const mimeType =+ validation.contentType && validation.contentType !== 'application/octet-stream'+ ? validation.contentType+ : fallbackMimeType || validation.contentType;+return {fileData: {fileUri: url,- mimeType: validation.contentType,+ mimeType,},thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,};@@ -198,6 +204,7 @@ export const buildGooglePart = async (case 'audio_url': {const { mimeType, base64, type } = parseDataUri(content.audio_url.url);+ const recordedMimeType = content.audio_url.mimeType?.split(';')[0].trim();if (type === 'base64') {if (!base64) {@@ -205,7 +212,7 @@ export const buildGooglePart = async (}return {- inlineData: { data: base64, mimeType: mimeType || 'audio/mp3' },+ inlineData: { data: base64, mimeType: mimeType || recordedMimeType || 'audio/mp3' },thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,};}@@ -213,16 +220,20 @@ export const buildGooglePart = async (if (type === 'url') {const url = content.audio_url.url;- const externalUrlPart = await buildExternalUrlFileDataPart(url, options);+ const externalUrlPart = await buildExternalUrlFileDataPart(url, options, recordedMimeType);if (externalUrlPart) return externalUrlPart;// Fallback: convert URL to base64 (for private/local URLs or earlier model// generations that don't support external fileData URIs).// imageUrlToBase64 provides SSRF protection and works for any binary data.const { base64: urlBase64, mimeType: urlMimeType } = await imageUrlToBase64(url);+ const resolvedMimeType =+ urlMimeType && urlMimeType !== 'application/octet-stream'+ ? urlMimeType+ : recordedMimeType || urlMimeType || 'audio/mp3';return {- inlineData: { data: urlBase64, mimeType: urlMimeType || 'audio/mp3' },+ inlineData: { data: urlBase64, mimeType: resolvedMimeType },thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,};}diff --git a/packages/model-runtime/src/core/contextBuilders/openai.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.test.tsindex 8ce19bf6932..b583cbef084 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.test.ts@@ -20,6 +20,9 @@ vi.mock('@lobechat/utils', () => ({}));vi.mock('../../utils/uriParser');+const MP3_BASE64 = 'SUQzBAAAAAA=';+const WAV_BASE64 = 'UklGRjAwMDBXQVZFZm10IA==';+describe('convertMessageContent', () => {beforeEach(() => {vi.resetAllMocks();@@ -35,16 +38,104 @@ describe('convertMessageContent', () => {expect(result).toEqual(content);});- it('should strip internal audio estimation fields from provider content', async () => {- const result = await convertMessageContent({- audio_url: { durationMs: 2500, url: 'https://example.com/audio.mp3' },+ it.each([+ ['WAV', 'audio/wav', 'wav', WAV_BASE64],+ ['MP3', 'audio/mpeg', 'mp3', MP3_BASE64],+ ] as const)(+ 'should convert a base64 %s data URI to input_audio',+ async (_, mimeType, format, base64) => {+ const content = {+ audio_url: {+ codec: format,+ durationMs: 2500,+ mimeType,+ url: `data:${mimeType};base64,${base64}`,+ },+ type: 'audio_url',+ } as const;+ vi.mocked(parseDataUri).mockReturnValue({+ base64,+ mimeType,+ type: 'base64',+ });++ await expect(convertMessageContent(content, { supportsAudioInput: true })).resolves.toEqual({+ input_audio: { data: base64, format },+ type: 'input_audio',+ });+ expect(imageUrlToBase64).not.toHaveBeenCalled();+ },+ );++ it.each([+ ['WAV', 'audio/wav', 'wav', WAV_BASE64],+ ['MP3', 'audio/mpeg', 'mp3', MP3_BASE64],+ ] as const)(+ 'should safely download a %s URL and convert it to input_audio',+ async (_, mimeType, format, base64) => {+ const url = `https://files.example.com/voice.${format}`;+ const content = { audio_url: { url }, type: 'audio_url' } as const;+ vi.mocked(parseDataUri).mockReturnValue({ base64: null, mimeType: null, type: 'url' });+ vi.mocked(imageUrlToBase64).mockResolvedValue({ base64, mimeType });++ await expect(convertMessageContent(content, { supportsAudioInput: true })).resolves.toEqual({+ input_audio: { data: base64, format },+ type: 'input_audio',+ });+ expect(imageUrlToBase64).toHaveBeenCalledWith(url, { maxBytes: 20 * 1024 * 1024 });+ },+ );++ it('should fail closed when the provider adapter does not enable audio input', async () => {+ const content = {+ audio_url: { url: 'data:audio/wav;base64,audioBase64' },type: 'audio_url',- });+ } as const;- expect(result).toEqual({- audio_url: { url: 'https://example.com/audio.mp3' },+ await expect(convertMessageContent(content)).rejects.toThrow(+ 'Audio input is not supported by this provider runtime',+ );+ expect(parseDataUri).not.toHaveBeenCalled();+ expect(imageUrlToBase64).not.toHaveBeenCalled();+ });++ it.each([+ ['base64 data', { base64: 'audioBase64', mimeType: 'audio/ogg', type: 'base64' as const }],+ ['download URL', { base64: null, mimeType: null, type: 'url' as const }],+ ])('should reject an unsupported audio MIME type from %s', async (_, parsedUri) => {+ const url =+ parsedUri.type === 'url'+ ? 'https://files.example.com/voice.ogg'+ : 'data:audio/ogg;base64,audioBase64';+ const content = { audio_url: { url }, type: 'audio_url' } as const;+ vi.mocked(parseDataUri).mockReturnValue(parsedUri);+ if (parsedUri.type === 'url') {+ vi.mocked(imageUrlToBase64).mockResolvedValue({+ base64: 'downloadedAudio',+ mimeType: 'audio/ogg',+ });+ }++ await expect(convertMessageContent(content, { supportsAudioInput: true })).rejects.toThrow(+ /only supports (?:base64 )?WAV or MP3/i,+ );+ });++ it('should reject bytes that only claim to be WAV in persisted metadata', async () => {+ const url = 'https://files.example.com/spoofed.wav';+ const content = {+ audio_url: { mimeType: 'audio/wav', url },type: 'audio_url',+ } as const;+ vi.mocked(parseDataUri).mockReturnValue({ base64: null, mimeType: null, type: 'url' });+ vi.mocked(imageUrlToBase64).mockResolvedValue({+ base64: 'bm90IGF1ZGlv',+ mimeType: 'application/octet-stream',});++ await expect(convertMessageContent(content, { supportsAudioInput: true })).rejects.toThrow(+ 'only supports WAV or MP3 files',+ );});it('should convert image URL to base64 when necessary', async () => {@@ -598,6 +689,24 @@ describe('convertOpenAIMessages', () => {});describe('convertOpenAIResponseInputs', () => {+ it('should reject raw audio explicitly instead of dropping it from Responses input', async () => {+ const messages: OpenAIChatMessage[] = [+ {+ content: [+ {+ audio_url: { mimeType: 'audio/wav', url: 'https://files.example.com/voice.wav' },+ type: 'audio_url',+ },+ ],+ role: 'user',+ },+ ];++ await expect(convertOpenAIResponseInputs(messages)).rejects.toThrow(+ 'OpenAI raw audio input requires the Chat Completions API',+ );+ });+it('应该正确转换普通文本消息', async () => {const messages: OpenAIChatMessage[] = [{ role: 'user', content: 'Hello' },diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ts b/packages/model-runtime/src/core/contextBuilders/openai.tsindex e8eed08a878..b1790933de5 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts@@ -21,23 +21,13 @@ export type ExtendedChatCompletionContentPart = {};};-type InternalAudioContentPart = {- audio_url: {- durationMs?: number;- url: string;- };- type: 'audio_url';-};--type ConvertibleMessageContentPart =- ExtendedChatCompletionContentPart | InternalAudioContentPart | OpenAI.ChatCompletionContentPart;-type ConvertMessageContentOptions = {forceImageBase64?: boolean;forceVideoBase64?: boolean;model?: string;provider?: string;reasoningSignatureScope?: SignatureScope;+ supportsAudioInput?: boolean;strictToolPairing?: boolean;thoughtSignatureScope?: SignatureScope;};@@ -48,6 +38,69 @@ const isDeepSeekModel = (model: string | undefined) =>type OpenAICompatibleContentPart =ExtendedChatCompletionContentPart | OpenAI.ChatCompletionContentPart | UserMessageContentPart;+type ConvertibleMessageContentPart =+ | ExtendedChatCompletionContentPart+ | OpenAI.ChatCompletionContentPart+ | Extract<UserMessageContentPart, { type: 'audio_url' }>;++const OPENAI_AUDIO_INPUT_MAX_BYTES = 20 * 1024 * 1024;++const detectOpenAIAudioFormat = (base64: string): 'mp3' | 'wav' | undefined => {+ const header = Buffer.from(base64.replaceAll(/\s/g, '').slice(0, 64), 'base64');++ if (+ header.length >= 12 &&+ header.toString('ascii', 0, 4) === 'RIFF' &&+ header.toString('ascii', 8, 12) === 'WAVE'+ ) {+ return 'wav';+ }++ if (header.length >= 3 && header.toString('ascii', 0, 3) === 'ID3') return 'mp3';++ const hasMpegFrameSync = header.length >= 2 && header[0] === 0xff && (header[1] & 0xe0) === 0xe0;+ const hasMpegAudioLayer = header.length >= 2 && ((header[1] >> 1) & 0x03) !== 0;+ if (hasMpegFrameSync && hasMpegAudioLayer) return 'mp3';++ return undefined;+};++const convertAudioContent = async (+ content: Extract<UserMessageContentPart, { type: 'audio_url' }>,+ options?: ConvertMessageContentOptions,+): Promise<OpenAI.ChatCompletionContentPartInputAudio> => {+ if (!options?.supportsAudioInput) {+ throw new TypeError('Audio input is not supported by this provider runtime');+ }++ const { base64, type } = parseDataUri(content.audio_url.url);++ if (type === 'base64') {+ const format = base64 ? detectOpenAIAudioFormat(base64) : undefined;+ if (!base64 || !format) {+ throw new TypeError('OpenAI audio input only supports base64 WAV or MP3 data');+ }++ return { input_audio: { data: base64, format }, type: 'input_audio' };+ }++ if (type === 'url') {+ // imageUrlToBase64 is a generic binary downloader with SSRF-safe server fetching and+ // magic-byte MIME detection. The OpenAI adapter narrows the result to WAV/MP3 below.+ const converted = await imageUrlToBase64(content.audio_url.url, {+ maxBytes: OPENAI_AUDIO_INPUT_MAX_BYTES,+ });+ const format = detectOpenAIAudioFormat(converted.base64);+ if (!format) {+ throw new TypeError('OpenAI audio input only supports WAV or MP3 files');+ }++ return { input_audio: { data: converted.base64, format }, type: 'input_audio' };+ }++ throw new TypeError(`Invalid audio URL: ${content.audio_url.url}`);+};+const isInternalThinkingContentPart = (content: OpenAICompatibleContentPart,): content is Extract<UserMessageContentPart, { type: 'thinking' }> => content.type === 'thinking';@@ -55,11 +108,8 @@ const isInternalThinkingContentPart = (export const convertMessageContent = async (content: ConvertibleMessageContentPart,options?: ConvertMessageContentOptions,-): Promise<ConvertibleMessageContentPart> => {- if (content.type === 'audio_url') {- // durationMs is an internal estimation hint, not part of provider request schemas.- return { audio_url: { url: content.audio_url.url }, type: 'audio_url' };- }+): Promise<OpenAI.ChatCompletionContentPart | ExtendedChatCompletionContentPart> => {+ if (content.type === 'audio_url') return convertAudioContent(content, options);if (content.type === 'image_url') {const { type } = parseDataUri(content.image_url.url);@@ -174,9 +224,7 @@ export const convertOpenAIMessages = async (: await Promise.all((message.content || []).filter((c) => !isInternalThinkingContentPart(c as OpenAICompatibleContentPart))- .map((c) =>- convertMessageContent(c as OpenAI.ChatCompletionContentPart, options),- ),+ .map((c) => convertMessageContent(c as ConvertibleMessageContentPart, options)),),role: msg.role,};@@ -444,6 +492,9 @@ export const convertOpenAIResponseInputs = async (type: 'input_video',};}+ if (c.type === 'audio_url') {+ throw new TypeError('OpenAI raw audio input requires the Chat Completions API');+ }const image = await convertMessageContent(c as OpenAI.ChatCompletionContentPart,options,diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex f76771f0fdc..8dccab9b167 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -241,6 +241,8 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =data: OpenAI.ChatCompletion,) => ReadableStream<OpenAI.ChatCompletionChunk>;noUserId?: boolean;+ /** Convert internal audio_url parts to OpenAI input_audio (WAV/MP3 only). */+ supportsAudioInput?: boolean;/*** If true, route chat requests to Responses API path directly*/@@ -726,6 +728,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anforceImageBase64: chatCompletion?.forceImageBase64,forceVideoBase64: chatCompletion?.forceVideoBase64,model: postPayload.model,+ supportsAudioInput: chatCompletion?.supportsAudioInput,thoughtSignatureScope,});const includeUsageRequested = Boolean(postPayload.stream && !chatCompletion?.excludeUsage);diff --git a/packages/model-runtime/src/providers/openai/index.test.ts b/packages/model-runtime/src/providers/openai/index.test.tsindex 958e754ce06..d210ae80483 100644--- a/packages/model-runtime/src/providers/openai/index.test.ts+++ b/packages/model-runtime/src/providers/openai/index.test.ts@@ -285,6 +285,45 @@ describe('LobeOpenAI', () => {});describe('chatCompletion.handlePayload', () => {+ it('should force raw audio input through Chat Completions and send input_audio', async () => {+ const wavBase64 = 'UklGRjAwMDBXQVZFZm10IA==';++ await instance.chat({+ enabledSearch: true,+ messages: [+ {+ content: [+ {+ audio_url: {+ mimeType: 'audio/wav',+ url: `data:audio/wav;base64,${wavBase64}`,+ },+ type: 'audio_url',+ },+ ],+ role: 'user',+ },+ ],+ model: 'o1-pro',+ temperature: 0.7,+ });++ expect(instance['client'].responses.create).not.toHaveBeenCalled();+ expect(instance['client'].chat.completions.create).toHaveBeenCalledTimes(1);+ const createCall = (instance['client'].chat.completions.create as Mock).mock.calls[0][0];+ expect(createCall.messages).toEqual([+ {+ content: [+ {+ input_audio: { data: wavBase64, format: 'wav' },+ type: 'input_audio',+ },+ ],+ role: 'user',+ },+ ]);+ });+it('should use responses API for responsesAPIModels without enabledSearch', async () => {const payload = {messages: [{ content: 'Hello', role: 'user' as const }],diff --git a/packages/model-runtime/src/providers/openai/index.ts b/packages/model-runtime/src/providers/openai/index.tsindex f9eb28415d5..ca52cff8881 100644--- a/packages/model-runtime/src/providers/openai/index.ts+++ b/packages/model-runtime/src/providers/openai/index.ts@@ -17,6 +17,12 @@ export interface OpenAIModelCard {id: string;}+const hasAudioInput = (payload: ChatStreamPayload) =>+ payload.messages.some(+ (message) =>+ Array.isArray(message.content) && message.content.some((part) => part.type === 'audio_url'),+ );+const oaiSearchContextSize = process.env.OPENAI_SEARCH_CONTEXT_SIZE; // low, medium, highconst enableServiceTierFlex = process.env.OPENAI_SERVICE_TIER_FLEX === '1';@@ -26,13 +32,18 @@ export const params = {contextPreFlight: { models: openaiChatModels },handlePayload: (payload) => {const { enabledSearch, model, ...rest } = payload;+ const containsAudioInput = hasAudioInput(payload);- if (isResponsesAPIModel(model) || enabledSearch) {+ if (!containsAudioInput && (isResponsesAPIModel(model) || enabledSearch)) {return { ...rest, apiMode: 'responses', enabledSearch, model } as ChatStreamPayload;}if (isOpenAIReasoningPayloadModel(model)) {- return pruneReasoningPayload(payload) as any;+ return pruneReasoningPayload({+ ...rest,+ ...(containsAudioInput && { apiMode: 'chatCompletion' }),+ model,+ } as ChatStreamPayload) as any;}if (model.includes('-search-')) {@@ -56,12 +67,14 @@ export const params = {return {...rest,+ ...(containsAudioInput && { apiMode: 'chatCompletion' }),model,...(enableServiceTierFlex &&supportsOpenAIServiceTierFlex(model) && { service_tier: 'flex' }),stream: payload.stream ?? true,};},+ supportsAudioInput: true,},debug: {chatCompletion: () => process.env.DEBUG_OPENAI_CHAT_COMPLETION === '1',diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.tsindex 2a6be7ae6b2..54268d973d9 100644--- a/packages/model-runtime/src/types/chat.ts+++ b/packages/model-runtime/src/types/chat.ts@@ -45,7 +45,12 @@ interface UserMessageContentPartVideo {video_url: { url: string };}interface UserMessageContentPartAudio {- audio_url: { durationMs?: number; url: string };+ audio_url: {+ codec?: string;+ durationMs?: number;+ mimeType?: string;+ url: string;+ };type: 'audio_url';}diff --git a/packages/types/src/files/upload.ts b/packages/types/src/files/upload.tsindex 94cf07fc45e..df3d09b9d98 100644--- a/packages/types/src/files/upload.ts+++ b/packages/types/src/files/upload.ts@@ -21,6 +21,14 @@ export type FileProcessStatus = 'pending' | 'chunking' | 'embedding' | 'success'export const UPLOAD_STATUS_SET = new Set(['uploading', 'pending', 'processing']);+export interface VoiceMessageRecording {+ codec?: string;+ durationMs: number;+ file: File;+ mimeType: string;+ waveform: number[];+}+// the file that is upload at chat pageexport interface UploadFileItem {/**@@ -29,6 +37,16 @@ export interface UploadFileItem {abortController?: AbortController;/** Agent that owns the draft upload, used to retry in the same conversation context. */agentId?: string;+ /**+ * Metadata captured by the voice-message recorder. Kept on the upload item so+ * optimistic and queued messages can render duration/codec before the+ * persisted file relation is fetched.+ */+ audioMetadata?: {+ codec?: string;+ durationMs: number;+ mimeType: string;+ };/*** base64 data, it will use in other data*/diff --git a/packages/types/src/message/ui/audio.ts b/packages/types/src/message/ui/audio.tsindex 6bc7013449b..7969350e3df 100644--- a/packages/types/src/message/ui/audio.ts+++ b/packages/types/src/message/ui/audio.ts@@ -1,7 +1,9 @@export interface ChatAudioItem {alt: string;+ codec?: string;/** Validated positive audio duration in milliseconds, when known. */durationMs?: number;id: string;+ mimeType?: string;url: string;}diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.tsindex d84bdda1388..af71d2e1f73 100644--- a/packages/types/src/message/ui/params.ts+++ b/packages/types/src/message/ui/params.ts@@ -154,12 +154,29 @@ export interface SendMessageParams {* This decouples sendMessage from store selectors.*/messages?: UIChatMessage[];-/*** Additional metadata for the message (e.g., mentioned users)*/metadata?: Record<string, any>;+onlyAddUserMessage?: boolean;+ /**+ * Called once the send lifecycle owns the turn, either by persisting the user message or by+ * placing it in the current conversation queue. Transient UI can release local resources after+ * this acknowledgement because queued turns retain their uploaded file metadata.+ */+ onMessageAccepted?: () => void;+ /**+ * Called once the user message has been persisted, before the assistant run completes.+ * UI flows that own separate transient content use this acknowledgement to release it+ * without waiting for the full generation.+ */+ onMessagePersisted?: () => void;+ /**+ * ID of a pre-created local user message that the formal send lifecycle should adopt in place.+ * This keeps an optimistic row stable while replacing its local preview with uploaded media.+ */+ optimisticUserMessageId?: string;/*** Page selections attached to the message (for Ask AI functionality)* These will be persisted to the database and injected via context-engine@@ -170,6 +187,18 @@ export interface SendMessageParams {* If not provided, will be calculated from messages list.*/parentId?: string;+ /**+ * Send a separate turn without consuming or clearing the active composer.+ * Voice messages use this so the current text draft and pending attachments+ * remain available after the audio-only turn is dispatched.+ */+ preserveComposer?: boolean;+ /**+ * Cancels the send before the conversation lifecycle accepts ownership of the turn.+ * Once `onMessageAccepted` fires, later aborts are ignored and the existing runtime Stop flow+ * owns any subsequent model execution.+ */+ signal?: AbortSignal;}export interface SendGroupMessageParams {diff --git a/packages/types/src/openai/chat.ts b/packages/types/src/openai/chat.tsindex fcc0647c419..8fb549c0960 100644--- a/packages/types/src/openai/chat.ts+++ b/packages/types/src/openai/chat.ts@@ -38,7 +38,12 @@ interface UserMessageContentPartVideo {video_url: { url: string };}interface UserMessageContentPartAudio {- audio_url: { durationMs?: number; url: string };+ audio_url: {+ codec?: string;+ durationMs?: number;+ mimeType?: string;+ url: string;+ };type: 'audio_url';}diff --git a/packages/utils/src/imageToBase64.test.ts b/packages/utils/src/imageToBase64.test.tsindex 300a5ae0bb8..ee5ce4a7ad8 100644--- a/packages/utils/src/imageToBase64.test.ts+++ b/packages/utils/src/imageToBase64.test.ts@@ -116,4 +116,34 @@ describe('imageUrlToBase64', () => {await expect(imageUrlToBase64('https://example.com/image.jpg')).rejects.toThrow('Fetch failed');});++ it('should cancel a streaming download once it exceeds the configured byte limit', async () => {+ const cancel = vi.fn().mockResolvedValue(undefined);+ const read = vi+ .fn()+ .mockResolvedValueOnce({ done: false, value: new Uint8Array(5) })+ .mockResolvedValueOnce({ done: false, value: new Uint8Array(5) });+ mockFetch.mockResolvedValue({+ body: { getReader: () => ({ cancel, read }) },+ headers: { get: () => null },+ });++ await expect(+ imageUrlToBase64('https://example.com/large-audio.wav', { maxBytes: 8 }),+ ).rejects.toThrow('8-byte download limit');+ expect(cancel).toHaveBeenCalledOnce();+ });++ it('should cancel a response whose declared length already exceeds the byte limit', async () => {+ const cancel = vi.fn().mockResolvedValue(undefined);+ mockFetch.mockResolvedValue({+ body: { cancel },+ headers: { get: (key: string) => (key === 'content-length' ? '9' : null) },+ });++ await expect(+ imageUrlToBase64('https://example.com/declared-large.wav', { maxBytes: 8 }),+ ).rejects.toThrow('8-byte download limit');+ expect(cancel).toHaveBeenCalledOnce();+ });});diff --git a/packages/utils/src/imageToBase64.ts b/packages/utils/src/imageToBase64.tsindex a957b2a1c1e..5b442c7c298 100644--- a/packages/utils/src/imageToBase64.ts+++ b/packages/utils/src/imageToBase64.ts@@ -40,12 +40,60 @@ export const imageToBase64 = ({return canvas.toDataURL(type);};+export interface ImageUrlToBase64Options {+ /** Abort the download once the response exceeds this many bytes. */+ maxBytes?: number;+}++const sizeLimitError = (maxBytes: number) =>+ new RangeError(`Remote binary exceeds the ${maxBytes}-byte download limit`);++const readBlobWithLimit = async (response: Response, maxBytes: number): Promise<Blob> => {+ const declaredLength = Number(response.headers.get('content-length'));+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {+ await response.body?.cancel().catch(() => {});+ throw sizeLimitError(maxBytes);+ }++ if (!response.body) {+ const blob = await response.blob();+ if (blob.size > maxBytes) throw sizeLimitError(maxBytes);+ return blob;+ }++ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let receivedBytes = 0;++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ receivedBytes += value.byteLength;+ if (receivedBytes > maxBytes) {+ await reader.cancel();+ throw sizeLimitError(maxBytes);+ }+ chunks.push(value);+ }++ const bytes = new Uint8Array(receivedBytes);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }++ return new Blob([bytes], { type: response.headers.get('content-type') || '' });+};+/*** Convert image URL to base64* Uses SSRF-safe fetch on server-side to prevent SSRF attacks*/export const imageUrlToBase64 = async (imageUrl: string,+ options: ImageUrlToBase64Options = {},): Promise<{ base64: string; mimeType: string }> => {try {const isServer = typeof window === 'undefined';@@ -55,7 +103,9 @@ export const imageUrlToBase64 = async (? await import('@lobechat/ssrf-safe-fetch').then((m) => m.ssrfSafeFetch(imageUrl)): await fetch(imageUrl);- const blob = await res.blob();+ const blob = options.maxBytes+ ? await readBlobWithLimit(res, options.maxBytes)+ : await res.blob();const arrayBuffer = await blob.arrayBuffer();const mimeType = await resolveMimeTypeFromBytes(blob.type, arrayBuffer);diff --git a/src/features/AudioPlayer/index.tsx b/src/features/AudioPlayer/index.tsxindex 0218171a6a1..255c6a364b3 100644--- a/src/features/AudioPlayer/index.tsx+++ b/src/features/AudioPlayer/index.tsx@@ -2,13 +2,21 @@import { Icon } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';-import { DownloadIcon, PauseIcon, PlayIcon } from 'lucide-react';-import { memo, type MouseEvent, useCallback, useRef, useState } from 'react';+import { DownloadIcon, PauseIcon, PlayIcon, RotateCcwIcon, XIcon } from 'lucide-react';+import { memo, type MouseEvent, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useChatStore } from '@/store/chat';++import { useAudioElementSource } from './useAudioElementSource';import { useWaveform } from './useWaveform';const styles = createStaticStyles(({ css, cssVar }) => ({+ actionGroup: css`+ display: flex;+ flex: none;+ gap: 2px;+ `,bar: css`flex: 1;@@ -83,6 +91,73 @@ const styles = createStaticStyles(({ css, cssVar }) => ({background: ${cssVar.colorFillSecondary};}`,+ miniButton: css`+ cursor: pointer;++ display: flex;+ align-items: center;+ justify-content: center;++ width: 28px;+ height: 28px;+ padding: 0;+ border: 0;+ border-radius: 8px;++ color: ${cssVar.colorTextSecondary};++ background: transparent;++ transition:+ color 120ms ease,+ background 120ms ease;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: 1px;+ }+ `,+ progress: css`+ position: absolute;+ inset-block-end: 0;+ inset-inline: 0;++ overflow: hidden;++ height: 2px;+ border-radius: 2px;++ background: ${cssVar.colorFillSecondary};+ `,+ progressValue: css`+ height: 100%;+ border-radius: inherit;+ background: ${cssVar.colorPrimary};+ transition: width 160ms ease;+ `,+ status: css`+ pointer-events: none;++ position: absolute;+ inset: 0;++ overflow: hidden;+ display: flex;+ align-items: center;+ justify-content: center;++ padding-inline: 4px;++ font-size: 11px;+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,time: css`flex: none;@@ -108,10 +183,32 @@ const styles = createStaticStyles(({ css, cssVar }) => ({button) pushes the tail controls out of the rounded box. */min-width: 0;height: 32px;+ padding: 0;+ border: 0;++ background: transparent;++ &:focus-visible {+ border-radius: 4px;+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: 2px;+ }+ `,+ waveformPending: css`+ opacity: 0.18;+ `,+ waveformWrap: css`+ position: relative;++ display: flex;+ flex: 1;++ min-width: 0;+ height: 32px;`,}));-const formatTime = (seconds: number): string => {+export 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);@@ -122,117 +219,192 @@ interface AudioPlayerProps {alt?: string;/** Download filename; also switches the download affordance on. */downloadFileName?: string;+ durationMs?: number;/*** Fill the host's width instead of the chat bubble's fixed 360px — evidence* surfaces render the player as a block, not an inline attachment.*/fullWidth?: boolean;+ messageId?: string;url: string;}-const AudioPlayer = memo<AudioPlayerProps>(({ url, alt, downloadFileName, fullWidth }) => {- 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 AudioPlayer = memo<AudioPlayerProps>(+ ({ url, alt, downloadFileName, durationMs, fullWidth, messageId }) => {+ const { t } = useTranslation('chat');+ const [uploadState, cancelVoiceMessage, retryVoiceMessage] = useChatStore((s) => [+ messageId ? s.voiceMessageUploadMap[messageId] : undefined,+ s.cancelVoiceMessage,+ s.retryVoiceMessage,+ ]);+ const audioRef = useRef<HTMLAudioElement>(null);+ const [isPlaying, setIsPlaying] = useState(false);+ const [currentTime, setCurrentTime] = useState(0);+ const [duration, setDuration] = useState(() => (durationMs ? durationMs / 1000 : 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);++ useAudioElementSource(audioRef, url);++ const peaks = useWaveform(url, waveformEnabled);+ const progress = duration > 0 ? currentTime / duration : 0;+ const uploadProgress = Math.min(100, Math.max(0, Math.round(uploadState?.progress ?? 0)));+ const isFailed = uploadState?.status === 'failed';+ const isPending = uploadState?.status === 'uploading' || uploadState?.status === 'sending';+ const statusText =+ uploadState?.status === 'uploading'+ ? t('voiceMessage.status.uploading', { progress: uploadProgress })+ : uploadState?.status === 'sending'+ ? t('voiceMessage.status.sending')+ : uploadState?.error === 'unsupported'+ ? t('voiceMessage.status.unsupported')+ : uploadState?.error === 'send'+ ? t('voiceMessage.status.sendFailed')+ : uploadState?.error === 'upload'+ ? t('voiceMessage.status.uploadFailed')+ : undefined;++ useEffect(() => {+ setCurrentTime(0);+ setDuration(durationMs ? durationMs / 1000 : 0);+ setIsPlaying(false);+ setWaveformEnabled(false);+ }, [durationMs, url]);++ const togglePlay = useCallback(() => {const audio = audioRef.current;- if (!audio || !duration) return;+ if (!audio) 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],- );-- // Cross-origin sources (a signed S3 url) ignore the anchor `download`- // attribute, so pull the bytes and hand out a same-origin object url — the- // one route that saves with the intended filename instead of navigating.- const handleDownload = useCallback(async () => {- if (!downloadFileName) return;- try {- const res = await fetch(url);- const blob = await res.blob();- const objectUrl = URL.createObjectURL(blob);- const anchor = document.createElement('a');- anchor.href = objectUrl;- anchor.download = downloadFileName;- anchor.click();- URL.revokeObjectURL(objectUrl);- } catch {- window.open(url, '_blank', 'noopener');- }- }, [url, downloadFileName]);-- return (- <div className={styles.container} style={fullWidth ? { width: '100%' } : undefined}>- <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>- {downloadFileName && (+ if (audio.paused) void audio.play();+ else audio.pause();+ }, []);++ const handleSeek = useCallback(+ (e: MouseEvent<HTMLButtonElement>) => {+ 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],+ );++ // Cross-origin sources (a signed S3 url) ignore the anchor `download`+ // attribute, so pull the bytes and hand out a same-origin object url — the+ // one route that saves with the intended filename instead of navigating.+ const handleDownload = useCallback(async () => {+ if (!downloadFileName) return;+ try {+ const res = await fetch(url);+ const blob = await res.blob();+ const objectUrl = URL.createObjectURL(blob);+ const anchor = document.createElement('a');+ anchor.href = objectUrl;+ anchor.download = downloadFileName;+ anchor.click();+ URL.revokeObjectURL(objectUrl);+ } catch {+ window.open(url, '_blank', 'noopener');+ }+ }, [url, downloadFileName]);++ return (+ <div className={styles.container} style={fullWidth ? { width: '100%' } : undefined}>+ <audio+ preload={'metadata'}+ ref={audioRef}+ 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={t('audioPlayer.download')}- className={styles.download}- title={t('audioPlayer.download')}+ aria-label={isPlaying ? t('audioPlayer.pause') : t('audioPlayer.play')}+ aria-pressed={isPlaying}+ className={styles.button}+ title={alt}type={'button'}- onClick={() => void handleDownload()}+ onClick={togglePlay}>- <Icon icon={DownloadIcon} size={15} />+ <Icon icon={isPlaying ? PauseIcon : PlayIcon} size={16} /></button>- )}- </div>- );-});+ <div className={styles.waveformWrap}>+ <button+ aria-label={t('audioPlayer.seek')}+ className={`${styles.waveform} ${uploadState ? styles.waveformPending : ''}`}+ type="button"+ 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)}%` }}+ />+ );+ })}+ </button>+ {statusText && (+ <span aria-live="polite" className={styles.status} role="status" title={statusText}>+ {statusText}+ </span>+ )}+ {uploadState?.status === 'uploading' && (+ <div className={styles.progress}>+ <div className={styles.progressValue} style={{ width: `${uploadProgress}%` }} />+ </div>+ )}+ </div>+ <span className={styles.time}>{formatTime(currentTime || duration)}</span>+ {downloadFileName && (+ <button+ aria-label={t('audioPlayer.download')}+ className={styles.download}+ title={t('audioPlayer.download')}+ type={'button'}+ onClick={() => void handleDownload()}+ >+ <Icon icon={DownloadIcon} size={15} />+ </button>+ )}+ {uploadState && messageId && (+ <div className={styles.actionGroup}>+ {isFailed && (+ <button+ aria-label={t('voiceMessage.retry')}+ className={styles.miniButton}+ title={t('voiceMessage.retry')}+ type="button"+ onClick={() => retryVoiceMessage(messageId)}+ >+ <Icon icon={RotateCcwIcon} size={14} />+ </button>+ )}+ {(isPending || isFailed) && (+ <button+ aria-label={t(isFailed ? 'voiceMessage.delete' : 'voiceMessage.cancelUpload')}+ className={styles.miniButton}+ title={t(isFailed ? 'voiceMessage.delete' : 'voiceMessage.cancelUpload')}+ type="button"+ onClick={() => void cancelVoiceMessage(messageId)}+ >+ <Icon icon={XIcon} size={14} />+ </button>+ )}+ </div>+ )}+ </div>+ );+ },+);AudioPlayer.displayName = 'AudioPlayer';diff --git a/src/features/AudioPlayer/useAudioElementSource.test.ts b/src/features/AudioPlayer/useAudioElementSource.test.tsnew file mode 100644index 00000000000..02e4a9fc751--- /dev/null+++ b/src/features/AudioPlayer/useAudioElementSource.test.ts@@ -0,0 +1,37 @@+import { renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useAudioElementSource } from './useAudioElementSource';++describe('useAudioElementSource', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('restores the next source after cleaning up the previous URL', () => {+ const audio = document.createElement('audio');+ const pause = vi.spyOn(audio, 'pause').mockImplementation(() => {});+ const load = vi.spyOn(audio, 'load').mockImplementation(() => {});+ const audioRef = { current: audio };+ const firstUrl = 'https://example.com/first.webm';+ const secondUrl = 'https://example.com/second.webm';++ const { rerender, unmount } = renderHook(({ url }) => useAudioElementSource(audioRef, url), {+ initialProps: { url: firstUrl },+ });++ expect(audio.src).toBe(firstUrl);++ rerender({ url: secondUrl });++ expect(pause).toHaveBeenCalledOnce();+ expect(load).toHaveBeenCalledOnce();+ expect(audio.src).toBe(secondUrl);++ unmount();++ expect(pause).toHaveBeenCalledTimes(2);+ expect(load).toHaveBeenCalledTimes(2);+ expect(audio.hasAttribute('src')).toBe(false);+ });+});diff --git a/src/features/AudioPlayer/useAudioElementSource.ts b/src/features/AudioPlayer/useAudioElementSource.tsnew file mode 100644index 00000000000..1850510b835--- /dev/null+++ b/src/features/AudioPlayer/useAudioElementSource.ts@@ -0,0 +1,20 @@+import type { RefObject } from 'react';+import { useEffect } from 'react';++export const useAudioElementSource = (+ audioRef: RefObject<HTMLAudioElement | null>,+ url: string,+) => {+ useEffect(() => {+ const audio = audioRef.current;+ if (!audio) return;++ audio.src = url;++ return () => {+ audio.pause();+ audio.removeAttribute('src');+ audio.load();+ };+ }, [audioRef, url]);+};diff --git a/src/features/ChatInput/ActionBar/config.ts b/src/features/ChatInput/ActionBar/config.tsindex 0e13a157df3..a1153858ff2 100644--- a/src/features/ChatInput/ActionBar/config.ts+++ b/src/features/ChatInput/ActionBar/config.ts@@ -1,3 +1,4 @@+import VoiceMessage from '../VoiceMessage';import AgentMode from './AgentMode';import Clear from './Clear';import Effort from './Effort';@@ -33,6 +34,7 @@ export const actionMap = {temperature: Params,tools: Tools,typo: Typo,+ voiceMessage: VoiceMessage,} as const;export type ActionKey = keyof typeof actionMap;diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsxindex 19d615f5452..737079ef200 100644--- a/src/features/ChatInput/ChatInputProvider.tsx+++ b/src/features/ChatInput/ChatInputProvider.tsx@@ -15,6 +15,7 @@ interface ChatInputProviderProps extends StoreUpdaterProps {export const ChatInputProvider = memo<ChatInputProviderProps>(({agentId,+ canRecordVoiceMessage,children,contextSelectionKey,contextWindowMessages,@@ -25,6 +26,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(mobile,sendButtonProps,onSend,+ onVoiceMessageSend,sendMenu,chatInputEditorRef,onMarkdownContentChange,@@ -42,6 +44,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(createStore={() =>createStore({allowExpand,+ canRecordVoiceMessage,contextSelectionKey,contextWindowMessages,draftKey,@@ -51,6 +54,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(mentionItems,mobile,rightActions,+ onVoiceMessageSend,sendButtonProps,sendMenu,slashMenuRef,@@ -61,6 +65,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(<StoreUpdateragentId={agentId}allowExpand={allowExpand}+ canRecordVoiceMessage={canRecordVoiceMessage}chatInputEditorRef={chatInputEditorRef}contextSelectionKey={contextSelectionKey}contextWindowMessages={contextWindowMessages}@@ -77,6 +82,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(slashPlacement={slashPlacement}onMarkdownContentChange={onMarkdownContentChange}onSend={onSend}+ onVoiceMessageSend={onVoiceMessageSend}/><ReasoningConfigLoader />{children}diff --git a/src/features/ChatInput/SendArea/index.tsx b/src/features/ChatInput/SendArea/index.tsxindex e9409ec6575..7e938f04e13 100644--- a/src/features/ChatInput/SendArea/index.tsx+++ b/src/features/ChatInput/SendArea/index.tsx@@ -29,22 +29,25 @@ const SendArea = memo<SendAreaProps>(({ hideContextWindow = true }) => {const { canShowControls } = useChatInputResourceAccess();const allowExpand = useChatInputStore((s) => s.allowExpand);const rightActions = useChatInputStore((s) => s.rightActions, isEqual);+ const voiceMessageActive = useChatInputStore((s) => s.activeAudioInputMode === 'voiceMessage');const items = useMemo(() =>canShowControls? mapActionsToItems(- resolveSendAreaActionKeys(rightActions as ActionKey[], hideContextWindow),+ voiceMessageActive+ ? (['voiceMessage'] as ActionKey[])+ : resolveSendAreaActionKeys(rightActions as ActionKey[], hideContextWindow),): [],- [canShowControls, rightActions, hideContextWindow],+ [canShowControls, hideContextWindow, rightActions, voiceMessageActive],);return (<Flexbox horizontal align={'center'} flex={'none'} gap={12}>- {canShowControls && allowExpand && <ExpandButton />}+ {canShowControls && allowExpand && !voiceMessageActive && <ExpandButton />}{items}- <SendButton />+ {!voiceMessageActive && <SendButton />}</Flexbox>);});diff --git a/src/features/ChatInput/StoreUpdater.test.tsx b/src/features/ChatInput/StoreUpdater.test.tsxindex 4ea05625937..6a4f532470f 100644--- a/src/features/ChatInput/StoreUpdater.test.tsx+++ b/src/features/ChatInput/StoreUpdater.test.tsx@@ -1,12 +1,47 @@import { type MenuProps } from '@lobehub/ui';-import { render } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { type PropsWithChildren, useEffect } from 'react';-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { useSingleton } from '@/hooks/useSingleton';import { createStore, Provider, useChatInputStore } from './store';import StoreUpdater from './StoreUpdater';+import VoiceMessage from './VoiceMessage';++const voiceCapability = vi.hoisted(() => ({ fallback: false }));+const voiceRecorder = vi.hoisted(() => ({+ durationMs: 0,+ error: undefined,+ minDurationMs: 500,+ recording: undefined,+ reset: vi.fn(),+ start: vi.fn(),+ status: 'idle' as 'idle' | 'recording',+ stop: vi.fn(),+ waveform: [],+}));++vi.mock('./ActionBar/components/ChatInputAction', () => ({+ ChatInputAction: ({+ disabled,+ 'data-testid': testId,+ onClick,+ }: {+ 'data-testid'?: string;+ 'disabled'?: boolean;+ 'onClick'?: () => void;+ }) => <button data-testid={testId} disabled={disabled} type="button" onClick={onClick} />,+}));++vi.mock('./VoiceMessage/useVoiceMessageCapability', async (importOriginal) => ({+ ...(await importOriginal()),+ useVoiceMessageCapability: () => voiceCapability.fallback,+}));++vi.mock('./VoiceMessage/useVoiceMessageRecorder', () => ({+ useVoiceMessageRecorder: () => voiceRecorder,+}));interface TestHarnessProps {onSendMenuChange: (menu: MenuProps | undefined) => void;@@ -27,12 +62,29 @@ const Probe = ({return null;};+const VoiceCapabilityProbe = ({ onChange }: { onChange: (value?: boolean) => void }) => {+ const canRecordVoiceMessage = useChatInputStore((s) => s.canRecordVoiceMessage);++ useEffect(() => {+ onChange(canRecordVoiceMessage);+ }, [canRecordVoiceMessage, onChange]);++ return null;+};+const TestHarness = ({ children }: PropsWithChildren) => {const store = useSingleton(createStore);return <Provider createStore={() => store}>{children}</Provider>;};+beforeEach(() => {+ voiceRecorder.status = 'idle';+ voiceRecorder.reset.mockReset();+ voiceRecorder.start.mockReset();+ voiceRecorder.stop.mockReset();+});+describe('ChatInput StoreUpdater', () => {it('clears sendMenu when the prop becomes undefined', () => {const initialSendMenu = { items: [{ key: 'test', label: 'Test' }] } satisfies MenuProps;@@ -61,4 +113,108 @@ describe('ChatInput StoreUpdater', () => {expect(onSendMenuChange).toHaveBeenLastCalledWith(undefined);});++ it('keeps canRecordVoiceMessage in sync when the prop changes', () => {+ const onChange = vi.fn();++ const { rerender } = render(+ <TestHarness>+ <StoreUpdater+ canRecordVoiceMessage={false}+ leftActions={[]}+ rightActions={[]}+ onSend={() => {}}+ />+ <VoiceCapabilityProbe onChange={onChange} />+ </TestHarness>,+ );++ expect(onChange).toHaveBeenLastCalledWith(false);++ rerender(+ <TestHarness>+ <StoreUpdater canRecordVoiceMessage leftActions={[]} rightActions={[]} onSend={() => {}} />+ <VoiceCapabilityProbe onChange={onChange} />+ </TestHarness>,+ );++ expect(onChange).toHaveBeenLastCalledWith(true);+ });++ it('lets an injected capability override the fallback model capability', () => {+ const store = createStore({+ agentId: 'voice-agent',+ canRecordVoiceMessage: true,+ leftActions: [],+ onVoiceMessageSend: () => true,+ rightActions: [],+ });++ render(+ <Provider createStore={() => store}>+ <VoiceMessage />+ </Provider>,+ );++ expect(voiceCapability.fallback).toBe(false);+ expect(screen.getByTestId('voice-message-action')).not.toBeDisabled();+ });++ it('blocks a second voice recording while the current response is generating', () => {+ const onStop = vi.fn();+ const store = createStore({+ agentId: 'voice-agent',+ canRecordVoiceMessage: true,+ leftActions: [],+ onVoiceMessageSend: () => true,+ rightActions: [],+ sendButtonProps: { generating: true, onStop },+ });++ render(+ <Provider createStore={() => store}>+ <VoiceMessage />+ </Provider>,+ );++ const action = screen.getByTestId('voice-message-action');+ expect(action).toBeDisabled();+ fireEvent.click(action);+ expect(voiceRecorder.start).not.toHaveBeenCalled();++ act(() => store.setState({ sendButtonProps: { generating: false, onStop } }));++ const restoredAction = screen.getByTestId('voice-message-action');+ expect(restoredAction).not.toBeDisabled();+ fireEvent.click(restoredAction);+ expect(voiceRecorder.start).toHaveBeenCalledOnce();+ });++ it('cancels an active recording when a response starts generating', async () => {+ voiceRecorder.status = 'recording';+ voiceRecorder.reset.mockImplementation(() => {+ voiceRecorder.status = 'idle';+ });+ const onStop = vi.fn();+ const store = createStore({+ activeAudioInputMode: 'voiceMessage',+ agentId: 'voice-agent',+ canRecordVoiceMessage: true,+ leftActions: [],+ onVoiceMessageSend: () => true,+ rightActions: [],+ sendButtonProps: { generating: false, onStop },+ });++ render(+ <Provider createStore={() => store}>+ <VoiceMessage />+ </Provider>,+ );++ act(() => store.setState({ sendButtonProps: { generating: true, onStop } }));++ await waitFor(() => expect(voiceRecorder.reset).toHaveBeenCalledOnce());+ expect(store.getState().activeAudioInputMode).toBeUndefined();+ });});diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsxindex 2e62881474d..6df8a785638 100644--- a/src/features/ChatInput/StoreUpdater.tsx+++ b/src/features/ChatInput/StoreUpdater.tsx@@ -17,6 +17,7 @@ export interface StoreUpdaterProps extends Partial<PublicState> {const StoreUpdater = memo<StoreUpdaterProps>(({agentId,+ canRecordVoiceMessage,chatInputEditorRef,contextSelectionKey,contextWindowMessages,@@ -27,6 +28,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(leftActions,rightActions,onSend,+ onVoiceMessageSend,onMarkdownContentChange,sendMenu,mentionItems,@@ -40,6 +42,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(const editor = useChatInputEditor();useStoreUpdater('agentId', agentId);+ useStoreUpdater('canRecordVoiceMessage', canRecordVoiceMessage);useStoreUpdater('contextSelectionKey', contextSelectionKey);useStoreUpdater('contextWindowMessages', contextWindowMessages);@@ -63,6 +66,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(useStoreUpdater('sendButtonProps', sendButtonProps);useStoreUpdater('resolveSendBlocked', resolveSendBlocked);useStoreUpdater('onSend', onSend);+ useStoreUpdater('onVoiceMessageSend', onVoiceMessageSend);useStoreUpdater('onMarkdownContentChange', onMarkdownContentChange);useEffect(() => {diff --git a/src/features/ChatInput/VoiceMessage/index.tsx b/src/features/ChatInput/VoiceMessage/index.tsxnew file mode 100644index 00000000000..1572f9ccd8c--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/index.tsx@@ -0,0 +1,679 @@+'use client';++import { type VoiceMessageRecording } from '@lobechat/types';+import { Icon, Tooltip } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { ArrowUp, type LucideProps, RotateCcw, X } from 'lucide-react';+import { memo, useCallback, useEffect, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import { ChatInputAction } from '../ActionBar/components/ChatInputAction';+import { useAgentId } from '../hooks/useAgentId';+import { useEffectiveModel } from '../hooks/useEffectiveModel';+import { useChatInputStore, useStoreApi } from '../store';+import { formatVoiceDuration } from './mediaRecorder';+import { useIntentionalHover } from './useIntentionalHover';+import { getVoiceMessageActionState, useVoiceMessageCapability } from './useVoiceMessageCapability';+import { useVoiceMessageRecorder } from './useVoiceMessageRecorder';++const VoiceMessageIcon = ({+ ref,+ size = 24,+ strokeWidth = 2,+ ...rest+}: LucideProps & { ref?: React.RefObject<SVGSVGElement | null> }) => (+ <svg+ fill="none"+ height={size}+ ref={ref}+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={strokeWidth}+ viewBox="0 0 24 24"+ width={size}+ {...rest}+ >+ <circle cx="12" cy="12" r="9" />+ <path d="M8.5 12h.01" />+ <path d="M11 9.75a3.25 3.25 0 0 1 0 4.5" />+ <path d="M14 7.5a6.25 6.25 0 0 1 0 9" />+ </svg>+);++VoiceMessageIcon.displayName = 'VoiceMessageIcon';++const styles = createStaticStyles(({ css, cssVar }) => ({+ bar: css`+ width: 4px;+ min-height: 4px;+ border-radius: 9999px;++ background: ${cssVar.colorPrimary};++ transition: height 80ms linear;++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ cancelButton: css`+ cursor: default;++ position: relative;++ display: inline-flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 32px;+ height: 32px;+ padding: 0;+ border: 0;+ border-radius: 9999px;++ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillSecondary};++ transition:+ color 120ms ease,+ background 120ms ease,+ transform 120ms ease;++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: 2px;+ }++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFill};+ }++ &:active {+ transform: scale(0.96);+ }++ @media (width <= 600px) {+ &::after {+ content: '';+ position: absolute;+ inset: -6px;+ }+ }++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ container: css`+ display: flex;+ flex: none;+ gap: 6px;+ align-items: center;++ width: min(300px, calc(100vw - 112px));+ min-width: min(220px, calc(100vw - 112px));+ height: 32px;+ padding-inline: 2px;++ animation: voice-message-enter 160ms ease-out;++ @media (prefers-reduced-motion: reduce) {+ animation: none;+ }++ @keyframes voice-message-enter {+ from {+ transform: translateX(8px);+ opacity: 0;+ }++ to {+ transform: translateX(0);+ opacity: 1;+ }+ }+ `,+ error: css`+ position: absolute;+ z-index: 1;+ inset-block-start: 50%;+ inset-inline: 12px 44px;+ transform: translateY(-50%);++ overflow: hidden;++ font-size: ${cssVar.fontSizeSM};+ line-height: 1.3;+ color: ${cssVar.colorError};+ text-align: center;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ pill: css`+ position: relative;++ overflow: hidden;+ flex: 1;++ min-width: 0;+ height: 100%;+ border-radius: 9999px;++ background: ${cssVar.colorFillSecondary};+ `,+ progress: css`+ position: absolute;+ z-index: 3;+ inset-block-end: 0;+ inset-inline: 6px;++ overflow: hidden;++ height: 2px;+ border-radius: 1px;++ background: ${cssVar.colorFillSecondary};+ `,+ progressValue: css`+ height: 100%;+ border-radius: inherit;++ opacity: 0.72;+ background: ${cssVar.colorBgContainer};++ transition: width 120ms linear;++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ sendArrow: css`+ position: absolute;+ z-index: 2;+ inset-block-start: 50%;+ inset-inline-end: 2px;+ transform: translateY(-50%);++ display: inline-flex;+ align-items: center;+ justify-content: center;++ width: 28px;+ height: 28px;++ opacity: 1;++ transition:+ opacity 100ms ease,+ transform 160ms ease;++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ sendButton: css`+ cursor: default;++ position: absolute;+ z-index: 2;+ inset: 0;++ overflow: hidden;++ width: 100%;+ padding: 0;+ border: 0;+ border-radius: inherit;++ color: ${cssVar.colorBgContainer};++ background: transparent;++ &::before {+ content: '';++ position: absolute;+ z-index: 0;+ inset: 0;++ border-radius: inherit;++ background: ${cssVar.colorPrimary};+ clip-path: circle(14px at calc(100% - 16px) 50%);++ transition: clip-path 160ms cubic-bezier(0.2, 0.8, 0.2, 1);+ }++ &[data-error='true']::before {+ background: ${cssVar.colorError};+ }++ &[data-hover-expanded='true']::before,+ &:focus-visible::before,+ &[data-expanded='true']::before {+ clip-path: circle(150% at calc(100% - 16px) 50%);+ }++ &[data-hover-expanded='true'] > span:first-child,+ &:focus-visible > span:first-child,+ &[data-expanded='true'] > span:first-child {+ transform: translateY(0);+ opacity: 1;+ }++ &[data-hover-expanded='true'] > span:last-child,+ &:focus-visible > span:last-child,+ &[data-expanded='true'] > span:last-child {+ transform: translateY(-50%) translateX(6px);+ opacity: 0;+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -3px;+ }++ &:disabled {+ cursor: not-allowed;+ }++ &:disabled::before {+ opacity: 0.45;+ }++ @media (prefers-reduced-motion: reduce) {+ &::before {+ transition: none;+ }+ }+ `,+ sendDots: css`+ display: inline-flex;+ gap: 3px;+ align-items: center;++ > i {+ width: 3px;+ height: 3px;+ border-radius: 9999px;+ background: currentcolor;+ }+ `,+ sendLabel: css`+ position: absolute;+ z-index: 2;+ inset: 0;+ transform: translateY(4px);++ display: flex;+ gap: 8px;+ align-items: center;+ justify-content: center;++ font-size: ${cssVar.fontSize};+ font-weight: ${cssVar.fontWeightStrong};++ opacity: 0;++ transition:+ opacity 100ms ease,+ transform 160ms ease;++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ waveform: css`+ pointer-events: none;++ position: absolute;+ z-index: 1;+ inset: 0;++ display: flex;+ gap: 4px;+ align-items: center;+ justify-content: center;+ `,+ visuallyHidden: css`+ position: absolute;++ overflow: hidden;++ width: 1px;+ height: 1px;+ margin: -1px;+ padding: 0;+ border: 0;++ white-space: nowrap;++ clip: rect(0, 0, 0, 0);+ clip-path: inset(50%);+ `,+}));++export interface VoiceMessageControlProps {+ actionLabel: string;+ actionText?: string;+ cancelLabel: string;+ durationLabel: string;+ errorText?: string;+ expanded?: boolean;+ groupLabel: string;+ isRetry?: boolean;+ onAction: () => void;+ onCancel: () => void;+ progress?: number;+ sendDisabled?: boolean;+ statusAnnouncement: string;+ tooltip?: string;+ waveform: number[];+}++const SendDots = memo(() => (+ <span aria-hidden className={styles.sendDots}>+ {Array.from({ length: 4 }, (_, index) => (+ <i key={index} />+ ))}+ </span>+));++SendDots.displayName = 'VoiceMessageSendDots';++export const VoiceMessageControl = memo<VoiceMessageControlProps>(+ ({+ actionLabel,+ actionText,+ cancelLabel,+ durationLabel,+ errorText,+ expanded,+ groupLabel,+ isRetry,+ progress,+ sendDisabled,+ statusAnnouncement,+ tooltip,+ waveform,+ onAction,+ onCancel,+ }) => {+ const sendButtonRef = useRef<HTMLButtonElement>(null);+ const { handlePointerEnter, handlePointerLeave, isHoverExpanded } =+ useIntentionalHover(sendButtonRef);++ return (+ <div+ aria-label={groupLabel}+ className={styles.container}+ data-testid="voice-message-recorder"+ role="group"+ >+ <span aria-live="polite" className={styles.visuallyHidden}>+ {statusAnnouncement}+ </span>+ <button+ aria-label={cancelLabel}+ className={styles.cancelButton}+ data-testid="voice-message-cancel"+ type="button"+ onClick={onCancel}+ >+ <Icon icon={X} size={17} />+ </button>++ <div className={styles.pill} data-testid="voice-message-pill">+ <span className={styles.visuallyHidden}>{durationLabel}</span>++ {errorText ? (+ <span className={styles.error} title={errorText}>+ {errorText}+ </span>+ ) : (+ <div aria-hidden className={styles.waveform}>+ {waveform.map((level, index) => (+ <span+ className={styles.bar}+ key={index}+ style={{ height: `${Math.max(4, Math.round(level * 18))}px` }}+ />+ ))}+ </div>+ )}++ <Tooltip title={tooltip}>+ <button+ aria-label={actionLabel}+ className={styles.sendButton}+ data-error={isRetry}+ data-expanded={expanded}+ data-hover-expanded={isHoverExpanded}+ data-testid={isRetry ? 'voice-message-retry' : 'voice-message-send'}+ disabled={sendDisabled}+ ref={sendButtonRef}+ type="button"+ onClick={onAction}+ onPointerEnter={(event) => handlePointerEnter(event.pointerType)}+ onPointerLeave={(event) => handlePointerLeave(event.pointerType)}+ >+ <span className={styles.sendLabel}>+ <SendDots />+ <span>{actionText}</span>+ <SendDots />+ </span>+ <span className={styles.sendArrow}>+ <Icon icon={isRetry ? RotateCcw : ArrowUp} size={18} />+ </span>+ </button>+ </Tooltip>++ {progress !== undefined && (+ <div aria-hidden className={styles.progress}>+ <div className={styles.progressValue} style={{ width: `${progress}%` }} />+ </div>+ )}+ </div>+ </div>+ );+ },+);++VoiceMessageControl.displayName = 'VoiceMessageControl';++const VoiceMessage = memo(() => {+ const { t } = useTranslation('chat');+ const agentId = useAgentId();+ const { model, provider } = useEffectiveModel(agentId);+ const fallbackCanRecordVoiceMessage = useVoiceMessageCapability(model, provider);+ const storeApi = useStoreApi();+ const [+ activeAudioInputMode,+ injectedCanRecordVoiceMessage,+ onVoiceMessageSend,+ sendButtonProps,+ setActiveAudioInputMode,+ ] = useChatInputStore((s) => [+ s.activeAudioInputMode,+ s.canRecordVoiceMessage,+ s.onVoiceMessageSend,+ s.sendButtonProps,+ s.setActiveAudioInputMode,+ ]);+ const canRecordVoiceMessage = injectedCanRecordVoiceMessage ?? fallbackCanRecordVoiceMessage;+ const isGenerating = Boolean(sendButtonProps?.generating);+ const canUseVoiceMessage = canRecordVoiceMessage && !isGenerating;+ const recorder = useVoiceMessageRecorder();+ const canUseVoiceMessageRef = useRef(canUseVoiceMessage);+ canUseVoiceMessageRef.current = canUseVoiceMessage;+ const sendCommittedRef = useRef(false);++ const hasRecorderActivity = recorder.status !== 'idle';+ const isActive = activeAudioInputMode === 'voiceMessage' || hasRecorderActivity;+ const isOtherAudioModeActive =+ activeAudioInputMode !== undefined && activeAudioInputMode !== 'voiceMessage';+ const canStart = canUseVoiceMessage && Boolean(onVoiceMessageSend) && !isOtherAudioModeActive;++ useEffect(() => {+ if (hasRecorderActivity && activeAudioInputMode !== 'voiceMessage') {+ setActiveAudioInputMode('voiceMessage');+ } else if (!hasRecorderActivity && activeAudioInputMode === 'voiceMessage') {+ setActiveAudioInputMode(undefined);+ }+ }, [activeAudioInputMode, hasRecorderActivity, setActiveAudioInputMode]);++ useEffect(+ () => () => {+ if (storeApi.getState().activeAudioInputMode === 'voiceMessage') {+ storeApi.getState().setActiveAudioInputMode(undefined);+ }+ },+ [storeApi],+ );++ const discard = useCallback(() => {+ recorder.reset();+ setActiveAudioInputMode(undefined);+ }, [recorder, setActiveAudioInputMode]);++ useEffect(() => {+ if (isGenerating && isActive) discard();+ }, [discard, isActive, isGenerating]);++ const commitRecording = useCallback(+ async (captured?: VoiceMessageRecording) => {+ if (!canUseVoiceMessageRef.current || sendCommittedRef.current) return;+ sendCommittedRef.current = true;++ try {+ const voiceRecording = captured ?? recorder.recording ?? (await recorder.stop());+ if (+ !canUseVoiceMessageRef.current ||+ !voiceRecording ||+ voiceRecording.durationMs < recorder.minDurationMs+ )+ return;+ if (!onVoiceMessageSend) return;++ const accepted = onVoiceMessageSend(voiceRecording);+ if (!accepted) return;++ recorder.reset();+ setActiveAudioInputMode(undefined);+ } finally {+ sendCommittedRef.current = false;+ }+ },+ [onVoiceMessageSend, recorder, setActiveAudioInputMode],+ );++ const handleStart = useCallback(() => {+ if (!canStart || storeApi.getState().sendButtonProps?.generating) return;+ setActiveAudioInputMode('voiceMessage');+ void recorder.start();+ }, [canStart, recorder, setActiveAudioInputMode, storeApi]);++ const handleRetryPermission = useCallback(() => {+ if (!canUseVoiceMessageRef.current) return;++ recorder.reset();+ void recorder.start();+ }, [recorder]);++ if (!isActive) {+ const disabledReason = isOtherAudioModeActive+ ? t('voiceMessage.otherAudioModeActive')+ : isGenerating+ ? t('voiceMessage.replyInProgress')+ : t('voiceMessage.unsupported');++ return canStart ? (+ <ChatInputAction+ aria-label={t('voiceMessage.action')}+ data-testid="voice-message-action"+ icon={VoiceMessageIcon}+ title={t('voiceMessage.action')}+ onClick={handleStart}+ />+ ) : (+ <Tooltip title={disabledReason}>+ <ChatInputAction+ disabled+ aria-label={t('voiceMessage.action')}+ data-testid="voice-message-action"+ icon={VoiceMessageIcon}+ showTooltip={false}+ title={t('voiceMessage.action')}+ />+ </Tooltip>+ );+ }++ const errorText = isGenerating+ ? t('voiceMessage.replyInProgress')+ : !canRecordVoiceMessage+ ? t('voiceMessage.unsupported')+ : recorder.error+ ? t(`voiceMessage.error.${recorder.error}`)+ : undefined;+ const waveform = recorder.recording?.waveform ?? recorder.waveform;+ const visibleWaveform = waveform.slice(-8);+ const canSendRecording =+ recorder.durationMs >= recorder.minDurationMs &&+ (recorder.status === 'recording' || recorder.status === 'ready');+ const { canSend, sendDisabled, showRetry } = getVoiceMessageActionState({+ canRecordVoiceMessage: canUseVoiceMessage,+ canSendRecording,+ hasRecoverableError: recorder.status === 'error',+ });+ const showBusy = recorder.status === 'requesting' || recorder.status === 'stopping';+ const statusText =+ recorder.status === 'requesting'+ ? t('voiceMessage.requesting')+ : recorder.status === 'stopping'+ ? t('voiceMessage.stopping')+ : undefined;+ const statusAnnouncement =+ errorText ??+ statusText ??+ (recorder.status === 'recording'+ ? t('voiceMessage.recording')+ : recorder.status === 'ready'+ ? t('voiceMessage.ready')+ : '');++ return (+ <VoiceMessageControl+ actionLabel={t(showRetry ? 'voiceMessage.retry' : 'voiceMessage.send')}+ cancelLabel={t(recorder.status === 'ready' ? 'voiceMessage.delete' : 'voiceMessage.cancel')}+ errorText={errorText}+ expanded={showBusy}+ groupLabel={t('voiceMessage.statusLabel')}+ isRetry={showRetry}+ sendDisabled={sendDisabled}+ statusAnnouncement={statusAnnouncement}+ waveform={visibleWaveform}+ actionText={+ showRetry ? t('input.inputCompletionError.retry') : showBusy ? statusText : t('input.send')+ }+ durationLabel={t('voiceMessage.duration', {+ duration: formatVoiceDuration(recorder.durationMs),+ })}+ tooltip={+ canUseVoiceMessage && !canSend && recorder.status === 'recording'+ ? t('voiceMessage.tooShort', { duration: recorder.minDurationMs })+ : undefined+ }+ onAction={showRetry ? handleRetryPermission : () => void commitRecording()}+ onCancel={discard}+ />+ );+});++VoiceMessage.displayName = 'VoiceMessage';++export default VoiceMessage;diff --git a/src/features/ChatInput/VoiceMessage/mediaRecorder.test.ts b/src/features/ChatInput/VoiceMessage/mediaRecorder.test.tsnew file mode 100644index 00000000000..88f167805ef--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/mediaRecorder.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it, vi } from 'vitest';++import {+ formatVoiceDuration,+ getAudioCodec,+ getAudioFileExtension,+ getVoiceRecorderErrorCode,+ resolveRecordingMimeType,+ selectRecordingMimeType,+} from './mediaRecorder';++describe('voice message media recorder compatibility', () => {+ it('prefers Opus WebM when Chromium reports it as supported', () => {+ const isTypeSupported = vi.fn((mimeType: string) => mimeType === 'audio/webm;codecs=opus');++ expect(selectRecordingMimeType({ isTypeSupported })).toBe('audio/webm;codecs=opus');+ });++ it('falls back to AAC MP4 for Safari-style support', () => {+ const isTypeSupported = vi.fn((mimeType: string) => mimeType === 'audio/mp4;codecs=mp4a.40.2');++ expect(selectRecordingMimeType({ isTypeSupported })).toBe('audio/mp4;codecs=mp4a.40.2');+ });++ it('lets the browser choose when none of the explicit containers are supported', () => {+ expect(selectRecordingMimeType({ isTypeSupported: () => false })).toBeUndefined();+ });++ it('uses the recorder-reported MIME before requested and chunk fallbacks', () => {+ const chunks = [new Blob(['audio'], { type: 'audio/ogg' })];++ expect(resolveRecordingMimeType('audio/mp4', chunks, 'audio/webm')).toBe('audio/mp4');+ expect(resolveRecordingMimeType('', chunks, 'audio/webm')).toBe('audio/ogg');+ expect(resolveRecordingMimeType('', [], 'audio/webm')).toBe('audio/webm');+ });++ it('derives compatible extensions and codec metadata', () => {+ expect(getAudioFileExtension('audio/webm;codecs=opus')).toBe('webm');+ expect(getAudioFileExtension('audio/mp4;codecs=mp4a.40.2')).toBe('m4a');+ expect(getAudioCodec('audio/webm;codecs="opus"')).toBe('opus');+ expect(getAudioCodec('audio/mp4')).toBeUndefined();+ });++ it('maps microphone permission errors without treating them as ASR failures', () => {+ expect(getVoiceRecorderErrorCode(new DOMException('denied', 'NotAllowedError'))).toBe(+ 'permission_denied',+ );+ expect(getVoiceRecorderErrorCode(new Error('device lost'))).toBe('recording_failed');+ });++ it('formats duration with a stable minute and second width', () => {+ expect(formatVoiceDuration(0)).toBe('0:00');+ expect(formatVoiceDuration(61_900)).toBe('1:01');+ });+});diff --git a/src/features/ChatInput/VoiceMessage/mediaRecorder.ts b/src/features/ChatInput/VoiceMessage/mediaRecorder.tsnew file mode 100644index 00000000000..597702aaaf8--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/mediaRecorder.ts@@ -0,0 +1,86 @@+export const VOICE_MESSAGE_MIN_DURATION_MS = 600;+export const VOICE_MESSAGE_MAX_DURATION_MS = 60_000;++export const RECORDING_MIME_TYPE_CANDIDATES = [+ 'audio/webm;codecs=opus',+ 'audio/mp4;codecs=mp4a.40.2',+ 'audio/webm',+ 'audio/mp4',+ 'audio/ogg;codecs=opus',+] as const;++type MediaRecorderSupport = Pick<typeof MediaRecorder, 'isTypeSupported'>;++export const selectRecordingMimeType = (+ mediaRecorder: MediaRecorderSupport,+): string | undefined => {+ for (const mimeType of RECORDING_MIME_TYPE_CANDIDATES) {+ if (mediaRecorder.isTypeSupported(mimeType)) return mimeType;+ }++ return undefined;+};++export const resolveRecordingMimeType = (+ recorderMimeType: string,+ chunks: Blob[],+ requestedMimeType?: string,+): string => {+ return (+ recorderMimeType ||+ chunks.find((chunk) => Boolean(chunk.type))?.type ||+ requestedMimeType ||+ 'audio/webm'+ );+};++export const getAudioCodec = (mimeType: string): string | undefined => {+ const codec = /codecs\s*=\s*"?([^";,]+)"?/i.exec(mimeType)?.[1]?.trim();+ return codec || undefined;+};++export const getAudioFileExtension = (mimeType: string): string => {+ const container = mimeType.split(';')[0]?.trim().toLowerCase();++ switch (container) {+ case 'audio/mp4':+ case 'audio/aac': {+ return 'm4a';+ }+ case 'audio/ogg': {+ return 'ogg';+ }+ case 'audio/wav':+ case 'audio/x-wav': {+ return 'wav';+ }+ case 'audio/mpeg': {+ return 'mp3';+ }+ default: {+ return 'webm';+ }+ }+};++export const formatVoiceDuration = (durationMs: number): string => {+ const totalSeconds = Math.max(0, Math.floor(durationMs / 1000));+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;++ return `${minutes}:${seconds.toString().padStart(2, '0')}`;+};++export type VoiceRecorderErrorCode = 'not_supported' | 'permission_denied' | 'recording_failed';++export const getVoiceRecorderErrorCode = (error: unknown): VoiceRecorderErrorCode => {+ const name =+ error && typeof error === 'object' && 'name' in error+ ? (error as { name?: unknown }).name+ : undefined;+ if (name === 'NotAllowedError' || name === 'SecurityError') {+ return 'permission_denied';+ }++ return 'recording_failed';+};diff --git a/src/features/ChatInput/VoiceMessage/normalizeRecording.test.ts b/src/features/ChatInput/VoiceMessage/normalizeRecording.test.tsnew file mode 100644index 00000000000..0729b6ea449--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/normalizeRecording.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it, vi } from 'vitest';++import { normalizeVoiceRecording } from './normalizeRecording';++const readAscii = (view: DataView, offset: number, length: number) =>+ Array.from({ length }, (_, index) => String.fromCharCode(view.getUint8(offset + index))).join('');++describe('normalizeVoiceRecording', () => {+ it('converts browser-recorded audio into mono 16 kHz PCM WAV', async () => {+ const source = new Blob(['webm audio'], { type: 'audio/webm;codecs=opus' });+ const decode = vi.fn().mockResolvedValue({+ getChannelData: (channel: number) =>+ channel === 0+ ? Float32Array.from([1, 1, 1, -1, -1, -1])+ : Float32Array.from([0, 0, 0, 0, 0, 0]),+ length: 6,+ numberOfChannels: 2,+ sampleRate: 48_000,+ });++ const result = await normalizeVoiceRecording(source, decode);+ const view = new DataView(await result.blob.arrayBuffer());++ expect(decode).toHaveBeenCalledWith(source);+ expect(result.mimeType).toBe('audio/wav');+ expect(result.codec).toBe('pcm_s16le');+ expect(result.blob.type).toBe('audio/wav');+ expect(readAscii(view, 0, 4)).toBe('RIFF');+ expect(readAscii(view, 8, 4)).toBe('WAVE');+ expect(view.getUint16(20, true)).toBe(1);+ expect(view.getUint16(22, true)).toBe(1);+ expect(view.getUint32(24, true)).toBe(16_000);+ expect(view.getUint16(34, true)).toBe(16);+ expect(view.getUint32(40, true)).toBe(4);+ expect(view.getInt16(44, true)).toBe(16_383);+ expect(view.getInt16(46, true)).toBe(-16_384);+ });++ it('rejects decoded audio without usable samples', async () => {+ const decode = vi.fn().mockResolvedValue({+ getChannelData: () => new Float32Array(),+ length: 0,+ numberOfChannels: 0,+ sampleRate: 0,+ });++ await expect(normalizeVoiceRecording(new Blob(['invalid']), decode)).rejects.toThrow(+ 'could not be decoded',+ );+ });+});diff --git a/src/features/ChatInput/VoiceMessage/normalizeRecording.ts b/src/features/ChatInput/VoiceMessage/normalizeRecording.tsnew file mode 100644index 00000000000..5ceaf9b54e6--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/normalizeRecording.ts@@ -0,0 +1,145 @@+const WAVE_MIME_TYPE = 'audio/wav';+const WAVE_CODEC = 'pcm_s16le';+const WAVE_SAMPLE_RATE = 16_000;+const WAVE_HEADER_SIZE = 44;++interface AudioBufferLike {+ getChannelData: (channel: number) => Float32Array;+ length: number;+ numberOfChannels: number;+ sampleRate: number;+}++interface WebkitWindow extends Window {+ webkitAudioContext?: typeof AudioContext;+}++export interface NormalizedVoiceRecording {+ blob: Blob;+ codec: string;+ mimeType: string;+}++type DecodeAudioBlob = (blob: Blob) => Promise<AudioBufferLike>;++const writeAscii = (view: DataView, offset: number, value: string) => {+ for (let index = 0; index < value.length; index += 1) {+ view.setUint8(offset + index, value.charCodeAt(index));+ }+};++export const downmixAndResample = (+ audioBuffer: AudioBufferLike,+ targetSampleRate = WAVE_SAMPLE_RATE,+): Float32Array => {+ const { length, numberOfChannels, sampleRate } = audioBuffer;+ if (length === 0 || numberOfChannels === 0 || sampleRate <= 0 || targetSampleRate <= 0) {+ throw new Error('The recorded audio could not be decoded');+ }++ const channels = Array.from({ length: numberOfChannels }, (_, channel) =>+ audioBuffer.getChannelData(channel),+ );+ const targetLength = Math.max(1, Math.round((length * targetSampleRate) / sampleRate));+ const result = new Float32Array(targetLength);+ const sourceFramesPerTargetFrame = sampleRate / targetSampleRate;++ for (let targetIndex = 0; targetIndex < targetLength; targetIndex += 1) {+ if (sourceFramesPerTargetFrame < 1) {+ const sourcePosition = targetIndex * sourceFramesPerTargetFrame;+ const lowerIndex = Math.min(length - 1, Math.floor(sourcePosition));+ const upperIndex = Math.min(length - 1, lowerIndex + 1);+ const mix = sourcePosition - lowerIndex;+ let sample = 0;++ for (const channel of channels) {+ sample += channel[lowerIndex] * (1 - mix) + channel[upperIndex] * mix;+ }++ result[targetIndex] = sample / numberOfChannels;+ continue;+ }++ const start = Math.min(length - 1, Math.floor(targetIndex * sourceFramesPerTargetFrame));+ const end = Math.max(+ start + 1,+ Math.min(length, Math.floor((targetIndex + 1) * sourceFramesPerTargetFrame)),+ );+ let sample = 0;++ for (const channel of channels) {+ for (let sourceIndex = start; sourceIndex < end; sourceIndex += 1) {+ sample += channel[sourceIndex];+ }+ }++ result[targetIndex] = sample / ((end - start) * numberOfChannels);+ }++ return result;+};++export const encodePcm16Wav = (samples: Float32Array, sampleRate = WAVE_SAMPLE_RATE): Blob => {+ const bytesPerSample = 2;+ const arrayBuffer = new ArrayBuffer(WAVE_HEADER_SIZE + samples.length * bytesPerSample);+ const view = new DataView(arrayBuffer);++ writeAscii(view, 0, 'RIFF');+ view.setUint32(4, arrayBuffer.byteLength - 8, true);+ writeAscii(view, 8, 'WAVE');+ writeAscii(view, 12, 'fmt ');+ view.setUint32(16, 16, true);+ view.setUint16(20, 1, true);+ view.setUint16(22, 1, true);+ view.setUint32(24, sampleRate, true);+ view.setUint32(28, sampleRate * bytesPerSample, true);+ view.setUint16(32, bytesPerSample, true);+ view.setUint16(34, 16, true);+ writeAscii(view, 36, 'data');+ view.setUint32(40, samples.length * bytesPerSample, true);++ for (let index = 0; index < samples.length; index += 1) {+ const finiteSample = Number.isFinite(samples[index]) ? samples[index] : 0;+ const sample = Math.max(-1, Math.min(1, finiteSample));+ view.setInt16(+ WAVE_HEADER_SIZE + index * bytesPerSample,+ sample < 0 ? sample * 0x8000 : sample * 0x7fff,+ true,+ );+ }++ return new Blob([arrayBuffer], { type: WAVE_MIME_TYPE });+};++const decodeAudioBlob: DecodeAudioBlob = async (blob) => {+ const AudioContextConstructor =+ window.AudioContext || (window as WebkitWindow).webkitAudioContext;+ if (!AudioContextConstructor) throw new Error('Web Audio is unavailable');++ const audioContext = new AudioContextConstructor();+ try {+ return await audioContext.decodeAudioData(await blob.arrayBuffer());+ } finally {+ if (audioContext.state !== 'closed') await audioContext.close();+ }+};++/**+ * MediaRecorder outputs browser-specific containers (WebM/Opus in Chrome and MP4/AAC in+ * Safari). Normalize them before upload because audio-capable model providers do not share a+ * common compressed-container contract. WAV/PCM gives provider adapters a broadly supported+ * canonical input while keeping the existing audioList path and never converting audio to text.+ */+export const normalizeVoiceRecording = async (+ blob: Blob,+ decode: DecodeAudioBlob = decodeAudioBlob,+): Promise<NormalizedVoiceRecording> => {+ const audioBuffer = await decode(blob);+ const samples = downmixAndResample(audioBuffer);++ return {+ blob: encodePcm16Wav(samples),+ codec: WAVE_CODEC,+ mimeType: WAVE_MIME_TYPE,+ };+};diff --git a/src/features/ChatInput/VoiceMessage/useIntentionalHover.test.ts b/src/features/ChatInput/VoiceMessage/useIntentionalHover.test.tsnew file mode 100644index 00000000000..1d874a1ab02--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/useIntentionalHover.test.ts@@ -0,0 +1,66 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useIntentionalHover } from './useIntentionalHover';++describe('useIntentionalHover', () => {+ beforeEach(() => {+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {+ callback(0);+ return 1;+ });+ vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('ignores inherited hover until the pointer leaves and deliberately re-enters', () => {+ const target = document.createElement('button');+ let isHovered = true;+ vi.spyOn(target, 'matches').mockImplementation(() => isHovered);++ const { result } = renderHook(() => useIntentionalHover({ current: target }));++ act(() => result.current.handlePointerEnter('mouse'));+ expect(result.current.isHoverExpanded).toBe(false);++ act(() => result.current.handlePointerLeave('mouse'));+ act(() => result.current.handlePointerEnter('mouse'));+ expect(result.current.isHoverExpanded).toBe(false);++ isHovered = false;+ act(() => result.current.handlePointerLeave('mouse'));+ isHovered = true;+ act(() => result.current.handlePointerEnter('mouse'));+ expect(result.current.isHoverExpanded).toBe(true);++ isHovered = false;+ act(() => result.current.handlePointerLeave('mouse'));+ expect(result.current.isHoverExpanded).toBe(false);+ });++ it('expands on the first deliberate hover when mounted away from the pointer', () => {+ const target = document.createElement('button');+ vi.spyOn(target, 'matches').mockReturnValue(false);++ const { result } = renderHook(() => useIntentionalHover({ current: target }));++ act(() => result.current.handlePointerEnter('mouse'));++ expect(result.current.isHoverExpanded).toBe(true);+ });++ it('does not arm or expand from touch pointer events', () => {+ const target = document.createElement('button');+ vi.spyOn(target, 'matches').mockReturnValue(true);++ const { result } = renderHook(() => useIntentionalHover({ current: target }));++ act(() => result.current.handlePointerLeave('touch'));+ act(() => result.current.handlePointerEnter('touch'));++ expect(result.current.isHoverExpanded).toBe(false);+ });+});diff --git a/src/features/ChatInput/VoiceMessage/useIntentionalHover.ts b/src/features/ChatInput/VoiceMessage/useIntentionalHover.tsnew file mode 100644index 00000000000..ea2ca59a0b4--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/useIntentionalHover.ts@@ -0,0 +1,40 @@+import { type RefObject, useCallback, useEffect, useRef, useState } from 'react';++export const useIntentionalHover = <T extends HTMLElement>(targetRef: RefObject<T | null>) => {+ const hoverArmedRef = useRef(false);+ const [isHoverExpanded, setIsHoverExpanded] = useState(false);++ useEffect(() => {+ const animationFrame = window.requestAnimationFrame(() => {+ const target = targetRef.current;+ if (!target) return;++ hoverArmedRef.current = !target.matches(':hover');+ });++ return () => window.cancelAnimationFrame(animationFrame);+ }, [targetRef]);++ const handlePointerEnter = useCallback((pointerType: string) => {+ if (pointerType !== 'touch' && hoverArmedRef.current) {+ setIsHoverExpanded(true);+ }+ }, []);++ const handlePointerLeave = useCallback(+ (pointerType: string) => {+ if (pointerType === 'touch') return;+ if (targetRef.current?.matches(':hover')) return;++ hoverArmedRef.current = true;+ setIsHoverExpanded(false);+ },+ [targetRef],+ );++ return {+ handlePointerEnter,+ handlePointerLeave,+ isHoverExpanded,+ };+};diff --git a/src/features/ChatInput/VoiceMessage/useVoiceMessageCapability.test.ts b/src/features/ChatInput/VoiceMessage/useVoiceMessageCapability.test.tsnew file mode 100644index 00000000000..f54e7bb9def--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/useVoiceMessageCapability.test.ts@@ -0,0 +1,215 @@+import { renderHook } from '@testing-library/react';+import { ModelProvider } from 'model-bank/modelProvider';+import { afterEach, describe, expect, it } from 'vitest';++import { useAiInfraStore } from '@/store/aiInfra';++import {+ getVoiceMessageActionState,+ supportsRawAudioMessage,+ useVoiceMessageCapability,+} from './useVoiceMessageCapability';++const initialStoreState = useAiInfraStore.getState();++const audioModel = (id: string, providerId: string) =>+ ({+ abilities: { audio: true },+ enabled: true,+ id,+ providerId,+ type: 'chat',+ }) as const;++describe('supportsRawAudioMessage', () => {+ it.each([+ [ModelProvider.Google, ModelProvider.Google],+ [ModelProvider.OpenAI, ModelProvider.OpenAI],+ [ModelProvider.VertexAI, ModelProvider.VertexAI],+ ])('enables a model on the supported %s runtime', (provider, runtimeProvider) => {+ expect(+ supportsRawAudioMessage({+ isCuratedModel: false,+ modelSupportsAudio: true,+ provider,+ runtimeProvider,+ }),+ ).toBe(true);+ });++ it.each([ModelProvider.AiHubMix, ModelProvider.LobeHub])(+ 'enables curated audio models on the %s router',+ (provider) => {+ expect(+ supportsRawAudioMessage({+ isCuratedModel: true,+ modelSupportsAudio: true,+ provider,+ runtimeProvider: provider,+ }),+ ).toBe(true);+ },+ );++ it('fails closed for a router model that is not in the curated audio model list', () => {+ expect(+ supportsRawAudioMessage({+ isCuratedModel: false,+ modelSupportsAudio: true,+ provider: ModelProvider.AiHubMix,+ runtimeProvider: ModelProvider.AiHubMix,+ }),+ ).toBe(false);+ });++ it('fails closed for an unsupported runtime even when the model claims audio support', () => {+ expect(+ supportsRawAudioMessage({+ isCuratedModel: false,+ modelSupportsAudio: true,+ provider: ModelProvider.Anthropic,+ runtimeProvider: ModelProvider.Anthropic,+ }),+ ).toBe(false);+ });++ it('requires the selected model to declare audio support', () => {+ expect(+ supportsRawAudioMessage({+ isCuratedModel: true,+ modelSupportsAudio: false,+ provider: ModelProvider.Google,+ runtimeProvider: ModelProvider.Google,+ }),+ ).toBe(false);+ });+});++describe('useVoiceMessageCapability', () => {+ afterEach(() => {+ useAiInfraStore.setState(initialStoreState, true);+ });++ it('uses a custom provider OpenAI runtime only when its model declares audio support', () => {+ const model = audioModel('custom-audio', 'custom-provider');+ useAiInfraStore.setState({+ aiProviderRuntimeConfig: {+ 'custom-provider': {+ config: {},+ keyVaults: {},+ settings: { sdkType: 'openai' },+ },+ },+ enabledAiModels: [model],+ });++ const { result } = renderHook(() =>+ useVoiceMessageCapability('custom-audio', 'custom-provider'),+ );++ expect(result.current).toBe(true);+ });++ it('disables a custom provider whose runtime has no raw-audio adapter', () => {+ const model = audioModel('custom-audio', 'custom-provider');+ useAiInfraStore.setState({+ aiProviderRuntimeConfig: {+ 'custom-provider': {+ config: {},+ keyVaults: {},+ settings: { sdkType: 'anthropic' },+ },+ },+ enabledAiModels: [model],+ });++ const { result } = renderHook(() =>+ useVoiceMessageCapability('custom-audio', 'custom-provider'),+ );++ expect(result.current).toBe(false);+ });++ it('requires a router audio model to match the curated model card', () => {+ const model = audioModel('gemini-audio', ModelProvider.AiHubMix);+ useAiInfraStore.setState({+ builtinAiModelList: [model],+ enabledAiModels: [model],+ });++ const { result } = renderHook(() =>+ useVoiceMessageCapability('gemini-audio', ModelProvider.AiHubMix),+ );++ expect(result.current).toBe(true);+ });++ it('does not require the curated LobeHub card to duplicate the runtime audio capability', () => {+ const id = 'gemini-3.5-flash';+ const curatedModel = {+ abilities: { functionCall: true },+ enabled: true,+ id,+ providerId: ModelProvider.LobeHub,+ type: 'chat',+ } as const;+ useAiInfraStore.setState({+ builtinAiModelList: [curatedModel],+ enabledAiModels: [audioModel(id, ModelProvider.LobeHub)],+ });++ const { result } = renderHook(() => useVoiceMessageCapability(id, ModelProvider.LobeHub));++ expect(result.current).toBe(true);+ });++ it('keeps a curated LobeHub model disabled when runtime audio support is absent', () => {+ const model = {+ abilities: { functionCall: true },+ enabled: true,+ id: 'text-only-model',+ providerId: ModelProvider.LobeHub,+ type: 'chat',+ } as const;+ useAiInfraStore.setState({+ builtinAiModelList: [model],+ enabledAiModels: [model],+ });++ const { result } = renderHook(() =>+ useVoiceMessageCapability('text-only-model', ModelProvider.LobeHub),+ );++ expect(result.current).toBe(false);+ });+});++describe('getVoiceMessageActionState', () => {+ it('disables send and retry if the active model stops supporting audio', () => {+ expect(+ getVoiceMessageActionState({+ canRecordVoiceMessage: false,+ canSendRecording: true,+ hasRecoverableError: true,+ }),+ ).toEqual({+ canSend: false,+ sendDisabled: true,+ showRetry: false,+ });+ });++ it('restores the available action after switching back to an audio model', () => {+ expect(+ getVoiceMessageActionState({+ canRecordVoiceMessage: true,+ canSendRecording: false,+ hasRecoverableError: true,+ }),+ ).toEqual({+ canSend: false,+ sendDisabled: false,+ showRetry: true,+ });+ });+});diff --git a/src/features/ChatInput/VoiceMessage/useVoiceMessageCapability.ts b/src/features/ChatInput/VoiceMessage/useVoiceMessageCapability.tsnew file mode 100644index 00000000000..c23e85cc128--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/useVoiceMessageCapability.ts@@ -0,0 +1,83 @@+import { ModelProvider } from 'model-bank/modelProvider';++import { getAiInfraStoreState, useAiInfraStore } from '@/store/aiInfra';+import { aiModelSelectors, aiProviderSelectors } from '@/store/aiInfra/selectors';+import type { AiInfraStore } from '@/store/aiInfra/store';++interface VoiceMessageActionStateInput {+ canRecordVoiceMessage: boolean;+ canSendRecording: boolean;+ hasRecoverableError: boolean;+}++export const getVoiceMessageActionState = ({+ canRecordVoiceMessage,+ canSendRecording,+ hasRecoverableError,+}: VoiceMessageActionStateInput) => {+ const canSend = canRecordVoiceMessage && canSendRecording;+ const showRetry = canRecordVoiceMessage && hasRecoverableError;++ return {+ canSend,+ sendDisabled: !showRetry && !canSend,+ showRetry,+ };+};++interface RawAudioCapabilityInput {+ isCuratedModel: boolean;+ modelSupportsAudio: boolean;+ provider: string;+ runtimeProvider: string;+}++const DIRECT_AUDIO_RUNTIMES = new Set<string>([+ ModelProvider.Google,+ ModelProvider.OpenAI,+ ModelProvider.VertexAI,+]);++const CURATED_AUDIO_ROUTERS = new Set<string>([ModelProvider.AiHubMix, ModelProvider.LobeHub]);++export const supportsRawAudioMessage = ({+ isCuratedModel,+ modelSupportsAudio,+ provider,+ runtimeProvider,+}: RawAudioCapabilityInput) => {+ if (!modelSupportsAudio) return false;++ return (+ DIRECT_AUDIO_RUNTIMES.has(runtimeProvider) ||+ (isCuratedModel && CURATED_AUDIO_ROUTERS.has(provider))+ );+};++export const getVoiceMessageCapability = (+ model?: string,+ provider?: string,+ state: AiInfraStore = getAiInfraStoreState(),+) => {+ if (!model || !provider) return false;++ const modelSupportsAudio = aiModelSelectors.isModelSupportAudio(model, provider)(state);+ const isCuratedModel = state.builtinAiModelList.some(+ (item) => item.id === model && item.providerId === provider,+ );+ const isBuiltinProvider = Object.values(ModelProvider).includes(provider as ModelProvider);+ const runtimeProvider = isBuiltinProvider+ ? provider+ : aiProviderSelectors.providerConfigById(provider)(state)?.settings.sdkType ||+ ModelProvider.OpenAI;++ return supportsRawAudioMessage({+ isCuratedModel,+ modelSupportsAudio,+ provider,+ runtimeProvider,+ });+};++export const useVoiceMessageCapability = (model?: string, provider?: string) =>+ useAiInfraStore((state) => getVoiceMessageCapability(model, provider, state));diff --git a/src/features/ChatInput/VoiceMessage/useVoiceMessageRecorder.test.ts b/src/features/ChatInput/VoiceMessage/useVoiceMessageRecorder.test.tsnew file mode 100644index 00000000000..dacee6994f6--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/useVoiceMessageRecorder.test.ts@@ -0,0 +1,375 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ calculateWaveformLevel,+ createWaveformSamples,+ useVoiceMessageRecorder,+} from './useVoiceMessageRecorder';++class FakeMediaRecorder extends EventTarget {+ static deferStopEvent = false;+ static isTypeSupported = vi.fn((mimeType: string) => mimeType === 'audio/webm;codecs=opus');+ static latest: FakeMediaRecorder | undefined;++ mimeType: string;+ state: RecordingState = 'inactive';++ constructor(+ public stream: MediaStream,+ options?: MediaRecorderOptions,+ ) {+ super();+ this.mimeType = options?.mimeType ?? 'audio/webm';+ FakeMediaRecorder.latest = this;+ }++ fail(error: unknown = new DOMException('encoder failed', 'UnknownError')) {+ this.state = 'inactive';+ const errorEvent = new Event('error') as Event & { error: unknown };+ errorEvent.error = error;+ this.dispatchEvent(errorEvent);++ const dataEvent = new Event('dataavailable') as Event & { data: Blob };+ dataEvent.data = new Blob(['partial audio'], { type: this.mimeType });+ this.dispatchEvent(dataEvent);+ this.dispatchEvent(new Event('stop'));+ }++ start() {+ this.state = 'recording';+ }++ completeStop() {+ const dataEvent = new Event('dataavailable') as Event & { data: Blob };+ dataEvent.data = new Blob(['recorded audio'], { type: this.mimeType });+ this.dispatchEvent(dataEvent);+ this.dispatchEvent(new Event('stop'));+ }++ stop() {+ this.state = 'inactive';+ if (!FakeMediaRecorder.deferStopEvent) this.completeStop();+ }+}++describe('useVoiceMessageRecorder', () => {+ const trackStop = vi.fn();+ let now = 0;++ beforeEach(() => {+ FakeMediaRecorder.deferStopEvent = false;+ FakeMediaRecorder.latest = undefined;+ vi.stubGlobal('MediaRecorder', FakeMediaRecorder);+ Object.defineProperty(navigator, 'mediaDevices', {+ configurable: true,+ value: {+ getUserMedia: vi.fn().mockResolvedValue({+ getTracks: () => [{ stop: trackStop }],+ }),+ },+ });+ now = 0;+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it('creates a binary audio File with duration and codec metadata', async () => {+ const normalizeRecording = vi.fn().mockResolvedValue({+ blob: new Blob(['wav audio'], { type: 'audio/wav' }),+ codec: 'pcm_s16le',+ mimeType: 'audio/wav',+ });+ const { result } = renderHook(() =>+ useVoiceMessageRecorder({ normalizeRecording, now: () => now }),+ );++ await act(async () => {+ await result.current.start();+ });+ expect(result.current.status).toBe('recording');++ now = 1_250;+ let recording: Awaited<ReturnType<typeof result.current.stop>>;+ await act(async () => {+ recording = await result.current.stop();+ });++ expect(normalizeRecording).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'audio/webm;codecs=opus' }),+ );+ expect(recording?.file).toBeInstanceOf(File);+ expect(recording?.file.type).toBe('audio/wav');+ expect(recording?.file.name).toMatch(/\.wav$/);+ expect(recording?.durationMs).toBe(1250);+ expect(recording?.codec).toBe('pcm_s16le');+ expect(result.current.status).toBe('ready');+ expect(trackStop).toHaveBeenCalledOnce();+ });++ it('surfaces a recoverable error when the recorded container cannot be normalized', async () => {+ const normalizeRecording = vi.fn().mockRejectedValue(new Error('decode failed'));+ const { result } = renderHook(() =>+ useVoiceMessageRecorder({ normalizeRecording, now: () => now }),+ );++ await act(async () => {+ await result.current.start();+ });+ now = 1_250;+ await act(async () => {+ await result.current.stop();+ });++ expect(result.current.status).toBe('error');+ expect(result.current.error).toBe('recording_failed');+ expect(result.current.recording).toBeUndefined();+ });++ it('keeps a new recording intact when a cancelled normalization finishes late', async () => {+ let finishNormalization:+ ((value: { blob: Blob; codec: string; mimeType: string }) => void) | undefined;+ const normalizedRecording = {+ blob: new Blob(['wav audio'], { type: 'audio/wav' }),+ codec: 'pcm_s16le',+ mimeType: 'audio/wav',+ };+ const normalizeRecording = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise<{ blob: Blob; codec: string; mimeType: string }>((resolve) => {+ finishNormalization = resolve;+ }),+ )+ .mockResolvedValue(normalizedRecording);+ const { result } = renderHook(() =>+ useVoiceMessageRecorder({ normalizeRecording, now: () => now }),+ );++ await act(async () => {+ await result.current.start();+ });+ now = 1_250;+ act(() => {+ void result.current.stop();+ });+ act(() => result.current.cancel());+ await act(async () => {+ await result.current.start();+ });+ finishNormalization?.(normalizedRecording);+ await act(async () => {+ await Promise.resolve();+ });++ expect(result.current.status).toBe('recording');+ now = 2_500;+ let secondRecording: Awaited<ReturnType<typeof result.current.stop>>;+ await act(async () => {+ secondRecording = await result.current.stop();+ });++ expect(secondRecording?.file.type).toBe('audio/wav');+ expect(result.current.status).toBe('ready');+ });++ it('advances the visible waveform when the analyser receives audible samples', async () => {+ let animationFrame: FrameRequestCallback | undefined;+ const source = {+ connect: vi.fn(),+ disconnect: vi.fn(),+ };+ const analyser = {+ fftSize: 2048,+ getByteTimeDomainData: vi.fn((samples: Uint8Array) => {+ samples.forEach((_, index) => {+ samples[index] = index % 2 === 0 ? 96 : 160;+ });+ }),+ smoothingTimeConstant: 0,+ };++ vi.stubGlobal(+ 'AudioContext',+ class {+ close = vi.fn().mockResolvedValue(undefined);+ createAnalyser = vi.fn(() => analyser);+ createMediaStreamSource = vi.fn(() => source);+ state: AudioContextState = 'running';+ },+ );+ vi.stubGlobal(+ 'requestAnimationFrame',+ vi.fn((callback: FrameRequestCallback) => {+ animationFrame = callback;+ return 1;+ }),+ );+ vi.stubGlobal('cancelAnimationFrame', vi.fn());++ const { result } = renderHook(() => useVoiceMessageRecorder({ now: () => now }));++ await act(async () => {+ await result.current.start();+ });+ act(() => animationFrame?.(100));++ expect(analyser.fftSize).toBe(64);+ expect(result.current.waveform.at(-1)).toBeGreaterThan(0.5);+ expect(result.current.waveform.at(-2)).toBe(0.12);++ act(() => result.current.cancel());+ });++ it('returns to idle and discards captured data when cancelled', async () => {+ const { result } = renderHook(() => useVoiceMessageRecorder({ now: () => now }));++ await act(async () => {+ await result.current.start();+ });+ act(() => result.current.cancel());++ expect(result.current.status).toBe('idle');+ expect(result.current.recording).toBeUndefined();+ expect(trackStop).toHaveBeenCalledOnce();+ });++ it('ignores a cancelled recorder stop event after a new recording starts', async () => {+ const normalizedRecording = {+ blob: new Blob(['wav audio'], { type: 'audio/wav' }),+ codec: 'pcm_s16le',+ mimeType: 'audio/wav',+ };+ const { result } = renderHook(() =>+ useVoiceMessageRecorder({+ normalizeRecording: vi.fn().mockResolvedValue(normalizedRecording),+ now: () => now,+ }),+ );++ FakeMediaRecorder.deferStopEvent = true;+ await act(async () => {+ await result.current.start();+ });+ const cancelledRecorder = FakeMediaRecorder.latest;+ act(() => result.current.cancel());++ FakeMediaRecorder.deferStopEvent = false;+ await act(async () => {+ await result.current.start();+ });+ act(() => cancelledRecorder?.completeStop());++ expect(result.current.status).toBe('recording');+ now = 1_250;+ await act(async () => {+ await result.current.stop();+ });+ expect(result.current.status).toBe('ready');+ });++ it('does not tear down a new recording when an older permission request rejects late', async () => {+ let rejectFirstRequest: ((reason?: unknown) => void) | undefined;+ const firstRequest = new Promise<MediaStream>((_, reject) => {+ rejectFirstRequest = reject;+ });+ const secondTrackStop = vi.fn();+ vi.mocked(navigator.mediaDevices.getUserMedia)+ .mockReturnValueOnce(firstRequest)+ .mockResolvedValueOnce({+ getTracks: () => [{ stop: secondTrackStop }],+ } as unknown as MediaStream);+ const normalizedRecording = {+ blob: new Blob(['wav audio'], { type: 'audio/wav' }),+ codec: 'pcm_s16le',+ mimeType: 'audio/wav',+ };+ const { result } = renderHook(() =>+ useVoiceMessageRecorder({+ normalizeRecording: vi.fn().mockResolvedValue(normalizedRecording),+ now: () => now,+ }),+ );++ let firstStart: Promise<void>;+ act(() => {+ firstStart = result.current.start();+ });+ act(() => result.current.cancel());+ await act(async () => {+ await result.current.start();+ });++ await act(async () => {+ rejectFirstRequest?.(new DOMException('late denial', 'NotAllowedError'));+ await firstStart;+ });++ expect(result.current.status).toBe('recording');+ expect(secondTrackStop).not.toHaveBeenCalled();++ now = 1_250;+ let recording: Awaited<ReturnType<typeof result.current.stop>>;+ await act(async () => {+ recording = await result.current.stop();+ });++ expect(recording?.file.type).toBe('audio/wav');+ expect(secondTrackStop).toHaveBeenCalledOnce();+ });++ it('surfaces a recoverable permission-denied state', async () => {+ vi.mocked(navigator.mediaDevices.getUserMedia).mockRejectedValueOnce(+ new DOMException('denied', 'NotAllowedError'),+ );+ const { result } = renderHook(() => useVoiceMessageRecorder());++ await act(async () => {+ await result.current.start();+ });++ expect(result.current.status).toBe('error');+ expect(result.current.error).toBe('permission_denied');+ expect(result.current.recording).toBeUndefined();+ });++ it('keeps an encoder error after the final data and stop events', async () => {+ const { result } = renderHook(() => useVoiceMessageRecorder({ now: () => now }));++ await act(async () => {+ await result.current.start();+ });+ act(() => FakeMediaRecorder.latest?.fail());++ expect(result.current.status).toBe('error');+ expect(result.current.error).toBe('recording_failed');+ expect(result.current.recording).toBeUndefined();+ });+});++describe('voice message waveform analysis', () => {+ it('configures the analyser before allocating an exact time-domain sample buffer', () => {+ const analyser = {+ fftSize: 2048,+ smoothingTimeConstant: 0,+ };++ const samples = createWaveformSamples(analyser);++ expect(analyser.fftSize).toBe(64);+ expect(analyser.smoothingTimeConstant).toBe(0.7);+ expect(samples).toHaveLength(64);+ });++ it('keeps silence low while mapping audible energy to a visibly taller level', () => {+ const silence = new Uint8Array(64).fill(128);+ const audible = Uint8Array.from({ length: 64 }, (_, index) => (index % 2 === 0 ? 96 : 160));++ expect(calculateWaveformLevel(silence)).toBe(0.08);+ expect(calculateWaveformLevel(audible)).toBeGreaterThan(0.5);+ });+});diff --git a/src/features/ChatInput/VoiceMessage/useVoiceMessageRecorder.ts b/src/features/ChatInput/VoiceMessage/useVoiceMessageRecorder.tsnew file mode 100644index 00000000000..f3dbe67bf89--- /dev/null+++ b/src/features/ChatInput/VoiceMessage/useVoiceMessageRecorder.ts@@ -0,0 +1,406 @@+'use client';++import { type VoiceMessageRecording } from '@lobechat/types';+import { useCallback, useEffect, useRef, useState } from 'react';++import {+ getAudioFileExtension,+ getVoiceRecorderErrorCode,+ resolveRecordingMimeType,+ selectRecordingMimeType,+ VOICE_MESSAGE_MAX_DURATION_MS,+ VOICE_MESSAGE_MIN_DURATION_MS,+ type VoiceRecorderErrorCode,+} from './mediaRecorder';+import { type NormalizedVoiceRecording, normalizeVoiceRecording } from './normalizeRecording';++const WAVEFORM_BAR_COUNT = 28;+const WAVEFORM_FFT_SIZE = 64;+const WAVEFORM_MIN_LEVEL = 0.08;+const WAVEFORM_UPDATE_INTERVAL_MS = 80;+const TIMER_INTERVAL_MS = 100;+const DATA_SLICE_MS = 250;++const initialWaveform = () => Array.from({ length: WAVEFORM_BAR_COUNT }, () => 0.12);++export const createWaveformSamples = (+ analyser: Pick<AnalyserNode, 'fftSize' | 'smoothingTimeConstant'>,+) => {+ analyser.fftSize = WAVEFORM_FFT_SIZE;+ analyser.smoothingTimeConstant = 0.7;++ return new Uint8Array(analyser.fftSize);+};++export const calculateWaveformLevel = (samples: Uint8Array) => {+ if (samples.length === 0) return WAVEFORM_MIN_LEVEL;++ let energy = 0;+ for (const value of samples) {+ const normalized = (value - 128) / 128;+ energy += normalized * normalized;+ }++ const rms = Math.sqrt(energy / samples.length);+ return Math.min(1, Math.max(WAVEFORM_MIN_LEVEL, rms * 2.5));+};++type RecorderStatus = 'idle' | 'requesting' | 'recording' | 'stopping' | 'ready' | 'error';++interface VoiceMessageRecorderOptions {+ maxDurationMs?: number;+ minDurationMs?: number;+ normalizeRecording?: (blob: Blob) => Promise<NormalizedVoiceRecording>;+ now?: () => number;+}++interface WebkitWindow extends Window {+ webkitAudioContext?: typeof AudioContext;+}++const stopStream = (stream?: MediaStream) => {+ for (const track of stream?.getTracks() ?? []) track.stop();+};++export const useVoiceMessageRecorder = ({+ maxDurationMs = VOICE_MESSAGE_MAX_DURATION_MS,+ minDurationMs = VOICE_MESSAGE_MIN_DURATION_MS,+ normalizeRecording = normalizeVoiceRecording,+ now = Date.now,+}: VoiceMessageRecorderOptions = {}) => {+ const [durationMs, setDurationMs] = useState(0);+ const [error, setError] = useState<VoiceRecorderErrorCode>();+ const [recording, setRecording] = useState<VoiceMessageRecording>();+ const [status, setStatus] = useState<RecorderStatus>('idle');+ const [waveform, setWaveform] = useState<number[]>(initialWaveform);++ const analyserFrameRef = useRef<number | undefined>(undefined);+ const audioContextRef = useRef<AudioContext | undefined>(undefined);+ const intervalRef = useRef<ReturnType<typeof setInterval> | undefined>(undefined);+ const lastWaveformUpdateRef = useRef(0);+ const mountedRef = useRef(true);+ const recorderRef = useRef<MediaRecorder | undefined>(undefined);+ const recordingRef = useRef<VoiceMessageRecording | undefined>(undefined);+ const requestIdRef = useRef(0);+ const sourceRef = useRef<MediaStreamAudioSourceNode | undefined>(undefined);+ const startedAtRef = useRef(0);+ const stopPromiseRef = useRef<Promise<VoiceMessageRecording | undefined> | undefined>(undefined);+ const stopRequestIdRef = useRef<number | undefined>(undefined);+ const stopResolveRef = useRef<((recording?: VoiceMessageRecording) => void) | undefined>(+ undefined,+ );+ const streamRef = useRef<MediaStream | undefined>(undefined);+ const wasCancelledRef = useRef(false);+ const waveformRef = useRef(waveform);++ waveformRef.current = waveform;++ const cleanupCapture = useCallback(() => {+ if (intervalRef.current) clearInterval(intervalRef.current);+ intervalRef.current = undefined;++ if (analyserFrameRef.current !== undefined) {+ cancelAnimationFrame(analyserFrameRef.current);+ analyserFrameRef.current = undefined;+ }++ sourceRef.current?.disconnect();+ sourceRef.current = undefined;++ const audioContext = audioContextRef.current;+ audioContextRef.current = undefined;+ if (audioContext && audioContext.state !== 'closed') void audioContext.close();++ stopStream(streamRef.current);+ streamRef.current = undefined;+ }, []);++ const settleStopPromise = useCallback((value?: VoiceMessageRecording, requestId?: number) => {+ if (requestId !== undefined && stopRequestIdRef.current !== requestId) return;++ stopResolveRef.current?.(value);+ stopResolveRef.current = undefined;+ stopPromiseRef.current = undefined;+ stopRequestIdRef.current = undefined;+ }, []);++ const reset = useCallback(() => {+ requestIdRef.current += 1;+ wasCancelledRef.current = true;++ const recorder = recorderRef.current;+ recorderRef.current = undefined;+ if (recorder && recorder.state !== 'inactive') recorder.stop();++ cleanupCapture();+ recordingRef.current = undefined;+ settleStopPromise();++ if (mountedRef.current) {+ setDurationMs(0);+ setError(undefined);+ setRecording(undefined);+ setStatus('idle');+ setWaveform(initialWaveform());+ }+ }, [cleanupCapture, settleStopPromise]);++ const setupWaveform = useCallback((stream: MediaStream) => {+ const AudioContextConstructor =+ window.AudioContext || (window as WebkitWindow).webkitAudioContext;+ if (!AudioContextConstructor) return;++ try {+ const audioContext = audioContextRef.current ?? new AudioContextConstructor();+ const analyser = audioContext.createAnalyser();+ const source = audioContext.createMediaStreamSource(stream);+ const samples = createWaveformSamples(analyser);++ source.connect(analyser);++ audioContextRef.current = audioContext;+ sourceRef.current = source;+ if (audioContext.state === 'suspended') void audioContext.resume().catch(() => {});++ const sample = (timestamp: number) => {+ analyserFrameRef.current = requestAnimationFrame(sample);+ if (timestamp - lastWaveformUpdateRef.current < WAVEFORM_UPDATE_INTERVAL_MS) return;+ lastWaveformUpdateRef.current = timestamp;++ analyser.getByteTimeDomainData(samples);+ const level = calculateWaveformLevel(samples);+ setWaveform((current) => [...current.slice(1), level]);+ };++ analyserFrameRef.current = requestAnimationFrame(sample);+ } catch {+ // Recording still works without Web Audio visualization.+ }+ }, []);++ const start = useCallback(async () => {+ if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {+ setError('not_supported');+ setStatus('error');+ return;+ }+ if (typeof MediaRecorder === 'undefined') {+ setError('not_supported');+ setStatus('error');+ return;+ }++ const requestId = requestIdRef.current + 1;+ requestIdRef.current = requestId;+ wasCancelledRef.current = false;+ setDurationMs(0);+ setError(undefined);+ setRecording(undefined);+ setStatus('requesting');+ setWaveform(initialWaveform());++ let stream: MediaStream | undefined;++ try {+ const AudioContextConstructor =+ window.AudioContext || (window as WebkitWindow).webkitAudioContext;+ if (AudioContextConstructor) {+ try {+ const audioContext = new AudioContextConstructor();+ audioContextRef.current = audioContext;+ if (audioContext.state === 'suspended') void audioContext.resume().catch(() => {});+ } catch {+ // Recording still works when Web Audio visualization is unavailable.+ }+ }++ stream = await navigator.mediaDevices.getUserMedia({+ audio: {+ echoCancellation: true,+ noiseSuppression: true,+ },+ });++ if (requestIdRef.current !== requestId || wasCancelledRef.current) {+ stopStream(stream);+ return;+ }++ const requestedMimeType = selectRecordingMimeType(MediaRecorder);+ const recorder = requestedMimeType+ ? new MediaRecorder(stream, { mimeType: requestedMimeType })+ : new MediaRecorder(stream);++ const chunks: Blob[] = [];+ let recorderFailed = false;+ recorderRef.current = recorder;+ streamRef.current = stream;+ startedAtRef.current = now();+ stopPromiseRef.current = new Promise((resolve) => {+ stopResolveRef.current = resolve;+ });+ stopRequestIdRef.current = requestId;++ recorder.addEventListener('dataavailable', (event) => {+ if (event.data.size > 0) chunks.push(event.data);+ });+ recorder.addEventListener('error', (event) => {+ if (requestIdRef.current !== requestId) return;++ recorderFailed = true;+ cleanupCapture();+ recorderRef.current = undefined;+ settleStopPromise(undefined, requestId);+ if (!mountedRef.current || wasCancelledRef.current) return;++ setError(getVoiceRecorderErrorCode((event as Event & { error?: unknown }).error));+ setStatus('error');+ });+ recorder.addEventListener('stop', async () => {+ if (requestIdRef.current !== requestId) {+ settleStopPromise(undefined, requestId);+ return;+ }++ cleanupCapture();+ recorderRef.current = undefined;++ if (wasCancelledRef.current || recorderFailed) {+ settleStopPromise(undefined, requestId);+ return;+ }++ const finalDurationMs = Math.min(maxDurationMs, Math.max(0, now() - startedAtRef.current));+ const mimeType = resolveRecordingMimeType(recorder.mimeType, chunks, requestedMimeType);+ const blob = new Blob(chunks, { type: mimeType });++ if (blob.size === 0) {+ settleStopPromise(undefined, requestId);+ if (requestIdRef.current === requestId && mountedRef.current) {+ setError('recording_failed');+ setStatus('error');+ }+ return;+ }++ let normalizedRecording: NormalizedVoiceRecording;+ try {+ normalizedRecording = await normalizeRecording(blob);+ } catch {+ settleStopPromise(undefined, requestId);+ if (+ requestIdRef.current === requestId &&+ mountedRef.current &&+ !wasCancelledRef.current+ ) {+ setError('recording_failed');+ setStatus('error');+ }+ return;+ }++ if (requestIdRef.current !== requestId || wasCancelledRef.current || recorderFailed) {+ settleStopPromise(undefined, requestId);+ return;+ }++ const file = new File(+ [normalizedRecording.blob],+ `voice-message-${now()}.${getAudioFileExtension(normalizedRecording.mimeType)}`,+ { type: normalizedRecording.mimeType },+ );+ const nextRecording: VoiceMessageRecording = {+ codec: normalizedRecording.codec,+ durationMs: finalDurationMs,+ file,+ mimeType: normalizedRecording.mimeType,+ waveform: waveformRef.current,+ };++ recordingRef.current = nextRecording;+ settleStopPromise(nextRecording, requestId);+ if (mountedRef.current) {+ setDurationMs(finalDurationMs);+ setRecording(nextRecording);+ setStatus('ready');+ }+ });++ recorder.start(DATA_SLICE_MS);+ setupWaveform(stream);+ setStatus('recording');++ intervalRef.current = setInterval(() => {+ const elapsed = Math.min(maxDurationMs, Math.max(0, now() - startedAtRef.current));+ if (mountedRef.current) setDurationMs(elapsed);++ if (elapsed >= maxDurationMs && recorder.state === 'recording') {+ if (mountedRef.current) setStatus('stopping');+ recorder.stop();+ }+ }, TIMER_INTERVAL_MS);+ } catch (cause) {+ stopStream(stream);+ if (requestIdRef.current !== requestId) return;++ cleanupCapture();+ recorderRef.current = undefined;+ settleStopPromise(undefined, requestId);+ if (!mountedRef.current) return;++ setError(getVoiceRecorderErrorCode(cause));+ setStatus('error');+ }+ }, [cleanupCapture, maxDurationMs, normalizeRecording, now, settleStopPromise, setupWaveform]);++ const stop = useCallback(async (): Promise<VoiceMessageRecording | undefined> => {+ if (recordingRef.current) return recordingRef.current;++ const recorder = recorderRef.current;+ const promise = stopPromiseRef.current;+ if (!recorder || !promise) return;++ if (recorder.state === 'recording') {+ setStatus('stopping');+ recorder.stop();+ }++ return promise;+ }, []);++ const cancel = useCallback(() => {+ reset();+ }, [reset]);++ useEffect(() => {+ mountedRef.current = true;++ return () => {+ mountedRef.current = false;+ requestIdRef.current += 1;+ wasCancelledRef.current = true;++ const recorder = recorderRef.current;+ recorderRef.current = undefined;+ if (recorder && recorder.state !== 'inactive') recorder.stop();++ cleanupCapture();+ settleStopPromise();+ };+ }, [cleanupCapture, settleStopPromise]);++ return {+ cancel,+ canSend: durationMs >= minDurationMs && (status === 'recording' || status === 'ready'),+ durationMs,+ error,+ maxDurationMs,+ minDurationMs,+ recording,+ reset,+ start,+ status,+ stop,+ waveform,+ };+};diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.tsindex 61f363f3491..53a449876ab 100644--- a/src/features/ChatInput/store/action.ts+++ b/src/features/ChatInput/store/action.ts@@ -18,6 +18,7 @@ export interface Action {handleSendButton: () => void;handleStop: () => void;pauseInputCompletion: (error: State['inputCompletionError']) => void;+ setActiveAudioInputMode: (mode?: State['activeAudioInputMode']) => void;setDocument: (type: string, content: any, options?: Record<string, unknown>) => void;setExpand: (expend: boolean) => void;setGoalMode: (enabled: boolean) => void;@@ -130,6 +131,10 @@ export const store: CreateStore = (publicState) => (set, get) => ({set({ inputCompletionError, inputCompletionErrorDismissed: false });},+ setActiveAudioInputMode: (activeAudioInputMode) => {+ set({ activeAudioInputMode });+ },+setDocument: (type, content, options) => {get().editor?.setDocument(type, content, options);},diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.tsindex a12089d5dc1..1cc95afbf04 100644--- a/src/features/ChatInput/store/initialState.ts+++ b/src/features/ChatInput/store/initialState.ts@@ -1,4 +1,4 @@-import { type OpenAIChatMessage } from '@lobechat/types';+import { type OpenAIChatMessage, type VoiceMessageRecording } from '@lobechat/types';import { type IEditor, type SlashOptions } from '@lobehub/editor';import { type ChatInputProps } from '@lobehub/editor/react';import { type MenuProps } from '@lobehub/ui';@@ -12,6 +12,8 @@ export type SendButtonHandler = (params: {getMarkdownContent: () => string;}) => Promise<void> | void;+export type VoiceMessageSendHandler = (recording: VoiceMessageRecording) => boolean;+export interface SendButtonProps {disabled?: boolean;generating: boolean;@@ -54,8 +56,10 @@ export const DEFAULT_CHAT_INPUT_FEATURE = {} as const satisfies Required<ChatInputFeature>;export interface PublicState {+ activeAudioInputMode?: 'dictation' | 'voiceMessage';agentId?: string;allowExpand?: boolean;+ canRecordVoiceMessage?: boolean;contextSelectionKey?: string;contextWindowMessages?: ContextWindowMessage[];draftKey?: string;@@ -67,6 +71,7 @@ export interface PublicState {mobile?: boolean;onMarkdownContentChange?: (content: string) => void;onSend?: SendButtonHandler;+ onVoiceMessageSend?: VoiceMessageSendHandler;/*** Live send gate consulted by `handleSendButton` instead of* `sendButtonProps.disabled`. The disabled flag mirrors editor content@@ -98,6 +103,7 @@ export interface State extends PublicState {}export const initialState: State = {+ activeAudioInputMode: undefined,allowExpand: true,expand: false,feature: DEFAULT_CHAT_INPUT_FEATURE,diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex 4893259ddaa..9c428352be6 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -1,5 +1,6 @@'use client';+import { type VoiceMessageRecording } from '@lobechat/types';import { type SlashOptions } from '@lobehub/editor';import { type ChatInputActionsProps } from '@lobehub/editor/react';import { Alert, Flexbox, type MenuProps } from '@lobehub/ui';@@ -38,6 +39,7 @@ import TodoProgress from '../TodoProgress';import InputCompletionErrorAlert from './InputCompletionErrorAlert';import OpStatusTray from './OpStatusTray';import QueueTray from './QueueTray';+import { sendVoiceMessage } from './sendVoiceMessage';import {getContextWindowMessages,getConversationChatInputUiState,@@ -46,6 +48,7 @@ import {import GoalArmedChip from './VerifyTray/GoalArmedChip';import { useGoalArmStore } from './VerifyTray/goalArmStore';import GoalTray from './VerifyTray/GoalTray';+import { canSendVoiceMessage, useCanSendVoiceMessage } from './voiceMessageCapability';/** Max recent messages to feed into auto-complete context (≈10 conversation turns) */const MAX_CONTEXT_MESSAGES = 25;@@ -185,6 +188,7 @@ const ChatInput = memo<ChatInputProps>(const dbMessages = useConversationStore(dataSelectors.dbMessages);const context = useConversationStore((s) => s.context);const contextKey = useMemo(() => messageMapKey(context), [context]);+ const canRecordVoiceMessage = useCanSendVoiceMessage(context);const [agentId, inputMessage, sendMessage, stopGenerating] = useConversationStore((s) => [s.context.agentId,s.inputMessage,@@ -402,6 +406,29 @@ const ChatInput = memo<ChatInputProps>(: undefined),};+ const handleVoiceMessageSend = useCallback(+ (recording: VoiceMessageRecording) => {+ if (operationSelectors.isInputVisiblyLoadingByContext(context)(useChatStore.getState())) {+ return false;+ }++ return Boolean(+ useChatStore.getState().sendVoiceMessage({+ canSend: canSendVoiceMessage,+ context,+ recording,+ send: (file, { context: targetContext, messageId, signal }) =>+ sendVoiceMessage(sendMessage, file, {+ context: targetContext,+ optimisticUserMessageId: messageId,+ signal,+ }),+ }),+ );+ },+ [context, sendMessage],+ );+const defaultContent = (<WideScreenContainerstyle={{ position: 'relative', ...(skipScrollMarginWithList ? { marginTop: -12 } : null) }}@@ -469,6 +496,7 @@ const ChatInput = memo<ChatInputProps>(<ChatInputProvideragentId={agentId}allowExpand={allowExpand}+ canRecordVoiceMessage={canRecordVoiceMessage}contextSelectionKey={contextKey}contextWindowMessages={contextWindowMessages}draftKey={contextKey}@@ -489,6 +517,7 @@ const ChatInput = memo<ChatInputProps>(}}onMarkdownContentChange={updateInputMessage}onSend={handleSend}+ onVoiceMessageSend={handleVoiceMessageSend}>{children ?? defaultContent}</ChatInputProvider>diff --git a/src/features/Conversation/ChatInput/sendVoiceMessage.test.ts b/src/features/Conversation/ChatInput/sendVoiceMessage.test.tsnew file mode 100644index 00000000000..9dddd655a5f--- /dev/null+++ b/src/features/Conversation/ChatInput/sendVoiceMessage.test.ts@@ -0,0 +1,126 @@+import { type SendMessageParams, type UploadFileItem } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { sendVoiceMessage } from './sendVoiceMessage';++const voiceFile = {+ id: 'voice-file',+ status: 'success',+} as UploadFileItem;++describe('sendVoiceMessage', () => {+ it('forwards the optimistic user message id to the formal send lifecycle', async () => {+ const context = { agentId: 'agent-1', topicId: 'topic-created' };+ const sendMessage = vi.fn(async (params: SendMessageParams) => {+ params.onMessageAccepted?.();+ });++ await expect(+ sendVoiceMessage(sendMessage, voiceFile, {+ context,+ optimisticUserMessageId: 'tmp-voice-message',+ }),+ ).resolves.toBeUndefined();++ expect(sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ conversationContext: context,+ optimisticUserMessageId: 'tmp-voice-message',+ }),+ );+ });++ it('releases the recording after acceptance without waiting for generation to finish', async () => {+ let params: SendMessageParams | undefined;+ let resolveSend!: () => void;+ let sendFinished = false;+ const sendMessage = vi.fn((nextParams: SendMessageParams) => {+ params = nextParams;+ return new Promise<void>((resolve) => {+ resolveSend = () => {+ sendFinished = true;+ resolve();+ };+ });+ });++ const result = sendVoiceMessage(sendMessage, voiceFile);+ params?.onMessageAccepted?.();++ await expect(result).resolves.toBeUndefined();+ expect(sendFinished).toBe(false);+ expect(sendMessage).toHaveBeenCalledWith({+ files: [voiceFile],+ message: '',+ onMessageAccepted: expect.any(Function),+ preserveComposer: true,+ });++ resolveSend();+ });++ it('lets acceptance win when cancellation races with the underlying send completion', async () => {+ const controller = new AbortController();+ const abortError = new DOMException('cancelled', 'AbortError');+ let params: SendMessageParams | undefined;+ let rejectSend!: (reason: unknown) => void;+ const sendMessage = vi.fn((nextParams: SendMessageParams) => {+ params = nextParams;+ return new Promise<void>((_, reject) => {+ rejectSend = reject;+ });+ });++ const result = sendVoiceMessage(sendMessage, voiceFile, { signal: controller.signal });+ expect(params?.signal).toBe(controller.signal);++ params?.onMessageAccepted?.();+ controller.abort(abortError);+ rejectSend(abortError);++ await expect(result).resolves.toBeUndefined();+ });++ it('waits for an unaccepted send to settle before reporting cancellation', async () => {+ const controller = new AbortController();+ const abortError = new DOMException('cancelled', 'AbortError');+ let resolveSend!: () => void;+ const sendMessage = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveSend = resolve;+ }),+ );+ const settled = vi.fn();++ const result = sendVoiceMessage(sendMessage, voiceFile, { signal: controller.signal });+ void result.then(settled, settled);+ controller.abort(abortError);+ await Promise.resolve();++ expect(settled).not.toHaveBeenCalled();++ resolveSend();+ await expect(result).rejects.toBe(abortError);+ });++ it('does not dispatch a pre-cancelled recording', async () => {+ const controller = new AbortController();+ const abortError = new DOMException('cancelled', 'AbortError');+ const sendMessage = vi.fn();+ controller.abort(abortError);++ await expect(+ sendVoiceMessage(sendMessage, voiceFile, { signal: controller.signal }),+ ).rejects.toBe(abortError);+ expect(sendMessage).not.toHaveBeenCalled();+ });++ it('keeps the recording available for retry when acceptance is not acknowledged', async () => {+ const sendMessage = vi.fn().mockResolvedValue(undefined);++ await expect(sendVoiceMessage(sendMessage, voiceFile)).rejects.toThrow(+ 'Voice message was not accepted',+ );+ });+});diff --git a/src/features/Conversation/ChatInput/sendVoiceMessage.ts b/src/features/Conversation/ChatInput/sendVoiceMessage.tsnew file mode 100644index 00000000000..d2ffd8ab337--- /dev/null+++ b/src/features/Conversation/ChatInput/sendVoiceMessage.ts@@ -0,0 +1,63 @@+import {+ type ConversationContext,+ type SendMessageParams,+ type UploadFileItem,+} from '@lobechat/types';++type SendMessage = (+ params: SendMessageParams & { conversationContext?: ConversationContext },+) => Promise<void>;++interface SendVoiceMessageOptions {+ context?: ConversationContext;+ optimisticUserMessageId?: string;+ signal?: AbortSignal;+}++const getAbortError = (signal: AbortSignal) =>+ signal.reason instanceof Error+ ? signal.reason+ : new DOMException('Voice message send was cancelled', 'AbortError');++/**+ * Dispatch an audio-only turn and retain the recording until the conversation lifecycle owns it+ * as either a persisted user message or a queued turn.+ */+export const sendVoiceMessage = (+ sendMessage: SendMessage,+ file: UploadFileItem,+ options: SendVoiceMessageOptions = {},+) => {+ const { context, optimisticUserMessageId, signal } = options;+ if (signal?.aborted) return Promise.reject(getAbortError(signal));++ return new Promise<void>((resolve, reject) => {+ let accepted = false;++ void sendMessage({+ files: [file],+ message: '',+ onMessageAccepted: () => {+ accepted = true;+ resolve();+ },+ preserveComposer: true,+ ...(context ? { conversationContext: context } : {}),+ ...(optimisticUserMessageId ? { optimisticUserMessageId } : {}),+ ...(signal ? { signal } : {}),+ }).then(+ () => {+ if (accepted) return;++ reject(+ signal?.aborted ? getAbortError(signal) : new Error('Voice message was not accepted'),+ );+ },+ (error) => {+ if (accepted) return;++ reject(signal?.aborted ? getAbortError(signal) : error);+ },+ );+ });+};diff --git a/src/features/Conversation/ChatInput/voiceMessageCapability.test.ts b/src/features/Conversation/ChatInput/voiceMessageCapability.test.tsnew file mode 100644index 00000000000..c4b954dc817--- /dev/null+++ b/src/features/Conversation/ChatInput/voiceMessageCapability.test.ts@@ -0,0 +1,138 @@+import { act, renderHook } from '@testing-library/react';+import { ModelProvider } from 'model-bank/modelProvider';+import { afterEach, describe, expect, it } from 'vitest';++import { useAgentStore } from '@/store/agent';+import { useAiInfraStore } from '@/store/aiInfra';+import { useChatStore } from '@/store/chat';+import { useUserStore } from '@/store/user';++import { canSendVoiceMessage, useCanSendVoiceMessage } from './voiceMessageCapability';++const initialAgentState = useAgentStore.getState();+const initialAiInfraState = useAiInfraStore.getState();+const initialChatState = useChatStore.getState();+const initialUserState = useUserStore.getState();++afterEach(() => {+ useAgentStore.setState(initialAgentState, true);+ useAiInfraStore.setState(initialAiInfraState, true);+ useChatStore.setState(initialChatState, true);+ useUserStore.setState(initialUserState, true);+});++describe('canSendVoiceMessage', () => {+ it('rechecks the transaction topic capability without depending on the mounted chat input', () => {+ const agentId = 'voice-agent';+ const topicId = 'voice-topic';+ const audioModel = {+ abilities: { audio: true },+ enabled: true,+ id: 'gemini-audio',+ providerId: ModelProvider.Google,+ type: 'chat',+ } as const;+ const textModel = {+ abilities: {},+ enabled: true,+ id: 'text-only',+ providerId: ModelProvider.Google,+ type: 'chat',+ } as const;+ useAgentStore.setState({+ agentMap: {+ [agentId]: { chatConfig: {}, model: audioModel.id, provider: ModelProvider.Google },+ },+ } as any);+ useAiInfraStore.setState({ enabledAiModels: [audioModel, textModel] });+ useUserStore.setState({ workspaceUserPreference: {} });+ useChatStore.setState({+ activeAgentId: 'another-agent',+ activeTopicId: 'another-topic',+ topicDataMap: {+ [`agent_${agentId}`]: {+ items: [{ id: topicId, model: audioModel.id, provider: ModelProvider.Google }],+ },+ },+ } as any);+ const context = { agentId, topicId };++ expect(canSendVoiceMessage(context)).toBe(true);++ useChatStore.setState({+ topicDataMap: {+ [`agent_${agentId}`]: {+ items: [{ id: topicId, model: textModel.id, provider: ModelProvider.Google }],+ },+ },+ } as any);++ expect(canSendVoiceMessage(context)).toBe(false);+ });+});++describe('useCanSendVoiceMessage', () => {+ it('updates when the effective conversation model switches capability', () => {+ const agentId = 'reactive-voice-agent';+ const audioModel = {+ abilities: { audio: true },+ enabled: true,+ id: 'gemini-audio',+ providerId: ModelProvider.Google,+ type: 'chat',+ } as const;+ const textModel = {+ abilities: {},+ enabled: true,+ id: 'text-only',+ providerId: ModelProvider.Google,+ type: 'chat',+ } as const;+ act(() => {+ useAgentStore.setState({+ agentMap: {+ [agentId]: {+ chatConfig: {},+ model: audioModel.id,+ provider: ModelProvider.Google,+ },+ },+ } as any);+ useAiInfraStore.setState({ enabledAiModels: [audioModel, textModel] });+ useUserStore.setState({ workspaceUserPreference: {} });+ });++ const context = { agentId };+ const { result } = renderHook(() => useCanSendVoiceMessage(context));++ expect(result.current).toBe(true);++ act(() => {+ useAgentStore.setState({+ agentMap: {+ [agentId]: {+ chatConfig: {},+ model: textModel.id,+ provider: ModelProvider.Google,+ },+ },+ } as any);+ });++ expect(result.current).toBe(false);++ act(() => {+ useAgentStore.setState({+ agentMap: {+ [agentId]: {+ chatConfig: {},+ model: audioModel.id,+ provider: ModelProvider.Google,+ },+ },+ } as any);+ });++ expect(result.current).toBe(true);+ });+});diff --git a/src/features/Conversation/ChatInput/voiceMessageCapability.ts b/src/features/Conversation/ChatInput/voiceMessageCapability.tsnew file mode 100644index 00000000000..3fe812dddad--- /dev/null+++ b/src/features/Conversation/ChatInput/voiceMessageCapability.ts@@ -0,0 +1,22 @@+import type { ConversationContext } from '@lobechat/types';++import {+ getVoiceMessageCapability,+ useVoiceMessageCapability,+} from '@/features/ChatInput/VoiceMessage/useVoiceMessageCapability';+import {+ getEffectiveConversationModelConfig,+ useEffectiveConversationModelConfig,+} from '@/features/Conversation/store/utils/effectiveModel';++export const canSendVoiceMessage = (context: ConversationContext) => {+ const { model, provider } = getEffectiveConversationModelConfig(context);++ return getVoiceMessageCapability(model, provider);+};++export const useCanSendVoiceMessage = (context: ConversationContext) => {+ const { model, provider } = useEffectiveConversationModelConfig(context);++ return useVoiceMessageCapability(model, provider);+};diff --git a/src/features/Conversation/Messages/User/Actions/index.tsx b/src/features/Conversation/Messages/User/Actions/index.tsxindex a1664008650..0318df03e76 100644--- a/src/features/Conversation/Messages/User/Actions/index.tsx+++ b/src/features/Conversation/Messages/User/Actions/index.tsx@@ -13,6 +13,7 @@ import {type MessageActionSlot,} from '../../components/MessageActionBar';import MessageBranch from '../../components/MessageBranch';+import { shouldShowUserActions } from './visibility';const DEFAULT_BAR: MessageActionSlot[] = ['regenerate', 'edit', 'copy'];const DEFAULT_MENU: MessageActionSlot[] = [@@ -38,6 +39,9 @@ interface UserActionsProps {export const UserActionsBar = memo<UserActionsProps>(({ actionsConfig, id, data }) => {const ctx = useMemo<MessageActionContext>(() => ({ data, id, role: 'user' }), [data, id]);++ if (!shouldShowUserActions(data)) return null;+return (<MessageActionBarbar={actionsConfig?.bar ?? DEFAULT_BAR}@@ -63,6 +67,8 @@ const Actions = memo<ActionsProps>(({ id, data, disableEditing }) => {const { branch } = data;const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);+ if (!shouldShowUserActions(data)) return null;+return (<Flexbox horizontal align={'center'}>{!disableEditing && (diff --git a/src/features/Conversation/Messages/User/Actions/visibility.test.ts b/src/features/Conversation/Messages/User/Actions/visibility.test.tsnew file mode 100644index 00000000000..9d0cd15e44e--- /dev/null+++ b/src/features/Conversation/Messages/User/Actions/visibility.test.ts@@ -0,0 +1,19 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';++import { shouldShowUserActions } from './visibility';++const createMessage = (metadata?: UIChatMessage['metadata']) =>+ ({ id: 'message-1', metadata, role: 'user' }) as UIChatMessage;++describe('shouldShowUserActions', () => {+ it('shows actions for persisted user messages', () => {+ expect(shouldShowUserActions(createMessage())).toBe(true);+ });++ it('hides actions for local-only optimistic messages', () => {+ expect(shouldShowUserActions(createMessage({ scope: LOCAL_MESSAGE_SCOPE }))).toBe(false);+ });+});diff --git a/src/features/Conversation/Messages/User/Actions/visibility.ts b/src/features/Conversation/Messages/User/Actions/visibility.tsnew file mode 100644index 00000000000..b673632869a--- /dev/null+++ b/src/features/Conversation/Messages/User/Actions/visibility.ts@@ -0,0 +1,5 @@+import type { UIChatMessage } from '@lobechat/types';++import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';++export const shouldShowUserActions = (message: UIChatMessage) => !isLocalOnlyMessage(message);diff --git a/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx b/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsxindex f8d48f75f51..b5f0cadd4ad 100644--- a/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx+++ b/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx@@ -6,13 +6,20 @@ import { type ChatAudioItem } from '@/types/index';interface AudioFileListViewerProps {items: ChatAudioItem[];+ messageId: string;}-const AudioFileListViewer = memo<AudioFileListViewerProps>(({ items }) => {+const AudioFileListViewer = memo<AudioFileListViewerProps>(({ items, messageId }) => {return (<Flexbox gap={8}>{items.map((item) => (- <AudioPlayer alt={item.alt} key={item.id} url={item.url} />+ <AudioPlayer+ alt={item.alt}+ durationMs={item.durationMs}+ key={item.id}+ messageId={messageId}+ url={item.url}+ />))}</Flexbox>);diff --git a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx b/src/features/Conversation/Messages/User/components/MessageContent.test.tsxindex d058d5517ae..5b854281a10 100644--- a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx+++ b/src/features/Conversation/Messages/User/components/MessageContent.test.tsx@@ -27,7 +27,11 @@ vi.mock('./VideoFileListViewer', () => ({default: () => null,}));vi.mock('./AudioFileListViewer', () => ({- default: ({ items }: any) => <div data-testid="audio-viewer">{items.length}</div>,+ default: ({ items, messageId }: any) => (+ <div data-message-id={messageId} data-testid="audio-viewer">+ {items.length}+ </div>+ ),}));describe('User MessageContent', () => {@@ -75,6 +79,7 @@ describe('User MessageContent', () => {);expect(screen.getByTestId('audio-viewer')).toHaveTextContent('1');+ expect(screen.getByTestId('audio-viewer')).toHaveAttribute('data-message-id', 'msg-3');});it('should render code context selections in the user message body', () => {diff --git a/src/features/Conversation/Messages/User/components/MessageContent.tsx b/src/features/Conversation/Messages/User/components/MessageContent.tsxindex ccb40711937..4dcb722ff86 100644--- a/src/features/Conversation/Messages/User/components/MessageContent.tsx+++ b/src/features/Conversation/Messages/User/components/MessageContent.tsx@@ -37,7 +37,9 @@ const UserMessageContent = memo<UIChatMessage>({textBody && <CollapsibleContent>{textBody}</CollapsibleContent>}{imageList && imageList?.length > 0 && <ImageFileListViewer items={imageList} />}{videoList && videoList?.length > 0 && <VideoFileListViewer items={videoList} />}- {audioList && audioList?.length > 0 && <AudioFileListViewer items={audioList} />}+ {audioList && audioList?.length > 0 && (+ <AudioFileListViewer items={audioList} messageId={id} />+ )}{fileList && fileList?.length > 0 && <FileListViewer items={fileList} />}</Flexbox>);diff --git a/src/features/Conversation/Messages/index.tsx b/src/features/Conversation/Messages/index.tsxindex 2c2b9c4c629..fdbfaacc4be 100644--- a/src/features/Conversation/Messages/index.tsx+++ b/src/features/Conversation/Messages/index.tsx@@ -24,6 +24,7 @@ import PendingRetryTurn from './components/PendingRetryTurn';import TextSelectionActionLayer from './components/TextSelectionActionLayer';import CompressedGroupMessage from './CompressedGroup';import GroupTasksMessage from './GroupTasks';+import { getMessageInteractionState } from './messageInteraction';import TaskMessage from './Task';import TaskCallbackMessage from './TaskCallback';import TasksMessage from './Tasks';@@ -80,6 +81,10 @@ const MessageItem = memo<MessageItemProps>(// Get message from ConversationStoreconst message = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual);const role = message?.role;+ const { effectiveDisableEditing, shouldSuppressContextMenu } = getMessageInteractionState(+ message,+ disableEditing,+ );const [editing, isMessageCreating] = useConversationStore((s) => [messageStateSelectors.isMessageEditing(id)(s),@@ -103,6 +108,11 @@ const MessageItem = memo<MessageItemProps>(const onContextMenu = useCallback(async (event: MouseEvent<HTMLDivElement>) => {+ if (shouldSuppressContextMenu) {+ event.preventDefault();+ return;+ }+if (!role || (role !== 'user' && role !== 'assistant' && role !== 'assistantGroup')) return;if (!message) return;@@ -128,7 +138,7 @@ const MessageItem = memo<MessageItemProps>(handleContextMenu(event);},- [handleContextMenu, id, role, message],+ [handleContextMenu, id, message, role, shouldSuppressContextMenu],);const renderContent = useCallback(() => {@@ -136,7 +146,7 @@ const MessageItem = memo<MessageItemProps>(case 'user': {return (<>- <UserMessage disableEditing={disableEditing} id={id} index={index} />+ <UserMessage disableEditing={effectiveDisableEditing} id={id} index={index} />{/* A retry deletes the failed reply before its replacement exists.The user turn outlives that window, so it carries the pendingstate the deleted reply no longer can. */}@@ -148,7 +158,7 @@ const MessageItem = memo<MessageItemProps>(case 'assistant': {return (<AssistantMessage- disableEditing={disableEditing}+ disableEditing={effectiveDisableEditing}footerRender={footerRender}id={id}index={index}@@ -161,7 +171,7 @@ const MessageItem = memo<MessageItemProps>(return (<AssistantGroupMessagedefaultWorkflowExpandLevel={defaultWorkflowExpandLevel}- disableEditing={disableEditing}+ disableEditing={effectiveDisableEditing}footerRender={footerRender}id={id}index={index}@@ -178,7 +188,7 @@ const MessageItem = memo<MessageItemProps>(return (<AssistantGroupMessagedefaultWorkflowExpandLevel={defaultWorkflowExpandLevel}- disableEditing={disableEditing}+ disableEditing={effectiveDisableEditing}footerRender={footerRender}id={id}index={index}@@ -190,7 +200,7 @@ const MessageItem = memo<MessageItemProps>(case 'task': {return (<TaskMessage- disableEditing={disableEditing}+ disableEditing={effectiveDisableEditing}id={id}index={index}isLatestItem={isLatestItem}@@ -214,7 +224,7 @@ const MessageItem = memo<MessageItemProps>(}case 'tool': {- return <ToolMessage disableEditing={disableEditing} id={id} index={index} />;+ return <ToolMessage disableEditing={effectiveDisableEditing} id={id} index={index} />;}case 'verify': {@@ -227,7 +237,15 @@ const MessageItem = memo<MessageItemProps>(}return null;- }, [role, defaultWorkflowExpandLevel, disableEditing, footerRender, id, index, isLatestItem]);+ }, [+ role,+ defaultWorkflowExpandLevel,+ effectiveDisableEditing,+ footerRender,+ id,+ index,+ isLatestItem,+ ]);if (!role) return;diff --git a/src/features/Conversation/Messages/messageInteraction.test.ts b/src/features/Conversation/Messages/messageInteraction.test.tsnew file mode 100644index 00000000000..02d495c8e83--- /dev/null+++ b/src/features/Conversation/Messages/messageInteraction.test.ts@@ -0,0 +1,32 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';++import { getMessageInteractionState } from './messageInteraction';++const createMessage = (metadata?: UIChatMessage['metadata']) =>+ ({ id: 'message-1', metadata, role: 'user' }) as UIChatMessage;++describe('getMessageInteractionState', () => {+ it('keeps persisted messages interactive by default', () => {+ expect(getMessageInteractionState(createMessage())).toEqual({+ effectiveDisableEditing: false,+ shouldSuppressContextMenu: false,+ });+ });++ it('retains an explicit editing restriction without suppressing the context menu', () => {+ expect(getMessageInteractionState(createMessage(), true)).toEqual({+ effectiveDisableEditing: true,+ shouldSuppressContextMenu: false,+ });+ });++ it('disables editing and suppresses the context menu for local-only messages', () => {+ expect(getMessageInteractionState(createMessage({ scope: LOCAL_MESSAGE_SCOPE }))).toEqual({+ effectiveDisableEditing: true,+ shouldSuppressContextMenu: true,+ });+ });+});diff --git a/src/features/Conversation/Messages/messageInteraction.ts b/src/features/Conversation/Messages/messageInteraction.tsnew file mode 100644index 00000000000..039a4249f2a--- /dev/null+++ b/src/features/Conversation/Messages/messageInteraction.ts@@ -0,0 +1,15 @@+import type { UIChatMessage } from '@lobechat/types';++import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';++export const getMessageInteractionState = (+ message: UIChatMessage | undefined,+ disableEditing?: boolean,+) => {+ const isLocalOnly = isLocalOnlyMessage(message);++ return {+ effectiveDisableEditing: Boolean(disableEditing || isLocalOnly),+ shouldSuppressContextMenu: isLocalOnly,+ };+};diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.tsindex d34649755bc..b9a8c242ce5 100644--- a/src/features/Conversation/store/slices/data/action.test.ts+++ b/src/features/Conversation/store/slices/data/action.test.ts@@ -9,6 +9,8 @@ import {MESSAGE_LIST_VERIFICATION_INTERVAL,runMessageListQuery,} from '@/services/message/cache';+import { useChatStore } from '@/store/chat';+import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';import { createStore } from '../../index';import { dataSelectors } from './selectors';@@ -611,6 +613,7 @@ describe('DataSlice', () => {beforeEach(() => {vi.clearAllMocks();clearMessageListClientCacheState();+ useChatStore.setState({ voiceMessageUploadMap: {} });});it('should pass threadId to messageService.getMessages', async () => {@@ -1019,6 +1022,168 @@ describe('DataSlice', () => {});});+ it('should preserve a local-only message that is missing from fetched data', async () => {+ const persistedMessage: UIChatMessage = {+ id: 'persisted-message',+ content: 'Persisted message',+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 1000,+ };+ const localVoiceMessage: UIChatMessage = {+ id: 'tmp-voice-message',+ audioList: [{ alt: 'voice.webm', id: 'tmp-audio', url: 'blob:voice-preview' }],+ content: '',+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ createdAt: 2000,+ updatedAt: 2000,+ };++ vi.mocked(messageService.getMessages).mockResolvedValue([persistedMessage]);++ const store = createStore({+ context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },+ });+ store.setState({ dbMessages: [localVoiceMessage] });+ useChatStore.setState({+ voiceMessageUploadMap: {+ [localVoiceMessage.id]: { progress: 50, status: 'uploading' },+ },+ });++ store.getState().useFetchMessages({+ agentId: 'test-session',+ topicId: 'test-topic',+ threadId: null,+ });++ await waitFor(() => {+ expect(store.getState().dbMessages).toEqual([persistedMessage, localVoiceMessage]);+ });+ });++ it('should keep an earlier local-only voice row ahead of a later fetched message', async () => {+ const localVoiceMessage: UIChatMessage = {+ id: 'tmp-voice-message',+ audioList: [{ alt: 'voice.webm', id: 'tmp-audio', url: 'blob:voice-preview' }],+ content: '',+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ createdAt: 1000,+ updatedAt: 1000,+ };+ const laterFetchedMessage: UIChatMessage = {+ id: 'later-message',+ content: 'Later text',+ role: 'user',+ createdAt: 2000,+ updatedAt: 2000,+ };++ vi.mocked(messageService.getMessages).mockResolvedValue([laterFetchedMessage]);++ const store = createStore({+ context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },+ });+ store.setState({ dbMessages: [localVoiceMessage] });+ useChatStore.setState({+ voiceMessageUploadMap: {+ [localVoiceMessage.id]: { progress: 50, status: 'uploading' },+ },+ });++ store.getState().useFetchMessages({+ agentId: 'test-session',+ topicId: 'test-topic',+ threadId: null,+ });++ await waitFor(() => {+ expect(store.getState().dbMessages).toEqual([localVoiceMessage, laterFetchedMessage]);+ });+ });++ it('should drop a missing local-only message after its voice transaction settles', async () => {+ const persistedMessage: UIChatMessage = {+ id: 'persisted-message',+ content: 'Persisted message',+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 1000,+ };+ const settledLocalVoiceMessage: UIChatMessage = {+ id: 'tmp-settled-voice-message',+ audioList: [{ alt: 'voice.webm', id: 'tmp-audio', url: 'blob:stale-voice-preview' }],+ content: '',+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ createdAt: 2000,+ updatedAt: 2000,+ };++ vi.mocked(messageService.getMessages).mockResolvedValue([persistedMessage]);++ const store = createStore({+ context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },+ });+ store.setState({ dbMessages: [settledLocalVoiceMessage] });++ store.getState().useFetchMessages({+ agentId: 'test-session',+ topicId: 'test-topic',+ threadId: null,+ });++ await waitFor(() => {+ expect(store.getState().dbMessages).toEqual([persistedMessage]);+ });+ });++ it('should let a fetched server row replace a newer local-only row with the same id', async () => {+ const fetchedMessage: UIChatMessage = {+ id: 'tmp-voice-message',+ audioList: [+ { alt: 'voice.webm', id: 'persisted-audio', url: 'https://example.com/voice.webm' },+ ],+ content: 'Persisted message',+ role: 'user',+ createdAt: 1000,+ updatedAt: 1000,+ };+ const localVoiceMessage: UIChatMessage = {+ id: 'tmp-voice-message',+ audioList: [{ alt: 'voice.webm', id: 'tmp-audio', url: 'blob:voice-preview' }],+ content: '',+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ createdAt: 1000,+ updatedAt: 2000,+ };++ vi.mocked(messageService.getMessages).mockResolvedValue([fetchedMessage]);++ const store = createStore({+ context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },+ });+ store.setState({ dbMessages: [localVoiceMessage] });+ useChatStore.setState({+ voiceMessageUploadMap: {+ [localVoiceMessage.id]: { progress: 100, status: 'sending' },+ },+ });++ store.getState().useFetchMessages({+ agentId: 'test-session',+ topicId: 'test-topic',+ threadId: null,+ });++ await waitFor(() => {+ expect(store.getState().dbMessages).toEqual([fetchedMessage]);+ });+ });+it('should accept fetched message state when server data is newer', async () => {vi.mocked(messageService.getMessages).mockResolvedValue([{diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.tsindex a6b30a7395a..551d339a8de 100644--- a/src/features/Conversation/store/slices/data/action.ts+++ b/src/features/Conversation/store/slices/data/action.ts@@ -13,6 +13,10 @@ import {} from '@/services/message/cache';import { getChatStoreState } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';+import {+ isLocalOnlyMessage,+ mergeLocalMessagesByCreatedAt,+} from '@/store/chat/utils/localMessages';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type Store as ConversationStore } from '../../action';@@ -27,23 +31,36 @@ const log = debug('lobe-render:features:Conversation');const mergeFetchedMessagesWithLocalState = (fetchedMessages: UIChatMessage[],localMessages: UIChatMessage[],+ activeVoiceMessageIds: ReadonlySet<string>,): UIChatMessage[] => {- if (localMessages.length === 0 || fetchedMessages.length === 0) return fetchedMessages;+ if (localMessages.length === 0) return fetchedMessages;const localById = new Map(localMessages.map((message) => [message.id, message]));+ const fetchedIds = new Set(fetchedMessages.map((message) => message.id));let changed = false;const mergedMessages = fetchedMessages.map((message) => {const localMessage = localById.get(message.id);if (!localMessage) return message;+ // Once the server returns this id, its persisted row replaces the local-only preview.+ if (isLocalOnlyMessage(localMessage)) return message;if (localMessage.updatedAt <= message.updatedAt) return message;changed = true;return localMessage;});- return changed ? mergedMessages : fetchedMessages;+ const missingLocalOnlyMessages = localMessages.filter(+ (message) =>+ isLocalOnlyMessage(message) &&+ activeVoiceMessageIds.has(message.id) &&+ !fetchedIds.has(message.id),+ );++ if (missingLocalOnlyMessages.length === 0) return changed ? mergedMessages : fetchedMessages;++ return mergeLocalMessagesByCreatedAt(mergedMessages, missingLocalOnlyMessages);};/**@@ -286,7 +303,14 @@ export const dataSlice: StateCreator<return;const prevDbMessages = get().dbMessages;- const mergedMessages = mergeFetchedMessagesWithLocalState(data, prevDbMessages);+ const activeVoiceMessageIds = new Set(+ Object.keys(getChatStoreState().voiceMessageUploadMap),+ );+ const mergedMessages = mergeFetchedMessagesWithLocalState(+ data,+ prevDbMessages,+ activeVoiceMessageIds,+ );// Parse messages using conversation-flowconst { flatList } = parse(mergedMessages);diff --git a/src/features/Conversation/store/slices/message/action/index.test.ts b/src/features/Conversation/store/slices/message/action/index.test.tsindex cb37603aec9..c4f0c75c5fe 100644--- a/src/features/Conversation/store/slices/message/action/index.test.ts+++ b/src/features/Conversation/store/slices/message/action/index.test.ts@@ -1,6 +1,8 @@import { type UIChatMessage } from '@lobechat/types';import { act } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useChatStore } from '@/store/chat';import type { ConversationContext } from '../../../../types';import { createStore } from '../../../index';@@ -29,6 +31,10 @@ describe('message convenience actions', () => {vi.clearAllMocks();});+ afterEach(() => {+ vi.restoreAllMocks();+ });+describe('addAIMessage', () => {it('creates an assistant message with its conversation context and the submitted text', async () => {const store = createTestStore();@@ -210,3 +216,108 @@ describe('message convenience actions', () => {});});});++describe('sendMessage composer ownership', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('keeps the active text draft when dispatching a separate voice message', async () => {+ const store = createTestStore();+ const sendMessage = vi.fn().mockResolvedValue({+ assistantMessageId: 'assistant-1',+ userMessageId: 'user-1',+ });+ vi.spyOn(useChatStore, 'getState').mockReturnValue({ sendMessage } as any);+ store.setState({ inputMessage: 'keep this draft' });++ await act(async () => {+ await store.getState().sendMessage({+ files: [+ {+ audioMetadata: {+ codec: 'opus',+ durationMs: 1200,+ mimeType: 'audio/webm;codecs=opus',+ },+ file: new File(['audio'], 'voice.webm', { type: 'audio/webm;codecs=opus' }),+ id: 'audio-1',+ status: 'success',+ },+ ],+ message: '',+ preserveComposer: true,+ });+ });++ expect(store.getState().inputMessage).toBe('keep this draft');+ expect(sendMessage).toHaveBeenCalledWith(expect.objectContaining({ preserveComposer: true }));+ });++ it('uses an explicit migrated context without forwarding the old provider messages', async () => {+ const store = createTestStore({ topicId: null });+ const sendMessage = vi.fn().mockResolvedValue({+ assistantMessageId: 'assistant-1',+ userMessageId: 'user-1',+ });+ vi.spyOn(useChatStore, 'getState').mockReturnValue({ sendMessage } as any);+ store.setState({+ displayMessages: [+ {+ content: 'stale new-topic message',+ createdAt: 1,+ id: 'old-message',+ role: 'user',+ updatedAt: 1,+ },+ ],+ });+ const targetContext = { agentId: 'agent-1', threadId: null, topicId: 'topic-created' };++ await act(async () => {+ await store.getState().sendMessage({+ conversationContext: targetContext,+ files: [],+ message: 'voice follow-up',+ preserveComposer: true,+ });+ });++ expect(sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({ context: targetContext, message: 'voice follow-up' }),+ );+ expect(sendMessage).toHaveBeenCalledWith(+ expect.not.objectContaining({ messages: expect.anything() }),+ );+ });++ it('does not clear or dispatch the draft when cancellation happens inside the before-send hook', async () => {+ const store = createTestStore();+ const sendMessage = vi.fn();+ const controller = new AbortController();+ const abortError = new DOMException('cancelled', 'AbortError');+ let releaseHook!: (allowed: boolean) => void;+ const onBeforeSendMessage = vi.fn(+ () =>+ new Promise<boolean>((resolve) => {+ releaseHook = resolve;+ }),+ );+ vi.spyOn(useChatStore, 'getState').mockReturnValue({ sendMessage } as any);+ store.setState({+ hooks: { onBeforeSendMessage },+ inputMessage: 'keep this draft',+ });++ const result = store.getState().sendMessage({+ message: 'draft',+ signal: controller.signal,+ });+ controller.abort(abortError);+ releaseHook(true);++ await expect(result).rejects.toBe(abortError);+ expect(sendMessage).not.toHaveBeenCalled();+ expect(store.getState().inputMessage).toBe('keep this draft');+ });+});diff --git a/src/features/Conversation/store/slices/message/action/sendMessage.ts b/src/features/Conversation/store/slices/message/action/sendMessage.tsindex 8cbaef3533a..b108056866a 100644--- a/src/features/Conversation/store/slices/message/action/sendMessage.ts+++ b/src/features/Conversation/store/slices/message/action/sendMessage.ts@@ -1,11 +1,22 @@-import { type SendMessageParams } from '@lobechat/types';+import { type ConversationContext, type SendMessageParams } from '@lobechat/types';import { useChatStore } from '@/store/chat';+import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';-import { isLocalOnlyMessage } from '../../../../utils/localMessages';import { type Store as ConversationStore } from '../../../action';-interface ConversationSendMessageParams extends SendMessageParams {+const throwIfAborted = (signal?: AbortSignal) => {+ if (!signal?.aborted) return;++ throw signal.reason instanceof Error+ ? signal.reason+ : new DOMException('Message send was cancelled', 'AbortError');+};++export interface ConversationSendMessageParams extends SendMessageParams {+ /** Internal override used by long-lived media transactions after a topic is created. */+ conversationContext?: ConversationContext;onPreflightFailure?: () => void;}@@ -15,7 +26,7 @@ interface ConversationSendMessageParams extends SendMessageParams {* This is a simplified wrapper that:* 1. Calls lifecycle hooks* 2. Forwards to ChatStore.sendMessage with context- * 3. Passes displayMessages to decouple from store selectors+ * 3. Passes displayMessages while the provider still owns the target context** All actual message sending logic lives in ChatStore.*/@@ -24,47 +35,56 @@ export const sendMessage = (get: () => ConversationStore,) => {return async (params: ConversationSendMessageParams) => {+ const { conversationContext, ...sendParams } = params;+ throwIfAborted(sendParams.signal);const state = get();const { context, editor, hooks, displayMessages } = state;+ const targetContext = conversationContext ?? context;+ const { preserveComposer } = sendParams;// ===== Hook: onBeforeSendMessage =====if (hooks.onBeforeSendMessage) {let result: boolean | void;try {- result = await hooks.onBeforeSendMessage(params);+ result = await hooks.onBeforeSendMessage(sendParams);} catch (error) {- params.onPreflightFailure?.();+ sendParams.onPreflightFailure?.();throw error;}if (result === false) {console.info('[ConversationStore] sendMessage blocked by onBeforeSendMessage hook');- params.onPreflightFailure?.();+ sendParams.onPreflightFailure?.();return;}++ throwIfAborted(sendParams.signal);}// Keep ConversationStore in sync with the editor, which is cleared immediately on send.// Do this before awaiting the full streaming lifecycle so drafts typed during generation// are not overwritten when the request completes.- set({ inputMessage: '' });+ if (!preserveComposer) set({ inputMessage: '' });// Get global chat storeconst chatStore = useChatStore.getState();- const messages = (params.messages ?? displayMessages).filter(- (message) => !isLocalOnlyMessage(message),- );+ const usesProviderContext = messageMapKey(targetContext) === messageMapKey(context);+ const sourceMessages =+ sendParams.messages ?? (usesProviderContext ? displayMessages : undefined);+ const messages = sourceMessages?.filter((message) => !isLocalOnlyMessage(message));// Forward to ChatStore.sendMessage with context and messages- // Pass displayMessages to decouple sendMessage from store selectors+ // Pass displayMessages only while this provider still owns the target context. A migrated+ // media transaction must let ChatStore read the real topic bucket instead of forwarding the+ // unmounted `_new` provider's stale snapshot.// `onTopicCreated` is invoked from inside ChatStore.sendMessage as soon as// the backend reports a new topic id (only under isolatedTopic contexts),// not here after the full streaming lifecycle — otherwise the isolated// UI would not see the AI response while it is still streaming.const result = await chatStore.sendMessage({- ...params,- context,+ ...sendParams,+ context: targetContext,inputEditor: editor,- messages,+ ...(messages ? { messages } : undefined),onTopicCreated: hooks.onTopicCreated,});diff --git a/src/features/Conversation/store/utils/effectiveModel.test.ts b/src/features/Conversation/store/utils/effectiveModel.test.tsindex b95d3744b98..cf52c98570d 100644--- a/src/features/Conversation/store/utils/effectiveModel.test.ts+++ b/src/features/Conversation/store/utils/effectiveModel.test.ts@@ -1,10 +1,15 @@+import { act, renderHook } from '@testing-library/react';import { afterEach, describe, expect, it } from 'vitest';import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';import { useUserStore } from '@/store/user';-import { getEffectiveConversationModel } from './effectiveModel';+import {+ getEffectiveConversationModel,+ getEffectiveConversationModelConfig,+ useEffectiveConversationModelConfig,+} from './effectiveModel';const AGENT_ID = 'agt_test';const TOPIC_ID = 'tpc_test';@@ -40,6 +45,32 @@ describe('getEffectiveConversationModel', () => {);});+ it('resolves model and provider from the requested topic instead of the active agent bucket', () => {+ useAgentStore.setState({+ agentMap: {+ [AGENT_ID]: { chatConfig: {}, model: 'gpt-5.2', provider: 'openai' },+ active_agent: { chatConfig: {}, model: 'text-model', provider: 'anthropic' },+ },+ } as any);+ useChatStore.setState({+ activeAgentId: 'active_agent',+ activeTopicId: 'active_topic',+ topicDataMap: {+ [`agent_${AGENT_ID}`]: {+ items: [{ id: TOPIC_ID, model: 'gemini-audio', provider: 'google' }],+ },+ agent_active_agent: {+ items: [{ id: 'active_topic', model: 'text-model', provider: 'anthropic' }],+ },+ },+ } as any);++ expect(getEffectiveConversationModelConfig({ agentId: AGENT_ID, topicId: TOPIC_ID })).toEqual({+ model: 'gemini-audio',+ provider: 'google',+ });+ });+it('falls back to the agent default when the topic has no model recorded', () => {useAgentStore.setState({agentMap: { [AGENT_ID]: { chatConfig: {}, model: 'gpt-5.2' } },@@ -76,6 +107,10 @@ describe('getEffectiveConversationModel', () => {} as any);expect(getEffectiveConversationModel({ agentId: AGENT_ID })).toBe('claude-opus-5');+ expect(getEffectiveConversationModelConfig({ agentId: AGENT_ID })).toMatchObject({+ model: 'claude-opus-5',+ provider: 'anthropic',+ });});it('applies the member override on a collaborative builtin the caller created', () => {@@ -112,3 +147,107 @@ describe('getEffectiveConversationModel', () => {expect(getEffectiveConversationModel({ agentId: AGENT_ID })).toBe('gpt-5.2');});});++describe('useEffectiveConversationModelConfig', () => {+ it('reacts when a public workspace member selects a personal model override', () => {+ act(() => {+ useAgentStore.setState({+ agentMap: {+ [AGENT_ID]: {+ chatConfig: {},+ model: 'shared-model',+ provider: 'openai',+ userId: 'user_author',+ visibility: 'public',+ workspaceId: 'ws_1',+ },+ },+ } as any);+ useUserStore.setState({+ user: { id: 'user_member' },+ workspaceUserPreference: {},+ } as any);+ });++ const { result } = renderHook(() => useEffectiveConversationModelConfig({ agentId: AGENT_ID }));++ expect(result.current).toEqual({ model: 'shared-model', provider: 'openai' });++ act(() => {+ useUserStore.setState({+ workspaceUserPreference: {+ agentModelOverrides: {+ [AGENT_ID]: { model: 'member-model', provider: 'anthropic' },+ },+ },+ });+ });++ expect(result.current).toEqual({ model: 'member-model', provider: 'anthropic' });+ });++ it('prefers subAgentId over agentId when resolving the shared model', () => {+ const parentAgentId = 'agt_parent';+ const subAgentId = 'agt_sub';+ act(() => {+ useAgentStore.setState({+ agentMap: {+ [parentAgentId]: { chatConfig: {}, model: 'parent-model', provider: 'openai' },+ [subAgentId]: { chatConfig: {}, model: 'subagent-model', provider: 'google' },+ },+ } as any);+ useUserStore.setState({ workspaceUserPreference: {} });+ });++ const { result } = renderHook(() =>+ useEffectiveConversationModelConfig({ agentId: parentAgentId, subAgentId }),+ );++ expect(result.current).toEqual({ model: 'subagent-model', provider: 'google' });+ });++ it('prefers the topic model over the subagent and its member override', () => {+ const parentAgentId = 'agt_topic_parent';+ const subAgentId = 'agt_topic_sub';+ act(() => {+ useAgentStore.setState({+ agentMap: {+ [parentAgentId]: { chatConfig: {}, model: 'parent-model', provider: 'openai' },+ [subAgentId]: {+ chatConfig: {},+ model: 'subagent-model',+ provider: 'google',+ userId: 'user_author',+ visibility: 'public',+ workspaceId: 'ws_1',+ },+ },+ } as any);+ useChatStore.setState({+ topicDataMap: {+ [`agent_${parentAgentId}`]: {+ items: [{ id: TOPIC_ID, model: 'topic-model', provider: 'anthropic' }],+ },+ },+ } as any);+ useUserStore.setState({+ user: { id: 'user_member' },+ workspaceUserPreference: {+ agentModelOverrides: {+ [subAgentId]: { model: 'member-model', provider: 'openai' },+ },+ },+ } as any);+ });++ const { result } = renderHook(() =>+ useEffectiveConversationModelConfig({+ agentId: parentAgentId,+ subAgentId,+ topicId: TOPIC_ID,+ }),+ );++ expect(result.current).toEqual({ model: 'topic-model', provider: 'anthropic' });+ });+});diff --git a/src/features/Conversation/store/utils/effectiveModel.ts b/src/features/Conversation/store/utils/effectiveModel.tsindex d56adceb837..695faed2b1f 100644--- a/src/features/Conversation/store/utils/effectiveModel.ts+++ b/src/features/Conversation/store/utils/effectiveModel.ts@@ -1,12 +1,82 @@import { isCollaborativeBuiltinAgentRow } from '@lobechat/builtin-agents';+import type {+ AgentItem,+ AgentModelOverride,+ ConversationContext,+ LobeAgentConfig,+} from '@lobechat/types';import { resolveAgentModelConfig } from '@lobechat/types';-import { getAgentStoreState } from '@/store/agent';+import { getAgentStoreState, useAgentStore } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';-import { topicSelectors } from '@/store/chat/selectors';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { useUserStore } from '@/store/user';-import { userProfileSelectors } from '@/store/user/selectors';+import { userProfileSelectors, workspaceUserSettingsSelectors } from '@/store/user/selectors';+import type { ChatTopic } from '@/types/topic';++export interface EffectiveConversationModelConfig {+ model?: string;+ provider?: string;+}++type EffectiveConversationModelContext = Pick<+ ConversationContext,+ 'agentId' | 'groupId' | 'scope' | 'subAgentId' | 'topicId'+>;++interface EffectiveConversationModelSources {+ agent?: Pick<Partial<AgentItem>, 'slug' | 'userId' | 'virtual' | 'visibility' | 'workspaceId'>;+ currentUserId?: string;+ memberOverride?: AgentModelOverride;+ sharedConfig?: LobeAgentConfig;+ topic?: Pick<ChatTopic, 'model' | 'provider'>;+}++const getConversationTopic = (+ context: EffectiveConversationModelContext,+ topicDataMap: ReturnType<typeof useChatStore.getState>['topicDataMap'],+) => {+ const topicListAgentId =+ context.groupId && context.scope === 'group' ? undefined : context.agentId;++ return context.topicId+ ? topicDataMap?.[+ topicMapKey({ agentId: topicListAgentId, groupId: context.groupId })+ ]?.items.find((item) => item.id === context.topicId)+ : undefined;+};++const resolveEffectiveConversationModelConfig = (+ modelAgentId: string | undefined,+ { agent, currentUserId, memberOverride, sharedConfig, topic }: EffectiveConversationModelSources,+): EffectiveConversationModelConfig => {+ if (topic?.model) return { model: topic.model, provider: topic.provider || undefined };+ if (!modelAgentId || !sharedConfig) return {};++ const isAuthor = !!currentUserId && agent?.userId === currentUserId;+ // Collaborative builtins have no author to speak of — the row belongs to+ // whoever opened the feature first — so their model stays personal for every+ // member (see `AgentModelConfig.personalModelSelection`).+ const personalModelSelection = isCollaborativeBuiltinAgentRow(agent ?? {});+ const usesWorkspaceMemberSelection =+ !!agent?.workspaceId && agent.visibility !== 'private' && (personalModelSelection || !isAuthor);+ const resolved = resolveAgentModelConfig(+ {+ ...sharedConfig,+ canManage: isAuthor,+ personalModelSelection,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ },+ usesWorkspaceMemberSelection ? memberOverride : undefined,+ );++ return {+ model: resolved.model,+ provider: resolved.provider ?? sharedConfig.provider,+ };+};/*** Resolve the model a generation in this conversation would actually use.@@ -24,45 +94,55 @@ import { userProfileSelectors } from '@/store/user/selectors';* UI guards keyed on model capabilities (e.g. the Claude prefill checks) must* resolve the same effective model, not the shared agent default.*/-export const getEffectiveConversationModel = (context: {- agentId?: string | null;- topicId?: string | null;-}): string | undefined => {+export const getEffectiveConversationModelConfig = (+ context: EffectiveConversationModelContext,+): EffectiveConversationModelConfig => {// Guard on topicDataMap: this runs inside UI actions whose tests build// partially-mocked chat stores, and a capability guard must never throw.const chatState = useChatStore.getState();- const topicModel =- context.topicId && chatState.topicDataMap- ? topicSelectors.getTopicModelById(context.topicId)(chatState)?.model- : undefined;- if (topicModel) return topicModel;-- if (!context.agentId) return undefined;-+ const topic = getConversationTopic(context, chatState.topicDataMap);+ const modelAgentId = context.subAgentId ?? context.agentId;const agentState = getAgentStoreState();- const sharedConfig = agentSelectors.getAgentConfigById(context.agentId)(agentState);- const agent = agentByIdSelectors.getAgentById(context.agentId)(agentState);+ const sharedConfig = agentSelectors.getAgentConfigById(modelAgentId)(agentState);+ const agent = agentByIdSelectors.getAgentById(modelAgentId)(agentState);const userState = useUserStore.getState();const currentUserId = userProfileSelectors.userId(userState);- const isAuthor = !!currentUserId && agent?.userId === currentUserId;- // Collaborative builtins have no author to speak of — the row belongs to- // whoever opened the feature first — so their model stays personal for every- // member (see `AgentModelConfig.personalModelSelection`).- const personalModelSelection = isCollaborativeBuiltinAgentRow(agent ?? {});- const usesWorkspaceMemberSelection =- !!agent?.workspaceId && agent.visibility !== 'private' && (personalModelSelection || !isAuthor);- const memberOverride = usesWorkspaceMemberSelection- ? userState.workspaceUserPreference?.agentModelOverrides?.[context.agentId]- : undefined;+ const memberOverride =+ workspaceUserSettingsSelectors.agentModelOverrideById(modelAgentId)(userState);- return resolveAgentModelConfig(- {- ...sharedConfig,- canManage: isAuthor,- personalModelSelection,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,- },+ return resolveEffectiveConversationModelConfig(modelAgentId, {+ agent,+ currentUserId,memberOverride,- ).model;+ sharedConfig,+ topic,+ });};++/** Reactive counterpart used by capability-gated conversation controls. */+export const useEffectiveConversationModelConfig = (+ context: EffectiveConversationModelContext,+): EffectiveConversationModelConfig => {+ const topic = useChatStore((state) => getConversationTopic(context, state.topicDataMap));+ const modelAgentId = context.subAgentId ?? context.agentId;+ const [agent, sharedConfig] = useAgentStore((state) => [+ agentByIdSelectors.getAgentById(modelAgentId)(state),+ agentSelectors.getAgentConfigById(modelAgentId)(state),+ ]);+ const [currentUserId, memberOverride] = useUserStore((state) => [+ userProfileSelectors.userId(state),+ workspaceUserSettingsSelectors.agentModelOverrideById(modelAgentId)(state),+ ]);++ return resolveEffectiveConversationModelConfig(modelAgentId, {+ agent,+ currentUserId,+ memberOverride,+ sharedConfig,+ topic,+ });+};++export const getEffectiveConversationModel = (+ context: EffectiveConversationModelContext,+): string | undefined => getEffectiveConversationModelConfig(context).model;diff --git a/src/features/Conversation/utils/localMessages.ts b/src/features/Conversation/utils/localMessages.tsdeleted file mode 100644index 6c964e5988f..00000000000--- a/src/features/Conversation/utils/localMessages.ts+++ /dev/null@@ -1,8 +0,0 @@-import type { UIChatMessage } from '@lobechat/types';--// Marks messages that should be rendered locally but never forwarded into the-// real send pipeline or persisted to the database.-export const LOCAL_MESSAGE_SCOPE = '__internal_local__';--export const isLocalOnlyMessage = (message: UIChatMessage | undefined) =>- message?.metadata?.scope === LOCAL_MESSAGE_SCOPE;diff --git a/src/features/Portal/Thread/Chat/index.tsx b/src/features/Portal/Thread/Chat/index.tsxindex 65b7babb63a..60241e1ba38 100644--- a/src/features/Portal/Thread/Chat/index.tsx+++ b/src/features/Portal/Thread/Chat/index.tsx@@ -98,7 +98,7 @@ const ThreadChatContent = memo<ThreadChatContentProps>(</Suspense>{composerWritable && inputMode === 'heterogeneous' && <HeterogeneousChatInput />}{composerWritable && inputMode === 'default' && (- <ChatInput leftActions={['typo']} rightActions={['contextWindow']} />+ <ChatInput leftActions={['typo']} rightActions={['voiceMessage', 'contextWindow']} />)}</>);diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsxindex 2e93f2ebee3..0e33ac653ac 100644--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx@@ -15,8 +15,12 @@ import { userGeneralSettingsSelectors } from '@/store/user/selectors';import AgentConfigError from './AgentConfigError';import { useSendMenuItems } from './useSendMenuItems';-const contextWindowRightActions: ActionKeys[] = ['contextWindow'];-const promptTransformRightActions: ActionKeys[] = ['promptTransform', 'contextWindow'];+const contextWindowRightActions: ActionKeys[] = ['voiceMessage', 'contextWindow'];+const promptTransformRightActions: ActionKeys[] = [+ 'promptTransform',+ 'voiceMessage',+ 'contextWindow',+];/*** MainChatInputdiff --git a/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsxindex 5f589cfc905..b5e37bae76b 100644--- a/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx+++ b/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx@@ -19,7 +19,7 @@ const leftActions: ActionKeys[] = [['typo', 'params', 'clear'],];-const rightActions: ActionKeys[] = ['contextWindow'];+const rightActions: ActionKeys[] = ['voiceMessage', 'contextWindow'];/*** MainChatInputdiff --git a/src/services/file/index.ts b/src/services/file/index.tsindex 083439b5ae6..29c606be014 100644--- a/src/services/file/index.ts+++ b/src/services/file/index.ts@@ -57,6 +57,10 @@ export class FileService {await lambdaClient.file.removeFile.mutate({ id });};+ removeUnreferencedFile = async (id: string): Promise<void> => {+ await lambdaClient.file.removeUnreferencedFile.mutate({ id });+ };+removeFiles = async (ids: string[]): Promise<void> => {await lambdaClient.file.removeFiles.mutate({ ids });};diff --git a/src/store/chat/initialState.ts b/src/store/chat/initialState.tsindex 0169929e232..f3fa825d620 100644--- a/src/store/chat/initialState.ts+++ b/src/store/chat/initialState.ts@@ -15,6 +15,8 @@ import { type ChatThreadState } from './slices/thread/initialState';import { initialThreadState } from './slices/thread/initialState';import { type ChatTopicState } from './slices/topic/initialState';import { initialTopicState } from './slices/topic/initialState';+import { type ChatVoiceMessageState } from './slices/voiceMessage/initialState';+import { initialVoiceMessageState } from './slices/voiceMessage/initialState';export type ChatStoreState = ChatTopicState &ChatMessageState &@@ -23,7 +25,8 @@ export type ChatStoreState = ChatTopicState &ChatThreadState &ChatPortalState &ChatAIAgentState &- ChatOperationState;+ ChatOperationState &+ ChatVoiceMessageState;export const initialState: ChatStoreState = {...initialMessageState,@@ -34,6 +37,7 @@ export const initialState: ChatStoreState = {...initialChatPortalState,...initialOperationState,...initialAiAgentState,+ ...initialVoiceMessageState,// cloud};diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 7bc2491452c..078134a55f5 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -12,6 +12,11 @@ import { messageService } from '@/services/message';import * as agentGroupStore from '@/store/agentGroup';import { setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { operationSelectors } from '@/store/chat/slices/operation/selectors';+import type {+ VoiceMessageSend,+ VoiceMessageSendOptions,+} from '@/store/chat/slices/voiceMessage/action';+import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { fileChatSelectors, useFileStore } from '@/store/file';@@ -303,6 +308,8 @@ describe('ConversationLifecycle actions', () => {it('should not process AI when onlyAddUserMessage is true', async () => {const { result } = renderHook(() => useChatStore());+ const onMessageAccepted = vi.fn();+ const onMessagePersisted = vi.fn();vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({messages: [],@@ -314,15 +321,20 @@ describe('ConversationLifecycle actions', () => {await result.current.sendMessage({message: TEST_CONTENT.USER_MESSAGE,onlyAddUserMessage: true,+ onMessageAccepted,+ onMessagePersisted,context: createTestContext(),});});expect(result.current.executeClientAgent).not.toHaveBeenCalled();+ expect(onMessageAccepted).toHaveBeenCalledOnce();+ expect(onMessagePersisted).toHaveBeenCalledOnce();});it('should restore the pre-send editor snapshot when server send fails', async () => {const { result } = renderHook(() => useChatStore());+ const onMessagePersisted = vi.fn();const inputEditorState = {root: {children: [@@ -361,6 +373,7 @@ describe('ConversationLifecycle actions', () => {context: createTestContext(),editorData: inputEditorState as any,message: 'Restored rich text',+ onMessagePersisted,});});@@ -371,6 +384,558 @@ describe('ConversationLifecycle actions', () => {expect(sendMessageOperation?.metadata.inputEditorTempState).toEqual(inputEditorState);expect(setJSONState).toHaveBeenCalledWith(inputEditorState);expect(setDocument).not.toHaveBeenCalled();+ expect(onMessagePersisted).not.toHaveBeenCalled();+ });++ it('should not restore an editor snapshot when a separate voice send fails', async () => {+ const { result } = renderHook(() => useChatStore());+ const getJSONState = vi.fn().mockReturnValue({ stale: 'draft' });+ const setDocument = vi.fn();+ const setJSONState = vi.fn();++ vi.spyOn(aiChatService, 'sendMessageInServer').mockRejectedValue(+ new TRPCClientError('voice persistence failed'),+ );++ act(() => {+ useChatStore.setState({+ mainInputEditor: {+ getJSONState,+ setDocument,+ setJSONState,+ } as any,+ });+ });++ await act(async () => {+ await result.current.sendMessage({+ context: createTestContext(),+ files: [{ id: 'voice-file' } as any],+ message: '',+ preserveComposer: true,+ });+ });++ const sendMessageOperation = Object.values(result.current.operations).find(+ (operation) => operation.type === 'sendMessage',+ );++ expect(sendMessageOperation?.metadata.inputEditorTempState).toBeUndefined();+ expect(getJSONState).not.toHaveBeenCalled();+ expect(setJSONState).not.toHaveBeenCalled();+ expect(setDocument).not.toHaveBeenCalled();+ });++ it('should move and adopt a first-turn voice row without sending local-only history', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const contextKey = messageMapKey(context);++ act(() => {+ useChatStore.setState({+ activeAgentId: TEST_IDS.SESSION_ID,+ activeTopicId: undefined,+ });+ });++ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:voice-preview');+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress').mockResolvedValue({+ id: 'uploaded-audio',+ url: 'https://example.com/voice.webm',+ });++ let resolvePersistence!: (value: any) => void;+ const persistence = new Promise<any>((resolve) => {+ resolvePersistence = resolve;+ });+ const sendMessageInServer = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockReturnValue(persistence);++ let optimisticUserMessageId!: string;+ act(() => {+ optimisticUserMessageId = result.current.sendVoiceMessage({+ canSend: () => true,+ context,+ recording: {+ codec: 'opus',+ durationMs: 1200,+ file: new File(['voice'], 'voice.webm', { type: 'audio/webm' }),+ mimeType: 'audio/webm',+ waveform: [0.2, 0.8, 0.3],+ },+ send: (file, options) =>+ new Promise<void>((resolve, reject) => {+ let accepted = false;+ void result.current+ .sendMessage({+ context: options.context,+ files: [file],+ message: '',+ onMessageAccepted: () => {+ accepted = true;+ resolve();+ },+ optimisticUserMessageId: options.messageId,+ preserveComposer: true,+ signal: options.signal,+ })+ .then(() => {+ if (!accepted) reject(new Error('Voice message was not accepted'));+ }, reject);+ }),+ })!;+ });++ await waitFor(() => expect(sendMessageInServer).toHaveBeenCalledOnce());++ const midState = useChatStore.getState();+ const mintedTopicId = midState.activeTopicId!;+ const mintedContextKey = messageMapKey({ ...context, topicId: mintedTopicId });+ const pendingMessages = midState.dbMessagesMap[mintedContextKey];+ expect(mintedTopicId).toMatch(/^tpc_/);+ expect(optimisticUserMessageId).toMatch(/^msg_/);+ expect(midState.dbMessagesMap[contextKey] ?? []).toEqual([]);+ expect(pendingMessages.filter((message) => message.role === 'user')).toHaveLength(1);+ expect(+ pendingMessages.filter((message) => message.id === optimisticUserMessageId),+ ).toHaveLength(1);+ expect(pendingMessages.find((message) => message.id === optimisticUserMessageId)).toEqual(+ expect.objectContaining({+ audioList: [+ expect.objectContaining({+ id: 'uploaded-audio',+ url: 'https://example.com/voice.webm',+ }),+ ],+ files: ['uploaded-audio'],+ metadata: expect.objectContaining({ scope: LOCAL_MESSAGE_SCOPE }),+ }),+ );+ expect(sendMessageInServer.mock.calls[0][0].newTopic?.id).toBe(mintedTopicId);+ expect(sendMessageInServer.mock.calls[0][0].newTopic?.topicMessageIds).toEqual([]);++ const request = sendMessageInServer.mock.calls[0][0];+ await act(async () => {+ resolvePersistence({+ assistantMessageId: request.newAssistantMessage.id,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({+ id: request.newUserMessage.id,+ role: 'user',+ topicId: mintedTopicId,+ }),+ createMockMessage({+ id: request.newAssistantMessage.id,+ role: 'assistant',+ topicId: mintedTopicId,+ }),+ ],+ topicId: mintedTopicId,+ topics: { items: [{ id: mintedTopicId, title: 'Voice topic' }], total: 1 },+ userMessageId: request.newUserMessage.id,+ });+ });++ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[optimisticUserMessageId]).toBe(+ undefined,+ ),+ );+ });++ it('should preserve a caller-owned optimistic user row when persistence fails before acceptance', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = {+ agentId: TEST_IDS.SESSION_ID,+ threadId: null,+ topicId: TEST_IDS.TOPIC_ID,+ };+ const contextKey = messageMapKey(context);+ const optimisticUserMessageId = 'tmp-voice-message';+ const localVoiceMessage = createMockMessage({+ audioList: [+ {+ alt: 'voice.webm',+ durationMs: 1200,+ id: 'tmp-audio',+ mimeType: 'audio/webm',+ url: 'blob:voice-preview',+ },+ ],+ content: '',+ id: optimisticUserMessageId,+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ topicId: TEST_IDS.TOPIC_ID,+ });++ act(() => {+ useChatStore.setState({+ activeAgentId: TEST_IDS.SESSION_ID,+ activeTopicId: TEST_IDS.TOPIC_ID,+ dbMessagesMap: { [contextKey]: [localVoiceMessage] },+ messagesMap: { [contextKey]: [localVoiceMessage] },+ });+ });++ const onMessageAccepted = vi.fn();+ vi.spyOn(aiChatService, 'sendMessageInServer').mockRejectedValue(+ new Error('persistence failed'),+ );++ await act(async () => {+ await result.current.sendMessage({+ context,+ files: [+ {+ audioMetadata: { durationMs: 1200, mimeType: 'audio/webm' },+ file: { name: 'voice.webm', type: 'audio/webm' },+ fileUrl: 'https://example.com/voice.webm',+ id: 'uploaded-audio',+ status: 'success',+ } as any,+ ],+ message: '',+ onMessageAccepted,+ optimisticUserMessageId,+ preserveComposer: true,+ });+ });++ const remainingMessages = useChatStore.getState().dbMessagesMap[contextKey];+ expect(onMessageAccepted).not.toHaveBeenCalled();+ expect(remainingMessages).toHaveLength(1);+ expect(remainingMessages[0]).toEqual(+ expect.objectContaining({+ id: optimisticUserMessageId,+ metadata: expect.objectContaining({ scope: LOCAL_MESSAGE_SCOPE }),+ role: 'user',+ }),+ );+ expect(remainingMessages.some((message) => message.role === 'assistant')).toBe(false);+ });++ it('should move a failed first-turn voice back to _new before retrying', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const newContextKey = messageMapKey(context);++ act(() => {+ useChatStore.setState({+ activeAgentId: TEST_IDS.SESSION_ID,+ activeTopicId: undefined,+ });+ });++ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:voice-retry');+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress').mockResolvedValue({+ id: 'uploaded-retry-audio',+ url: 'https://example.com/retry.webm',+ });++ const sendMessageInServer = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockRejectedValueOnce(new Error('persistence failed'))+ .mockImplementationOnce(async (params: any) => {+ const topicId = params.newTopic?.id;+ return {+ assistantMessageId: params.newAssistantMessage.id,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({ id: params.newUserMessage.id, role: 'user', topicId }),+ createMockMessage({+ id: params.newAssistantMessage.id,+ role: 'assistant',+ topicId,+ }),+ ],+ topicId,+ topics: { items: [{ id: topicId, title: 'Retried voice topic' }], total: 1 },+ userMessageId: params.newUserMessage.id,+ } as any;+ });++ const sendThroughLifecycle: VoiceMessageSend = (file, options: VoiceMessageSendOptions) =>+ new Promise<void>((resolve, reject) => {+ let accepted = false;+ void result.current+ .sendMessage({+ context: options.context,+ files: [file],+ message: '',+ onMessageAccepted: () => {+ accepted = true;+ resolve();+ },+ optimisticUserMessageId: options.messageId,+ preserveComposer: true,+ signal: options.signal,+ })+ .then(() => {+ if (!accepted) reject(new Error('Voice message was not accepted'));+ }, reject);+ });++ let messageId!: string;+ act(() => {+ messageId = result.current.sendVoiceMessage({+ canSend: () => true,+ context,+ recording: {+ codec: 'opus',+ durationMs: 1200,+ file: new File(['voice'], 'voice.webm', { type: 'audio/webm' }),+ mimeType: 'audio/webm',+ waveform: [0.2, 0.8, 0.3],+ },+ send: sendThroughLifecycle,+ })!;+ });++ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]?.status).toBe('failed'),+ );++ const failedTopicId = sendMessageInServer.mock.calls[0][0].newTopic?.id;+ const failedTopicKey = messageMapKey({ ...context, topicId: failedTopicId });+ const failedState = useChatStore.getState();+ const uploadOperation = Object.values(failedState.operations).find(+ (operation) =>+ operation.type === 'uploadVoiceMessage' && operation.context.messageId === messageId,+ );+ expect(failedTopicId).toMatch(/^tpc_/);+ expect(failedState.activeTopicId).toBeFalsy();+ expect(failedState.dbMessagesMap[newContextKey]?.map((message) => message.id)).toContain(+ messageId,+ );+ expect(failedState.dbMessagesMap[failedTopicKey] ?? []).toEqual([]);+ expect(uploadOperation?.context.topicId).toBeNull();++ act(() => result.current.retryVoiceMessage(messageId));++ await waitFor(() => expect(sendMessageInServer).toHaveBeenCalledTimes(2));+ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toBeUndefined(),+ );++ const retryRequest = sendMessageInServer.mock.calls[1][0];+ expect(retryRequest.newTopic?.id).toMatch(/^tpc_/);+ expect(retryRequest.newTopic?.id).not.toBe(failedTopicId);+ expect(retryRequest.newUserMessage.id).toBe(messageId);+ });++ it('should acknowledge persistence before client generation completes', async () => {+ const { result } = renderHook(() => useChatStore());+ const onMessageAccepted = vi.fn();+ const onMessagePersisted = vi.fn();+ let resolveExecution!: () => void;+ let sendCompleted = false;+ const executionPromise = new Promise<void>((resolve) => {+ resolveExecution = resolve;+ });++ act(() => {+ useChatStore.setState({+ executeClientAgent: vi.fn().mockReturnValue(executionPromise),+ });+ });+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current+ .sendMessage({+ context: createTestContext(),+ message: TEST_CONTENT.USER_MESSAGE,+ onMessageAccepted,+ onMessagePersisted,+ })+ .then((value) => {+ sendCompleted = true;+ return value;+ });+ });++ await waitFor(() => expect(onMessagePersisted).toHaveBeenCalledOnce());+ expect(onMessageAccepted).toHaveBeenCalledOnce();+ expect(sendCompleted).toBe(false);++ await act(async () => {+ resolveExecution();+ await sendPromise;+ });+ });++ it('reconciles a persisted client message but skips generation when cancellation wins the request race', async () => {+ const { result } = renderHook(() => useChatStore());+ const controller = new AbortController();+ const onMessageAccepted = vi.fn();+ const onMessagePersisted = vi.fn();+ let resolvePersistence!: (value: any) => void;+ const persistence = new Promise<any>((resolve) => {+ resolvePersistence = resolve;+ });+ const sendMessageInServer = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockReturnValue(persistence);+ const context = {+ agentId: TEST_IDS.SESSION_ID,+ threadId: null,+ topicId: TEST_IDS.TOPIC_ID,+ };++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context,+ message: TEST_CONTENT.USER_MESSAGE,+ onMessageAccepted,+ onMessagePersisted,+ signal: controller.signal,+ });+ });+ await waitFor(() => expect(sendMessageInServer).toHaveBeenCalledOnce());++ act(() => controller.abort(new DOMException('cancelled', 'AbortError')));+ await act(async () => {+ resolvePersistence({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId: TEST_IDS.TOPIC_ID,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: TEST_IDS.TOPIC_ID,+ }),+ ],+ topicId: TEST_IDS.TOPIC_ID,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ });+ await sendPromise;+ });++ expect(onMessageAccepted).toHaveBeenCalledOnce();+ expect(onMessagePersisted).toHaveBeenCalledOnce();+ expect(result.current.executeClientAgent).not.toHaveBeenCalled();+ expect(result.current.messagesMap[messageMapKey(context)]).toHaveLength(2);+ });++ it('stops the operations-driven topic spinner when cancellation wins persistence', async () => {+ const { result } = renderHook(() => useChatStore());+ const controller = new AbortController();+ const agentId = TEST_IDS.SESSION_ID;+ const topicKey = topicMapKey({ agentId });+ let resolvePersistence!: (value: any) => void;+ const persistence = new Promise<any>((resolve) => {+ resolvePersistence = resolve;+ });++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ topicDataMap: {+ [topicKey]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ },+ },+ });+ });+ const sendMessageInServer = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockReturnValue(persistence);++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: TEST_CONTENT.USER_MESSAGE,+ signal: controller.signal,+ });+ });+ await waitFor(() => expect(sendMessageInServer).toHaveBeenCalledOnce());++ const optimisticTopicId = useChatStore.getState().topicDataMap[topicKey]?.items[0]?.id;+ expect(optimisticTopicId).toMatch(/^tpc_/);+ expect(+ operationSelectors.isTopicVisiblyRunning(optimisticTopicId!)(useChatStore.getState()),+ ).toBe(true);++ act(() => controller.abort(new DOMException('cancelled', 'AbortError')));+ await act(async () => {+ resolvePersistence({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId: optimisticTopicId,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: optimisticTopicId,+ }),+ ],+ topicId: optimisticTopicId,+ topics: { items: [{ id: optimisticTopicId, title: 'Server Topic' }], total: 1 },+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ });+ await sendPromise;+ });++ expect(result.current.executeClientAgent).not.toHaveBeenCalled();+ expect(useChatStore.getState().topicDataMap[topicKey]?.items[0]?.id).toBe(+ optimisticTopicId,+ );+ expect(+ operationSelectors.isTopicVisiblyRunning(optimisticTopicId!)(useChatStore.getState()),+ ).toBe(false);+ });++ it('detaches the caller cancellation signal after an unaccepted persistence failure', async () => {+ const { result } = renderHook(() => useChatStore());+ const controller = new AbortController();+ vi.spyOn(aiChatService, 'sendMessageInServer').mockRejectedValue(+ new TRPCClientError('persistence failed'),+ );++ await act(async () => {+ await result.current.sendMessage({+ context: createTestContext(),+ message: TEST_CONTENT.USER_MESSAGE,+ signal: controller.signal,+ });+ });+ const sendOperation = Object.values(result.current.operations).find(+ (operation) => operation.type === 'sendMessage',+ );+ expect(sendOperation?.status).toBe('failed');++ act(() => controller.abort(new DOMException('late cancel', 'AbortError')));++ expect(result.current.operations[sendOperation!.id]?.status).toBe('failed');});it('should create user message and trigger AI processing', async () => {@@ -919,6 +1484,69 @@ describe('ConversationLifecycle actions', () => {).toBe(false);});+ it('keeps persisted gateway messages when caller cancellation wins after acceptance', async () => {+ const { result } = renderHook(() => useChatStore());+ const controller = new AbortController();+ const context = {+ agentId: TEST_IDS.SESSION_ID,+ threadId: null,+ topicId: TEST_IDS.TOPIC_ID,+ };+ let gatewayParams: any;+ let resolveGateway!: () => void;+ const executeGatewayAgentSpy = vi.fn().mockImplementation(+ (params: any) =>+ new Promise<any>((resolve) => {+ gatewayParams = params;+ resolveGateway = () =>+ resolve({+ assistantMessageId: gatewayParams.clientIds.assistantMessageId,+ operationId: 'gateway-op-cancelled-after-persistence',+ topicId: TEST_IDS.TOPIC_ID,+ userMessageId: gatewayParams.clientIds.userMessageId,+ });+ }),+ );+ const internalDispatchMessageSpy = vi.spyOn(result.current, 'internal_dispatchMessage');++ act(() => {+ useChatStore.setState({+ executeGatewayAgent: executeGatewayAgentSpy,+ isGatewayModeEnabled: () => true,+ });+ });++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context,+ message: TEST_CONTENT.USER_MESSAGE,+ signal: controller.signal,+ });+ });+ await waitFor(() => expect(executeGatewayAgentSpy).toHaveBeenCalledOnce());++ act(() => controller.abort(new DOMException('cancelled', 'AbortError')));+ await act(async () => {+ gatewayParams.onMessageAccepted();+ resolveGateway();+ await sendPromise;+ });++ expect(internalDispatchMessageSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ type: 'deleteMessages' }),+ expect.anything(),+ );+ expect(+ (result.current.messagesMap[messageMapKey(context)] ?? []).map((message) => message.id),+ ).toEqual(+ expect.arrayContaining([+ gatewayParams.clientIds.userMessageId,+ gatewayParams.clientIds.assistantMessageId,+ ]),+ );+ });+it('should keep the sidebar spinner on through a hetero new-topic run and stop it at the end', async () => {mockConstEnv.isDesktop = true;setupMockSelectors({@@ -1508,10 +2136,90 @@ describe('ConversationLifecycle actions', () => {).toBe(false);});+ it('should exclude another active local-only voice row from client runtime after a partial merge', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicId = TEST_IDS.TOPIC_ID;+ const context = { agentId, threadId: null, topicId };+ const key = messageMapKey(context);+ const localVoiceMessage = createMockMessage({+ audioList: [{ alt: 'voice.webm', id: 'tmp-audio', url: 'blob:voice-preview' }],+ content: '',+ id: 'tmp-other-voice-message',+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ topicId,+ });+ const existingMessages = [+ createMockMessage({ id: 'existing-user', role: 'user', topicId }),+ createMockMessage({ id: 'existing-assistant', role: 'assistant', topicId }),+ localVoiceMessage,+ ];+ const persistedUserMessage = createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId,+ });+ const persistedAssistantMessage = createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ parentId: TEST_IDS.USER_MESSAGE_ID,+ role: 'assistant',+ topicId,+ });+ const executeClientAgent = vi.fn().mockResolvedValue(undefined);++ act(() => {+ useChatStore.setState({+ dbMessagesMap: { [key]: existingMessages },+ executeClientAgent,+ messagesMap: { [key]: existingMessages },+ voiceMessageUploadMap: {+ [localVoiceMessage.id]: { progress: 50, status: 'uploading' },+ },+ });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ __isPartialMessages: true,+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: false,+ messages: [persistedUserMessage, persistedAssistantMessage],+ topicId,+ topics: undefined,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ context,+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ expect(result.current.messagesMap[key].map((message) => message.id)).toContain(+ localVoiceMessage.id,+ );+ expect(executeClientAgent).toHaveBeenCalledOnce();+ const runtimeMessages = executeClientAgent.mock.calls[0][0].messages;+ expect(runtimeMessages.map((message: any) => message.id)).not.toContain(+ localVoiceMessage.id,+ );+ expect(runtimeMessages.map((message: any) => message.id)).toEqual(+ expect.arrayContaining([+ 'existing-user',+ 'existing-assistant',+ TEST_IDS.USER_MESSAGE_ID,+ TEST_IDS.ASSISTANT_MESSAGE_ID,+ ]),+ );+ });+it('should preserve editorData when enqueueing a queued message', async () => {const { result } = renderHook(() => useChatStore());const context = createTestContext();const contextKey = messageMapKey(context);+ const onMessageAccepted = vi.fn();+ const onMessagePersisted = vi.fn();const editorData = {root: {children: [@@ -1557,6 +2265,8 @@ describe('ConversationLifecycle actions', () => {context,editorData: editorData as any,message: 'queued message',+ onMessageAccepted,+ onMessagePersisted,});});@@ -1568,6 +2278,47 @@ describe('ConversationLifecycle actions', () => {}),'op-running',);+ expect(onMessageAccepted).toHaveBeenCalledOnce();+ expect(onMessagePersisted).not.toHaveBeenCalled();+ });++ it('should enqueue a later text turn behind an optimistic voice upload', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const contextKey = messageMapKey(context);++ act(() => {+ useChatStore.setState({+ operations: {+ 'op-voice-upload': {+ childOperationIds: [],+ context: { ...context, messageId: 'tmp_voice' },+ id: 'op-voice-upload',+ metadata: { startTime: Date.now() },+ status: 'running',+ type: 'uploadVoiceMessage',+ },+ } as any,+ operationsByContext: {+ [contextKey]: ['op-voice-upload'],+ },+ });+ });++ const enqueueMessageSpy = vi.spyOn(result.current, 'enqueueMessage');++ await act(async () => {+ await result.current.sendMessage({+ context,+ message: 'text after voice',+ });+ });++ expect(enqueueMessageSpy).toHaveBeenCalledWith(+ contextKey,+ expect.objectContaining({ content: 'text after voice' }),+ 'op-voice-upload',+ );});it('should enqueue when an execHeterogeneousAgent op is running (CC queue mode)', async () => {@@ -1724,16 +2475,13 @@ describe('ConversationLifecycle actions', () => {it('should move queued follow-ups from the new-topic key to the created topic key', async () => {const { result } = renderHook(() => useChatStore());const agentId = TEST_IDS.SESSION_ID;- const createdTopicId = 'created-topic-id';const newTopicKey = messageMapKey({ agentId, topicId: null });- const createdTopicKey = messageMapKey({ agentId, topicId: createdTopicId });const queuedMessage = {content: 'queued while topic is being created',createdAt: Date.now(),id: 'queued-before-topic-created',interruptMode: 'soft' as const,};-act(() => {useChatStore.setState({activeAgentId: agentId,@@ -1744,24 +2492,28 @@ describe('ConversationLifecycle actions', () => {});});- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,- isCreateNewTopic: true,- messages: [- createMockMessage({- id: TEST_IDS.USER_MESSAGE_ID,- role: 'user',- topicId: createdTopicId,- }),- createMockMessage({- id: TEST_IDS.ASSISTANT_MESSAGE_ID,- role: 'assistant',- topicId: createdTopicId,- }),- ],- topicId: createdTopicId,- userMessageId: TEST_IDS.USER_MESSAGE_ID,- } as any);+ let createdTopicId: string | undefined;+ vi.spyOn(aiChatService, 'sendMessageInServer').mockImplementation(async (params: any) => {+ createdTopicId = params.newTopic?.id;+ return {+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId: createdTopicId,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: createdTopicId,+ }),+ ],+ topicId: createdTopicId,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any;+ });await act(async () => {await result.current.sendMessage({@@ -1770,6 +2522,8 @@ describe('ConversationLifecycle actions', () => {});});+ expect(createdTopicId).toMatch(/^tpc_/);+ const createdTopicKey = messageMapKey({ agentId, topicId: createdTopicId });expect(useChatStore.getState().queuedMessages[newTopicKey] ?? []).toEqual([]);expect(useChatStore.getState().queuedMessages[createdTopicKey]).toEqual([queuedMessage]);});@@ -2395,6 +3149,72 @@ describe('ConversationLifecycle actions', () => {expect(useChatStore.getState().messagesMap[leakedNewTopicKey] ?? []).toHaveLength(0);});+ it('reconciles a persisted heterogeneous message but skips CLI execution after cancellation', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ },+ },+ });+ const { result } = renderHook(() => useChatStore());+ const controller = new AbortController();+ const onMessageAccepted = vi.fn();+ const onMessagePersisted = vi.fn();+ let resolvePersistence!: (value: any) => void;+ const persistence = new Promise<any>((resolve) => {+ resolvePersistence = resolve;+ });+ const sendMessageInServer = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockReturnValue(persistence);+ const context = {+ agentId: TEST_IDS.SESSION_ID,+ threadId: null,+ topicId: TEST_IDS.TOPIC_ID,+ };++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context,+ message: TEST_CONTENT.USER_MESSAGE,+ onMessageAccepted,+ onMessagePersisted,+ signal: controller.signal,+ });+ });+ await waitFor(() => expect(sendMessageInServer).toHaveBeenCalledOnce());++ act(() => controller.abort(new DOMException('cancelled', 'AbortError')));+ await act(async () => {+ resolvePersistence({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId: TEST_IDS.TOPIC_ID,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: TEST_IDS.TOPIC_ID,+ }),+ ],+ topicId: TEST_IDS.TOPIC_ID,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ });+ await sendPromise;+ });++ expect(onMessageAccepted).toHaveBeenCalledOnce();+ expect(onMessagePersisted).toHaveBeenCalledOnce();+ expect(executeHeterogeneousAgentMock).not.toHaveBeenCalled();+ expect(result.current.messagesMap[messageMapKey(context)]).toHaveLength(2);+ });+it('should preserve the isNew marker for heterogeneous new-thread contexts', async () => {mockConstEnv.isDesktop = true;setupMockSelectors({diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 872a336f664..b8202008f40 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as ConstVersion from '@/const/version';import { aiAgentService } from '@/services/aiAgent';+import { messageService } from '@/services/message';import { topicService } from '@/services/topic';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -528,6 +529,7 @@ describe('GatewayActionImpl', () => {function createExecuteTestAction() {const mockClient = createMockClient();const moveQueuedMessages = vi.fn();+ const moveVoiceMessages = vi.fn();const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };const associateMessageWithOperation = vi.fn();const connectToGateway = vi.fn();@@ -554,6 +556,7 @@ describe('GatewayActionImpl', () => {internal_dispatchTopic: internalDispatchTopic,internal_replaceTopicId: internalReplaceTopicId,moveQueuedMessages,+ moveVoiceMessages,onOperationCancel,replaceMessages,refreshTopic,@@ -583,6 +586,7 @@ describe('GatewayActionImpl', () => {internalReplaceTopicId,mockClient,moveQueuedMessages,+ moveVoiceMessages,onOperationCancel,replaceMessages,refreshTopic,@@ -719,7 +723,7 @@ describe('GatewayActionImpl', () => {});it('should move queued follow-ups from the new-topic key to the server-created topic key', async () => {- const { action, moveQueuedMessages } = createExecuteTestAction();+ const { action, moveQueuedMessages, moveVoiceMessages } = createExecuteTestAction();const context = { agentId: 'agent-1', topicId: null, threadId: null };vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({@@ -746,6 +750,10 @@ describe('GatewayActionImpl', () => {messageMapKey(context),messageMapKey({ ...context, topicId: 'topic-created' }),);+ expect(moveVoiceMessages).toHaveBeenCalledWith(context, {+ ...context,+ topicId: 'topic-created',+ });});it('should replace the optimistic topic placeholder with the server topic id', async () => {@@ -992,19 +1000,17 @@ describe('GatewayActionImpl', () => {);});- it('forwards the parent abort signal to execAgentTask and bails out (with server interrupt) when cancel arrives after the request resolved', async () => {+ it('reconciles an accepted message but skips the gateway child when cancel races with phase-1 persistence', async () => {const startOperation = vi.fn(() => ({ operationId: 'gw-op-local' }));const completeOperation = vi.fn();const associateMessageWithOperation = vi.fn();const connectToGateway = vi.fn();+ const moveQueuedMessages = vi.fn();const onOperationCancel = vi.fn();+ const onMessageAccepted = vi.fn();+ const replaceMessages = vi.fn();- // Pre-aborted controller simulates the user clicking Stop while- // execAgentTask is still in flight: when it resolves the signal is- // already `aborted: true`, so executeGatewayAgent must NOT proceed to- // start the child op or open a WS connection.const controller = new AbortController();- controller.abort('user cancelled');const mockClient = createMockClient();const state: Record<string, any> = { gatewayConnections: {} };@@ -1018,8 +1024,10 @@ describe('GatewayActionImpl', () => {completeOperation,connectToGateway,getOperationAbortSignal: vi.fn(() => controller.signal),+ moveQueuedMessages,+ moveVoiceMessages: vi.fn(),onOperationCancel,- replaceMessages: vi.fn(),+ replaceMessages,startOperation,switchTopic: vi.fn(),})) as any;@@ -1035,8 +1043,7 @@ describe('GatewayActionImpl', () => {const interruptTaskSpy = vi.mocked(aiAgentService.interruptTask).mockResolvedValue({ operationId: 'server-op-cancel', success: true });-- vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ const persistedResult = {agentId: 'agent-1',assistantMessageId: 'ast-1',autoStarted: true,@@ -1049,36 +1056,46 @@ describe('GatewayActionImpl', () => {token: 'test-token',topicId: 'topic-1',userMessageId: 'usr-1',+ } as const;+ let resolvePersistence!: (value: typeof persistedResult) => void;+ vi.mocked(aiAgentService.execAgentTask).mockReturnValue(+ new Promise((resolve) => {+ resolvePersistence = resolve;+ }),+ );+ vi.mocked(messageService.getMessages).mockRejectedValueOnce(new Error('refresh failed'));++ const execution = action.executeGatewayAgent({+ context: { agentId: 'agent-1', topicId: 'topic-1', threadId: null, scope: 'main' },+ message: 'Hello',+ onMessageAccepted,+ parentOperationId: 'parent-send-msg-op',});+ await vi.waitFor(() => expect(aiAgentService.execAgentTask).toHaveBeenCalledOnce());+ controller.abort('user cancelled');+ resolvePersistence(persistedResult);- await expect(- action.executeGatewayAgent({- context: { agentId: 'agent-1', topicId: 'topic-1', threadId: null, scope: 'main' },- message: 'Hello',- parentOperationId: 'parent-send-msg-op',- }),- ).rejects.toBeDefined();+ await expect(execution).resolves.toEqual(persistedResult);- // The signal must be forwarded into execAgentTask so the fetch itself- // is aborted in-flight when cancel comes during the round-trip.expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(expect.anything(),expect.objectContaining({ signal: controller.signal }),);-// Server task was created before the signal flipped — best-effort// interrupt must fire so the agent run stops server-side.- expect(interruptTaskSpy).toHaveBeenCalledWith({- operationId: 'server-op-cancel',- topicId: 'topic-1',- });-- // No child op, no message association, no WS connect, no parent complete- // — the cancel must short-circuit the whole hand-off.+ await vi.waitFor(() =>+ expect(interruptTaskSpy).toHaveBeenCalledWith({+ operationId: 'server-op-cancel',+ topicId: 'topic-1',+ }),+ );+ expect(onMessageAccepted).toHaveBeenCalledOnce();+ expect(replaceMessages).not.toHaveBeenCalled();+ expect(moveQueuedMessages).toHaveBeenCalledOnce();expect(startOperation).not.toHaveBeenCalled();expect(associateMessageWithOperation).not.toHaveBeenCalled();expect(connectToGateway).not.toHaveBeenCalled();- expect(completeOperation).not.toHaveBeenCalled();+ expect(completeOperation).toHaveBeenCalledWith('parent-send-msg-op');});it('registers a cancel handler that calls aiAgentService.interruptTask with the server operationId', async () => {@@ -1097,6 +1114,7 @@ describe('GatewayActionImpl', () => {connectToGateway: vi.fn(),internal_dispatchTopic: vi.fn(),moveQueuedMessages: vi.fn(),+ moveVoiceMessages: vi.fn(),onOperationCancel,replaceMessages: vi.fn(),startOperation,@@ -1185,6 +1203,7 @@ describe('GatewayActionImpl', () => {connectToGateway,internal_dispatchTopic: internalDispatchTopic,moveQueuedMessages: vi.fn(),+ moveVoiceMessages: vi.fn(),onOperationCancel: vi.fn(),startOperation,updateTopicStatus: vi.fn(),@@ -1272,6 +1291,7 @@ describe('GatewayActionImpl', () => {connectToGateway,internal_dispatchTopic: internalDispatchTopic,moveQueuedMessages: vi.fn(),+ moveVoiceMessages: vi.fn(),onOperationCancel: vi.fn(),startOperation,updateTopicStatus: vi.fn(),@@ -1362,6 +1382,7 @@ describe('GatewayActionImpl', () => {connectToGateway,internal_dispatchTopic: internalDispatchTopic,moveQueuedMessages: vi.fn(),+ moveVoiceMessages: vi.fn(),onOperationCancel: vi.fn(),startOperation,updateTopicStatus: vi.fn(),diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 23ddb462e26..f3bbb483127 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -6,6 +6,7 @@ import { formatSelectedSkillsContext, formatSelectedToolsContext } from '@lobechimport { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';import { chainCompressContext } from '@lobechat/prompts';import type {+ ChatAudioItem,ChatImageItem,ChatThreadType,ChatTopicMetadata,@@ -73,6 +74,7 @@ import {getCompressionCandidateMessageIds,hasRunningCompressionOperation,} from '@/store/chat/utils/compression';+import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { snapshotAgentModel } from '@/store/chat/utils/snapshotAgentModel';import { topicMapKey } from '@/store/chat/utils/topicMapKey';@@ -179,6 +181,14 @@ const createAbortError = () =>const QUEUE_BLOCKING_OPERATION_TYPE_SET = new Set<OperationType>(QUEUE_BLOCKING_OPERATION_TYPES);+const throwIfSendAborted = (signal?: AbortSignal) => {+ if (!signal?.aborted) return;++ throw signal.reason instanceof Error+ ? signal.reason+ : new DOMException('Message send was cancelled', 'AbortError');+};+const attachSendTimeMetadataToUserMessage = (messages: UIChatMessage[],userMessageId: string,@@ -263,11 +273,47 @@ export class ConversationLifecycleActionImpl {contextSelections,inputEditor,messages: inputMessages,+ optimisticUserMessageId,parentId: inputParentId,pageSelections,onPreflightFailure,+ onMessageAccepted,+ onMessagePersisted,onTopicCreated,+ preserveComposer,+ signal,}: SendMessageWithContextParams): Promise<SendMessageResult | undefined> => {+ throwIfSendAborted(signal);++ let detachCallerAbort = () => {};+ let hasNotifiedMessageAccepted = false;+ const detachUnacceptedCallerAbort = () => {+ if (!hasNotifiedMessageAccepted) detachCallerAbort();+ };+ const notifyMessageAccepted = () => {+ if (hasNotifiedMessageAccepted) return;++ hasNotifiedMessageAccepted = true;+ detachCallerAbort();+ try {+ onMessageAccepted?.();+ } catch (error) {+ console.error('[sendMessage] onMessageAccepted callback failed:', error);+ }+ };+ let hasNotifiedMessagePersisted = false;+ const notifyMessagePersisted = () => {+ if (hasNotifiedMessagePersisted) return;++ notifyMessageAccepted();+ hasNotifiedMessagePersisted = true;+ try {+ onMessagePersisted?.();+ } catch (error) {+ console.error('[sendMessage] onMessagePersisted callback failed:', error);+ }+ };+let editorData = inputEditorData;const { executeClientAgent, mainInputEditor } = this.#get();const targetInputEditor = inputEditor ?? mainInputEditor;@@ -517,6 +563,8 @@ export class ConversationLifecycleActionImpl {const requestTrigger = (metadata as Pick<MessageMetadata, 'trigger'> | undefined)?.trigger;const requestMetadata = requestTrigger ? { trigger: requestTrigger } : undefined;+ throwIfSendAborted(signal);+const hasFile = !!fileIdList && fileIdList.length > 0;// if message is empty or no files, then stop@@ -552,12 +600,35 @@ export class ConversationLifecycleActionImpl {].filter((key) => key !== currentContextKey): []),];- const findRunningBlockingOp = (key: string) =>- (this.#get().operationsByContext[key] || [])- .map((id) => this.#get().operations[id])+ const findRunningBlockingOp = (key: string) => {+ const contextOpIds = this.#get().operationsByContext[key] || [];+ const ownVoiceUploadIndex = optimisticUserMessageId+ ? contextOpIds.findIndex((id) => {+ const operation = this.#get().operations[id];+ return (+ operation?.type === 'uploadVoiceMessage' &&+ operation.context.messageId === optimisticUserMessageId+ );+ })+ : -1;++ return contextOpIds+ .map((id, index) => ({ index, operation: this.#get().operations[id] })).find(- (op) => op && QUEUE_BLOCKING_OPERATION_TYPE_SET.has(op.type) && op.status === 'running',- );+ ({ index, operation }) =>+ operation &&+ QUEUE_BLOCKING_OPERATION_TYPE_SET.has(operation.type) &&+ operation.status === 'running' &&+ // The upload transaction calls this lifecycle after its own binary is ready. It must+ // not queue behind itself (or a later voice upload); earlier voice uploads still block.+ !(+ optimisticUserMessageId &&+ operation.type === 'uploadVoiceMessage' &&+ (operation.context.messageId === optimisticUserMessageId ||+ (ownVoiceUploadIndex >= 0 && index > ownVoiceUploadIndex))+ ),+ )?.operation;+ };let queueTargetKey = currentContextKey;let runningQueueBlockingOp: ReturnType<typeof findRunningBlockingOp>;for (const key of queueCandidateKeys) {@@ -567,12 +638,12 @@ export class ConversationLifecycleActionImpl {break;}}-if (runningQueueBlockingOp) {// Snapshot file previews so the tray can render thumbnails AND the- // resumed sendMessage can rebuild imageList/videoList — by the time+ // resumed sendMessage can rebuild audioList/imageList/videoList — by the time// we drain, chatUploadFileList has long been cleared.const filesPreview: QueuedFile[] = (files ?? []).map((f) => ({+ audioMetadata: f.audioMetadata,id: f.id,mimeType: f.file?.type ?? '',name: f.file?.name ?? f.id,@@ -594,6 +665,7 @@ export class ConversationLifecycleActionImpl {},runningQueueBlockingOp.id,);+ notifyMessageAccepted();return;}@@ -603,6 +675,7 @@ export class ConversationLifecycleActionImpl {fileList: fileIdList,metadata: userMessageMetadata,});+ notifyMessagePersisted();return;}@@ -610,9 +683,12 @@ export class ConversationLifecycleActionImpl {// Use provided messages or query from store// For /newTopic from existing topic, start with empty message list (fresh topic)const contextKey = messageMapKey(context);- const messages = forceNewTopicFromExisting- ? []- : (inputMessages ?? displayMessageSelectors.getDisplayMessagesByKey(contextKey)(this.#get()));+ const messages = (+ forceNewTopicFromExisting+ ? []+ : (inputMessages ??+ displayMessageSelectors.getDisplayMessagesByKey(contextKey)(this.#get()))+ ).filter((item) => !isLocalOnlyMessage(item));// Historical callback/tool sibling forks are rendered with the recovered// taskCallback card as supplemental history. It is not the active// conversational tail: using it here lets findLastMessageId descend into@@ -640,7 +716,7 @@ export class ConversationLifecycleActionImpl {// re-keyed when the response lands. That is what keeps the conversation's// identity — and therefore the mounted message list — stable across the// whole send.- const tempId = generateEntityId('messages');+ const tempId = optimisticUserMessageId ?? generateEntityId('messages');const tempAssistantId = generateEntityId('messages');const { operationId, abortController } = this.#get().startOperation({type: 'sendMessage',@@ -651,6 +727,40 @@ export class ConversationLifecycleActionImpl {inThread: !!operationContext.threadId,},});+ // Voice recording starts before a first-send topic exists, so its upload+ // transaction and local row initially live in the legacy `_new` bucket.+ // Adopt the client-minted topic context before looking up that row; otherwise+ // the formal send would create a duplicate in the minted bucket.+ this.#get().moveVoiceMessages(context, operationContext);++ const cleanupTempMessages = (options?: { preserveOptimisticUser?: boolean }) => {+ const ids = options?.preserveOptimisticUser ? [tempAssistantId] : [tempId, tempAssistantId];+ this.#get().internal_dispatchMessage({ ids, type: 'deleteMessages' }, { operationId });+ };+ const restoreUnacceptedVoiceMessageContext = () => {+ if (!optimisticUserMessageId || hasNotifiedMessageAccepted) return;++ // The minted topic is rolled back on a pre-accept failure. Return the+ // retry-owned upload operation and playable local row to the visible+ // `_new` conversation instead of leaving them under a deleted topic id.+ this.#get().moveVoiceMessages(operationContext, context);+ };+ if (signal) {+ const cancelFromCaller = () => {+ const operation = this.#get().operations[operationId];+ if (hasNotifiedMessageAccepted || operation?.status !== 'running') return;++ this.#get().cancelOperation(operationId, 'Caller cancelled before message acceptance');+ };++ if (signal.aborted) {+ cancelFromCaller();+ } else {+ signal.addEventListener('abort', cancelFromCaller, { once: true });+ detachCallerAbort = () => signal.removeEventListener('abort', cancelFromCaller);+ }+ }+ throwIfSendAborted(signal);// Shared run lifecycle for the post-persist topic-title hook. Built once here// so all three runtime branches fire the SAME `afterUserMessagePersisted`@@ -685,26 +795,64 @@ export class ConversationLifecycleActionImpl {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,+ }));- // use optimistic update to avoid the slow waiting (now with operationId for correct context)- this.#get().optimisticCreateTmpMessage(- {- content: message,- editorData: editorData ?? undefined,- // if message has attached with files, then add files to message and the agent- files: fileIdList,- role: 'user',- agentId: operationContext.agentId,- // if there is topicId, then add topicId to message- topicId: operationContext.topicId ?? undefined,- threadId: operationContext.threadId ?? undefined,- imageList: tempImages.length > 0 ? tempImages : undefined,- videoList: tempVideos.length > 0 ? tempVideos : undefined,- // Pass metadata for immediate display- metadata: userMessageMetadata,- },- { operationId, tempMessageId: tempId },+ const optimisticUserMessage = {+ content: message,+ editorData: editorData ?? undefined,+ // if message has attached with files, then add files to message and the agent+ files: fileIdList,+ role: 'user' as const,+ agentId: operationContext.agentId,+ // 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,+ // Pass metadata for immediate display+ metadata: userMessageMetadata,+ };+ const operationMessageKey = messageMapKey(+ this.#get().internal_getConversationContext({ operationId }),+ );+ const existingOptimisticUserMessage = this.#get().dbMessagesMap[operationMessageKey]?.find(+ (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.+ if (existingOptimisticUserMessage) {+ this.#get().internal_dispatchMessage(+ {+ id: tempId,+ type: 'updateMessage',+ value: {+ ...optimisticUserMessage,+ groupId: operationContext.groupId,+ metadata: {+ ...existingOptimisticUserMessage.metadata,+ ...userMessageMetadata,+ scope: existingOptimisticUserMessage.metadata?.scope,+ },+ },+ },+ { operationId },+ );+ } else {+ // use optimistic update to avoid the slow waiting (now with operationId for correct context)+ this.#get().optimisticCreateTmpMessage(optimisticUserMessage, {+ operationId,+ tempMessageId: tempId,+ });+ }this.#get().optimisticCreateTmpMessage({content: LOADING_FLAT,@@ -989,7 +1137,9 @@ export class ConversationLifecycleActionImpl {}// Store editor state in operation metadata for cancel restoration- const jsonState = inputEditorData ?? targetInputEditor?.getJSONState();+ const jsonState = preserveComposer+ ? undefined+ : (inputEditorData ?? targetInputEditor?.getJSONState());this.#get().updateOperationMetadata(operationId, {inputEditorTempState: jsonState,inputSendErrorMsg: undefined,@@ -1010,6 +1160,7 @@ export class ConversationLifecycleActionImpl {// Persist messages to DB first (same as client mode)let heteroData: SendMessageServerResponse | undefined;try {+ throwIfSendAborted(signal);heteroData = await aiChatService.sendMessageInServer({agentId: operationContext.agentId,@@ -1063,18 +1214,27 @@ export class ConversationLifecycleActionImpl {);} catch (e) {console.error('[HeterogeneousAgent] Failed to persist messages:', e);- this.#get().failOperation(operationId, {- message: e instanceof Error ? e.message : 'Unknown error',- type: 'HeterogeneousAgentError',- });+ if (this.#get().operations[operationId]?.status !== 'cancelled') {+ this.#get().failOperation(operationId, {+ message: e instanceof Error ? e.message : 'Unknown error',+ type: 'HeterogeneousAgentError',+ });+ }+ cleanupTempMessages({ preserveOptimisticUser: Boolean(optimisticUserMessageId) });+ detachUnacceptedCallerAbort();rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');+ restoreUnacceptedVoiceMessageContext();return;}if (!heteroData) {+ cleanupTempMessages({ preserveOptimisticUser: Boolean(optimisticUserMessageId) });+ detachUnacceptedCallerAbort();rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');+ restoreUnacceptedVoiceMessageContext();return;}+ notifyMessageAccepted();// Update context with server-created topicId. Once the server has returned a// persisted topic, the hetero stream must target the real topic bucket; keeping@@ -1099,6 +1259,7 @@ export class ConversationLifecycleActionImpl {messageMapKey({ ...operationContext, topicId: null }),heteroMessageKey,);+ this.#get().moveVoiceMessages(operationContext, heteroContext);const heteroMessages = heteroResponseMeta.__isPartialMessages? mergePartialPersistedMessages(this.#get().messagesMap[heteroMessageKey] || [],@@ -1174,6 +1335,21 @@ export class ConversationLifecycleActionImpl {// Complete sendMessage operation, start ACP execution as child operationthis.#get().completeOperation(operationId);+ notifyMessagePersisted();++ // Clear editor temp state — the user's message is already persisted, so+ // a later Stop click must NOT restore it into the input (would feel like+ // the app re-sent the message). Client/Gateway paths clear this at+ // line 684-686 after `sendMessageInServer` resolves, but the hetero+ // branch returns early (line 498) and never reaches that clear.+ this.#get().updateOperationMetadata(operationId, { inputEditorTempState: null });++ if (abortController.signal.aborted) {+ return {+ assistantMessageId: heteroData.assistantMessageId,+ userMessageId: heteroData.userMessageId,+ };+ }// Topic title: hetero used to set only a sliced placeholder// title on new topics — upgrade it to the LLM summary via the shared hook@@ -1191,13 +1367,6 @@ export class ConversationLifecycleActionImpl {}).catch(console.error);- // Clear editor temp state — the user's message is already persisted, so- // a later Stop click must NOT restore it into the input (would feel like- // the app re-sent the message). Client/Gateway paths clear this at- // line 684-686 after `sendMessageInServer` resolves, but the hetero- // branch returns early (line 498) and never reaches that clear.- this.#get().updateOperationMetadata(operationId, { inputEditorTempState: null });-// Sidebar "running" spinner for hetero runs is driven off the persisted// `topic.status === 'running'` (written by the executor's writeTopicStatus,// and bucketed by resolveStatusBucket) plus the running@@ -1337,6 +1506,7 @@ export class ConversationLifecycleActionImpl {fileIds: fileIdList,message,metadata: requestMetadata,+ onMessageAccepted: notifyMessageAccepted,parentOperationId: operationId,optimisticTopic,// Forward @-mentioned tool ids so the server runtime enables them for@@ -1357,6 +1527,7 @@ export class ConversationLifecycleActionImpl {// messages with the server's real IDs.tempMessageIds: [tempAssistantId],});+ const cancelledAfterPersistence = abortController.signal.aborted;// Topic title: gateway-created topics had no LLM-summarized// title. executeGatewayAgent has already replaced messages + switched to@@ -1370,22 +1541,26 @@ export class ConversationLifecycleActionImpl {if (optimisticTopic && optimisticTopicActive) {optimisticTopicActive = false;}- void sendRunLifecycle- .afterUserMessagePersisted({- assistantMessageId: result.assistantMessageId,- context: { ...operationContext, topicId: result.topicId },- isCreateNewTopic: willCreateNewTopic,- operationId,- runId: operationId,- runScope: sendRunScope,- runtimeType,- topicId: result.topicId,- })- .catch(console.error);+ if (!cancelledAfterPersistence) {+ void sendRunLifecycle+ .afterUserMessagePersisted({+ assistantMessageId: result.assistantMessageId,+ context: { ...operationContext, topicId: result.topicId },+ isCreateNewTopic: willCreateNewTopic,+ operationId,+ runId: operationId,+ runScope: sendRunScope,+ runtimeType,+ topicId: result.topicId,+ })+ .catch(console.error);+ }} else {rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');}+ notifyMessagePersisted();+return {assistantMessageId: result.assistantMessageId,userMessageId: result.userMessageId,@@ -1396,7 +1571,12 @@ export class ConversationLifecycleActionImpl {// server task. Don't clobber that with 'failed'.const op = this.#get().operations[operationId];if (op?.status === 'cancelled') {+ cleanupTempMessages({+ preserveOptimisticUser: Boolean(optimisticUserMessageId && !hasNotifiedMessageAccepted),+ });+ detachUnacceptedCallerAbort();rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');+ restoreUnacceptedVoiceMessageContext();return;}@@ -1405,7 +1585,12 @@ export class ConversationLifecycleActionImpl {message: e instanceof Error ? e.message : 'Unknown error',type: 'GatewayError',});+ cleanupTempMessages({+ preserveOptimisticUser: Boolean(optimisticUserMessageId && !hasNotifiedMessageAccepted),+ });+ detachUnacceptedCallerAbort();rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');+ restoreUnacceptedVoiceMessageContext();return;}}@@ -1418,6 +1603,7 @@ export class ConversationLifecycleActionImpl {);try {+ throwIfSendAborted(signal);const { model, provider } = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());const topicId = operationContext.topicId;@@ -1501,6 +1687,7 @@ export class ConversationLifecycleActionImpl {},abortController,);+ notifyMessageAccepted();const responseMeta = data as SendMessageServerResponseMeta;// Use created topicId/threadId if available, otherwise use original from contextlet finalTopicId = data.topicId ?? operationContext.topicId;@@ -1584,6 +1771,7 @@ export class ConversationLifecycleActionImpl {messageMapKey({ ...operationContext, topicId: null }),finalMessageKey,);+ this.#get().moveVoiceMessages(operationContext, finalContext);const persistedMessages = attachSendTimeMetadataToUserMessage(data.messages,data.userMessageId,@@ -1622,12 +1810,14 @@ export class ConversationLifecycleActionImpl {console.error(e);rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');// Fail operation on error- this.#get().failOperation(operationId, {- type: e instanceof Error ? e.name : 'unknown_error',- message: e instanceof Error ? e.message : 'Unknown error',- });+ if (this.#get().operations[operationId]?.status !== 'cancelled') {+ this.#get().failOperation(operationId, {+ type: e instanceof Error ? e.name : 'unknown_error',+ message: e instanceof Error ? e.message : 'Unknown error',+ });+ }- if (e instanceof TRPCClientError) {+ if (!preserveComposer && e instanceof TRPCClientError) {const isAbort = e.message.includes('aborted') || e.name === 'AbortError';// Check if error is due to cancellationif (!isAbort) {@@ -1646,12 +1836,10 @@ export class ConversationLifecycleActionImpl {// under the ids the server persisted, so `replaceMessages` reconciled them// in place — and for a brand-new topic `switchTopic({ clearNewKey: true })`// drops the now-empty `_new` bucket anyway.- if (!data) {- this.#get().internal_dispatchMessage(- { type: 'deleteMessages', ids: [tempId, tempAssistantId] },- { operationId },- );- }+ if (!data)+ cleanupTempMessages({+ preserveOptimisticUser: Boolean(optimisticUserMessageId && !hasNotifiedMessageAccepted),+ });}// Clear editor temp state after message created@@ -1660,12 +1848,25 @@ export class ConversationLifecycleActionImpl {}if (!data) {+ detachUnacceptedCallerAbort();rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');+ restoreUnacceptedVoiceMessageContext();return;}rollbackOptimisticTopic('sendMessage/rollbackUnresolvedOptimisticTopic');+ if (abortController.signal.aborted) {+ this.#get().completeOperation(operationId);+ notifyMessagePersisted();++ return {+ assistantMessageId: data.assistantMessageId,+ createdThreadId: data.createdThreadId,+ createdTopicId: isCreatedTopicResponse(data) ? data.topicId : undefined,+ userMessageId: data.userMessageId,+ };+ }// Topic title auto-generation, now via the shared `afterUserMessagePersisted`// hook. The client passes its freshly-created `data.messages`// (not yet in the store under the real topicId); gateway/hetero call the same@@ -1684,10 +1885,6 @@ export class ConversationLifecycleActionImpl {}).catch(console.error);- // Complete sendMessage operation here - message creation is done- // execAgentRuntime is a separate operation (child) that handles AI response generation- this.#get().completeOperation(operationId);-const execContext = {...operationContext,// The persisted topic/thread is now the identity of this conversation.@@ -1744,9 +1941,20 @@ export class ConversationLifecycleActionImpl {// ── AI execution (client mode) ──{+ let sendOperationHandedOff = false;+ const handoffSendOperation = () => {+ if (sendOperationHandedOff) return;++ sendOperationHandedOff = true;+ // Keep the send operation running until the child runtime is ready to start. This makes+ // `_new` → persisted-topic migration one continuous queue barrier for follow-up turns.+ this.#get().completeOperation(operationId);+ notifyMessagePersisted();+ };+try {if (directMentionRoute) {- await executeDirectMention(+ const directMentionRun = executeDirectMention({context: execContext,instruction: message,@@ -1757,10 +1965,12 @@ export class ConversationLifecycleActionImpl {},this.#get,);+ handoffSendOperation();+ await directMentionRun;} else {- const displayMessages = displayMessageSelectors.getDisplayMessagesByKey(- messageMapKey(execContext),- )(this.#get());+ const displayMessages = displayMessageSelectors+ .getDisplayMessagesByKey(messageMapKey(execContext))(this.#get())+ .filter((item) => !isLocalOnlyMessage(item));// When agents are @mentioned, inject a slim callAgent-only manifest// so the AI can delegate directly without activating the full agent-management tool@@ -1789,7 +1999,7 @@ export class ConversationLifecycleActionImpl {agentRuntimeInitialContext,);- await executeClientAgent({+ const clientRun = executeClientAgent({context: execContext,initialContext: mergedAgentRuntimeInitialContext,metadata: requestMetadata,@@ -1801,6 +2011,8 @@ export class ConversationLifecycleActionImpl {skipCreateFirstMessage: true,userMessageId: data.userMessageId,});+ handoffSendOperation();+ await clientRun;}const userFiles = dbMessageSelectors@@ -1813,6 +2025,8 @@ export class ConversationLifecycleActionImpl {}} catch (e) {console.error(e);+ } finally {+ handoffSendOperation();}}diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex f1d6a9603f1..5be68c5b03a 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -426,6 +426,8 @@ export class GatewayActionImpl {messageContext?: ConversationContext;/** Request metadata carried from the originating user message. */metadata?: Pick<MessageMetadata, 'trigger'>;+ /** Called as soon as phase-1 returns with a persisted user message. */+ onMessageAccepted?: () => void;/** Called when the gateway session completes (agent finished running) */onComplete?: () => void;/** Temporary sidebar topic inserted by sendMessage before the server creates the real topic. */@@ -494,6 +496,7 @@ export class GatewayActionImpl {messageContext = executionContext,metadata,onComplete,+ onMessageAccepted,optimisticTopic,parentMessageId,parentOperationId,@@ -550,10 +553,9 @@ export class GatewayActionImpl {// Honour user-initiated cancel during phase-1 init: while we await the// execAgentTask round-trip the caller's loading state (e.g. `sendMessage`)// is still running, so the ChatInput stop button is active. Forward the- // signal into the request so the fetch aborts in-flight, and re-check- // afterwards in case cancel arrived just after the request resolved (the- // server task is then already created — best-effort interrupt it before- // bailing out, otherwise the agent run continues server-side).+ // signal into the request so the fetch aborts in-flight. If the server has+ // already persisted the turn, interrupt generation but still reconcile the+ // message locally before returning.const abortSignal = parentOperationId? this.#get().getOperationAbortSignal(parentOperationId): undefined;@@ -564,6 +566,10 @@ export class GatewayActionImpl {allowList: toolInterventionSelectors.allowList(useUserStore.getState()),};+ if (abortSignal?.aborted) {+ throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');+ }+const result = await aiAgentService.execAgentTask({agentId: executionContext.agentId,@@ -625,16 +631,46 @@ export class GatewayActionImpl {{ signal: abortSignal },);- if (abortSignal?.aborted) {- // Cancel arrived after execAgentTask resolved — server task exists.- aiAgentService- .interruptTask({ operationId: result.operationId, topicId: result.topicId })- .catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));- throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');+ // Persistence is the ownership boundary. Notify before later UI synchronization awaits and+ // before handling a late abort so callers never delete a file already attached server-side.+ try {+ onMessageAccepted?.();+ } catch (error) {+ console.error('[Gateway] onMessageAccepted callback failed:', error);+ }++ let hasInterruptedAfterPersistence = false;+ const interruptIfCancelledAfterPersistence = () => {+ if (!abortSignal?.aborted) return false;++ if (!hasInterruptedAfterPersistence) {+ hasInterruptedAfterPersistence = true;+ // Cancel arrived after execAgentTask resolved — server task exists. Interrupt generation,+ // but keep reconciling the persisted message before returning to the caller.+ aiAgentService+ .interruptTask({ operationId: result.operationId, topicId: result.topicId })+ .catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));+ }++ return true;+ };+ let cancelledAfterPersistence = interruptIfCancelledAfterPersistence();++ // Keep execution identity separate from the conversation bucket that owns+ // the streamed messages. They differ for callAgent/sub-agent runs.+ const resolvedExecutionContext = { ...executionContext, topicId: result.topicId };+ const resolvedMessageContext = { ...messageContext, topicId: result.topicId };+ this.#get().moveVoiceMessages(messageContext, resolvedMessageContext);++ if (!isCreateNewTopic && cancelledAfterPersistence) {+ try {+ const messages = await messageService.getMessages(resolvedMessageContext);+ this.#get().replaceMessages(messages, { context: resolvedMessageContext });+ } catch {+ /* non-critical */+ }}- // If server created a new topic, fetch messages first then switch topic- // (same pattern as client mode: replaceMessages before switchTopic to avoid skeleton flash)if (isCreateNewTopic && result.topicId) {// Topic created successfully — now safe to clear the pending repo selection.if (messageContext.agentId) consumePendingTopicRepos(messageContext.agentId);@@ -657,9 +693,8 @@ export class GatewayActionImpl {);}try {- const newContext = { ...messageContext, topicId: result.topicId };- const messages = await messageService.getMessages(newContext);- this.#get().replaceMessages(messages, { context: newContext });+ const messages = await messageService.getMessages(resolvedMessageContext);+ this.#get().replaceMessages(messages, { context: resolvedMessageContext });} catch {/* non-critical */}@@ -676,19 +711,8 @@ export class GatewayActionImpl {this.#get().refreshTopic().catch((err) => console.error('[Gateway] refreshTopic after topic creation failed:', err));-- if (abortSignal?.aborted) {- aiAgentService- .interruptTask({ operationId: result.operationId, topicId: result.topicId })- .catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));- throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');- }}- // Keep execution identity separate from the conversation bucket that owns- // the streamed messages. They differ for callAgent/sub-agent runs.- const resolvedExecutionContext = { ...executionContext, topicId: result.topicId };- const resolvedMessageContext = { ...messageContext, topicId: result.topicId };this.#get().moveQueuedMessages(messageMapKey(messageContext),messageMapKey(resolvedMessageContext),@@ -700,6 +724,12 @@ export class GatewayActionImpl {messageMapKey({ ...messageContext, topicId: null }),messageMapKey(resolvedMessageContext),);+ cancelledAfterPersistence = interruptIfCancelledAfterPersistence() || cancelledAfterPersistence;++ if (cancelledAfterPersistence) {+ if (parentOperationId) this.#get().completeOperation(parentOperationId);+ return result;+ }if (result.topicId) {void this.#get().updateTopicStatus?.({diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.tsindex 7816f6eb98d..30b4efa5b62 100644--- a/src/store/chat/slices/message/action.test.ts+++ b/src/store/chat/slices/message/action.test.ts@@ -14,6 +14,7 @@ import {runMessageListQuery,} from '@/services/message/cache';import { topicService } from '@/services/topic';+import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useChatStore } from '../../store';@@ -68,6 +69,7 @@ const mockState = {refreshTopic: vi.fn(),internal_coreProcessMessage: vi.fn(),saveToTopic: vi.fn(),+ voiceMessageUploadMap: {},};beforeEach(() => {@@ -1299,6 +1301,121 @@ describe('chatMessage actions', () => {expect(isMessageListServerVerified(context)).toBe(false);});+ it('keeps an active local voice row in memory without writing it to SWR', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'voice-agent', topicId: 'voice-topic' };+ const key = messageMapKey(context);+ const persistedMessage = {+ content: 'persisted',+ createdAt: 1,+ id: 'persisted-message',+ role: 'assistant',+ updatedAt: 1,+ } as any;+ const localVoiceMessage = {+ audioList: [{ id: 'local-audio', url: 'blob:voice-preview' }],+ content: '',+ createdAt: 2,+ id: 'tmp-voice-message',+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ updatedAt: 2,+ } as any;++ act(() => {+ useChatStore.setState({+ dbMessagesMap: { [key]: [localVoiceMessage] },+ voiceMessageUploadMap: {+ [localVoiceMessage.id]: { progress: 50, status: 'uploading' },+ },+ });+ });++ await act(async () => {+ result.current.replaceMessages([persistedMessage], { context });+ });++ expect(result.current.dbMessagesMap[key]).toEqual([persistedMessage, localVoiceMessage]);+ expect(mutate).toHaveBeenCalledWith(messageListKey(context), [persistedMessage], {+ revalidate: false,+ });+ });++ it('keeps an earlier local voice row ahead of a later server snapshot message', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'voice-order-agent', topicId: 'voice-order-topic' };+ const key = messageMapKey(context);+ const localVoiceMessage = {+ audioList: [{ id: 'local-audio', url: 'blob:voice-preview' }],+ content: '',+ createdAt: 1,+ id: 'tmp-voice-message',+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ updatedAt: 1,+ } as any;+ const laterPersistedMessage = {+ content: 'later text',+ createdAt: 2,+ id: 'persisted-message',+ role: 'user',+ updatedAt: 2,+ } as any;++ act(() => {+ useChatStore.setState({+ dbMessagesMap: { [key]: [localVoiceMessage] },+ voiceMessageUploadMap: {+ [localVoiceMessage.id]: { progress: 50, status: 'uploading' },+ },+ });+ });++ await act(async () => {+ result.current.replaceMessages([laterPersistedMessage], { context });+ });++ expect(result.current.dbMessagesMap[key]).toEqual([localVoiceMessage, laterPersistedMessage]);+ });++ it('drops an inactive local-only row from memory and cache input', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'inactive-voice-agent', topicId: 'inactive-voice-topic' };+ const key = messageMapKey(context);+ const persistedMessage = {+ content: 'persisted',+ createdAt: 1,+ id: 'persisted-message',+ role: 'assistant',+ updatedAt: 1,+ } as any;+ const inactiveLocalMessage = {+ audioList: [{ id: 'local-audio', url: 'blob:stale-preview' }],+ content: '',+ createdAt: 2,+ id: 'tmp-stale-voice-message',+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ updatedAt: 2,+ } as any;++ act(() => {+ useChatStore.setState({+ dbMessagesMap: { [key]: [inactiveLocalMessage] },+ voiceMessageUploadMap: {},+ });+ });++ await act(async () => {+ result.current.replaceMessages([persistedMessage, inactiveLocalMessage], { context });+ });++ expect(result.current.dbMessagesMap[key]).toEqual([persistedMessage]);+ expect(mutate).toHaveBeenCalledWith(messageListKey(context), [persistedMessage], {+ revalidate: false,+ });+ });+it('skips write-through when the conversation has no persisted topic', async () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/message/actions/internals.ts b/src/store/chat/slices/message/actions/internals.tsindex 89d908722d6..b11d28bf779 100644--- a/src/store/chat/slices/message/actions/internals.ts+++ b/src/store/chat/slices/message/actions/internals.ts@@ -1,5 +1,5 @@import { parse } from '@lobechat/conversation-flow';-import { type TraceEventPayloads } from '@lobechat/types';+import { type ConversationContext, type TraceEventPayloads } from '@lobechat/types';import debug from 'debug';import isEqual from 'fast-deep-equal';@@ -20,6 +20,12 @@ const log = debug('lobe-store:message-internals');*/type Setter = StoreSetter<ChatStore>;+type MessageDispatchContext = NonNullable<+ Parameters<ChatStore['internal_getConversationContext']>[0]+> & {+ conversationContext?: ConversationContext;+};+export const messageInternals = (set: Setter, get: () => ChatStore, _api?: unknown) =>new MessageInternalsActionImpl(set, get, _api);@@ -33,12 +39,10 @@ export class MessageInternalsActionImpl {this.#get = get;}- internal_dispatchMessage = (- payload: MessageDispatch,- context?: Parameters<ChatStore['internal_getConversationContext']>[0],- ): void => {+ internal_dispatchMessage = (payload: MessageDispatch, context?: MessageDispatchContext): void => {// Get full conversation context (including scope) from operation or global state- const ctx = this.#get().internal_getConversationContext(context);+ const ctx =+ context?.conversationContext ?? this.#get().internal_getConversationContext(context);log('[internal_dispatchMessage] context: agentId=%s, topicId=%s, threadId=%s, scope=%s',ctx.agentId,diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.tsindex 6a4a1a2ea92..63204a9f011 100644--- a/src/store/chat/slices/message/actions/query.ts+++ b/src/store/chat/slices/message/actions/query.ts@@ -17,6 +17,10 @@ import {} from '@/services/message/cache';import { operationSelectors } from '@/store/chat/slices/operation/selectors';import { type ChatStore } from '@/store/chat/store';+import {+ isLocalOnlyMessage,+ mergeLocalMessagesByCreatedAt,+} from '@/store/chat/utils/localMessages';import { type StoreSetter } from '@/store/types';import { type MessageMapKeyInput } from '../../../utils/messageMapKey';@@ -199,7 +203,31 @@ export class MessageQueryActionImpl {// link while the tool row survives, which would orphan the tool bubble (see// reconcileAssistantToolLinks). Keeps dbMessagesMap (SoT) consistent for// optimistic updates, not just the parsed display.- const reconciled = reconcileAssistantToolLinks(incoming);+ const persistedIncoming = incoming.filter((message) => !isLocalOnlyMessage(message));+ const persistedIds = new Set(persistedIncoming.map((message) => message.id));+ const currentMessages = this.#get().dbMessagesMap[messagesKey] ?? [];+ const voiceMessageUploadMap = this.#get().voiceMessageUploadMap;+ const activeLocalMessagesById = new Map<string, UIChatMessage>();++ // 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.+ for (const message of [...currentMessages, ...incoming]) {+ if (+ isLocalOnlyMessage(message) &&+ voiceMessageUploadMap[message.id] &&+ !persistedIds.has(message.id) &&+ !activeLocalMessagesById.has(message.id)+ ) {+ activeLocalMessagesById.set(message.id, message);+ }+ }++ const persistedReconciled = reconcileAssistantToolLinks(persistedIncoming);+ const reconciled = reconcileAssistantToolLinks(+ mergeLocalMessagesByCreatedAt(persistedReconciled, [...activeLocalMessagesById.values()]),+ );// Get raw messages from dbMessagesMap and apply reducerconst nextDbMap = { ...this.#get().dbMessagesMap, [messagesKey]: reconciled };@@ -217,8 +245,10 @@ export class MessageQueryActionImpl {// Fetch echoes never write through: SWR already holds that exact value, and// at mount the echo is the STALE cached list racing the in-flight// revalidation (see `source` doc above).+ // Local-only rows can contain blob: URLs and have no durable retry owner after reload. Never+ // write them into SWR/IndexedDB; only the server-backed portion belongs in the canonical cache.if (params?.source !== 'fetch') {- this.#writeThroughMessageCache(ctx, messagesKey, reconciled, params?.action);+ this.#writeThroughMessageCache(ctx, messagesKey, persistedReconciled, params?.action);}if (isEqual(nextDbMap, this.#get().dbMessagesMap)) return;diff --git a/src/store/chat/slices/operation/__tests__/selectors.test.ts b/src/store/chat/slices/operation/__tests__/selectors.test.tsindex 8535edd197b..59d33ad0a3e 100644--- a/src/store/chat/slices/operation/__tests__/selectors.test.ts+++ b/src/store/chat/slices/operation/__tests__/selectors.test.ts@@ -28,6 +28,11 @@ describe('Operation Selectors', () => {expect(QUEUE_BLOCKING_OPERATION_TYPES).toContain(type);}});++ it('queues later turns behind voice upload without locking the composer', () => {+ expect(QUEUE_BLOCKING_OPERATION_TYPES).toContain('uploadVoiceMessage');+ expect(INPUT_LOADING_OPERATION_TYPES).not.toContain('uploadVoiceMessage');+ });});describe('getRunningQueueBlockingOperationIds', () => {diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 3ca7cc03be1..c721771ed69 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -16,6 +16,7 @@ import type {export type OperationType =// === Message sending ===| 'sendMessage' // Send message to server+ | 'uploadVoiceMessage' // Upload a local voice recording before dispatching its turn| 'createTopic' // Auto create topic| 'regenerate' // Regenerate message| 'continue' // Continue generation@@ -88,7 +89,8 @@ export type OperationStatus =/*** Operation context - business entity associations* Extends ConversationContext with operation-specific fields- * Captured when Operation is created, never changes afterwards+ * Captured when an operation is created. A temporary `_new` conversation may be rekeyed once+ * the server resolves its persisted topic/thread id; all other context changes create a new op.*/export interface OperationContext extends Partial<ConversationContext> {agentId?: string; // Associated agent ID (specific agent in Group Chat)@@ -223,10 +225,11 @@ export interface Operation {/*** Per-file preview metadata snapshotted at enqueue time so the queue tray can* render thumbnails and the resumed sendMessage can rebuild the optimistic- * imageList/videoList without relying on the global chat upload store (which+ * audioList/imageList/videoList without relying on the global chat upload store (which* is cleared as soon as the user submits).*/export interface QueuedFile {+ audioMetadata?: UploadFileItem['audioMetadata'];id: string;/** MIME type, e.g. `image/png`, `video/mp4`, `application/pdf` */mimeType: string;@@ -237,7 +240,7 @@ export interface QueuedFile {/*** Rebuild `UploadFileItem`-shaped objects from queued previews so the resumed- * `sendMessage` can derive imageList/videoList AND so we can repopulate+ * `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.@@ -248,6 +251,7 @@ export interface QueuedFile {*/export const reconstructUploadFilesFromQueue = (files: QueuedFile[]): UploadFileItem[] =>files.map((f) => ({+ audioMetadata: f.audioMetadata,id: f.id,file: new File([], f.name, { type: f.mimeType }),fileUrl: f.url || undefined,@@ -501,5 +505,9 @@ export const INPUT_LOADING_OPERATION_TYPES: OperationType[] = [export const QUEUE_BLOCKING_OPERATION_TYPES: OperationType[] = [...AI_RUNTIME_OPERATION_TYPES,'sendMessage',+ // A voice turn becomes visible before its binary upload finishes. Keep later composer sends in+ // the normal queue so the model observes the same order as the optimistic transcript. This is+ // intentionally not an INPUT_LOADING operation: recording upload must not lock the composer.+ 'uploadVoiceMessage',...INTERIM_LOADING_OPERATION_TYPES,];diff --git a/src/store/chat/slices/voiceMessage/action.test.ts b/src/store/chat/slices/voiceMessage/action.test.tsnew file mode 100644index 00000000000..312246cf40e--- /dev/null+++ b/src/store/chat/slices/voiceMessage/action.test.ts@@ -0,0 +1,537 @@+import type { ConversationContext, UploadFileItem, VoiceMessageRecording } from '@lobechat/types';+import { act, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { fileService } from '@/services/file';+import { useChatStore } from '@/store/chat/store';+import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { useFileStore } from '@/store/file/store';++import type { SendVoiceMessageParams, VoiceMessageSend, VoiceMessageSendOptions } from './action';++const context = { agentId: 'agent-voice', topicId: 'topic-voice' };+const messagesKey = messageMapKey(context);+const previewUrl = 'blob:voice-preview';+const uploadedResult = { id: 'file-voice', url: 'https://files.test/voice.webm' };++const deferred = <T = void>() => {+ let reject!: (reason?: unknown) => void;+ let resolve!: (value: T | PromiseLike<T>) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ reject = rejectPromise;+ resolve = resolvePromise;+ });++ return { promise, reject, resolve };+};++const createRecording = (): VoiceMessageRecording => {+ const mimeType = 'audio/webm;codecs=opus';++ return {+ codec: 'opus',+ durationMs: 2400,+ file: new File(['voice'], 'voice.webm', { type: mimeType }),+ mimeType,+ waveform: [0.1, 0.5, 0.2],+ };+};++const getMessage = (messageId: string) =>+ useChatStore.getState().dbMessagesMap[messagesKey]?.find((message) => message.id === messageId);++const adoptUploadedFile = (+ file: UploadFileItem,+ messageId: string,+ conversationContext: ConversationContext = context,+) => {+ useChatStore.getState().internal_dispatchMessage(+ {+ id: messageId,+ type: 'updateMessage',+ value: {+ audioList: [+ {+ ...file.audioMetadata,+ alt: file.file.name,+ id: file.id,+ url: file.fileUrl!,+ },+ ],+ },+ },+ { conversationContext },+ );+};++let createdMessageIds: string[] = [];++const startVoiceMessage = ({+ canSend = () => true,+ context: transactionContext = context,+ recording = createRecording(),+ send,+}: Pick<SendVoiceMessageParams, 'send'> & Partial<SendVoiceMessageParams>) => {+ let messageId: string | undefined;++ act(() => {+ messageId = useChatStore.getState().sendVoiceMessage({+ canSend,+ context: transactionContext,+ recording,+ send,+ });+ });++ if (!messageId) throw new Error('Expected voice message to start');+ createdMessageIds.push(messageId);+ return messageId;+};++beforeEach(() => {+ vi.clearAllMocks();+ useChatStore.getState().reset();+ useFileStore.getState().reset();+ useChatStore.setState({+ activeAgentId: context.agentId,+ activeTopicId: context.topicId,+ dbMessagesMap: {},+ messagesMap: {},+ voiceMessageUploadMap: {},+ });+ createdMessageIds = [];++ vi.spyOn(URL, 'createObjectURL').mockReturnValue(previewUrl);+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});+ vi.spyOn(fileService, 'removeUnreferencedFile').mockResolvedValue(undefined);+});++afterEach(async () => {+ for (const messageId of createdMessageIds) {+ await useChatStore.getState().cancelVoiceMessage(messageId);+ }++ vi.restoreAllMocks();+});++describe('VoiceMessageAction', () => {+ it('inserts a local blob audio row immediately and reflects upload progress', async () => {+ const upload = deferred<typeof uploadedResult>();+ let reportProgress: ((progress: number) => void) | undefined;+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress').mockImplementation(+ async ({ onStatusUpdate, uploadId }) => {+ reportProgress = (progress) =>+ onStatusUpdate?.({+ id: uploadId!,+ type: 'updateFile',+ value: { uploadState: { progress, restTime: 1, speed: 2 } },+ });+ return upload.promise;+ },+ );++ const messageId = startVoiceMessage({ send: vi.fn() });+ const message = getMessage(messageId);++ expect(message).toMatchObject({+ audioList: [+ {+ codec: 'opus',+ durationMs: 2400,+ mimeType: 'audio/webm;codecs=opus',+ url: previewUrl,+ },+ ],+ id: messageId,+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ });+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toEqual({+ progress: 0,+ status: 'uploading',+ });++ act(() => reportProgress?.(46));++ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toEqual({+ progress: 46,+ status: 'uploading',+ });+ });++ it('keeps a successful optimistic row when the send lifecycle adopted the uploaded audio', async () => {+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress').mockResolvedValue(uploadedResult);+ const send = vi.fn<VoiceMessageSend>(async (file, { messageId }) => {+ adoptUploadedFile(file, messageId);+ });++ const messageId = startVoiceMessage({ send });++ await waitFor(() => expect(send).toHaveBeenCalledOnce());+ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toBeUndefined(),+ );++ expect(getMessage(messageId)?.audioList?.[0]).toMatchObject({+ id: uploadedResult.id,+ url: uploadedResult.url,+ });+ });++ it('removes a successful local row when queue-like acceptance did not adopt it', async () => {+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress').mockResolvedValue(uploadedResult);+ const send = vi.fn<VoiceMessageSend>().mockResolvedValue(undefined);++ const messageId = startVoiceMessage({ send });++ await waitFor(() => expect(send).toHaveBeenCalledOnce());+ await waitFor(() => expect(getMessage(messageId)).toBeUndefined());+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toBeUndefined();+ });++ it('keeps the same local row after upload failure and retries with the same message id', async () => {+ const upload = vi+ .spyOn(useFileStore.getState(), 'uploadWithProgress')+ .mockRejectedValueOnce(new Error('upload failed'))+ .mockResolvedValueOnce(uploadedResult);+ const send = vi.fn<VoiceMessageSend>(async (file, { messageId }) => {+ adoptUploadedFile(file, messageId);+ });++ const messageId = startVoiceMessage({ send });++ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toMatchObject({+ error: 'upload',+ status: 'failed',+ }),+ );+ expect(getMessage(messageId)).toMatchObject({ id: messageId });++ act(() => useChatStore.getState().retryVoiceMessage(messageId));++ await waitFor(() => expect(send).toHaveBeenCalledOnce());+ expect(upload).toHaveBeenCalledTimes(2);+ expect(upload.mock.calls.map(([params]) => params.uploadId)).toEqual([messageId, messageId]);+ expect(getMessage(messageId)?.audioList?.[0].id).toBe(uploadedResult.id);+ });++ it('restores one playable local row when the send lifecycle deletes it before failing', async () => {+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress').mockResolvedValue(uploadedResult);+ const send = vi.fn<VoiceMessageSend>(async (_file, { messageId }) => {+ useChatStore.getState().internal_dispatchMessage({ id: messageId, type: 'deleteMessage' });+ throw new Error('send failed');+ });++ const messageId = startVoiceMessage({ send });++ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toMatchObject({+ error: 'send',+ status: 'failed',+ }),+ );++ const matchingMessages =+ useChatStore+ .getState()+ .dbMessagesMap[messagesKey]?.filter((message) => message.id === messageId) ?? [];+ expect(matchingMessages).toHaveLength(1);+ expect(matchingMessages[0].audioList?.[0].url).toBe(previewUrl);+ expect(matchingMessages[0].metadata?.scope).toBe(LOCAL_MESSAGE_SCOPE);+ });++ it('deletes the preview and unreferenced upload when cancellation wins an in-flight send', async () => {+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress').mockResolvedValue(uploadedResult);+ const sendResult = deferred();+ let sendSignal: AbortSignal | undefined;+ const send = vi.fn<VoiceMessageSend>((_file, { signal }) => {+ sendSignal = signal;+ return sendResult.promise;+ });+ const removeFile = vi.mocked(fileService.removeUnreferencedFile);++ const messageId = startVoiceMessage({ send });+ await waitFor(() => expect(send).toHaveBeenCalledOnce());++ const cancellation = useChatStore.getState().cancelVoiceMessage(messageId);+ sendResult.reject(new Error('not accepted'));+ await cancellation;++ expect(sendSignal?.aborted).toBe(true);+ expect(getMessage(messageId)).toBeUndefined();+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toBeUndefined();+ expect(URL.revokeObjectURL).toHaveBeenCalledWith(previewUrl);+ expect(removeFile).toHaveBeenCalledOnce();+ expect(removeFile).toHaveBeenCalledWith(uploadedResult.id);+ });++ it('keeps an adopted row and referenced upload when acceptance wins cancellation', async () => {+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress').mockResolvedValue(uploadedResult);+ const sendResult = deferred();+ let uploadedFile: UploadFileItem | undefined;+ const send = vi.fn<VoiceMessageSend>((file) => {+ uploadedFile = file;+ return sendResult.promise;+ });+ const removeFile = vi.mocked(fileService.removeUnreferencedFile);++ const messageId = startVoiceMessage({ send });+ await waitFor(() => expect(uploadedFile).toBeDefined());+ act(() => adoptUploadedFile(uploadedFile!, messageId));++ const cancellation = useChatStore.getState().cancelVoiceMessage(messageId);+ sendResult.resolve();+ await cancellation;++ expect(getMessage(messageId)?.audioList?.[0]).toMatchObject({+ id: uploadedResult.id,+ url: uploadedResult.url,+ });+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toBeUndefined();+ expect(removeFile).not.toHaveBeenCalled();+ });++ it('runs only one upload when retry is triggered twice', async () => {+ const retryUpload = deferred<typeof uploadedResult>();+ const upload = vi+ .spyOn(useFileStore.getState(), 'uploadWithProgress')+ .mockRejectedValueOnce(new Error('upload failed'))+ .mockImplementationOnce(() => retryUpload.promise);+ const send = vi.fn<VoiceMessageSend>().mockResolvedValue(undefined);++ const messageId = startVoiceMessage({ send });+ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]?.status).toBe('failed'),+ );++ act(() => {+ useChatStore.getState().retryVoiceMessage(messageId);+ useChatStore.getState().retryVoiceMessage(messageId);+ });++ expect(upload).toHaveBeenCalledTimes(2);+ retryUpload.resolve(uploadedResult);+ await waitFor(() => expect(send).toHaveBeenCalledOnce());+ expect(upload).toHaveBeenCalledTimes(2);+ });++ it('keeps voice sends in creation order when a later upload finishes first', async () => {+ const firstUpload = deferred<typeof uploadedResult>();+ const secondUpload = deferred<typeof uploadedResult>();+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress')+ .mockImplementationOnce(() => firstUpload.promise)+ .mockImplementationOnce(() => secondUpload.promise);+ const sendOrder: string[] = [];+ const firstSend = vi.fn<VoiceMessageSend>(async (file, { messageId }) => {+ sendOrder.push('first');+ adoptUploadedFile(file, messageId);+ });+ const secondSend = vi.fn<VoiceMessageSend>(async (file, { messageId }) => {+ sendOrder.push('second');+ adoptUploadedFile(file, messageId);+ });++ startVoiceMessage({ send: firstSend });+ startVoiceMessage({ send: secondSend });++ secondUpload.resolve({ id: 'file-second', url: 'https://files.test/second.webm' });+ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap).toEqual(+ expect.objectContaining({+ [createdMessageIds[1]]: expect.objectContaining({ status: 'sending' }),+ }),+ ),+ );+ expect(secondSend).not.toHaveBeenCalled();++ firstUpload.resolve({ id: 'file-first', url: 'https://files.test/first.webm' });++ await waitFor(() => expect(secondSend).toHaveBeenCalledOnce());+ expect(firstSend).toHaveBeenCalledOnce();+ expect(sendOrder).toEqual(['first', 'second']);+ });++ it('moves a waiting voice turn to the created topic without overtaking its predecessor', async () => {+ const sourceContext = { agentId: context.agentId, threadId: null, topicId: null };+ const targetContext = {+ ...sourceContext,+ isNew: false,+ topicId: 'topic-created-from-first-turn',+ };+ const sourceKey = messageMapKey(sourceContext);+ const targetKey = messageMapKey(targetContext);+ const { operationId: predecessorOperationId } = useChatStore.getState().startOperation({+ context: sourceContext,+ type: 'sendMessage',+ });+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress').mockResolvedValue(uploadedResult);+ const canSend = vi.fn(() => true);+ const send = vi.fn<VoiceMessageSend>(async (file, options: VoiceMessageSendOptions) =>+ adoptUploadedFile(file, options.messageId, options.context),+ );++ const messageId = startVoiceMessage({ canSend, context: sourceContext, send });+ const uploadOperationId = useChatStore.getState().operationsByMessage[messageId]?.at(-1);+ if (!uploadOperationId) throw new Error('Expected voice upload operation');++ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]?.status).toBe('sending'),+ );+ expect(send).not.toHaveBeenCalled();++ act(() => useChatStore.getState().moveVoiceMessages(sourceContext, targetContext));++ expect(+ useChatStore.getState().dbMessagesMap[sourceKey]?.find((message) => message.id === messageId),+ ).toBeUndefined();+ expect(+ useChatStore.getState().dbMessagesMap[targetKey]?.find((message) => message.id === messageId),+ ).toMatchObject({ id: messageId, topicId: targetContext.topicId });+ expect(useChatStore.getState().operationsByContext[sourceKey]).not.toContain(uploadOperationId);+ expect(useChatStore.getState().operationsByContext[targetKey]).toContain(uploadOperationId);+ expect(useChatStore.getState().operations[uploadOperationId].context).toMatchObject(+ targetContext,+ );+ expect(send).not.toHaveBeenCalled();++ let runtimeOperationId = '';+ act(() => {+ runtimeOperationId = useChatStore.getState().startOperation({+ context: targetContext,+ parentOperationId: predecessorOperationId,+ type: 'execAgentRuntime',+ }).operationId;+ useChatStore.getState().completeOperation(predecessorOperationId);+ });+ await Promise.resolve();+ expect(send).not.toHaveBeenCalled();++ act(() => useChatStore.getState().completeOperation(runtimeOperationId));++ await waitFor(() => expect(send).toHaveBeenCalledOnce());+ expect(send).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ context: targetContext, messageId }),+ );+ expect(canSend).toHaveBeenLastCalledWith(targetContext);+ });++ it('rechecks the current capability when retrying a long-lived transaction', async () => {+ let supported = true;+ const canSend = vi.fn(() => supported);+ const upload = vi+ .spyOn(useFileStore.getState(), 'uploadWithProgress')+ .mockRejectedValueOnce(new Error('upload failed'))+ .mockResolvedValueOnce(uploadedResult);+ const send = vi.fn<VoiceMessageSend>(async (file, { messageId }) => {+ adoptUploadedFile(file, messageId);+ });+ const messageId = startVoiceMessage({ canSend, send });++ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]?.error).toBe('upload'),+ );++ supported = false;+ act(() => useChatStore.getState().retryVoiceMessage(messageId));+ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toMatchObject({+ error: 'unsupported',+ status: 'failed',+ }),+ );+ expect(send).not.toHaveBeenCalled();++ supported = true;+ act(() => useChatStore.getState().retryVoiceMessage(messageId));++ await waitFor(() => expect(send).toHaveBeenCalledOnce());+ expect(upload).toHaveBeenCalledTimes(2);+ expect(canSend).toHaveBeenLastCalledWith(context);+ });++ it('aborts and disposes private voice transactions before resetting the chat store', async () => {+ const upload = deferred<typeof uploadedResult>();+ let uploadSignal: AbortSignal | undefined;+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress').mockImplementation(+ ({ abortController }) => {+ if (!abortController) throw new Error('Expected upload abort controller');+ uploadSignal = abortController.signal;+ return upload.promise;+ },+ );+ const send = vi.fn<VoiceMessageSend>().mockResolvedValue(undefined);+ const removeFile = vi.mocked(fileService.removeUnreferencedFile);++ const messageId = startVoiceMessage({ send });++ act(() => useChatStore.getState().reset());++ expect(uploadSignal?.aborted).toBe(true);+ expect(useChatStore.getState().voiceMessageUploadMap).toEqual({});+ expect(useChatStore.getState().dbMessagesMap[messagesKey]).toBeUndefined();+ expect(URL.revokeObjectURL).toHaveBeenCalledWith(previewUrl);++ upload.resolve(uploadedResult);++ await waitFor(() => expect(removeFile).toHaveBeenCalledWith(uploadedResult.id));+ expect(send).not.toHaveBeenCalled();+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]).toBeUndefined();+ });++ it('retries with a fresh operation and the captured context after the failed operation is GCd', async () => {+ const retryUpload = deferred<typeof uploadedResult>();+ vi.spyOn(useFileStore.getState(), 'uploadWithProgress')+ .mockRejectedValueOnce(new Error('upload failed'))+ .mockImplementationOnce(() => retryUpload.promise);+ const send = vi.fn<VoiceMessageSend>().mockResolvedValue(undefined);+ const messageId = startVoiceMessage({ send });++ await waitFor(() =>+ expect(useChatStore.getState().voiceMessageUploadMap[messageId]?.status).toBe('failed'),+ );+ const failedOperationId = useChatStore.getState().operationsByMessage[messageId][0];+ const failedOperation = useChatStore.getState().operations[failedOperationId];++ act(() => {+ useChatStore.setState({+ activeAgentId: 'other-agent',+ activeTopicId: 'other-topic',+ operations: {+ ...useChatStore.getState().operations,+ [failedOperationId]: {+ ...failedOperation,+ metadata: { ...failedOperation.metadata, endTime: Date.now() - 60_000 },+ },+ },+ });+ useChatStore.getState().cleanupCompletedOperations(30_000);+ useChatStore+ .getState()+ .internal_dispatchMessage(+ { id: messageId, type: 'deleteMessage' },+ { conversationContext: context },+ );+ useChatStore.getState().retryVoiceMessage(messageId);+ });++ const retryOperationId = useChatStore.getState().operationsByMessage[messageId]?.at(-1);+ expect(retryOperationId).toBeDefined();+ expect(retryOperationId).not.toBe(failedOperationId);+ expect(useChatStore.getState().operations[retryOperationId!].context).toMatchObject(context);+ expect(getMessage(messageId)).toMatchObject({ id: messageId });+ expect(+ useChatStore.getState().dbMessagesMap[+ messageMapKey({+ agentId: 'other-agent',+ topicId: 'other-topic',+ })+ ],+ ).toBeUndefined();++ await useChatStore.getState().cancelVoiceMessage(messageId);+ expect(getMessage(messageId)).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/voiceMessage/action.ts b/src/store/chat/slices/voiceMessage/action.tsnew file mode 100644index 00000000000..acefba4c946--- /dev/null+++ b/src/store/chat/slices/voiceMessage/action.ts@@ -0,0 +1,596 @@+import type {+ ConversationContext,+ CreateMessageParams,+ UploadFileItem,+ VoiceMessageRecording,+} from '@lobechat/types';+import { generateEntityId } from '@lobechat/utils';+import { produce } from 'immer';+import type { StoreApi } from 'zustand';++import { fileService } from '@/services/file';+import { QUEUE_BLOCKING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';+import type { ChatStore } from '@/store/chat/store';+import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { getFileStoreState } from '@/store/file/store';+import type { StoreSetter } from '@/store/types';++import type { VoiceMessageUploadError, VoiceMessageUploadState } from './initialState';+import { VoiceMessageUploadOwnership } from './uploadOwnership';++export interface VoiceMessageSendOptions {+ context: ConversationContext;+ messageId: string;+ signal: AbortSignal;+}++export type VoiceMessageSend = (+ file: UploadFileItem,+ options: VoiceMessageSendOptions,+) => Promise<void>;++export interface SendVoiceMessageParams {+ canSend: (context: ConversationContext) => boolean;+ context: ConversationContext;+ recording: VoiceMessageRecording;+ send: VoiceMessageSend;+}++interface VoiceMessageTransaction extends SendVoiceMessageParams {+ abortController: AbortController;+ discardPromise?: Promise<void>;+ messageId: string;+ operationId: string;+ ownership: VoiceMessageUploadOwnership;+ predecessorOperationIds: string[];+ previewUrl: string;+ runPromise?: Promise<void>;+}++type Setter = StoreSetter<ChatStore>;++const getErrorMessage = (error: unknown) =>+ error instanceof Error ? error.message : 'Unknown voice message error';++export class VoiceMessageActionImpl {+ readonly #api: StoreApi<ChatStore>;+ readonly #get: () => ChatStore;+ readonly #set: Setter;+ readonly #transactions = new Map<string, VoiceMessageTransaction>();++ constructor(set: Setter, get: () => ChatStore, api: StoreApi<ChatStore>) {+ this.#api = api;+ this.#get = get;+ this.#set = set;+ }++ #createLocalMessage = (transaction: VoiceMessageTransaction): CreateMessageParams => ({+ agentId: transaction.context.agentId,+ audioList: [+ {+ alt: transaction.recording.file.name,+ codec: transaction.recording.codec,+ durationMs: transaction.recording.durationMs,+ id: `${transaction.messageId}_audio`,+ mimeType: transaction.recording.mimeType,+ url: transaction.previewUrl,+ },+ ],+ content: '',+ groupId: transaction.context.groupId,+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ threadId: transaction.context.threadId,+ topicId: transaction.context.topicId ?? undefined,+ });++ #deleteLocalMessage = (transaction: VoiceMessageTransaction) => {+ this.#get().internal_dispatchMessage(+ { id: transaction.messageId, type: 'deleteMessage' },+ { conversationContext: transaction.context },+ );+ };++ #deleteUploadState = (messageId: string) => {+ this.#set(+ (state) => {+ if (!state.voiceMessageUploadMap[messageId]) return state;++ const voiceMessageUploadMap = { ...state.voiceMessageUploadMap };+ delete voiceMessageUploadMap[messageId];+ return { voiceMessageUploadMap };+ },+ false,+ `voiceMessage/deleteUploadState/${messageId}`,+ );+ };++ #discardTransaction = (transaction: VoiceMessageTransaction): Promise<void> => {+ if (transaction.discardPromise) return transaction.discardPromise;+ if (this.#transactions.get(transaction.messageId) !== transaction) return Promise.resolve();++ const discardPromise = this.#performDiscardTransaction(transaction);+ transaction.discardPromise = discardPromise;+ return discardPromise;+ };++ #performDiscardTransaction = async (transaction: VoiceMessageTransaction) => {+ const uploadedFile = transaction.ownership.getPending();+ this.#transactions.delete(transaction.messageId);+ transaction.abortController.abort(+ new DOMException('Voice message upload was cancelled', 'AbortError'),+ );++ let discardOutcome: 'accepted' | 'discarded' = 'discarded';+ try {+ discardOutcome = await transaction.ownership.discard();+ } catch (error) {+ console.error('[VoiceMessage] Failed to discard an uploaded voice file:', error);+ }++ if (+ discardOutcome !== 'accepted' ||+ !uploadedFile ||+ this.#shouldDeleteAcceptedPreview(transaction, uploadedFile)+ ) {+ this.#deleteLocalMessage(transaction);+ }+ this.#deleteUploadState(transaction.messageId);+ URL.revokeObjectURL(transaction.previewUrl);+ };++ #ensureLocalMessage = (transaction: VoiceMessageTransaction) => {+ const messages = this.#get().dbMessagesMap[messageMapKey(transaction.context)] ?? [];+ if (messages.some((message) => message.id === transaction.messageId)) return;++ this.#get().internal_dispatchMessage(+ {+ id: transaction.messageId,+ type: 'createMessage',+ value: this.#createLocalMessage(transaction),+ },+ { conversationContext: transaction.context },+ );+ };++ #moveLocalMessage = (+ transaction: VoiceMessageTransaction,+ sourceContext: ConversationContext,+ ) => {+ const sourceKey = messageMapKey(sourceContext);+ const targetKey = messageMapKey(transaction.context);+ const sourceMessage = this.#get().dbMessagesMap[sourceKey]?.find(+ (message) => message.id === transaction.messageId,+ );+ if (!sourceMessage) return;++ const targetMessages = this.#get().dbMessagesMap[targetKey] ?? [];+ if (!targetMessages.some((message) => message.id === transaction.messageId)) {+ this.#get().replaceMessages(+ [+ ...targetMessages,+ {+ ...sourceMessage,+ agentId: transaction.context.agentId,+ groupId: transaction.context.groupId,+ threadId: transaction.context.threadId ?? undefined,+ topicId: transaction.context.topicId ?? undefined,+ },+ ],+ { action: 'voiceMessage/moveLocalMessage', context: transaction.context },+ );+ }++ this.#get().internal_dispatchMessage(+ { id: transaction.messageId, type: 'deleteMessage' },+ { conversationContext: sourceContext },+ );+ };++ #getBlockingOperationIds = (transaction: VoiceMessageTransaction) => {+ const contextKey = messageMapKey(transaction.context);+ const contextOperationIds = this.#get().operationsByContext[contextKey] ?? [];+ const ownIndex = contextOperationIds.indexOf(transaction.operationId);++ const contextBlockers = contextOperationIds.filter((operationId, index) => {+ if (operationId === transaction.operationId) return false;++ const operation = this.#get().operations[operationId];+ if (+ !operation ||+ operation.status !== 'running' ||+ !QUEUE_BLOCKING_OPERATION_TYPES.includes(operation.type)+ )+ return false;++ // A later recording must not make an earlier voice turn wait for it. Earlier voice uploads+ // do block, which gives multiple recordings FIFO semantics even when their upload speeds+ // differ.+ if (operation.type === 'uploadVoiceMessage' && ownIndex >= 0 && index > ownIndex)+ return false;++ return true;+ });++ const predecessorBlockers = transaction.predecessorOperationIds.filter((operationId) => {+ const operation = this.#get().operations[operationId];++ return (+ operation?.status === 'running' && QUEUE_BLOCKING_OPERATION_TYPES.includes(operation.type)+ );+ });++ return [...new Set([...predecessorBlockers, ...contextBlockers])];+ };++ #waitForTurn = (transaction: VoiceMessageTransaction) => {+ if (this.#getBlockingOperationIds(transaction).length === 0) return Promise.resolve();++ return new Promise<void>((resolve, reject) => {+ const { signal } = transaction.abortController;+ let settleScheduled = false;+ let unsubscribe = () => {};++ const cleanup = () => {+ unsubscribe();+ signal.removeEventListener('abort', check);+ };+ const rejectIfCancelled = () => {+ if (!this.#isCurrent(transaction) || signal.aborted) {+ cleanup();+ reject(+ signal.reason instanceof Error+ ? signal.reason+ : new DOMException('Voice message was cancelled', 'AbortError'),+ );+ return true;+ }++ return false;+ };++ const settle = () => {+ settleScheduled = false;+ if (rejectIfCancelled()) return;++ if (this.#getBlockingOperationIds(transaction).length === 0) {+ cleanup();+ resolve();+ }+ };++ const check = () => {+ if (rejectIfCancelled()) return;++ // Topic creation completes the parent operation immediately before starting the child+ // runtime. Recheck in a microtask so the voice turn cannot slip through that handoff gap.+ if (this.#getBlockingOperationIds(transaction).length === 0 && !settleScheduled) {+ settleScheduled = true;+ queueMicrotask(settle);+ }+ };++ unsubscribe = this.#api.subscribe(check);+ signal.addEventListener('abort', check, { once: true });+ check();+ });+ };++ #renewOperation = (transaction: VoiceMessageTransaction) => {+ const { abortController, operationId } = this.#get().startOperation({+ context: { ...transaction.context, messageId: transaction.messageId },+ label: 'Upload Voice Message',+ type: 'uploadVoiceMessage',+ });++ transaction.abortController = abortController;+ transaction.operationId = operationId;+ this.#get().onOperationCancel(operationId, () => this.#discardTransaction(transaction));+ };++ #failTransaction = (+ transaction: VoiceMessageTransaction,+ error: VoiceMessageUploadError,+ cause?: unknown,+ ) => {+ if (this.#transactions.get(transaction.messageId) !== transaction) return;++ // The formal send lifecycle adopts this row and removes it from its `finally` block when the+ // request fails. Restore the same local-only preview so upload/send failures remain playable+ // and retryable. Checking the captured conversation bucket prevents duplicate rows.+ this.#ensureLocalMessage(transaction);+ const current = this.#get().voiceMessageUploadMap[transaction.messageId];+ this.#setUploadState(transaction.messageId, {+ error,+ progress: current?.progress ?? 0,+ status: 'failed',+ });+ this.#get().failOperation(transaction.operationId, {+ message: cause ? getErrorMessage(cause) : `Voice message ${error}`,+ type: `voice_message_${error}`,+ });+ };++ #shouldDeleteAcceptedPreview = (+ transaction: VoiceMessageTransaction,+ uploadedFile: UploadFileItem,+ ) => {+ const messages = this.#get().dbMessagesMap[messageMapKey(transaction.context)] ?? [];+ const optimisticMessage = messages.find((message) => message.id === transaction.messageId);+ const wasAdoptedBySendLifecycle = optimisticMessage?.audioList?.some(+ (audio) => audio.id === uploadedFile.id,+ );+ const hasPersistedReplacement = messages.some(+ (message) =>+ message.id !== transaction.messageId &&+ (message.files?.includes(uploadedFile.id) ||+ message.audioList?.some((audio) => audio.id === uploadedFile.id)),+ );++ return !wasAdoptedBySendLifecycle || hasPersistedReplacement;+ };++ #finishTransaction = (transaction: VoiceMessageTransaction, uploadedFile: UploadFileItem) => {+ if (this.#transactions.get(transaction.messageId) !== transaction) return;++ this.#transactions.delete(transaction.messageId);+ // Queue acceptance never adopts the local row, so remove that preview immediately. A normal+ // send updates the row to the uploaded file first; keep it until the persisted server snapshot+ // arrives, unless that replacement is already in the bucket.+ if (this.#shouldDeleteAcceptedPreview(transaction, uploadedFile)) {+ this.#deleteLocalMessage(transaction);+ }+ this.#deleteUploadState(transaction.messageId);+ URL.revokeObjectURL(transaction.previewUrl);+ this.#get().completeOperation(transaction.operationId);+ };++ #isCurrent = (transaction: VoiceMessageTransaction) =>+ this.#transactions.get(transaction.messageId) === transaction;++ #executeTransaction = async (transaction: VoiceMessageTransaction) => {+ const attemptId = transaction.ownership.beginAttempt();+ let phase: VoiceMessageUploadError = 'upload';++ try {+ let uploadItem = transaction.ownership.getPending();+ if (!uploadItem) {+ this.#setUploadState(transaction.messageId, { progress: 0, status: 'uploading' });++ const result = await getFileStoreState().uploadWithProgress({+ abortController: transaction.abortController,+ file: transaction.recording.file,+ fileMetadata: {+ codec: transaction.recording.codec,+ durationMs: transaction.recording.durationMs,+ mimeType: transaction.recording.mimeType,+ },+ uploadId: transaction.messageId,+ onStatusUpdate: (event) => {+ if (+ event.type !== 'updateFile' ||+ !transaction.ownership.isCurrent(attemptId) ||+ !this.#isCurrent(transaction) ||+ !event.value.uploadState+ )+ return;++ this.#setUploadState(transaction.messageId, {+ progress: event.value.uploadState.progress,+ status: 'uploading',+ });+ },+ });++ if (!result) throw new Error('Voice message upload did not return a file');++ uploadItem = {+ audioMetadata: {+ codec: transaction.recording.codec,+ durationMs: transaction.recording.durationMs,+ mimeType: transaction.recording.mimeType,+ },+ file: transaction.recording.file,+ fileUrl: result.url,+ id: result.id,+ status: 'success',+ };++ if (!(await transaction.ownership.ownUploaded(attemptId, uploadItem))) return;+ }++ if (!this.#isCurrent(transaction) || transaction.abortController.signal.aborted) return;++ if (!transaction.canSend(transaction.context)) {+ this.#failTransaction(transaction, 'unsupported');+ return;+ }++ phase = 'send';+ this.#setUploadState(transaction.messageId, { progress: 100, status: 'sending' });++ // Keep the optimistic transcript and model input in the same order. The upload operation is+ // a queue barrier for later composer sends; this transaction waits for older turns and then+ // invokes the formal lifecycle, which ignores its own barrier.+ await this.#waitForTurn(transaction);++ if (!this.#isCurrent(transaction) || transaction.abortController.signal.aborted) return;+ if (!transaction.canSend(transaction.context)) {+ this.#failTransaction(transaction, 'unsupported');+ return;+ }++ const sendPromise = transaction.send(uploadItem, {+ context: transaction.context,+ messageId: transaction.messageId,+ signal: transaction.abortController.signal,+ });+ transaction.ownership.trackSend(uploadItem, sendPromise);+ try {+ await sendPromise;+ transaction.ownership.accept(uploadItem);+ } finally {+ transaction.ownership.finishSend(sendPromise);+ }++ this.#finishTransaction(transaction, uploadItem);+ } catch (error) {+ if (!this.#isCurrent(transaction) || transaction.abortController.signal.aborted) return;++ this.#failTransaction(transaction, phase, error);+ }+ };++ #runTransaction = (transaction: VoiceMessageTransaction) => {+ if (transaction.runPromise) return transaction.runPromise;++ const runPromise = this.#executeTransaction(transaction);+ transaction.runPromise = runPromise;+ void runPromise.then(+ () => {+ if (transaction.runPromise === runPromise) transaction.runPromise = undefined;+ },+ () => {+ if (transaction.runPromise === runPromise) transaction.runPromise = undefined;+ },+ );++ return runPromise;+ };++ #setUploadState = (messageId: string, value: VoiceMessageUploadState) => {+ if (!this.#transactions.has(messageId)) return;++ this.#set(+ (state) => ({+ voiceMessageUploadMap: { ...state.voiceMessageUploadMap, [messageId]: value },+ }),+ false,+ `voiceMessage/setUploadState/${messageId}/${value.status}`,+ );+ };++ cancelVoiceMessage = async (messageId: string) => {+ const transaction = this.#transactions.get(messageId);+ if (!transaction) return;++ const operation = this.#get().operations[transaction.operationId];+ if (operation && operation.status !== 'cancelled' && operation.status !== 'completed') {+ this.#get().cancelOperation(transaction.operationId, 'Voice message cancelled');+ }++ await this.#discardTransaction(transaction);+ };++ retryVoiceMessage = (messageId: string) => {+ const transaction = this.#transactions.get(messageId);+ const uploadState = this.#get().voiceMessageUploadMap[messageId];+ if (!transaction || transaction.runPromise || uploadState?.status !== 'failed') return;++ this.#renewOperation(transaction);+ this.#ensureLocalMessage(transaction);+ void this.#runTransaction(transaction);+ };++ disposeVoiceMessages = () => {+ const transactions = [...this.#transactions.values()];+ this.#transactions.clear();++ for (const transaction of transactions) {+ transaction.abortController.abort(new DOMException('Chat store was reset', 'AbortError'));+ URL.revokeObjectURL(transaction.previewUrl);+ void transaction.ownership.discard().catch((error) => {+ console.error('[VoiceMessage] Failed to clean up a voice file during reset:', error);+ });+ }+ };++ moveVoiceMessages = (sourceContext: ConversationContext, targetContext: ConversationContext) => {+ const sourceKey = messageMapKey(sourceContext);+ const targetKey = messageMapKey(targetContext);+ if (sourceKey === targetKey) return;++ const transactions = [...this.#transactions.values()].filter(+ (transaction) => messageMapKey(transaction.context) === sourceKey,+ );+ if (transactions.length === 0) return;++ for (const transaction of transactions) {+ transaction.context = { ...targetContext };+ }++ this.#set(+ produce((state: ChatStore) => {+ for (const transaction of transactions) {+ const operation = state.operations[transaction.operationId];+ if (!operation || operation.status !== 'running') continue;++ state.operationsByContext[sourceKey] = (+ state.operationsByContext[sourceKey] ?? []+ ).filter((operationId) => operationId !== transaction.operationId);+ const targetOperationIds = state.operationsByContext[targetKey] ?? [];+ if (!targetOperationIds.includes(transaction.operationId)) {+ state.operationsByContext[targetKey] = [...targetOperationIds, transaction.operationId];+ }+ operation.context = {+ ...targetContext,+ messageId: transaction.messageId,+ };+ }+ }),+ false,+ `voiceMessage/moveTransactions/${sourceKey}/${targetKey}`,+ );++ for (const transaction of transactions) {+ this.#moveLocalMessage(transaction, sourceContext);+ }+ };++ sendVoiceMessage = ({ canSend, context, recording, send }: SendVoiceMessageParams) => {+ if (!canSend(context)) return;++ // The server accepts caller-provided message ids and validates the canonical+ // `msg_*` entity shape. Reuse that final id from the first optimistic frame.+ const messageId = generateEntityId('messages');+ const previewUrl = URL.createObjectURL(recording.file);+ const predecessorOperationIds = (+ this.#get().operationsByContext[messageMapKey(context)] ?? []+ ).filter((operationId) => {+ const operation = this.#get().operations[operationId];++ return (+ operation?.status === 'running' && QUEUE_BLOCKING_OPERATION_TYPES.includes(operation.type)+ );+ });+ const { abortController, operationId } = this.#get().startOperation({+ context: { ...context, messageId },+ label: 'Upload Voice Message',+ type: 'uploadVoiceMessage',+ });+ const transaction: VoiceMessageTransaction = {+ abortController,+ canSend,+ context,+ messageId,+ operationId,+ ownership: new VoiceMessageUploadOwnership((id) => fileService.removeUnreferencedFile(id)),+ predecessorOperationIds,+ previewUrl,+ recording,+ send,+ };+ this.#transactions.set(messageId, transaction);+ this.#get().onOperationCancel(operationId, () => this.#discardTransaction(transaction));++ this.#ensureLocalMessage(transaction);+ this.#setUploadState(messageId, { progress: 0, status: 'uploading' });++ void this.#runTransaction(transaction);++ return messageId;+ };+}++export type VoiceMessageAction = Pick<VoiceMessageActionImpl, keyof VoiceMessageActionImpl>;diff --git a/src/store/chat/slices/voiceMessage/initialState.ts b/src/store/chat/slices/voiceMessage/initialState.tsnew file mode 100644index 00000000000..da85485367f--- /dev/null+++ b/src/store/chat/slices/voiceMessage/initialState.ts@@ -0,0 +1,17 @@+export type VoiceMessageUploadError = 'send' | 'unsupported' | 'upload';++export type VoiceMessageUploadStatus = 'failed' | 'sending' | 'uploading';++export interface VoiceMessageUploadState {+ error?: VoiceMessageUploadError;+ progress: number;+ status: VoiceMessageUploadStatus;+}++export interface ChatVoiceMessageState {+ voiceMessageUploadMap: Record<string, VoiceMessageUploadState>;+}++export const initialVoiceMessageState: ChatVoiceMessageState = {+ voiceMessageUploadMap: {},+};diff --git a/src/store/chat/slices/voiceMessage/uploadOwnership.test.ts b/src/store/chat/slices/voiceMessage/uploadOwnership.test.tsnew file mode 100644index 00000000000..b72d6da0a8b--- /dev/null+++ b/src/store/chat/slices/voiceMessage/uploadOwnership.test.ts@@ -0,0 +1,101 @@+import { type UploadFileItem } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { VoiceMessageUploadOwnership } from './uploadOwnership';++const voiceFile = { id: 'voice-file', status: 'success' } as UploadFileItem;++const deferred = <T = void>() => {+ let reject!: (reason?: unknown) => void;+ let resolve!: (value: T | PromiseLike<T>) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ reject = rejectPromise;+ resolve = resolvePromise;+ });++ return { promise, reject, resolve };+};++describe('VoiceMessageUploadOwnership', () => {+ it('retains a failed send for retry and removes the upload only when discarded', async () => {+ const removeFile = vi.fn().mockResolvedValue(undefined);+ const ownership = new VoiceMessageUploadOwnership(removeFile);+ const attemptId = ownership.beginAttempt();+ await expect(ownership.ownUploaded(attemptId, voiceFile)).resolves.toBe(true);++ const failedSend = Promise.reject(new Error('send failed'));+ ownership.trackSend(voiceFile, failedSend);+ await expect(failedSend).rejects.toThrow('send failed');+ ownership.finishSend(failedSend);++ ownership.beginAttempt();+ expect(ownership.getPending()).toBe(voiceFile);+ expect(removeFile).not.toHaveBeenCalled();++ await expect(ownership.discard()).resolves.toBe('discarded');+ expect(removeFile).toHaveBeenCalledOnce();+ expect(removeFile).toHaveBeenCalledWith(voiceFile.id);+ });++ it('waits for an accepted in-flight send and never removes its file', async () => {+ const removeFile = vi.fn().mockResolvedValue(undefined);+ const ownership = new VoiceMessageUploadOwnership(removeFile);+ const send = deferred();+ const attemptId = ownership.beginAttempt();+ await ownership.ownUploaded(attemptId, voiceFile);+ ownership.trackSend(voiceFile, send.promise);++ const cleanup = ownership.discard();+ await Promise.resolve();+ expect(removeFile).not.toHaveBeenCalled();++ send.resolve();+ await expect(cleanup).resolves.toBe('accepted');+ expect(removeFile).not.toHaveBeenCalled();+ });++ it('removes a rejected in-flight send once across repeated discard calls', async () => {+ const removeFile = vi.fn().mockResolvedValue(undefined);+ const ownership = new VoiceMessageUploadOwnership(removeFile);+ const send = deferred();+ const attemptId = ownership.beginAttempt();+ await ownership.ownUploaded(attemptId, voiceFile);+ ownership.trackSend(voiceFile, send.promise);++ const firstCleanup = ownership.discard();+ const secondCleanup = ownership.discard();+ send.reject(new Error('not accepted'));++ await expect(Promise.all([firstCleanup, secondCleanup])).resolves.toEqual([+ 'discarded',+ 'discarded',+ ]);+ expect(removeFile).toHaveBeenCalledOnce();+ });++ it('cleans up an upload that finishes after its attempt was discarded', async () => {+ const removeFile = vi.fn().mockResolvedValue(undefined);+ const ownership = new VoiceMessageUploadOwnership(removeFile);+ const attemptId = ownership.beginAttempt();++ await expect(ownership.discard()).resolves.toBe('discarded');++ await expect(ownership.ownUploaded(attemptId, voiceFile)).resolves.toBe(false);+ expect(removeFile).toHaveBeenCalledOnce();+ });++ it('retries transient cleanup failures', async () => {+ const removeFile = vi+ .fn()+ .mockRejectedValueOnce(new Error('temporary'))+ .mockRejectedValueOnce(new Error('temporary'))+ .mockResolvedValue(undefined);+ const ownership = new VoiceMessageUploadOwnership(removeFile);+ const attemptId = ownership.beginAttempt();+ await ownership.ownUploaded(attemptId, voiceFile);++ await expect(ownership.discard()).resolves.toBe('discarded');++ expect(removeFile).toHaveBeenCalledTimes(3);+ });+});diff --git a/src/store/chat/slices/voiceMessage/uploadOwnership.ts b/src/store/chat/slices/voiceMessage/uploadOwnership.tsnew file mode 100644index 00000000000..e981ee1a3a0--- /dev/null+++ b/src/store/chat/slices/voiceMessage/uploadOwnership.ts@@ -0,0 +1,92 @@+import type { UploadFileItem } from '@lobechat/types';++type RemoveFile = (id: string) => Promise<void>;++const CLEANUP_ATTEMPTS = 3;++interface ActiveSend {+ fileId: string;+ promise: Promise<void>;+}++/**+ * Owns uploaded voice files until the conversation lifecycle acknowledges them.+ *+ * The ownership boundary is independent from React and Zustand state: retries reuse the same+ * uploaded row, stale upload completions are cleaned up, and cancellation waits for an in-flight+ * send to confirm that it was not accepted before deleting its file.+ */+export class VoiceMessageUploadOwnership {+ private activeSend?: ActiveSend;+ private attemptId = 0;+ private pending?: UploadFileItem;++ constructor(private readonly removeFile: RemoveFile) {}++ private cleanupFile = async (id: string) => {+ let lastError: unknown;++ for (let attempt = 0; attempt < CLEANUP_ATTEMPTS; attempt += 1) {+ try {+ await this.removeFile(id);+ return;+ } catch (error) {+ lastError = error;+ }+ }++ throw lastError;+ };++ accept = (file: UploadFileItem) => {+ if (this.pending?.id === file.id) this.pending = undefined;+ };++ beginAttempt = () => {+ this.attemptId += 1;+ return this.attemptId;+ };++ discard = async (): Promise<'accepted' | 'discarded'> => {+ this.attemptId += 1;++ const pending = this.pending;+ this.pending = undefined;+ if (!pending) return 'discarded';++ const activeSend = this.activeSend?.fileId === pending.id ? this.activeSend.promise : undefined;+ if (activeSend) {+ try {+ await activeSend;+ return 'accepted';+ } catch {+ // The send settled without acceptance, so this transaction still owns the file.+ }+ }++ await this.cleanupFile(pending.id);+ return 'discarded';+ };++ finishSend = (promise: Promise<void>) => {+ if (this.activeSend?.promise === promise) this.activeSend = undefined;+ };++ getPending = () => this.pending;++ isCurrent = (attemptId: number) => attemptId === this.attemptId;++ ownUploaded = async (attemptId: number, file: UploadFileItem) => {+ if (!this.isCurrent(attemptId)) {+ await this.cleanupFile(file.id);+ return false;+ }++ this.pending = file;+ return true;+ };++ trackSend = (file: UploadFileItem, promise: Promise<void>) => {+ this.activeSend = { fileId: file.id, promise };+ };+}diff --git a/src/store/chat/store.ts b/src/store/chat/store.tsindex d341b7cfbc1..23e33171372 100644--- a/src/store/chat/store.ts+++ b/src/store/chat/store.ts@@ -33,6 +33,8 @@ import { type ChatTranslateAction } from './slices/translate/action';import { ChatTranslateActionImpl } from './slices/translate/action';import { type ChatTTSAction } from './slices/tts/action';import { ChatTTSActionImpl } from './slices/tts/action';+import { type VoiceMessageAction } from './slices/voiceMessage/action';+import { VoiceMessageActionImpl } from './slices/voiceMessage/action';export type ChatStoreAction = ChatMessageAction &ChatForwardAction &@@ -46,6 +48,7 @@ export type ChatStoreAction = ChatMessageAction &ChatPortalAction &OperationActions &ChatAIAgentAction &+ VoiceMessageAction &ResetableStore;export type ChatStore = ChatStoreAction & ChatStoreState;@@ -54,12 +57,24 @@ export type ChatStore = ChatStoreAction & ChatStoreState;class ChatStoreResetAction extends ResetableStoreAction<ChatStore> {protected readonly resetActionName = 'resetChatStore';++ constructor(+ ...[set, get, api, disposeVoiceMessages]: [+ ...Parameters<StateCreator<ChatStore, [['zustand/devtools', never]]>>,+ () => void,+ ]+ ) {+ super(set, get, api);+ this.beforeReset = disposeVoiceMessages;+ }}const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (...params: Parameters<StateCreator<ChatStore, [['zustand/devtools', never]]>>-) =>- ({+) => {+ const voiceMessageAction = new VoiceMessageActionImpl(...params);++ return {...initialState,...(flattenActions<ChatStoreAction>([chatMessage(...params),@@ -74,10 +89,12 @@ const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (new ChatPortalActionImpl(...params),new OperationActionsImpl(...params),chatAiAgent(...params),- new ChatStoreResetAction(...params),+ voiceMessageAction,+ new ChatStoreResetAction(...params, voiceMessageAction.disposeVoiceMessages),]) as ChatStoreAction),// cloud- }) as ChatStore;+ } as ChatStore;+};// =============== Implement useStore ============ //const devtools = createDevtools('chat');diff --git a/src/store/chat/utils/localMessages.ts b/src/store/chat/utils/localMessages.tsnew file mode 100644index 00000000000..ad7366b62d2--- /dev/null+++ b/src/store/chat/utils/localMessages.ts@@ -0,0 +1,31 @@+import type { UIChatMessage } from '@lobechat/types';++// Marks messages that should be rendered locally but never forwarded into the+// real send pipeline or persisted to the database.+export const LOCAL_MESSAGE_SCOPE = '__internal_local__';++export const isLocalOnlyMessage = (message: UIChatMessage | undefined) =>+ message?.metadata?.scope === LOCAL_MESSAGE_SCOPE;++/**+ * Insert transient rows into a server snapshot without moving them to the end of the transcript.+ * Only local rows are repositioned; the canonical order of persisted messages remains untouched.+ */+export const mergeLocalMessagesByCreatedAt = (+ persistedMessages: UIChatMessage[],+ localMessages: UIChatMessage[],+) => {+ const merged = [...persistedMessages];+ const sortedLocalMessages = [...localMessages].sort((a, b) => a.createdAt - b.createdAt);++ for (const localMessage of sortedLocalMessages) {+ const insertionIndex = merged.findIndex(+ (message) => message.createdAt > localMessage.createdAt,+ );++ if (insertionIndex === -1) merged.push(localMessage);+ else merged.splice(insertionIndex, 0, localMessage);+ }++ return merged;+};diff --git a/src/store/file/slices/upload/action.test.ts b/src/store/file/slices/upload/action.test.tsindex 2079c3926a7..cf0ba97d76c 100644--- a/src/store/file/slices/upload/action.test.ts+++ b/src/store/file/slices/upload/action.test.ts@@ -374,6 +374,54 @@ describe('FileUploadAction', () => {});});+ it('persists voice-message duration and codec metadata with the binary upload', async () => {+ const { result } = renderHook(() => useStore());+ const mockFile = new File(['audio'], 'voice.webm', {+ type: 'audio/webm;codecs=opus',+ });+ const mockMetadata = {+ date: '12345',+ dirname: '/uploads',+ filename: 'voice.webm',+ path: '/uploads/voice.webm',+ };++ 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: 'voice-file-id',+ url: 'https://example.com/voice.webm',+ });++ await act(async () => {+ await result.current.uploadWithProgress({+ file: mockFile,+ fileMetadata: {+ codec: 'opus',+ durationMs: 1250,+ mimeType: mockFile.type,+ },+ });+ });++ expect(fileService.createFile).toHaveBeenCalledWith(+ expect.objectContaining({+ fileType: mockFile.type,+ metadata: {+ ...mockMetadata,+ codec: 'opus',+ durationMs: 1250,+ mimeType: mockFile.type,+ },+ }),+ undefined,+ );+ });+it('should call onProgress callback during upload', async () => {const { result } = renderHook(() => useStore());diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.tsindex a88ce962467..022a113e1b0 100644--- a/src/store/file/slices/upload/action.ts+++ b/src/store/file/slices/upload/action.ts@@ -31,6 +31,12 @@ type OnStatusUpdate = (interface UploadWithProgressParams {abortController?: AbortController;file: File;+ /**+ * Additional metadata persisted with the file record. Media capture flows use+ * this for duration/codec while the storage path metadata continues to come+ * from the upload service.+ */+ fileMetadata?: Record<string, unknown>;knowledgeBaseId?: string;onStatusUpdate?: OnStatusUpdate;parentId?: string;@@ -135,6 +141,7 @@ export class FileUploadActionImpl {uploadId,abortController,visibility,+ fileMetadata,}: UploadWithProgressParams): Promise<UploadWithProgressResult | undefined> => {const statusId = uploadId ?? file.name;@@ -223,6 +230,7 @@ export class FileUploadActionImpl {fileType,hash,metadata: {+ ...fileMetadata,...metadata,...dimensions,...(durationMs === undefined ? {} : { durationMs }),diff --git a/src/store/utils/resetableStore.ts b/src/store/utils/resetableStore.tsindex cd42c906bb7..0ba717b2251 100644--- a/src/store/utils/resetableStore.ts+++ b/src/store/utils/resetableStore.ts@@ -14,6 +14,8 @@ export abstract class ResetableStoreAction<TStore extends object> implements Resprotected abstract readonly resetActionName: string;+ protected beforeReset = () => {};+constructor(set: Setter<TStore>, _get: () => TStore, api: StoreApi<TStore>) {void _get;this.#set = set;@@ -21,6 +23,7 @@ export abstract class ResetableStoreAction<TStore extends object> implements Res}reset = () => {+ this.beforeReset();this.#set(this.#api.getInitialState(), false, this.resetActionName);};}