🤯 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: support google video understanding (#8761)
Arvin Xuf02d43b8d33f
diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.tsindex bd28903efb4..41a0db135a2 100644--- a/packages/context-engine/src/processors/MessageContent.ts+++ b/packages/context-engine/src/processors/MessageContent.ts@@ -17,6 +17,8 @@ export interface FileContextConfig {export interface MessageContentConfig {/** File context configuration */fileContext?: FileContextConfig;+ /** Function to check if video is supported */+ isCanUseVideo?: (model: string, provider: string) => boolean | undefined;/** Function to check if vision is supported */isCanUseVision?: (model: string, provider: string) => boolean | undefined;/** Model name */@@ -33,7 +35,10 @@ export interface UserMessageContentPart {signature?: string;text?: string;thinking?: string;- type: 'text' | 'image_url' | 'thinking';+ type: 'text' | 'image_url' | 'thinking' | 'video_url';+ video_url?: {+ url: string;+ };}/**@@ -104,12 +109,13 @@ export class MessageContentProcessor extends BaseProcessor {* Process user message content*/private async processUserMessage(message: any): Promise<any> {- // Check if images or files need processing+ // Check if images, videos or files need processingconst hasImages = message.imageList && message.imageList.length > 0;+ const hasVideos = message.videoList && message.videoList.length > 0;const hasFiles = message.fileList && message.fileList.length > 0;- // If no images and files, return plain text content directly- if (!hasImages && !hasFiles) {+ // If no images, videos and files, return plain text content directly+ if (!hasImages && !hasVideos && !hasFiles) {return {...message,content: message.content,@@ -121,12 +127,13 @@ export class MessageContentProcessor extends BaseProcessor {// Add text contentlet textContent = message.content || '';- // Add file context (if file context is enabled and has files or images)- if ((hasFiles || hasImages) && this.config.fileContext?.enabled) {+ // Add file context (if file context is enabled and has files, images or videos)+ if ((hasFiles || hasImages || hasVideos) && this.config.fileContext?.enabled) {const filesContext = filesPrompts({addUrl: this.config.fileContext.includeFileUrl ?? true,fileList: message.fileList,- imageList: message.imageList,+ imageList: message.imageList || [],+ videoList: message.videoList || [],});if (filesContext) {@@ -148,17 +155,26 @@ export class MessageContentProcessor extends BaseProcessor {contentParts.push(...imageContentParts);}+ // Process video content+ if (hasVideos && this.config.isCanUseVideo?.(this.config.model, this.config.provider)) {+ const videoContentParts = await this.processVideoList(message.videoList || []);+ contentParts.push(...videoContentParts);+ }+// 明确返回的字段,只保留必要的消息字段- const hasFileContext = (hasFiles || hasImages) && this.config.fileContext?.enabled;+ const hasFileContext = (hasFiles || hasImages || hasVideos) && this.config.fileContext?.enabled;const hasVisionContent =hasImages && this.config.isCanUseVision?.(this.config.model, this.config.provider);+ const hasVideoContent =+ hasVideos && this.config.isCanUseVideo?.(this.config.model, this.config.provider);- // 如果只有文本内容且没有添加文件上下文也没有视觉内容,返回纯文本+ // 如果只有文本内容且没有添加文件上下文也没有视觉/视频内容,返回纯文本if (contentParts.length === 1 &&contentParts[0].type === 'text' &&!hasFileContext &&- !hasVisionContent+ !hasVisionContent &&+ !hasVideoContent) {return {content: contentParts[0].text,@@ -274,6 +290,22 @@ export class MessageContentProcessor extends BaseProcessor {);}+ /**+ * 处理视频列表+ */+ private async processVideoList(videoList: any[]): Promise<UserMessageContentPart[]> {+ if (!videoList || videoList.length === 0) {+ return [];+ }++ return videoList.map((video) => {+ return {+ type: 'video_url',+ video_url: { url: video.url },+ } as UserMessageContentPart;+ });+ }+/*** 验证内容部分格式*/@@ -290,6 +322,9 @@ export class MessageContentProcessor extends BaseProcessor {case 'thinking': {return !!(part.thinking && part.signature);}+ case 'video_url': {+ return !!(part.video_url && part.video_url.url);+ }default: {return false;}diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.tsindex 2a887333941..989c7d3ca38 100644--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts@@ -1,4 +1,4 @@-import { ChatImageItem, ChatMessage } from '@lobechat/types';+import { ChatImageItem, ChatMessage, ChatVideoItem } from '@lobechat/types';import { describe, expect, it, vi } from 'vitest';import type { PipelineContext } from '../../types';@@ -26,6 +26,7 @@ const createContext = (messages: ChatMessage[]): PipelineContext => ({});const mockIsCanUseVision = vi.fn();+const mockIsCanUseVideo = vi.fn();describe('MessageContentProcessor', () => {describe('Image processing functionality', () => {@@ -391,4 +392,181 @@ describe('MessageContentProcessor', () => {expect(result.metadata.assistantMessagesProcessed).toBe(1);});});++ describe('Video processing functionality', () => {+ it('should return empty video content parts if model cannot use video', async () => {+ mockIsCanUseVideo.mockReturnValue(false);++ const processor = new MessageContentProcessor({+ model: 'any-model',+ provider: 'any-provider',+ isCanUseVideo: mockIsCanUseVideo,+ fileContext: { enabled: false },+ });++ const messages: ChatMessage[] = [+ {+ id: 'test',+ role: 'user',+ content: 'Hello',+ videoList: [{ url: 'video_url', alt: 'test video', id: 'test' } as ChatVideoItem],+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},+ },+ ];++ const result = await processor.process(createContext(messages));++ // Should return plain text when video is not supported+ expect(result.messages[0].content).toBe('Hello');+ });++ it('should process videos if model can use video', async () => {+ mockIsCanUseVideo.mockReturnValue(true);++ const processor = new MessageContentProcessor({+ model: 'gpt-4-vision',+ provider: 'openai',+ isCanUseVideo: mockIsCanUseVideo,+ fileContext: { enabled: false },+ });++ const messages: ChatMessage[] = [+ {+ id: 'test',+ role: 'user',+ content: 'Hello',+ videoList: [+ { url: 'http://example.com/video.mp4', alt: 'test video', id: 'test1' },+ { url: 'http://example.com/video2.mp4', alt: 'test video 2', id: 'test2' },+ ] as ChatVideoItem[],+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},+ },+ ];++ const result = await processor.process(createContext(messages));++ const content = result.messages[0].content as any[];+ expect(content).toHaveLength(3); // text + 2 videos+ expect(content[0].type).toBe('text');+ expect(content[0].text).toBe('Hello');+ expect(content[1].type).toBe('video_url');+ expect(content[1].video_url.url).toBe('http://example.com/video.mp4');+ expect(content[2].type).toBe('video_url');+ expect(content[2].video_url.url).toBe('http://example.com/video2.mp4');+ });++ it('should handle video disabled scenario correctly', async () => {+ mockIsCanUseVideo.mockReturnValue(false);++ const processor = new MessageContentProcessor({+ model: 'text-model',+ provider: 'openai',+ isCanUseVideo: mockIsCanUseVideo,+ fileContext: { enabled: false },+ });++ const messages: ChatMessage[] = [+ {+ id: 'test',+ role: 'user',+ content: 'Analyze this video',+ videoList: [+ { url: 'http://example.com/video.mp4', alt: 'test video', id: 'test' },+ ] as ChatVideoItem[],+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},+ },+ ];++ const result = await processor.process(createContext(messages));++ // Should return plain text only when video not supported+ expect(result.messages[0].content).toBe('Analyze this video');+ });++ it('should include videos in file context when enabled', async () => {+ mockIsCanUseVideo.mockReturnValue(false); // Video processing disabled but file context enabled++ const processor = new MessageContentProcessor({+ model: 'gpt-4',+ provider: 'openai',+ isCanUseVideo: mockIsCanUseVideo,+ fileContext: { enabled: true, includeFileUrl: true },+ });++ const messages: ChatMessage[] = [+ {+ id: 'test',+ role: 'user',+ content: 'Hello',+ videoList: [+ {+ id: 'video1',+ url: 'http://example.com/video.mp4',+ alt: 'Test video',+ },+ ] as ChatVideoItem[],+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},+ },+ ];++ const result = await processor.process(createContext(messages));++ // Should return structured content when has videos and file context enabled+ expect(Array.isArray(result.messages[0].content)).toBe(true);+ const content = result.messages[0].content as any[];+ expect(content).toHaveLength(1);+ expect(content[0].type).toBe('text');+ expect(content[0].text).toContain('SYSTEM CONTEXT');+ expect(content[0].text).toContain('Hello');+ });++ it('should handle mixed images and videos correctly', async () => {+ mockIsCanUseVision.mockReturnValue(true);+ mockIsCanUseVideo.mockReturnValue(true);++ const processor = new MessageContentProcessor({+ model: 'gpt-4-vision',+ provider: 'openai',+ isCanUseVideo: mockIsCanUseVideo,+ isCanUseVision: mockIsCanUseVision,+ fileContext: { enabled: false },+ });++ const messages: ChatMessage[] = [+ {+ id: 'test',+ role: 'user',+ content: 'Analyze these media files',+ imageList: [+ { url: 'http://example.com/image.jpg', alt: 'test image', id: 'img1' },+ ] as ChatImageItem[],+ videoList: [+ { url: 'http://example.com/video.mp4', alt: 'test video', id: 'vid1' },+ ] as ChatVideoItem[],+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},+ },+ ];++ const result = await processor.process(createContext(messages));++ const content = result.messages[0].content as any[];+ expect(content).toHaveLength(3); // text + image + video+ expect(content[0].type).toBe('text');+ expect(content[0].text).toBe('Analyze these media files');+ expect(content[1].type).toBe('image_url');+ expect(content[1].image_url.url).toBe('http://example.com/image.jpg');+ expect(content[2].type).toBe('video_url');+ expect(content[2].video_url.url).toBe('http://example.com/video.mp4');+ });+ });});diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 6d7d0478e7b..aa0db589179 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -5,6 +5,7 @@ import {ChatTTS,ChatToolPayload,ChatTranslate,+ ChatVideoItem,CreateMessageParams,MessageItem,ModelRankItem,@@ -175,7 +176,10 @@ export class MessageModel {}const imageList = relatedFileList.filter((i) => (i.fileType || '').startsWith('image'));- const fileList = relatedFileList.filter((i) => !(i.fileType || '').startsWith('image'));+ const videoList = relatedFileList.filter((i) => (i.fileType || '').startsWith('video'));+ const fileList = relatedFileList.filter(+ (i) => !(i.fileType || '').startsWith('image') && !(i.fileType || '').startsWith('video'),+ );// 3. get relative file chunksconst chunksList = await this.db@@ -251,6 +255,10 @@ export class MessageModel {ragQuery: messageQuery?.rewriteQuery,ragQueryId: messageQuery?.id,ragRawQuery: messageQuery?.userQuery,+ videoList: videoList+ .filter((relation) => relation.messageId === item.id)+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ .map<ChatVideoItem>(({ id, url, name }) => ({ alt: name!, id, url })),} as unknown as ChatMessage;},);diff --git a/packages/model-bank/src/aiModels/google.ts b/packages/model-bank/src/aiModels/google.tsindex e2818d0d4dc..193641817c0 100644--- a/packages/model-bank/src/aiModels/google.ts+++ b/packages/model-bank/src/aiModels/google.ts@@ -7,6 +7,7 @@ const googleChatModels: AIChatModelCard[] = [functionCall: true,reasoning: true,search: true,+ video: true,vision: true,},contextWindowTokens: 1_048_576 + 65_536,@@ -60,6 +61,7 @@ const googleChatModels: AIChatModelCard[] = [functionCall: true,reasoning: true,search: true,+ video: true,vision: true,},contextWindowTokens: 1_048_576 + 65_536,@@ -112,6 +114,7 @@ const googleChatModels: AIChatModelCard[] = [functionCall: true,reasoning: true,search: true,+ video: true,vision: true,},contextWindowTokens: 1_048_576 + 65_536,@@ -163,6 +166,7 @@ const googleChatModels: AIChatModelCard[] = [functionCall: true,reasoning: true,search: true,+ video: true,vision: true,},contextWindowTokens: 1_048_576 + 65_536,@@ -191,6 +195,7 @@ const googleChatModels: AIChatModelCard[] = [functionCall: true,reasoning: true,search: true,+ video: true,vision: true,},contextWindowTokens: 1_048_576 + 65_536,@@ -240,6 +245,7 @@ const googleChatModels: AIChatModelCard[] = [functionCall: true,reasoning: true,search: true,+ video: true,vision: true,},contextWindowTokens: 1_048_576 + 65_536,@@ -267,6 +273,7 @@ const googleChatModels: AIChatModelCard[] = [functionCall: true,reasoning: true,search: true,+ video: true,vision: true,},contextWindowTokens: 1_048_576 + 65_536,diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.tsindex 1639d804615..9f861cafedb 100644--- a/packages/model-runtime/src/providers/google/index.ts+++ b/packages/model-runtime/src/providers/google/index.ts@@ -439,10 +439,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {}return {- inlineData: {- data: base64,- mimeType: mimeType || 'image/png',- },+ inlineData: { data: base64, mimeType: mimeType || 'image/png' },};}@@ -450,15 +447,41 @@ export class LobeGoogleAI implements LobeRuntimeAI {const { base64, mimeType } = await imageUrlToBase64(content.image_url.url);return {- inlineData: {- data: base64,- mimeType,- },+ inlineData: { data: base64, mimeType },};}throw new TypeError(`currently we don't support image url: ${content.image_url.url}`);}++ case 'video_url': {+ const { mimeType, base64, type } = parseDataUri(content.video_url.url);++ if (type === 'base64') {+ if (!base64) {+ throw new TypeError("Video URL doesn't contain base64 data");+ }++ return {+ inlineData: { data: base64, mimeType: mimeType || 'video/mp4' },+ };+ }++ if (type === 'url') {+ // For video URLs, we need to fetch and convert to base64+ // Note: This might need size/duration limits for practical use+ const response = await fetch(content.video_url.url);+ const arrayBuffer = await response.arrayBuffer();+ const base64 = Buffer.from(arrayBuffer).toString('base64');+ const mimeType = response.headers.get('content-type') || 'video/mp4';++ return {+ inlineData: { data: base64, mimeType },+ };+ }++ throw new TypeError(`currently we don't support video url: ${content.video_url.url}`);+ }}};diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.tsindex a0941ef9439..6a1f56fe90e 100644--- a/packages/model-runtime/src/types/chat.ts+++ b/packages/model-runtime/src/types/chat.ts@@ -21,9 +21,15 @@ interface UserMessageContentPartImage {type: 'image_url';}+interface UserMessageContentPartVideo {+ type: 'video_url';+ video_url: { url: string };+}+export type UserMessageContentPart =| UserMessageContentPartText| UserMessageContentPartImage+ | UserMessageContentPartVideo| UserMessageContentPartThinking;export interface OpenAIChatMessage {diff --git a/packages/prompts/src/prompts/files/index.test.ts b/packages/prompts/src/prompts/files/index.test.tsindex cea4808f728..d18c6cfea54 100644--- a/packages/prompts/src/prompts/files/index.test.ts+++ b/packages/prompts/src/prompts/files/index.test.ts@@ -1,4 +1,4 @@-import { ChatFileItem, ChatImageItem } from '@lobechat/types';+import { ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';import { describe, expect, it } from 'vitest';import { filesPrompts } from './index';@@ -19,6 +19,12 @@ describe('filesPrompts', () => {url: 'https://example.com/test.pdf',};+ const mockVideo: ChatVideoItem = {+ id: 'video-1',+ alt: 'test video',+ url: 'https://example.com/video.mp4',+ };+it('should generate prompt with only images', () => {const result = filesPrompts({imageList: [mockImage],@@ -37,7 +43,6 @@ describe('filesPrompts', () => {<images_docstring>here are user upload images you can refer to</images_docstring><image name="test image" url="https://example.com/image.jpg"></image></images>-</files_info><!-- END SYSTEM CONTEXT -->`,);@@ -57,7 +62,6 @@ describe('filesPrompts', () => {2. the context is only required when user's queries rely on it.</context.instruction><files_info>-<files><files_docstring>here are user upload files you can refer to</files_docstring><file id="file-1" name="test.pdf" type="application/pdf" size="1024" url="https://example.com/test.pdf"></file>@@ -184,4 +188,145 @@ describe('filesPrompts', () => {<!-- END SYSTEM CONTEXT -->"`);});++ describe('Video functionality', () => {+ it('should generate prompt with only videos', () => {+ const result = filesPrompts({+ videoList: [mockVideo],+ });++ expect(result).toEqual(+ `<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->+<context.instruction>following part contains context information injected by the system. Please follow these instructions:++1. Always prioritize handling user-visible content.+2. the context is only required when user's queries rely on it.+</context.instruction>+<files_info>+<videos>+<videos_docstring>here are user upload videos you can refer to</videos_docstring>+<video name="test video" url="https://example.com/video.mp4"></video>+</videos>+</files_info>+<!-- END SYSTEM CONTEXT -->`,+ );+ });++ it('should generate prompt with videos and images', () => {+ const result = filesPrompts({+ imageList: [mockImage],+ videoList: [mockVideo],+ });++ expect(result).toEqual(+ `<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->+<context.instruction>following part contains context information injected by the system. Please follow these instructions:++1. Always prioritize handling user-visible content.+2. the context is only required when user's queries rely on it.+</context.instruction>+<files_info>+<images>+<images_docstring>here are user upload images you can refer to</images_docstring>+<image name="test image" url="https://example.com/image.jpg"></image>+</images>+<videos>+<videos_docstring>here are user upload videos you can refer to</videos_docstring>+<video name="test video" url="https://example.com/video.mp4"></video>+</videos>+</files_info>+<!-- END SYSTEM CONTEXT -->`,+ );+ });++ it('should generate prompt with all media types', () => {+ const result = filesPrompts({+ imageList: [mockImage],+ fileList: [mockFile],+ videoList: [mockVideo],+ });++ expect(result).toEqual(+ `<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->+<context.instruction>following part contains context information injected by the system. Please follow these instructions:++1. Always prioritize handling user-visible content.+2. the context is only required when user's queries rely on it.+</context.instruction>+<files_info>+<images>+<images_docstring>here are user upload images you can refer to</images_docstring>+<image name="test image" url="https://example.com/image.jpg"></image>+</images>+<files>+<files_docstring>here are user upload files you can refer to</files_docstring>+<file id="file-1" name="test.pdf" type="application/pdf" size="1024" url="https://example.com/test.pdf"></file>+</files>+<videos>+<videos_docstring>here are user upload videos you can refer to</videos_docstring>+<video name="test video" url="https://example.com/video.mp4"></video>+</videos>+</files_info>+<!-- END SYSTEM CONTEXT -->`,+ );+ });++ it('should handle multiple videos', () => {+ const videos: ChatVideoItem[] = [+ mockVideo,+ {+ id: 'video-2',+ alt: 'second video',+ url: 'https://example.com/video2.mp4',+ },+ ];++ const result = filesPrompts({+ videoList: videos,+ });++ expect(result).toContain('test video');+ expect(result).toContain('second video');+ expect(result).toMatch(/<video.*?>.*<video.*?>/s); // Check for multiple video tags+ });++ it('should handle videos without url when addUrl is false', () => {+ const result = filesPrompts({+ videoList: [mockVideo],+ addUrl: false,+ });++ expect(result).toMatchInlineSnapshot(`+ "<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->+ <context.instruction>following part contains context information injected by the system. Please follow these instructions:++ 1. Always prioritize handling user-visible content.+ 2. the context is only required when user's queries rely on it.+ </context.instruction>+ <files_info>+ <videos>+ <videos_docstring>here are user upload videos you can refer to</videos_docstring>+ <video name="test video"></video>+ </videos>+ </files_info>+ <!-- END SYSTEM CONTEXT -->"+ `);+ });++ it('should return empty string when all lists are empty', () => {+ const result = filesPrompts({+ imageList: [],+ fileList: [],+ videoList: [],+ });++ expect(result).toEqual('');+ });++ it('should return empty string when no lists are provided', () => {+ const result = filesPrompts({});++ expect(result).toEqual('');+ });+ });});diff --git a/packages/prompts/src/prompts/files/index.ts b/packages/prompts/src/prompts/files/index.tsindex b3700e8b229..eb02d2f6381 100644--- a/packages/prompts/src/prompts/files/index.ts+++ b/packages/prompts/src/prompts/files/index.ts@@ -1,18 +1,31 @@-import { ChatFileItem, ChatImageItem } from '@lobechat/types';+import { ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';import { filePrompts } from './file';import { imagesPrompts } from './image';+import { videosPrompts } from './video';export const filesPrompts = ({imageList,fileList,+ videoList,addUrl = true,}: {addUrl?: boolean;fileList?: ChatFileItem[];- imageList: ChatImageItem[];+ imageList?: ChatImageItem[];+ videoList?: ChatVideoItem[];}) => {- if (imageList.length === 0 && (fileList || []).length === 0) return '';+ const hasImages = (imageList || []).length > 0;+ const hasFiles = (fileList || []).length > 0;+ const hasVideos = (videoList || []).length > 0;++ if (!hasImages && !hasFiles && !hasVideos) return '';++ const contentParts = [+ hasImages ? imagesPrompts(imageList!, addUrl) : '',+ hasFiles ? filePrompts(fileList!, addUrl) : '',+ hasVideos ? videosPrompts(videoList!, addUrl) : '',+ ].filter(Boolean);const prompt = `<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) --><context.instruction>following part contains context information injected by the system. Please follow these instructions:@@ -21,8 +34,7 @@ export const filesPrompts = ({2. the context is only required when user's queries rely on it.</context.instruction><files_info>-${imagesPrompts(imageList, addUrl)}-${fileList ? filePrompts(fileList, addUrl) : ''}+${contentParts.join('\n')}</files_info><!-- END SYSTEM CONTEXT -->`;diff --git a/packages/prompts/src/prompts/files/video.ts b/packages/prompts/src/prompts/files/video.tsnew file mode 100644index 00000000000..9b4cd38f5f6--- /dev/null+++ b/packages/prompts/src/prompts/files/video.ts@@ -0,0 +1,17 @@+import { ChatVideoItem } from '@lobechat/types';++const videoPrompt = (item: ChatVideoItem, attachUrl: boolean) =>+ attachUrl+ ? `<video name="${item.alt}" url="${item.url}"></video>`+ : `<video name="${item.alt}"></video>`;++export const videosPrompts = (videoList: ChatVideoItem[], addUrl: boolean = true) => {+ if (videoList.length === 0) return '';++ const prompt = `<videos>+<videos_docstring>here are user upload videos you can refer to</videos_docstring>+${videoList.map((item) => videoPrompt(item, addUrl)).join('\n')}+</videos>`;++ return prompt.trim();+};diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.tsindex 20c6688aefa..2152bc53fab 100644--- a/packages/types/src/agent/index.ts+++ b/packages/types/src/agent/index.ts@@ -1,4 +1,4 @@-import { LLMParams } from '../../../model-bank/src/types/aiModel';+import { LLMParams } from 'model-bank';import { FileItem } from '../files';import { KnowledgeBaseItem } from '../knowledgeBase';import { FewShots } from '../llm';diff --git a/packages/types/src/message/chat.ts b/packages/types/src/message/chat.tsindex 08be47f0d75..a1bff344c33 100644--- a/packages/types/src/message/chat.ts+++ b/packages/types/src/message/chat.ts@@ -5,6 +5,7 @@ import type { ChatMessageError, MessageMetadata, MessageRoleType, ModelReasoningimport { ChatImageItem } from './image';import { ChatPluginPayload, ChatToolPayload } from './tools';import { Translate } from './translate';+import { ChatVideoItem } from './video';export interface ChatTranslate extends Translate {content?: string;@@ -63,13 +64,11 @@ export interface ChatMessage {id: string;imageList?: ChatImageItem[];meta: MetaData;-metadata?: MessageMetadata | null;/*** observation id*/observationId?: string;-/*** parent message id*/@@ -83,14 +82,12 @@ export interface ChatMessage {quotaId?: string;ragQuery?: string | null;ragQueryId?: string | null;-ragRawQuery?: string | null;reasoning?: ModelReasoning | null;/*** message role type*/role: MessageRoleType;-search?: GroundingSearch | null;sessionId?: string;threadId?: string | null;@@ -105,6 +102,7 @@ export interface ChatMessage {*/traceId?: string;updatedAt: number;+ videoList?: ChatVideoItem[];}export interface CreateMessageParamsdiff --git a/packages/types/src/message/index.ts b/packages/types/src/message/index.tsindex cd19cdd6ef5..eacaeccbc8c 100644--- a/packages/types/src/message/index.ts+++ b/packages/types/src/message/index.ts@@ -5,6 +5,7 @@ export * from './chat';export * from './image';export * from './rag';export * from './tools';+export * from './video';export interface SendMessageParams {/**diff --git a/packages/types/src/message/video.ts b/packages/types/src/message/video.tsnew file mode 100644index 00000000000..7b179f09653--- /dev/null+++ b/packages/types/src/message/video.ts@@ -0,0 +1,5 @@+export interface ChatVideoItem {+ alt: string;+ id: string;+ url: string;+}diff --git a/packages/utils/src/client/index.ts b/packages/utils/src/client/index.tsindex 866082f7c96..b3d728b53cd 100644--- a/packages/utils/src/client/index.ts+++ b/packages/utils/src/client/index.ts@@ -3,3 +3,4 @@ export * from './downloadFile';export * from './exportFile';export * from './fetchEventSource';export * from './sanitize';+export * from './videoValidation';diff --git a/packages/utils/src/client/videoValidation.test.ts b/packages/utils/src/client/videoValidation.test.tsnew file mode 100644index 00000000000..2ef4ebcb4a6--- /dev/null+++ b/packages/utils/src/client/videoValidation.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';++import { validateVideoFileSize } from './videoValidation';++describe('validateVideoFileSize', () => {+ it('should return valid for non-video files', () => {+ const mockFile = new File(['test'], 'test.txt', { type: 'text/plain' });+ const result = validateVideoFileSize(mockFile);++ expect(result.isValid).toBe(true);+ expect(result.actualSize).toBeUndefined();+ });++ it('should return valid for video files under 20MB', () => {+ const mockVideoFile = new File(['x'.repeat(10 * 1024 * 1024)], 'video.mp4', {+ type: 'video/mp4',+ });+ const result = validateVideoFileSize(mockVideoFile);++ expect(result.isValid).toBe(true);+ expect(result.actualSize).toBe('10.0 MB');+ });++ it('should return invalid for video files over 20MB', () => {+ const mockLargeVideoFile = new File(['x'.repeat(25 * 1024 * 1024)], 'large-video.mp4', {+ type: 'video/mp4',+ });+ const result = validateVideoFileSize(mockLargeVideoFile);++ expect(result.isValid).toBe(false);+ expect(result.actualSize).toBe('25.0 MB');+ });++ it('should return invalid for video files exactly at 20MB limit plus 1 byte', () => {+ const mockBoundaryFile = new File(['x'.repeat(20 * 1024 * 1024 + 1)], 'boundary.mp4', {+ type: 'video/mp4',+ });+ const result = validateVideoFileSize(mockBoundaryFile);++ expect(result.isValid).toBe(false);+ expect(result.actualSize).toBe('20.0 MB');+ });++ it('should return valid for video files exactly at 20MB limit', () => {+ const mockBoundaryFile = new File(['x'.repeat(20 * 1024 * 1024)], 'boundary.mp4', {+ type: 'video/mp4',+ });+ const result = validateVideoFileSize(mockBoundaryFile);++ expect(result.isValid).toBe(true);+ expect(result.actualSize).toBe('20.0 MB');+ });+});diff --git a/packages/utils/src/client/videoValidation.ts b/packages/utils/src/client/videoValidation.tsnew file mode 100644index 00000000000..68f172d5032--- /dev/null+++ b/packages/utils/src/client/videoValidation.ts@@ -0,0 +1,21 @@+import { formatSize } from '../format';++const VIDEO_SIZE_LIMIT = 20 * 1024 * 1024; // 20MB in bytes++export interface VideoValidationResult {+ actualSize?: string;+ isValid: boolean;+}++export const validateVideoFileSize = (file: File): VideoValidationResult => {+ if (!file.type.startsWith('video/')) {+ return { isValid: true };+ }++ const isValid = file.size <= VIDEO_SIZE_LIMIT;++ return {+ actualSize: formatSize(file.size),+ isValid,+ };+};diff --git a/packages/utils/src/parseModels.ts b/packages/utils/src/parseModels.tsindex 6b142370643..68f3f1b0669 100644--- a/packages/utils/src/parseModels.ts+++ b/packages/utils/src/parseModels.ts@@ -90,6 +90,10 @@ export const parseModelString = async (model.abilities!.files = true;break;}+ case 'video': {+ model.abilities!.video = true;+ break;+ }case 'search': {model.abilities!.search = true;break;diff --git a/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/useSend.ts b/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/useSend.tsindex ca250735672..c212f4e4fff 100644--- a/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/useSend.ts+++ b/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/useSend.ts@@ -38,13 +38,14 @@ export const useSend = () => {const { analytics } = useAnalytics();const checkGeminiChineseWarning = useGeminiChineseWarning();- const fileList = fileChatSelectors.chatUploadFileList(useFileStore.getState());+ // 使用订阅以保持最新文件列表+ const reactiveFileList = useFileStore(fileChatSelectors.chatUploadFileList);const [isUploadingFiles, clearChatUploadFileList] = useFileStore((s) => [fileChatSelectors.isUploadingFiles(s),s.clearChatUploadFileList,]);- const isInputEmpty = isContentEmpty && fileList.length === 0;+ const isInputEmpty = isContentEmpty && reactiveFileList.length === 0;const canNotSend =isInputEmpty || isUploadingFiles || isSendButtonDisabledByMessage || isSendingMessage;@@ -63,6 +64,8 @@ export const useSend = () => {if (chatSelectors.isAIGenerating(store)) return;const inputMessage = store.inputMessage;+ // 发送时再取一次最新的文件列表,防止闭包拿到旧值+ const fileList = fileChatSelectors.chatUploadFileList(useFileStore.getState());// if there is no message and no image, then we should not send the messageif (!inputMessage && fileList.length === 0) return;@@ -92,9 +95,11 @@ export const useSend = () => {// 获取分析数据const userStore = getUserStoreState();- // 直接使用现有数据结构判断消息类型+ // 直接使用现有数据结构判断消息类型(支持 video)const hasImages = fileList.some((file) => file.file?.type?.startsWith('image'));- const messageType = fileList.length === 0 ? 'text' : hasImages ? 'image' : 'file';+ const hasVideos = fileList.some((file) => file.file?.type?.startsWith('video'));+ const messageType =+ fileList.length === 0 ? 'text' : hasVideos ? 'video' : hasImages ? 'image' : 'file';analytics?.track({name: 'send_message',diff --git a/src/components/ModelSelect/index.tsx b/src/components/ModelSelect/index.tsxindex a19c6fc41eb..68080a3d191 100644--- a/src/components/ModelSelect/index.tsx+++ b/src/components/ModelSelect/index.tsx@@ -1,3 +1,4 @@+import { ChatModelCard } from '@lobechat/types';import { IconAvatarProps, ModelIcon, ProviderIcon } from '@lobehub/icons';import { Avatar, Icon, Tag, Text, Tooltip } from '@lobehub/ui';import { createStyles, useResponsive } from 'antd-style';@@ -9,15 +10,15 @@ import {LucideImage,LucidePaperclip,ToyBrick,+ Video,} from 'lucide-react';+import { ModelAbilities } from 'model-bank';import numeral from 'numeral';import { FC, memo } from 'react';import { useTranslation } from 'react-i18next';import { Flexbox } from 'react-layout-kit';-import { ModelAbilities } from '../../../packages/model-bank/src/types/aiModel';import { AiProviderSourceType } from '@/types/aiProvider';-import { ChatModelCard } from '@/types/llm';import { formatTokenNumber } from '@/utils/format';export const TAG_CLASSNAME = 'lobe-model-info-tags';@@ -99,6 +100,17 @@ export const ModelInfoTags = memo<ModelInfoTagsProps>(</Tag></Tooltip>)}+ {model.video && (+ <Tooltip+ placement={placement}+ styles={{ root: { pointerEvents: 'none' } }}+ title={t('ModelSelect.featureTag.video')}+ >+ <Tag className={styles.tag} color={'magenta'} size={'small'}>+ <Icon icon={Video} />+ </Tag>+ </Tooltip>+ )}{model.functionCall && (<Tooltipplacement={placement}diff --git a/src/features/ChatInput/ActionBar/Upload/ClientMode.tsx b/src/features/ChatInput/ActionBar/Upload/ClientMode.tsxindex 26c2e3e85c0..35fc0a8014a 100644--- a/src/features/ChatInput/ActionBar/Upload/ClientMode.tsx+++ b/src/features/ChatInput/ActionBar/Upload/ClientMode.tsx@@ -4,6 +4,7 @@ import { FileUp, LucideImage } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { message } from '@/components/AntdStaticMethods';import { useModelSupportFiles } from '@/hooks/useModelSupportFiles';import { useModelSupportVision } from '@/hooks/useModelSupportVision';import { useAgentStore } from '@/store/agent';@@ -26,6 +27,12 @@ const FileUpload = memo(() => {<Uploadaccept={enabledFiles ? undefined : 'image/*'}beforeUpload={async (file) => {+ // Check if trying to upload non-image files in client mode+ if (!enabledFiles && !file.type.startsWith('image')) {+ message.warning(t('upload.clientMode.fileNotSupported'));+ return false;+ }+await upload([file]);return false;diff --git a/src/features/ChatInput/ActionBar/Upload/ServerMode.tsx b/src/features/ChatInput/ActionBar/Upload/ServerMode.tsxindex 6f0032b5abd..11fef3023a2 100644--- a/src/features/ChatInput/ActionBar/Upload/ServerMode.tsx+++ b/src/features/ChatInput/ActionBar/Upload/ServerMode.tsx@@ -1,3 +1,4 @@+import { validateVideoFileSize } from '@lobechat/utils/client';import { MenuProps, Tooltip } from '@lobehub/ui';import { Upload } from 'antd';import { css, cx } from 'antd-style';@@ -5,9 +6,10 @@ import { FileUp, FolderUp, ImageUp, Paperclip } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { message } from '@/components/AntdStaticMethods';import { useModelSupportVision } from '@/hooks/useModelSupportVision';import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/slices/chat';+import { agentSelectors } from '@/store/agent/selectors';import { useFileStore } from '@/store/file';import Action from '../components/Action';@@ -61,7 +63,19 @@ const FileUpload = memo(() => {label: (<UploadbeforeUpload={async (file) => {- if (!canUploadImage && file.type.startsWith('image')) return false;+ if (!canUploadImage && (file.type.startsWith('image') || file.type.startsWith('video')))+ return false;++ // Validate video file size+ const validation = validateVideoFileSize(file);+ if (!validation.isValid) {+ message.error(+ t('upload.validation.videoSizeExceeded', {+ actualSize: validation.actualSize,+ }),+ );+ return false;+ }await upload([file]);@@ -80,7 +94,19 @@ const FileUpload = memo(() => {label: (<UploadbeforeUpload={async (file) => {- if (!canUploadImage && file.type.startsWith('image')) return false;+ if (!canUploadImage && (file.type.startsWith('image') || file.type.startsWith('video')))+ return false;++ // Validate video file size+ const validation = validateVideoFileSize(file);+ if (!validation.isValid) {+ message.error(+ t('upload.validation.videoSizeExceeded', {+ actualSize: validation.actualSize,+ }),+ );+ return false;+ }await upload([file]);diff --git a/src/features/ChatInput/components/UploadDetail/UploadStatus.tsx b/src/features/ChatInput/components/UploadDetail/UploadStatus.tsxindex 18d2b4f6346..a64bc0d6a16 100644--- a/src/features/ChatInput/components/UploadDetail/UploadStatus.tsx+++ b/src/features/ChatInput/components/UploadDetail/UploadStatus.tsx@@ -38,7 +38,7 @@ const UploadStatus = memo<UploadStateProps>(({ status, size, uploadState }) => {<Flexbox align={'center'} gap={4} horizontal><Progress percent={uploadState?.progress} size={14} type="circle" /><Text style={{ fontSize: 12 }} type={'secondary'}>- {formatSize(size * ((uploadState?.progress || 0) / 100), 0)} / {formatSize(size)}+ {formatSize(size * ((uploadState?.progress || 0) / 100), 0)}</Text></Flexbox>);diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsxindex fa8b21c33d6..ed7471c1170 100644--- a/src/features/Conversation/Messages/Assistant/index.tsx+++ b/src/features/Conversation/Messages/Assistant/index.tsx@@ -3,6 +3,7 @@ import { Flexbox } from 'react-layout-kit';import { LOADING_FLAT } from '@/const/message';import ImageFileListViewer from '@/features/Conversation/Messages/User/ImageFileListViewer';+import VideoFileListViewer from '@/features/Conversation/Messages/User/VideoFileListViewer';import { useChatStore } from '@/store/chat';import { aiChatSelectors, chatSelectors } from '@/store/chat/selectors';import { ChatMessage } from '@/types/message';@@ -18,7 +19,7 @@ export const AssistantMessage = memo<ChatMessage & {editableContent: ReactNode;}->(({ id, tools, content, chunksList, search, imageList, ...props }) => {+>(({ id, tools, content, chunksList, search, imageList, videoList, ...props }) => {const editing = useChatStore(chatSelectors.isMessageEditing(id));const generating = useChatStore(chatSelectors.isMessageGenerating(id));@@ -30,6 +31,7 @@ export const AssistantMessage = memo<const showSearch = !!search && !!search.citations?.length;const showImageItems = !!imageList && imageList.length > 0;+ const showVideoItems = !!videoList && videoList.length > 0;// remove \n to avoid empty content// refs: https://github.com/lobehub/lobe-chat/pull/6153@@ -67,6 +69,7 @@ export const AssistantMessage = memo<))}{showImageItems && <ImageFileListViewer items={imageList} />}+ {showVideoItems && <VideoFileListViewer items={videoList} />}{tools && (<Flexbox gap={8}>{tools.map((toolCall, index) => (diff --git a/src/features/Conversation/Messages/User/VideoFileListViewer.tsx b/src/features/Conversation/Messages/User/VideoFileListViewer.tsxnew file mode 100644index 00000000000..b06621620f9--- /dev/null+++ b/src/features/Conversation/Messages/User/VideoFileListViewer.tsx@@ -0,0 +1,31 @@+import { memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import { ChatVideoItem } from '@/types/message';++interface VideoFileListViewerProps {+ items: ChatVideoItem[];+}++const VideoFileListViewer = memo<VideoFileListViewerProps>(({ items }) => {+ return (+ <Flexbox gap={8}>+ {items.map((item) => (+ <video+ controls+ key={item.id}+ style={{+ borderRadius: 8,+ maxHeight: 400,+ maxWidth: '100%',+ }}+ >+ <source src={item.url} />+ {item.alt}+ </video>+ ))}+ </Flexbox>+ );+});++export default VideoFileListViewer;diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsxindex 31c8f362e7f..1854a327d81 100644--- a/src/features/Conversation/Messages/User/index.tsx+++ b/src/features/Conversation/Messages/User/index.tsx@@ -7,18 +7,20 @@ import { ChatMessage } from '@/types/message';import FileListViewer from './FileListViewer';import ImageFileListViewer from './ImageFileListViewer';+import VideoFileListViewer from './VideoFileListViewer';export const UserMessage = memo<ChatMessage & {editableContent: ReactNode;}->(({ id, editableContent, content, imageList, fileList }) => {+>(({ id, editableContent, content, imageList, videoList, fileList }) => {if (content === LOADING_FLAT) return <BubblesLoading />;return (<Flexbox gap={8} id={id}>{editableContent}{imageList && imageList?.length > 0 && <ImageFileListViewer items={imageList} />}+ {videoList && videoList?.length > 0 && <VideoFileListViewer items={videoList} />}{fileList && fileList?.length > 0 && (<div style={{ marginTop: 8 }}><FileListViewer items={fileList} />diff --git a/src/hooks/useModelSupportVideo.ts b/src/hooks/useModelSupportVideo.tsnew file mode 100644index 00000000000..e3ae608132a--- /dev/null+++ b/src/hooks/useModelSupportVideo.ts@@ -0,0 +1,10 @@+import { useAiInfraStore } from '@/store/aiInfra';+import { aiModelSelectors } from '@/store/aiInfra/selectors';++export const useModelSupportVideo = (id?: string, provider?: string) => {+ return useAiInfraStore((s) => {+ if (!id || !provider) return false;++ return aiModelSelectors.isModelSupportVideo(id, provider)(s);+ });+};diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex 9dcc452cb93..fd94c2339c0 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -285,6 +285,7 @@ export default {actionFiletip: '上传文件',actionTooltip: '上传',disabled: '当前模型不支持视觉识别和文件分析,请切换模型后使用',+ fileNotSupported: '浏览器模式下暂不支持上传文件,仅支持图片',visionNotSupported: '当前模型不支持视觉识别,请切换模型后使用',},preview: {@@ -294,6 +295,9 @@ export default {processing: '文件处理中...',},},+ validation: {+ videoSizeExceeded: '视频文件大小不能超过 20MB,当前文件大小为 {{actualSize}}',+ },},zenMode: '专注模式',};diff --git a/src/locales/default/components.ts b/src/locales/default/components.tsindex a9d8cabb099..60492df6d6e 100644--- a/src/locales/default/components.ts+++ b/src/locales/default/components.ts@@ -116,6 +116,7 @@ export default {reasoning: '该模型支持深度思考',search: '该模型支持联网搜索',tokens: '该模型单个会话最多支持 {{tokens}} Tokens',+ video: '该模型支持视频识别',vision: '该模型支持视觉识别',},removed: '该模型不在列表中,若取消选中将会自动移除',diff --git a/src/services/chat/contextEngineering.test.ts b/src/services/chat/contextEngineering.test.tsindex 63caba21444..6c565d7a026 100644--- a/src/services/chat/contextEngineering.test.ts+++ b/src/services/chat/contextEngineering.test.ts@@ -162,7 +162,6 @@ describe('contextEngineering', () => {<images_docstring>here are user upload images you can refer to</images_docstring><image name="abc.png" url="http://example.com/image.jpg"></image></images>-</files_info><!-- END SYSTEM CONTEXT -->`,type: 'text',diff --git a/src/services/chat/contextEngineering.ts b/src/services/chat/contextEngineering.tsindex 6a9d4c5f539..052c172653d 100644--- a/src/services/chat/contextEngineering.ts+++ b/src/services/chat/contextEngineering.ts@@ -23,7 +23,8 @@ import { toolSelectors } from '@/store/tool/selectors';import { VARIABLE_GENERATORS } from '@/utils/client/parserPlaceholder';import { genToolCallingName } from '@/utils/toolCall';-import { isCanUseFC, isCanUseVision } from './helper';+import { isCanUseFC, isCanUseVideo, isCanUseVision } from './helper';+interface ContextEngineeringContext {enableHistoryCount?: boolean;@@ -98,6 +99,7 @@ export const contextEngineering = async ({// 8. Message content processingnew MessageContentProcessor({fileContext: { enabled: isServerMode, includeFileUrl: !isDesktop },+ isCanUseVideo,isCanUseVision,model,provider,diff --git a/src/services/chat/helper.ts b/src/services/chat/helper.tsindex 5854e402c73..996f4897327 100644--- a/src/services/chat/helper.ts+++ b/src/services/chat/helper.ts@@ -23,6 +23,10 @@ export const isCanUseVision = (model: string, provider: string): boolean => {return aiModelSelectors.isModelSupportVision(model, provider)(getAiInfraStoreState());};+export const isCanUseVideo = (model: string, provider: string): boolean => {+ return aiModelSelectors.isModelSupportVideo(model, provider)(getAiInfraStoreState()) || false;+};+/*** TODO: we need to update this function to auto find deploymentName with provider setting config*/diff --git a/src/services/upload.ts b/src/services/upload.tsindex 6bbd61c7275..ebfbc8c11fa 100644--- a/src/services/upload.ts+++ b/src/services/upload.ts@@ -84,7 +84,7 @@ class UploadService {// upload to client s3// 客户端上传逻辑- if (!skipCheckFileType && !file.type.startsWith('image')) {+ if (!skipCheckFileType && !file.type.startsWith('image') && !file.type.startsWith('video')) {onNotSupported?.();return { data: undefined as unknown as FileMetadata, success: false };}diff --git a/src/store/aiInfra/slices/aiModel/selectors.ts b/src/store/aiInfra/slices/aiModel/selectors.tsindex 92777e7a207..fae1d0fb4bb 100644--- a/src/store/aiInfra/slices/aiModel/selectors.ts+++ b/src/store/aiInfra/slices/aiModel/selectors.ts@@ -62,6 +62,12 @@ const isModelSupportVision = (id: string, provider: string) => (s: AIProviderStoreturn model?.abilities?.vision || false;};+const isModelSupportVideo = (id: string, provider: string) => (s: AIProviderStoreState) => {+ const model = getEnabledModelById(id, provider)(s);++ return model?.abilities?.video;+};+const isModelSupportReasoning = (id: string, provider: string) => (s: AIProviderStoreState) => {const model = getEnabledModelById(id, provider)(s);@@ -136,6 +142,7 @@ export const aiModelSelectors = {isModelSupportFiles,isModelSupportReasoning,isModelSupportToolUse,+ isModelSupportVideo,isModelSupportVision,modelBuiltinSearchImpl,modelContextWindowTokens,diff --git a/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts b/src/store/chat/slices/aiChat/actions/generateAIChatV2.tsindex 580d7b7a2bb..a3d01d2bda6 100644--- a/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts+++ b/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts@@ -23,8 +23,11 @@ import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/slices/cimport { aiModelSelectors, aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';import { MainSendMessageOperation } from '@/store/chat/slices/aiChat/initialState';import type { ChatStore } from '@/store/chat/store';+import { getFileStoreState } from '@/store/file/store';import { getSessionStoreState } from '@/store/session';import { WebBrowsingManifest } from '@/tools/web-browsing';+import { ChatImageItem } from '@/types/message/image';+import { ChatVideoItem } from '@/types/message/video';import { setNamespace } from '@/utils/storeDebug';import { chatSelectors, topicSelectors } from '../../../selectors';@@ -107,6 +110,23 @@ export const generateAIChatV2: StateCreator<const messages = chatSelectors.activeBaseChats(get());+ // 构造服务端模式临时消息的本地媒体预览(优先使用 S3 URL)+ const filesInStore = getFileStoreState().chatUploadFileList;+ const tempImages: ChatImageItem[] = filesInStore+ .filter((f) => f.file?.type?.startsWith('image'))+ .map((f) => ({+ id: f.id,+ url: f.fileUrl || f.base64Url || f.previewUrl || '',+ alt: f.file?.name || f.id,+ }));+ const tempVideos: ChatVideoItem[] = filesInStore+ .filter((f) => f.file?.type?.startsWith('video'))+ .map((f) => ({+ id: f.id,+ url: f.fileUrl || f.base64Url || f.previewUrl || '',+ alt: f.file?.name || f.id,+ }));+// use optimistic update to avoid the slow waitingconst tempId = get().internal_createTmpMessage({content: message,@@ -117,6 +137,8 @@ export const generateAIChatV2: StateCreator<// if there is activeTopicId,then add topicId to messagetopicId: activeTopicId,threadId: activeThreadId,+ imageList: tempImages.length > 0 ? tempImages : undefined,+ videoList: tempVideos.length > 0 ? tempVideos : undefined,});get().internal_toggleMessageLoading(true, tempId);diff --git a/src/store/chat/slices/message/action.ts b/src/store/chat/slices/message/action.tsindex abb1cfaac2a..596efd0bcae 100644--- a/src/store/chat/slices/message/action.ts+++ b/src/store/chat/slices/message/action.ts@@ -1,6 +1,20 @@/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */// Disable the auto sort key eslint rule to make the code more logic and readable-import { ChatErrorType, TraceEventType } from '@lobechat/types';+import {+ ChatErrorType,+ ChatImageItem,+ ChatMessage,+ ChatMessageError,+ ChatMessagePluginError,+ CreateMessageParams,+ GroundingSearch,+ MessageMetadata,+ MessageToolCall,+ ModelReasoning,+ TraceEventPayloads,+ TraceEventType,+ UpdateMessageRAGParams,+} from '@lobechat/types';import { copyToClipboard } from '@lobehub/ui';import isEqual from 'fast-deep-equal';import { SWRResponse, mutate } from 'swr';@@ -12,19 +26,6 @@ import { topicService } from '@/services/topic';import { traceService } from '@/services/trace';import { ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';-import {- ChatMessage,- ChatMessageError,- ChatMessagePluginError,- CreateMessageParams,- MessageMetadata,- MessageToolCall,- ModelReasoning,-} from '@/types/message';-import { ChatImageItem } from '@/types/message/image';-import { UpdateMessageRAGParams } from '@/types/message/rag';-import { GroundingSearch } from '@/types/search';-import { TraceEventPayloads } from '@/types/trace';import { Action, setNamespace } from '@/utils/storeDebug';import { nanoid } from '@/utils/uuid';