Skip to content

🤯 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.

✨ feat(im): support uploaded message attachments (#21581)

Inneic83244a37e8e
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index d4ae7914b1e..dec5c90e53f 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -547,11 +547,13 @@ export class AiAgentService {
* 2. Delegate to execAgent for the rest
*/
async execGroupAgent(
- params: ExecGroupAgentParams & Pick<InternalExecAgentParams, 'clientIds' | 'interactiveStart'>,
+ params: ExecGroupAgentParams &
+ Pick<InternalExecAgentParams, 'clientIds' | 'fileIds' | 'interactiveStart'>,
): Promise<ExecGroupAgentResult> {
const {
agentId,
clientIds,
+ fileIds,
groupId,
interactiveStart,
message,
@@ -594,6 +596,7 @@ export class AiAgentService {
appContext: { groupId, orchestrationRole: 'supervisor', topicId },
autoStart: true,
clientIds,
+ fileIds,
interactiveStart,
prompt: message,
trigger: RequestTrigger.Chat,
diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.yml
index 9b54db9ff2b..35077d11271 100644
--- a/packages/openapi/openapi.yml
+++ b/packages/openapi/openapi.yml
@@ -13548,6 +13548,28 @@ paths:
type: string
error:
type: boolean
+ files:
+ type: array
+ items:
+ type: object
+ additionalProperties: false
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ fileType:
+ type: string
+ size:
+ type: number
+ url:
+ type: string
+ required:
+ - id
+ - name
+ - fileType
+ - size
+ - url
id:
type: string
role:
@@ -13653,8 +13675,13 @@ paths:
pattern: ^msg_[\w-]{8,64}$
content:
type: string
- minLength: 1
maxLength: 100000
+ fileIds:
+ maxItems: 10
+ type: array
+ items:
+ type: string
+ minLength: 1
groupId:
type: string
minLength: 1
@@ -13676,8 +13703,13 @@ paths:
pattern: ^msg_[\w-]{8,64}$
content:
type: string
- minLength: 1
maxLength: 100000
+ fileIds:
+ maxItems: 10
+ type: array
+ items:
+ type: string
+ minLength: 1
groupId:
type: string
minLength: 1
@@ -13722,6 +13754,28 @@ paths:
type: string
error:
type: boolean
+ files:
+ type: array
+ items:
+ type: object
+ additionalProperties: false
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ fileType:
+ type: string
+ size:
+ type: number
+ url:
+ type: string
+ required:
+ - id
+ - name
+ - fileType
+ - size
+ - url
id:
type: string
role:
diff --git a/packages/openapi/src/services/__tests__/im.service.test.ts b/packages/openapi/src/services/__tests__/im.service.test.ts
index c4256188ee1..3771b681766 100644
--- a/packages/openapi/src/services/__tests__/im.service.test.ts
+++ b/packages/openapi/src/services/__tests__/im.service.test.ts
@@ -8,7 +8,9 @@ import {
agents,
chatGroups,
chatGroupsAgents,
+ files,
messages,
+ messagesFiles,
pushLiveActivities,
pushTokens,
topics,
@@ -102,6 +104,7 @@ beforeEach(async () => {
await db.delete(pushTokens);
await db.delete(agentOperations);
await db.delete(messages);
+ await db.delete(files);
await db.delete(topics);
await db.delete(chatGroupsAgents);
await db.delete(chatGroups);
@@ -113,6 +116,55 @@ beforeEach(async () => {
});
describe('ImRestService.sync — whole-message delivery', () => {
+ it('delivers and counts an attachment-only assistant reply and allows marking it read', async () => {
+ await db.insert(files).values({
+ id: 'file_reply',
+ userId: USER,
+ name: 'reply.png',
+ fileType: 'image/png',
+ size: 123,
+ url: 'https://example.com/reply.png',
+ });
+ await insertMessage('msg_file_reply', 'assistant', '', '2026-10-04T10:00:00Z');
+ await db
+ .insert(messagesFiles)
+ .values({ fileId: 'file_reply', messageId: 'msg_file_reply', userId: USER });
+ const result = await service.sync(TOPIC, {});
+ expect(result.messages[0]).toMatchObject({ content: '', files: [{ id: 'file_reply' }] });
+ expect(result.unread).toBe(1);
+ await expect(service.markRead(TOPIC, { messageId: 'msg_file_reply' })).resolves.toEqual({
+ unread: 0,
+ });
+ });
+ it('returns attachment metadata with an attachment-only user message', async () => {
+ await db.insert(files).values({
+ id: 'file_tea',
+ userId: USER,
+ name: 'tea.png',
+ fileType: 'image/png',
+ size: 123,
+ url: 'https://example.com/tea.png',
+ });
+ await insertMessage('msg_photo', 'user', '', '2026-10-04T10:00:00Z');
+ await db
+ .insert(messagesFiles)
+ .values({ fileId: 'file_tea', messageId: 'msg_photo', userId: USER });
+
+ const result = await service.sync(TOPIC, {});
+ expect(result.messages[0]).toMatchObject({
+ content: '',
+ files: [
+ {
+ id: 'file_tea',
+ name: 'tea.png',
+ fileType: 'image/png',
+ size: 123,
+ url: 'https://example.com/tea.png',
+ },
+ ],
+ });
+ });
+
it('withholds the reply (placeholder included) while the run is in flight, then delivers it whole', async () => {
await insertMessage('msg_u1', 'user', 'hi', '2026-10-04T10:00:00.000100Z');
await insertMessage('msg_a1', 'assistant', '...', '2026-10-04T10:00:00.000300Z');
@@ -535,6 +587,71 @@ describe('ImRestService.send', () => {
expect(ImSendRequestSchema.safeParse({ content: 'hi', groupId: GROUP }).success).toBe(true);
});
+ it('accepts attachment-only messages but rejects an empty turn', () => {
+ expect(
+ ImSendRequestSchema.safeParse({ agentId: AGENT, content: '', fileIds: ['file_tea'] }).success,
+ ).toBe(true);
+ expect(
+ ImSendRequestSchema.safeParse({ agentId: AGENT, content: ' ', fileIds: [] }).success,
+ ).toBe(false);
+ expect(
+ ImSendRequestSchema.safeParse({ agentId: AGENT, content: '', fileIds: [''] }).success,
+ ).toBe(false);
+ });
+
+ it('rejects missing or inaccessible files before starting an agent', async () => {
+ await db.insert(files).values({
+ id: 'file_other',
+ userId: OTHER,
+ name: 'private.png',
+ fileType: 'image/png',
+ size: 123,
+ url: 'https://example.com/private.png',
+ });
+ for (const fileId of ['file_missing', 'file_other']) {
+ await expect(
+ service.send({ agentId: AGENT, content: 'look', fileIds: [fileId] }),
+ ).rejects.toThrow();
+ }
+ expect(execAgentMock).not.toHaveBeenCalled();
+ });
+
+ it('attaches uploaded files to an agent turn and retains them in an idempotent receipt', async () => {
+ await db.insert(files).values({
+ id: 'file_tea',
+ userId: USER,
+ name: 'tea.png',
+ fileType: 'image/png',
+ size: 123,
+ url: 'https://example.com/tea.png',
+ });
+ execAgentMock.mockImplementation(async (input) => {
+ await insertMessage('msg_file00001', 'user', input.prompt, '2026-10-04T10:00:00Z');
+ await insertMessage('msg_file_reply', 'assistant', '...', '2026-10-04T10:00:01Z');
+ for (const fileId of input.fileIds ?? []) {
+ await db.insert(messagesFiles).values({ fileId, messageId: 'msg_file00001', userId: USER });
+ }
+ return {
+ success: true,
+ operationId: 'op_file',
+ topicId: TOPIC,
+ userMessageId: 'msg_file00001',
+ };
+ });
+ const input = {
+ agentId: AGENT,
+ content: '',
+ fileIds: ['file_tea'],
+ clientMessageId: 'msg_file00001',
+ };
+ const sent = await service.send(input);
+ const retried = await service.send(input);
+ expect(sent.userMessage.files?.map((file) => file.id)).toEqual(['file_tea']);
+ expect(retried.userMessage.files).toEqual(sent.userMessage.files);
+ expect(retried.accepted).toBe(false);
+ expect(execAgentMock).toHaveBeenCalledTimes(1);
+ });
+
it('runs a group send through the group supervisor in a new group topic', async () => {
await insertGroup();
execGroupAgentMock.mockImplementation(async () => {
diff --git a/packages/openapi/src/services/im.service.ts b/packages/openapi/src/services/im.service.ts
index b133927ac49..61d48d11893 100644
--- a/packages/openapi/src/services/im.service.ts
+++ b/packages/openapi/src/services/im.service.ts
@@ -4,12 +4,14 @@ import { and, asc, desc, eq, inArray, isNull, lte, type SQL, sql } from 'drizzle
import type { AnyPgColumn } from 'drizzle-orm/pg-core';
import { ChatGroupModel } from '@/database/models/chatGroup';
+import { FileModel } from '@/database/models/file';
import { PushLiveActivityModel, PushTokenModel } from '@/database/models/pushToken';
import { TopicModel } from '@/database/models/topic';
-import { agentOperations, messages, pushTokens, topics } from '@/database/schemas';
+import { agentOperations, messages, messagesFiles, pushTokens, topics } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
import { AiAgentService } from '@/server/services/aiAgent';
+import { FileService } from '@/server/services/file';
import { BaseService } from '../common/base.service';
import type { ServiceResult } from '../types';
@@ -123,12 +125,18 @@ const toImMessage = (row: Omit<MessageRow, 'createdAtUs'>): ImMessage => ({
* words. Expressed in SQL as well ({@link visibleRow}) so a `limit` counts
* bubbles rather than the working rows hidden behind them.
*/
-const VISIBLE_BUBBLE = sql`(${messages.error} is not null or (btrim(coalesce(${messages.content}, '')) <> '' and btrim(coalesce(${messages.content}, '')) <> ${LOADING_PLACEHOLDER}))`;
+const HAS_FILES = sql<boolean>`exists (select 1 from ${messagesFiles} where ${messagesFiles.messageId} = ${messages.id})`;
+const VISIBLE_BUBBLE = sql`(${messages.error} is not null or ${HAS_FILES} or (btrim(coalesce(${messages.content}, '')) <> '' and btrim(coalesce(${messages.content}, '')) <> ${LOADING_PLACEHOLDER}))`;
const visibleRow = (): SQL => sql`(${messages.role} = 'user' or ${VISIBLE_BUBBLE})`;
/** JS twin of {@link VISIBLE_BUBBLE}'s agent branch: a row that says something (or failed). */
-const isDeliveredAgentRow = (row: { content: string | null; error: unknown }) => {
+const isDeliveredAgentRow = (row: {
+ content: string | null;
+ error: unknown;
+ hasFiles: boolean;
+}) => {
+ if (row.hasFiles) return true;
if (row.error !== null && row.error !== undefined) return true;
const content = (row.content ?? '').trim();
return content !== '' && content !== LOADING_PLACEHOLDER;
@@ -187,6 +195,15 @@ export class ImRestService extends BaseService {
const receipt = await this.idempotentReceipt(input.clientMessageId);
if (receipt) return receipt;
+ if (input.fileIds?.length) {
+ const accessible = await new FileModel(this.db, this.userId, this.workspaceId).findByIds(
+ input.fileIds,
+ );
+ if (accessible.length !== new Set(input.fileIds).size) {
+ throw this.createAuthorizationError('One or more attachments are unavailable');
+ }
+ }
+
const aiAgentService = new AiAgentService(this.db, this.userId, {
workspaceId: this.workspaceId,
});
@@ -200,6 +217,7 @@ export class ImRestService extends BaseService {
? await aiAgentService.execGroupAgent({
agentId: supervisorId,
clientIds,
+ ...(input.fileIds?.length ? { fileIds: input.fileIds } : {}),
groupId: input.groupId,
interactiveStart: true,
message: input.content,
@@ -209,6 +227,7 @@ export class ImRestService extends BaseService {
agentId: input.agentId,
appContext: input.topicId ? { topicId: input.topicId } : undefined,
clientIds,
+ ...(input.fileIds?.length ? { fileIds: input.fileIds } : {}),
interactiveStart: true,
prompt: input.content,
trigger: RequestTrigger.Chat,
@@ -237,7 +256,7 @@ export class ImRestService extends BaseService {
accepted: true,
operationId: result.operationId,
topicId: result.topicId,
- userMessage: toImMessage(userMessage),
+ userMessage: (await this.withFiles([userMessage]))[0]!,
};
}
@@ -382,7 +401,7 @@ export class ImRestService extends BaseService {
accepted: false,
operationId: null,
topicId: existing.topicId,
- userMessage: toImMessage(existing),
+ userMessage: (await this.withFiles([existing]))[0]!,
};
}
@@ -443,6 +462,56 @@ export class ImRestService extends BaseService {
return row;
}
+ private async withFiles(rows: Omit<MessageRow, 'createdAtUs'>[]): Promise<ImMessage[]> {
+ if (rows.length === 0) return [];
+ const links = await this.db
+ .select({ messageId: messagesFiles.messageId, fileId: messagesFiles.fileId })
+ .from(messagesFiles)
+ .where(
+ and(
+ inArray(
+ messagesFiles.messageId,
+ rows.map((row) => row.id),
+ ),
+ this.buildWorkspaceWhere(messagesFiles),
+ ),
+ );
+ if (links.length === 0) return rows.map(toImMessage);
+ const records = await new FileModel(this.db, this.userId, this.workspaceId).findByIds(
+ links.map((link) => link.fileId),
+ );
+ const attachments = new Map(
+ await Promise.all(
+ records.map(
+ async (file) =>
+ [
+ file.id,
+ {
+ id: file.id,
+ name: file.name,
+ fileType: file.fileType,
+ size: file.size,
+ url: file.url.startsWith('http')
+ ? file.url
+ : (await new FileService(this.db, this.userId, this.workspaceId).getFullFileUrl(
+ file.url,
+ )) || file.url,
+ },
+ ] as const,
+ ),
+ ),
+ );
+ return rows.map((row) => {
+ const files = links
+ .filter((link) => link.messageId === row.id)
+ .flatMap((link) => {
+ const file = attachments.get(link.fileId);
+ return file ? [file] : [];
+ });
+ return { ...toImMessage(row), ...(files.length ? { files } : {}) };
+ });
+ }
+
/** The newest top-level run on the conversation — the one the user is waiting on. */
private async latestRun(topicId: string): Promise<LatestRun | undefined> {
const [run] = await this.db
@@ -481,6 +550,7 @@ export class ImRestService extends BaseService {
}
private readonly rowSelect = {
+ hasFiles: HAS_FILES,
agentId: messages.agentId,
content: messages.content,
createdAt: messages.createdAt,
@@ -525,7 +595,7 @@ export class ImRestService extends BaseService {
return {
cursor,
- messages: delivered.map(toImMessage),
+ messages: await this.withFiles(delivered),
readUpTo: readUpTo && { messageId: readUpTo.messageId, readAt: readUpTo.readAt },
// `state` doubles as the long-poll's change token: it must move for every
// fact the client can observe, including a new message. It is deliberately
diff --git a/packages/openapi/src/spec.ts b/packages/openapi/src/spec.ts
index 2fd05b57f00..b6e025b5650 100644
--- a/packages/openapi/src/spec.ts
+++ b/packages/openapi/src/spec.ts
@@ -486,6 +486,21 @@ const imMessageSchema: SchemaObject = {
content: { type: 'string' },
createdAt: dateTime,
error: { type: 'boolean' },
+ files: {
+ type: 'array',
+ items: {
+ type: 'object',
+ additionalProperties: false,
+ properties: {
+ id: { type: 'string' },
+ name: { type: 'string' },
+ fileType: { type: 'string' },
+ size: { type: 'number' },
+ url: { type: 'string' },
+ },
+ required: ['id', 'name', 'fileType', 'size', 'url'],
+ },
+ },
id: { type: 'string' },
role: { enum: ['assistant', 'user'], type: 'string' },
},
diff --git a/packages/openapi/src/types/im.type.ts b/packages/openapi/src/types/im.type.ts
index 37cb232a049..976a0042c8a 100644
--- a/packages/openapi/src/types/im.type.ts
+++ b/packages/openapi/src/types/im.type.ts
@@ -27,7 +27,9 @@ const ImSendFieldsSchema = z.object({
.regex(/^msg_[\w-]{8,64}$/, 'clientMessageId must look like msg_<8-64 url-safe chars>')
.optional(),
/** The message text. */
- content: z.string().trim().min(1).max(100_000),
+ content: z.string().trim().max(100_000),
+ /** Already-uploaded files to attach to this turn. */
+ fileIds: z.array(z.string().min(1)).max(10).optional(),
/** The group chat the user is talking to; its supervisor orchestrates the members. */
groupId: z.string().min(1).optional(),
/** The conversation to continue; omit to start a new one for the agent or group. */
@@ -35,10 +37,14 @@ const ImSendFieldsSchema = z.object({
});
// A union rather than .refine() so the generated spec and SDK require a target too.
-export const ImSendRequestSchema = z.union([
- ImSendFieldsSchema.extend({ agentId: z.string().min(1) }),
- ImSendFieldsSchema.extend({ groupId: z.string().min(1) }),
-]);
+export const ImSendRequestSchema = z
+ .union([
+ ImSendFieldsSchema.extend({ agentId: z.string().min(1) }),
+ ImSendFieldsSchema.extend({ groupId: z.string().min(1) }),
+ ])
+ .refine((input) => input.content.length > 0 || !!input.fileIds?.length, {
+ message: 'A message needs text or an attachment',
+ });
export type ImSendRequest = z.infer<typeof ImSendRequestSchema>;
export const ImTopicParamSchema = z.object({
@@ -85,10 +91,19 @@ export interface ImMessage {
createdAt: string;
/** Set when the agent's turn failed; the client shows a retry affordance. */
error: boolean;
+ files?: ImAttachment[];
id: string;
role: 'assistant' | 'user';
}
+export interface ImAttachment {
+ fileType: string;
+ id: string;
+ name: string;
+ size: number;
+ url: string;
+}
+
export interface ImSendResult {
/** `false` when this was an idempotent retry of an already-received message. */
accepted: boolean;