π€― 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
π¨ chore: support multimodal input for server-side agent execution (#13759)
Arvin Xu3ad124ac4fb8
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 19697ea4ae6..661092b246e 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -32,6 +32,14 @@ export interface ExecAgentParams {deviceId?: string;/** Optional existing message IDs to include in context */existingMessageIds?: string[];+ /**+ * File IDs of already-uploaded attachments to attach to the new user message.+ * Resolved server-side via FileModel.findByIds into imageList / videoList / fileList.+ * Use this when files were uploaded separately via the file upload flow+ * (e.g. SPA Gateway mode). For platform-adapter ingestion from raw URL/buffer,+ * use the internal `files` param instead.+ */+ fileIds?: string[];/** Additional system instructions appended after the agent's own system role */instructions?: string;/** Override the agent's default model */diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.tsindex 680a193ed3c..9b89b5478eb 100644--- a/src/server/routers/lambda/aiAgent.ts+++ b/src/server/routers/lambda/aiAgent.ts@@ -95,6 +95,8 @@ const ExecAgentSchema = zdeviceId: z.string().optional(),/** Optional existing message IDs to include in context */existingMessageIds: z.array(z.string()).optional().default([]),+ /** File IDs of already-uploaded attachments to attach to the new user message */+ fileIds: z.array(z.string()).optional(),/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId: z.string().optional(),/** The user input/prompt */@@ -530,6 +532,7 @@ export const aiAgentRouter = router({autoStart = true,deviceId,existingMessageIds = [],+ fileIds,parentMessageId,} = input;@@ -542,6 +545,7 @@ export const aiAgentRouter = router({autoStart,deviceId,existingMessageIds,+ fileIds,parentMessageId,prompt,// When parentMessageId is provided, this is a regeneration/continue β skip user message creationdiff --git a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts b/src/server/services/aiAgent/__tests__/execAgent.files.test.tsindex 1e290d78cbc..be743204753 100644--- a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.files.test.ts@@ -3,14 +3,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AiAgentService } from '../index';-const { mockMessageCreate, mockCreateOperation, mockIngestAttachment, mockParseFile } = vi.hoisted(- () => ({- mockCreateOperation: vi.fn(),- mockIngestAttachment: vi.fn(),- mockMessageCreate: vi.fn(),- mockParseFile: vi.fn(),- }),-);+const {+ mockMessageCreate,+ mockCreateOperation,+ mockIngestAttachment,+ mockParseFile,+ mockFindByIds,+} = vi.hoisted(() => ({+ mockCreateOperation: vi.fn(),+ mockFindByIds: vi.fn(),+ mockIngestAttachment: vi.fn(),+ mockMessageCreate: vi.fn(),+ mockParseFile: vi.fn(),+}));vi.mock('@/libs/trusted-client', () => ({generateTrustedClientToken: vi.fn().mockReturnValue(undefined),@@ -63,6 +68,12 @@ vi.mock('@/database/models/plugin', () => ({})),}));+vi.mock('@/database/models/file', () => ({+ FileModel: vi.fn().mockImplementation(() => ({+ findByIds: mockFindByIds,+ })),+}));+vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),@@ -407,4 +418,213 @@ describe('AiAgentService.execAgent - file upload handling', () => {expect(userMessageCall![0].files).toEqual([]);});});++ // βββ Already-uploaded attachments (SPA Gateway mode) βββ+ describe('when fileIds are provided (already-uploaded attachments)', () => {+ it('resolves image fileIds into imageList with full URLs and attaches them to the user message', async () => {+ mockFindByIds.mockResolvedValue([+ {+ id: 'file-img-1',+ fileType: 'image/png',+ name: 'photo.png',+ size: 2048,+ url: 'files/test-user-id/xxx/photo.png',+ },+ ]);++ await service.execAgent({+ agentId: 'agent-1',+ fileIds: ['file-img-1'],+ prompt: 'What is in this image?',+ });++ expect(mockFindByIds).toHaveBeenCalledWith(['file-img-1']);++ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');+ expect(userMessageCall![0].files).toEqual(['file-img-1']);++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ const lastMessage = createOpArgs.initialMessages.at(-1);++ expect(lastMessage.imageList).toEqual([+ {+ alt: 'photo.png',+ id: 'file-img-1',+ url: 'https://s3.example.com/files/test-user-id/xxx/photo.png',+ },+ ]);+ expect(lastMessage.videoList).toBeUndefined();+ expect(lastMessage.fileList).toBeUndefined();+ // parseFile is for documents only; image resolution must skip it+ expect(mockParseFile).not.toHaveBeenCalled();+ });++ it('parses document fileIds and populates fileList content', async () => {+ mockFindByIds.mockResolvedValue([+ {+ id: 'file-pdf-1',+ fileType: 'application/pdf',+ name: 'doc.pdf',+ size: 4096,+ url: 'files/test-user-id/xxx/doc.pdf',+ },+ ]);+ mockParseFile.mockResolvedValue({ content: 'parsed pdf body text' });++ await service.execAgent({+ agentId: 'agent-1',+ fileIds: ['file-pdf-1'],+ prompt: 'Summarize this document',+ });++ expect(mockParseFile).toHaveBeenCalledWith('file-pdf-1');++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ const lastMessage = createOpArgs.initialMessages.at(-1);++ expect(lastMessage.imageList).toBeUndefined();+ expect(lastMessage.fileList).toEqual([+ {+ content: 'parsed pdf body text',+ fileType: 'application/pdf',+ id: 'file-pdf-1',+ name: 'doc.pdf',+ size: 4096,+ url: 'https://s3.example.com/files/test-user-id/xxx/doc.pdf',+ },+ ]);+ });++ it('routes video fileIds into videoList (not imageList / fileList)', async () => {+ mockFindByIds.mockResolvedValue([+ {+ id: 'file-vid-1',+ fileType: 'video/mp4',+ name: 'clip.mp4',+ size: 67_890,+ url: 'files/test-user-id/xxx/clip.mp4',+ },+ ]);++ await service.execAgent({+ agentId: 'agent-1',+ fileIds: ['file-vid-1'],+ prompt: 'Describe this clip',+ });++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ const lastMessage = createOpArgs.initialMessages.at(-1);++ expect(lastMessage.imageList).toBeUndefined();+ expect(lastMessage.fileList).toBeUndefined();+ expect(lastMessage.videoList).toEqual([+ {+ alt: 'clip.mp4',+ id: 'file-vid-1',+ url: 'https://s3.example.com/files/test-user-id/xxx/clip.mp4',+ },+ ]);+ expect(mockParseFile).not.toHaveBeenCalled();+ });++ it('preserves the caller-provided ordering of fileIds across classifications', async () => {+ // DB often returns rows in different order than queried; we must follow caller order.+ mockFindByIds.mockResolvedValue([+ {+ id: 'file-img-1',+ fileType: 'image/png',+ name: 'a.png',+ size: 1,+ url: 'a.png',+ },+ {+ id: 'file-pdf-1',+ fileType: 'application/pdf',+ name: 'b.pdf',+ size: 2,+ url: 'b.pdf',+ },+ ]);+ mockParseFile.mockResolvedValue({ content: 'b-content' });++ await service.execAgent({+ agentId: 'agent-1',+ fileIds: ['file-pdf-1', 'file-img-1'],+ prompt: 'Mix of files',+ });++ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');+ // Caller order preserved on the stored message relation.+ expect(userMessageCall![0].files).toEqual(['file-pdf-1', 'file-img-1']);+ });++ it('skips missing file records with a warning instead of failing', async () => {+ // Only one of the two requested IDs exists.+ mockFindByIds.mockResolvedValue([+ {+ id: 'file-img-1',+ fileType: 'image/png',+ name: 'ok.png',+ size: 1,+ url: 'ok.png',+ },+ ]);++ await service.execAgent({+ agentId: 'agent-1',+ fileIds: ['file-img-1', 'file-missing'],+ prompt: 'Look at the good one',+ });++ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');+ expect(userMessageCall![0].files).toEqual(['file-img-1']);++ // Agent still runs end-to-end.+ expect(mockCreateOperation).toHaveBeenCalled();+ });++ it('deduplicates repeated fileIds before inserting the messages_files link', async () => {+ // messages_files has a composite PK on (file_id, message_id). Duplicate+ // fileIds would cause a constraint violation and abort the whole send.+ mockFindByIds.mockResolvedValue([+ {+ id: 'file-img-1',+ fileType: 'image/png',+ name: 'photo.png',+ size: 1,+ url: 'photo.png',+ },+ ]);++ await service.execAgent({+ agentId: 'agent-1',+ fileIds: ['file-img-1', 'file-img-1', 'file-img-1'],+ prompt: 'Triple duplicate',+ });++ // FileModel.findByIds sees deduped input (cheaper query)+ expect(mockFindByIds).toHaveBeenCalledWith(['file-img-1']);++ // Only one link row will be inserted+ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');+ expect(userMessageCall![0].files).toEqual(['file-img-1']);++ // And imageList only contains the image once (no duplicate rendering)+ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ const lastMessage = createOpArgs.initialMessages.at(-1);+ expect(lastMessage.imageList).toHaveLength(1);+ });++ it('no-ops cleanly when fileIds is an empty array', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ fileIds: [],+ prompt: 'Hello',+ });++ expect(mockFindByIds).not.toHaveBeenCalled();+ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');+ expect(userMessageCall![0].files).toBeUndefined();+ });+ });});diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 6b332cca35a..d774a5f3cd6 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -37,6 +37,7 @@ import debug from 'debug';import { AgentModel } from '@/database/models/agent';import { AgentSkillModel } from '@/database/models/agentSkill';import { AiModelModel } from '@/database/models/aiModel';+import { FileModel } from '@/database/models/file';import { MessageModel } from '@/database/models/message';import { PluginModel } from '@/database/models/plugin';import { ThreadModel } from '@/database/models/thread';@@ -226,6 +227,7 @@ export class AiAgentService {botPlatformContext,discordContext,existingMessageIds = [],+ fileIds: attachedFileIds,files,functionTools,hooks,@@ -977,6 +979,106 @@ export class AiAgentService {if (fileList.length === 0) fileList = undefined;}+ // 13b. Attach already-uploaded files referenced by fileIds (e.g. SPA Gateway mode).+ // These files are already in the `files` table; resolve URLs + classify, and+ // merge into the imageList/videoList/fileList passed to the LLM and stored+ // as message relations via messagesFiles.+ if (attachedFileIds && attachedFileIds.length > 0) {+ await throwIfExecutionAborted('file resolution');++ // Dedupe while preserving caller order. messages_files has a composite PK+ // on (file_id, message_id), so duplicate fileIds would violate the+ // constraint on messageModel.create and abort the whole send.+ const dedupedFileIds = Array.from(new Set(attachedFileIds));++ const fileModel = new FileModel(this.db, this.userId);+ const fileRecords = await fileModel.findByIds(dedupedFileIds);++ if (fileRecords.length > 0) {+ fileIds = fileIds ?? [];+ imageList = imageList ?? [];+ videoList = videoList ?? [];+ fileList = fileList ?? [];++ const documentService = new DocumentService(this.db, this.userId);++ // Preserve caller's ordering of fileIds so rendering matches upload order.+ const recordById = new Map(fileRecords.map((f) => [f.id, f]));++ for (const id of dedupedFileIds) {+ const file = recordById.get(id);+ if (!file) {+ warnings.push(`Attachment "${id}" was not found and skipped.`);+ continue;+ }++ fileIds.push(file.id);+ const resolvedUrl = (await fileService.getFullFileUrl(file.url)) || file.url;+ const fileType = file.fileType || '';++ if (fileType.startsWith('image')) {+ imageList.push({+ alt: file.name || 'image',+ id: file.id,+ url: resolvedUrl,+ });+ continue;+ }++ if (fileType.startsWith('video')) {+ videoList.push({+ alt: file.name || 'video',+ id: file.id,+ url: resolvedUrl,+ });+ continue;+ }++ // Non-image / non-video: ensure the document content is parsed so+ // MessageContentProcessor can inject it via filesPrompts(). parseFile+ // is idempotent β returns cached content when the document already exists.+ let content: string | undefined;+ try {+ const document = await documentService.parseFile(file.id);+ content = document.content ?? undefined;+ } catch (parseError) {+ log(+ 'execAgent: parseFile failed for attached file %s (id=%s): %O',+ file.name,+ file.id,+ parseError,+ );+ warnings.push(+ `File "${file.name || 'unknown'}" was attached but its contents could not be extracted.`,+ );+ }++ fileList.push({+ content,+ fileType: fileType || 'application/octet-stream',+ id: file.id,+ name: file.name || 'file',+ size: file.size ?? 0,+ url: resolvedUrl,+ });+ }++ log(+ 'execAgent: resolved %d attached file(s) (%d images, %d videos, %d documents)',+ fileRecords.length,+ imageList.length,+ videoList.length,+ fileList.length,+ );++ if (imageList.length === 0) imageList = undefined;+ if (videoList.length === 0) videoList = undefined;+ if (fileList.length === 0) fileList = undefined;+ } else {+ log('execAgent: no file records found for attachedFileIds=%O', dedupedFileIds);+ }+ }+await throwIfExecutionAborted('message creation');// 13. Create user message in databasediff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex c24b5ff5ee2..40351f4ba69 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -16,6 +16,8 @@ export interface ExecAgentTaskParams {autoStart?: boolean;deviceId?: string;existingMessageIds?: string[];+ /** File IDs of already-uploaded attachments to attach to the new user message */+ fileIds?: string[];/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId?: string;prompt: string;diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex c6b38cc7cc0..07ed479b9bf 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -347,6 +347,7 @@ export class ConversationLifecycleActionImpl {try {const result = await this.#get().executeGatewayAgent({context: operationContext,+ fileIds: fileIdList,message,});diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.tsindex 6eb24a46342..8df5a5a9573 100644--- a/src/store/chat/slices/aiChat/actions/gateway.ts+++ b/src/store/chat/slices/aiChat/actions/gateway.ts@@ -206,13 +206,15 @@ export class GatewayActionImpl {*/executeGatewayAgent = async (params: {context: ConversationContext;+ /** File IDs of already-uploaded attachments to attach to the new user message */+ fileIds?: string[];message: string;/** Called when the gateway session completes (agent finished running) */onComplete?: () => void;/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId?: string;}): Promise<ExecAgentResult> => {- const { context, message, onComplete, parentMessageId } = params;+ const { context, fileIds, message, onComplete, parentMessageId } = params;const agentGatewayUrl =window.global_serverConfigStore!.getState().serverConfig.agentGatewayUrl!;@@ -227,6 +229,7 @@ export class GatewayActionImpl {threadId: context.threadId,topicId: context.topicId,},+ fileIds,parentMessageId,prompt: message,});