🤯 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
⚡️ perf: add quiet message batch mutation (#16863)
Arvin Xu1cd906be3fe9
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.tsindex 2c728731d11..c6594babe21 100644--- a/apps/server/src/routers/lambda/message.ts+++ b/apps/server/src/routers/lambda/message.ts@@ -19,7 +19,7 @@ import { CompressionRepository } from '@/database/repositories/compression';import { publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { FileService } from '@/server/services/file';-import { MessageService } from '@/server/services/message';+import { type MessageBatchOperation, MessageService } from '@/server/services/message';import { resolveAgentIdFromSession, resolveContext } from './_helpers/resolveContext';import { basicContextSchema } from './_schema/context';@@ -54,6 +54,28 @@ const messageAnalyticsSchema = z.object({topicId: z.string().optional(),});+const messageBatchOperationSchema = z.discriminatedUnion('type', [+ z.object({+ message: CreateNewMessageParamsSchema,+ type: z.literal('createMessage'),+ }),+ z.object({+ id: z.string(),+ type: z.literal('updateMessage'),+ value: UpdateMessageParamsSchema,+ }),+ z.object({+ id: z.string(),+ type: z.literal('updateToolMessage'),+ value: z.object({+ content: z.string().optional(),+ metadata: z.record(z.string(), z.any()).optional(),+ pluginError: z.any().optional(),+ pluginState: z.record(z.string(), z.any()).optional(),+ }),+ }),+]);+export const messageRouter = router({addFilesToMessage: messageProcedure.use(withScopedPermission('message:update'))@@ -77,6 +99,45 @@ export const messageRouter = router({return ctx.messageService.addFilesToMessage(id, fileIds, resolved);}),+ batchMutate: messageProcedure+ .use(withScopedPermission('message:create'))+ .use(withScopedPermission('message:update'))+ .input(+ z.object({+ operations: z.array(messageBatchOperationSchema).min(1).max(200),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const operations: MessageBatchOperation[] = await Promise.all(+ input.operations.map(async (operation): Promise<MessageBatchOperation> => {+ if (+ operation.type !== 'createMessage' ||+ operation.message.agentId ||+ !operation.message.sessionId+ ) {+ return operation as MessageBatchOperation;+ }++ const agentId = await resolveAgentIdFromSession(+ operation.message.sessionId,+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ );++ return {+ ...operation,+ message: {+ ...operation.message,+ agentId: agentId!,+ },+ } as MessageBatchOperation;+ }),+ );++ return ctx.messageService.batchMutate(operations);+ }),+/*** Cancel compression by deleting the compression group and restoring original messages*/@@ -115,11 +176,9 @@ export const messageRouter = router({return ctx.messageModel.queryAll(input);}),- count: messageProcedure- .input(messageAnalyticsSchema.optional())- .query(async ({ ctx, input }) => {- return ctx.messageModel.count(input);- }),+ count: messageProcedure.input(messageAnalyticsSchema.optional()).query(async ({ ctx, input }) => {+ return ctx.messageModel.count(input);+ }),/*** Count messages grouped by topic (server-side GROUP BY), sorted by countdiff --git a/apps/server/src/services/message/__tests__/index.test.ts b/apps/server/src/services/message/__tests__/index.test.tsindex 3a50bcd9c69..7f5fe5cdae4 100644--- a/apps/server/src/services/message/__tests__/index.test.ts+++ b/apps/server/src/services/message/__tests__/index.test.ts@@ -28,6 +28,7 @@ describe('MessageService', () => {updateMessageRAG: vi.fn(),updateMetadata: vi.fn(),updatePluginState: vi.fn(),+ updateToolMessage: vi.fn(),} as any;mockFileService = {@@ -223,6 +224,77 @@ describe('MessageService', () => {});});+ describe('batchMutate', () => {+ it('quietly applies create/update/tool updates without querying messages', async () => {+ vi.mocked(mockMessageModel.create).mockResolvedValue({ id: 'msg-created' } as any);+ vi.mocked(mockMessageModel.update).mockResolvedValue({ success: true } as any);+ vi.mocked(mockMessageModel.updateToolMessage).mockResolvedValue({ success: true } as any);++ const result = await messageService.batchMutate([+ {+ message: { content: '', id: 'msg-created', role: 'assistant', topicId: 'topic-1' } as any,+ type: 'createMessage',+ },+ {+ id: 'msg-created',+ type: 'updateMessage',+ value: { content: 'hello' } as any,+ },+ {+ id: 'tool-1',+ type: 'updateToolMessage',+ value: { content: 'tool result' },+ },+ ]);++ expect(mockMessageModel.create).toHaveBeenCalledWith(+ { content: '', id: 'msg-created', role: 'assistant', topicId: 'topic-1' },+ 'msg-created',+ );+ expect(mockMessageModel.update).toHaveBeenCalledWith('msg-created', { content: 'hello' });+ expect(mockMessageModel.updateToolMessage).toHaveBeenCalledWith('tool-1', {+ content: 'tool result',+ });+ expect(mockMessageModel.query).not.toHaveBeenCalled();+ expect(result).toEqual({+ results: [+ { id: 'msg-created', index: 0, success: true, type: 'createMessage' },+ { id: 'msg-created', index: 1, success: true, type: 'updateMessage' },+ { id: 'tool-1', index: 2, success: true, type: 'updateToolMessage' },+ ],+ success: true,+ });+ });++ it('returns per-operation failures without throwing away later operations', async () => {+ vi.mocked(mockMessageModel.create).mockRejectedValueOnce(new Error('create failed'));+ vi.mocked(mockMessageModel.update).mockResolvedValue({ success: true } as any);++ const result = await messageService.batchMutate([+ {+ message: { content: '', id: 'missing-assistant', role: 'assistant' } as any,+ type: 'createMessage',+ },+ {+ id: 'still-runs',+ type: 'updateMessage',+ value: { content: 'still runs' } as any,+ },+ ]);++ expect(mockMessageModel.update).toHaveBeenCalledWith('still-runs', {+ content: 'still runs',+ });+ expect(result).toEqual({+ results: [+ { id: 'missing-assistant', index: 0, success: false, type: 'createMessage' },+ { id: 'still-runs', index: 1, success: true, type: 'updateMessage' },+ ],+ success: false,+ });+ });+ });+describe('updateMetadata', () => {it('should update metadata and return { success: true } when no sessionId/topicId provided', async () => {const messageId = 'msg-1';diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.tsindex afbc81fb876..60609cad269 100644--- a/apps/server/src/services/message/index.ts+++ b/apps/server/src/services/message/index.ts@@ -42,6 +42,27 @@ interface CreateMessageResult {messages: any[];}+export type MessageBatchOperation =+ | {+ message: CreateMessageParams;+ type: 'createMessage';+ }+ | {+ id: string;+ type: 'updateMessage';+ value: UpdateMessageParams;+ }+ | {+ id: string;+ type: 'updateToolMessage';+ value: {+ content?: string;+ metadata?: Record<string, any>;+ pluginError?: any;+ pluginState?: Record<string, any>;+ };+ };+/*** Message Service*@@ -125,6 +146,57 @@ export class MessageService {return this.messageModel.query(params, this.getQueryOptions());}+ /**+ * Quiet write-behind batch for streaming runtimes. Unlike createMessage /+ * updateMessage, this intentionally does not query the full message list after+ * each write; callers flush before reconciliation boundaries themselves.+ */+ async batchMutate(operations: MessageBatchOperation[]): Promise<{+ results: {+ id?: string;+ index: number;+ success: boolean;+ type: MessageBatchOperation['type'];+ }[];+ success: boolean;+ }> {+ const results: {+ id?: string;+ index: number;+ success: boolean;+ type: MessageBatchOperation['type'];+ }[] = [];++ for (const [index, operation] of operations.entries()) {+ try {+ if (operation.type === 'createMessage') {+ const item = await this.messageModel.create(operation.message, operation.message.id);+ results.push({ id: item.id, index, success: true, type: operation.type });+ continue;+ }++ if (operation.type === 'updateToolMessage') {+ const result = await this.messageModel.updateToolMessage(operation.id, operation.value);+ results.push({ id: operation.id, index, success: result.success, type: operation.type });+ continue;+ }++ const result = await this.messageModel.update(operation.id, operation.value as any);+ results.push({ id: operation.id, index, success: result.success, type: operation.type });+ } catch (error) {+ console.error('[MessageService] batchMutate operation failed:', error);+ results.push({+ id: operation.type === 'createMessage' ? operation.message.id : operation.id,+ index,+ success: false,+ type: operation.type,+ });+ }+ }++ return { results, success: results.every((result) => result.success) };+ }+/*** Create a new message and return the complete message list* Pattern: create + query