🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(context-engine): keep SVG uploads out of vision image input (#20946)
YuTengjing305bddbe59e2
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.tsindex b7b9037f9d9..c60ac6156a4 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts@@ -489,6 +489,7 @@ describe('AiAgentService.execAgent - file upload handling', () => {{alt: 'photo.png',id: 'file-img-1',+ mimeType: 'image/png',url: 'https://s3.example.com/files/test-user-id/xxx/photo.png',},]);diff --git a/apps/server/src/services/file/resolveAttachments.test.ts b/apps/server/src/services/file/resolveAttachments.test.tsindex 82cd0002fa7..b1d809a1958 100644--- a/apps/server/src/services/file/resolveAttachments.test.ts+++ b/apps/server/src/services/file/resolveAttachments.test.ts@@ -94,6 +94,15 @@ describe('resolveAttachmentMetadata', () => {expect(mocks.findByIds).toHaveBeenCalledWith(['file-visitor'], fileAccessScope);expect(result.orderedFileIds).toEqual(['file-visitor']);+ // The model input layer reads the type to keep formats such as SVG out of vision parts.+ expect(result.imageList).toEqual([+ {+ alt: 'cat.png',+ id: 'file-visitor',+ mimeType: 'image/png',+ url: 'https://storage.example.com/agent-share/cat.png',+ },+ ]);});it('passes share provenance into document parsing', async () => {diff --git a/apps/server/src/services/file/resolveAttachments.ts b/apps/server/src/services/file/resolveAttachments.tsindex eef7ecf3856..610d9dd93cc 100644--- a/apps/server/src/services/file/resolveAttachments.ts+++ b/apps/server/src/services/file/resolveAttachments.ts@@ -136,7 +136,12 @@ export const resolveAttachmentsByFileIds = async ({const { file, fileType, resolvedUrl } = entry;result.orderedFileIds.push(file.id);if (fileType.startsWith('image')) {- result.imageList.push({ alt: file.name || 'image', id: file.id, url: resolvedUrl });+ result.imageList.push({+ alt: file.name || 'image',+ id: file.id,+ mimeType: fileType,+ url: resolvedUrl,+ });continue;}if (fileType.startsWith('video')) {diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.tsindex f42495ceb23..9dd32c60acb 100644--- a/packages/context-engine/src/processors/MessageContent.ts+++ b/packages/context-engine/src/processors/MessageContent.ts@@ -39,6 +39,31 @@ export const VISION_DOWNGRADE_PLACEHOLDER =const requiresVisualAnalysis = (mediaType: unknown): boolean =>typeof mediaType === 'string' && mediaType.split(';', 1)[0].trim().toLowerCase() === 'image/avif';+/**+ * Image formats no vision API accepts. Agent-mode uploads skip the chat+ * file-type whitelist, so an SVG still lands in `imageList`; sending it as an+ * `image_url` part makes every request in that topic fail with a 400.+ * Provider-specific formats (e.g. HEIC on Gemini) stay with each provider's+ * context builder, and images without a known type keep the previous behavior.+ */+const NON_VISION_IMAGE_TYPES = new Set(['image/svg+xml']);++const getUnsupportedVisionImageType = (image: {+ mimeType?: string;+ url?: string;+}): string | undefined => {+ const mimeType =+ image.mimeType ||+ (typeof image.url === 'string' ? parseDataUri(image.url).mimeType : undefined);+ if (!mimeType) return;++ const normalized = mimeType.split(';', 1)[0].trim().toLowerCase();+ return NON_VISION_IMAGE_TYPES.has(normalized) ? normalized : undefined;+};++const createUnsupportedImageFormatPlaceholder = (mimeType: string) =>+ `[image omitted: ${mimeType} is not a supported vision input format. Do not infer or describe the image. If the request depends on it, read the attached file with an available tool.]`;+/*** Heterogeneous-agent image uploads mirror each persisted image URL into tool* text as ``. Non-vision models must receive only the opaque@@ -261,11 +286,21 @@ export class MessageContentProcessor extends BaseProcessor {(!canUseVision && hasImages ? message.imageList.length : 0) +(!canUseVision ? arrayImageUrlCount : 0);- if (imageDowngradeCount > 0) {- const placeholders = Array.from(- { length: imageDowngradeCount },- () => VISION_DOWNGRADE_PLACEHOLDER,- ).join('\n');+ const unsupportedImageTypes: string[] = [];+ const visionImageList = canUseVision+ ? (message.imageList || []).filter((image: { mimeType?: string; url?: string }) => {+ const unsupportedType = getUnsupportedVisionImageType(image);+ if (unsupportedType) unsupportedImageTypes.push(unsupportedType);+ return !unsupportedType;+ })+ : [];++ const placeholders = [+ ...Array.from({ length: imageDowngradeCount }, () => VISION_DOWNGRADE_PLACEHOLDER),+ ...unsupportedImageTypes.map(createUnsupportedImageFormatPlaceholder),+ ].join('\n');++ if (placeholders) {textContent = textContent ? `${textContent}\n\n${placeholders}` : placeholders;}@@ -298,8 +333,8 @@ export class MessageContentProcessor extends BaseProcessor {}// Process image content (legacy imageList path)- if (hasImages && canUseVision) {- const imageContentParts = await this.processImageList(message.imageList || []);+ if (visionImageList.length > 0) {+ const imageContentParts = await this.processImageList(visionImageList);contentParts.push(...imageContentParts);}@@ -325,7 +360,7 @@ export class MessageContentProcessor extends BaseProcessor {// Explicitly return fields, keeping only necessary message fieldsconst hasFileContext =(hasFiles || hasImages || hasVideos || hasAudios) && this.config.fileContext?.enabled;- const hasVisionContent = (hasImages || arrayImageUrlCount > 0) && canUseVision;+ const hasVisionContent = (visionImageList.length > 0 || arrayImageUrlCount > 0) && canUseVision;const hasVideoContent = hasVideos && canUseVideo;const hasAudioContent = hasAudios && canUseAudio;diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.unsupportedImageFormat.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.unsupportedImageFormat.test.tsnew file mode 100644index 00000000000..681759ff1e9--- /dev/null+++ b/packages/context-engine/src/processors/__tests__/MessageContent.unsupportedImageFormat.test.ts@@ -0,0 +1,97 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { MessageContentProcessor } from '../MessageContent';++const createContext = (messages: UIChatMessage[]): PipelineContext => ({+ initialState: { messages: [] } as any,+ isAborted: false,+ messages,+ metadata: { maxTokens: 100000, model: 'muse-wonder-1.0', provider: 'lobehub' },+});++const createProcessor = () =>+ new MessageContentProcessor({+ fileContext: { enabled: false },+ isCanUseVision: () => true,+ model: 'muse-wonder-1.0',+ provider: 'lobehub',+ });++const createUserMessage = (imageList: UIChatMessage['imageList']): UIChatMessage => ({+ content: 'Animate this',+ createdAt: Date.now(),+ id: 'msg-1',+ imageList,+ role: 'user',+ updatedAt: Date.now(),+});++describe('MessageContentProcessor unsupported image formats', () => {+ it('keeps an uploaded SVG out of image_url parts for a vision model', async () => {+ const result = await createProcessor().process(+ createContext([+ createUserMessage([+ {+ alt: 'Group 2.svg',+ id: 'file-svg',+ mimeType: 'image/svg+xml',+ url: 'https://example.com/group.svg',+ },+ {+ alt: 'photo.png',+ id: 'file-png',+ mimeType: 'image/png',+ url: 'https://example.com/photo.png',+ },+ ]),+ ]),+ );++ const content = result.messages[0].content as any[];+ expect(content.filter((part) => part.type === 'image_url')).toEqual([+ { image_url: { detail: 'auto', url: 'https://example.com/photo.png' }, type: 'image_url' },+ ]);+ expect(content[0].type).toBe('text');+ expect(content[0].text).toContain('image/svg+xml is not a supported vision input format');+ });++ it('downgrades an inline SVG data URI to text only', async () => {+ const result = await createProcessor().process(+ createContext([+ createUserMessage([+ { alt: 'inline.svg', id: 'file-svg', url: 'data:image/svg+xml;base64,PHN2Zy8+' },+ ]),+ ]),+ );++ // Only text remains, so the processor collapses content to a plain string.+ expect(result.messages[0].content).toBe(+ 'Animate this\n\n[image omitted: image/svg+xml is not a supported vision input format. Do not infer or describe the image. If the request depends on it, read the attached file with an available tool.]',+ );+ });++ it('keeps provider-specific and unknown image types for the provider to decide', async () => {+ const result = await createProcessor().process(+ createContext([+ createUserMessage([+ {+ alt: 'photo.heic',+ id: 'file-heic',+ mimeType: 'image/heic',+ url: 'https://example.com/photo.heic',+ },+ { alt: 'legacy', id: 'file-legacy', url: 'https://example.com/a' },+ ]),+ ]),+ );++ const content = result.messages[0].content as any[];+ expect(content).toEqual([+ { text: 'Animate this', type: 'text' },+ { image_url: { detail: 'auto', url: 'https://example.com/photo.heic' }, type: 'image_url' },+ { image_url: { detail: 'auto', url: 'https://example.com/a' }, type: 'image_url' },+ ]);+ });+});diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex 0a776d3e6da..5a819dda5ed 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -344,11 +344,12 @@ describe('MessageModel Query Tests', () => {alt: 'file-1',height: 600,id: 'f-0',+ mimeType: 'image/png',ratio: 1.3333,url: `${domain}/f-0/abc`,width: 800,},- { alt: 'file-3', id: 'f-3', url: `${domain}/f-3/abc` },+ { alt: 'file-3', id: 'f-3', mimeType: 'image/png', url: `${domain}/f-3/abc` },]);expect(postProcessUrl).toHaveBeenCalledWith('abc',@@ -358,7 +359,6 @@ describe('MessageModel Query Tests', () => {'abc',expect.objectContaining({ fileType: 'image/png', id: 'f-3' }),);-expect(result[1].id).toBe('2');expect(result[1].imageList).toEqual([]);});@@ -393,12 +393,12 @@ describe('MessageModel Query Tests', () => {);const result = await messageModel.queryByIds(['query-by-id-message'], { postProcessUrl });-expect(result[0].imageList).toEqual([{alt: 'query-by-id.png',height: 720,id: 'query-by-id-file',+ mimeType: 'image/png',ratio: 1.7778,url: '/f/query-by-id-file/files/query-by-id.png',width: 1280,diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex feadf845087..0f5721e45f3 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -145,40 +145,30 @@ const toFileDocumentsMap = (}, {});const createChatImageItem = ({+ fileType,id,metadata,name,url,}: {+ fileType?: string | null;id: string;metadata: unknown;name: string;url: string;}): ChatImageItem => {const imageMetadata = isPlainRecord(metadata) ? metadata : {};- const height =- typeof imageMetadata.height === 'number' &&- Number.isFinite(imageMetadata.height) &&- imageMetadata.height > 0- ? imageMetadata.height- : undefined;- const ratio =- typeof imageMetadata.ratio === 'number' &&- Number.isFinite(imageMetadata.ratio) &&- imageMetadata.ratio > 0- ? imageMetadata.ratio- : undefined;- const width =- typeof imageMetadata.width === 'number' &&- Number.isFinite(imageMetadata.width) &&- imageMetadata.width > 0- ? imageMetadata.width- : undefined;+ const toPositiveNumber = (value: unknown) =>+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;+ const height = toPositiveNumber(imageMetadata.height);+ const ratio = toPositiveNumber(imageMetadata.ratio);+ const width = toPositiveNumber(imageMetadata.width);return {alt: name,...(height && { height }),id,+ ...(fileType && { mimeType: fileType }),...(ratio && { ratio }),url,...(width && { width }),@@ -1884,8 +1874,8 @@ export class MessageModel {),imageList: imageList.filter((relation) => relation.messageId === item.id)- .map(({ id, metadata, name, url }) =>- createChatImageItem({ id, metadata, name: name!, url }),+ .map(({ fileType, id, metadata, name, url }) =>+ createChatImageItem({ fileType, id, metadata, name: name!, url }),),model,@@ -2783,8 +2773,8 @@ export class MessageModel {),imageList: imageList.filter((relation) => relation.messageId === item.id)- .map(({ id, metadata, name, url }) =>- createChatImageItem({ id, metadata, name: name!, url }),+ .map(({ fileType, id, metadata, name, url }) =>+ createChatImageItem({ fileType, id, metadata, name: name!, url }),),model,diff --git a/packages/types/src/message/common/image.ts b/packages/types/src/message/common/image.tsindex 4eec5d9302f..a0515a6f2ca 100644--- a/packages/types/src/message/common/image.ts+++ b/packages/types/src/message/common/image.ts@@ -5,6 +5,11 @@ export interface ChatImageItem {/** Intrinsic image height in pixels, when known from upload metadata. */height?: number;id: string;+ /**+ * MIME type of the stored file (e.g. `image/png`), when known. Used to keep+ * formats that vision APIs reject, such as `image/svg+xml`, out of model input.+ */+ mimeType?: string;/** Intrinsic aspect ratio (width / height), when known from upload metadata. */ratio?: number;url: string;@@ -16,6 +21,7 @@ export const ChatImageItemSchema = z.object({alt: z.string(),height: z.number().optional(),id: z.string(),+ mimeType: z.string().optional(),ratio: z.number().optional(),url: z.string(),width: z.number().optional(),