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.

🔨 chore: pre-merge message group code (#9896)

Arvin Xu7fa6c749db24
diff --git a/packages/database/src/utils/__tests__/groupMessages.test.ts b/packages/database/src/utils/__tests__/groupMessages.test.ts
new file mode 100644
index 00000000000..80eb60d8c78
--- /dev/null
+++ b/packages/database/src/utils/__tests__/groupMessages.test.ts
@@ -0,0 +1,989 @@
+import { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { groupAssistantMessages } from '../groupMessages';
+
+describe('groupAssistantMessages', () => {
+ describe('Basic Scenarios', () => {
+ it('should group single assistant with single tool result', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Checking weather',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{"city":"Beijing"}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: 'Beijing: Sunny, 25°C',
+ pluginState: { cached: true },
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('group');
+ expect(result[0].content).toBe('');
+ expect(result[0].children).toHaveLength(1);
+
+ const block = result[0].children![0];
+ expect(block.content).toBe('Checking weather');
+ expect(block.tools).toHaveLength(1);
+ expect(block.tools![0]).toMatchObject({
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ result: {
+ content: 'Beijing: Sunny, 25°C',
+ state: { cached: true },
+ },
+ });
+ });
+
+ it('should group assistant message with multiple tool results', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Checking weather and news',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{"city":"Beijing"}',
+ type: 'default',
+ },
+ {
+ id: 'tool-2',
+ identifier: 'news',
+ apiName: 'getNews',
+ arguments: '{"category":"tech"}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: 'Beijing: Sunny, 25°C',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-3',
+ role: 'tool',
+ tool_call_id: 'tool-2',
+ content: 'Latest tech news: AI breakthrough',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('group');
+ expect(result[0].children).toHaveLength(1);
+
+ const block = result[0].children![0];
+ expect(block.tools).toHaveLength(2);
+ expect(block.tools![0].result?.content).toBe('Beijing: Sunny, 25°C');
+ expect(block.tools![1].result?.content).toBe('Latest tech news: AI breakthrough');
+ });
+
+ it('should handle assistant message without tools', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Hello!',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('assistant');
+ expect(result[0].content).toBe('Hello!');
+ expect(result[0].children).toBeUndefined();
+ });
+
+ it('should handle tool result not yet available', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Checking weather',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{"city":"Beijing"}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('group');
+ expect(result[0].children).toHaveLength(1);
+
+ const block = result[0].children![0];
+ expect(block.tools).toHaveLength(1);
+ expect(block.tools![0].result).toBeUndefined();
+ });
+ });
+
+ describe('Multi-turn Conversation', () => {
+ it('should group messages in multi-turn conversation', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'user',
+ content: 'What is the weather?',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'assistant',
+ content: 'Checking weather',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-3',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: 'Sunny, 25°C',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-4',
+ role: 'user',
+ content: 'What about news?',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-5',
+ role: 'assistant',
+ content: 'Checking news',
+ tools: [
+ {
+ id: 'tool-2',
+ identifier: 'news',
+ apiName: 'getNews',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-6',
+ role: 'tool',
+ tool_call_id: 'tool-2',
+ content: 'AI breakthrough',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result).toHaveLength(4); // 2 users + 2 grouped assistants
+ expect(result[0].role).toBe('user');
+ expect(result[1].role).toBe('group');
+ expect(result[2].role).toBe('user');
+ expect(result[3].role).toBe('group');
+ });
+
+ it('should handle mixed grouped and non-grouped messages', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Hello!',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'assistant',
+ content: 'Using tools',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-3',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: 'Result',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result).toHaveLength(2);
+ expect(result[0].role).toBe('assistant');
+ expect(result[0].children).toBeUndefined();
+ expect(result[1].role).toBe('group');
+ expect(result[1].children).toHaveLength(1);
+ });
+ });
+
+ describe('Edge Cases', () => {
+ it('should group follow-up assistant with its own tools and results', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Let me check the weather',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: 'Sunny, 25°C',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-3',
+ role: 'assistant',
+ content: 'Based on weather, let me check news',
+ parentId: 'msg-2',
+ tools: [
+ {
+ id: 'tool-2',
+ identifier: 'news',
+ apiName: 'getNews',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-4',
+ role: 'tool',
+ tool_call_id: 'tool-2',
+ content: 'Breaking news',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ // Should have 1 group with 2 children
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('group');
+ expect(result[0].children).toHaveLength(2);
+
+ // First child: original assistant with tool result
+ expect(result[0].children![0].id).toBe('msg-1');
+ expect(result[0].children![0].tools![0].result?.content).toBe('Sunny, 25°C');
+
+ // Second child: follow-up assistant with its own tool result
+ expect(result[0].children![1].id).toBe('msg-3');
+ expect(result[0].children![1].tools).toHaveLength(1);
+ expect(result[0].children![1].tools![0].result?.content).toBe('Breaking news');
+ });
+
+ it('should group multiple follow-up assistants in chain (3+ assistants)', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Step 1',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test1',
+ apiName: 'test1',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: 'Result 1',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-3',
+ role: 'assistant',
+ content: 'Step 2',
+ parentId: 'msg-2',
+ tools: [
+ {
+ id: 'tool-2',
+ identifier: 'test2',
+ apiName: 'test2',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-4',
+ role: 'tool',
+ tool_call_id: 'tool-2',
+ content: 'Result 2',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-5',
+ role: 'assistant',
+ content: 'Step 3 final',
+ parentId: 'msg-4',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ // Should have 1 group with 3 children
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('group');
+ expect(result[0].children).toHaveLength(3);
+
+ expect(result[0].children![0].id).toBe('msg-1');
+ expect(result[0].children![0].tools![0].result?.content).toBe('Result 1');
+
+ expect(result[0].children![1].id).toBe('msg-3');
+ expect(result[0].children![1].tools![0].result?.content).toBe('Result 2');
+
+ expect(result[0].children![2].id).toBe('msg-5');
+ expect(result[0].children![2].content).toBe('Step 3 final');
+ });
+
+ it('should group follow-up assistant with parentId pointing to tool', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Let me check',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: 'Tool result',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-3',
+ role: 'assistant',
+ content: 'Based on the result, here is my answer',
+ parentId: 'msg-2', // Points to tool message
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ // Should have 1 group containing both assistants
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('group');
+ expect(result[0].children).toHaveLength(2);
+
+ // First child: original assistant with tool result
+ expect(result[0].children![0].id).toBe('msg-1');
+ expect(result[0].children![0].content).toBe('Let me check');
+ expect(result[0].children![0].tools![0].result?.content).toBe('Tool result');
+
+ // Second child: follow-up assistant
+ expect(result[0].children![1].id).toBe('msg-3');
+ expect(result[0].children![1].content).toBe('Based on the result, here is my answer');
+ });
+
+ it('should handle orphaned tool messages', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'tool',
+ tool_call_id: 'unknown-tool',
+ content: 'Orphaned result',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('tool');
+ });
+
+ it('should handle tool messages with errors', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Checking',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: '',
+ pluginError: { message: 'Failed to execute' },
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('group');
+
+ const block = result[0].children![0];
+ expect(block.tools![0].result?.error).toEqual({ message: 'Failed to execute' });
+ });
+
+ it('should preserve message order', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'user',
+ content: 'First',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'assistant',
+ content: 'Second',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-3',
+ role: 'user',
+ content: 'Third',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result).toHaveLength(3);
+ expect(result[0].content).toBe('First');
+ expect(result[1].content).toBe('Second');
+ expect(result[2].content).toBe('Third');
+ });
+ });
+
+ describe('Children Structure Validation', () => {
+ it('should use message ID as block ID', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Test',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result[0].children![0].id).toBe('msg-1');
+ });
+
+ it('should clear parent fields when creating children', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Test',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ imageList: [{ id: 'img-1', url: 'http://example.com/img.png', alt: 'test' }],
+ fileList: [
+ {
+ id: 'file-1',
+ url: 'http://example.com/file.pdf',
+ name: 'test.pdf',
+ size: 1024,
+ fileType: 'application/pdf',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result[0].tools).toBeUndefined();
+ expect(result[0].imageList).toBeUndefined();
+ expect(result[0].fileList).toBeUndefined();
+ expect(result[0].content).toBe('');
+
+ const block = result[0].children![0];
+ expect(block.content).toBe('Test');
+ expect(block.tools).toHaveLength(1);
+ expect(block.imageList).toHaveLength(1);
+ expect(block.fileList).toHaveLength(1);
+ });
+
+ it('should preserve all tool result fields', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Test',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: 'Result content',
+ pluginState: { step: 1 },
+ pluginError: null,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ const block = result[0].children![0];
+ expect(block.tools![0].result).toMatchObject({
+ content: 'Result content',
+ state: { step: 1 },
+ error: null,
+ });
+ });
+ });
+
+ describe('Metadata Handling', () => {
+ it('should preserve usage and performance in children blocks', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Test',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ metadata: {
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150,
+ cost: 0.01,
+ tps: 50,
+ ttft: 100,
+ },
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ // Child should have usage
+ expect(result[0].children![0].usage).toEqual({
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150,
+ cost: 0.01,
+ });
+
+ // Child should have performance
+ expect(result[0].children![0].performance).toEqual({
+ tps: 50,
+ ttft: 100,
+ });
+ });
+
+ it('should aggregate usage and performance from multiple children', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Step 1',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test1',
+ apiName: 'test1',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ metadata: {
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150,
+ cost: 0.01,
+ },
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: 'Result 1',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-3',
+ role: 'assistant',
+ content: 'Step 2',
+ parentId: 'msg-2',
+ metadata: {
+ totalInputTokens: 200,
+ totalOutputTokens: 100,
+ totalTokens: 300,
+ cost: 0.02,
+ },
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ // Group should have aggregated usage
+ expect(result[0].usage).toEqual({
+ totalInputTokens: 300, // 100 + 200
+ totalOutputTokens: 150, // 50 + 100
+ totalTokens: 450, // 150 + 300
+ cost: 0.03, // 0.01 + 0.02
+ });
+
+ // metadata should be cleared in favor of usage/performance
+ expect(result[0].metadata).toBeUndefined();
+ });
+
+ it('should handle speed metrics correctly', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Step 1',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test1',
+ apiName: 'test1',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ metadata: {
+ ttft: 100,
+ tps: 50,
+ duration: 1000,
+ latency: 1200,
+ },
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ content: 'Result 1',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ {
+ id: 'msg-3',
+ role: 'assistant',
+ content: 'Step 2',
+ parentId: 'msg-2',
+ metadata: {
+ ttft: 200, // Should be ignored
+ tps: 60,
+ duration: 1500,
+ latency: 1800,
+ },
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ // Verify performance metrics aggregation
+ expect(result[0].performance).toEqual({
+ ttft: 100, // First child's value only
+ tps: 55, // Average: (50 + 60) / 2
+ duration: 2500, // Sum: 1000 + 1500
+ latency: 3000, // Sum: 1200 + 1800
+ });
+
+ // metadata should be cleared in favor of usage/performance
+ expect(result[0].metadata).toBeUndefined();
+ });
+
+ it('should have no usage or performance if children have no metadata', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Test',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ // Should have no usage or performance
+ expect(result[0].usage).toBeUndefined();
+ expect(result[0].performance).toBeUndefined();
+ expect(result[0].metadata).toBeUndefined();
+ });
+ });
+
+ describe('Empty and Null Cases', () => {
+ it('should convert empty arrays to undefined in children', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Test',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ imageList: [], // Empty array
+ fileList: [], // Empty array
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ // Empty arrays should become undefined
+ expect(result[0].children![0].imageList).toBeUndefined();
+ expect(result[0].children![0].fileList).toBeUndefined();
+ });
+
+ it('should handle empty message list', () => {
+ const result = groupAssistantMessages([]);
+ expect(result).toEqual([]);
+ });
+
+ it('should handle empty tools array', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Test',
+ tools: [],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('assistant');
+ expect(result[0].children).toBeUndefined();
+ });
+ });
+});
diff --git a/packages/database/src/utils/groupMessages.ts b/packages/database/src/utils/groupMessages.ts
new file mode 100644
index 00000000000..84f6bed85d9
--- /dev/null
+++ b/packages/database/src/utils/groupMessages.ts
@@ -0,0 +1,359 @@
+import {
+ AssistantContentBlock,
+ ChatToolPayloadWithResult,
+ MessageMetadata,
+ ModelPerformance,
+ ModelUsage,
+ UIChatMessage,
+} from '@lobechat/types';
+
+/**
+ * Split MessageMetadata into usage and performance
+ */
+function splitMetadata(metadata?: MessageMetadata | null): {
+ performance?: ModelPerformance;
+ usage?: ModelUsage;
+} {
+ if (!metadata) return {};
+
+ const usage: ModelUsage = {};
+ const performance: ModelPerformance = {};
+
+ // Extract usage fields (tokens and cost)
+ const usageFields = [
+ 'inputCachedTokens',
+ 'inputCacheMissTokens',
+ 'inputWriteCacheTokens',
+ 'inputTextTokens',
+ 'inputImageTokens',
+ 'inputAudioTokens',
+ 'inputCitationTokens',
+ 'outputTextTokens',
+ 'outputImageTokens',
+ 'outputAudioTokens',
+ 'outputReasoningTokens',
+ 'acceptedPredictionTokens',
+ 'rejectedPredictionTokens',
+ 'totalInputTokens',
+ 'totalOutputTokens',
+ 'totalTokens',
+ 'cost',
+ ] as const;
+
+ let hasUsage = false;
+ usageFields.forEach((field) => {
+ if (metadata[field] !== undefined) {
+ usage[field] = metadata[field] as any;
+ hasUsage = true;
+ }
+ });
+
+ // Extract performance fields
+ const performanceFields = ['tps', 'ttft', 'duration', 'latency'] as const;
+ let hasPerformance = false;
+ performanceFields.forEach((field) => {
+ if (metadata[field] !== undefined) {
+ performance[field] = metadata[field];
+ hasPerformance = true;
+ }
+ });
+
+ return {
+ performance: hasPerformance ? performance : undefined,
+ usage: hasUsage ? usage : undefined,
+ };
+}
+
+/**
+ * Aggregate metadata from all children blocks
+ * Creates structured usage and performance metrics
+ */
+function aggregateMetadata(
+ children: AssistantContentBlock[],
+): { performance?: ModelPerformance; usage?: ModelUsage } | null {
+ const usage: ModelUsage = {};
+ const performance: ModelPerformance = {};
+ let hasUsageData = false;
+ let hasPerformanceData = false;
+ let tpsSum = 0;
+ let tpsCount = 0;
+
+ children.forEach((child) => {
+ // Aggregate usage metrics (tokens and cost)
+ if (child.usage) {
+ const tokenFields = [
+ 'inputCachedTokens',
+ 'inputCacheMissTokens',
+ 'inputWriteCacheTokens',
+ 'inputTextTokens',
+ 'inputImageTokens',
+ 'inputAudioTokens',
+ 'inputCitationTokens',
+ 'outputTextTokens',
+ 'outputImageTokens',
+ 'outputAudioTokens',
+ 'outputReasoningTokens',
+ 'acceptedPredictionTokens',
+ 'rejectedPredictionTokens',
+ 'totalInputTokens',
+ 'totalOutputTokens',
+ 'totalTokens',
+ ] as const;
+
+ tokenFields.forEach((field) => {
+ if (typeof child.usage![field] === 'number') {
+ usage[field] = (usage[field] || 0) + child.usage![field]!;
+ hasUsageData = true;
+ }
+ });
+
+ if (typeof child.usage.cost === 'number') {
+ usage.cost = (usage.cost || 0) + child.usage.cost;
+ hasUsageData = true;
+ }
+ }
+
+ // Aggregate performance metrics
+ // - ttft: use the first child's value (time to first token)
+ // - tps: calculate average across all children
+ // - duration: sum all durations
+ // - latency: sum all latencies
+ if (child.performance) {
+ if (child.performance.ttft !== undefined && performance.ttft === undefined) {
+ performance.ttft = child.performance.ttft; // First child only
+ hasPerformanceData = true;
+ }
+ if (typeof child.performance.tps === 'number') {
+ tpsSum += child.performance.tps;
+ tpsCount += 1;
+ hasPerformanceData = true;
+ }
+ if (child.performance.duration !== undefined) {
+ performance.duration = (performance.duration || 0) + child.performance.duration;
+ hasPerformanceData = true;
+ }
+ if (child.performance.latency !== undefined) {
+ performance.latency = (performance.latency || 0) + child.performance.latency;
+ hasPerformanceData = true;
+ }
+ }
+ });
+
+ // Calculate average tps
+ if (tpsCount > 0) {
+ performance.tps = tpsSum / tpsCount;
+ }
+
+ // Return null if no data
+ if (!hasUsageData && !hasPerformanceData) return null;
+
+ // Return structured metrics
+ const result: { performance?: ModelPerformance; usage?: ModelUsage } = {};
+ if (hasUsageData) result.usage = usage;
+ if (hasPerformanceData) result.performance = performance;
+
+ return result;
+}
+
+/**
+ * Group assistant messages with their tool results
+ * Converts flat message list into grouped structure with children
+ *
+ * @param messages - Flat message list from database query
+ * @returns Grouped message list with assistant children populated
+ */
+export function groupAssistantMessages(messages: UIChatMessage[]): UIChatMessage[] {
+ const result: UIChatMessage[] = [];
+ const toolMessageIds = new Set<string>();
+ const processedAssistantIds = new Set<string>();
+
+ // 1. Create tool_call_id -> tool message mapping
+ const toolMessageMap = new Map<string, UIChatMessage>();
+ messages.forEach((msg) => {
+ if (msg.role === 'tool' && msg.tool_call_id) {
+ toolMessageMap.set(msg.tool_call_id, msg);
+ }
+ });
+
+ // 2. Build message ID -> message mapping for quick lookup
+ const messageMap = new Map<string, UIChatMessage>();
+ messages.forEach((msg) => {
+ messageMap.set(msg.id, msg);
+ });
+
+ // 3. Find follow-up assistants that have tool messages as parent
+ // Map: tool message id -> follow-up assistant messages
+ const toolToFollowUpAssistants = new Map<string, UIChatMessage[]>();
+ messages.forEach((msg) => {
+ if (msg.role === 'assistant' && msg.parentId) {
+ const parent = messageMap.get(msg.parentId);
+ if (parent && parent.role === 'tool') {
+ const existing = toolToFollowUpAssistants.get(msg.parentId) || [];
+ toolToFollowUpAssistants.set(msg.parentId, [...existing, msg]);
+ }
+ }
+ });
+
+ // 4. Process messages
+ messages.forEach((msg) => {
+ // Skip tool messages that have been merged
+ if (msg.role === 'tool') {
+ if (!toolMessageIds.has(msg.id)) {
+ result.push(msg);
+ }
+ return;
+ }
+
+ // Handle non-assistant messages
+ if (msg.role !== 'assistant') {
+ result.push(msg);
+ return;
+ }
+
+ // Skip assistant messages that have been processed as follow-ups
+ if (processedAssistantIds.has(msg.id)) {
+ return;
+ }
+
+ // 5. Process assistant messages
+ const assistantMsg = { ...msg };
+
+ // If no tools, add as-is (unless it's a follow-up, which should have been skipped above)
+ if (!msg.tools || msg.tools.length === 0) {
+ result.push(assistantMsg);
+ return;
+ }
+
+ // 6. Build children structure
+ const children: AssistantContentBlock[] = [];
+
+ // First child: original assistant with tool results
+ const toolsWithResults: ChatToolPayloadWithResult[] = msg.tools.map((tool) => {
+ const toolMsg = toolMessageMap.get(tool.id);
+
+ if (toolMsg) {
+ // Mark tool message as merged
+ toolMessageIds.add(toolMsg.id);
+
+ return {
+ ...tool,
+ result: {
+ content: toolMsg.content,
+ error: toolMsg.pluginError,
+ id: toolMsg.id,
+ state: toolMsg.pluginState,
+ },
+ };
+ }
+
+ // Tool message not yet available (still executing)
+ return tool;
+ });
+
+ const { usage: msgUsage, performance: msgPerformance } = splitMetadata(msg.metadata);
+ children.push({
+ content: msg.content || '',
+ fileList: msg.fileList && msg.fileList.length > 0 ? msg.fileList : undefined,
+ id: msg.id,
+ imageList: msg.imageList && msg.imageList.length > 0 ? msg.imageList : undefined,
+ performance: msgPerformance,
+ tools: toolsWithResults,
+ usage: msgUsage,
+ });
+
+ // 7. Recursively add follow-up assistants as additional children
+ // Keep track of tool result IDs that are part of this group
+ const groupToolResultIds = new Set<string>();
+ toolsWithResults.forEach((tool) => {
+ if (tool.result) {
+ groupToolResultIds.add(tool.result.id);
+ }
+ });
+
+ // Recursively collect all follow-up assistants
+ const collectFollowUpAssistants = (currentToolResultIds: Set<string>): void => {
+ const newToolResultIds = new Set<string>();
+
+ currentToolResultIds.forEach((toolResultId) => {
+ const followUps = toolToFollowUpAssistants.get(toolResultId) || [];
+ followUps.forEach((followUpMsg) => {
+ // Skip if already processed
+ if (processedAssistantIds.has(followUpMsg.id)) return;
+
+ // Process follow-up assistant's tools and fill in their results
+ const followUpToolsWithResults: ChatToolPayloadWithResult[] | undefined =
+ followUpMsg.tools?.map((followUpTool) => {
+ const followUpToolMsg = toolMessageMap.get(followUpTool.id);
+
+ if (followUpToolMsg) {
+ // Mark tool message as merged
+ toolMessageIds.add(followUpToolMsg.id);
+ // Track this tool result for next iteration
+ newToolResultIds.add(followUpToolMsg.id);
+
+ return {
+ ...followUpTool,
+ result: {
+ content: followUpToolMsg.content,
+ error: followUpToolMsg.pluginError,
+ id: followUpToolMsg.id,
+ state: followUpToolMsg.pluginState,
+ },
+ };
+ }
+
+ // Tool message not yet available
+ return followUpTool;
+ });
+
+ const { usage: followUpUsage, performance: followUpPerformance } = splitMetadata(
+ followUpMsg.metadata,
+ );
+ children.push({
+ content: followUpMsg.content || '',
+ fileList:
+ followUpMsg.fileList && followUpMsg.fileList.length > 0
+ ? followUpMsg.fileList
+ : undefined,
+ id: followUpMsg.id,
+ imageList:
+ followUpMsg.imageList && followUpMsg.imageList.length > 0
+ ? followUpMsg.imageList
+ : undefined,
+ performance: followUpPerformance,
+ tools: followUpToolsWithResults,
+ usage: followUpUsage,
+ });
+ processedAssistantIds.add(followUpMsg.id);
+ });
+ });
+
+ // Recursively process the next level
+ if (newToolResultIds.size > 0) {
+ collectFollowUpAssistants(newToolResultIds);
+ }
+ };
+
+ collectFollowUpAssistants(groupToolResultIds);
+
+ // 8. Aggregate usage and performance from all children
+ const aggregated = aggregateMetadata(children);
+
+ // 9. Set children and aggregated metrics
+ assistantMsg.role = 'group';
+ assistantMsg.children = children;
+ if (aggregated) {
+ assistantMsg.usage = aggregated.usage;
+ assistantMsg.performance = aggregated.performance;
+ }
+ delete assistantMsg.metadata; // Clear individual metadata
+ delete assistantMsg.tools;
+ delete assistantMsg.imageList;
+ delete assistantMsg.fileList;
+ assistantMsg.content = ''; // Content moved to children
+
+ result.push(assistantMsg);
+ });
+
+ return result;
+}
diff --git a/packages/memory-extract/.env.example b/packages/memory-extract/.env.example
new file mode 100644
index 00000000000..cac89eabf7a
--- /dev/null
+++ b/packages/memory-extract/.env.example
@@ -0,0 +1,3 @@
+# OpenAI Configuration
+OPENAI_API_KEY=your_openai_api_key_here
+OPENAI_BASE_URL=https://api.openai.com/v1
diff --git a/packages/memory-extract/.gitignore b/packages/memory-extract/.gitignore
new file mode 100644
index 00000000000..9a3551f360b
--- /dev/null
+++ b/packages/memory-extract/.gitignore
@@ -0,0 +1,8 @@
+# Environment variables
+.env
+
+# Output files
+datasets
+!datasets/*/.gitkeep
+
+
diff --git a/packages/memory-extract/package.json b/packages/memory-extract/package.json
new file mode 100644
index 00000000000..bb9031d2455
--- /dev/null
+++ b/packages/memory-extract/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@lobechat/memory-extract",
+ "version": "1.0.0",
+ "private": true,
+ "main": "src/index.ts",
+ "scripts": {
+ "gatekeeper": "tsx scripts/run-gatekeeper.ts"
+ },
+ "dependencies": {
+ "@lobechat/model-runtime": "workspace:*",
+ "@lobechat/prompts": "workspace:*",
+ "dotenv": "^16.4.7",
+ "ora": "^8.2.0"
+ },
+ "devDependencies": {
+ "tsx": "^4.19.2"
+ },
+ "peerDependencies": {
+ "zod": "^3"
+ }
+}
diff --git a/packages/memory-extract/vitest.config.mts b/packages/memory-extract/vitest.config.mts
new file mode 100644
index 00000000000..78007b7aeb2
--- /dev/null
+++ b/packages/memory-extract/vitest.config.mts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ reporter: ['text', 'json', 'lcov', 'text-summary'],
+ },
+ environment: 'node',
+ },
+});
diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.ts
index e3f0936f202..aa6705d181a 100644
--- a/packages/model-runtime/src/core/streams/protocol.ts
+++ b/packages/model-runtime/src/core/streams/protocol.ts
@@ -1,4 +1,4 @@
-import { ChatCitationItem, ModelSpeed, ModelUsage } from '@lobechat/types';
+import { ChatCitationItem, ModelPerformance, ModelUsage } from '@lobechat/types';
import type { Pricing } from 'model-bank';
import { parseToolCalls } from '../../helpers';
@@ -218,7 +218,7 @@ export function createCallbacksTransformer(cb: ChatStreamCallbacks | undefined)
let aggregatedText = '';
let aggregatedThinking: string | undefined = undefined;
let usage: ModelUsage | undefined;
- let speed: ModelSpeed | undefined;
+ let speed: ModelPerformance | undefined;
let grounding: any;
let toolsCalling: any;
@@ -410,7 +410,7 @@ export const createTokenSpeedCalculator = (
latency,
tps,
ttft,
- } as ModelSpeed,
+ } as ModelPerformance,
id: TOKEN_SPEED_CHUNK_ID,
type: 'speed',
});
diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.ts
index d4fa27745f2..c1e857c1155 100644
--- a/packages/model-runtime/src/types/chat.ts
+++ b/packages/model-runtime/src/types/chat.ts
@@ -1,4 +1,4 @@
-import { ModelSpeed, ModelTokensUsage, ModelUsage } from '@lobechat/types';
+import { ModelPerformance, ModelTokensUsage, ModelUsage } from '@lobechat/types';
import { MessageToolCall, MessageToolCallChunk } from './toolsCalling';
@@ -186,7 +186,7 @@ export interface ChatCompletionTool {
export interface OnFinishData {
grounding?: any;
- speed?: ModelSpeed;
+ speed?: ModelPerformance;
text: string;
thinking?: string;
toolsCalling?: MessageToolCall[];
diff --git a/packages/types/src/message/common/base.ts b/packages/types/src/message/common/base.ts
index 1254d164e31..05e583a8d6f 100644
--- a/packages/types/src/message/common/base.ts
+++ b/packages/types/src/message/common/base.ts
@@ -1,4 +1,3 @@
-/* eslint-disable sort-keys-fix/sort-keys-fix , typescript-sort-keys/interface */
import type { ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';
import type { IPluginErrorType } from '@lobehub/chat-plugin-sdk';
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index 074c1d89e81..cf7fc980f09 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -45,23 +45,23 @@ export interface ModelUsage extends ModelTokensUsage {
cost?: number;
}
-export interface ModelSpeed {
+export interface ModelPerformance {
/**
* tokens per second
*/
tps?: number;
/**
- * time to first token
+ * time to first token (ms)
*/
ttft?: number;
/**
- * from output start to output finish
+ * from output start to output finish (ms)
*/
duration?: number;
/**
- * from input start to output finish
+ * from input start to output finish (ms)
*/
latency?: number;
}
-export interface MessageMetadata extends ModelUsage, ModelSpeed {}
+export interface MessageMetadata extends ModelUsage, ModelPerformance {}
diff --git a/packages/types/src/message/common/tools.ts b/packages/types/src/message/common/tools.ts
index db9c8231c1a..634ab6cd6b0 100644
--- a/packages/types/src/message/common/tools.ts
+++ b/packages/types/src/message/common/tools.ts
@@ -19,6 +19,23 @@ export interface ChatToolPayload {
type: LobeToolRenderType;
}
+/**
+ * Tool execution result from tool messages
+ */
+export interface ChatToolResult {
+ content: string | null;
+ error?: any;
+ id: string;
+ state?: any;
+}
+
+/**
+ * Chat tool payload with merged execution result
+ */
+export interface ChatToolPayloadWithResult extends ChatToolPayload {
+ result?: ChatToolResult;
+}
+
export interface ToolsCallingContext {
topicId?: string;
}
diff --git a/packages/types/src/message/db/item.ts b/packages/types/src/message/db/item.ts
index 16739cdb17d..f35e819fd66 100644
--- a/packages/types/src/message/db/item.ts
+++ b/packages/types/src/message/db/item.ts
@@ -1,29 +1,35 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix , typescript-sort-keys/interface */
import { GroundingSearch } from '../../search';
import { MessageMetadata, ModelReasoning } from '../common';
export interface DBMessageItem {
- agentId: string | null;
- clientId: string | null;
- content: string | null;
- createdAt: Date;
- error: any | null;
- favorite: boolean | null;
id: string;
- metadata?: MessageMetadata | null;
- model: string | null;
- observationId: string | null;
- parentId: string | null;
- provider: string | null;
- quotaId: string | null;
- reasoning: ModelReasoning | null;
+
role: string;
+ content: string;
+ reasoning: ModelReasoning | null;
search: GroundingSearch | null;
- sessionId: string | null;
- threadId: string | null;
tools: any | null;
+
+ sessionId: string | null;
topicId: string | null;
- // jsonb type
+ threadId: string | null;
+ agentId: string | null;
+
+ parentId: string | null;
+ quotaId: string | null;
+ favorite: boolean | null;
+ metadata?: MessageMetadata | null;
+ error: any | null;
+ model: string | null;
+ provider: string | null;
+
traceId: string | null;
- updatedAt: Date;
+ observationId: string | null;
+
+ clientId: string | null;
+
userId: string;
+ updatedAt: Date;
+ createdAt: Date;
}
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index 1167e31fbba..86d305e8952 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -1,14 +1,19 @@
-import { UploadFileItem } from '../../files';
import { MetaData } from '../../meta';
-import { MessageSemanticSearchChunk } from '../../rag';
import { GroundingSearch } from '../../search';
-import { ChatImageItem, ChatMessageError, MessageMetadata, ModelReasoning } from '../common';
-import { ChatPluginPayload, ChatToolPayload } from '../common/tools';
+import {
+ ChatImageItem,
+ ChatMessageError,
+ MessageMetadata,
+ ModelPerformance,
+ ModelReasoning,
+ ModelUsage,
+} from '../common';
+import { ChatPluginPayload, ChatToolPayload, ChatToolPayloadWithResult } from '../common/tools';
import { ChatMessageExtra } from './extra';
import { ChatFileChunk } from './rag';
import { ChatVideoItem } from './video';
-export type UIMessageRoleType = 'user' | 'system' | 'assistant' | 'tool' | 'supervisor';
+export type UIMessageRoleType = 'user' | 'system' | 'assistant' | 'tool' | 'supervisor' | 'group';
export interface ChatFileItem {
content?: string;
@@ -24,7 +29,9 @@ export interface AssistantContentBlock {
fileList?: ChatFileItem[];
id: string;
imageList?: ChatImageItem[];
- tools?: ChatToolPayload[];
+ performance?: ModelPerformance;
+ tools?: ChatToolPayloadWithResult[];
+ usage?: ModelUsage;
}
export interface UIChatMessage {
@@ -63,6 +70,11 @@ export interface UIChatMessage {
* parent message id
*/
parentId?: string;
+ /**
+ * Performance metrics (tps, ttft, duration, latency)
+ * Aggregated from all children in group messages
+ */
+ performance?: ModelPerformance;
plugin?: ChatPluginPayload;
pluginError?: any;
pluginState?: any;
@@ -96,66 +108,10 @@ export interface UIChatMessage {
*/
traceId?: string;
updatedAt: number;
- videoList?: ChatVideoItem[];
-}
-
-export interface CreateMessageParams
- extends Partial<Omit<UIChatMessage, 'content' | 'role' | 'topicId' | 'chunksList'>> {
- content: string;
- error?: ChatMessageError | null;
- fileChunks?: MessageSemanticSearchChunk[];
- files?: string[];
- fromModel?: string;
- fromProvider?: string;
- groupId?: string;
- role: UIMessageRoleType;
- sessionId: string;
- targetId?: string | null;
- threadId?: string | null;
- topicId?: string;
- traceId?: string;
-}
-
-export interface SendMessageParams {
- /**
- * create a thread
- */
- createThread?: boolean;
- files?: UploadFileItem[];
- /**
- *
- * https://github.com/lobehub/lobe-chat/pull/2086
- */
- isWelcomeQuestion?: boolean;
- message: string;
- /**
- * Additional metadata for the message (e.g., mentioned users)
- */
- metadata?: Record<string, any>;
- onlyAddUserMessage?: boolean;
-}
-
-export interface SendThreadMessageParams {
- /**
- * create a thread
- */
- createNewThread?: boolean;
- // files?: UploadFileItem[];
- message: string;
- onlyAddUserMessage?: boolean;
-}
-
-export interface SendGroupMessageParams {
- files?: UploadFileItem[];
- groupId: string;
- message: string;
- /**
- * Additional metadata for the message (e.g., mentioned users)
- */
- metadata?: Record<string, any>;
- onlyAddUserMessage?: boolean;
/**
- * for group chat
+ * Token usage and cost metrics
+ * Aggregated from all children in group messages
*/
- targetMemberId?: string | null;
+ usage?: ModelUsage;
+ videoList?: ChatVideoItem[];
}
diff --git a/packages/types/src/message/ui/index.ts b/packages/types/src/message/ui/index.ts
index ad8ca3c3214..6c36fb48a4e 100644
--- a/packages/types/src/message/ui/index.ts
+++ b/packages/types/src/message/ui/index.ts
@@ -1,4 +1,5 @@
export * from './chat';
export * from './extra';
+export * from './params';
export * from './rag';
export * from './video';
diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.ts
new file mode 100644
index 00000000000..1cdc70e9a66
--- /dev/null
+++ b/packages/types/src/message/ui/params.ts
@@ -0,0 +1,65 @@
+import { UploadFileItem } from '../../files';
+import { MessageSemanticSearchChunk } from '../../rag';
+import { ChatMessageError } from '../common/base';
+import { UIChatMessage, UIMessageRoleType } from './chat';
+
+export interface CreateMessageParams
+ extends Partial<Omit<UIChatMessage, 'content' | 'role' | 'topicId' | 'chunksList'>> {
+ content: string;
+ error?: ChatMessageError | null;
+ fileChunks?: MessageSemanticSearchChunk[];
+ files?: string[];
+ fromModel?: string;
+ fromProvider?: string;
+ groupId?: string;
+ role: UIMessageRoleType;
+ sessionId: string;
+ targetId?: string | null;
+ threadId?: string | null;
+ topicId?: string;
+ traceId?: string;
+}
+
+export interface SendMessageParams {
+ /**
+ * create a thread
+ */
+ createThread?: boolean;
+ files?: UploadFileItem[];
+ /**
+ *
+ * https://github.com/lobehub/lobe-chat/pull/2086
+ */
+ isWelcomeQuestion?: boolean;
+ message: string;
+ /**
+ * Additional metadata for the message (e.g., mentioned users)
+ */
+ metadata?: Record<string, any>;
+ onlyAddUserMessage?: boolean;
+}
+
+export interface SendThreadMessageParams {
+ /**
+ * create a thread
+ */
+ createNewThread?: boolean;
+ // files?: UploadFileItem[];
+ message: string;
+ onlyAddUserMessage?: boolean;
+}
+
+export interface SendGroupMessageParams {
+ files?: UploadFileItem[];
+ groupId: string;
+ message: string;
+ /**
+ * Additional metadata for the message (e.g., mentioned users)
+ */
+ metadata?: Record<string, any>;
+ onlyAddUserMessage?: boolean;
+ /**
+ * for group chat
+ */
+ targetMemberId?: string | null;
+}
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 4720dea4d54..5d74beb7519 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -1,5 +1,7 @@
import { ReactNode } from 'react';
+import { z } from 'zod';
+import { HumanInterventionConfigSchema, HumanInterventionPolicySchema } from './intervention';
import type { HumanInterventionConfig, HumanInterventionPolicy } from './intervention';
interface Meta {
@@ -26,6 +28,14 @@ interface Meta {
tags?: string[];
title: string;
}
+
+const MetaSchema = z.object({
+ avatar: z.string().optional(),
+ description: z.string().optional(),
+ tags: z.array(z.string()).optional(),
+ title: z.string(),
+});
+
export interface LobeChatPluginApi {
description: string;
/**
@@ -46,6 +56,14 @@ export interface LobeChatPluginApi {
url?: string;
}
+export const LobeChatPluginApiSchema = z.object({
+ description: z.string(),
+ humanIntervention: HumanInterventionConfigSchema.optional(),
+ name: z.string(),
+ parameters: z.record(z.string(), z.any()),
+ url: z.string().optional(),
+});
+
export interface BuiltinToolManifest {
api: LobeChatPluginApi[];
@@ -74,6 +92,15 @@ export interface BuiltinToolManifest {
type?: 'builtin';
}
+export const BuiltinToolManifestSchema = z.object({
+ api: z.array(LobeChatPluginApiSchema),
+ humanIntervention: HumanInterventionPolicySchema.optional(),
+ identifier: z.string(),
+ meta: MetaSchema,
+ systemRole: z.string(),
+ type: z.literal('builtin').optional(),
+});
+
export interface LobeBuiltinTool {
hidden?: boolean;
identifier: string;
@@ -81,6 +108,13 @@ export interface LobeBuiltinTool {
type: 'builtin';
}
+export const LobeBuiltinToolSchema = z.object({
+ hidden: z.boolean().optional(),
+ identifier: z.string(),
+ manifest: BuiltinToolManifestSchema,
+ type: z.literal('builtin'),
+});
+
export interface BuiltinRenderProps<Content = any, Arguments = any, State = any> {
apiName?: string;
args: Arguments;
diff --git a/packages/types/src/tool/intervention.ts b/packages/types/src/tool/intervention.ts
index af93a8c8e19..77a26438d3e 100644
--- a/packages/types/src/tool/intervention.ts
+++ b/packages/types/src/tool/intervention.ts
@@ -1,3 +1,5 @@
+import { z } from 'zod';
+
/**
* Human Intervention Policy
*/
@@ -6,6 +8,8 @@ export type HumanInterventionPolicy =
| 'always' // Always require intervention
| 'first'; // Require intervention on first call only
+export const HumanInterventionPolicySchema = z.enum(['never', 'always', 'first']);
+
/**
* Argument Matcher for parameter-level filtering
* Supports wildcard patterns, prefix matching, and regex
@@ -22,6 +26,14 @@ export type ArgumentMatcher =
type: 'exact' | 'prefix' | 'wildcard' | 'regex';
};
+export const ArgumentMatcherSchema: z.ZodType<ArgumentMatcher> = z.union([
+ z.string(),
+ z.object({
+ pattern: z.string(),
+ type: z.enum(['exact', 'prefix', 'wildcard', 'regex']),
+ }),
+]);
+
/**
* Human Intervention Rule
* Used for parameter-level control of intervention behavior
@@ -42,6 +54,11 @@ export interface HumanInterventionRule {
policy: HumanInterventionPolicy;
}
+export const HumanInterventionRuleSchema: z.ZodType<HumanInterventionRule> = z.object({
+ match: z.record(z.string(), ArgumentMatcherSchema).optional(),
+ policy: HumanInterventionPolicySchema,
+});
+
/**
* Human Intervention Configuration
* Can be either:
@@ -54,6 +71,11 @@ export interface HumanInterventionRule {
*/
export type HumanInterventionConfig = HumanInterventionPolicy | HumanInterventionRule[];
+export const HumanInterventionConfigSchema: z.ZodType<HumanInterventionConfig> = z.union([
+ HumanInterventionPolicySchema,
+ z.array(HumanInterventionRuleSchema),
+]);
+
/**
* Human Intervention Response
* User's response to an intervention request
@@ -85,6 +107,16 @@ export interface HumanInterventionResponse {
};
}
+export const HumanInterventionResponseSchema = z.object({
+ action: z.enum(['approve', 'reject', 'select']),
+ data: z
+ .object({
+ remember: z.boolean().optional(),
+ selected: z.union([z.string(), z.array(z.string())]).optional(),
+ })
+ .optional(),
+});
+
/**
* Parameters for shouldIntervene method
*/
@@ -112,3 +144,10 @@ export interface ShouldInterveneParams {
*/
toolKey?: string;
}
+
+export const ShouldInterveneParamsSchema = z.object({
+ config: HumanInterventionConfigSchema.optional(),
+ confirmedHistory: z.array(z.string()).optional(),
+ toolArgs: z.record(z.string(), z.any()).optional(),
+ toolKey: z.string().optional(),
+});
diff --git a/packages/utils/src/fetch/fetchSSE.ts b/packages/utils/src/fetch/fetchSSE.ts
index a4b9c04a1ce..156b6496b93 100644
--- a/packages/utils/src/fetch/fetchSSE.ts
+++ b/packages/utils/src/fetch/fetchSSE.ts
@@ -6,8 +6,8 @@ import {
ChatMessageError,
GroundingSearch,
MessageToolCall,
+ ModelPerformance,
ModelReasoning,
- ModelSpeed,
ModelUsage,
ResponseAnimation,
ResponseAnimationStyle,
@@ -26,7 +26,7 @@ export type OnFinishHandler = (
images?: ChatImageChunk[];
observationId?: string | null;
reasoning?: ModelReasoning;
- speed?: ModelSpeed;
+ speed?: ModelPerformance;
toolCalls?: MessageToolCall[];
traceId?: string | null;
type?: SSEFinishType;
@@ -40,7 +40,7 @@ export interface MessageUsageChunk {
}
export interface MessageSpeedChunk {
- speed: ModelSpeed;
+ speed: ModelPerformance;
type: 'speed';
}
@@ -265,7 +265,7 @@ export const fetchSSE = async (url: string, options: RequestInit & FetchSSEOptio
let grounding: GroundingSearch | undefined = undefined;
let usage: ModelUsage | undefined = undefined;
let images: ChatImageChunk[] = [];
- let speed: ModelSpeed | undefined = undefined;
+ let speed: ModelPerformance | undefined = undefined;
await fetchEventSource(url, {
body: options.body,
diff --git a/src/features/ChatItem/components/Title.tsx b/src/features/ChatItem/components/Title.tsx
index b4340560edc..047023c0c2a 100644
--- a/src/features/ChatItem/components/Title.tsx
+++ b/src/features/ChatItem/components/Title.tsx
@@ -7,6 +7,7 @@ import { ChatItemProps } from '../type';
export interface TitleProps {
avatar: ChatItemProps['avatar'];
+ className?: string;
placement?: ChatItemProps['placement'];
showTitle?: ChatItemProps['showTitle'];
time?: ChatItemProps['time'];
@@ -26,13 +27,13 @@ const formatTime = (time: number): string => {
}
};
-const Title = memo<TitleProps>(({ showTitle, placement, time, avatar, titleAddon }) => {
- const { styles } = useStyles({ placement, showTitle, time });
+const Title = memo<TitleProps>(({ showTitle, placement, time, avatar, titleAddon, className }) => {
+ const { styles, cx } = useStyles({ placement, showTitle, time });
return (
<Flexbox
align={'center'}
- className={styles.name}
+ className={cx(styles.name, className)}
direction={placement === 'left' ? 'horizontal' : 'horizontal-reverse'}
gap={4}
>
diff --git a/src/features/Conversation/Messages/Assistant/MessageContent.tsx b/src/features/Conversation/Messages/Assistant/MessageContent.tsx
index 920f426756e..5d8606a9ec7 100644
--- a/src/features/Conversation/Messages/Assistant/MessageContent.tsx
+++ b/src/features/Conversation/Messages/Assistant/MessageContent.tsx
@@ -1,15 +1,13 @@
+import { LOADING_FLAT } from '@lobechat/const';
import { UIChatMessage } from '@lobechat/types';
import { ReactNode, memo } from 'react';
import { Flexbox } from 'react-layout-kit';
-import { LOADING_FLAT } from '@/const/message';
-import { AssistantBlock } from '@/features/Conversation/Messages/Assistant/Block';
-import ImageFileListViewer from '@/features/Conversation/Messages/User/ImageFileListViewer';
-import VideoFileListViewer from '@/features/Conversation/Messages/User/VideoFileListViewer';
import { useChatStore } from '@/store/chat';
import { aiChatSelectors, chatSelectors } from '@/store/chat/selectors';
import { DefaultMessage } from '../Default';
+import ImageFileListViewer from '../User/ImageFileListViewer';
import FileChunks from './FileChunks';
import IntentUnderstanding from './IntentUnderstanding';
import Reasoning from './Reasoning';
@@ -20,7 +18,7 @@ export const AssistantMessageContent = memo<
UIChatMessage & {
editableContent: ReactNode;
}
->(({ id, tools, content, chunksList, search, imageList, videoList, children, ...props }) => {
+>(({ id, tools, content, chunksList, search, imageList, ...props }) => {
const editing = useChatStore(chatSelectors.isMessageEditing(id));
const generating = useChatStore(chatSelectors.isMessageGenerating(id));
@@ -32,7 +30,6 @@ export const AssistantMessageContent = memo<
const showSearch = !!search && !!search.citations?.length;
const showImageItems = !!imageList && imageList.length > 0;
- const showVideoItems = !!videoList && videoList.length > 0;
// remove \n to avoid empty content
// refs: https://github.com/lobehub/lobe-chat/pull/6153
@@ -42,15 +39,6 @@ export const AssistantMessageContent = memo<
const showFileChunks = !!chunksList && chunksList.length > 0;
- if (children && children?.length > 0)
- return (
- <Flexbox gap={8}>
- {children.map((item) => (
- <AssistantBlock key={item.id} {...item} editableContent={props.editableContent} />
- ))}
- </Flexbox>
- );
-
return editing ? (
<DefaultMessage
content={content}
@@ -79,7 +67,6 @@ export const AssistantMessageContent = memo<
)
)}
{showImageItems && <ImageFileListViewer items={imageList} />}
- {showVideoItems && <VideoFileListViewer items={videoList} />}
{tools && (
<Flexbox gap={8}>
{tools.map((toolCall, index) => (
diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsx
index 20cc306cb07..f1283a27ff5 100644
--- a/src/features/Conversation/Messages/Assistant/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import { LOADING_FLAT } from '@lobechat/const';
import { UIChatMessage } from '@lobechat/types';
import { Tag } from '@lobehub/ui';
import { useResponsive } from 'antd-style';
@@ -8,7 +9,6 @@ import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { HtmlPreviewAction } from '@/components/HtmlPreview';
-import { LOADING_FLAT } from '@/const/message';
import Avatar from '@/features/ChatItem/components/Avatar';
import BorderSpacing from '@/features/ChatItem/components/BorderSpacing';
import ErrorContent from '@/features/ChatItem/components/ErrorContent';
@@ -17,7 +17,7 @@ import Title from '@/features/ChatItem/components/Title';
import { useStyles } from '@/features/ChatItem/style';
import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/slices/chat';
+import { agentChatConfigSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { chatSelectors } from '@/store/chat/selectors';
import { chatGroupSelectors, useChatGroupStore } from '@/store/chatGroup';
@@ -30,7 +30,7 @@ import { userGeneralSettingsSelectors, userProfileSelectors } from '@/store/user
import ErrorMessageExtra, { useErrorContent } from '../../Error';
import { markdownElements } from '../../MarkdownElements';
import { useDoubleClickEdit } from '../../hooks/useDoubleClickEdit';
-import { normalizeThinkTags, processWithArtifact } from '../../utils';
+import { normalizeThinkTags, processWithArtifact } from '../../utils/markdown';
import { AssistantActionsBar } from './Actions';
import { AssistantMessageExtra } from './Extra';
import { AssistantMessageContent } from './MessageContent';
diff --git a/src/features/Conversation/utils.test.ts b/src/features/Conversation/utils/markdown.test.ts
similarity index 99%
rename from src/features/Conversation/utils.test.ts
rename to src/features/Conversation/utils/markdown.test.ts
index c923e5d4153..a02d6ee4db8 100644
--- a/src/features/Conversation/utils.test.ts
+++ b/src/features/Conversation/utils/markdown.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { processWithArtifact } from './utils';
+import { processWithArtifact } from './markdown';
describe('processWithArtifact', () => {
it('should removeLineBreaks with closed tag', () => {
diff --git a/src/features/Conversation/utils.ts b/src/features/Conversation/utils/markdown.ts
similarity index 99%
rename from src/features/Conversation/utils.ts
rename to src/features/Conversation/utils/markdown.ts
index 2b041247a2c..0380cfacf49 100644
--- a/src/features/Conversation/utils.ts
+++ b/src/features/Conversation/utils/markdown.ts
@@ -1,4 +1,4 @@
-import { ARTIFACT_TAG_REGEX, ARTIFACT_THINKING_TAG_REGEX } from '@/const/plugin';
+import { ARTIFACT_TAG_REGEX, ARTIFACT_THINKING_TAG_REGEX } from '@lobechat/const';
/**
* Replace all line breaks in the matched `lobeArtifact` tag with an empty string
diff --git a/src/tools/web-browsing/Render/PageContent/index.tsx b/src/tools/web-browsing/Render/PageContent/index.tsx
index ac487721645..ebf574176df 100644
--- a/src/tools/web-browsing/Render/PageContent/index.tsx
+++ b/src/tools/web-browsing/Render/PageContent/index.tsx
@@ -12,10 +12,10 @@ import Result from './Result';
interface PagesContentProps {
messageId: string;
results?: CrawlPluginState['results'];
- urls: string[];
+ urls?: string[];
}
-const PagesContent = memo<PagesContentProps>(({ results, messageId, urls }) => {
+const PagesContent = memo<PagesContentProps>(({ results, messageId, urls = [] }) => {
const isMobile = useIsMobile();
if (!results || results.length === 0) {
diff --git a/src/tools/web-browsing/Render/index.tsx b/src/tools/web-browsing/Render/index.tsx
index 5b543e8c30a..4d54a953a48 100644
--- a/src/tools/web-browsing/Render/index.tsx
+++ b/src/tools/web-browsing/Render/index.tsx
@@ -1,11 +1,12 @@
import {
+ BuiltinRenderProps,
CrawlMultiPagesQuery,
CrawlPluginState,
CrawlSinglePageQuery,
SearchContent,
SearchQuery,
UniformSearchResponse,
- BuiltinRenderProps } from '@lobechat/types';
+} from '@lobechat/types';
import { memo } from 'react';
import { WebBrowsingApiName } from '@/tools/web-browsing';
@@ -22,7 +23,7 @@ const WebBrowsing = memo<BuiltinRenderProps<SearchContent[]>>(
<Search
messageId={messageId}
pluginError={pluginError}
- searchQuery={args as SearchQuery}
+ searchQuery={(args as SearchQuery) || {}}
searchResponse={pluginState as UniformSearchResponse}
/>
);
@@ -33,7 +34,7 @@ const WebBrowsing = memo<BuiltinRenderProps<SearchContent[]>>(
<PageContent
messageId={messageId}
results={(pluginState as CrawlPluginState)?.results}
- urls={[(args as CrawlSinglePageQuery).url]}
+ urls={[(args as CrawlSinglePageQuery)?.url]}
/>
);
}
@@ -43,7 +44,7 @@ const WebBrowsing = memo<BuiltinRenderProps<SearchContent[]>>(
<PageContent
messageId={messageId}
results={(pluginState as CrawlPluginState)?.results}
- urls={(args as CrawlMultiPagesQuery).urls}
+ urls={(args as CrawlMultiPagesQuery)?.urls}
/>
);
}