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.

♻️ refactor: enhance message router with service layer and comprehensive tests (#10056)

Arvin Xu62110e08c86d
diff --git a/packages/database/src/models/__tests__/message.test.ts b/packages/database/src/models/__tests__/message.test.ts
index dabce45d29f..2b5fbaaec48 100644
--- a/packages/database/src/models/__tests__/message.test.ts
+++ b/packages/database/src/models/__tests__/message.test.ts
@@ -932,135 +932,6 @@ describe('MessageModel', () => {
});
});
- describe('createNewMessage', () => {
- it('should create message and return id with messages list', async () => {
- // Call createNewMessage method
- const result = await messageModel.createNewMessage({
- role: 'user',
- content: 'test message',
- sessionId: '1',
- });
-
- // Assert return structure
- expect(result).toHaveProperty('id');
- expect(result).toHaveProperty('messages');
- expect(result.id).toBeDefined();
- expect(result.messages).toBeInstanceOf(Array);
- });
-
- it('should return newly created message in messages list', async () => {
- const content = 'new test message ' + Date.now();
-
- const result = await messageModel.createNewMessage({
- role: 'user',
- content,
- sessionId: '1',
- });
-
- // Verify newly created message is in the list
- const createdMessage = result.messages.find((m) => m.id === result.id);
- expect(createdMessage).toBeDefined();
- expect(createdMessage?.content).toBe(content);
- expect(createdMessage?.role).toBe('user');
- });
-
- it('should return all messages for the session', async () => {
- // Create multiple messages
- await messageModel.create({ role: 'user', content: 'message 1', sessionId: '1' });
- await messageModel.create({ role: 'assistant', content: 'message 2', sessionId: '1' });
-
- // Create third message and get complete list
- const result = await messageModel.createNewMessage({
- role: 'user',
- content: 'message 3',
- sessionId: '1',
- });
-
- // Verify all messages are returned
- expect(result.messages.length).toBeGreaterThanOrEqual(3);
- });
-
- it('should apply groupAssistantMessages transformation', async () => {
- // Create an assistant message with tools
- const assistantMsg = await messageModel.create({
- role: 'assistant',
- content: 'Checking weather',
- tools: [
- {
- id: 'tool-1',
- identifier: 'weather',
- apiName: 'getWeather',
- arguments: '{"city":"Beijing"}',
- type: 'default',
- },
- ],
- sessionId: '1',
- });
-
- // Create corresponding tool message
- const toolMsg = await messageModel.create({
- role: 'tool',
- content: 'Beijing: Sunny, 25°C',
- tool_call_id: 'tool-1',
- sessionId: '1',
- plugin: {
- identifier: 'weather',
- apiName: 'getWeather',
- arguments: '{"city":"Beijing"}',
- type: 'default',
- },
- });
-
- // Create new message and get list
- const result = await messageModel.createNewMessage({
- role: 'user',
- content: 'Thanks!',
- sessionId: '1',
- });
-
- // Verify assistant message is grouped
- const groupMessage = result.messages.find((m) => m.id === assistantMsg.id);
- expect(groupMessage?.role).toBe('group');
- expect(groupMessage?.children).toBeDefined();
- expect(groupMessage?.children).toHaveLength(1);
-
- // Verify tool results are merged into children
- const childBlock = groupMessage?.children?.[0];
- expect(childBlock?.tools).toBeDefined();
- expect(childBlock?.tools).toHaveLength(1);
-
- // Verify tool contains execution result
- const tool = childBlock?.tools?.[0];
- expect(tool?.id).toBe('tool-1');
- expect(tool?.identifier).toBe('weather');
- expect(tool?.result).toBeDefined();
- expect(tool?.result?.content).toBe('Beijing: Sunny, 25°C');
- });
-
- it('should filter messages by topicId if provided', async () => {
- const topicId = 'topic-1';
- await serverDB.insert(topics).values({ id: topicId, sessionId: '1', userId });
-
- // Create messages with different topics
- await messageModel.create({ role: 'user', content: 'topic 1 msg', sessionId: '1', topicId });
- await messageModel.create({ role: 'user', content: 'no topic msg', sessionId: '1' });
-
- // Create new message and specify topicId
- const result = await messageModel.createNewMessage({
- role: 'user',
- content: 'new topic msg',
- sessionId: '1',
- topicId,
- });
-
- // Verify only messages from that topic are returned
- expect(result.messages.every((m) => m.topicId === topicId || m.topicId === undefined)).toBe(
- true,
- );
- expect(result.messages.find((m) => m.content === 'no topic msg')).toBeUndefined();
- });
- });
-
describe('updateMessage', () => {
it('should update message content', async () => {
// Create test data
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 7377c3ff8d0..17fb4c906e2 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -7,7 +7,6 @@ import {
ChatTranslate,
ChatVideoItem,
CreateMessageParams,
- CreateMessageResult,
DBMessageItem,
ModelRankItem,
NewMessageQueryParams,
@@ -532,54 +531,6 @@ export class MessageModel {
});
};
- /**
- * Create a new message and return the complete message list
- *
- * This method combines message creation and querying into a single operation,
- * reducing the need for separate refresh calls and improving performance.
- *
- * @param params - Message creation parameters
- * @param options - Query options for post-processing
- * @returns Object containing the created message ID and full message list
- *
- * @example
- * const { id, messages } = await messageModel.createNewMessage({
- * role: 'assistant',
- * content: 'Hello',
- * tools: [...],
- * sessionId: 'session-1',
- * });
- * // messages already contains grouped structure, no need to refresh
- */
- createNewMessage = async (
- params: CreateMessageParams,
- options: {
- postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;
- } = {},
- ): Promise<CreateMessageResult> => {
- // 1. Create the message (reuse existing create method)
- const item = await this.create(params);
-
- // 2. Query all messages for this session/topic
- // query() method internally applies groupAssistantMessages transformation
- const messages = await this.query(
- {
- current: 0,
- groupId: params.groupId,
- pageSize: 9999,
- sessionId: params.sessionId,
- topicId: params.topicId, // Get all messages
- },
- { ...options, groupAssistantMessages: true },
- );
-
- // 3. Return the result
- return {
- id: item.id,
- messages,
- };
- };
-
batchCreate = async (newMessages: DBMessageItem[]) => {
const messagesToInsert = newMessages.map((m) => {
// TODO: need a better way to handle this
diff --git a/src/server/routers/lambda/__tests__/integration/message.integration.test.ts b/src/server/routers/lambda/__tests__/integration/message.integration.test.ts
index 0cd99b20ba6..006f17fe26c 100644
--- a/src/server/routers/lambda/__tests__/integration/message.integration.test.ts
+++ b/src/server/routers/lambda/__tests__/integration/message.integration.test.ts
@@ -101,7 +101,7 @@ describe('Message Router Integration Tests', () => {
// 先创建 thread
const { threads } = await import('@/database/schemas');
- const [thread] = await serverDB
+ const [thread] = (await serverDB
.insert(threads)
.values({
userId,
@@ -109,7 +109,7 @@ describe('Message Router Integration Tests', () => {
sourceMessageId: 'msg-source',
type: 'continuation', // type is required
})
- .returning();
+ .returning()) as any;
const result = await caller.createNewMessage({
content: 'Test message in thread',
@@ -316,6 +316,74 @@ describe('Message Router Integration Tests', () => {
expect(page1Ids).not.toEqual(page2Ids);
}
});
+
+ it('should return messages filtered by groupId', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 首先创建一个 chat_group
+ const { chatGroups } = await import('@/database/schemas');
+ const [chatGroup] = await serverDB
+ .insert(chatGroups)
+ .values({
+ userId,
+ title: 'Test Chat Group',
+ })
+ .returning();
+
+ // 创建消息并设置 groupId
+ const msg1 = await caller.createNewMessage({
+ content: 'Message 1 in group',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ await serverDB
+ .update(messages)
+ .set({ groupId: chatGroup.id })
+ .where(eq(messages.id, msg1.id));
+
+ // 创建不在 group 中的消息
+ await caller.createNewMessage({
+ content: 'Message without group',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ // 查询 group 中的消息
+ const result = await caller.getMessages({
+ sessionId: testSessionId,
+ groupId: chatGroup.id,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe(msg1.id);
+ });
+
+ it('should support useGroup parameter', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 创建多个消息
+ await caller.createNewMessage({
+ content: 'Message 1',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ await caller.createNewMessage({
+ content: 'Message 2',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // useGroup 参数应该影响消息分组展示
+ const result = await caller.getMessages({
+ sessionId: testSessionId,
+ useGroup: true,
+ });
+
+ expect(result).toBeDefined();
+ expect(Array.isArray(result)).toBe(true);
+ });
});
describe('removeMessages', () => {
@@ -346,6 +414,160 @@ describe('Message Router Integration Tests', () => {
expect(remainingMessages).toHaveLength(0);
});
+
+ it('should return message list when sessionId is provided', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 创建消息
+ const msg1Result = await caller.createNewMessage({
+ content: 'Message 1',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const msg2Result = await caller.createNewMessage({
+ content: 'Message 2',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const msg3Result = await caller.createNewMessage({
+ content: 'Message 3',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ // 删除消息并返回列表
+ const result = await caller.removeMessages({
+ ids: [msg1Result.id],
+ sessionId: testSessionId,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.messages).toBeDefined();
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages?.map((m) => m.id)).toContain(msg2Result.id);
+ expect(result.messages?.map((m) => m.id)).toContain(msg3Result.id);
+ });
+ });
+
+ describe('removeMessage', () => {
+ it('should remove a single message', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msgResult = await caller.createNewMessage({
+ content: 'Message to remove',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ await caller.removeMessage({ id: msgResult.id });
+
+ // 验证消息已删除
+ const deletedMessage = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, msgResult.id));
+
+ expect(deletedMessage).toHaveLength(0);
+ });
+
+ it('should return message list when sessionId is provided', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg1Result = await caller.createNewMessage({
+ content: 'Message 1',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const msg2Result = await caller.createNewMessage({
+ content: 'Message 2',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const result = await caller.removeMessage({
+ id: msg1Result.id,
+ sessionId: testSessionId,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.messages).toBeDefined();
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages?.[0].id).toBe(msg2Result.id);
+ });
+ });
+
+ describe('removeAllMessages', () => {
+ it('should remove all messages for the user', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 创建多个 session 和消息
+ await caller.createNewMessage({
+ content: 'Message 1',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const [anotherSession] = await serverDB
+ .insert(sessions)
+ .values({
+ userId,
+ type: 'agent',
+ })
+ .returning();
+
+ await caller.createNewMessage({
+ content: 'Message 2',
+ role: 'user',
+ sessionId: anotherSession.id,
+ });
+
+ // 删除所有消息
+ await caller.removeAllMessages();
+
+ // 验证所有消息已删除
+ const remainingMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.userId, userId));
+
+ expect(remainingMessages).toHaveLength(0);
+ });
+ });
+
+ describe('removeMessageQuery', () => {
+ it('should remove message query', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msgResult = await caller.createNewMessage({
+ content: 'Message with query',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ // 创建一个 message query 记录,使用 UUID
+ const { messageQueries } = await import('@/database/schemas');
+ const [queryRecord] = await serverDB
+ .insert(messageQueries)
+ .values({
+ messageId: msgResult.id,
+ userId,
+ userQuery: 'test query',
+ })
+ .returning();
+
+ await caller.removeMessageQuery({ id: queryRecord.id });
+
+ // 验证消息查询已删除
+ const deletedQuery = await serverDB
+ .select()
+ .from(messageQueries)
+ .where(eq(messageQueries.id, queryRecord.id));
+
+ expect(deletedQuery).toHaveLength(0);
+ });
});
describe('removeMessagesByAssistant', () => {
@@ -414,6 +636,43 @@ describe('Message Router Integration Tests', () => {
});
});
+ describe('removeMessagesByGroup', () => {
+ it('should call removeMessagesByGroup endpoint', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 首先创建一个 chat_group
+ const { chatGroups } = await import('@/database/schemas');
+ const [chatGroup] = await serverDB
+ .insert(chatGroups)
+ .values({
+ userId,
+ title: 'Test Chat Group for Delete',
+ })
+ .returning();
+
+ // 创建消息并设置 groupId
+ const msg1 = await caller.createNewMessage({
+ content: 'Message 1 in group',
+ role: 'assistant',
+ sessionId: testSessionId,
+ topicId: testTopicId,
+ });
+
+ await serverDB
+ .update(messages)
+ .set({ groupId: chatGroup.id })
+ .where(eq(messages.id, msg1.id));
+
+ // 调用删除接口(不会抛出错误即为成功)
+ await expect(
+ caller.removeMessagesByGroup({
+ groupId: chatGroup.id,
+ topicId: testTopicId,
+ }),
+ ).resolves.not.toThrow();
+ });
+ });
+
describe('update', () => {
it('should update message content', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
@@ -438,6 +697,36 @@ describe('Message Router Integration Tests', () => {
expect(updatedMessage.content).toBe('Updated content');
});
+
+ it('should update message and return message list when sessionId is provided', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg1 = await caller.createNewMessage({
+ content: 'Message 1',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const msg2 = await caller.createNewMessage({
+ content: 'Message 2',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const result = await caller.update({
+ id: msg1.id,
+ sessionId: testSessionId,
+ value: {
+ content: 'Updated Message 1',
+ },
+ });
+
+ expect(result).toBeDefined();
+ // The update method returns the updated message list
+ const messages = await caller.getMessages({ sessionId: testSessionId });
+ expect(messages).toHaveLength(2);
+ expect(messages.find((m) => m.id === msg1.id)?.content).toBe('Updated Message 1');
+ });
});
describe('searchMessages', () => {
@@ -465,6 +754,458 @@ describe('Message Router Integration Tests', () => {
});
});
+ describe('updateMessagePlugin', () => {
+ it('should update message plugin state', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createNewMessage({
+ content: 'Message with plugin',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 先创建一个 plugin 记录
+ const { messagePlugins } = await import('@/database/schemas');
+ await serverDB.insert(messagePlugins).values({
+ id: msg.id,
+ userId,
+ toolCallId: 'test-tool-call',
+ type: 'default',
+ });
+
+ await caller.updateMessagePlugin({
+ id: msg.id,
+ value: {
+ state: { key: 'value' },
+ },
+ });
+
+ const [updatedPlugin] = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, msg.id));
+
+ expect(updatedPlugin).toBeDefined();
+ expect(updatedPlugin.state).toBeDefined();
+ });
+ });
+
+ describe('updateMessageRAG', () => {
+ it('should update message RAG information', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createNewMessage({
+ content: 'Message with RAG',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 创建必要的依赖: chunks -> messageQueries -> messageQueryChunks
+ const { chunks, messageQueries, messageQueryChunks } = await import('@/database/schemas');
+
+ // 1. 创建 chunk
+ const [chunk] = await serverDB
+ .insert(chunks)
+ .values({
+ userId,
+ text: 'test chunk content',
+ })
+ .returning();
+
+ // 2. 创建 message query
+ const [query] = await serverDB
+ .insert(messageQueries)
+ .values({
+ messageId: msg.id,
+ userId,
+ userQuery: 'test query',
+ })
+ .returning();
+
+ // 3. 调用 updateMessageRAG
+ await caller.updateMessageRAG({
+ id: msg.id,
+ value: {
+ fileChunks: [{ id: chunk.id, similarity: 0.95 }],
+ ragQueryId: query.id,
+ },
+ });
+
+ // 验证 messageQueryChunks 记录已创建
+ const [queryChunk] = await serverDB
+ .select()
+ .from(messageQueryChunks)
+ .where(eq(messageQueryChunks.messageId, msg.id));
+
+ expect(queryChunk).toBeDefined();
+ expect(queryChunk.chunkId).toBe(chunk.id);
+ });
+
+ it('should return message list when sessionId is provided', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg1 = await caller.createNewMessage({
+ content: 'Message 1',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ await caller.createNewMessage({
+ content: 'Message 2',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 创建必要的依赖: chunks -> messageQueries
+ const { chunks, messageQueries } = await import('@/database/schemas');
+ const [chunk] = await serverDB
+ .insert(chunks)
+ .values({
+ userId,
+ text: 'test chunk content',
+ })
+ .returning();
+
+ // 创建 query (需要 queryId)
+ const [query] = await serverDB
+ .insert(messageQueries)
+ .values({
+ messageId: msg1.id,
+ userId,
+ userQuery: 'test query',
+ })
+ .returning();
+
+ const result = await caller.updateMessageRAG({
+ id: msg1.id,
+ sessionId: testSessionId,
+ value: {
+ fileChunks: [{ id: chunk.id, similarity: 0.95 }],
+ ragQueryId: query.id,
+ },
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.messages).toBeDefined();
+ expect(result.messages).toHaveLength(2);
+ });
+ });
+
+ describe('updateMetadata', () => {
+ it('should update message metadata', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createNewMessage({
+ content: 'Message with metadata',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ await caller.updateMetadata({
+ id: msg.id,
+ value: { customKey: 'customValue' },
+ });
+
+ const [updatedMessage] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, msg.id));
+
+ expect(updatedMessage).toBeDefined();
+ // Verify the message still exists after update
+ expect(updatedMessage.id).toBe(msg.id);
+ });
+ });
+
+ describe('updatePluginError', () => {
+ it('should update plugin error state', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createNewMessage({
+ content: 'Message with plugin error',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 先创建一个 plugin 记录
+ const { messagePlugins } = await import('@/database/schemas');
+ await serverDB.insert(messagePlugins).values({
+ id: msg.id,
+ userId,
+ toolCallId: 'test-tool-call-error',
+ type: 'default',
+ });
+
+ await caller.updatePluginError({
+ id: msg.id,
+ value: { message: 'Plugin error occurred' },
+ });
+
+ const [updatedPlugin] = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, msg.id));
+
+ expect(updatedPlugin).toBeDefined();
+ expect(updatedPlugin.error).toBeDefined();
+ });
+
+ it('should return message list when sessionId is provided', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg1 = await caller.createNewMessage({
+ content: 'Message 1',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 先创建一个 plugin 记录
+ const { messagePlugins } = await import('@/database/schemas');
+ await serverDB.insert(messagePlugins).values({
+ id: msg1.id,
+ userId,
+ toolCallId: 'test-tool-call-error-2',
+ type: 'default',
+ });
+
+ await caller.createNewMessage({
+ content: 'Message 2',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ const result = await caller.updatePluginError({
+ id: msg1.id,
+ sessionId: testSessionId,
+ value: { message: 'Error' },
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.messages).toBeDefined();
+ expect(result.messages).toHaveLength(2);
+ });
+ });
+
+ describe('updatePluginState', () => {
+ it('should update plugin state', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createNewMessage({
+ content: 'Message with plugin state',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 先创建一个 plugin 记录
+ const { messagePlugins } = await import('@/database/schemas');
+ await serverDB.insert(messagePlugins).values({
+ id: msg.id,
+ userId,
+ toolCallId: 'test-tool-call-state',
+ type: 'default',
+ });
+
+ const result = await caller.updatePluginState({
+ id: msg.id,
+ sessionId: testSessionId,
+ value: { stateKey: 'stateValue' },
+ });
+
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('updateTTS', () => {
+ it('should update TTS information', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createNewMessage({
+ content: 'Message with TTS',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 创建 file 记录
+ const { files } = await import('@/database/schemas');
+ const [file] = await serverDB
+ .insert(files)
+ .values({
+ userId,
+ name: 'audio.mp3',
+ fileType: 'audio/mpeg',
+ size: 1024,
+ url: '/files/audio.mp3',
+ })
+ .returning();
+
+ await caller.updateTTS({
+ id: msg.id,
+ value: {
+ file: file.id,
+ voice: 'en-US-neural',
+ contentMd5: 'abc123',
+ },
+ });
+
+ const { messageTTS } = await import('@/database/schemas');
+ const [ttsRecord] = await serverDB.select().from(messageTTS).where(eq(messageTTS.id, msg.id));
+
+ expect(ttsRecord).toBeDefined();
+ expect(ttsRecord.voice).toBe('en-US-neural');
+ expect(ttsRecord.fileId).toBe(file.id);
+ });
+
+ it('should delete TTS when value is false', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createNewMessage({
+ content: 'Message with TTS to delete',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 创建 file 记录
+ const { files } = await import('@/database/schemas');
+ const [file] = await serverDB
+ .insert(files)
+ .values({
+ userId,
+ name: 'audio-delete.mp3',
+ fileType: 'audio/mpeg',
+ size: 1024,
+ url: '/files/audio-delete.mp3',
+ })
+ .returning();
+
+ // First add TTS
+ await caller.updateTTS({
+ id: msg.id,
+ value: {
+ file: file.id,
+ voice: 'en-US-neural',
+ },
+ });
+
+ // Then delete it
+ await caller.updateTTS({
+ id: msg.id,
+ value: false,
+ });
+
+ const { messageTTS } = await import('@/database/schemas');
+ const [ttsRecord] = await serverDB.select().from(messageTTS).where(eq(messageTTS.id, msg.id));
+
+ expect(ttsRecord).toBeUndefined();
+ });
+ });
+
+ describe('updateTranslate', () => {
+ it('should update translation information', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createNewMessage({
+ content: 'Hello world',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ await caller.updateTranslate({
+ id: msg.id,
+ value: {
+ content: '你好世界',
+ from: 'en',
+ to: 'zh',
+ },
+ });
+
+ const { messageTranslates } = await import('@/database/schemas');
+ const [translateRecord] = await serverDB
+ .select()
+ .from(messageTranslates)
+ .where(eq(messageTranslates.id, msg.id));
+
+ expect(translateRecord).toBeDefined();
+ expect(translateRecord.to).toBe('zh');
+ });
+
+ it('should delete translation when value is false', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createNewMessage({
+ content: 'Hello world',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ // First add translation
+ await caller.updateTranslate({
+ id: msg.id,
+ value: {
+ content: '你好世界',
+ to: 'zh',
+ },
+ });
+
+ // Then delete it
+ await caller.updateTranslate({
+ id: msg.id,
+ value: false,
+ });
+
+ const [updatedMessage] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, msg.id));
+
+ expect(updatedMessage).toBeDefined();
+ });
+ });
+
+ describe('getHeatmaps', () => {
+ it('should get message heatmaps', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 创建一些消息
+ await caller.createNewMessage({
+ content: 'Message 1',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ await caller.createNewMessage({
+ content: 'Message 2',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ const heatmaps = await caller.getHeatmaps();
+
+ expect(heatmaps).toBeDefined();
+ expect(Array.isArray(heatmaps)).toBe(true);
+ });
+ });
+
+ describe('rankModels', () => {
+ it('should get model usage ranking', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 创建带有模型信息的消息
+ const msg = await caller.createNewMessage({
+ content: 'Message from AI',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 添加模型信息
+ await serverDB.update(messages).set({ model: 'gpt-4' }).where(eq(messages.id, msg.id));
+
+ const ranking = await caller.rankModels();
+
+ expect(ranking).toBeDefined();
+ expect(Array.isArray(ranking)).toBe(true);
+ });
+ });
+
describe('count and statistics', () => {
it('should count messages', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
@@ -487,6 +1228,26 @@ describe('Message Router Integration Tests', () => {
expect(count).toBe(2);
});
+ it('should count messages with date range', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ await caller.createNewMessage({
+ content: 'Message 1',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const startDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
+ const endDate = new Date().toISOString();
+
+ const count = await caller.count({
+ startDate,
+ endDate,
+ });
+
+ expect(count).toBeGreaterThanOrEqual(1);
+ });
+
it('should count words', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
@@ -500,5 +1261,25 @@ describe('Message Router Integration Tests', () => {
expect(wordCount).toBeGreaterThan(0);
});
+
+ it('should count words with date range', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ await caller.createNewMessage({
+ content: 'Hello world test message',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const startDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
+ const endDate = new Date().toISOString();
+
+ const wordCount = await caller.countWords({
+ startDate,
+ endDate,
+ });
+
+ expect(wordCount).toBeGreaterThan(0);
+ });
});
});
diff --git a/src/server/routers/lambda/message.ts b/src/server/routers/lambda/message.ts
index c0d5f723252..0095f06fadd 100644
--- a/src/server/routers/lambda/message.ts
+++ b/src/server/routers/lambda/message.ts
@@ -11,6 +11,7 @@ import { getServerDB } from '@/database/server';
import { authedProcedure, 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';
const messageProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -19,6 +20,7 @@ const messageProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>
ctx: {
fileService: new FileService(ctx.serverDB, ctx.userId),
messageModel: new MessageModel(ctx.serverDB, ctx.userId),
+ messageService: new MessageService(ctx.serverDB, ctx.userId),
},
});
});
@@ -53,11 +55,10 @@ export const messageRouter = router({
}),
createNewMessage: messageProcedure
- .input(CreateNewMessageParamsSchema)
+ .input(CreateNewMessageParamsSchema.extend({ useGroup: z.boolean().optional() }))
.mutation(async ({ input, ctx }) => {
- return ctx.messageModel.createNewMessage(input as any, {
- postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
- });
+ const { useGroup, ...params } = input;
+ return ctx.messageService.createNewMessage(params as any, { useGroup });
}),
getHeatmaps: messageProcedure.query(async ({ ctx }) => {
@@ -109,23 +110,8 @@ export const messageRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- await ctx.messageModel.deleteMessage(input.id);
-
- // If sessionId or topicId is provided, return the full message list
- if (input.sessionId !== undefined || input.topicId !== undefined) {
- const messageList = await ctx.messageModel.query(
- {
- sessionId: input.sessionId,
- topicId: input.topicId,
- },
- {
- groupAssistantMessages: input.useGroup ?? false,
- postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
- },
- );
- return { messages: messageList, success: true };
- }
- return { success: true };
+ const { id, ...options } = input;
+ return ctx.messageService.removeMessage(id, options);
}),
removeMessageQuery: messageProcedure
@@ -144,23 +130,8 @@ export const messageRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- await ctx.messageModel.deleteMessages(input.ids);
-
- // If sessionId or topicId is provided, return the full message list
- if (input.sessionId !== undefined || input.topicId !== undefined) {
- const messageList = await ctx.messageModel.query(
- {
- sessionId: input.sessionId,
- topicId: input.topicId,
- },
- {
- groupAssistantMessages: input.useGroup ?? false,
- postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
- },
- );
- return { messages: messageList, success: true };
- }
- return { success: true };
+ const { ids, ...options } = input;
+ return ctx.messageService.removeMessages(ids, options);
}),
removeMessagesByAssistant: messageProcedure
@@ -207,12 +178,8 @@ export const messageRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- return ctx.messageModel.update(input.id, input.value as any, {
- groupAssistantMessages: input.useGroup ?? false,
- postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
- sessionId: input.sessionId,
- topicId: input.topicId,
- });
+ const { id, value, ...options } = input;
+ return ctx.messageService.updateMessage(id, value as any, options);
}),
updateMessagePlugin: messageProcedure
@@ -235,23 +202,8 @@ export const messageRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- await ctx.messageModel.updateMessageRAG(input.id, input.value);
-
- // If sessionId or topicId is provided, return the full message list
- if (input.sessionId !== undefined || input.topicId !== undefined) {
- const messageList = await ctx.messageModel.query(
- {
- sessionId: input.sessionId,
- topicId: input.topicId,
- },
- {
- groupAssistantMessages: input.useGroup ?? false,
- postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
- },
- );
- return { messages: messageList, success: true };
- }
- return { success: true };
+ const { id, value, ...options } = input;
+ return ctx.messageService.updateMessageRAG(id, value, options);
}),
updateMetadata: messageProcedure
@@ -276,23 +228,8 @@ export const messageRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- // If sessionId or topicId is provided, we need to return the full message list
- if (input.sessionId !== undefined || input.topicId !== undefined) {
- await ctx.messageModel.updateMessagePlugin(input.id, { error: input.value });
- const messageList = await ctx.messageModel.query(
- {
- sessionId: input.sessionId,
- topicId: input.topicId,
- },
- {
- groupAssistantMessages: input.useGroup ?? false,
- postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
- },
- );
- return { messages: messageList, success: true };
- }
- await ctx.messageModel.updateMessagePlugin(input.id, { error: input.value });
- return { success: true };
+ const { id, value, ...options } = input;
+ return ctx.messageService.updatePluginError(id, value, options);
}),
updatePluginState: messageProcedure
@@ -306,12 +243,8 @@ export const messageRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- return ctx.messageModel.updatePluginState(input.id, input.value, {
- groupAssistantMessages: input.useGroup ?? false,
- postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
- sessionId: input.sessionId,
- topicId: input.topicId,
- });
+ const { id, value, ...options } = input;
+ return ctx.messageService.updatePluginState(id, value, options);
}),
updateTTS: messageProcedure
diff --git a/src/server/services/message/__tests__/index.test.ts b/src/server/services/message/__tests__/index.test.ts
new file mode 100644
index 00000000000..a698b5b4b6e
--- /dev/null
+++ b/src/server/services/message/__tests__/index.test.ts
@@ -0,0 +1,348 @@
+import { LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MessageModel } from '@/database/models/message';
+import { FileService } from '@/server/services/file';
+
+import { MessageService } from '../index';
+
+vi.mock('@/database/models/message');
+vi.mock('@/server/services/file');
+
+describe('MessageService', () => {
+ let messageService: MessageService;
+ let mockDB: LobeChatDatabase;
+ let mockMessageModel: MessageModel;
+ let mockFileService: FileService;
+ const userId = 'test-user-id';
+
+ beforeEach(() => {
+ mockDB = {} as LobeChatDatabase;
+ mockMessageModel = {
+ create: vi.fn(),
+ deleteMessage: vi.fn(),
+ deleteMessages: vi.fn(),
+ query: vi.fn(),
+ update: vi.fn(),
+ updateMessagePlugin: vi.fn(),
+ updateMessageRAG: vi.fn(),
+ updatePluginState: vi.fn(),
+ } as any;
+
+ mockFileService = {
+ getFullFileUrl: vi.fn().mockImplementation((path) => Promise.resolve(`/files${path}`)),
+ } as any;
+
+ // Mock constructors
+ vi.mocked(MessageModel).mockImplementation(() => mockMessageModel);
+ vi.mocked(FileService).mockImplementation(() => mockFileService);
+
+ messageService = new MessageService(mockDB, userId);
+ });
+
+ describe('removeMessage', () => {
+ it('should delete message and return { success: true } when no sessionId/topicId provided', async () => {
+ const messageId = 'msg-1';
+
+ const result = await messageService.removeMessage(messageId);
+
+ expect(mockMessageModel.deleteMessage).toHaveBeenCalledWith(messageId);
+ expect(result).toEqual({ success: true });
+ expect(mockMessageModel.query).not.toHaveBeenCalled();
+ });
+
+ it('should delete message and return message list when sessionId provided', async () => {
+ const messageId = 'msg-1';
+ const mockMessages = [{ id: 'msg-2', content: 'test' }];
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.removeMessage(messageId, { sessionId: 'session-1' });
+
+ expect(mockMessageModel.deleteMessage).toHaveBeenCalledWith(messageId);
+ expect(mockMessageModel.query).toHaveBeenCalledWith(
+ { groupId: undefined, sessionId: 'session-1', topicId: undefined },
+ expect.objectContaining({
+ groupAssistantMessages: false,
+ }),
+ );
+ expect(result).toEqual({ messages: mockMessages, success: true });
+ });
+
+ it('should delete message and return message list when topicId provided', async () => {
+ const messageId = 'msg-1';
+ const mockMessages = [{ id: 'msg-2', content: 'test' }];
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.removeMessage(messageId, { topicId: 'topic-1' });
+
+ expect(mockMessageModel.deleteMessage).toHaveBeenCalledWith(messageId);
+ expect(mockMessageModel.query).toHaveBeenCalledWith(
+ { groupId: undefined, sessionId: undefined, topicId: 'topic-1' },
+ expect.objectContaining({
+ groupAssistantMessages: false,
+ }),
+ );
+ expect(result).toEqual({ messages: mockMessages, success: true });
+ });
+ });
+
+ describe('removeMessages', () => {
+ it('should delete messages and return { success: true } when no sessionId/topicId provided', async () => {
+ const messageIds = ['msg-1', 'msg-2'];
+
+ const result = await messageService.removeMessages(messageIds);
+
+ expect(mockMessageModel.deleteMessages).toHaveBeenCalledWith(messageIds);
+ expect(result).toEqual({ success: true });
+ expect(mockMessageModel.query).not.toHaveBeenCalled();
+ });
+
+ it('should delete messages and return message list when sessionId provided', async () => {
+ const messageIds = ['msg-1', 'msg-2'];
+ const mockMessages = [{ id: 'msg-3', content: 'test' }];
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.removeMessages(messageIds, { sessionId: 'session-1' });
+
+ expect(mockMessageModel.deleteMessages).toHaveBeenCalledWith(messageIds);
+ expect(mockMessageModel.query).toHaveBeenCalled();
+ expect(result).toEqual({ messages: mockMessages, success: true });
+ });
+ });
+
+ describe('updateMessageRAG', () => {
+ it('should update RAG and return { success: true } when no sessionId/topicId provided', async () => {
+ const messageId = 'msg-1';
+ const ragValue = { fileChunks: [{ id: 'chunk-1', similarity: 0.95 }] };
+
+ const result = await messageService.updateMessageRAG(messageId, ragValue);
+
+ expect(mockMessageModel.updateMessageRAG).toHaveBeenCalledWith(messageId, ragValue);
+ expect(result).toEqual({ success: true });
+ expect(mockMessageModel.query).not.toHaveBeenCalled();
+ });
+
+ it('should update RAG and return message list when sessionId provided', async () => {
+ const messageId = 'msg-1';
+ const ragValue = { fileChunks: [{ id: 'chunk-1', similarity: 0.95 }] };
+ const mockMessages = [{ id: 'msg-1', content: 'test' }];
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.updateMessageRAG(messageId, ragValue, {
+ sessionId: 'session-1',
+ });
+
+ expect(mockMessageModel.updateMessageRAG).toHaveBeenCalledWith(messageId, ragValue);
+ expect(mockMessageModel.query).toHaveBeenCalled();
+ expect(result).toEqual({ messages: mockMessages, success: true });
+ });
+ });
+
+ describe('updatePluginError', () => {
+ it('should update plugin error and return { success: true } when no sessionId/topicId provided', async () => {
+ const messageId = 'msg-1';
+ const error = { type: 'TestError', message: 'Test error message' };
+
+ const result = await messageService.updatePluginError(messageId, error);
+
+ expect(mockMessageModel.updateMessagePlugin).toHaveBeenCalledWith(messageId, { error });
+ expect(result).toEqual({ success: true });
+ expect(mockMessageModel.query).not.toHaveBeenCalled();
+ });
+
+ it('should update plugin error and return message list when sessionId provided', async () => {
+ const messageId = 'msg-1';
+ const error = { type: 'TestError', message: 'Test error message' };
+ const mockMessages = [{ id: 'msg-1', content: 'test' }];
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.updatePluginError(messageId, error, {
+ sessionId: 'session-1',
+ });
+
+ expect(mockMessageModel.updateMessagePlugin).toHaveBeenCalledWith(messageId, { error });
+ expect(mockMessageModel.query).toHaveBeenCalled();
+ expect(result).toEqual({ messages: mockMessages, success: true });
+ });
+ });
+
+ describe('updatePluginState', () => {
+ it('should update plugin state and return { success: true } when no sessionId/topicId provided', async () => {
+ const messageId = 'msg-1';
+ const state = { key: 'value' };
+
+ const result = await messageService.updatePluginState(messageId, state, {});
+
+ expect(mockMessageModel.updatePluginState).toHaveBeenCalledWith(messageId, state);
+ expect(result).toEqual({ success: true });
+ expect(mockMessageModel.query).not.toHaveBeenCalled();
+ });
+
+ it('should update plugin state and return message list when sessionId provided', async () => {
+ const messageId = 'msg-1';
+ const state = { key: 'value' };
+ const mockMessages = [{ id: 'msg-1', content: 'test' }];
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.updatePluginState(messageId, state, {
+ sessionId: 'session-1',
+ });
+
+ expect(mockMessageModel.updatePluginState).toHaveBeenCalledWith(messageId, state);
+ expect(mockMessageModel.query).toHaveBeenCalled();
+ expect(result).toEqual({ messages: mockMessages, success: true });
+ });
+ });
+
+ describe('updateMessage', () => {
+ it('should update message and return { success: true } when no sessionId/topicId provided', async () => {
+ const messageId = 'msg-1';
+ const value = { content: 'updated content' };
+
+ const result = await messageService.updateMessage(messageId, value as any, {});
+
+ expect(mockMessageModel.update).toHaveBeenCalledWith(messageId, value);
+ expect(result).toEqual({ success: true });
+ expect(mockMessageModel.query).not.toHaveBeenCalled();
+ });
+
+ it('should update message and return message list when sessionId provided', async () => {
+ const messageId = 'msg-1';
+ const value = { content: 'updated content' };
+ const mockMessages = [{ id: 'msg-1', content: 'updated content' }];
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.updateMessage(messageId, value as any, {
+ sessionId: 'session-1',
+ });
+
+ expect(mockMessageModel.update).toHaveBeenCalledWith(messageId, value);
+ expect(mockMessageModel.query).toHaveBeenCalled();
+ expect(result).toEqual({ messages: mockMessages, success: true });
+ });
+ });
+
+ describe('useGroup option', () => {
+ it('should pass useGroup option to query', async () => {
+ const mockMessages = [{ id: 'msg-1', content: 'test' }];
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ await messageService.removeMessage('msg-1', {
+ sessionId: 'session-1',
+ useGroup: true,
+ });
+
+ expect(mockMessageModel.query).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ groupAssistantMessages: true,
+ }),
+ );
+ });
+
+ it('should default useGroup to false', async () => {
+ const mockMessages = [{ id: 'msg-1', content: 'test' }];
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ await messageService.removeMessage('msg-1', { sessionId: 'session-1' });
+
+ expect(mockMessageModel.query).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ groupAssistantMessages: false,
+ }),
+ );
+ });
+ });
+
+ describe('createNewMessage', () => {
+ it('should create message and return message list', async () => {
+ const params = {
+ content: 'Hello',
+ role: 'user' as const,
+ sessionId: 'session-1',
+ };
+ const createdMessage = { id: 'msg-1', ...params };
+ const mockMessages = [createdMessage, { id: 'msg-2', content: 'Hi' }];
+
+ vi.mocked(mockMessageModel.create).mockResolvedValue(createdMessage as any);
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.createNewMessage(params as any);
+
+ expect(mockMessageModel.create).toHaveBeenCalledWith(params);
+ expect(mockMessageModel.query).toHaveBeenCalledWith(
+ {
+ current: 0,
+ groupId: undefined,
+ pageSize: 9999,
+ sessionId: 'session-1',
+ topicId: undefined,
+ },
+ expect.objectContaining({
+ groupAssistantMessages: false,
+ }),
+ );
+ expect(result).toEqual({
+ id: 'msg-1',
+ messages: mockMessages,
+ });
+ });
+
+ it('should create message with useGroup option', async () => {
+ const params = {
+ content: 'Hello',
+ role: 'assistant' as const,
+ sessionId: 'session-1',
+ };
+ const createdMessage = { id: 'msg-1', ...params };
+ const mockMessages = [createdMessage];
+
+ vi.mocked(mockMessageModel.create).mockResolvedValue(createdMessage as any);
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.createNewMessage(params as any, { useGroup: true });
+
+ expect(mockMessageModel.query).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ groupAssistantMessages: true,
+ }),
+ );
+ expect(result).toEqual({
+ id: 'msg-1',
+ messages: mockMessages,
+ });
+ });
+
+ it('should create message with topicId and groupId', async () => {
+ const params = {
+ content: 'Hello',
+ groupId: 'group-1',
+ role: 'user' as const,
+ sessionId: 'session-1',
+ topicId: 'topic-1',
+ };
+ const createdMessage = { id: 'msg-1', ...params };
+ const mockMessages = [createdMessage];
+
+ vi.mocked(mockMessageModel.create).mockResolvedValue(createdMessage as any);
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.createNewMessage(params as any);
+
+ expect(mockMessageModel.query).toHaveBeenCalledWith(
+ {
+ current: 0,
+ groupId: 'group-1',
+ pageSize: 9999,
+ sessionId: 'session-1',
+ topicId: 'topic-1',
+ },
+ expect.anything(),
+ );
+ expect(result.id).toBe('msg-1');
+ expect(result.messages).toEqual(mockMessages);
+ });
+ });
+});
diff --git a/src/server/services/message/index.ts b/src/server/services/message/index.ts
new file mode 100644
index 00000000000..7818618bcb6
--- /dev/null
+++ b/src/server/services/message/index.ts
@@ -0,0 +1,159 @@
+import { LobeChatDatabase } from '@lobechat/database';
+import { CreateMessageParams, UpdateMessageParams } from '@lobechat/types';
+
+import { MessageModel } from '@/database/models/message';
+
+import { FileService } from '../file';
+
+interface QueryOptions {
+ groupId?: string | null;
+ sessionId?: string | null;
+ topicId?: string | null;
+ useGroup?: boolean;
+}
+
+interface CreateMessageResult {
+ id: string;
+ messages: any[];
+}
+
+/**
+ * Message Service
+ *
+ * Encapsulates repeated "mutation + conditional query" logic.
+ * After performing update/delete operations, conditionally returns message list based on sessionId/topicId.
+ */
+export class MessageService {
+ private messageModel: MessageModel;
+ private fileService: FileService;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.messageModel = new MessageModel(db, userId);
+ this.fileService = new FileService(db, userId);
+ }
+
+ /**
+ * Unified URL processing function
+ */
+ private get postProcessUrl() {
+ return (path: string | null) => this.fileService.getFullFileUrl(path);
+ }
+
+ /**
+ * Unified query options
+ */
+ private getQueryOptions(options: QueryOptions) {
+ return {
+ groupAssistantMessages: options.useGroup ?? false,
+ postProcessUrl: this.postProcessUrl,
+ };
+ }
+
+ /**
+ * Query messages and return response with success status (used after mutations)
+ */
+ private async queryWithSuccess(options?: QueryOptions) {
+ if (!options || (options.sessionId === undefined && options.topicId === undefined)) {
+ return { success: true };
+ }
+
+ const { sessionId, topicId, groupId } = options;
+
+ const messages = await this.messageModel.query(
+ { groupId, sessionId, topicId },
+ this.getQueryOptions(options),
+ );
+
+ return { messages, success: true };
+ }
+
+ /**
+ * Remove messages with optional message list return
+ * Pattern: delete + conditional query
+ */
+ async removeMessages(ids: string[], options?: QueryOptions) {
+ await this.messageModel.deleteMessages(ids);
+ return this.queryWithSuccess(options);
+ }
+
+ /**
+ * Remove single message with optional message list return
+ * Pattern: delete + conditional query
+ */
+ async removeMessage(id: string, options?: QueryOptions) {
+ await this.messageModel.deleteMessage(id);
+ return this.queryWithSuccess(options);
+ }
+
+ /**
+ * Update message RAG with optional message list return
+ * Pattern: update + conditional query
+ */
+ async updateMessageRAG(id: string, value: any, options?: QueryOptions) {
+ await this.messageModel.updateMessageRAG(id, value);
+ return this.queryWithSuccess(options);
+ }
+
+ /**
+ * Update plugin error with optional message list return
+ * Pattern: update + conditional query
+ */
+ async updatePluginError(id: string, value: any, options?: QueryOptions) {
+ await this.messageModel.updateMessagePlugin(id, { error: value });
+ return this.queryWithSuccess(options);
+ }
+
+ /**
+ * Update plugin state and return message list
+ * Pattern: update + conditional query
+ */
+ async updatePluginState(id: string, value: any, options: QueryOptions): Promise<any> {
+ await this.messageModel.updatePluginState(id, value);
+ return this.queryWithSuccess(options);
+ }
+
+ /**
+ * Update message and return message list
+ * Pattern: update + conditional query
+ */
+ async updateMessage(id: string, value: UpdateMessageParams, options: QueryOptions): Promise<any> {
+ await this.messageModel.update(id, value as any);
+ return this.queryWithSuccess(options);
+ }
+
+ /**
+ * Create a new message and return the complete message list
+ * Pattern: create + query
+ *
+ * This method combines message creation and querying into a single operation,
+ * reducing the need for separate refresh calls and improving performance.
+ */
+ async createNewMessage(
+ params: CreateMessageParams,
+ options?: QueryOptions,
+ ): Promise<CreateMessageResult> {
+ // 1. Create the message
+ const item = await this.messageModel.create(params);
+
+ // 2. Query all messages for this session/topic
+ const messages = await this.messageModel.query(
+ {
+ current: 0,
+ groupId: params.groupId,
+ pageSize: 9999,
+ sessionId: params.sessionId,
+ topicId: params.topicId,
+ },
+ {
+ groupAssistantMessages: options?.useGroup ?? false,
+ postProcessUrl: this.postProcessUrl,
+ },
+ );
+
+ // 3. Return the result
+ return {
+ id: item.id,
+ messages,
+ };
+ }
+}
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 0d00012d0f5..8c12f438c01 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -31,6 +31,7 @@ export class MessageService {
return lambdaClient.message.createNewMessage.mutate({
...params,
sessionId: sessionId ? this.toDbSessionId(sessionId) : undefined,
+ useGroup: this.useGroup,
});
};