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: remove dalle builtin plugin (#9952)

Arvin Xu2d4d70a66d39
diff --git a/packages/const/src/guide.ts b/packages/const/src/guide.ts
deleted file mode 100644
index f416c5dcc90..00000000000
--- a/packages/const/src/guide.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import urlJoin from 'url-join';
-
-import { BRANDING_EMAIL } from './branding';
-import {
- BLOG,
- DOCKER_IMAGE,
- GITHUB,
- OFFICIAL_PREVIEW_URL,
- OFFICIAL_SITE,
- OFFICIAL_URL,
- SELF_HOSTING_DOCUMENTS,
- USAGE_DOCUMENTS,
- WIKI,
-} from './url';
-
-export const INBOX_GUIDE_SYSTEMROLE = `# Role: LobeChat Support Assistant
-
-## About [LobeHub](${OFFICIAL_SITE})
-
-LobeHub is an organization of design-engineers dedicated to providing advanced design components and tools for AI-generated content (AIGC).
-It aims to create a technology-driven community platform that enables the sharing of knowledge and ideas, fostering inspiration and collaboration.
-
-Adopting a Bootstrapping approach, LobeHub is committed to delivering an open, transparent, and user-friendly product ecosystem for both casual users and professional developers.
-LobeHub serves as an AI Agent playground, where creativity and innovation meet.
-
-## About [LobeChat](${OFFICIAL_URL})
-
-LobeChat, a product of LobeHub, is an open-source ChatGPT/LLMs UI/Framework designed for modern LLMs/AI applications.
-Supports Multi AI Providers( OpenAI / Claude 3 / Gemini / Perplexity / Bedrock / Azure / Mistral / Ollama ), Multi-Modals (Vision/TTS) and plugin system.
-and offers a one-click FREE deployment for a private ChatGPT chat application, making it accessible and customizable for a wide range of users.
-
-### Features
-
-- [Multi-Model Service Provider Support](${urlJoin(USAGE_DOCUMENTS, '/features/multi-ai-providers')})
-- [Local Large Language Model (LLM) Support](${urlJoin(USAGE_DOCUMENTS, '/features/local-llm')})
-- [Model Visual Recognition](${urlJoin(USAGE_DOCUMENTS, '/features/vision')})
-- [TTS & STT Voice Conversation](${urlJoin(USAGE_DOCUMENTS, '/features/tts')})
-- [Text to Image Generation](${urlJoin(USAGE_DOCUMENTS, '/features/text-to-image')})
-- [Plugin System (Function Calling)](${urlJoin(USAGE_DOCUMENTS, '/features/plugin-system')})
-- [Agent Market (GPTs)](${urlJoin(USAGE_DOCUMENTS, '/features/agent-market')})
-
-### Community Edition and Cloud Version
-
-LobeChat is currently available as a community preview version, completely open-source and free of charge.
-
-In the LobeChat Cloud version, we provide 500,000 free computing credits to all registered users. It is ready to use without complex configurations.
-If you require more usage, you can subscribe to the Basic, Advanced, or Professional versions for a fee.
-
-### Self Hosting
-
-LobeChat provides Self-Hosted Version with [Vercel](${urlJoin(SELF_HOSTING_DOCUMENTS, '/platform/vercel')}) and [Docker Image](${DOCKER_IMAGE}).
-This allows you to deploy your own chatbot within a few minutes without any prior knowledge.
-
-**IMPORTANT**
-
-When users ask about usage or deployment, DO NOT MAKE UP ANSWERS. Instead, guide them to the relevant documentation!!!
-
-Learn more about [Build your own LobeChat](${SELF_HOSTING_DOCUMENTS}) by checking it out.
-
-## Resources Links
-
-In the response, please try to pick and include the relevant links below, and if a relevant answer cannot be provided, also offer the user these related links:
-
-- Official Website: ${OFFICIAL_SITE}
-- Cloud Version: ${OFFICIAL_URL}
-- Community Edition: ${OFFICIAL_PREVIEW_URL}
-- GitHub Repository: ${GITHUB}
-- Latest News: ${BLOG}
-- Usage Documentation: ${USAGE_DOCUMENTS}
-- Self-Hosting Documentation: ${SELF_HOSTING_DOCUMENTS}
-- Development Guide: ${WIKI}
-- Email Support: ${BRANDING_EMAIL.support}
-- Business Inquiries: ${BRANDING_EMAIL.business}
-
-## Workflow
-
-1. Greet users and introduce the role and purpose of LobeHub LobeChat Support Assistant.
-2. Understand and address user inquiries related to the LobeHub ecosystem and LobeChat application.
-3. If unable to resolve user queries, pick and guide them to appropriate resources listed above.
-
-## Initialization
-
-As the role <Role>, I will adhere to the following guidelines:
-- Provide accurate and helpful information to users.
-- Maintain a friendly and professional demeanor.
-- Direct users to the appropriate resources when necessary.
-- Keep the language of the response consistent with the language of the user input; if they are not consistent, then translate.
-
-Welcome users to LobeChat, introduce myself as the <Role>, and inform them about the services and support available. Then, guide users through the <Workflow> for assistance.`;
diff --git a/packages/const/src/index.ts b/packages/const/src/index.ts
index 6d1c9fc0486..462ac22ffbc 100644
--- a/packages/const/src/index.ts
+++ b/packages/const/src/index.ts
@@ -3,7 +3,6 @@ export * from './branding';
export * from './currency';
export * from './desktop';
export * from './discover';
-export * from './guide';
export * from './layoutTokens';
export * from './message';
export * from './meta';
diff --git a/packages/const/src/url.ts b/packages/const/src/url.ts
index 20049adc31f..b22c981ee1c 100644
--- a/packages/const/src/url.ts
+++ b/packages/const/src/url.ts
@@ -8,26 +8,23 @@ const isDev = process.env.NODE_ENV === 'development';
export const UTM_SOURCE = 'chat_preview';
export const OFFICIAL_URL = 'https://lobechat.com';
-export const OFFICIAL_PREVIEW_URL = 'https://chat-preview.lobehub.com';
export const OFFICIAL_SITE = 'https://lobehub.com';
+export const OFFICIAL_DOMAIN = 'lobehub.com';
export const OG_URL = '/og/cover.png?v=1';
export const GITHUB = 'https://github.com/lobehub/lobe-chat';
export const GITHUB_ISSUES = urlJoin(GITHUB, 'issues/new/choose');
export const CHANGELOG = 'https://lobehub.com/changelog';
-export const DOCKER_IMAGE = 'https://hub.docker.com/r/lobehub/lobe-chat';
export const DOCUMENTS = urlJoin(OFFICIAL_SITE, '/docs');
export const USAGE_DOCUMENTS = urlJoin(DOCUMENTS, '/usage');
export const SELF_HOSTING_DOCUMENTS = urlJoin(DOCUMENTS, '/self-hosting');
-export const WEBRTC_SYNC_DOCUMENTS = urlJoin(SELF_HOSTING_DOCUMENTS, '/advanced/webrtc');
export const DATABASE_SELF_HOSTING_URL = urlJoin(SELF_HOSTING_DOCUMENTS, '/server-database');
// use this for the link
export const DOCUMENTS_REFER_URL = `${DOCUMENTS}?utm_source=${UTM_SOURCE}`;
-export const WIKI = urlJoin(GITHUB, 'wiki');
export const WIKI_PLUGIN_GUIDE = urlJoin(USAGE_DOCUMENTS, '/plugins/development');
export const MANUAL_UPGRADE_URL = urlJoin(SELF_HOSTING_DOCUMENTS, '/advanced/upstream-sync');
diff --git a/packages/context-engine/src/index.ts b/packages/context-engine/src/index.ts
index 366d637b4f2..cf4fd5e87c7 100644
--- a/packages/context-engine/src/index.ts
+++ b/packages/context-engine/src/index.ts
@@ -10,12 +10,7 @@ export type { ContextEngineConfig } from './pipeline';
export { ContextEngine } from './pipeline';
// Context Providers
-export {
- HistorySummaryProvider,
- InboxGuideProvider,
- SystemRoleInjector,
- ToolSystemRoleProvider,
-} from './providers';
+export { HistorySummaryProvider, SystemRoleInjector, ToolSystemRoleProvider } from './providers';
// Processors
export {
diff --git a/packages/context-engine/src/processors/GroupMessageFlatten.ts b/packages/context-engine/src/processors/GroupMessageFlatten.ts
index ae39d6e6e46..c582be0c2df 100644
--- a/packages/context-engine/src/processors/GroupMessageFlatten.ts
+++ b/packages/context-engine/src/processors/GroupMessageFlatten.ts
@@ -67,8 +67,18 @@ export class GroupMessageFlattenProcessor extends BaseProcessor {
}
// Add reasoning if present (for models that support reasoning)
- if (message.reasoning) {
- assistantMsg.reasoning = message.reasoning;
+ if (child.reasoning) {
+ assistantMsg.reasoning = child.reasoning;
+ }
+
+ // Add error if present
+ if (child.error) {
+ assistantMsg.error = child.error;
+ }
+
+ // Add imageList if present
+ if (child.imageList && child.imageList.length > 0) {
+ assistantMsg.imageList = child.imageList;
}
// Preserve other fields that might be needed
diff --git a/packages/context-engine/src/processors/__tests__/GroupMessageFlatten.test.ts b/packages/context-engine/src/processors/__tests__/GroupMessageFlatten.test.ts
index eb3ad243cf5..50151020253 100644
--- a/packages/context-engine/src/processors/__tests__/GroupMessageFlatten.test.ts
+++ b/packages/context-engine/src/processors/__tests__/GroupMessageFlatten.test.ts
@@ -340,7 +340,7 @@ describe('GroupMessageFlattenProcessor', () => {
expect(result.messages[0].id).toBe('msg-group-1');
});
- it('should preserve reasoning field from group message', async () => {
+ it('should preserve reasoning field from child block', async () => {
const processor = new GroupMessageFlattenProcessor();
const input: any[] = [
@@ -348,14 +348,14 @@ describe('GroupMessageFlattenProcessor', () => {
id: 'msg-group-1',
role: 'group',
content: '',
- reasoning: {
- content: 'Thinking about the query...',
- signature: 'sig-123',
- },
children: [
{
id: 'msg-1',
content: 'Result',
+ reasoning: {
+ content: 'Thinking about the query...',
+ signature: 'sig-123',
+ },
tools: [],
},
],
@@ -372,6 +372,70 @@ describe('GroupMessageFlattenProcessor', () => {
});
});
+ it('should preserve error field from child block', async () => {
+ const processor = new GroupMessageFlattenProcessor();
+
+ const input: any[] = [
+ {
+ id: 'msg-group-1',
+ role: 'group',
+ content: '',
+ children: [
+ {
+ id: 'msg-1',
+ content: 'Error occurred',
+ error: {
+ type: 'InvalidAPIKey',
+ message: 'API key is invalid',
+ },
+ tools: [],
+ },
+ ],
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].error).toEqual({
+ type: 'InvalidAPIKey',
+ message: 'API key is invalid',
+ });
+ });
+
+ it('should preserve imageList field from child block', async () => {
+ const processor = new GroupMessageFlattenProcessor();
+
+ const input: any[] = [
+ {
+ id: 'msg-group-1',
+ role: 'group',
+ content: '',
+ children: [
+ {
+ id: 'msg-1',
+ content: 'Here are the images',
+ imageList: [
+ { id: 'img-1', url: 'https://example.com/img1.jpg', alt: 'Image 1' },
+ { id: 'img-2', url: 'https://example.com/img2.jpg', alt: 'Image 2' },
+ ],
+ tools: [],
+ },
+ ],
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].imageList).toEqual([
+ { id: 'img-1', url: 'https://example.com/img1.jpg', alt: 'Image 1' },
+ { id: 'img-2', url: 'https://example.com/img2.jpg', alt: 'Image 2' },
+ ]);
+ });
+
it('should preserve parent/thread/group/topic IDs', async () => {
const processor = new GroupMessageFlattenProcessor();
@@ -435,10 +499,6 @@ describe('GroupMessageFlattenProcessor', () => {
id: 'msg_LnIlOyMUnX1ylf',
role: 'group',
content: '',
- reasoning: {
- content:
- '**Checking Hangzhou weather**\n\nIt seems the user is asking to check the weather in Hangzhou...',
- },
createdAt: '2025-10-27T10:47:59.475Z',
updatedAt: '2025-10-27T10:48:10.768Z',
topicId: 'tpc_WQ1wRvxdDpLw',
@@ -451,6 +511,10 @@ describe('GroupMessageFlattenProcessor', () => {
{
content: '',
id: 'msg_LnIlOyMUnX1ylf',
+ reasoning: {
+ content:
+ '**Checking Hangzhou weather**\n\nIt seems the user is asking to check the weather in Hangzhou...',
+ },
performance: {
tps: 29.336734693877553,
ttft: 3844,
diff --git a/packages/context-engine/src/providers/InboxGuide.ts b/packages/context-engine/src/providers/InboxGuide.ts
deleted file mode 100644
index bccc25c33fe..00000000000
--- a/packages/context-engine/src/providers/InboxGuide.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import debug from 'debug';
-
-import { BaseProvider } from '../base/BaseProvider';
-import type { PipelineContext, ProcessorOptions } from '../types';
-
-const log = debug('context-engine:provider:InboxGuideProvider');
-
-/**
- * Inbox Guide System Role Configuration
- */
-export interface InboxGuideConfig {
- /** Inbox guide system role content */
- inboxGuideSystemRole: string;
- /** Inbox session ID constant */
- inboxSessionId: string;
- /** Whether it's a welcome question */
- isWelcomeQuestion?: boolean;
- /** Session ID */
- sessionId?: string;
-}
-
-/**
- * Inbox Guide Provider
- * Responsible for injecting guide system role for welcome questions in inbox sessions
- */
-export class InboxGuideProvider extends BaseProvider {
- readonly name = 'InboxGuideProvider';
-
- constructor(
- private config: InboxGuideConfig,
- options: ProcessorOptions = {},
- ) {
- super(options);
- }
-
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
- const clonedContext = this.cloneContext(context);
-
- // 检查是否需要注入收件箱引导
- const shouldInject = this.shouldInjectInboxGuide();
-
- if (!shouldInject) {
- log('Inbox guide injection conditions not met, skipping processing');
- return this.markAsExecuted(clonedContext);
- }
-
- // 注入收件箱引导系统角色
- this.injectInboxGuideSystemRole(clonedContext);
-
- // 更新元数据
- clonedContext.metadata.inboxGuide = {
- contentLength: this.config.inboxGuideSystemRole.length,
- injected: true,
- isWelcomeQuestion: this.config.isWelcomeQuestion,
- sessionId: this.config.sessionId,
- };
-
- log('Inbox guide system role injection completed');
- return this.markAsExecuted(clonedContext);
- }
-
- /**
- * Check if inbox guide should be injected
- */
- private shouldInjectInboxGuide(): boolean {
- return (
- (this.config.isWelcomeQuestion &&
- this.config.sessionId === this.config.inboxSessionId &&
- !!this.config.inboxGuideSystemRole) ||
- false
- );
- }
-
- /**
- * Inject inbox guide system role
- */
- private injectInboxGuideSystemRole(context: PipelineContext): void {
- const existingSystemMessage = context.messages.find((msg) => msg.role === 'system');
-
- if (existingSystemMessage) {
- // 合并到现有系统消息
- existingSystemMessage.content = [
- existingSystemMessage.content,
- this.config.inboxGuideSystemRole,
- ]
- .filter(Boolean)
- .join('\n\n');
-
- log(
- `Inbox guide merged to existing system message, final length: ${existingSystemMessage.content.length}`,
- );
- } else {
- context.messages.unshift({
- content: this.config.inboxGuideSystemRole,
- role: 'system' as const,
- } as any);
- log(
- `New inbox guide system message created, content length: ${this.config.inboxGuideSystemRole.length}`,
- );
- }
- }
-}
diff --git a/packages/context-engine/src/providers/__tests__/InboxGuideProvider.test.ts b/packages/context-engine/src/providers/__tests__/InboxGuideProvider.test.ts
deleted file mode 100644
index 45c23ecfed3..00000000000
--- a/packages/context-engine/src/providers/__tests__/InboxGuideProvider.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import type { PipelineContext } from '../../types';
-import { InboxGuideProvider } from '../InboxGuide';
-
-const createContext = (messages: any[]): PipelineContext => ({
- initialState: { messages: [] } as any,
- messages,
- metadata: { model: 'gpt-4', maxTokens: 4096 },
- isAborted: false,
-});
-
-describe('InboxGuideProvider', () => {
- const mockInboxGuideContent = '# Role: LobeChat Support Assistant\n\nWelcome to LobeChat!';
- const INBOX_SESSION_ID = 'inbox';
-
- it('should inject inbox guide for welcome questions in inbox session', async () => {
- const provider = new InboxGuideProvider({
- isWelcomeQuestion: true,
- sessionId: INBOX_SESSION_ID,
- inboxSessionId: INBOX_SESSION_ID,
- inboxGuideSystemRole: mockInboxGuideContent,
- });
-
- const messages = [{ id: 'u1', role: 'user', content: 'Hello, this is my first question' }];
-
- const ctx = createContext(messages);
- const result = await provider.process(ctx);
-
- // Should have system message with inbox guide content
- const systemMessage = result.messages.find((msg) => msg.role === 'system');
- expect(systemMessage).toBeDefined();
- expect(systemMessage!.content).toBe(mockInboxGuideContent);
-
- // Should update metadata
- expect(result.metadata.inboxGuide).toEqual({
- injected: true,
- sessionId: INBOX_SESSION_ID,
- isWelcomeQuestion: true,
- contentLength: mockInboxGuideContent.length,
- });
- });
-
- it('should merge inbox guide with existing system message', async () => {
- const provider = new InboxGuideProvider({
- isWelcomeQuestion: true,
- sessionId: INBOX_SESSION_ID,
- inboxSessionId: INBOX_SESSION_ID,
- inboxGuideSystemRole: mockInboxGuideContent,
- });
-
- const existingSystemContent = 'Existing system message';
- const messages = [
- { id: 's1', role: 'system', content: existingSystemContent },
- { id: 'u1', role: 'user', content: 'Hello' },
- ];
-
- const ctx = createContext(messages);
- const result = await provider.process(ctx);
-
- const systemMessage = result.messages.find((msg) => msg.role === 'system');
- expect(systemMessage!.content).toBe(`${existingSystemContent}\n\n${mockInboxGuideContent}`);
- });
-
- it('should skip injection when not welcome question', async () => {
- const provider = new InboxGuideProvider({
- isWelcomeQuestion: false,
- sessionId: INBOX_SESSION_ID,
- inboxSessionId: INBOX_SESSION_ID,
- inboxGuideSystemRole: mockInboxGuideContent,
- });
-
- const messages = [{ id: 'u1', role: 'user', content: 'Regular question' }];
-
- const ctx = createContext(messages);
- const result = await provider.process(ctx);
-
- // Should not have system message
- const systemMessage = result.messages.find((msg) => msg.role === 'system');
- expect(systemMessage).toBeUndefined();
-
- // Should not have metadata
- expect(result.metadata.inboxGuide).toBeUndefined();
- });
-
- it('should skip injection when not in inbox session', async () => {
- const provider = new InboxGuideProvider({
- isWelcomeQuestion: true,
- sessionId: 'other-session',
- inboxSessionId: INBOX_SESSION_ID,
- inboxGuideSystemRole: mockInboxGuideContent,
- });
-
- const messages = [{ id: 'u1', role: 'user', content: 'Hello' }];
-
- const ctx = createContext(messages);
- const result = await provider.process(ctx);
-
- // Should not have system message
- const systemMessage = result.messages.find((msg) => msg.role === 'system');
- expect(systemMessage).toBeUndefined();
- });
-
- it('should skip injection when no inbox guide content', async () => {
- const provider = new InboxGuideProvider({
- isWelcomeQuestion: true,
- sessionId: INBOX_SESSION_ID,
- inboxSessionId: INBOX_SESSION_ID,
- inboxGuideSystemRole: '',
- });
-
- const messages = [{ id: 'u1', role: 'user', content: 'Hello' }];
-
- const ctx = createContext(messages);
- const result = await provider.process(ctx);
-
- // Should not have system message
- const systemMessage = result.messages.find((msg) => msg.role === 'system');
- expect(systemMessage).toBeUndefined();
- });
-});
diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.ts
index b0d6e60e365..bd221334324 100644
--- a/packages/context-engine/src/providers/index.ts
+++ b/packages/context-engine/src/providers/index.ts
@@ -1,11 +1,9 @@
// Context Provider exports
export { HistorySummaryProvider } from './HistorySummary';
-export { InboxGuideProvider } from './InboxGuide';
export { SystemRoleInjector } from './SystemRoleInjector';
export { ToolSystemRoleProvider } from './ToolSystemRole';
// Re-export types
export type { HistorySummaryConfig } from './HistorySummary';
-export type { InboxGuideConfig } from './InboxGuide';
export type { SystemRoleInjectorConfig } from './SystemRoleInjector';
export type { ToolSystemRoleConfig } from './ToolSystemRole';
diff --git a/packages/database/package.json b/packages/database/package.json
index 5cb4d0d17a6..60e51720530 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -9,7 +9,7 @@
},
"scripts": {
"test": "npm run test:client-db && npm run test:server-db",
- "test:client-db": "vitest run",
+ "test:client-db": "vitest run --silent='passed-only'",
"test:coverage": "vitest --coverage --silent='passed-only' --config vitest.config.server.mts",
"test:server-db": "vitest run --config vitest.config.server.mts"
},
diff --git a/packages/database/src/models/__tests__/message.grouping.test.ts b/packages/database/src/models/__tests__/message.grouping.test.ts
new file mode 100644
index 00000000000..480ada23657
--- /dev/null
+++ b/packages/database/src/models/__tests__/message.grouping.test.ts
@@ -0,0 +1,812 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../models/__tests__/_util';
+import { files, messagePlugins, messages, messagesFiles, sessions, users } from '../../schemas';
+import { LobeChatDatabase } from '../../type';
+import { MessageModel } from '../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'message-grouping-test';
+const messageModel = new MessageModel(serverDB, userId);
+
+beforeEach(async () => {
+ // Clear tables before each test
+ await serverDB.transaction(async (trx) => {
+ await trx.delete(users);
+ await trx.insert(users).values([{ id: userId }, { id: '456' }]);
+ await trx.insert(sessions).values([{ id: '1', userId }]);
+ await trx.insert(files).values({
+ id: 'f1',
+ userId: userId,
+ name: 'test.png',
+ fileType: 'image/png',
+ size: 100,
+ url: 'url1',
+ });
+ });
+});
+
+afterEach(async () => {
+ // Clean up after each test
+ await serverDB.delete(messages);
+ await serverDB.delete(messagePlugins);
+ await serverDB.delete(messagesFiles);
+});
+
+describe('MessageModel - Message Grouping', () => {
+ describe('Basic Grouping Scenarios', () => {
+ it('should group assistant message with single tool result', async () => {
+ // Create assistant message with tool
+ await serverDB.insert(messages).values({
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Checking weather',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{"city":"Beijing"}',
+ type: 'default',
+ },
+ ],
+ });
+
+ // Create tool message
+ await serverDB.insert(messages).values({
+ id: 'msg-2',
+ userId,
+ role: 'tool',
+ content: 'Beijing: Sunny, 25°C',
+ });
+
+ await serverDB.insert(messagePlugins).values({
+ id: 'msg-2',
+ userId,
+ toolCallId: 'tool-1',
+ identifier: 'weather',
+ state: { cached: true },
+ });
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify grouping
+ 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',
+ });
+ expect(block.tools![0].result).toMatchObject({
+ content: 'Beijing: Sunny, 25°C',
+ state: { cached: true },
+ });
+ });
+
+ it('should group assistant message with multiple tool results', async () => {
+ // Create assistant message with multiple tools
+ await serverDB.insert(messages).values({
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Checking weather and news',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{}',
+ type: 'default',
+ },
+ {
+ id: 'tool-2',
+ identifier: 'news',
+ apiName: 'getNews',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ });
+
+ // Create tool messages
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-2',
+ userId,
+ role: 'tool',
+ content: 'Beijing: Sunny, 25°C',
+ },
+ {
+ id: 'msg-3',
+ userId,
+ role: 'tool',
+ content: 'Latest tech news: AI breakthrough',
+ },
+ ]);
+
+ await serverDB.insert(messagePlugins).values([
+ {
+ id: 'msg-2',
+ userId,
+ toolCallId: 'tool-1',
+ identifier: 'weather',
+ },
+ {
+ id: 'msg-3',
+ userId,
+ toolCallId: 'tool-2',
+ identifier: 'news',
+ },
+ ]);
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify grouping
+ 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 not group assistant message without tools', async () => {
+ // Create assistant message without tools
+ await serverDB.insert(messages).values({
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Hello!',
+ });
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify no grouping
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('assistant');
+ expect(result[0].content).toBe('Hello!');
+ expect(result[0].children).toBeUndefined();
+ });
+
+ it('should handle assistant message with tool but no result yet', async () => {
+ // Create assistant message with tool
+ await serverDB.insert(messages).values({
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Checking weather',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ });
+
+ // No tool message created yet
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify grouping without result
+ 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 Grouping', () => {
+ it('should group assistant with follow-up assistant (parentId→tool)', async () => {
+ // Scenario: assistant → tool → assistant (parentId → tool)
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Let me check the weather',
+ createdAt: new Date('2023-01-01T10:00:00Z'),
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ {
+ id: 'msg-2',
+ userId,
+ role: 'tool',
+ content: 'Sunny, 25°C',
+ createdAt: new Date('2023-01-01T10:00:01Z'),
+ },
+ {
+ id: 'msg-3',
+ userId,
+ role: 'assistant',
+ content: 'Based on the weather, let me check the news',
+ parentId: 'msg-2',
+ createdAt: new Date('2023-01-01T10:00:02Z'),
+ tools: [
+ {
+ id: 'tool-2',
+ identifier: 'news',
+ apiName: 'getNews',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ {
+ id: 'msg-4',
+ userId,
+ role: 'tool',
+ content: 'Breaking: AI news',
+ createdAt: new Date('2023-01-01T10:00:03Z'),
+ },
+ ]);
+
+ await serverDB.insert(messagePlugins).values([
+ {
+ id: 'msg-2',
+ userId,
+ toolCallId: 'tool-1',
+ identifier: 'weather',
+ },
+ {
+ id: 'msg-4',
+ userId,
+ toolCallId: 'tool-2',
+ identifier: 'news',
+ },
+ ]);
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // 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].content).toBe('Let me check the weather');
+ expect(result[0].children![0].tools).toHaveLength(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].content).toBe('Based on the weather, let me check the news');
+ expect(result[0].children![1].tools).toHaveLength(1);
+ expect(result[0].children![1].tools![0].result?.content).toBe('Breaking: AI news');
+ });
+
+ it('should group multiple follow-up assistants in chain (3+ assistants)', async () => {
+ // Scenario: assistant → tool → assistant → tool → assistant (chain of parentId→tool)
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Step 1: Check weather',
+ createdAt: new Date('2023-01-01T10:00:00Z'),
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ {
+ id: 'msg-2',
+ userId,
+ role: 'tool',
+ content: 'Sunny, 25°C',
+ createdAt: new Date('2023-01-01T10:00:01Z'),
+ },
+ {
+ id: 'msg-3',
+ userId,
+ role: 'assistant',
+ content: 'Step 2: Based on weather, check news',
+ parentId: 'msg-2',
+ createdAt: new Date('2023-01-01T10:00:02Z'),
+ tools: [
+ {
+ id: 'tool-2',
+ identifier: 'news',
+ apiName: 'getNews',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ {
+ id: 'msg-4',
+ userId,
+ role: 'tool',
+ content: 'Breaking: AI news',
+ createdAt: new Date('2023-01-01T10:00:03Z'),
+ },
+ {
+ id: 'msg-5',
+ userId,
+ role: 'assistant',
+ content: 'Step 3: Final summary based on weather and news',
+ parentId: 'msg-4',
+ createdAt: new Date('2023-01-01T10:00:04Z'),
+ },
+ ]);
+
+ await serverDB.insert(messagePlugins).values([
+ {
+ id: 'msg-2',
+ userId,
+ toolCallId: 'tool-1',
+ identifier: 'weather',
+ },
+ {
+ id: 'msg-4',
+ userId,
+ toolCallId: 'tool-2',
+ identifier: 'news',
+ },
+ ]);
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Should have 1 group with 3 children
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('group');
+ expect(result[0].children).toHaveLength(3);
+
+ // First child: original assistant with tool result
+ expect(result[0].children![0].id).toBe('msg-1');
+ expect(result[0].children![0].content).toBe('Step 1: Check weather');
+ 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].content).toBe('Step 2: Based on weather, check news');
+ expect(result[0].children![1].tools![0].result?.content).toBe('Breaking: AI news');
+
+ // Third child: final assistant (parentId pointed to second tool)
+ expect(result[0].children![2].id).toBe('msg-5');
+ expect(result[0].children![2].content).toBe(
+ 'Step 3: Final summary based on weather and news',
+ );
+ });
+
+ it('should group messages in multi-turn conversation', async () => {
+ // Create multi-turn conversation
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-1',
+ userId,
+ role: 'user',
+ content: 'What is the weather?',
+ createdAt: new Date('2023-01-01T10:00:00Z'),
+ },
+ {
+ id: 'msg-2',
+ userId,
+ role: 'assistant',
+ content: 'Checking weather',
+ createdAt: new Date('2023-01-01T10:00:01Z'),
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'weather',
+ apiName: 'getWeather',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ {
+ id: 'msg-3',
+ userId,
+ role: 'tool',
+ content: 'Sunny, 25°C',
+ createdAt: new Date('2023-01-01T10:00:02Z'),
+ },
+ {
+ id: 'msg-4',
+ userId,
+ role: 'user',
+ content: 'What about news?',
+ createdAt: new Date('2023-01-01T10:00:03Z'),
+ },
+ {
+ id: 'msg-5',
+ userId,
+ role: 'assistant',
+ content: 'Checking news',
+ createdAt: new Date('2023-01-01T10:00:04Z'),
+ tools: [
+ {
+ id: 'tool-2',
+ identifier: 'news',
+ apiName: 'getNews',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ {
+ id: 'msg-6',
+ userId,
+ role: 'tool',
+ content: 'AI breakthrough',
+ createdAt: new Date('2023-01-01T10:00:05Z'),
+ },
+ ]);
+
+ await serverDB.insert(messagePlugins).values([
+ {
+ id: 'msg-3',
+ userId,
+ toolCallId: 'tool-1',
+ identifier: 'weather',
+ },
+ {
+ id: 'msg-6',
+ userId,
+ toolCallId: 'tool-2',
+ identifier: 'news',
+ },
+ ]);
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify grouping
+ 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', async () => {
+ // Create mixed messages
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Hello!',
+ createdAt: new Date('2023-01-01T10:00:00Z'),
+ },
+ {
+ id: 'msg-2',
+ userId,
+ role: 'assistant',
+ content: 'Using tools',
+ createdAt: new Date('2023-01-01T10:00:01Z'),
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ {
+ id: 'msg-3',
+ userId,
+ role: 'tool',
+ content: 'Result',
+ createdAt: new Date('2023-01-01T10:00:02Z'),
+ },
+ ]);
+
+ await serverDB.insert(messagePlugins).values({
+ id: 'msg-3',
+ userId,
+ toolCallId: 'tool-1',
+ identifier: 'test',
+ });
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify grouping
+ 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 handle tool messages with errors', async () => {
+ // Create assistant with tool
+ await serverDB.insert(messages).values({
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Checking',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ });
+
+ // Create tool message with error
+ await serverDB.insert(messages).values({
+ id: 'msg-2',
+ userId,
+ role: 'tool',
+ content: '',
+ });
+
+ await serverDB.insert(messagePlugins).values({
+ id: 'msg-2',
+ userId,
+ toolCallId: 'tool-1',
+ identifier: 'test',
+ error: { message: 'Failed to execute' },
+ });
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify error is preserved
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('group');
+ expect(result[0].children![0].tools![0].result?.error).toEqual({
+ message: 'Failed to execute',
+ });
+ });
+
+ it('should preserve message order', async () => {
+ // Create messages in specific order
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-1',
+ userId,
+ role: 'user',
+ content: 'First',
+ createdAt: new Date('2023-01-01T10:00:00Z'),
+ },
+ {
+ id: 'msg-2',
+ userId,
+ role: 'assistant',
+ content: 'Second',
+ createdAt: new Date('2023-01-01T10:00:01Z'),
+ },
+ {
+ id: 'msg-3',
+ userId,
+ role: 'user',
+ content: 'Third',
+ createdAt: new Date('2023-01-01T10:00:02Z'),
+ },
+ ]);
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify order
+ expect(result).toHaveLength(3);
+ expect(result[0].content).toBe('First');
+ expect(result[1].content).toBe('Second');
+ expect(result[2].content).toBe('Third');
+ });
+
+ it('should handle orphaned tool messages', async () => {
+ // Create orphaned tool message
+ await serverDB.insert(messages).values({
+ id: 'msg-1',
+ userId,
+ role: 'tool',
+ content: 'Orphaned result',
+ });
+
+ await serverDB.insert(messagePlugins).values({
+ id: 'msg-1',
+ userId,
+ toolCallId: 'unknown-tool',
+ identifier: 'test',
+ });
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify orphaned tool is not filtered
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('tool');
+ });
+ });
+
+ describe('Children Structure Validation', () => {
+ it('should use message ID as block ID', async () => {
+ // Create assistant with tool
+ await serverDB.insert(messages).values({
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Test',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ });
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify block ID uses message ID
+ expect(result[0].children![0].id).toBe('msg-1');
+ });
+
+ it('should convert empty imageList/fileList to undefined in children', async () => {
+ // Create assistant with tools but empty imageList/fileList
+ await serverDB.insert(messages).values({
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Test',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ });
+
+ // Query messages (no files attached, so imageList/fileList will be empty)
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify empty arrays become undefined
+ expect(result[0].children![0].imageList).toBeUndefined();
+ });
+
+ it('should move tools/imageList/fileList to children', async () => {
+ // Create files
+ await serverDB.insert(files).values([
+ {
+ id: 'img-1',
+ userId,
+ name: 'test.png',
+ fileType: 'image/png',
+ size: 1024,
+ url: 'http://example.com/img.png',
+ },
+ {
+ id: 'file-1',
+ userId,
+ name: 'test.pdf',
+ fileType: 'application/pdf',
+ size: 2048,
+ url: 'http://example.com/file.pdf',
+ },
+ ]);
+
+ // Create assistant with tools and files
+ await serverDB.insert(messages).values({
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Test',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ });
+
+ await serverDB.insert(messagesFiles).values([
+ { messageId: 'msg-1', fileId: 'img-1', userId },
+ { messageId: 'msg-1', fileId: 'file-1', userId },
+ ]);
+
+ // Query messages
+ const result = await messageModel.query(
+ { sessionId: null },
+ { groupAssistantMessages: true },
+ );
+
+ // Verify parent fields are cleared
+ expect(result[0].tools).toBeUndefined();
+ expect(result[0].imageList).toBeUndefined();
+ expect(result[0].fileList).toBeUndefined();
+ expect(result[0].content).toBe('');
+
+ // Verify children have the data
+ const block = result[0].children![0];
+ expect(block.content).toBe('Test');
+ expect(block.tools).toHaveLength(1);
+ expect(block.imageList).toHaveLength(1);
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/message.test.ts b/packages/database/src/models/__tests__/message.test.ts
index bccfd00d77d..dabce45d29f 100644
--- a/packages/database/src/models/__tests__/message.test.ts
+++ b/packages/database/src/models/__tests__/message.test.ts
@@ -35,7 +35,7 @@ const messageModel = new MessageModel(serverDB, userId);
const embeddingsId = uuid();
beforeEach(async () => {
- // 在每个测试用例之前,清空表
+ // Clear tables before each test case
await serverDB.transaction(async (trx) => {
await trx.delete(users);
await trx.insert(users).values([{ id: userId }, { id: '456' }]);
@@ -63,14 +63,14 @@ beforeEach(async () => {
});
afterEach(async () => {
- // 在每个测试用例之后,清空表
+ // Clear tables after each test case
await serverDB.delete(users);
});
describe('MessageModel', () => {
describe('query', () => {
it('should query messages by user ID', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1', createdAt: new Date('2023-01-01') },
{ id: '2', userId, role: 'user', content: 'message 2', createdAt: new Date('2023-02-01') },
@@ -83,39 +83,39 @@ describe('MessageModel', () => {
},
]);
- // 调用 query 方法
+ // Call query method
const result = await messageModel.query();
- // 断言结果
+ // Assert result
expect(result).toHaveLength(2);
expect(result[0].id).toBe('1');
expect(result[1].id).toBe('2');
});
it('should return empty messages if not match the user ID', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId: '456', role: 'user', content: '1', createdAt: new Date('2023-01-01') },
{ id: '2', userId: '456', role: 'user', content: '2', createdAt: new Date('2023-02-01') },
{ id: '3', userId: '456', role: 'user', content: '3', createdAt: new Date('2023-03-01') },
]);
- // 调用 query 方法
+ // Call query method
const result = await messageModel.query();
- // 断言结果
+ // Assert result
expect(result).toHaveLength(0);
});
it('should query messages with pagination', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1', createdAt: new Date('2023-01-01') },
{ id: '2', userId, role: 'user', content: 'message 2', createdAt: new Date('2023-02-01') },
{ id: '3', userId, role: 'user', content: 'message 3', createdAt: new Date('2023-03-01') },
]);
- // 测试分页
+ // Test pagination
const result1 = await messageModel.query({ current: 0, pageSize: 2 });
expect(result1).toHaveLength(2);
@@ -125,7 +125,7 @@ describe('MessageModel', () => {
});
it('should filter messages by sessionId', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(sessions).values([
{ id: 'session1', userId },
{ id: 'session2', userId },
@@ -150,7 +150,7 @@ describe('MessageModel', () => {
{ id: '3', userId, role: 'user', sessionId: 'session2', content: 'message 3' },
]);
- // 测试根据 sessionId 过滤
+ // Test filtering by sessionId
const result = await messageModel.query({ sessionId: 'session1' });
expect(result).toHaveLength(2);
expect(result[0].id).toBe('1');
@@ -158,7 +158,7 @@ describe('MessageModel', () => {
});
it('should filter messages by topicId', async () => {
- // 创建测试数据
+ // Create test data
const sessionId = 'session1';
await serverDB.insert(sessions).values([{ id: sessionId, userId }]);
const topicId = 'topic1';
@@ -173,7 +173,7 @@ describe('MessageModel', () => {
{ id: '3', userId, role: 'user', topicId: 'topic2', content: 'message 3' },
]);
- // 测试根据 topicId 过滤
+ // Test filtering by topicId
const result = await messageModel.query({ topicId });
expect(result).toHaveLength(2);
expect(result[0].id).toBe('1');
@@ -226,7 +226,7 @@ describe('MessageModel', () => {
});
it('should query messages with join', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.transaction(async (trx) => {
await trx.insert(messages).values([
{
@@ -268,13 +268,13 @@ describe('MessageModel', () => {
});
const domain = 'http://abc.com';
- // 调用 query 方法
+ // Call query method
const result = await messageModel.query(
{},
{ postProcessUrl: async (path) => `${domain}/${path}` },
);
- // 断言结果
+ // Assert result
expect(result).toHaveLength(2);
expect(result[0].id).toBe('1');
expect(result[0].imageList).toEqual([
@@ -287,7 +287,7 @@ describe('MessageModel', () => {
});
it('should include translate, tts and other extra fields in query result', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.transaction(async (trx) => {
await trx.insert(messages).values([
{
@@ -306,10 +306,10 @@ describe('MessageModel', () => {
.values([{ id: '1', voice: 'voice1', fileId: 'f1', contentMd5: 'md5', userId }]);
});
- // 调用 query 方法
+ // Call query method
const result = await messageModel.query();
- // 断言结果
+ // Assert result
expect(result[0].extra!.translate).toEqual({ content: 'translated', from: 'en', to: 'zh' });
expect(result[0].extra!.tts).toEqual({
contentMd5: 'md5',
@@ -319,7 +319,7 @@ describe('MessageModel', () => {
});
it('should handle edge cases of pagination parameters', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1' },
{ id: '2', userId, role: 'user', content: 'message 2' },
@@ -339,7 +339,7 @@ describe('MessageModel', () => {
describe('query with messageQueries', () => {
it('should include ragQuery, ragQueryId and ragRawQuery in query results', async () => {
- // 创建测试数据
+ // Create test data
const messageId = 'msg-with-query';
const queryId = uuid();
@@ -358,10 +358,10 @@ describe('MessageModel', () => {
userId,
});
- // 调用 query 方法
+ // Call query method
const result = await messageModel.query();
- // 断言结果
+ // Assert result
expect(result).toHaveLength(1);
expect(result[0].id).toBe(messageId);
expect(result[0].ragQueryId).toBe(queryId);
@@ -370,7 +370,7 @@ describe('MessageModel', () => {
});
it.skip('should handle multiple message queries for the same message', async () => {
- // 创建测试数据
+ // Create test data
const messageId = 'msg-multi-query';
const queryId1 = uuid();
const queryId2 = uuid();
@@ -400,10 +400,10 @@ describe('MessageModel', () => {
},
]);
- // 调用 query 方法
+ // Call query method
const result = await messageModel.query();
- // 断言结果 - 应该只包含最新的查询
+ // Assert result - 应该只包含最新的查询
expect(result).toHaveLength(1);
expect(result[0].id).toBe(messageId);
expect(result[0].ragQueryId).toBe(queryId2);
@@ -505,7 +505,7 @@ describe('MessageModel', () => {
describe('queryAll', () => {
it('should return all messages belonging to the user in ascending order', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{
id: '1',
@@ -530,10 +530,10 @@ describe('MessageModel', () => {
},
]);
- // 调用 queryAll 方法
+ // Call queryAll method
const result = await messageModel.queryAll();
- // 断言结果
+ // Assert result
expect(result).toHaveLength(2);
expect(result[0].id).toBe('1');
expect(result[1].id).toBe('2');
@@ -542,37 +542,37 @@ describe('MessageModel', () => {
describe('findById', () => {
it('should find message by ID', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1' },
{ id: '2', userId: '456', role: 'user', content: 'message 2' },
]);
- // 调用 findById 方法
+ // Call findById method
const result = await messageModel.findById('1');
- // 断言结果
+ // Assert result
expect(result?.id).toBe('1');
expect(result?.content).toBe('message 1');
});
it('should return undefined if message does not belong to user', async () => {
- // 创建测试数据
+ // Create test data
await serverDB
.insert(messages)
.values([{ id: '1', userId: '456', role: 'user', content: 'message 1' }]);
- // 调用 findById 方法
+ // Call findById method
const result = await messageModel.findById('1');
- // 断言结果
+ // Assert result
expect(result).toBeUndefined();
});
});
describe('queryBySessionId', () => {
it('should query messages by sessionId', async () => {
- // 创建测试数据
+ // Create test data
const sessionId = 'session1';
await serverDB.insert(sessions).values([
{ id: 'session1', userId },
@@ -598,10 +598,10 @@ describe('MessageModel', () => {
{ id: '3', userId, role: 'user', sessionId: 'session2', content: 'message 3' },
]);
- // 调用 queryBySessionId 方法
+ // Call queryBySessionId method
const result = await messageModel.queryBySessionId(sessionId);
- // 断言结果
+ // Assert result
expect(result).toHaveLength(2);
expect(result[0].id).toBe('1');
expect(result[1].id).toBe('2');
@@ -610,7 +610,7 @@ describe('MessageModel', () => {
describe('queryByKeyWord', () => {
it('should query messages by keyword', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'apple', createdAt: new Date('2022-02-01') },
{ id: '2', userId, role: 'user', content: 'banana' },
@@ -618,17 +618,17 @@ describe('MessageModel', () => {
{ id: '4', userId, role: 'user', content: 'apple pie', createdAt: new Date('2024-02-01') },
]);
- // 测试查询包含特定关键字的消息
+ // Test querying messages with specific keyword
const result = await messageModel.queryByKeyword('apple');
- // 断言结果
+ // Assert result
expect(result).toHaveLength(2);
expect(result[0].id).toBe('4');
expect(result[1].id).toBe('1');
});
it('should return empty array when keyword is empty', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'apple' },
{ id: '2', userId, role: 'user', content: 'banana' },
@@ -636,20 +636,20 @@ describe('MessageModel', () => {
{ id: '4', userId, role: 'user', content: 'apple pie' },
]);
- // 测试当关键字为空时返回空数组
+ // Test returning empty array when keyword is empty
const result = await messageModel.queryByKeyword('');
- // 断言结果
+ // Assert result
expect(result).toHaveLength(0);
});
});
describe('createMessage', () => {
it('should create a new message', async () => {
- // 调用 createMessage 方法
+ // Call createMessage method
await messageModel.create({ role: 'user', content: 'new message', sessionId: '1' });
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.userId, userId));
expect(result).toHaveLength(1);
expect(result[0].content).toBe('new message');
@@ -673,21 +673,21 @@ describe('MessageModel', () => {
});
it('should generate message ID automatically', async () => {
- // 调用 createMessage 方法
+ // Call createMessage method
await messageModel.create({
role: 'user',
content: 'new message',
sessionId: '1',
});
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.userId, userId));
expect(result[0].id).toBeDefined();
expect(result[0].id).toHaveLength(18);
});
it('should create a tool message and insert into messagePlugins table', async () => {
- // 调用 create 方法
+ // Call create method
const result = await messageModel.create({
content: 'message 1',
role: 'tool',
@@ -701,7 +701,7 @@ describe('MessageModel', () => {
},
});
- // 断言结果
+ // Assert result
expect(result.id).toBeDefined();
expect(result.content).toBe('message 1');
expect(result.role).toBe('tool');
@@ -716,7 +716,7 @@ describe('MessageModel', () => {
});
it('should create tool message ', async () => {
- // 调用 create 方法
+ // Call create method
const state = {
query: 'Composio',
answers: [],
@@ -768,7 +768,7 @@ describe('MessageModel', () => {
sessionId: '1',
});
- // 断言结果
+ // Assert result
expect(result.id).toBeDefined();
expect(result.content).toBe('[{}]');
expect(result.role).toBe('tool');
@@ -798,14 +798,14 @@ describe('MessageModel', () => {
expect(result.id).toBe(customId);
- // 验证数据库中的记录
+ // Verify database records
const dbResult = await serverDB.select().from(messages).where(eq(messages.id, customId));
expect(dbResult).toHaveLength(1);
expect(dbResult[0].id).toBe(customId);
});
it.skip('should create a message with file chunks and RAG query ID', async () => {
- // 创建测试数据
+ // Create test data
const chunkId1 = uuid();
const chunkId2 = uuid();
const ragQueryId = uuid();
@@ -815,7 +815,7 @@ describe('MessageModel', () => {
{ id: chunkId2, text: 'chunk text 2' },
]);
- // 调用 create 方法
+ // Call create method
const result = await messageModel.create({
role: 'assistant',
content: 'message with file chunks',
@@ -827,10 +827,10 @@ describe('MessageModel', () => {
sessionId: '1',
});
- // 验证消息创建成功
+ // Verify message created successfully
expect(result.id).toBeDefined();
- // 验证消息查询块关联创建成功
+ // Verify message query chunk associations created successfully
const queryChunks = await serverDB
.select()
.from(messageQueryChunks)
@@ -845,7 +845,7 @@ describe('MessageModel', () => {
});
it('should create a message with files', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(files).values([
{
id: 'file1',
@@ -865,7 +865,7 @@ describe('MessageModel', () => {
},
]);
- // 调用 create 方法
+ // Call create method
const result = await messageModel.create({
role: 'user',
content: 'message with files',
@@ -873,10 +873,10 @@ describe('MessageModel', () => {
sessionId: '1',
});
- // 验证消息创建成功
+ // Verify message created successfully
expect(result.id).toBeDefined();
- // 验证消息文件关联创建成功
+ // Verify message file associations created successfully
const messageFiles = await serverDB
.select()
.from(messagesFiles)
@@ -899,10 +899,10 @@ describe('MessageModel', () => {
sessionId: '1',
});
- // 验证数据库中的记录
+ // Verify database records
const dbResult = await serverDB.select().from(messages).where(eq(messages.id, result.id));
- // 日期比较需要考虑时区和格式化问题,所以使用 toISOString 进行比较
+ // Date comparison needs to consider timezone and formatting, so use toISOString for comparison
expect(new Date(dbResult[0].createdAt!).toISOString()).toBe(
new Date(customCreatedAt).toISOString(),
);
@@ -915,16 +915,16 @@ describe('MessageModel', () => {
describe('batchCreateMessages', () => {
it('should batch create messages', async () => {
- // 准备测试数据
+ // Prepare test data
const newMessages = [
{ id: '1', role: 'user', content: 'message 1' },
{ id: '2', role: 'assistant', content: 'message 2' },
] as DBMessageItem[];
- // 调用 batchCreateMessages 方法
+ // Call batchCreateMessages method
await messageModel.batchCreate(newMessages);
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.userId, userId));
expect(result).toHaveLength(2);
expect(result[0].content).toBe('message 1');
@@ -934,14 +934,14 @@ describe('MessageModel', () => {
describe('createNewMessage', () => {
it('should create message and return id with messages list', async () => {
- // 调用 createNewMessage 方法
+ // 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();
@@ -957,7 +957,7 @@ describe('MessageModel', () => {
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);
@@ -965,30 +965,87 @@ describe('MessageModel', () => {
});
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 });
- // 创建不同 topic 的消息
+ // 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' });
- // 创建新消息并指定 topicId
+ // Create new message and specify topicId
const result = await messageModel.createNewMessage({
role: 'user',
content: 'new topic msg',
@@ -996,7 +1053,7 @@ describe('MessageModel', () => {
topicId,
});
- // 验证只返回该 topic 的消息
+ // Verify only messages from that topic are returned
expect(result.messages.every((m) => m.topicId === topicId || m.topicId === undefined)).toBe(
true,
);
@@ -1006,35 +1063,35 @@ describe('MessageModel', () => {
describe('updateMessage', () => {
it('should update message content', async () => {
- // 创建测试数据
+ // Create test data
await serverDB
.insert(messages)
.values([{ id: '1', userId, role: 'user', content: 'message 1' }]);
- // 调用 updateMessage 方法
+ // Call updateMessage method
await messageModel.update('1', { content: 'updated message' });
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.id, '1'));
expect(result[0].content).toBe('updated message');
});
it('should only update messages belonging to the user', async () => {
- // 创建测试数据
+ // Create test data
await serverDB
.insert(messages)
.values([{ id: '1', userId: '456', role: 'user', content: 'message 1' }]);
- // 调用 updateMessage 方法
+ // Call updateMessage method
await messageModel.update('1', { content: 'updated message' });
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.id, '1'));
expect(result[0].content).toBe('message 1');
});
it('should update message tools', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{
id: '1',
@@ -1054,7 +1111,7 @@ describe('MessageModel', () => {
},
]);
- // 调用 updateMessage 方法
+ // Call updateMessage method
await messageModel.update('1', {
tools: [
{
@@ -1067,7 +1124,7 @@ describe('MessageModel', () => {
],
});
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.id, '1'));
expect((result[0].tools as any)[0].arguments).toBe(
'{"query":"2024 杭州暴雨","searchEngines":["duckduckgo","google","brave"]}',
@@ -1076,7 +1133,7 @@ describe('MessageModel', () => {
describe('update with imageList', () => {
it('should update a message and add image files', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg-to-update',
userId,
@@ -1096,7 +1153,7 @@ describe('MessageModel', () => {
{ id: 'img2', name: 'image2.png', fileType: 'image/png', size: 200, url: 'url2', userId },
]);
- // 调用 update 方法
+ // Call update method
await messageModel.update('msg-to-update', {
content: 'updated content',
imageList: [
@@ -1105,7 +1162,7 @@ describe('MessageModel', () => {
],
});
- // 验证消息更新成功
+ // Verify message updated successfully
const updatedMessage = await serverDB
.select()
.from(messages)
@@ -1113,7 +1170,7 @@ describe('MessageModel', () => {
expect(updatedMessage[0].content).toBe('updated content');
- // 验证消息文件关联创建成功
+ // Verify message file associations created successfully
const messageFiles = await serverDB
.select()
.from(messagesFiles)
@@ -1125,7 +1182,7 @@ describe('MessageModel', () => {
});
it('should handle empty imageList', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg-no-images',
userId,
@@ -1133,12 +1190,12 @@ describe('MessageModel', () => {
content: 'original content',
});
- // 调用 update 方法,不提供 imageList
+ // Call update method without providing imageList
await messageModel.update('msg-no-images', {
content: 'updated content',
});
- // 验证消息更新成功
+ // Verify message updated successfully
const updatedMessage = await serverDB
.select()
.from(messages)
@@ -1146,7 +1203,7 @@ describe('MessageModel', () => {
expect(updatedMessage[0].content).toBe('updated content');
- // 验证没有创建消息文件关联
+ // Verify no message file associations created
const messageFiles = await serverDB
.select()
.from(messagesFiles)
@@ -1156,7 +1213,7 @@ describe('MessageModel', () => {
});
it('should update multiple fields at once', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg-multi-update',
userId,
@@ -1165,7 +1222,7 @@ describe('MessageModel', () => {
model: 'gpt-3.5',
});
- // 调用 update 方法,更新多个字段
+ // Call update method to update multiple fields
await messageModel.update('msg-multi-update', {
content: 'updated content',
role: 'assistant',
@@ -1173,7 +1230,7 @@ describe('MessageModel', () => {
metadata: { tps: 1 },
});
- // 验证消息更新成功
+ // Verify message updated successfully
const updatedMessage = await serverDB
.select()
.from(messages)
@@ -1185,11 +1242,106 @@ describe('MessageModel', () => {
expect(updatedMessage[0].metadata).toEqual({ tps: 1 });
});
});
+
+ describe('update with returnQuery option', () => {
+ it('should return updated message list when sessionId is provided', async () => {
+ // Create test data
+ const sessionId = '1';
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg1',
+ userId,
+ sessionId,
+ role: 'user',
+ content: 'message 1',
+ },
+ {
+ id: 'msg2',
+ userId,
+ sessionId,
+ role: 'assistant',
+ content: 'message 2',
+ },
+ ]);
+
+ // Call update method with sessionId option
+ const result = await messageModel.update(
+ 'msg1',
+ { content: 'updated message 1' },
+ { sessionId },
+ );
+
+ // Verify return result contains message list
+ expect(result.success).toBe(true);
+ expect(result.messages).toBeDefined();
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages![0].content).toBe('updated message 1');
+ expect(result.messages![1].content).toBe('message 2');
+ });
+
+ it('should return updated message list when topicId is provided', async () => {
+ // Create test data
+ const sessionId = '1';
+ const topicId = 'topic-1';
+ await serverDB.insert(topics).values({ id: topicId, sessionId, userId });
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-topic1',
+ userId,
+ sessionId,
+ topicId,
+ role: 'user',
+ content: 'topic message 1',
+ },
+ {
+ id: 'msg-topic2',
+ userId,
+ sessionId,
+ topicId,
+ role: 'assistant',
+ content: 'topic message 2',
+ },
+ ]);
+
+ // Call update method with topicId option
+ const result = await messageModel.update(
+ 'msg-topic1',
+ { content: 'updated topic message 1' },
+ { topicId, sessionId },
+ );
+
+ // Verify return result contains message list
+ expect(result.success).toBe(true);
+ expect(result.messages).toBeDefined();
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages![0].content).toBe('updated topic message 1');
+ expect(result.messages![1].content).toBe('topic message 2');
+ });
+
+ it('should return success without messages when options not provided', async () => {
+ // Create test data
+ await serverDB.insert(messages).values({
+ id: 'msg-no-options',
+ userId,
+ role: 'user',
+ content: 'original content',
+ });
+
+ // Call update method,不提供选项
+ const result = await messageModel.update('msg-no-options', {
+ content: 'updated content',
+ });
+
+ // 验证返回结果不包含消息列表
+ expect(result.success).toBe(true);
+ expect(result.messages).toBeUndefined();
+ });
+ });
});
describe('deleteMessage', () => {
it('should delete a message', async () => {
- // 创建测试数据
+ // Create test data
await serverDB
.insert(messages)
.values([{ id: '1', userId, role: 'user', content: 'message 1' }]);
@@ -1197,13 +1349,13 @@ describe('MessageModel', () => {
// 调用 deleteMessage 方法
await messageModel.deleteMessage('1');
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.id, '1'));
expect(result).toHaveLength(0);
});
it('should delete a message with tool calls', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.transaction(async (trx) => {
await trx.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1', tools: [{ id: 'tool1' }] },
@@ -1217,7 +1369,7 @@ describe('MessageModel', () => {
// 调用 deleteMessage 方法
await messageModel.deleteMessage('1');
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.id, '1'));
expect(result).toHaveLength(0);
@@ -1230,7 +1382,7 @@ describe('MessageModel', () => {
});
it('should only delete messages belonging to the user', async () => {
- // 创建测试数据
+ // Create test data
await serverDB
.insert(messages)
.values([{ id: '1', userId: '456', role: 'user', content: 'message 1' }]);
@@ -1238,7 +1390,7 @@ describe('MessageModel', () => {
// 调用 deleteMessage 方法
await messageModel.deleteMessage('1');
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.id, '1'));
expect(result).toHaveLength(1);
});
@@ -1246,7 +1398,7 @@ describe('MessageModel', () => {
describe('deleteMessages', () => {
it('should delete 2 messages', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1' },
{ id: '2', userId, role: 'user', content: 'message 2' },
@@ -1255,7 +1407,7 @@ describe('MessageModel', () => {
// 调用 deleteMessage 方法
await messageModel.deleteMessages(['1', '2']);
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.id, '1'));
expect(result).toHaveLength(0);
const result2 = await serverDB.select().from(messages).where(eq(messages.id, '2'));
@@ -1263,7 +1415,7 @@ describe('MessageModel', () => {
});
it('should only delete messages belonging to the user', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId: '456', role: 'user', content: 'message 1' },
{ id: '2', userId: '456', role: 'user', content: 'message 1' },
@@ -1272,7 +1424,7 @@ describe('MessageModel', () => {
// 调用 deleteMessage 方法
await messageModel.deleteMessages(['1', '2']);
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.id, '1'));
expect(result).toHaveLength(1);
});
@@ -1280,7 +1432,7 @@ describe('MessageModel', () => {
describe('deleteAllMessages', () => {
it('should delete all messages belonging to the user', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1' },
{ id: '2', userId, role: 'user', content: 'message 2' },
@@ -1290,7 +1442,7 @@ describe('MessageModel', () => {
// 调用 deleteAllMessages 方法
await messageModel.deleteAllMessages();
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messages).where(eq(messages.userId, userId));
expect(result).toHaveLength(0);
@@ -1303,7 +1455,7 @@ describe('MessageModel', () => {
describe('updatePluginState', () => {
it('should update the state field in messagePlugins table', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({ id: '1', content: 'abc', role: 'user', userId });
await serverDB.insert(messagePlugins).values([
{
@@ -1318,7 +1470,7 @@ describe('MessageModel', () => {
// 调用 updatePluginState 方法
await messageModel.updatePluginState('1', { key2: 'value2' });
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messagePlugins).where(eq(messagePlugins.id, '1'));
expect(result[0].state).toEqual({ key1: 'value1', key2: 'value2' });
@@ -1333,7 +1485,7 @@ describe('MessageModel', () => {
});
describe('updateMessagePlugin', () => {
it('should update the state field in messagePlugins table', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({ id: '1', content: 'abc', role: 'user', userId });
await serverDB.insert(messagePlugins).values([
{
@@ -1348,7 +1500,7 @@ describe('MessageModel', () => {
// 调用 updatePluginState 方法
await messageModel.updateMessagePlugin('1', { identifier: 'plugin2' });
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messagePlugins).where(eq(messagePlugins.id, '1'));
expect(result[0].identifier).toEqual('plugin2');
@@ -1364,7 +1516,7 @@ describe('MessageModel', () => {
describe('updateMetadata', () => {
it('should update metadata for an existing message', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg-with-metadata',
userId,
@@ -1376,7 +1528,7 @@ describe('MessageModel', () => {
// 调用 updateMetadata 方法
await messageModel.updateMetadata('msg-with-metadata', { newKey: 'newValue' });
- // 断言结果
+ // Assert result
const result = await serverDB
.select()
.from(messages)
@@ -1389,7 +1541,7 @@ describe('MessageModel', () => {
});
it('should merge new metadata with existing metadata using lodash merge behavior', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg-merge-metadata',
userId,
@@ -1413,7 +1565,7 @@ describe('MessageModel', () => {
newTopLevel: 'value',
});
- // 断言结果 - 应该使用 lodash merge 行为
+ // Assert result - 应该使用 lodash merge 行为
const result = await serverDB
.select()
.from(messages)
@@ -1434,12 +1586,12 @@ describe('MessageModel', () => {
// 调用 updateMetadata 方法,尝试更新不存在的消息
const result = await messageModel.updateMetadata('non-existent-id', { key: 'value' });
- // 断言结果 - 应该返回 undefined
+ // Assert result - 应该返回 undefined
expect(result).toBeUndefined();
});
it('should handle empty metadata updates', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg-empty-metadata',
userId,
@@ -1451,7 +1603,7 @@ describe('MessageModel', () => {
// 调用 updateMetadata 方法,传递空对象
await messageModel.updateMetadata('msg-empty-metadata', {});
- // 断言结果 - 原始 metadata 应该保持不变
+ // Assert result - 原始 metadata 应该保持不变
const result = await serverDB
.select()
.from(messages)
@@ -1461,7 +1613,7 @@ describe('MessageModel', () => {
});
it('should handle message with null metadata', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg-null-metadata',
userId,
@@ -1473,7 +1625,7 @@ describe('MessageModel', () => {
// 调用 updateMetadata 方法
await messageModel.updateMetadata('msg-null-metadata', { key: 'value' });
- // 断言结果 - 应该创建新的 metadata
+ // Assert result - 应该创建新的 metadata
const result = await serverDB
.select()
.from(messages)
@@ -1483,7 +1635,7 @@ describe('MessageModel', () => {
});
it('should only update messages belonging to the current user', async () => {
- // 创建测试数据 - 其他用户的消息
+ // Create test data - 其他用户的消息
await serverDB.insert(messages).values({
id: 'msg-other-user',
userId: '456',
@@ -1497,7 +1649,7 @@ describe('MessageModel', () => {
hackedKey: 'hackedValue',
});
- // 断言结果 - 应该返回 undefined
+ // Assert result - 应该返回 undefined
expect(result).toBeUndefined();
// 验证原始 metadata 未被修改
@@ -1510,7 +1662,7 @@ describe('MessageModel', () => {
});
it('should handle complex nested metadata updates', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg-complex-metadata',
userId,
@@ -1539,7 +1691,7 @@ describe('MessageModel', () => {
stats: { count: 10 },
});
- // 断言结果
+ // Assert result
const result = await serverDB
.select()
.from(messages)
@@ -1562,7 +1714,7 @@ describe('MessageModel', () => {
describe('updateTranslate', () => {
it('should insert a new record if message does not exist in messageTranslates table', async () => {
- // 创建测试数据
+ // Create test data
await serverDB
.insert(messages)
.values([{ id: '1', userId, role: 'user', content: 'message 1' }]);
@@ -1574,7 +1726,7 @@ describe('MessageModel', () => {
to: 'zh',
});
- // 断言结果
+ // Assert result
const result = await serverDB
.select()
.from(messageTranslates)
@@ -1585,7 +1737,7 @@ describe('MessageModel', () => {
});
it('should update the corresponding fields if message exists in messageTranslates table', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.transaction(async (trx) => {
await trx
.insert(messages)
@@ -1598,7 +1750,7 @@ describe('MessageModel', () => {
// 调用 updateTranslate 方法
await messageModel.updateTranslate('1', { content: 'updated translated message 1' });
- // 断言结果
+ // Assert result
const result = await serverDB
.select()
.from(messageTranslates)
@@ -1610,7 +1762,7 @@ describe('MessageModel', () => {
describe('updateTTS', () => {
it('should insert a new record if message does not exist in messageTTS table', async () => {
- // 创建测试数据
+ // Create test data
await serverDB
.insert(messages)
.values([{ id: '1', userId, role: 'user', content: 'message 1' }]);
@@ -1618,7 +1770,7 @@ describe('MessageModel', () => {
// 调用 updateTTS 方法
await messageModel.updateTTS('1', { contentMd5: 'md5', file: 'f1', voice: 'voice1' });
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messageTTS).where(eq(messageTTS.id, '1'));
expect(result).toHaveLength(1);
@@ -1626,7 +1778,7 @@ describe('MessageModel', () => {
});
it('should update the corresponding fields if message exists in messageTTS table', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.transaction(async (trx) => {
await trx
.insert(messages)
@@ -1639,7 +1791,7 @@ describe('MessageModel', () => {
// 调用 updateTTS 方法
await messageModel.updateTTS('1', { voice: 'updated voice1' });
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messageTTS).where(eq(messageTTS.id, '1'));
expect(result[0].voice).toBe('updated voice1');
@@ -1648,14 +1800,14 @@ describe('MessageModel', () => {
describe('deleteMessageTranslate', () => {
it('should delete the message translate record', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([{ id: '1', role: 'abc', userId }]);
await serverDB.insert(messageTranslates).values([{ id: '1', userId }]);
// 调用 deleteMessageTranslate 方法
await messageModel.deleteMessageTranslate('1');
- // 断言结果
+ // Assert result
const result = await serverDB
.select()
.from(messageTranslates)
@@ -1667,14 +1819,14 @@ describe('MessageModel', () => {
describe('deleteMessageTTS', () => {
it('should delete the message TTS record', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([{ id: '1', role: 'abc', userId }]);
await serverDB.insert(messageTTS).values([{ userId, id: '1' }]);
// 调用 deleteMessageTTS 方法
await messageModel.deleteMessageTTS('1');
- // 断言结果
+ // Assert result
const result = await serverDB.select().from(messageTTS).where(eq(messageTTS.id, '1'));
expect(result).toHaveLength(0);
});
@@ -1682,7 +1834,7 @@ describe('MessageModel', () => {
describe('count', () => {
it('should return the count of messages belonging to the user', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1' },
{ id: '2', userId, role: 'user', content: 'message 2' },
@@ -1692,13 +1844,13 @@ describe('MessageModel', () => {
// 调用 count 方法
const result = await messageModel.count();
- // 断言结果
+ // Assert result
expect(result).toBe(2);
});
describe('count with date filters', () => {
beforeEach(async () => {
- // 创建测试数据,包含不同日期的消息
+ // Create test data,包含不同日期的消息
await serverDB.insert(messages).values([
{
id: 'date1',
@@ -1919,7 +2071,7 @@ describe('MessageModel', () => {
describe('countWords', () => {
it('should count total words of messages belonging to the user', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'hello world' },
{ id: '2', userId, role: 'user', content: 'test message' },
@@ -1929,12 +2081,12 @@ describe('MessageModel', () => {
// 调用 countWords 方法
const result = await messageModel.countWords();
- // 断言结果 - 'hello world' + 'test message' = 23 characters
+ // Assert result - 'hello world' + 'test message' = 23 characters
expect(result).toEqual(23);
});
it('should count words within date range', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{
id: '1',
@@ -1957,12 +2109,12 @@ describe('MessageModel', () => {
range: ['2023-05-01', '2023-07-01'],
});
- // 断言结果 - 只计算 'new message' = 11 characters
+ // Assert result - 只计算 'new message' = 11 characters
expect(result).toEqual(11);
});
it('should handle empty content', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: '' },
{ id: '2', userId, role: 'user', content: null },
@@ -1971,7 +2123,7 @@ describe('MessageModel', () => {
// 调用 countWords 方法
const result = await messageModel.countWords();
- // 断言结果
+ // Assert result
expect(result).toEqual(0);
});
});
@@ -1988,7 +2140,7 @@ describe('MessageModel', () => {
const oneDayAgoDate = today.subtract(1, 'day').format('YYYY-MM-DD');
const todayDate = today.format('YYYY-MM-DD');
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{
id: '1',
@@ -2016,7 +2168,7 @@ describe('MessageModel', () => {
// 调用 getHeatmaps 方法
const result = await messageModel.getHeatmaps();
- // 断言结果
+ // Assert result
expect(result.length).toBeGreaterThanOrEqual(366);
expect(result.length).toBeLessThan(368);
@@ -2051,7 +2203,7 @@ describe('MessageModel', () => {
const oneDayAgoDate = today.subtract(1, 'day').format('YYYY-MM-DD');
const todayDate = today.format('YYYY-MM-DD');
- // 创建测试数据 - 不同数量的消息以测试不同的等级
+ // Create test data - 不同数量的消息以测试不同的等级
await serverDB.insert(messages).values([
// 1 message - level 1
{
@@ -2141,7 +2293,7 @@ describe('MessageModel', () => {
const oneDayAgoDate = today.subtract(1, 'day').format('YYYY-MM-DD');
const todayDate = today.format('YYYY-MM-DD');
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{
id: '1',
@@ -2169,7 +2321,7 @@ describe('MessageModel', () => {
// 调用 getHeatmaps 方法
const result = await messageModel.getHeatmaps();
- // 断言结果
+ // Assert result
expect(result.length).toBeGreaterThanOrEqual(366);
expect(result.length).toBeLessThan(368);
@@ -2197,7 +2349,7 @@ describe('MessageModel', () => {
// 调用 getHeatmaps 方法
const result = await messageModel.getHeatmaps();
- // 断言结果
+ // Assert result
expect(result.length).toBeGreaterThanOrEqual(366);
expect(result.length).toBeLessThan(368);
@@ -2211,7 +2363,7 @@ describe('MessageModel', () => {
describe('rankModels', () => {
it('should rank models by usage count', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'assistant', content: 'message 1', model: 'gpt-3.5' },
{ id: '2', userId, role: 'assistant', content: 'message 2', model: 'gpt-3.5' },
@@ -2222,14 +2374,14 @@ describe('MessageModel', () => {
// 调用 rankModels 方法
const result = await messageModel.rankModels();
- // 断言结果
+ // Assert result
expect(result).toHaveLength(2);
expect(result[0]).toEqual({ id: 'gpt-3.5', count: 2 }); // 当前用户使用 gpt-3.5 两次
expect(result[1]).toEqual({ id: 'gpt-4', count: 1 }); // 当前用户使用 gpt-4 一次
});
it('should only count messages with model field', async () => {
- // 创建测试数据,包括没有 model 字段的消息
+ // Create test data,包括没有 model 字段的消息
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'assistant', content: 'message 1', model: 'gpt-3.5' },
{ id: '2', userId, role: 'assistant', content: 'message 2', model: null },
@@ -2239,13 +2391,13 @@ describe('MessageModel', () => {
// 调用 rankModels 方法
const result = await messageModel.rankModels();
- // 断言结果
+ // Assert result
expect(result).toHaveLength(1);
expect(result[0]).toEqual({ id: 'gpt-3.5', count: 1 });
});
it('should return empty array when no models are used', async () => {
- // 创建测试数据,所有消息都没有 model
+ // Create test data,所有消息都没有 model
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1' },
{ id: '2', userId, role: 'assistant', content: 'message 2' },
@@ -2254,12 +2406,12 @@ describe('MessageModel', () => {
// 调用 rankModels 方法
const result = await messageModel.rankModels();
- // 断言结果
+ // Assert result
expect(result).toHaveLength(0);
});
it('should order models by count in descending order', async () => {
- // 创建测试数据,使用不同次数的模型
+ // Create test data,使用不同次数的模型
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'assistant', content: 'message 1', model: 'gpt-4' },
{ id: '2', userId, role: 'assistant', content: 'message 2', model: 'gpt-3.5' },
@@ -2271,7 +2423,7 @@ describe('MessageModel', () => {
// 调用 rankModels 方法
const result = await messageModel.rankModels();
- // 断言结果
+ // Assert result
expect(result).toHaveLength(3);
expect(result[0]).toEqual({ id: 'gpt-3.5', count: 3 }); // 最多使用
expect(result[1]).toEqual({ id: 'claude', count: 1 });
@@ -2281,7 +2433,7 @@ describe('MessageModel', () => {
describe('hasMoreThanN', () => {
it('should return true when message count is greater than N', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1' },
{ id: '2', userId, role: 'user', content: 'message 2' },
@@ -2299,7 +2451,7 @@ describe('MessageModel', () => {
});
it('should only count messages belonging to the user', async () => {
- // 创建测试数据,包括其他用户的消息
+ // Create test data,包括其他用户的消息
await serverDB.insert(messages).values([
{ id: '1', userId, role: 'user', content: 'message 1' },
{ id: '2', userId, role: 'user', content: 'message 2' },
@@ -2335,7 +2487,7 @@ describe('MessageModel', () => {
describe('createMessageQuery', () => {
it('should create a new message query', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg1',
userId,
@@ -2351,7 +2503,7 @@ describe('MessageModel', () => {
embeddingsId,
});
- // 断言结果
+ // Assert result
expect(result).toBeDefined();
expect(result.id).toBeDefined();
expect(result.messageId).toBe('msg1');
@@ -2372,7 +2524,7 @@ describe('MessageModel', () => {
});
it('should create a message query with embeddings ID', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg2',
userId,
@@ -2388,7 +2540,7 @@ describe('MessageModel', () => {
embeddingsId,
});
- // 断言结果
+ // Assert result
expect(result).toBeDefined();
expect(result.embeddingsId).toBe(embeddingsId);
@@ -2402,7 +2554,7 @@ describe('MessageModel', () => {
});
it('should generate a unique ID for each message query', async () => {
- // 创建测试数据
+ // Create test data
await serverDB.insert(messages).values({
id: 'msg3',
userId,
@@ -2425,7 +2577,7 @@ describe('MessageModel', () => {
embeddingsId,
});
- // 断言结果
+ // Assert result
expect(result1.id).not.toBe(result2.id);
});
});
@@ -2473,7 +2625,7 @@ describe('MessageModel', () => {
describe('deleteMessageQuery', () => {
it('should delete a message query by ID', async () => {
- // 创建测试数据
+ // Create test data
const queryId = uuid();
await serverDB.insert(messages).values({
id: 'msg4',
@@ -2511,7 +2663,7 @@ describe('MessageModel', () => {
});
it('should only delete message queries belonging to the user', async () => {
- // 创建测试数据 - 其他用户的查询
+ // Create test data - 其他用户的查询
const queryId = uuid();
await serverDB.insert(messages).values({
id: 'msg5',
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index ad96107b0b5..780f581c691 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -1,3 +1,4 @@
+import { INBOX_SESSION_ID } from '@lobechat/const';
import {
ChatFileItem,
ChatImageItem,
@@ -14,6 +15,7 @@ import {
UIChatMessage,
UpdateMessageParams,
UpdateMessageRAGParams,
+ UpdateMessageResult,
} from '@lobechat/types';
import type { HeatmapsProps } from '@lobehub/charts';
import dayjs from 'dayjs';
@@ -39,6 +41,7 @@ import {
} from '../schemas';
import { LobeChatDatabase } from '../type';
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
+import { groupAssistantMessages } from '../utils/groupMessages';
import { idGenerator } from '../utils/idGenerator';
export class MessageModel {
@@ -54,6 +57,7 @@ export class MessageModel {
query = async (
{ current = 0, pageSize = 1000, sessionId, topicId, groupId }: QueryMessageParams = {},
options: {
+ groupAssistantMessages?: boolean;
postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;
} = {},
) => {
@@ -211,7 +215,7 @@ export class MessageModel {
.from(messageQueries)
.where(inArray(messageQueries.messageId, messageIds));
- return result.map(
+ const mappedMessages = result.map(
({ model, provider, translate, ttsId, ttsFile, ttsContentMd5, ttsVoice, ...item }) => {
const messageQuery = messageQueriesList.find((relation) => relation.messageId === item.id);
return {
@@ -246,13 +250,15 @@ export class MessageModel {
size: size!,
url,
})),
-
imageList: imageList
.filter((relation) => relation.messageId === item.id)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.map<ChatImageItem>(({ id, url, name }) => ({ alt: name!, id, url })),
-
meta: {},
+
+ model,
+
+ provider,
ragQuery: messageQuery?.rewriteQuery,
ragQueryId: messageQuery?.id,
ragRawQuery: messageQuery?.userQuery,
@@ -263,6 +269,10 @@ export class MessageModel {
} as unknown as UIChatMessage;
},
);
+
+ // Group assistant messages with their tool results
+ const { groupAssistantMessages: useGroup = false } = options;
+ return useGroup ? groupAssistantMessages(mappedMessages) : mappedMessages;
};
findById = async (id: string) => {
@@ -560,7 +570,7 @@ export class MessageModel {
sessionId: params.sessionId,
topicId: params.topicId, // Get all messages
},
- options,
+ { ...options, groupAssistantMessages: true },
);
// 3. Return the result
@@ -589,27 +599,52 @@ export class MessageModel {
};
// **************** Update *************** //
- update = async (id: string, { imageList, ...message }: Partial<UpdateMessageParams>) => {
- return this.db.transaction(async (trx) => {
- // 1. insert message files
- if (imageList && imageList.length > 0) {
+ update = async (
+ id: string,
+ { imageList, ...message }: Partial<UpdateMessageParams>,
+ options?: {
+ postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;
+ sessionId?: string | null;
+ topicId?: string | null;
+ },
+ ): Promise<UpdateMessageResult> => {
+ try {
+ await this.db.transaction(async (trx) => {
+ // 1. insert message files
+ if (imageList && imageList.length > 0) {
+ await trx
+ .insert(messagesFiles)
+ .values(
+ imageList.map((file) => ({ fileId: file.id, messageId: id, userId: this.userId })),
+ );
+ }
+
await trx
- .insert(messagesFiles)
- .values(
- imageList.map((file) => ({ fileId: file.id, messageId: id, userId: this.userId })),
- );
+ .update(messages)
+ .set({ ...message })
+ .where(and(eq(messages.id, id), eq(messages.userId, this.userId)));
+ });
+
+ // if sessionId or topicId provided, return the updated message list
+ if (options?.sessionId !== undefined || options?.topicId !== undefined) {
+ const messageList = await this.query(
+ {
+ sessionId: options.sessionId,
+ topicId: options.topicId,
+ },
+ {
+ postProcessUrl: options.postProcessUrl,
+ },
+ );
+
+ return { messages: messageList, success: true };
}
- return trx
- .update(messages)
- .set({
- ...message,
- // TODO: need a better way to handle this
- // TODO: but I forget why 🤡
- role: message.role as any,
- })
- .where(and(eq(messages.id, id), eq(messages.userId, this.userId)));
- });
+ return { success: true };
+ } catch (error) {
+ console.error('Update message error:', error);
+ return { success: false };
+ }
};
updateMetadata = async (id: string, metadata: Record<string, any>) => {
@@ -778,8 +813,11 @@ export class MessageModel {
private genId = () => idGenerator('messages', 14);
- private matchSession = (sessionId?: string | null) =>
- sessionId ? eq(messages.sessionId, sessionId) : isNull(messages.sessionId);
+ private matchSession = (sessionId?: string | null) => {
+ if (sessionId === INBOX_SESSION_ID) return isNull(messages.sessionId);
+
+ return sessionId ? eq(messages.sessionId, sessionId) : isNull(messages.sessionId);
+ };
private matchTopic = (topicId?: string | null) =>
topicId ? eq(messages.topicId, topicId) : isNull(messages.topicId);
diff --git a/packages/database/src/utils/__tests__/groupMessages.test.ts b/packages/database/src/utils/__tests__/groupMessages.test.ts
index 80eb60d8c78..2ff6dbf29f4 100644
--- a/packages/database/src/utils/__tests__/groupMessages.test.ts
+++ b/packages/database/src/utils/__tests__/groupMessages.test.ts
@@ -54,6 +54,7 @@ describe('groupAssistantMessages', () => {
content: 'Beijing: Sunny, 25°C',
state: { cached: true },
},
+ result_msg_id: 'msg-2',
});
});
@@ -112,7 +113,9 @@ describe('groupAssistantMessages', () => {
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![0].result_msg_id).toBe('msg-2');
expect(block.tools![1].result?.content).toBe('Latest tech news: AI breakthrough');
+ expect(block.tools![1].result_msg_id).toBe('msg-3');
});
it('should handle assistant message without tools', () => {
@@ -165,6 +168,7 @@ describe('groupAssistantMessages', () => {
const block = result[0].children![0];
expect(block.tools).toHaveLength(1);
expect(block.tools![0].result).toBeUndefined();
+ expect(block.tools![0].result_msg_id).toBeUndefined();
});
});
@@ -366,11 +370,13 @@ describe('groupAssistantMessages', () => {
// 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');
+ expect(result[0].children![0].tools![0].result_msg_id).toBe('msg-2');
// 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');
+ expect(result[0].children![1].tools![0].result_msg_id).toBe('msg-4');
});
it('should group multiple follow-up assistants in chain (3+ assistants)', () => {
@@ -448,9 +454,11 @@ describe('groupAssistantMessages', () => {
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![0].tools![0].result_msg_id).toBe('msg-2');
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![1].tools![0].result_msg_id).toBe('msg-4');
expect(result[0].children![2].id).toBe('msg-5');
expect(result[0].children![2].content).toBe('Step 3 final');
@@ -677,7 +685,6 @@ describe('groupAssistantMessages', () => {
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', () => {
@@ -720,6 +727,7 @@ describe('groupAssistantMessages', () => {
state: { step: 1 },
error: null,
});
+ expect(block.tools![0].result_msg_id).toBe('msg-2');
});
});
@@ -928,6 +936,142 @@ describe('groupAssistantMessages', () => {
expect(result[0].performance).toBeUndefined();
expect(result[0].metadata).toBeUndefined();
});
+
+ it('should map reasoning field to reasoning in children blocks', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Test response',
+ reasoning: {
+ content: 'This is my reasoning process',
+ duration: 1500,
+ },
+ 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: 'Follow-up response',
+ parentId: 'msg-2',
+ reasoning: {
+ content: 'Follow-up reasoning',
+ duration: 2000,
+ },
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ // First block should have reasoning
+ expect(result[0].children![0].reasoning).toEqual({
+ content: 'This is my reasoning process',
+ duration: 1500,
+ });
+
+ // Second block (follow-up) should also have reasoning
+ expect(result[0].children![1].reasoning).toEqual({
+ content: 'Follow-up reasoning',
+ duration: 2000,
+ });
+
+ // Group message should not have reasoning (moved to children)
+ expect(result[0].reasoning).toBeUndefined();
+ });
+
+ it('should preserve error field in children blocks', () => {
+ const input = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Failed to process',
+ error: {
+ type: 'InvalidAPIKey',
+ message: 'API key is invalid',
+ },
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as unknown as UIChatMessage,
+ ] as UIChatMessage[];
+
+ const result = groupAssistantMessages(input);
+
+ // Child block should have error
+ expect(result[0].children![0].error).toEqual({
+ type: 'InvalidAPIKey',
+ message: 'API key is invalid',
+ });
+ });
+
+ it('should preserve imageList in children blocks', () => {
+ const input: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Here are the images',
+ imageList: [
+ { id: 'img-1', url: 'https://example.com/img1.jpg', alt: 'Image 1' },
+ { id: 'img-2', url: 'https://example.com/img2.jpg', alt: 'Image 2' },
+ ],
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const result = groupAssistantMessages(input);
+
+ // Child block should have imageList
+ expect(result[0].children![0].imageList).toEqual([
+ { id: 'img-1', url: 'https://example.com/img1.jpg', alt: 'Image 1' },
+ { id: 'img-2', url: 'https://example.com/img2.jpg', alt: 'Image 2' },
+ ]);
+
+ // Parent should not have imageList (moved to children)
+ expect(result[0].imageList).toBeUndefined();
+ });
});
describe('Empty and Null Cases', () => {
@@ -958,7 +1102,6 @@ describe('groupAssistantMessages', () => {
// 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', () => {
diff --git a/packages/database/src/utils/groupMessages.ts b/packages/database/src/utils/groupMessages.ts
index 84f6bed85d9..a11651605bf 100644
--- a/packages/database/src/utils/groupMessages.ts
+++ b/packages/database/src/utils/groupMessages.ts
@@ -243,6 +243,7 @@ export function groupAssistantMessages(messages: UIChatMessage[]): UIChatMessage
id: toolMsg.id,
state: toolMsg.pluginState,
},
+ result_msg_id: toolMsg.id,
};
}
@@ -253,10 +254,11 @@ export function groupAssistantMessages(messages: UIChatMessage[]): UIChatMessage
const { usage: msgUsage, performance: msgPerformance } = splitMetadata(msg.metadata);
children.push({
content: msg.content || '',
- fileList: msg.fileList && msg.fileList.length > 0 ? msg.fileList : undefined,
+ error: msg.error,
id: msg.id,
imageList: msg.imageList && msg.imageList.length > 0 ? msg.imageList : undefined,
performance: msgPerformance,
+ reasoning: msg.reasoning || undefined,
tools: toolsWithResults,
usage: msgUsage,
});
@@ -299,6 +301,7 @@ export function groupAssistantMessages(messages: UIChatMessage[]): UIChatMessage
id: followUpToolMsg.id,
state: followUpToolMsg.pluginState,
},
+ result_msg_id: followUpToolMsg.id,
};
}
@@ -311,16 +314,14 @@ export function groupAssistantMessages(messages: UIChatMessage[]): UIChatMessage
);
children.push({
content: followUpMsg.content || '',
- fileList:
- followUpMsg.fileList && followUpMsg.fileList.length > 0
- ? followUpMsg.fileList
- : undefined,
+ error: followUpMsg.error,
id: followUpMsg.id,
imageList:
followUpMsg.imageList && followUpMsg.imageList.length > 0
? followUpMsg.imageList
: undefined,
performance: followUpPerformance,
+ reasoning: followUpMsg.reasoning || undefined,
tools: followUpToolsWithResults,
usage: followUpUsage,
});
@@ -347,6 +348,7 @@ export function groupAssistantMessages(messages: UIChatMessage[]): UIChatMessage
assistantMsg.performance = aggregated.performance;
}
delete assistantMsg.metadata; // Clear individual metadata
+ delete assistantMsg.reasoning; // Reasoning moved to children blocks
delete assistantMsg.tools;
delete assistantMsg.imageList;
delete assistantMsg.fileList;
diff --git a/packages/types/src/message/common/base.ts b/packages/types/src/message/common/base.ts
index 05e583a8d6f..20b78cd0255 100644
--- a/packages/types/src/message/common/base.ts
+++ b/packages/types/src/message/common/base.ts
@@ -1,5 +1,6 @@
import type { ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';
import type { IPluginErrorType } from '@lobehub/chat-plugin-sdk';
+import { z } from 'zod';
import { ErrorType } from '../../fetch';
@@ -12,6 +13,12 @@ export interface ChatMessageError {
type: ErrorType | IPluginErrorType | ILobeAgentRuntimeErrorType;
}
+export const ChatMessageErrorSchema = z.object({
+ body: z.any().optional(),
+ message: z.string(),
+ type: z.union([z.string(), z.number()]),
+});
+
export interface ChatCitationItem {
id?: string;
onlyUrl?: boolean;
@@ -24,3 +31,9 @@ export interface ModelReasoning {
duration?: number;
signature?: string;
}
+
+export const ModelReasoningSchema = z.object({
+ content: z.string().optional(),
+ duration: z.number().optional(),
+ signature: z.string().optional(),
+});
diff --git a/packages/types/src/message/common/image.ts b/packages/types/src/message/common/image.ts
index 5b2d8c5b34e..f9cf341c7ed 100644
--- a/packages/types/src/message/common/image.ts
+++ b/packages/types/src/message/common/image.ts
@@ -1,9 +1,17 @@
+import { z } from 'zod';
+
export interface ChatImageItem {
alt: string;
id: string;
url: string;
}
+export const ChatImageItemSchema = z.object({
+ alt: z.string(),
+ id: z.string(),
+ url: z.string(),
+});
+
export interface ChatImageChunk {
data: string;
id: string;
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index cf7fc980f09..be8881e312c 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -1,4 +1,5 @@
/* eslint-disable sort-keys-fix/sort-keys-fix , typescript-sort-keys/interface */
+import { z } from 'zod';
export interface ModelTokensUsage {
// Input tokens breakdown
@@ -38,6 +39,44 @@ export interface ModelTokensUsage {
totalTokens?: number;
}
+export const ModelUsageSchema = z.object({
+ // Input tokens breakdown
+ inputCachedTokens: z.number().optional(),
+ inputCacheMissTokens: z.number().optional(),
+ inputWriteCacheTokens: z.number().optional(),
+ inputTextTokens: z.number().optional(),
+ inputImageTokens: z.number().optional(),
+ inputAudioTokens: z.number().optional(),
+ inputCitationTokens: z.number().optional(),
+
+ // Output tokens breakdown
+ outputTextTokens: z.number().optional(),
+ outputImageTokens: z.number().optional(),
+ outputAudioTokens: z.number().optional(),
+ outputReasoningTokens: z.number().optional(),
+
+ // Prediction tokens
+ acceptedPredictionTokens: z.number().optional(),
+ rejectedPredictionTokens: z.number().optional(),
+
+ // Total tokens
+ totalInputTokens: z.number().optional(),
+ totalOutputTokens: z.number().optional(),
+ totalTokens: z.number().optional(),
+
+ // Cost
+ cost: z.number().optional(),
+});
+
+export const ModelPerformanceSchema = z.object({
+ tps: z.number().optional(),
+ ttft: z.number().optional(),
+ duration: z.number().optional(),
+ latency: z.number().optional(),
+});
+
+export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchema);
+
export interface ModelUsage extends ModelTokensUsage {
/**
* dollar
diff --git a/packages/types/src/message/common/tools.ts b/packages/types/src/message/common/tools.ts
index 634ab6cd6b0..4324bcfd530 100644
--- a/packages/types/src/message/common/tools.ts
+++ b/packages/types/src/message/common/tools.ts
@@ -16,6 +16,7 @@ export interface ChatToolPayload {
arguments: string;
id: string;
identifier: string;
+ result_msg_id?: string;
type: LobeToolRenderType;
}
@@ -85,6 +86,15 @@ export const MessageToolCallSchema = z.object({
type: z.string(),
});
+export const ChatToolPayloadSchema = z.object({
+ apiName: z.string(),
+ arguments: z.string(),
+ id: z.string(),
+ identifier: z.string(),
+ result_msg_id: z.string().optional(),
+ type: z.string(),
+});
+
/**
* 聊天消息错误对象
*/
diff --git a/packages/types/src/message/db/params.ts b/packages/types/src/message/db/params.ts
index 7982aaa785b..176c6a338cc 100644
--- a/packages/types/src/message/db/params.ts
+++ b/packages/types/src/message/db/params.ts
@@ -1,11 +1,20 @@
-import { GroundingSearch } from '../../search';
+/* eslint-disable sort-keys-fix/sort-keys-fix */
+import { z } from 'zod';
+
+import { GroundingSearch, GroundingSearchSchema } from '../../search';
import {
ChatImageItem,
+ ChatImageItemSchema,
ChatMessageError,
+ ChatMessageErrorSchema,
ChatToolPayload,
+ ChatToolPayloadSchema,
MessageMetadata,
+ MessageMetadataSchema,
MessageToolCall,
+ MessageToolCallSchema,
ModelReasoning,
+ ModelReasoningSchema,
} from '../common';
import { UIChatMessage } from '../ui';
@@ -34,6 +43,21 @@ export interface CreateMessageResult {
messages: UIChatMessage[];
}
+/**
+ * Result type for updateMessage
+ * Contains success status and optional message list
+ */
+export interface UpdateMessageResult {
+ /**
+ * Updated message list (only present when success is true and sessionId/topicId provided)
+ */
+ messages?: UIChatMessage[];
+ /**
+ * Whether the update was successful
+ */
+ success: boolean;
+}
+
export interface NewMessage {
agentId?: string | null;
clientId?: string | null;
@@ -67,12 +91,14 @@ export interface UpdateMessageParams {
imageList?: ChatImageItem[];
metadata?: MessageMetadata;
model?: string;
+ observationId?: string;
provider?: string;
reasoning?: ModelReasoning;
role?: string;
search?: GroundingSearch;
toolCalls?: MessageToolCall[];
tools?: ChatToolPayload[] | null;
+ traceId?: string;
}
export interface NewMessageQueryParams {
@@ -81,3 +107,23 @@ export interface NewMessageQueryParams {
rewriteQuery: string;
userQuery: string;
}
+
+// ========== Zod Schemas ========== //
+
+export const UpdateMessageParamsSchema = z
+ .object({
+ content: z.string().optional(),
+ error: ChatMessageErrorSchema.nullable().optional(),
+ imageList: z.array(ChatImageItemSchema).optional(),
+ metadata: MessageMetadataSchema.optional(),
+ model: z.string().optional(),
+ observationId: z.string().optional(),
+ provider: z.string().optional(),
+ reasoning: ModelReasoningSchema.optional(),
+ role: z.string().optional(),
+ search: GroundingSearchSchema.optional(),
+ toolCalls: z.array(MessageToolCallSchema).optional(),
+ tools: z.array(ChatToolPayloadSchema).nullable().optional(),
+ traceId: z.string().optional(),
+ })
+ .passthrough();
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index 86d305e8952..a3a440364e1 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -26,10 +26,11 @@ export interface ChatFileItem {
export interface AssistantContentBlock {
content: string;
- fileList?: ChatFileItem[];
+ error?: ChatMessageError | null;
id: string;
imageList?: ChatImageItem[];
performance?: ModelPerformance;
+ reasoning?: ModelReasoning;
tools?: ChatToolPayloadWithResult[];
usage?: ModelUsage;
}
@@ -62,6 +63,7 @@ export interface UIChatMessage {
imageList?: ChatImageItem[];
meta: MetaData;
metadata?: MessageMetadata | null;
+ model?: string | null;
/**
* observation id
*/
@@ -78,6 +80,7 @@ export interface UIChatMessage {
plugin?: ChatPluginPayload;
pluginError?: any;
pluginState?: any;
+ provider?: string | null;
/**
* quoted other message's id
*/
diff --git a/packages/types/src/search.ts b/packages/types/src/search.ts
index ad5958258f1..c8482ff9d08 100644
--- a/packages/types/src/search.ts
+++ b/packages/types/src/search.ts
@@ -1,3 +1,5 @@
+import { z } from 'zod';
+
export type SearchMode = 'off' | 'auto' | 'on';
export enum ModelSearchImplement {
@@ -27,3 +29,17 @@ export interface GroundingSearch {
citations?: CitationItem[];
searchQueries?: string[];
}
+
+export const GroundingSearchSchema = z.object({
+ citations: z
+ .array(
+ z.object({
+ favicon: z.string().optional(),
+ id: z.string().optional(),
+ title: z.string().optional(),
+ url: z.string(),
+ }),
+ )
+ .optional(),
+ searchQueries: z.array(z.string()).optional(),
+});
diff --git a/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/V1Mobile/index.tsx b/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/V1Mobile/index.tsx
index 017af6d73c6..9633cbbdcac 100644
--- a/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/V1Mobile/index.tsx
+++ b/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/V1Mobile/index.tsx
@@ -9,7 +9,7 @@ import { Flexbox } from 'react-layout-kit';
import { ActionKeys } from '@/features/ChatInput/ActionBar/config';
import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
import ActionBar from './ActionBar';
import Files from './Files';
@@ -37,7 +37,7 @@ const MobileChatInput = memo(() => {
const { isLoading } = useInitAgentConfig();
const [loading, value, onInput, onStop] = useChatStore((s) => [
- chatSelectors.isAIGenerating(s),
+ messageStateSelectors.isAIGenerating(s),
s.inputMessage,
s.updateInputMessage,
s.stopGenerateMessage,
diff --git a/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/V1Mobile/useSend.ts b/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/V1Mobile/useSend.ts
index 268825877c3..15b690e4fcf 100644
--- a/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/V1Mobile/useSend.ts
+++ b/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/V1Mobile/useSend.ts
@@ -6,7 +6,7 @@ import { useGeminiChineseWarning } from '@/hooks/useGeminiChineseWarning';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { chatSelectors, topicSelectors } from '@/store/chat/selectors';
+import { chatSelectors, messageStateSelectors, topicSelectors } from '@/store/chat/selectors';
import { fileChatSelectors, useFileStore } from '@/store/file';
import { getUserStoreState } from '@/store/user';
@@ -26,17 +26,19 @@ export const useSendMessage = () => {
const clearChatUploadFileList = useFileStore((s) => s.clearChatUploadFileList);
const isUploadingFiles = useFileStore(fileChatSelectors.isUploadingFiles);
- const isSendButtonDisabledByMessage = useChatStore(chatSelectors.isSendButtonDisabledByMessage);
+ const isSendButtonDisabledByMessage = useChatStore(
+ messageStateSelectors.isSendButtonDisabledByMessage,
+ );
const canSend = !isUploadingFiles && !isSendButtonDisabledByMessage;
const send = useCallback(async (params: UseSendMessageParams = {}) => {
const store = useChatStore.getState();
- if (chatSelectors.isAIGenerating(store)) return;
+ if (messageStateSelectors.isAIGenerating(store)) return;
// if uploading file or send button is disabled by message, then we should not send the message
const isUploadingFiles = fileChatSelectors.isUploadingFiles(useFileStore.getState());
- const isSendButtonDisabledByMessage = chatSelectors.isSendButtonDisabledByMessage(
+ const isSendButtonDisabledByMessage = messageStateSelectors.isSendButtonDisabledByMessage(
useChatStore.getState(),
);
diff --git a/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/useSend.ts b/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/useSend.ts
index 762c2cee9f4..a6b7a87b4d5 100644
--- a/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/useSend.ts
+++ b/src/app/[variants]/(main)/chat/(workspace)/@conversation/features/ChatInput/useSend.ts
@@ -5,7 +5,12 @@ import { useGeminiChineseWarning } from '@/hooks/useGeminiChineseWarning';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { getChatStoreState, useChatStore } from '@/store/chat';
-import { aiChatSelectors, chatSelectors, topicSelectors } from '@/store/chat/selectors';
+import {
+ aiChatSelectors,
+ chatSelectors,
+ messageStateSelectors,
+ topicSelectors,
+} from '@/store/chat/selectors';
import { fileChatSelectors, useFileStore } from '@/store/file';
import { mentionSelectors, useMentionStore } from '@/store/mention';
import { useSessionStore } from '@/store/session';
@@ -38,8 +43,8 @@ export const useSend = () => {
s.addAIMessage,
s.stopGenerateMessage,
s.cancelSendMessageInServer,
- chatSelectors.isAIGenerating(s),
- chatSelectors.isSendButtonDisabledByMessage(s),
+ messageStateSelectors.isAIGenerating(s),
+ messageStateSelectors.isSendButtonDisabledByMessage(s),
aiChatSelectors.isCurrentSendMessageLoading(s),
]);
const { analytics } = useAnalytics();
@@ -68,7 +73,7 @@ export const useSend = () => {
return;
}
- if (chatSelectors.isAIGenerating(store)) return;
+ if (messageStateSelectors.isAIGenerating(store)) return;
const inputMessage = store.inputMessage;
// 发送时再取一次最新的文件列表,防止闭包拿到旧值
@@ -127,7 +132,7 @@ export const useSend = () => {
const stop = () => {
const store = getChatStoreState();
- const generating = chatSelectors.isAIGenerating(store);
+ const generating = messageStateSelectors.isAIGenerating(store);
if (generating) {
stopGenerateMessage();
@@ -165,8 +170,8 @@ export const useSendGroupMessage = () => {
s.sendGroupMessage,
s.updateInputMessage,
s.stopGenerateMessage,
- chatSelectors.isSendButtonDisabledByMessage(s),
- chatSelectors.isCreatingMessage(s),
+ messageStateSelectors.isSendButtonDisabledByMessage(s),
+ messageStateSelectors.isCreatingMessage(s),
]);
const isSupervisorThinking = useChatStore((s) =>
@@ -205,7 +210,7 @@ export const useSendGroupMessage = () => {
if (
chatSelectors.isSupervisorLoading(store.activeId)(store) ||
- chatSelectors.isCreatingMessage(store)
+ messageStateSelectors.isCreatingMessage(store)
)
return;
@@ -287,8 +292,8 @@ export const useSendGroupMessage = () => {
const stop = useCallback(() => {
const store = getChatStoreState();
- const isAgentGenerating = chatSelectors.isAIGenerating(store);
- const isCreating = chatSelectors.isCreatingMessage(store);
+ const isAgentGenerating = messageStateSelectors.isAIGenerating(store);
+ const isCreating = messageStateSelectors.isCreatingMessage(store);
if (isAgentGenerating) {
stopGenerateMessage();
diff --git a/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/index.tsx b/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/index.tsx
index 31961751008..45e8fc65ca0 100644
--- a/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/index.tsx
+++ b/src/app/[variants]/(main)/chat/@session/features/SessionListContent/List/Item/index.tsx
@@ -8,7 +8,7 @@ import { isDesktop } from '@/const/version';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
import { useSessionStore } from '@/store/session';
import { sessionHelpers } from '@/store/session/helpers';
@@ -33,7 +33,9 @@ const SessionItem = memo<SessionItemProps>(({ id }) => {
const openSessionInNewWindow = useGlobalStore((s) => s.openSessionInNewWindow);
const [active] = useSessionStore((s) => [s.activeId === id]);
- const [loading] = useChatStore((s) => [chatSelectors.isAIGenerating(s) && id === s.activeId]);
+ const [loading] = useChatStore((s) => [
+ messageStateSelectors.isAIGenerating(s) && id === s.activeId,
+ ]);
const [pin, title, avatar, avatarBackground, updateAt, members, model, group, sessionType] =
useSessionStore((s) => {
diff --git a/src/components/Thinking/index.tsx b/src/components/Thinking/index.tsx
index cc4e5085cf4..4ff7c3df030 100644
--- a/src/components/Thinking/index.tsx
+++ b/src/components/Thinking/index.tsx
@@ -1,8 +1,8 @@
import { ChatCitationItem } from '@lobechat/types';
-import { ActionIcon, CopyButton, Icon, Markdown, ScrollShadow } from '@lobehub/ui';
+import { CopyButton, Icon, Markdown, ScrollShadow } from '@lobehub/ui';
import { createStyles } from 'antd-style';
import { AnimatePresence, motion } from 'framer-motion';
-import { AtomIcon, ChevronDown, ChevronRight } from 'lucide-react';
+import { AtomIcon } from 'lucide-react';
import { rgba } from 'polished';
import { CSSProperties, RefObject, memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -24,8 +24,10 @@ const useStyles = createStyles(({ css, token }) => ({
color: ${token.colorTextTertiary};
`,
header: css`
+ min-height: 32px;
padding-block: 4px;
padding-inline: 8px 4px;
+
transition: background 0.2s ${token.motionEaseOut};
transition: all 0.2s ${token.motionEaseOut};
@@ -165,7 +167,6 @@ const Thinking = memo<ThinkingProps>((props) => {
<CopyButton content={content} size={'small'} title={t('copy', { ns: 'common' })} />
</div>
)}
- <ActionIcon icon={showDetail ? ChevronDown : ChevronRight} size={'small'} />
</Flexbox>
</Flexbox>
<AnimatePresence initial={false}>
diff --git a/src/features/AgentSetting/AgentPlugin/index.tsx b/src/features/AgentSetting/AgentPlugin/index.tsx
index c7f89268e3c..c4b21f0c0c3 100644
--- a/src/features/AgentSetting/AgentPlugin/index.tsx
+++ b/src/features/AgentSetting/AgentPlugin/index.tsx
@@ -34,8 +34,8 @@ const AgentPlugin = memo(() => {
s.toggleAgentPlugin,
]);
- const { showDalle, showMarket } = useServerConfigStore(featureFlagsSelectors);
- const installedPlugins = useToolStore(toolSelectors.metaList(showDalle), isEqual);
+ const { showMarket } = useServerConfigStore(featureFlagsSelectors);
+ const installedPlugins = useToolStore(toolSelectors.metaList, isEqual);
const { isLoading } = useFetchInstalledPlugins();
diff --git a/src/features/ChatInput/ActionBar/STT/browser.tsx b/src/features/ChatInput/ActionBar/STT/browser.tsx
index 3bdf7240e60..129e1d1c960 100644
--- a/src/features/ChatInput/ActionBar/STT/browser.tsx
+++ b/src/features/ChatInput/ActionBar/STT/browser.tsx
@@ -8,7 +8,7 @@ import { SWRConfiguration } from 'swr';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/slices/chat';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
@@ -43,7 +43,7 @@ const BrowserSTT = memo<{ mobile?: boolean }>(({ mobile }) => {
const { t } = useTranslation('chat');
const [loading, updateInputMessage] = useChatStore((s) => [
- chatSelectors.isAIGenerating(s),
+ messageStateSelectors.isAIGenerating(s),
s.updateInputMessage,
]);
diff --git a/src/features/ChatInput/ActionBar/STT/openai.tsx b/src/features/ChatInput/ActionBar/STT/openai.tsx
index b7a50acc729..f2c3b469b6e 100644
--- a/src/features/ChatInput/ActionBar/STT/openai.tsx
+++ b/src/features/ChatInput/ActionBar/STT/openai.tsx
@@ -11,7 +11,7 @@ import { API_ENDPOINTS } from '@/services/_url';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/slices/message/selectors';
+import { messageStateSelectors } from '@/store/chat/slices/message/selectors';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
@@ -54,7 +54,7 @@ const OpenaiSTT = memo<{ mobile?: boolean }>(({ mobile }) => {
const { t } = useTranslation('chat');
const [loading, updateInputMessage] = useChatStore((s) => [
- chatSelectors.isAIGenerating(s),
+ messageStateSelectors.isAIGenerating(s),
s.updateInputMessage,
]);
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index 79b3480cb72..87708fd54c4 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -9,7 +9,6 @@ import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useToolStore } from '@/store/tool';
import { builtinToolSelectors, pluginSelectors } from '@/store/tool/selectors';
@@ -24,12 +23,11 @@ export const useControls = ({
}) => {
const { t } = useTranslation('setting');
const list = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
- const { showDalle } = useServerConfigStore(featureFlagsSelectors);
const [checked, togglePlugin] = useAgentStore((s) => [
agentSelectors.currentAgentPlugins(s),
s.togglePlugin,
]);
- const builtinList = useToolStore(builtinToolSelectors.metaList(showDalle), isEqual);
+ const builtinList = useToolStore(builtinToolSelectors.metaList, isEqual);
const enablePluginCount = useAgentStore(
(s) =>
agentSelectors
diff --git a/src/features/Conversation/Error/ErrorJsonViewer.tsx b/src/features/Conversation/Error/ErrorJsonViewer.tsx
index 347f9767de5..81db2fee95a 100644
--- a/src/features/Conversation/Error/ErrorJsonViewer.tsx
+++ b/src/features/Conversation/Error/ErrorJsonViewer.tsx
@@ -4,18 +4,19 @@ import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
interface ErrorJSONViewerProps {
+ block?: boolean;
error?: ChatMessageError | null;
id: string;
}
-const ErrorJsonViewer = memo<ErrorJSONViewerProps>(({ error, id }) => {
+const ErrorJsonViewer = memo<ErrorJSONViewerProps>(({ error, id, block }) => {
const errorBody = error?.body || error;
if (!errorBody) return;
return (
- <Flexbox id={id} style={{ maxWidth: 600 }}>
- <Highlighter actionIconSize={'small'} language={'json'}>
+ <Flexbox id={id} style={{ maxWidth: block ? '100%' : 600, width: block ? '100%' : undefined }}>
+ <Highlighter actionIconSize={'small'} language={'json'} wrap>
{JSON.stringify(errorBody, null, 2)}
</Highlighter>
</Flexbox>
diff --git a/src/features/Conversation/Error/OllamaBizError/index.tsx b/src/features/Conversation/Error/OllamaBizError/index.tsx
index 09916bab9ac..ef6748731d7 100644
--- a/src/features/Conversation/Error/OllamaBizError/index.tsx
+++ b/src/features/Conversation/Error/OllamaBizError/index.tsx
@@ -1,4 +1,4 @@
-import { UIChatMessage } from '@lobechat/types';
+import { ChatMessageError } from '@lobechat/types';
import { Skeleton } from 'antd';
import dynamic from 'next/dynamic';
import { memo } from 'react';
@@ -24,7 +24,12 @@ interface OllamaErrorResponse {
const UNRESOLVED_MODEL_REGEXP = /model "([\w+,-_]+)" not found/;
-const OllamaBizError = memo<UIChatMessage>(({ error, id }) => {
+interface OllamaBizErrorProps {
+ error?: ChatMessageError | null;
+ id: string;
+}
+
+const OllamaBizError = memo<OllamaBizErrorProps>(({ error, id }) => {
const errorBody: OllamaErrorResponse = (error as any)?.body;
const errorMessage = errorBody.error?.message;
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index c37c2102c7f..7dfa84eb059 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -1,5 +1,5 @@
import { AgentRuntimeErrorType, ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';
-import { ChatErrorType, ChatMessageError, ErrorType, UIChatMessage } from '@lobechat/types';
+import { ChatErrorType, ChatMessageError, ErrorType } from '@lobechat/types';
import { IPluginErrorType } from '@lobehub/chat-plugin-sdk';
import type { AlertProps } from '@lobehub/ui';
import { Skeleton } from 'antd';
@@ -15,6 +15,11 @@ import ErrorJsonViewer from './ErrorJsonViewer';
import InvalidAccessCode from './InvalidAccessCode';
import { ErrorActionContainer } from './style';
+interface ErrorMessageData {
+ error?: ChatMessageError | null;
+ id: string;
+}
+
const loading = () => <Skeleton active />;
const OllamaBizError = dynamic(() => import('./OllamaBizError'), { loading, ssr: false });
@@ -87,7 +92,12 @@ export const useErrorContent = (error: any) => {
}, [error]);
};
-const ErrorMessageExtra = memo<{ data: UIChatMessage }>(({ data }) => {
+interface ErrorExtraProps {
+ block?: boolean;
+ data: ErrorMessageData;
+}
+
+const ErrorMessageExtra = memo<ErrorExtraProps>(({ data, block }) => {
const error = data.error as ChatMessageError;
if (!error?.type) return;
@@ -123,10 +133,10 @@ const ErrorMessageExtra = memo<{ data: UIChatMessage }>(({ data }) => {
return <ChatInvalidAPIKey id={data.id} provider={data.error?.body?.provider} />;
}
- return <ErrorJsonViewer error={data.error} id={data.id} />;
+ return <ErrorJsonViewer block={block} error={data.error} id={data.id} />;
});
-export default memo<{ data: UIChatMessage }>(({ data }) => (
+export default memo<ErrorExtraProps>(({ data, block }) => (
<Suspense
fallback={
<ErrorActionContainer>
@@ -134,6 +144,6 @@ export default memo<{ data: UIChatMessage }>(({ data }) => (
</ErrorActionContainer>
}
>
- <ErrorMessageExtra data={data} />
+ <ErrorMessageExtra block={block} data={data} />
</Suspense>
));
diff --git a/src/features/Conversation/MarkdownElements/LobeArtifact/Render/index.tsx b/src/features/Conversation/MarkdownElements/LobeArtifact/Render/index.tsx
index f9a6b387f24..8b70b1c5689 100644
--- a/src/features/Conversation/MarkdownElements/LobeArtifact/Render/index.tsx
+++ b/src/features/Conversation/MarkdownElements/LobeArtifact/Render/index.tsx
@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';
import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors, chatSelectors } from '@/store/chat/selectors';
+import { chatPortalSelectors, messageStateSelectors } from '@/store/chat/selectors';
import { dotLoading } from '@/styles/loading';
import { InPortalThreadContext } from '../../../context/InPortalThreadContext';
@@ -66,7 +66,7 @@ const Render = memo<ArtifactProps>(({ identifier, title, type, language, childre
const { message } = App.useApp();
const [isGenerating, isArtifactTagClosed, openArtifact, closeArtifact] = useChatStore((s) => {
return [
- chatSelectors.isMessageGenerating(id)(s),
+ messageStateSelectors.isMessageGenerating(id)(s),
chatPortalSelectors.isArtifactTagClosed(id)(s),
s.openArtifact,
s.closeArtifact,
diff --git a/src/features/Conversation/Messages/Assistant/Extra/index.tsx b/src/features/Conversation/Messages/Assistant/Extra/index.tsx
index 87e7da64cd3..ca609ceb843 100644
--- a/src/features/Conversation/Messages/Assistant/Extra/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/Extra/index.tsx
@@ -8,7 +8,7 @@ import TTS from '@/features/Conversation/components/Extras/TTS';
import Translate from '@/features/Conversation/components/Extras/Translate';
import Usage from '@/features/Conversation/components/Extras/Usage';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
interface AssistantMessageExtraProps {
content: string;
@@ -20,7 +20,7 @@ interface AssistantMessageExtraProps {
export const AssistantMessageExtra = memo<AssistantMessageExtraProps>(
({ extra, id, content, metadata, tools }) => {
- const loading = useChatStore(chatSelectors.isMessageGenerating(id));
+ const loading = useChatStore(messageStateSelectors.isMessageGenerating(id));
return (
<Flexbox gap={8} style={{ marginTop: !!tools?.length ? 8 : 4 }}>
diff --git a/src/features/Conversation/Messages/Assistant/MessageContent.tsx b/src/features/Conversation/Messages/Assistant/MessageContent.tsx
index 5d8606a9ec7..45fcbe846b3 100644
--- a/src/features/Conversation/Messages/Assistant/MessageContent.tsx
+++ b/src/features/Conversation/Messages/Assistant/MessageContent.tsx
@@ -4,7 +4,7 @@ import { ReactNode, memo } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useChatStore } from '@/store/chat';
-import { aiChatSelectors, chatSelectors } from '@/store/chat/selectors';
+import { aiChatSelectors, messageStateSelectors } from '@/store/chat/selectors';
import { DefaultMessage } from '../Default';
import ImageFileListViewer from '../User/ImageFileListViewer';
@@ -19,8 +19,10 @@ export const AssistantMessageContent = memo<
editableContent: ReactNode;
}
>(({ id, tools, content, chunksList, search, imageList, ...props }) => {
- const editing = useChatStore(chatSelectors.isMessageEditing(id));
- const generating = useChatStore(chatSelectors.isMessageGenerating(id));
+ const [editing, generating] = useChatStore((s) => [
+ messageStateSelectors.isMessageEditing(id)(s),
+ messageStateSelectors.isMessageGenerating(id)(s),
+ ]);
const isToolCallGenerating = generating && (content === LOADING_FLAT || !content) && !!tools;
diff --git a/src/features/Conversation/Messages/Assistant/Tool/Inspector/BuiltinPluginTitle.tsx b/src/features/Conversation/Messages/Assistant/Tool/Inspector/BuiltinPluginTitle.tsx
index a28f72b2a07..75b723def81 100644
--- a/src/features/Conversation/Messages/Assistant/Tool/Inspector/BuiltinPluginTitle.tsx
+++ b/src/features/Conversation/Messages/Assistant/Tool/Inspector/BuiltinPluginTitle.tsx
@@ -5,7 +5,7 @@ import { ReactNode, memo } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
import { shinyTextStylish } from '@/styles/loading';
export const useStyles = createStyles(({ css, token }) => ({
@@ -38,7 +38,7 @@ const BuiltinPluginTitle = memo<BuiltinPluginTitleProps>(
const { styles } = useStyles();
const isLoading = useChatStore(
- chatSelectors.isToolApiNameShining(messageId, index, toolCallId),
+ messageStateSelectors.isToolApiNameShining(messageId, index, toolCallId),
);
return (
diff --git a/src/features/Conversation/Messages/Assistant/Tool/Inspector/ToolTitle.tsx b/src/features/Conversation/Messages/Assistant/Tool/Inspector/ToolTitle.tsx
index dc6e25d9714..11e48885d8d 100644
--- a/src/features/Conversation/Messages/Assistant/Tool/Inspector/ToolTitle.tsx
+++ b/src/features/Conversation/Messages/Assistant/Tool/Inspector/ToolTitle.tsx
@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
import { pluginHelpers, useToolStore } from '@/store/tool';
import { toolSelectors } from '@/store/tool/selectors';
import { shinyTextStylish } from '@/styles/loading';
@@ -43,7 +43,9 @@ const ToolTitle = memo<ToolTitleProps>(({ identifier, messageId, index, apiName,
const { t } = useTranslation('plugin');
const { styles } = useStyles();
- const isLoading = useChatStore(chatSelectors.isToolApiNameShining(messageId, index, toolCallId));
+ const isLoading = useChatStore(
+ messageStateSelectors.isToolApiNameShining(messageId, index, toolCallId),
+ );
const pluginMeta = useToolStore(toolSelectors.getMetaById(identifier), isEqual);
diff --git a/src/features/Conversation/Messages/Assistant/Tool/Render/CustomRender.tsx b/src/features/Conversation/Messages/Assistant/Tool/Render/CustomRender.tsx
index b8871d8f6d5..becbb080e49 100644
--- a/src/features/Conversation/Messages/Assistant/Tool/Render/CustomRender.tsx
+++ b/src/features/Conversation/Messages/Assistant/Tool/Render/CustomRender.tsx
@@ -10,7 +10,7 @@ import { Flexbox } from 'react-layout-kit';
import PluginResult from '@/features/Conversation/Messages/Assistant/Tool/Inspector/PluginResult';
import PluginRender from '@/features/PluginsUI/Render';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
import Arguments from './Arguments';
import KeyValueEditor from './KeyValueEditor';
@@ -43,7 +43,7 @@ const CustomRender = memo<CustomRenderProps>(
tool_call_id,
}) => {
const { t } = useTranslation(['tool', 'common']);
- const [loading] = useChatStore((s) => [chatSelectors.isPluginApiInvoking(id)(s)]);
+ const [loading] = useChatStore((s) => [messageStateSelectors.isPluginApiInvoking(id)(s)]);
const [isEditing, setIsEditing] = useState(false);
const { message } = App.useApp();
const [updatePluginArguments, reInvokeToolMessage] = useChatStore((s) => [
diff --git a/src/features/Conversation/Messages/Assistant/Tool/Render/index.tsx b/src/features/Conversation/Messages/Assistant/Tool/Render/index.tsx
index 945b240caf2..12a47917341 100644
--- a/src/features/Conversation/Messages/Assistant/Tool/Render/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/Tool/Render/index.tsx
@@ -3,7 +3,7 @@ import isEqual from 'fast-deep-equal';
import { Suspense, memo } from 'react';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { chatSelectors, messageStateSelectors } from '@/store/chat/selectors';
import CustomRender from './CustomRender';
import ErrorResponse from './ErrorResponse';
@@ -31,7 +31,7 @@ const Render = memo<RenderProps>(
identifier,
apiName,
}) => {
- const loading = useChatStore(chatSelectors.isToolCallStreaming(messageId, toolIndex));
+ const loading = useChatStore(messageStateSelectors.isToolCallStreaming(messageId, toolIndex));
const toolMessage = useChatStore(chatSelectors.getMessageByToolCallId(toolCallId), isEqual);
if (loading || !toolMessage) return null;
diff --git a/src/features/Conversation/Messages/Assistant/Tool/index.tsx b/src/features/Conversation/Messages/Assistant/Tool/index.tsx
index 3d50e15f121..a4c21d0ffc7 100644
--- a/src/features/Conversation/Messages/Assistant/Tool/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/Tool/index.tsx
@@ -3,7 +3,7 @@ import { Flexbox } from 'react-layout-kit';
import AnimatedCollapsed from '@/components/AnimatedCollapsed';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
import Inspectors from './Inspector';
import Render from './Render';
@@ -24,7 +24,7 @@ const Tool = memo<InspectorProps>(
({ arguments: requestArgs, apiName, messageId, id, index, identifier, style, payload, type }) => {
const [showDetail, setShowDetail] = useState(type !== 'mcp');
const [showPluginRender, setShowPluginRender] = useState(false);
- const isLoading = useChatStore(chatSelectors.isInToolsCalling(messageId, index));
+ const isLoading = useChatStore(messageStateSelectors.isInToolsCalling(messageId, index));
useEffect(() => {
if (type !== 'mcp') return;
diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsx
index f1283a27ff5..b6e2e7ce70e 100644
--- a/src/features/Conversation/Messages/Assistant/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/index.tsx
@@ -19,7 +19,7 @@ import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
import { useAgentStore } from '@/store/agent';
import { agentChatConfigSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/slices/message/selectors';
import { chatGroupSelectors, useChatGroupStore } from '@/store/chatGroup';
import { useGlobalStore } from '@/store/global';
import { useSessionStore } from '@/store/session';
@@ -81,9 +81,9 @@ const AssistantMessage = memo<AssistantMessageProps>((props) => {
);
const [generating, isInRAGFlow, editing] = useChatStore((s) => [
- chatSelectors.isMessageGenerating(id)(s),
- chatSelectors.isMessageInRAGFlow(id)(s),
- chatSelectors.isMessageEditing(id)(s),
+ messageStateSelectors.isMessageGenerating(id)(s),
+ messageStateSelectors.isMessageInRAGFlow(id)(s),
+ messageStateSelectors.isMessageEditing(id)(s),
]);
const { styles } = useStyles({
diff --git a/src/features/Conversation/Messages/Default.tsx b/src/features/Conversation/Messages/Default.tsx
index 86cab134d90..b78b94d6472 100644
--- a/src/features/Conversation/Messages/Default.tsx
+++ b/src/features/Conversation/Messages/Default.tsx
@@ -4,7 +4,7 @@ import { ReactNode, memo } from 'react';
import BubblesLoading from '@/components/BubblesLoading';
import { LOADING_FLAT } from '@/const/message';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
export const DefaultMessage = memo<
UIChatMessage & {
@@ -13,7 +13,7 @@ export const DefaultMessage = memo<
isToolCallGenerating?: boolean;
}
>(({ id, editableContent, content, isToolCallGenerating, addIdOnDOM = true }) => {
- const editing = useChatStore(chatSelectors.isMessageEditing(id));
+ const editing = useChatStore(messageStateSelectors.isMessageEditing(id));
if (isToolCallGenerating) return;
diff --git a/src/features/Conversation/Messages/User/Extra.tsx b/src/features/Conversation/Messages/User/Extra.tsx
index 25c03baf791..1fd91426a86 100644
--- a/src/features/Conversation/Messages/User/Extra.tsx
+++ b/src/features/Conversation/Messages/User/Extra.tsx
@@ -5,7 +5,7 @@ import ExtraContainer from '@/features/Conversation/components/Extras/ExtraConta
import TTS from '@/features/Conversation/components/Extras/TTS';
import Translate from '@/features/Conversation/components/Extras/Translate';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
interface UserMessageExtraProps {
content: string;
@@ -13,7 +13,7 @@ interface UserMessageExtraProps {
id: string;
}
export const UserMessageExtra = memo<UserMessageExtraProps>(({ extra, id, content }) => {
- const loading = useChatStore(chatSelectors.isMessageGenerating(id));
+ const loading = useChatStore(messageStateSelectors.isMessageGenerating(id));
const showTranslate = !!extra?.translate;
const showTTS = !!extra?.tts;
diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsx
index c4df9b988ee..480f2f99afa 100644
--- a/src/features/Conversation/Messages/User/index.tsx
+++ b/src/features/Conversation/Messages/User/index.tsx
@@ -15,7 +15,7 @@ import { useUserAvatar } from '@/hooks/useUserAvatar';
import { useAgentStore } from '@/store/agent';
import { agentChatConfigSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors } from '@/store/chat/selectors';
import { useSessionStore } from '@/store/session';
import { sessionSelectors } from '@/store/session/selectors';
import { useUserStore } from '@/store/user';
@@ -55,9 +55,9 @@ const UserMessage = memo<UserMessageProps>((props) => {
const displayMode = useAgentStore(agentChatConfigSelectors.displayMode);
const [editing, generating, isInRAGFlow] = useChatStore((s) => [
- chatSelectors.isMessageEditing(id)(s),
- chatSelectors.isMessageGenerating(id)(s),
- chatSelectors.isMessageInRAGFlow(id)(s),
+ messageStateSelectors.isMessageEditing(id)(s),
+ messageStateSelectors.isMessageGenerating(id)(s),
+ messageStateSelectors.isMessageInRAGFlow(id)(s),
]);
const loading = isInRAGFlow || generating;
diff --git a/src/features/Conversation/Messages/index.tsx b/src/features/Conversation/Messages/index.tsx
index 166d8904aaf..c0e0c28755c 100644
--- a/src/features/Conversation/Messages/index.tsx
+++ b/src/features/Conversation/Messages/index.tsx
@@ -1,17 +1,17 @@
'use client';
+import { isDesktop } from '@lobechat/const';
import { createStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
import { ReactNode, memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { Flexbox } from 'react-layout-kit';
-import { isDesktop } from '@/const/version';
import {
removeVirtuosoVisibleItem,
upsertVirtuosoVisibleItem,
} from '@/features/Conversation/components/VirtualizedList/VirtuosoContext';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { chatSelectors, messageStateSelectors } from '@/store/chat/selectors';
import History from '../components/History';
import { InPortalThreadContext } from '../context/InPortalThreadContext';
@@ -57,7 +57,7 @@ const Item = memo<ChatListItemProps>(
const item = useChatStore(chatSelectors.getMessageById(id), isEqual);
- const [isMessageLoading] = useChatStore((s) => [chatSelectors.isMessageLoading(id)(s)]);
+ const [isMessageLoading] = useChatStore((s) => [messageStateSelectors.isMessageLoading(id)(s)]);
// ======================= Performance Optimization ======================= //
// these useMemo/useCallback are all for the performance optimization
diff --git a/src/features/Conversation/components/AutoScroll.tsx b/src/features/Conversation/components/AutoScroll.tsx
index 228af814fff..794061b2cc2 100644
--- a/src/features/Conversation/components/AutoScroll.tsx
+++ b/src/features/Conversation/components/AutoScroll.tsx
@@ -1,7 +1,7 @@
import { memo, useEffect } from 'react';
import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
+import { chatSelectors, messageStateSelectors } from '@/store/chat/selectors';
import BackBottom from './BackBottom';
@@ -11,7 +11,7 @@ interface AutoScrollProps {
onScrollToBottom: (type: 'auto' | 'click') => void;
}
const AutoScroll = memo<AutoScrollProps>(({ atBottom, isScrolling, onScrollToBottom }) => {
- const trackVisibility = useChatStore(chatSelectors.isAIGenerating);
+ const trackVisibility = useChatStore(messageStateSelectors.isAIGenerating);
const str = useChatStore(chatSelectors.mainAIChatsMessageString);
const reasoningStr = useChatStore(chatSelectors.mainAILatestMessageReasoningContent);
diff --git a/src/features/Conversation/components/Extras/Usage/UsageDetail/index.tsx b/src/features/Conversation/components/Extras/Usage/UsageDetail/index.tsx
index d02c4538b49..687a370735e 100644
--- a/src/features/Conversation/components/Extras/Usage/UsageDetail/index.tsx
+++ b/src/features/Conversation/components/Extras/Usage/UsageDetail/index.tsx
@@ -11,7 +11,7 @@ import InfoTooltip from '@/components/InfoTooltip';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-import { formatNumber } from '@/utils/format';
+import { formatNumber, formatShortenNumber } from '@/utils/format';
import ModelCard from './ModelCard';
import TokenProgress, { TokenProgressItem } from './TokenProgress';
@@ -111,10 +111,13 @@ const TokenDetail = memo<TokenDetailProps>(({ meta, model, provider }) => {
},
].filter(Boolean) as TokenProgressItem[];
- const displayTotal =
+ const totalCount =
isShowCredit && !!detailTokens.totalTokens
- ? formatNumber(detailTokens.totalTokens.credit)
- : formatNumber(detailTokens.totalTokens!.token);
+ ? detailTokens.totalTokens.credit
+ : detailTokens.totalTokens!.token;
+
+ const shortTotal = (formatShortenNumber(totalCount) as string).toLowerCase?.();
+ const detailTotal = formatNumber(totalCount);
const averagePricing = formatNumber(
detailTokens.totalTokens!.credit / detailTokens.totalTokens!.token,
@@ -171,7 +174,7 @@ const TokenDetail = memo<TokenDetailProps>(({ meta, model, provider }) => {
<div style={{ color: theme.colorTextSecondary }}>
{t('messages.tokenDetails.total')}
</div>
- <div style={{ fontWeight: 500 }}>{displayTotal}</div>
+ <div style={{ fontWeight: 500 }}>{detailTotal}</div>
</Flexbox>
{isShowCredit && (
<Flexbox align={'center'} gap={4} horizontal justify={'space-between'}>
@@ -212,7 +215,7 @@ const TokenDetail = memo<TokenDetailProps>(({ meta, model, provider }) => {
>
<Center gap={2} horizontal style={{ cursor: 'default' }}>
<Icon icon={isShowCredit ? BadgeCent : CoinsIcon} />
- {displayTotal}
+ {shortTotal}
</Center>
</Popover>
);
diff --git a/src/features/PluginTag/index.tsx b/src/features/PluginTag/index.tsx
index bcade81293c..e4a11d49004 100644
--- a/src/features/PluginTag/index.tsx
+++ b/src/features/PluginTag/index.tsx
@@ -7,7 +7,6 @@ import { memo } from 'react';
import { Center } from 'react-layout-kit';
import Avatar from '@/components/Plugins/PluginAvatar';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { pluginHelpers, useToolStore } from '@/store/tool';
import { toolSelectors } from '@/store/tool/selectors';
@@ -18,8 +17,7 @@ export interface PluginTagProps {
}
const PluginTag = memo<PluginTagProps>(({ plugins }) => {
- const { showDalle } = useServerConfigStore(featureFlagsSelectors);
- const list = useToolStore(toolSelectors.metaList(showDalle), isEqual);
+ const list = useToolStore(toolSelectors.metaList, isEqual);
const displayPlugin = useToolStore(toolSelectors.getMetaById(plugins[0]), isEqual);
diff --git a/src/features/PluginsUI/Render/BuiltinType/index.test.tsx b/src/features/PluginsUI/Render/BuiltinType/index.test.tsx
index e2a18498993..ab9a74baacf 100644
--- a/src/features/PluginsUI/Render/BuiltinType/index.test.tsx
+++ b/src/features/PluginsUI/Render/BuiltinType/index.test.tsx
@@ -1,22 +1,19 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import { DalleManifest } from '@/tools/dalle';
-import { BuiltinToolsRenders } from '@/tools/renders';
-
import BuiltinType from './index';
-// Mock Render component and useParseContent hook
+// Mock renders module
vi.mock('@/tools/renders', () => ({
BuiltinToolsRenders: {
- dalle3: vi.fn(() => <div>Test Renderer</div>),
- [DalleManifest.identifier]: vi.fn(() => <div>{DalleManifest.identifier}</div>),
+ 'lobe-web-browsing': vi.fn(({ content }) => <div>WebBrowsingRender: {content}</div>),
+ 'lobe-code-interpreter': vi.fn(({ content }) => <div>CodeInterpreterRender: {content}</div>),
},
}));
-// Mock Loading component
-vi.mock('../Loading', () => ({
- default: vi.fn(() => <div>Loading...</div>),
+// Mock useParseContent hook
+vi.mock('../useParseContent', () => ({
+ useParseContent: vi.fn((content) => ({ data: content })),
}));
describe('BuiltinType', () => {
@@ -25,29 +22,41 @@ describe('BuiltinType', () => {
expect(container).toBeEmptyDOMElement();
});
- it('should not render anything if content is not JSON and no identifier', () => {
- const { container } = render(<BuiltinType content="..." id="123" />);
- expect(container).toBeEmptyDOMElement();
- });
-
it('should not render anything if identifier is unknown', () => {
const { container } = render(<BuiltinType content="{}" id="123" identifier="unknown" />);
expect(container).toBeEmptyDOMElement();
});
- describe('DALL·E', () => {
- it('should render the correct renderer if identifier is dalle3', () => {
- render(<BuiltinType content='{"some":"data"}' id="123" identifier="dalle3" />);
- expect(BuiltinToolsRenders.dalle3).toHaveBeenCalled();
- expect(screen.getByText('Test Renderer')).toBeInTheDocument();
- });
-
- it('should render the correct renderer if is DALL·E ', () => {
- render(
- <BuiltinType content='{"some":"data"}' id="123" identifier={DalleManifest.identifier} />,
- );
- expect(BuiltinToolsRenders.dalle3).toHaveBeenCalled();
- expect(screen.getByText(DalleManifest.identifier)).toBeInTheDocument();
- });
+ it('should render the correct renderer for web browsing', () => {
+ const content = '{"query":"test"}';
+ render(<BuiltinType content={content} id="123" identifier="lobe-web-browsing" />);
+ expect(screen.getByText(`WebBrowsingRender: ${content}`)).toBeInTheDocument();
+ });
+
+ it('should render the correct renderer for code interpreter', () => {
+ const content = '{"code":"print(1)"}';
+ render(<BuiltinType content={content} id="123" identifier="lobe-code-interpreter" />);
+ expect(screen.getByText(`CodeInterpreterRender: ${content}`)).toBeInTheDocument();
+ });
+
+ it('should pass correct props to renderer', () => {
+ const content = '{"test":"data"}';
+ const args = '{"arg":"value"}';
+ const pluginState = { state: 'value' };
+ const pluginError = { error: 'test' };
+
+ render(
+ <BuiltinType
+ content={content}
+ id="msg-123"
+ identifier="lobe-web-browsing"
+ arguments={args}
+ pluginState={pluginState}
+ pluginError={pluginError}
+ apiName="testApi"
+ />,
+ );
+
+ expect(screen.getByText(`WebBrowsingRender: ${content}`)).toBeInTheDocument();
});
});
diff --git a/src/features/Portal/Artifacts/Body/index.tsx b/src/features/Portal/Artifacts/Body/index.tsx
index 30b67c2b950..3f2824577d1 100644
--- a/src/features/Portal/Artifacts/Body/index.tsx
+++ b/src/features/Portal/Artifacts/Body/index.tsx
@@ -3,7 +3,7 @@ import { memo, useEffect, useMemo } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors, chatSelectors } from '@/store/chat/selectors';
+import { chatPortalSelectors, messageStateSelectors } from '@/store/chat/selectors';
import { ArtifactDisplayMode } from '@/store/chat/slices/portal/initialState';
import { ArtifactType } from '@/types/artifact';
@@ -24,7 +24,7 @@ const ArtifactsUI = memo(() => {
return [
messageId,
s.portalArtifactDisplayMode,
- chatSelectors.isMessageGenerating(messageId)(s),
+ messageStateSelectors.isMessageGenerating(messageId)(s),
chatPortalSelectors.artifactType(s),
chatPortalSelectors.artifactCode(messageId)(s),
chatPortalSelectors.artifactCodeLanguage(s),
diff --git a/src/server/modules/ModelRuntime/trace.ts b/src/server/modules/ModelRuntime/trace.ts
index 6ee18e7e0c2..d176beb17a7 100644
--- a/src/server/modules/ModelRuntime/trace.ts
+++ b/src/server/modules/ModelRuntime/trace.ts
@@ -42,6 +42,16 @@ export const createTraceOptions = (
startTime: new Date(),
});
+ const headers = new Headers();
+
+ if (trace?.id) {
+ headers.set(LOBE_CHAT_TRACE_ID, trace.id);
+ }
+
+ if (generation?.id) {
+ headers.set(LOBE_CHAT_OBSERVATION_ID, generation.id);
+ }
+
return {
callback: {
onCompletion: async ({ text, thinking, usage, grounding, toolsCalling }) => {
@@ -94,9 +104,6 @@ export const createTraceOptions = (
});
},
} as ChatStreamCallbacks,
- headers: {
- [LOBE_CHAT_OBSERVATION_ID]: generation?.id,
- [LOBE_CHAT_TRACE_ID]: trace?.id,
- },
+ headers: headers,
};
};
diff --git a/src/server/routers/lambda/message.ts b/src/server/routers/lambda/message.ts
index 40d4783f028..02a82b72e79 100644
--- a/src/server/routers/lambda/message.ts
+++ b/src/server/routers/lambda/message.ts
@@ -1,4 +1,9 @@
-import { BatchTaskResult, UIChatMessage, UpdateMessageRAGParamsSchema } from '@lobechat/types';
+import {
+ BatchTaskResult,
+ UIChatMessage,
+ UpdateMessageParamsSchema,
+ UpdateMessageRAGParamsSchema,
+} from '@lobechat/types';
import { z } from 'zod';
import { MessageModel } from '@/database/models/message';
@@ -180,11 +185,17 @@ export const messageRouter = router({
.input(
z.object({
id: z.string(),
- value: z.object({}).passthrough().partial(),
+ sessionId: z.string().nullable().optional(),
+ topicId: z.string().nullable().optional(),
+ value: UpdateMessageParamsSchema,
}),
)
.mutation(async ({ input, ctx }) => {
- return ctx.messageModel.update(input.id, input.value);
+ return ctx.messageModel.update(input.id, input.value as any, {
+ postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
+ sessionId: input.sessionId,
+ topicId: input.topicId,
+ });
}),
updateMessagePlugin: messageProcedure
diff --git a/src/services/chat/__snapshots__/chat.test.ts.snap b/src/services/chat/__snapshots__/chat.test.ts.snap
deleted file mode 100644
index 26320c0b7ef..00000000000
--- a/src/services/chat/__snapshots__/chat.test.ts.snap
+++ /dev/null
@@ -1,110 +0,0 @@
-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
-
-exports[`ChatService > createAssistantMessage > with tools messages > work with dalle3 1`] = `
-{
- "enabledSearch": undefined,
- "messages": [
- {
- "content": "<plugins description="The plugins you can use below">
-<collection name="DALL·E 3">
-<collection.instructions>Whenever a description of an image is given, use lobe-image-designer to create the images and then summarize the prompts used to generate the images in plain text. If the user does not ask for a specific number of images, default to creating four captions to send to lobe-image-designer that are written to be as diverse as possible.
-
- All captions sent to lobe-image-designer must abide by the following policies:
-
-1. If the description is not in English, then translate it.
-2. Do not create more than 4 images, even if the user requests more.
-3. Don't create images of politicians or other public figures. Recommend other ideas instead.
-5. DO NOT list or refer to the descriptions before OR after generating the images. They should ONLY ever be written out ONCE, in the \`prompts\` field of the request. You do not need to ask for permission to generate, just do it!
-6. Always mention the image type (photo, oil painting, watercolor painting, illustration, cartoon, drawing, vector, render, etc.) at the beginning of the caption. Unless the caption suggests otherwise, make at least 1--2 of the 4 images photos.
-7. Diversify depictions of ALL images with people to include DESCENT and GENDER for EACH person using direct terms. Adjust only human descriptions.
- - EXPLICITLY specify these attributes, not abstractly reference them. The attributes should be specified in a minimal way and should directly describe their physical form.
- - Your choices should be grounded in reality. For example, all of a given OCCUPATION should not be the same gender or race. Additionally, focus on creating diverse, inclusive, and exploratory scenes via the properties you choose during rewrites. Make choices that may be insightful or unique sometimes.
- - Use "various" or "diverse" ONLY IF the description refers to groups of more than 3 people. Do not change the number of people requested in the original description.
- - Don't alter memes, fictional character origins, or unseen people. Maintain the original prompt's intent and prioritize quality.
- - Do not create any imagery that would be offensive.
-
-8. Silently modify descriptions that include names or hints or references of specific people or celebrities by carefully selecting a few minimal modifications to substitute references to the people with generic descriptions that don't divulge any information about their identities, except for their genders and physiques. Do this EVEN WHEN the instructions ask for the prompt to not be changed. Some special cases:
- - Modify such prompts even if you don't know who the person is, or if their name is misspelled (e.g. "Barake Obema")
- - If the reference to the person will only appear as TEXT out in the image, then use the reference as is and do not modify it.
- - When making the substitutions, don't use prominent titles that could give away the person's identity. E.g., instead of saying "president", "prime minister", or "chancellor", say "politician"; instead of saying "king", "queen", "emperor", or "empress", say "public figure"; instead of saying "Pope", say "religious figure"; and so on.
- - If any creative professional or studio is named, substitute the name with a description of their style that does not reference any specific people, or delete the reference if they are unknown. DO NOT refer to the artist or studio's style.
-
-The prompt must intricately describe every part of the image in concrete, objective detail. THINK about what the end goal of the description is, and extrapolate that to what would make satisfying images.
-All descriptions sent to lobe-image-designer should be a paragraph of text that is extremely descriptive and detailed. Each should be more than 3 sentences long.</collection.instructions>
-<api identifier="lobe-image-designer____text2image____builtin">Create images from a text-only prompt.</api>
-</collection>
-</plugins>",
- "role": "system",
- },
- {
- "content": "https://vercel.com/ 请分析 chatGPT 关键词
-
-",
- "role": "user",
- },
- ],
- "model": "gpt-3.5-turbo-1106",
- "tools": [
- {
- "function": {
- "description": "Create images from a text-only prompt.",
- "name": "lobe-image-designer____text2image____builtin",
- "parameters": {
- "properties": {
- "prompts": {
- "description": "The user's original image description, potentially modified to abide by the lobe-image-designer policies. If the user does not suggest a number of captions to create, create four of them. If creating multiple captions, make them as diverse as possible. If the user requested modifications to previous images, the captions should not simply be longer, but rather it should be refactored to integrate the suggestions into each of the captions. Generate no more than 4 images, even if the user requests more.",
- "items": {
- "type": "string",
- },
- "maxItems": 4,
- "minItems": 1,
- "type": "array",
- },
- "quality": {
- "default": "standard",
- "description": "The quality of the image that will be generated. hd creates images with finer details and greater consistency across the image.",
- "enum": [
- "standard",
- "hd",
- ],
- "type": "string",
- },
- "seeds": {
- "description": "A list of seeds to use for each prompt. If the user asks to modify a previous image, populate this field with the seed used to generate that image from the image lobe-image-designer metadata.",
- "items": {
- "type": "integer",
- },
- "type": "array",
- },
- "size": {
- "default": "1024x1024",
- "description": "The resolution of the requested image, which can be wide, square, or tall. Use 1024x1024 (square) as the default unless the prompt suggests a wide image, 1792x1024, or a full-body portrait, in which case 1024x1792 (tall) should be used instead. Always include this parameter in the request.",
- "enum": [
- "1792x1024",
- "1024x1024",
- "1024x1792",
- ],
- "type": "string",
- },
- "style": {
- "default": "vivid",
- "description": "The style of the generated images. Must be one of vivid or natural. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images.",
- "enum": [
- "vivid",
- "natural",
- ],
- "type": "string",
- },
- },
- "required": [
- "prompts",
- ],
- "type": "object",
- },
- },
- "type": "function",
- },
- ],
- "top_p": 1,
-}
-`;
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index 9b12bc5f13a..74f6f2e84bc 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -8,18 +8,12 @@ import { type Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vite
import { DEFAULT_USER_AVATAR } from '@/const/meta';
import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
-import * as isCanUseFCModule from '@/helpers/isCanUseFC';
import * as toolEngineeringModule from '@/helpers/toolEngineering';
-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
+import { agentChatConfigSelectors } from '@/store/agent/selectors';
import { aiModelSelectors } from '@/store/aiInfra';
import { useToolStore } from '@/store/tool';
-import { toolSelectors } from '@/store/tool/selectors';
-import { modelProviderSelectors } from '@/store/user/selectors';
-import { DalleManifest } from '@/tools/dalle';
import { WebBrowsingManifest } from '@/tools/web-browsing';
-import { API_ENDPOINTS } from '../_url';
-import * as helpers from './helper';
import { chatService } from './index';
// Mocking external dependencies
@@ -831,39 +825,6 @@ describe('ChatService', () => {
undefined,
);
});
-
- it('work with dalle3', async () => {
- const getChatCompletionSpy = vi.spyOn(chatService, 'getChatCompletion');
- const messages = [
- {
- role: 'user',
- content: 'https://vercel.com/ 请分析 chatGPT 关键词\n\n',
- sessionId: 'inbox',
- createdAt: 1702723964330,
- id: 'vyQvEw6V',
- updatedAt: 1702723964330,
- extra: {},
- meta: {
- avatar: DEFAULT_USER_AVATAR,
- },
- },
- ] as UIChatMessage[];
-
- await chatService.createAssistantMessage({
- messages,
- model: 'gpt-3.5-turbo-1106',
- top_p: 1,
- plugins: [DalleManifest.identifier],
- });
-
- // Assert that getChatCompletionSpy was called with the expected arguments
- expect(getChatCompletionSpy).toHaveBeenCalled();
-
- const calls = getChatCompletionSpy.mock.lastCall;
- // Take a snapshot of the first call's first argument
- expect(calls![0]).toMatchSnapshot();
- expect(calls![1]).toBeUndefined();
- });
});
describe('search functionality', () => {
diff --git a/src/services/chat/contextEngineering.test.ts b/src/services/chat/contextEngineering.test.ts
index adf2c43e33c..297345e723a 100644
--- a/src/services/chat/contextEngineering.test.ts
+++ b/src/services/chat/contextEngineering.test.ts
@@ -248,36 +248,6 @@ describe('contextEngineering', () => {
]);
});
- it('should inject INBOX_GUIDE_SYSTEM_ROLE for welcome questions in inbox session', async () => {
- // Don't mock INBOX_GUIDE_SYSTEMROLE, use the real one
- const messages: UIChatMessage[] = [
- {
- role: 'user',
- content: 'Hello, this is my first question',
- createdAt: Date.now(),
- id: 'test-welcome',
- meta: {},
- updatedAt: Date.now(),
- },
- ];
-
- const result = await contextEngineering({
- messages,
- model: 'gpt-4',
- provider: 'openai',
- isWelcomeQuestion: true,
- sessionId: 'inbox',
- });
-
- // Should have system message with inbox guide content
- const systemMessage = result.find((msg) => msg.role === 'system');
- expect(systemMessage).toBeDefined();
- // Check for characteristic content of the actual INBOX_GUIDE_SYSTEMROLE
- expect(systemMessage!.content).toContain('LobeChat Support Assistant');
- expect(systemMessage!.content).toContain('LobeHub');
- expect(Object.keys(systemMessage!).length).toEqual(2);
- });
-
it('should inject historySummary into system message when provided', async () => {
const historySummary = 'Previous conversation summary: User discussed AI topics.';
diff --git a/src/services/chat/contextEngineering.ts b/src/services/chat/contextEngineering.ts
index 987130e0404..512a08ac897 100644
--- a/src/services/chat/contextEngineering.ts
+++ b/src/services/chat/contextEngineering.ts
@@ -1,9 +1,8 @@
-import { INBOX_GUIDE_SYSTEMROLE, INBOX_SESSION_ID, isDesktop, isServerMode } from '@lobechat/const';
+import { isDesktop, isServerMode } from '@lobechat/const';
import {
ContextEngine,
HistorySummaryProvider,
HistoryTruncateProcessor,
- InboxGuideProvider,
InputTemplateProcessor,
MessageCleanupProcessor,
MessageContentProcessor,
@@ -48,8 +47,6 @@ export const contextEngineering = async ({
enableHistoryCount,
historyCount,
historySummary,
- sessionId,
- isWelcomeQuestion,
}: ContextEngineeringContext): Promise<OpenAIChatMessage[]> => {
const toolNameResolver = new ToolNameResolver();
@@ -63,14 +60,6 @@ export const contextEngineering = async ({
// 2. System role injection (agent's system role)
new SystemRoleInjector({ systemRole }),
- // 3. Inbox guide system role injection
- new InboxGuideProvider({
- inboxGuideSystemRole: INBOX_GUIDE_SYSTEMROLE,
- inboxSessionId: INBOX_SESSION_ID,
- isWelcomeQuestion: isWelcomeQuestion,
- sessionId: sessionId,
- }),
-
// 4. Tool system role injection
new ToolSystemRoleProvider({
getToolSystemRoles: (tools) => toolSelectors.enabledSystemRoles(tools)(getToolStoreState()),
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 1f167b66f16..bb7fb497da8 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -66,7 +66,6 @@ interface FetchAITaskResultParams extends FetchSSEOptions {
interface CreateAssistantMessageStream extends FetchSSEOptions {
abortController?: AbortController;
historySummary?: string;
- isWelcomeQuestion?: boolean;
params: GetChatCompletionPayload;
trace?: TracePayload;
}
@@ -113,9 +112,7 @@ class ChatService {
enableHistoryCount: agentChatConfigSelectors.enableHistoryCount(agentStoreState),
// include user messages
historyCount: agentChatConfigSelectors.historyCount(agentStoreState) + 2,
- historySummary: options?.historySummary,
inputTemplate: chatConfig.inputTemplate,
- isWelcomeQuestion: options?.isWelcomeQuestion,
messages,
model: payload.model,
provider: payload.provider!,
@@ -217,12 +214,10 @@ class ChatService {
onErrorHandle,
onFinish,
trace,
- isWelcomeQuestion,
historySummary,
}: CreateAssistantMessageStream) => {
await this.createAssistantMessage(params, {
historySummary,
- isWelcomeQuestion,
onAbort,
onErrorHandle,
onFinish,
@@ -404,7 +399,7 @@ class ChatService {
onLoadingChange?.(true);
try {
- const oaiMessages = await contextEngineering({
+ const llmMessages = await contextEngineering({
messages: params.messages as any,
model: params.model!,
provider: params.provider!,
@@ -421,7 +416,7 @@ class ChatService {
// remove plugins
delete params.plugins;
await this.getChatCompletion(
- { ...params, messages: oaiMessages, tools },
+ { ...params, messages: llmMessages, tools },
{
onErrorHandle: (error) => {
errorHandle(new Error(error.message), error);
diff --git a/src/services/chat/types.ts b/src/services/chat/types.ts
index 09129814976..b12834024e4 100644
--- a/src/services/chat/types.ts
+++ b/src/services/chat/types.ts
@@ -1,9 +1,9 @@
import { TracePayload } from '@lobechat/types';
+
import { FetchSSEOptions } from '@/utils/fetch';
export interface FetchOptions extends FetchSSEOptions {
historySummary?: string;
- isWelcomeQuestion?: boolean;
signal?: AbortSignal | undefined;
trace?: TracePayload;
}
diff --git a/src/services/message/_deprecated.ts b/src/services/message/_deprecated.ts
index 02ccf160b3f..db95aef1876 100644
--- a/src/services/message/_deprecated.ts
+++ b/src/services/message/_deprecated.ts
@@ -102,7 +102,7 @@ export class ClientService implements IMessageService {
}
// @ts-ignore
- async updateMessage(id: string, message: Partial<DB_Message>) {
+ async updateMessage(id: string, message: Partial<DB_Message>): Promise<any> {
return MessageModel.update(id, message);
}
diff --git a/src/services/message/client.ts b/src/services/message/client.ts
index 40daf4cf74c..9861530e84d 100644
--- a/src/services/message/client.ts
+++ b/src/services/message/client.ts
@@ -45,6 +45,7 @@ export class ClientService extends BaseClientService implements IMessageService
topicId,
},
{
+ groupAssistantMessages: false,
postProcessUrl: this.postProcessUrl,
},
);
@@ -60,6 +61,7 @@ export class ClientService extends BaseClientService implements IMessageService
topicId,
},
{
+ groupAssistantMessages: false,
postProcessUrl: this.postProcessUrl,
},
);
@@ -99,8 +101,12 @@ export class ClientService extends BaseClientService implements IMessageService
return this.messageModel.update(id, { error });
};
- updateMessage: IMessageService['updateMessage'] = async (id, message) => {
- return this.messageModel.update(id, message);
+ updateMessage: IMessageService['updateMessage'] = async (id, message, options) => {
+ return this.messageModel.update(id, message, {
+ postProcessUrl: this.postProcessUrl,
+ sessionId: options?.sessionId,
+ topicId: options?.topicId,
+ });
};
updateMessageTTS: IMessageService['updateMessageTTS'] = async (id, tts) => {
diff --git a/src/services/message/server.ts b/src/services/message/server.ts
index 17c278dd789..b3a1a4073ab 100644
--- a/src/services/message/server.ts
+++ b/src/services/message/server.ts
@@ -81,8 +81,13 @@ export class ServerService implements IMessageService {
return lambdaClient.message.updateMessagePlugin.mutate({ id, value: { arguments: args } });
};
- updateMessage: IMessageService['updateMessage'] = async (id, value) => {
- return lambdaClient.message.update.mutate({ id, value });
+ updateMessage: IMessageService['updateMessage'] = async (id, value, options) => {
+ return lambdaClient.message.update.mutate({
+ id,
+ sessionId: options?.sessionId,
+ topicId: options?.topicId,
+ value,
+ });
};
updateMessageTranslate: IMessageService['updateMessageTranslate'] = async (id, translate) => {
diff --git a/src/services/message/type.ts b/src/services/message/type.ts
index 5a08e751964..c1544c6739d 100644
--- a/src/services/message/type.ts
+++ b/src/services/message/type.ts
@@ -10,6 +10,7 @@ import {
UIChatMessage,
UpdateMessageParams,
UpdateMessageRAGParams,
+ UpdateMessageResult,
} from '@lobechat/types';
import type { HeatmapsProps } from '@lobehub/charts';
@@ -37,7 +38,11 @@ export interface IMessageService {
rankModels(): Promise<ModelRankItem[]>;
getHeatmaps(): Promise<HeatmapsProps['data']>;
updateMessageError(id: string, error: ChatMessageError): Promise<any>;
- updateMessage(id: string, message: Partial<UpdateMessageParams>): Promise<any>;
+ updateMessage(
+ id: string,
+ message: Partial<UpdateMessageParams>,
+ options?: { sessionId?: string | null; topicId?: string | null },
+ ): Promise<UpdateMessageResult>;
updateMessageTTS(id: string, tts: Partial<ChatTTS> | false): Promise<any>;
updateMessageTranslate(id: string, translate: Partial<ChatTranslate> | false): Promise<any>;
updateMessagePluginState(id: string, value: Record<string, any>): Promise<any>;
diff --git a/src/store/chat/helpers.test.ts b/src/store/chat/helpers.test.ts
index 71bd12823f1..e1c93fc8350 100644
--- a/src/store/chat/helpers.test.ts
+++ b/src/store/chat/helpers.test.ts
@@ -64,6 +64,105 @@ describe('chatHelpers', () => {
const message = chatHelpers.getMessageById([], '1');
expect(message).toBeUndefined();
});
+
+ it('finds a block within a group message', () => {
+ const messagesWithGroup = [
+ { id: '1', content: 'Hello' },
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ children: [
+ { id: 'block1', content: 'First block' },
+ { id: 'block2', content: 'Second block' },
+ ],
+ },
+ ] as UIChatMessage[];
+
+ const block = chatHelpers.getMessageById(messagesWithGroup, 'block1');
+ expect(block).toBeDefined();
+ expect(block?.id).toBe('block1');
+ expect(block?.content).toBe('First block');
+ });
+
+ it('returns block with parentId set to group message id', () => {
+ const messagesWithGroup = [
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ children: [{ id: 'block1', content: 'Block content' }],
+ },
+ ] as UIChatMessage[];
+
+ const block = chatHelpers.getMessageById(messagesWithGroup, 'block1');
+ expect(block).toBeDefined();
+ expect(block?.parentId).toBe('group1');
+ });
+
+ it('searches across multiple group messages', () => {
+ const messagesWithGroups = [
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ children: [{ id: 'block1', content: 'First group block' }],
+ },
+ {
+ id: 'group2',
+ role: 'group',
+ content: '',
+ children: [{ id: 'block2', content: 'Second group block' }],
+ },
+ ] as UIChatMessage[];
+
+ const block = chatHelpers.getMessageById(messagesWithGroups, 'block2');
+ expect(block).toBeDefined();
+ expect(block?.id).toBe('block2');
+ expect(block?.parentId).toBe('group2');
+ expect(block?.content).toBe('Second group block');
+ });
+
+ it('prioritizes top-level message over block with same id', () => {
+ const messagesWithConflict = [
+ { id: 'duplicate', content: 'Top-level message', role: 'user' },
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ children: [{ id: 'duplicate', content: 'Block message' }],
+ },
+ ] as UIChatMessage[];
+
+ const message = chatHelpers.getMessageById(messagesWithConflict, 'duplicate');
+ expect(message).toBeDefined();
+ expect(message?.content).toBe('Top-level message');
+ expect(message?.role).toBe('user');
+ expect(message?.parentId).toBeUndefined();
+ });
+
+ it('returns undefined when block is not found in any group', () => {
+ const messagesWithGroup = [
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ children: [{ id: 'block1', content: 'Block content' }],
+ },
+ ] as UIChatMessage[];
+
+ const block = chatHelpers.getMessageById(messagesWithGroup, 'nonexistent');
+ expect(block).toBeUndefined();
+ });
+
+ it('handles group message without children', () => {
+ const messagesWithEmptyGroup = [
+ { id: 'group1', role: 'group', content: '' },
+ ] as UIChatMessage[];
+
+ const block = chatHelpers.getMessageById(messagesWithEmptyGroup, 'block1');
+ expect(block).toBeUndefined();
+ });
});
describe('getSlicedMessages', () => {
diff --git a/src/store/chat/helpers.ts b/src/store/chat/helpers.ts
index 0e3cc41def7..2d4266a4d5c 100644
--- a/src/store/chat/helpers.ts
+++ b/src/store/chat/helpers.ts
@@ -5,8 +5,27 @@ import { encodeAsync } from '@/utils/tokenizer';
export const getMessagesTokenCount = async (messages: OpenAIChatMessage[]) =>
encodeAsync(messages.map((m) => m.content).join(''));
-export const getMessageById = (messages: UIChatMessage[], id: string) =>
- messages.find((m) => m.id === id);
+export const getMessageById = (
+ messages: UIChatMessage[],
+ id: string,
+): UIChatMessage | undefined => {
+ // First try to find in top-level messages
+ const directMatch = messages.find((m) => m.id === id);
+ if (directMatch) return directMatch;
+
+ // If not found, search in group message children (blocks)
+ for (const message of messages) {
+ if (message.role === 'group' && message.children) {
+ const blockMatch = message.children.find((block) => block.id === id);
+ if (blockMatch) {
+ // Return the block with parentId set to group message ID
+ return { ...blockMatch, parentId: message.id } as UIChatMessage;
+ }
+ }
+ }
+
+ return undefined;
+};
const getSlicedMessages = (
messages: UIChatMessage[],
diff --git a/src/store/chat/selectors.ts b/src/store/chat/selectors.ts
index f68f24aaf8d..985049a0956 100644
--- a/src/store/chat/selectors.ts
+++ b/src/store/chat/selectors.ts
@@ -1,6 +1,6 @@
export { aiChatSelectors } from './slices/aiChat/selectors';
export { chatToolSelectors } from './slices/builtinTool/selectors';
-export { chatSelectors } from './slices/message/selectors';
+export * from './slices/message/selectors';
export * from './slices/portal/selectors';
export { threadSelectors } from './slices/thread/selectors';
export { topicSelectors } from './slices/topic/selectors';
diff --git a/src/store/chat/slices/aiChat/actions/generateAIChat.ts b/src/store/chat/slices/aiChat/actions/generateAIChat.ts
index 53a8a82d9bc..6265ab49153 100644
--- a/src/store/chat/slices/aiChat/actions/generateAIChat.ts
+++ b/src/store/chat/slices/aiChat/actions/generateAIChat.ts
@@ -29,7 +29,7 @@ import { useSessionStore } from '@/store/session';
import { WebBrowsingManifest } from '@/tools/web-browsing';
import { Action, setNamespace } from '@/utils/storeDebug';
-import { chatSelectors, topicSelectors } from '../../../selectors';
+import { chatSelectors, messageStateSelectors, topicSelectors } from '../../../selectors';
const n = setNamespace('ai');
@@ -598,7 +598,6 @@ export const generateAIChat: StateCreator<
topicId: get().activeTopicId,
traceName: TraceNameMap.Conversation,
},
- isWelcomeQuestion: params?.isWelcomeQuestion,
onErrorHandle: async (error) => {
await messageService.updateMessageError(messageId, error);
await refreshMessages();
@@ -707,7 +706,8 @@ export const generateAIChat: StateCreator<
if (!duration) {
duration = Date.now() - thinkingStartAt;
- const isInChatReasoning = chatSelectors.isMessageInChatReasoning(messageId)(get());
+ const isInChatReasoning =
+ messageStateSelectors.isMessageInChatReasoning(messageId)(get());
if (isInChatReasoning) {
internal_toggleChatReasoning(
false,
diff --git a/src/store/chat/slices/builtinTool/actions/__tests__/dalle.test.ts b/src/store/chat/slices/builtinTool/actions/__tests__/dalle.test.ts
deleted file mode 100644
index 77373febe74..00000000000
--- a/src/store/chat/slices/builtinTool/actions/__tests__/dalle.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { UIChatMessage } from '@lobechat/types';
-import { act, renderHook } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { messageService } from '@/services/message';
-import { imageGenerationService } from '@/services/textToImage';
-import { uploadService } from '@/services/upload';
-import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
-import { useFileStore } from '@/store/file';
-import { DallEImageItem } from '@/types/tool/dalle';
-
-describe('chatToolSlice - dalle', () => {
- describe('generateImageFromPrompts', () => {
- it('should generate images from prompts, update items, and upload images', async () => {
- const { result } = renderHook(() => useChatStore());
-
- const initialMessageContent = JSON.stringify([
- { prompt: 'test prompt', previewUrl: 'old-url', imageId: 'old-id' },
- ]);
-
- vi.spyOn(chatSelectors, 'getMessageById').mockImplementationOnce(
- (id) => () =>
- ({
- id,
- content: initialMessageContent,
- }) as UIChatMessage,
- );
-
- const messageId = 'message-id';
- const prompts = [
- { prompt: 'test prompt 1' },
- { prompt: 'test prompt 2' },
- ] as DallEImageItem[];
- const mockUrl = 'https://example.com/image.png';
- const mockId = 'image-id';
-
- vi.spyOn(imageGenerationService, 'generateImage').mockResolvedValue(mockUrl);
- vi.spyOn(uploadService, 'getImageFileByUrlWithCORS').mockResolvedValue(
- new File(['1'], 'file.png', { type: 'image/png' }),
- );
-
- // Mock the new uploadWithProgress method from useFileStore
- vi.spyOn(useFileStore, 'getState').mockReturnValue({
- uploadWithProgress: vi.fn().mockResolvedValue({
- id: mockId,
- url: '',
- dimensions: { width: 512, height: 512 },
- filename: 'file.png',
- }),
- } as any);
-
- // Mock store methods that are called in the implementation
- vi.spyOn(result.current, 'toggleDallEImageLoading');
- vi.spyOn(result.current, 'updatePluginState').mockResolvedValue(undefined);
- vi.spyOn(result.current, 'internal_updateMessageContent').mockResolvedValue(undefined);
-
- await act(async () => {
- await result.current.generateImageFromPrompts(prompts, messageId);
- });
- // For each prompt, loading is toggled on and then off
- expect(imageGenerationService.generateImage).toHaveBeenCalledTimes(prompts.length);
- expect(useFileStore.getState().uploadWithProgress).toHaveBeenCalledTimes(prompts.length);
- expect(result.current.toggleDallEImageLoading).toHaveBeenCalledTimes(prompts.length * 2);
- });
- });
-
- describe('updateImageItem', () => {
- it('should update image item correctly', async () => {
- const { result } = renderHook(() => useChatStore());
- const messageId = 'message-id';
- const initialMessageContent = JSON.stringify([
- { prompt: 'test prompt', previewUrl: 'old-url', imageId: 'old-id' },
- ]);
- const updateFunction = (draft: any) => {
- draft[0].previewUrl = 'new-url';
- draft[0].imageId = 'new-id';
- };
- vi.spyOn(result.current, 'internal_updateMessageContent').mockResolvedValue(undefined);
-
- // 模拟 getMessageById 返回消息内容
- vi.spyOn(chatSelectors, 'getMessageById').mockImplementationOnce(
- (id) => () =>
- ({
- id,
- content: initialMessageContent,
- }) as UIChatMessage,
- );
- vi.spyOn(messageService, 'updateMessage').mockResolvedValueOnce(undefined);
-
- await act(async () => {
- await result.current.updateImageItem(messageId, updateFunction);
- });
-
- // 验证 internal_updateMessageContent 是否被正确调用以更新内容
- expect(result.current.internal_updateMessageContent).toHaveBeenCalledWith(
- messageId,
- JSON.stringify([{ prompt: 'test prompt', previewUrl: 'new-url', imageId: 'new-id' }]),
- );
- });
- });
-
- describe('text2image', () => {
- it('should call generateImageFromPrompts with provided data', async () => {
- const { result } = renderHook(() => useChatStore());
- const id = 'message-id';
- const data = [{ prompt: 'prompt 1' }, { prompt: 'prompt 2' }] as DallEImageItem[];
-
- // Mock generateImageFromPrompts
- const generateImageFromPromptsMock = vi
- .spyOn(result.current, 'generateImageFromPrompts')
- .mockResolvedValue(undefined);
-
- await act(async () => {
- await result.current.text2image(id, data);
- });
-
- expect(generateImageFromPromptsMock).toHaveBeenCalledWith(data, id);
- });
- });
-});
diff --git a/src/store/chat/slices/builtinTool/actions/dalle.ts b/src/store/chat/slices/builtinTool/actions/dalle.ts
deleted file mode 100644
index fc46b442810..00000000000
--- a/src/store/chat/slices/builtinTool/actions/dalle.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import { produce } from 'immer';
-import pMap from 'p-map';
-import { SWRResponse } from 'swr';
-import { StateCreator } from 'zustand/vanilla';
-
-import { useClientDataSWR } from '@/libs/swr';
-import { fileService } from '@/services/file';
-import { imageGenerationService } from '@/services/textToImage';
-import { uploadService } from '@/services/upload';
-import { chatSelectors } from '@/store/chat/selectors';
-import { ChatStore } from '@/store/chat/store';
-import { useFileStore } from '@/store/file';
-import { DallEImageItem } from '@/types/tool/dalle';
-import { setNamespace } from '@/utils/storeDebug';
-
-const n = setNamespace('tool');
-
-const SWR_FETCH_KEY = 'FetchImageItem';
-
-export interface ChatDallEAction {
- generateImageFromPrompts: (items: DallEImageItem[], id: string) => Promise<void>;
- text2image: (id: string, data: DallEImageItem[]) => Promise<void>;
- toggleDallEImageLoading: (key: string, value: boolean) => void;
- updateImageItem: (id: string, updater: (data: DallEImageItem[]) => void) => Promise<void>;
- useFetchDalleImageItem: (id: string) => SWRResponse;
-}
-
-export const dalleSlice: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ChatDallEAction
-> = (set, get) => ({
- generateImageFromPrompts: async (items, messageId) => {
- const { toggleDallEImageLoading, updateImageItem } = get();
- // eslint-disable-next-line unicorn/consistent-function-scoping
- const getMessageById = (id: string) => chatSelectors.getMessageById(id)(get());
-
- const message = getMessageById(messageId);
- if (!message) return;
-
- const parent = getMessageById(message!.parentId!);
- const originPrompt = parent?.content;
- let errorArray: any[] = [];
-
- await pMap(items, async (params, index) => {
- toggleDallEImageLoading(messageId + params.prompt, true);
-
- let url = '';
- try {
- url = await imageGenerationService.generateImage(params);
- } catch (e) {
- toggleDallEImageLoading(messageId + params.prompt, false);
- errorArray[index] = e;
-
- await get().updatePluginState(messageId, { error: errorArray });
- }
-
- if (!url) return;
-
- await updateImageItem(messageId, (draft) => {
- draft[index].previewUrl = url;
- });
-
- toggleDallEImageLoading(messageId + params.prompt, false);
- const imageFile = await uploadService.getImageFileByUrlWithCORS(
- url,
- `${originPrompt || params.prompt}_${index}.png`,
- );
-
- const data = await useFileStore.getState().uploadWithProgress({
- file: imageFile,
- });
-
- if (!data) return;
-
- await updateImageItem(messageId, (draft) => {
- draft[index].imageId = data.id;
- draft[index].previewUrl = undefined;
- });
- });
- },
- text2image: async (id, data) => {
- // const isAutoGen = settingsSelectors.isDalleAutoGenerating(useGlobalStore.getState());
- // if (!isAutoGen) return;
-
- await get().generateImageFromPrompts(data, id);
- },
-
- toggleDallEImageLoading: (key, value) => {
- set(
- { dalleImageLoading: { ...get().dalleImageLoading, [key]: value } },
- false,
- n('toggleDallEImageLoading'),
- );
- },
-
- updateImageItem: async (id, updater) => {
- const message = chatSelectors.getMessageById(id)(get());
- if (!message) return;
-
- const data: DallEImageItem[] = JSON.parse(message.content);
-
- const nextContent = produce(data, updater);
- await get().internal_updateMessageContent(id, JSON.stringify(nextContent));
- },
-
- useFetchDalleImageItem: (id) =>
- useClientDataSWR([SWR_FETCH_KEY, id], async () => {
- const item = await fileService.getFile(id);
-
- set(
- produce((draft) => {
- if (draft.dalleImageMap[id]) return;
-
- draft.dalleImageMap[id] = item;
- }),
- false,
- n('useFetchFile'),
- );
-
- return item;
- }),
-});
diff --git a/src/store/chat/slices/builtinTool/actions/index.ts b/src/store/chat/slices/builtinTool/actions/index.ts
index 512a0abb26f..3f3a3280ed3 100644
--- a/src/store/chat/slices/builtinTool/actions/index.ts
+++ b/src/store/chat/slices/builtinTool/actions/index.ts
@@ -2,14 +2,12 @@ import { StateCreator } from 'zustand/vanilla';
import { ChatStore } from '@/store/chat/store';
-import { ChatDallEAction, dalleSlice } from './dalle';
import { ChatCodeInterpreterAction, codeInterpreterSlice } from './interpreter';
import { LocalFileAction, localSystemSlice } from './localSystem';
import { SearchAction, searchSlice } from './search';
export interface ChatBuiltinToolAction
- extends ChatDallEAction,
- SearchAction,
+ extends SearchAction,
LocalFileAction,
ChatCodeInterpreterAction {}
@@ -19,7 +17,6 @@ export const chatToolSlice: StateCreator<
[],
ChatBuiltinToolAction
> = (...params) => ({
- ...dalleSlice(...params),
...searchSlice(...params),
...localSystemSlice(...params),
...codeInterpreterSlice(...params),
diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.ts
index e99d72f54d0..387ea66aa7d 100644
--- a/src/store/chat/slices/message/action.test.ts
+++ b/src/store/chat/slices/message/action.test.ts
@@ -471,7 +471,11 @@ describe('chatMessage actions', () => {
await result.current.internal_updateMessageContent(messageId, newContent);
});
- expect(spy).toHaveBeenCalledWith(messageId, { content: newContent });
+ expect(spy).toHaveBeenCalledWith(
+ messageId,
+ { content: newContent },
+ { sessionId: 'session-id', topicId: 'topic-id' },
+ );
});
it('should dispatch message update action', async () => {
diff --git a/src/store/chat/slices/message/action.ts b/src/store/chat/slices/message/action.ts
index 3760ac83760..6bc86037f63 100644
--- a/src/store/chat/slices/message/action.ts
+++ b/src/store/chat/slices/message/action.ts
@@ -6,6 +6,7 @@ import {
ChatMessageError,
ChatMessagePluginError,
CreateMessageParams,
+ CreateNewMessageParams,
GroundingSearch,
MessageMetadata,
MessageToolCall,
@@ -117,6 +118,14 @@ export interface ChatMessageAction {
* otherwise the message will be too slow to show
*/
internal_createTmpMessage: (params: CreateMessageParams) => string;
+ /**
+ * create a new message using createNewMessage API and return full message list
+ * used for group message scenarios to reduce network requests
+ */
+ internal_createNewMessage: (
+ params: CreateNewMessageParams,
+ context?: { tempMessageId?: string; groupMessageId?: string },
+ ) => Promise<{ id: string; messages: UIChatMessage[] } | undefined>;
/**
* delete the message content with optimistic update
*/
@@ -374,8 +383,16 @@ export const chatMessage: StateCreator<
internal_updateMessageError: async (id, error) => {
get().internal_dispatchMessage({ id, type: 'updateMessage', value: { error } });
- await messageService.updateMessage(id, { error });
- await get().refreshMessages();
+ const result = await messageService.updateMessage(
+ id,
+ { error },
+ { topicId: get().activeTopicId, sessionId: get().activeId },
+ );
+ if (result?.success && result.messages) {
+ get().replaceMessages(result.messages);
+ } else {
+ await get().refreshMessages();
+ }
},
internal_updateMessagePluginError: async (id, error) => {
@@ -384,7 +401,12 @@ export const chatMessage: StateCreator<
},
internal_updateMessageContent: async (id, content, extra) => {
- const { internal_dispatchMessage, refreshMessages, internal_transformToolCalls } = get();
+ const {
+ internal_dispatchMessage,
+ refreshMessages,
+ internal_transformToolCalls,
+ replaceMessages,
+ } = get();
// Due to the async update method and refresh need about 100ms
// we need to update the message content at the frontend to avoid the update flick
@@ -403,17 +425,26 @@ export const chatMessage: StateCreator<
});
}
- await messageService.updateMessage(id, {
- content,
- tools: extra?.toolCalls ? internal_transformToolCalls(extra?.toolCalls) : undefined,
- reasoning: extra?.reasoning,
- search: extra?.search,
- metadata: extra?.metadata,
- model: extra?.model,
- provider: extra?.provider,
- imageList: extra?.imageList,
- });
- await refreshMessages();
+ const result = await messageService.updateMessage(
+ id,
+ {
+ content,
+ tools: extra?.toolCalls ? internal_transformToolCalls(extra?.toolCalls) : undefined,
+ reasoning: extra?.reasoning,
+ search: extra?.search,
+ metadata: extra?.metadata,
+ model: extra?.model,
+ provider: extra?.provider,
+ imageList: extra?.imageList,
+ },
+ { topicId: get().activeTopicId, sessionId: get().activeId },
+ );
+
+ if (result && result.success && result.messages) {
+ replaceMessages(result.messages);
+ } else {
+ await refreshMessages();
+ }
},
internal_createMessage: async (message, context) => {
@@ -473,6 +504,63 @@ export const chatMessage: StateCreator<
return tempId;
},
+
+ internal_createNewMessage: async (message, context) => {
+ const {
+ internal_createTmpMessage,
+ internal_toggleMessageLoading,
+ internal_dispatchMessage,
+ replaceMessages,
+ } = get();
+
+ let tempId = context?.tempMessageId;
+ if (!tempId) {
+ tempId = 'tmp_' + nanoid();
+
+ // Check if should add as group block (explicitly controlled by caller)
+ if (context?.groupMessageId) {
+ internal_dispatchMessage({
+ type: 'addGroupBlock',
+ groupMessageId: context.groupMessageId,
+ blockId: tempId,
+ value: {
+ id: tempId,
+ content: message.content,
+ },
+ });
+ internal_toggleMessageLoading(true, tempId);
+ } else {
+ // Regular message creation at top level
+ tempId = internal_createTmpMessage(message as any);
+ internal_toggleMessageLoading(true, tempId);
+ }
+ }
+
+ try {
+ // 使用 createNewMessage API
+ const result = await messageService.createNewMessage(message);
+
+ // 直接用返回的 messages 更新 store(已包含 group 结构)
+ replaceMessages(result.messages);
+
+ internal_toggleMessageLoading(false, tempId);
+ return result;
+ } catch (e) {
+ internal_toggleMessageLoading(false, tempId);
+ internal_dispatchMessage({
+ id: tempId,
+ type: 'updateMessage',
+ value: {
+ error: {
+ type: ChatErrorType.CreateMessageError,
+ message: (e as Error).message,
+ body: e,
+ },
+ },
+ });
+ }
+ },
+
internal_deleteMessage: async (id: string) => {
get().internal_dispatchMessage({ type: 'deleteMessage', id });
await messageService.removeMessage(id);
diff --git a/src/store/chat/slices/message/reducer.test.ts b/src/store/chat/slices/message/reducer.test.ts
index 353500e732c..716a6a145ba 100644
--- a/src/store/chat/slices/message/reducer.test.ts
+++ b/src/store/chat/slices/message/reducer.test.ts
@@ -57,16 +57,131 @@ describe('messagesReducer', () => {
expect(newState).toEqual(initialState);
});
- it('should not modify the state if the specified message does not exist', () => {
+ it('should update a block in group message children when id matches a block', () => {
+ const stateWithGroup: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ meta: {},
+ children: [
+ {
+ id: 'block1',
+ content: 'Original block content',
+ tools: [
+ {
+ id: 'tool1',
+ identifier: 'search',
+ apiName: 'search',
+ type: 'builtin',
+ arguments: '{"query": "test"}',
+ },
+ ],
+ },
+ ],
+ } as UIChatMessage,
+ ];
+
const payload: MessageDispatch = {
type: 'updateMessage',
- id: 'nonexistentMessage',
- value: { content: 'Updated Message' },
+ id: 'block1',
+ value: { content: 'Updated block content' },
};
- const newState = messagesReducer(initialState, payload);
+ const newState = messagesReducer(stateWithGroup, payload);
+ const groupMessage = newState.find((m) => m.id === 'group1');
+ const block = groupMessage?.children?.find((b) => b.id === 'block1');
- expect(newState).toEqual(initialState);
+ expect(block?.content).toBe('Updated block content');
+ expect(groupMessage?.updatedAt).toBeGreaterThan(1629264000000);
+ });
+
+ it('should update block tools in group message children', () => {
+ const stateWithGroup: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ meta: {},
+ children: [
+ {
+ id: 'block1',
+ content: 'Block content',
+ tools: [
+ {
+ id: 'tool1',
+ identifier: 'search',
+ apiName: 'search',
+ type: 'builtin',
+ arguments: '{"query": "test"}',
+ },
+ ],
+ },
+ ],
+ } as UIChatMessage,
+ ];
+
+ const newTools = [
+ {
+ id: 'tool1',
+ identifier: 'search',
+ apiName: 'search',
+ type: 'builtin',
+ arguments: '{"query": "updated"}',
+ result: {
+ id: 'result1',
+ content: 'Search result',
+ },
+ },
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'updateMessage',
+ id: 'block1',
+ value: { tools: newTools as any },
+ };
+
+ const newState = messagesReducer(stateWithGroup, payload);
+ const groupMessage = newState.find((m) => m.id === 'group1');
+ const block = groupMessage?.children?.find((b) => b.id === 'block1');
+
+ expect(block?.tools).toEqual(newTools);
+ expect(groupMessage?.updatedAt).toBeGreaterThan(1629264000000);
+ });
+
+ it('should not modify state when updating non-existent block in group message', () => {
+ const stateWithGroup: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ meta: {},
+ children: [
+ {
+ id: 'block1',
+ content: 'Block content',
+ },
+ ],
+ } as UIChatMessage,
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'updateMessage',
+ id: 'nonexistentBlock',
+ value: { content: 'Updated content' },
+ };
+
+ const newState = messagesReducer(stateWithGroup, payload);
+ expect(newState).toEqual(stateWithGroup);
});
});
@@ -502,4 +617,247 @@ describe('messagesReducer', () => {
expect(newState).toEqual(initialState);
});
});
+
+ describe('updateGroupBlockToolResult', () => {
+ it('should update a tool result in a group message block', () => {
+ const stateWithGroup: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ meta: {},
+ children: [
+ {
+ id: 'block1',
+ content: 'Assistant response',
+ tools: [
+ {
+ id: 'tool1',
+ identifier: 'search',
+ apiName: 'search',
+ type: 'builtin',
+ arguments: '{"query": "test"}',
+ result: {
+ id: 'result1',
+ content: 'Initial result',
+ },
+ },
+ ],
+ },
+ ],
+ } as UIChatMessage,
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'updateGroupBlockToolResult',
+ groupMessageId: 'group1',
+ blockId: 'block1',
+ toolId: 'tool1',
+ toolResult: {
+ id: 'result1',
+ content: 'Updated result content',
+ state: { foo: 'bar' },
+ },
+ };
+
+ const newState = messagesReducer(stateWithGroup, payload);
+ const groupMessage = newState.find((m) => m.id === 'group1');
+ const block = groupMessage?.children?.find((b) => b.id === 'block1');
+ const tool = block?.tools?.find((t) => t.id === 'tool1');
+
+ expect(tool?.result).toEqual({
+ id: 'result1',
+ content: 'Updated result content',
+ state: { foo: 'bar' },
+ });
+ expect(groupMessage?.updatedAt).toBeGreaterThan(1629264000000);
+ });
+
+ it('should not modify state if group message is not found', () => {
+ const payload: MessageDispatch = {
+ type: 'updateGroupBlockToolResult',
+ groupMessageId: 'nonexistent',
+ blockId: 'block1',
+ toolId: 'tool1',
+ toolResult: {
+ id: 'result1',
+ content: 'Updated result',
+ },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toEqual(initialState);
+ });
+
+ it('should not modify state if block is not found', () => {
+ const stateWithGroup: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ meta: {},
+ children: [
+ {
+ id: 'block1',
+ content: 'Assistant response',
+ tools: [],
+ },
+ ],
+ } as UIChatMessage,
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'updateGroupBlockToolResult',
+ groupMessageId: 'group1',
+ blockId: 'nonexistentBlock',
+ toolId: 'tool1',
+ toolResult: {
+ id: 'result1',
+ content: 'Updated result',
+ },
+ };
+
+ const newState = messagesReducer(stateWithGroup, payload);
+ expect(newState).toEqual(stateWithGroup);
+ });
+
+ it('should not modify state if tool is not found', () => {
+ const stateWithGroup: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ meta: {},
+ children: [
+ {
+ id: 'block1',
+ content: 'Assistant response',
+ tools: [
+ {
+ id: 'tool1',
+ identifier: 'search',
+ apiName: 'search',
+ type: 'builtin',
+ arguments: '{"query": "test"}',
+ },
+ ],
+ },
+ ],
+ } as UIChatMessage,
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'updateGroupBlockToolResult',
+ groupMessageId: 'group1',
+ blockId: 'block1',
+ toolId: 'nonexistentTool',
+ toolResult: {
+ id: 'result1',
+ content: 'Updated result',
+ },
+ };
+
+ const newState = messagesReducer(stateWithGroup, payload);
+ expect(newState).toEqual(stateWithGroup);
+ });
+ });
+
+ describe('addGroupBlock', () => {
+ it('should add a new block to group message children', () => {
+ const stateWithGroup: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ meta: {},
+ children: [
+ {
+ id: 'block1',
+ content: 'First block',
+ },
+ ],
+ } as UIChatMessage,
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'addGroupBlock',
+ groupMessageId: 'group1',
+ blockId: 'block2',
+ value: {
+ id: 'block2',
+ content: 'Second block',
+ },
+ };
+
+ const newState = messagesReducer(stateWithGroup, payload);
+ const groupMessage = newState.find((m) => m.id === 'group1');
+
+ expect(groupMessage?.children).toHaveLength(2);
+ expect(groupMessage?.children?.[1]).toEqual({
+ id: 'block2',
+ content: 'Second block',
+ });
+ expect(groupMessage?.updatedAt).toBeGreaterThan(1629264000000);
+ });
+
+ it('should not modify state if group message is not found', () => {
+ const stateWithGroup: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'group1',
+ role: 'group',
+ content: '',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ meta: {},
+ children: [
+ {
+ id: 'block1',
+ content: 'First block',
+ },
+ ],
+ } as UIChatMessage,
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'addGroupBlock',
+ groupMessageId: 'nonexistentGroup',
+ blockId: 'block2',
+ value: {
+ id: 'block2',
+ content: 'Second block',
+ },
+ };
+
+ const newState = messagesReducer(stateWithGroup, payload);
+ expect(newState).toEqual(stateWithGroup);
+ });
+
+ it('should not modify state if message is not a group message', () => {
+ const payload: MessageDispatch = {
+ type: 'addGroupBlock',
+ groupMessageId: 'message1',
+ blockId: 'block2',
+ value: {
+ id: 'block2',
+ content: 'Second block',
+ },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toEqual(initialState);
+ });
+ });
});
diff --git a/src/store/chat/slices/message/reducer.ts b/src/store/chat/slices/message/reducer.ts
index 69da809a55b..b9bcc5095c4 100644
--- a/src/store/chat/slices/message/reducer.ts
+++ b/src/store/chat/slices/message/reducer.ts
@@ -75,6 +75,29 @@ interface UpdateMessageExtra {
value: any;
}
+interface UpdateGroupBlockToolResult {
+ blockId: string;
+ groupMessageId: string;
+ toolId: string;
+ toolResult: {
+ content: string;
+ error?: any;
+ id: string;
+ state?: any;
+ };
+ type: 'updateGroupBlockToolResult';
+}
+
+interface AddGroupBlock {
+ blockId: string;
+ groupMessageId: string;
+ type: 'addGroupBlock';
+ value: {
+ content: string;
+ id: string;
+ };
+}
+
export type MessageDispatch =
| CreateMessage
| UpdateMessage
@@ -86,7 +109,9 @@ export type MessageDispatch =
| UpdateMessageTools
| AddMessageTool
| DeleteMessageTool
- | DeleteMessages;
+ | DeleteMessages
+ | UpdateGroupBlockToolResult
+ | AddGroupBlock;
export const messagesReducer = (
state: UIChatMessage[],
@@ -96,10 +121,27 @@ export const messagesReducer = (
case 'updateMessage': {
return produce(state, (draftState) => {
const { id, value } = payload;
+
+ // First, try to find in top-level messages
const index = draftState.findIndex((i) => i.id === id);
- if (index < 0) return;
+ if (index >= 0) {
+ draftState[index] = merge(draftState[index], { ...value, updatedAt: Date.now() });
+ return;
+ }
- draftState[index] = merge(draftState[index], { ...value, updatedAt: Date.now() });
+ // If not found, search in group message children (blocks)
+ for (const message of draftState) {
+ if (message.role === 'group' && message.children) {
+ const blockIndex = message.children.findIndex((block) => block.id === id);
+ if (blockIndex >= 0) {
+ message.children[blockIndex] = merge(message.children[blockIndex], {
+ ...value,
+ });
+ message.updatedAt = Date.now();
+ return;
+ }
+ }
+ }
});
}
@@ -226,6 +268,48 @@ export const messagesReducer = (
});
});
}
+
+ case 'updateGroupBlockToolResult': {
+ return produce(state, (draftState) => {
+ const { groupMessageId, blockId, toolId, toolResult } = payload;
+
+ // Find the group message
+ const msg = draftState.find((m) => m.id === groupMessageId);
+ if (!msg || msg.role !== 'group' || !msg.children) return;
+
+ // Find the block within children
+ const block = msg.children.find((b) => b.id === blockId);
+ if (!block || !block.tools) return;
+
+ // Find the tool and update its result
+ const tool = block.tools.find((t) => t.id === toolId);
+ if (!tool) return;
+
+ // Update tool result (optimistic update)
+ tool.result = toolResult;
+
+ msg.updatedAt = Date.now();
+ });
+ }
+
+ case 'addGroupBlock': {
+ return produce(state, (draftState) => {
+ const { groupMessageId, blockId, value } = payload;
+
+ // Find the group message
+ const msg = draftState.find((m) => m.id === groupMessageId);
+ if (!msg || msg.role !== 'group' || !msg.children) return;
+
+ // Add new block to children
+ msg.children.push({
+ content: value.content,
+ id: blockId,
+ });
+
+ msg.updatedAt = Date.now();
+ });
+ }
+
default: {
throw new Error('暂未实现的 type,请检查 reducer');
}
diff --git a/src/store/chat/slices/message/selectors.test.ts b/src/store/chat/slices/message/selectors/chat.test.ts
similarity index 65%
rename from src/store/chat/slices/message/selectors.test.ts
rename to src/store/chat/slices/message/selectors/chat.test.ts
index 016c3c23912..018361fb3af 100644
--- a/src/store/chat/slices/message/selectors.test.ts
+++ b/src/store/chat/slices/message/selectors/chat.test.ts
@@ -12,7 +12,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { createServerConfigStore } from '@/store/serverConfig/store';
import { merge } from '@/utils/merge';
-import { chatSelectors } from './selectors';
+import { chatSelectors } from './chat';
vi.mock('i18next', () => ({
t: vi.fn((key) => key), // Simplified mock return value
@@ -416,35 +416,6 @@ describe('chatSelectors', () => {
});
});
- describe('isToolCallStreaming', () => {
- it('should return true when tool call is streaming for given message and index', () => {
- const state: Partial<ChatStore> = {
- toolCallingStreamIds: {
- 'msg-1': [true, false, true],
- },
- };
- expect(chatSelectors.isToolCallStreaming('msg-1', 0)(state as ChatStore)).toBe(true);
- expect(chatSelectors.isToolCallStreaming('msg-1', 2)(state as ChatStore)).toBe(true);
- });
-
- it('should return false when tool call is not streaming for given message and index', () => {
- const state: Partial<ChatStore> = {
- toolCallingStreamIds: {
- 'msg-1': [true, false, true],
- },
- };
- expect(chatSelectors.isToolCallStreaming('msg-1', 1)(state as ChatStore)).toBe(false);
- expect(chatSelectors.isToolCallStreaming('msg-2', 0)(state as ChatStore)).toBe(false);
- });
-
- it('should return false when no streaming data exists for the message', () => {
- const state: Partial<ChatStore> = {
- toolCallingStreamIds: {},
- };
- expect(chatSelectors.isToolCallStreaming('msg-1', 0)(state as ChatStore)).toBe(false);
- });
- });
-
describe('activeBaseChats with group chat messages', () => {
it('should retrieve agent meta for group chat messages with groupId and agentId', () => {
const groupChatMessages = [
@@ -470,4 +441,269 @@ describe('chatSelectors', () => {
expect(chats[0].meta).toBeDefined();
});
});
+
+ describe('getGroupLatestMessageWithoutTools', () => {
+ it('should return the last child without tools', () => {
+ const groupMessage = {
+ id: 'group-1',
+ role: 'group',
+ content: '',
+ children: [
+ {
+ id: 'child-1',
+ content: 'First response',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ {
+ id: 'child-2',
+ content: 'Second response',
+ tools: [],
+ },
+ {
+ id: 'child-3',
+ content: 'Final response',
+ },
+ ],
+ } as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [groupMessage],
+ },
+ };
+
+ const result = chatSelectors.getGroupLatestMessageWithoutTools('group-1')(state as ChatStore);
+ expect(result).toBeDefined();
+ expect(result?.id).toBe('child-3');
+ expect(result?.content).toBe('Final response');
+ });
+
+ it('should return null if the last child has tools', () => {
+ const groupMessage = {
+ id: 'group-2',
+ role: 'group',
+ content: '',
+ children: [
+ {
+ id: 'child-1',
+ content: 'First response',
+ },
+ {
+ id: 'child-2',
+ content: 'Second response with tools',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ ],
+ } as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [groupMessage],
+ },
+ };
+
+ const result = chatSelectors.getGroupLatestMessageWithoutTools('group-2')(state as ChatStore);
+ expect(result).toBeUndefined();
+ });
+
+ it('should return the last child when it has empty tools array', () => {
+ const groupMessage = {
+ id: 'group-3',
+ role: 'group',
+ content: '',
+ children: [
+ {
+ id: 'child-1',
+ content: 'First response with tools',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ {
+ id: 'child-2',
+ content: 'Final response',
+ tools: [],
+ },
+ ],
+ } as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [groupMessage],
+ },
+ };
+
+ const result = chatSelectors.getGroupLatestMessageWithoutTools('group-3')(state as ChatStore);
+ expect(result).toBeDefined();
+ expect(result?.id).toBe('child-2');
+ expect(result?.content).toBe('Final response');
+ });
+
+ it('should return null for non-group messages', () => {
+ const assistantMessage = {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Regular message',
+ } as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [assistantMessage],
+ },
+ };
+
+ const result = chatSelectors.getGroupLatestMessageWithoutTools('msg-1')(state as ChatStore);
+ expect(result).toBeUndefined();
+ });
+
+ it('should return null for group messages without children', () => {
+ const groupMessage = {
+ id: 'group-4',
+ role: 'group',
+ content: '',
+ children: undefined,
+ } as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [groupMessage],
+ },
+ };
+
+ const result = chatSelectors.getGroupLatestMessageWithoutTools('group-4')(state as ChatStore);
+ expect(result).toBeUndefined();
+ });
+
+ it('should return null for group messages with empty children array', () => {
+ const groupMessage = {
+ id: 'group-5',
+ role: 'group',
+ content: '',
+ children: [],
+ } as unknown as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [groupMessage],
+ },
+ };
+
+ const result = chatSelectors.getGroupLatestMessageWithoutTools('group-5')(state as ChatStore);
+ expect(result).toBeUndefined();
+ });
+
+ it('should return null if all children have tools', () => {
+ const groupMessage = {
+ id: 'group-6',
+ role: 'group',
+ content: '',
+ children: [
+ {
+ id: 'child-1',
+ content: 'First response',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ {
+ id: 'child-2',
+ content: 'Second response',
+ tools: [
+ {
+ id: 'tool-2',
+ identifier: 'test2',
+ apiName: 'test2',
+ arguments: '{}',
+ type: 'default',
+ },
+ ],
+ },
+ ],
+ } as unknown as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [groupMessage],
+ },
+ };
+
+ const result = chatSelectors.getGroupLatestMessageWithoutTools('group-6')(state as ChatStore);
+ expect(result).toBeUndefined();
+ });
+
+ it('should handle empty tools array as no tools', () => {
+ const groupMessage = {
+ id: 'group-7',
+ role: 'group',
+ content: '',
+ children: [
+ {
+ id: 'child-1',
+ content: 'Response with empty tools',
+ tools: [],
+ },
+ ],
+ } as unknown as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [groupMessage],
+ },
+ };
+
+ const result = chatSelectors.getGroupLatestMessageWithoutTools('group-7')(state as ChatStore);
+ expect(result).toBeDefined();
+ expect(result?.id).toBe('child-1');
+ });
+
+ it('should return null when message is not found', () => {
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [],
+ },
+ };
+
+ const result = chatSelectors.getGroupLatestMessageWithoutTools('non-existent')(
+ state as ChatStore,
+ );
+ expect(result).toBeUndefined();
+ });
+ });
});
diff --git a/src/store/chat/slices/message/selectors.ts b/src/store/chat/slices/message/selectors/chat.ts
similarity index 71%
rename from src/store/chat/slices/message/selectors.ts
rename to src/store/chat/slices/message/selectors/chat.ts
index 0a21c43c752..b55eca5f93f 100644
--- a/src/store/chat/slices/message/selectors.ts
+++ b/src/store/chat/slices/message/selectors/chat.ts
@@ -10,8 +10,8 @@ import { sessionMetaSelectors } from '@/store/session/selectors';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
-import { chatHelpers } from '../../helpers';
-import type { ChatStoreState } from '../../initialState';
+import { chatHelpers } from '../../../helpers';
+import type { ChatStoreState } from '../../../initialState';
const getMeta = (message: UIChatMessage) => {
switch (message.role) {
@@ -47,7 +47,7 @@ const getBaseChatsByKey =
return messages.map((i) => ({ ...i, meta: getMeta(i) }));
};
-const currentChatKey = (s: ChatStoreState) => messageMapKey(s.activeId, s.activeTopicId);
+export const currentChatKey = (s: ChatStoreState) => messageMapKey(s.activeId, s.activeTopicId);
/**
* Current active raw message list, include thread messages
@@ -89,7 +89,7 @@ const mainDisplayChats = (s: ChatStoreState): UIChatMessage[] => {
return getChatsWithThread(s, displayChats);
};
-const mainDisplayChatIDs = (s: ChatStoreState) => mainDisplayChats(s).map((s) => s.id);
+export const mainDisplayChatIDs = (s: ChatStoreState) => mainDisplayChats(s).map((s) => s.id);
const mainAIChats = (s: ChatStoreState): UIChatMessage[] => {
const messages = activeBaseChats(s);
@@ -154,7 +154,7 @@ const countMessagesByThreadId = (id: string) => (s: ChatStoreState) => {
return messages.length;
};
-const getMessageByToolCallId = (id: string) => (s: ChatStoreState) => {
+export const getMessageByToolCallId = (id: string) => (s: ChatStoreState) => {
const messages = activeBaseChats(s);
return messages.find((m) => m.tool_call_id === id);
};
@@ -166,67 +166,6 @@ const currentChatLoadingState = (s: ChatStoreState) => !s.messagesInit;
const isCurrentChatLoaded = (s: ChatStoreState) => !!s.messagesMap[currentChatKey(s)];
-const isMessageEditing = (id: string) => (s: ChatStoreState) => s.messageEditingIds.includes(id);
-const isMessageLoading = (id: string) => (s: ChatStoreState) => s.messageLoadingIds.includes(id);
-
-const isMessageGenerating = (id: string) => (s: ChatStoreState) => s.chatLoadingIds.includes(id);
-const isMessageInRAGFlow = (id: string) => (s: ChatStoreState) =>
- s.messageRAGLoadingIds.includes(id);
-const isMessageInChatReasoning = (id: string) => (s: ChatStoreState) =>
- s.reasoningLoadingIds.includes(id);
-
-const isPluginApiInvoking = (id: string) => (s: ChatStoreState) =>
- s.pluginApiLoadingIds.includes(id);
-
-const isToolCallStreaming = (id: string, index: number) => (s: ChatStoreState) => {
- const isLoading = s.toolCallingStreamIds[id];
-
- if (!isLoading) return false;
-
- return isLoading[index];
-};
-
-const isInToolsCalling = (id: string, index: number) => (s: ChatStoreState) => {
- const isStreamingToolsCalling = isToolCallStreaming(id, index)(s);
-
- const isInvokingPluginApi = s.messageInToolsCallingIds.includes(id);
-
- return isStreamingToolsCalling || isInvokingPluginApi;
-};
-
-const isToolApiNameShining =
- (messageId: string, index: number, toolCallId: string) => (s: ChatStoreState) => {
- const toolMessageId = getMessageByToolCallId(toolCallId)(s)?.id;
- const isStreaming = isToolCallStreaming(messageId, index)(s);
- const isPluginInvoking = !toolMessageId ? true : isPluginApiInvoking(toolMessageId)(s);
-
- return isStreaming || isPluginInvoking;
- };
-
-const isAIGenerating = (s: ChatStoreState) =>
- s.chatLoadingIds.some((id) => mainDisplayChatIDs(s).includes(id));
-
-const isInRAGFlow = (s: ChatStoreState) =>
- s.messageRAGLoadingIds.some((id) => mainDisplayChatIDs(s).includes(id));
-
-const isCreatingMessage = (s: ChatStoreState) => s.isCreatingMessage;
-
-const isHasMessageLoading = (s: ChatStoreState) =>
- s.messageLoadingIds.some((id) => mainDisplayChatIDs(s).includes(id));
-
-/**
- * this function is used to determine whether the send button should be disabled
- */
-const isSendButtonDisabledByMessage = (s: ChatStoreState) =>
- // 1. when there is message loading
- isHasMessageLoading(s) ||
- // 2. when is creating the topic
- s.creatingTopic ||
- // 3. when is creating the message
- isCreatingMessage(s) ||
- // 4. when the message is in RAG flow
- isInRAGFlow(s);
-
const inboxActiveTopicMessages = (state: ChatStoreState) => {
const activeTopicId = state.activeTopicId;
return state.messagesMap[messageMapKey(INBOX_SESSION_ID, activeTopicId)] || [];
@@ -280,6 +219,29 @@ const getSupervisorTodos = (groupId?: string, topicId?: string | null) => (s: Ch
return s.supervisorTodos[messageMapKey(groupId, topicId)] || [];
};
+/**
+ * Gets the latest message block from a group message that doesn't contain tools
+ * Returns null if the last block contains tools or if message is not a group message
+ */
+const getGroupLatestMessageWithoutTools = (id: string) => (s: ChatStoreState) => {
+ const message = getMessageById(id)(s);
+
+ if (!message || message.role !== 'group' || !message.children || message.children.length === 0)
+ return;
+
+ // Get the last child
+ const lastChild = message.children.at(-1);
+
+ if (!lastChild) return;
+
+ // Return the last child only if it doesn't have tools
+ if (!lastChild.tools || lastChild.tools.length === 0) {
+ return lastChild;
+ }
+
+ return;
+};
+
export const chatSelectors = {
activeBaseChats,
activeBaseChatsWithoutTool,
@@ -289,6 +251,7 @@ export const chatSelectors = {
currentToolMessages,
currentUserFiles,
getBaseChatsByKey,
+ getGroupLatestMessageWithoutTools,
getMessageById,
getMessageByToolCallId,
getSupervisorTodos,
@@ -296,21 +259,8 @@ export const chatSelectors = {
getThreadMessages,
getTraceIdByMessageId,
inboxActiveTopicMessages,
- isAIGenerating,
- isCreatingMessage,
isCurrentChatLoaded,
- isHasMessageLoading,
- isInToolsCalling,
- isMessageEditing,
- isMessageGenerating,
- isMessageInChatReasoning,
- isMessageInRAGFlow,
- isMessageLoading,
- isPluginApiInvoking,
- isSendButtonDisabledByMessage,
isSupervisorLoading,
- isToolApiNameShining,
- isToolCallStreaming,
latestMessage,
mainAIChats,
mainAIChatsMessageString,
diff --git a/src/store/chat/slices/message/selectors/index.ts b/src/store/chat/slices/message/selectors/index.ts
new file mode 100644
index 00000000000..fb1a0dbb287
--- /dev/null
+++ b/src/store/chat/slices/message/selectors/index.ts
@@ -0,0 +1,2 @@
+export * from './chat';
+export * from './messageState';
diff --git a/src/store/chat/slices/message/selectors/messageState.test.ts b/src/store/chat/slices/message/selectors/messageState.test.ts
new file mode 100644
index 00000000000..e5a3208125f
--- /dev/null
+++ b/src/store/chat/slices/message/selectors/messageState.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+
+import { ChatStore } from '@/store/chat';
+
+import { messageStateSelectors } from './messageState';
+
+describe('messageStateSelectors', () => {
+ describe('isToolCallStreaming', () => {
+ it('should return true when tool call is streaming for given message and index', () => {
+ const state: Partial<ChatStore> = {
+ toolCallingStreamIds: {
+ 'msg-1': [true, false, true],
+ },
+ };
+ expect(messageStateSelectors.isToolCallStreaming('msg-1', 0)(state as ChatStore)).toBe(true);
+ expect(messageStateSelectors.isToolCallStreaming('msg-1', 2)(state as ChatStore)).toBe(true);
+ });
+
+ it('should return false when tool call is not streaming for given message and index', () => {
+ const state: Partial<ChatStore> = {
+ toolCallingStreamIds: {
+ 'msg-1': [true, false, true],
+ },
+ };
+ expect(messageStateSelectors.isToolCallStreaming('msg-1', 1)(state as ChatStore)).toBe(false);
+ expect(messageStateSelectors.isToolCallStreaming('msg-2', 0)(state as ChatStore)).toBe(false);
+ });
+
+ it('should return false when no streaming data exists for the message', () => {
+ const state: Partial<ChatStore> = {
+ toolCallingStreamIds: {},
+ };
+ expect(messageStateSelectors.isToolCallStreaming('msg-1', 0)(state as ChatStore)).toBe(false);
+ });
+ });
+});
diff --git a/src/store/chat/slices/message/selectors/messageState.ts b/src/store/chat/slices/message/selectors/messageState.ts
new file mode 100644
index 00000000000..71b1121179e
--- /dev/null
+++ b/src/store/chat/slices/message/selectors/messageState.ts
@@ -0,0 +1,80 @@
+import type { ChatStoreState } from '../../../initialState';
+import { getMessageByToolCallId, mainDisplayChatIDs } from './chat';
+
+const isMessageEditing = (id: string) => (s: ChatStoreState) => s.messageEditingIds.includes(id);
+const isMessageLoading = (id: string) => (s: ChatStoreState) => s.messageLoadingIds.includes(id);
+
+const isMessageGenerating = (id: string) => (s: ChatStoreState) => s.chatLoadingIds.includes(id);
+const isMessageInRAGFlow = (id: string) => (s: ChatStoreState) =>
+ s.messageRAGLoadingIds.includes(id);
+const isMessageInChatReasoning = (id: string) => (s: ChatStoreState) =>
+ s.reasoningLoadingIds.includes(id);
+
+const isPluginApiInvoking = (id: string) => (s: ChatStoreState) =>
+ s.pluginApiLoadingIds.includes(id);
+
+const isToolCallStreaming = (id: string, index: number) => (s: ChatStoreState) => {
+ const isLoading = s.toolCallingStreamIds[id];
+
+ if (!isLoading) return false;
+
+ return isLoading[index];
+};
+
+const isInToolsCalling = (id: string, index: number) => (s: ChatStoreState) => {
+ const isStreamingToolsCalling = isToolCallStreaming(id, index)(s);
+
+ const isInvokingPluginApi = s.messageInToolsCallingIds.includes(id);
+
+ return isStreamingToolsCalling || isInvokingPluginApi;
+};
+
+const isToolApiNameShining =
+ (messageId: string, index: number, toolCallId: string) => (s: ChatStoreState) => {
+ const toolMessageId = getMessageByToolCallId(toolCallId)(s)?.id;
+ const isStreaming = isToolCallStreaming(messageId, index)(s);
+ const isPluginInvoking = !toolMessageId ? true : isPluginApiInvoking(toolMessageId)(s);
+
+ return isStreaming || isPluginInvoking;
+ };
+
+const isAIGenerating = (s: ChatStoreState) =>
+ s.chatLoadingIds.some((id) => mainDisplayChatIDs(s).includes(id));
+
+const isInRAGFlow = (s: ChatStoreState) =>
+ s.messageRAGLoadingIds.some((id) => mainDisplayChatIDs(s).includes(id));
+
+const isCreatingMessage = (s: ChatStoreState) => s.isCreatingMessage;
+
+const isHasMessageLoading = (s: ChatStoreState) =>
+ s.messageLoadingIds.some((id) => mainDisplayChatIDs(s).includes(id));
+
+/**
+ * this function is used to determine whether the send button should be disabled
+ */
+const isSendButtonDisabledByMessage = (s: ChatStoreState) =>
+ // 1. when there is message loading
+ isHasMessageLoading(s) ||
+ // 2. when is creating the topic
+ s.creatingTopic ||
+ // 3. when is creating the message
+ isCreatingMessage(s) ||
+ // 4. when the message is in RAG flow
+ isInRAGFlow(s);
+
+export const messageStateSelectors = {
+ isAIGenerating,
+ isCreatingMessage,
+ isHasMessageLoading,
+ isInRAGFlow,
+ isInToolsCalling,
+ isMessageEditing,
+ isMessageGenerating,
+ isMessageInChatReasoning,
+ isMessageInRAGFlow,
+ isMessageLoading,
+ isPluginApiInvoking,
+ isSendButtonDisabledByMessage,
+ isToolApiNameShining,
+ isToolCallStreaming,
+};
diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.ts
index 216765f1d98..221086e01c8 100644
--- a/src/store/chat/slices/plugin/action.test.ts
+++ b/src/store/chat/slices/plugin/action.test.ts
@@ -171,7 +171,11 @@ describe('ChatPluginAction', () => {
});
// 验证 messageService.internal_updateMessageContent 是否被正确调用
- expect(messageService.updateMessage).toHaveBeenCalledWith(messageId, { content: newContent });
+ expect(messageService.updateMessage).toHaveBeenCalledWith(
+ messageId,
+ { content: newContent },
+ { sessionId: 'inbox', topicId: null },
+ );
// 验证 refreshMessages 是否被调用
expect(result.current.refreshMessages).toHaveBeenCalled();
@@ -207,7 +211,11 @@ describe('ChatPluginAction', () => {
});
// 验证 messageService.internal_updateMessageContent 是否被正确调用
- expect(messageService.updateMessage).toHaveBeenCalledWith(messageId, { content: newContent });
+ expect(messageService.updateMessage).toHaveBeenCalledWith(
+ messageId,
+ { content: newContent },
+ { sessionId: 'inbox', topicId: null },
+ );
// 验证 refreshMessages 是否被调用
expect(result.current.refreshMessages).toHaveBeenCalled();
@@ -246,9 +254,11 @@ describe('ChatPluginAction', () => {
expect.any(String),
);
expect(runSpy).toHaveBeenCalledWith(pluginPayload, { signal: undefined, trace: {} });
- expect(messageService.updateMessage).toHaveBeenCalledWith(messageId, {
- content: pluginApiResponse,
- });
+ expect(messageService.updateMessage).toHaveBeenCalledWith(
+ messageId,
+ { content: pluginApiResponse },
+ { sessionId: 'inbox', topicId: null },
+ );
expect(storeState.refreshMessages).toHaveBeenCalled();
expect(storeState.internal_togglePluginApiCalling).toHaveBeenCalledWith(
false,
@@ -602,24 +612,18 @@ describe('ChatPluginAction', () => {
});
describe('invokeBuiltinTool', () => {
- it('should invoke a builtin tool and update message content ,then run text2image', async () => {
+ it('should invoke the builtin tool action with parsed arguments', async () => {
const payload = {
- apiName: 'text2image',
- arguments: JSON.stringify({ key: 'value' }),
+ apiName: 'mockBuiltinAction',
+ arguments: JSON.stringify({ input: 'test', value: 123 }),
} as ChatToolPayload;
const messageId = 'message-id';
- const toolResponse = JSON.stringify({ abc: 'data' });
-
- useToolStore.setState({
- transformApiArgumentsToAiState: vi.fn().mockResolvedValue(toolResponse),
- });
+ const mockActionFn = vi.fn().mockResolvedValue(undefined);
useChatStore.setState({
- internal_togglePluginApiCalling: vi.fn(),
- internal_updateMessageContent: vi.fn(),
- text2image: vi.fn(),
- });
+ mockBuiltinAction: mockActionFn,
+ } as any);
const { result } = renderHook(() => useChatStore());
@@ -627,114 +631,39 @@ describe('ChatPluginAction', () => {
await result.current.invokeBuiltinTool(messageId, payload);
});
- // Verify that the builtin tool was invoked with the correct arguments
- expect(useToolStore.getState().transformApiArgumentsToAiState).toHaveBeenCalledWith(
- payload.apiName,
- JSON.parse(payload.arguments),
- );
-
- // Verify that the message content was updated with the tool response
- expect(result.current.internal_updateMessageContent).toHaveBeenCalledWith(
- messageId,
- toolResponse,
- );
-
- // Verify that loading was toggled correctly
- expect(result.current.internal_togglePluginApiCalling).toHaveBeenCalledTimes(2);
-
- expect(result.current.internal_togglePluginApiCalling).toHaveBeenNthCalledWith(
- 1,
- true,
- messageId,
- expect.any(String),
- );
- expect(result.current.internal_togglePluginApiCalling).toHaveBeenNthCalledWith(
- 2,
- false,
- messageId,
- expect.any(String),
- );
- expect(useChatStore.getState().text2image).toHaveBeenCalled();
+ // Verify that the builtin action was called with correct arguments
+ expect(mockActionFn).toHaveBeenCalledWith(messageId, { input: 'test', value: 123 });
});
- it('should invoke a builtin tool and update message content', async () => {
+ it('should not invoke action if apiName does not exist in store', async () => {
const payload = {
- apiName: 'text2image',
+ apiName: 'nonExistentAction',
arguments: JSON.stringify({ key: 'value' }),
} as ChatToolPayload;
const messageId = 'message-id';
- const toolResponse = 'Builtin tool response';
-
- act(() => {
- useToolStore.setState({
- transformApiArgumentsToAiState: vi.fn().mockResolvedValue(toolResponse),
- text2image: vi.fn(),
- });
- useChatStore.setState({
- internal_togglePluginApiCalling: vi.fn(),
- text2image: vi.fn(),
- internal_updateMessageContent: vi.fn(),
- });
- });
const { result } = renderHook(() => useChatStore());
await act(async () => {
await result.current.invokeBuiltinTool(messageId, payload);
});
- // Verify that the builtin tool was invoked with the correct arguments
- expect(useToolStore.getState().transformApiArgumentsToAiState).toHaveBeenCalledWith(
- payload.apiName,
- JSON.parse(payload.arguments),
- );
-
- // Verify that the message content was updated with the tool response
- expect(result.current.internal_togglePluginApiCalling).toHaveBeenCalledTimes(2);
- expect(result.current.internal_updateMessageContent).toHaveBeenCalledWith(
- messageId,
- toolResponse,
- );
-
- // Verify that loading was toggled correctly
- expect(result.current.internal_togglePluginApiCalling).toHaveBeenNthCalledWith(
- 1,
- true,
- messageId,
- expect.any(String),
- );
- expect(result.current.internal_togglePluginApiCalling).toHaveBeenNthCalledWith(
- 2,
- false,
- messageId,
- expect.any(String),
- );
- expect(useChatStore.getState().text2image).not.toHaveBeenCalled();
+ // Should not throw error, just return early
});
- it('should handle errors when transformApiArgumentsToAiState throw error', async () => {
- const args = { key: 'value' };
+ it('should not invoke action if arguments cannot be parsed', async () => {
const payload = {
- apiName: 'builtinApi',
- arguments: JSON.stringify(args),
+ apiName: 'mockBuiltinAction',
+ arguments: 'invalid json',
} as ChatToolPayload;
const messageId = 'message-id';
-
- useToolStore.setState({
- transformApiArgumentsToAiState: vi
- .fn()
- .mockRejectedValue({ error: 'transformApiArgumentsToAiState throw error' }),
- });
+ const mockActionFn = vi.fn().mockResolvedValue(undefined);
useChatStore.setState({
- internal_togglePluginApiCalling: vi.fn(),
- internal_updateMessageContent: vi.fn(),
- internal_updatePluginError: vi.fn(),
- text2image: vi.fn(),
- refreshMessages: vi.fn(),
- });
+ mockBuiltinAction: mockActionFn,
+ } as any);
const { result } = renderHook(() => useChatStore());
@@ -742,35 +671,8 @@ describe('ChatPluginAction', () => {
await result.current.invokeBuiltinTool(messageId, payload);
});
- expect(result.current.internal_updatePluginError).toHaveBeenCalledWith('message-id', {
- type: 'PluginFailToTransformArguments',
- body: {
- message: expect.any(String),
- stack: undefined,
- arguments: args,
- schema: undefined,
- },
- message: expect.any(String),
- });
- // Verify that loading was toggled correctly
- expect(result.current.internal_togglePluginApiCalling).toHaveBeenNthCalledWith(
- 1,
- true,
- messageId,
- expect.any(String),
- );
- expect(result.current.internal_togglePluginApiCalling).toHaveBeenNthCalledWith(
- 2,
- false,
- messageId,
- expect.any(String),
- );
-
- // Verify that the message content was not updated
- expect(result.current.internal_updateMessageContent).not.toHaveBeenCalled();
-
- // Verify that messages were not refreshed
- expect(useChatStore.getState().text2image).not.toHaveBeenCalled();
+ // Should not call the action if arguments can't be parsed
+ expect(mockActionFn).not.toHaveBeenCalled();
});
});
diff --git a/src/store/chat/slices/plugin/action.ts b/src/store/chat/slices/plugin/action.ts
index d2c9d8990b1..b744fcc5a89 100644
--- a/src/store/chat/slices/plugin/action.ts
+++ b/src/store/chat/slices/plugin/action.ts
@@ -1,7 +1,6 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
import { ToolNameResolver } from '@lobechat/context-engine';
import {
- ChatErrorType,
ChatMessageError,
ChatToolPayload,
CreateMessageParams,
@@ -111,54 +110,12 @@ export const chatPlugin: StateCreator<
if (triggerAiMessage) await triggerAIMessage({ parentId: id });
},
invokeBuiltinTool: async (id, payload) => {
- const {
- internal_togglePluginApiCalling,
- internal_updateMessageContent,
- internal_updatePluginError,
- } = get();
- const params = JSON.parse(payload.arguments);
- internal_togglePluginApiCalling(true, id, n('invokeBuiltinTool/start') as string);
- let data;
- try {
- data = await useToolStore.getState().transformApiArgumentsToAiState(payload.apiName, params);
- } catch (error) {
- const err = error as Error;
- console.error(err);
-
- const tool = builtinTools.find((tool) => tool.identifier === payload.identifier);
- const schema = tool?.manifest?.api.find((api) => api.name === payload.apiName)?.parameters;
-
- await internal_updatePluginError(id, {
- type: ChatErrorType.PluginFailToTransformArguments,
- body: {
- message:
- "[plugin] fail to transform plugin arguments to ai state, it may due to model's limited tools calling capacity. You can refer to https://lobehub.com/docs/usage/tools-calling for more detail.",
- stack: err.stack,
- arguments: params,
- schema,
- },
- message: '',
- });
- }
- internal_togglePluginApiCalling(false, id, n('invokeBuiltinTool/end') as string);
-
- if (!data) return;
-
- await internal_updateMessageContent(id, data);
-
// run tool api call
- // postToolCalling
// @ts-ignore
const { [payload.apiName]: action } = get();
if (!action) return;
- let content;
-
- try {
- content = JSON.parse(data);
- } catch {
- /* empty block */
- }
+ const content = safeParseJSON(payload.arguments);
if (!content) return;
diff --git a/src/store/tool/selectors/tool.test.ts b/src/store/tool/selectors/tool.test.ts
index b943c0f03eb..5eef17aaeab 100644
--- a/src/store/tool/selectors/tool.test.ts
+++ b/src/store/tool/selectors/tool.test.ts
@@ -78,7 +78,7 @@ describe('toolSelectors', () => {
describe('metaList and getMetaById', () => {
it('should return the correct list of tool metadata', () => {
- const result = toolSelectors.metaList()(mockState);
+ const result = toolSelectors.metaList(mockState);
expect(result).toEqual([
{
type: 'builtin',
diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.ts
index 4599931bcfc..8c4891d1a7b 100644
--- a/src/store/tool/selectors/tool.ts
+++ b/src/store/tool/selectors/tool.ts
@@ -53,18 +53,16 @@ const enabledSystemRoles =
return '';
};
-const metaList =
- (showDalle?: boolean) =>
- (s: ToolStoreState): LobeToolMeta[] => {
- const pluginList = pluginSelectors.installedPluginMetaList(s) as LobeToolMeta[];
+const metaList = (s: ToolStoreState): LobeToolMeta[] => {
+ const pluginList = pluginSelectors.installedPluginMetaList(s) as LobeToolMeta[];
- return builtinToolSelectors.metaList(showDalle)(s).concat(pluginList);
- };
+ return builtinToolSelectors.metaList(s).concat(pluginList);
+};
const getMetaById =
- (id: string, showDalle: boolean = true) =>
+ (id: string) =>
(s: ToolStoreState): MetaData | undefined => {
- const item = metaList(showDalle)(s).find((m) => m.identifier === id);
+ const item = metaList(s).find((m) => m.identifier === id);
if (!item) return;
diff --git a/src/store/tool/slices/builtin/action.test.ts b/src/store/tool/slices/builtin/action.test.ts
index 71b67e5b29f..8965032772a 100644
--- a/src/store/tool/slices/builtin/action.test.ts
+++ b/src/store/tool/slices/builtin/action.test.ts
@@ -6,19 +6,20 @@ import { useToolStore } from '../../store';
vi.mock('zustand/traditional');
describe('createBuiltinToolSlice', () => {
- describe('invokeBuiltinTool', () => {
- it('should return if the tool is already loading', async () => {
+ describe('transformApiArgumentsToAiState', () => {
+ it('should return early if the tool is already loading', async () => {
// Given
- const key = 'text2image';
- const params = {};
+ const key = 'mockTool';
+ const params = { test: 'data' };
const mockFn = vi.fn();
const { result } = renderHook(() => useToolStore());
act(() => {
useToolStore.setState({
- text2image: mockFn,
- });
+ builtinToolLoading: { [key]: true },
+ mockTool: mockFn,
+ } as any);
});
await act(async () => {
@@ -27,61 +28,108 @@ describe('createBuiltinToolSlice', () => {
expect(data).toBeUndefined();
});
- // Then
- expect(mockFn).toHaveBeenCalled();
+ // Then - should not call the action if already loading
+ expect(mockFn).not.toHaveBeenCalled();
});
it('should invoke the specified tool action and return the stringified result', async () => {
// Given
- const key = 'text2image';
-
- const mockFn = vi.fn();
+ const key = 'mockTool';
+ const mockResult = { success: true, data: 'test result' };
+ const mockFn = vi.fn().mockResolvedValue(mockResult);
const { result } = renderHook(() => useToolStore());
const params = {
- prompts: ['test prompt'],
- size: '512x512',
- quality: 'standard',
- style: 'vivid',
+ input: 'test input',
+ option: 'value',
};
act(() => {
useToolStore.setState({
builtinToolLoading: { [key]: false },
- text2image: mockFn,
+ mockTool: mockFn,
+ } as any);
+ });
+
+ // When
+ let resultData: string | undefined;
+ await act(async () => {
+ resultData = await result.current.transformApiArgumentsToAiState(key, params);
+ });
+
+ // Then
+ expect(mockFn).toHaveBeenCalledWith({
+ input: 'test input',
+ option: 'value',
+ });
+ expect(resultData).toBe(JSON.stringify(mockResult));
+ });
+
+ it('should return stringified params if action does not exist', async () => {
+ // Given
+ const key = 'nonExistentTool';
+ const params = { test: 'data' };
+ const { result } = renderHook(() => useToolStore());
+
+ act(() => {
+ useToolStore.setState({
+ builtinToolLoading: {},
});
});
+
// When
+ let resultData: string | undefined;
await act(async () => {
- await result.current.transformApiArgumentsToAiState(key, params);
+ resultData = await result.current.transformApiArgumentsToAiState(key, params);
});
- expect(mockFn).toBeCalledWith({
- prompts: ['test prompt'],
- quality: 'standard',
- size: '512x512',
- style: 'vivid',
+ // Then
+ expect(resultData).toBe(JSON.stringify(params));
+ });
+
+ it('should handle errors and toggle loading state', async () => {
+ // Given
+ const key = 'mockTool';
+ const params = { test: 'data' };
+ const error = new Error('Tool execution failed');
+ const mockFn = vi.fn().mockRejectedValue(error);
+ const { result } = renderHook(() => useToolStore());
+
+ act(() => {
+ useToolStore.setState({
+ builtinToolLoading: { [key]: false },
+ mockTool: mockFn,
+ } as any);
+ });
+
+ // When/Then
+ await act(async () => {
+ await expect(result.current.transformApiArgumentsToAiState(key, params)).rejects.toThrow(
+ 'Tool execution failed',
+ );
});
+
+ // Should have toggled loading state back to false
+ expect(result.current.builtinToolLoading[key]).toBe(false);
});
});
- describe('text2image', () => {
- it('should map the prompts to DallEImageItem objects', () => {
- // When
+ describe('toggleBuiltinToolLoading', () => {
+ it('should toggle the loading state for a tool', () => {
const { result } = renderHook(() => useToolStore());
+ const key = 'testTool';
+
+ act(() => {
+ result.current.toggleBuiltinToolLoading(key, true);
+ });
+
+ expect(result.current.builtinToolLoading[key]).toBe(true);
- const data = result.current.text2image({
- prompts: ['prompt1', 'prompt2'],
- size: '1024x1024',
- quality: 'standard',
- style: 'vivid',
+ act(() => {
+ result.current.toggleBuiltinToolLoading(key, false);
});
- // Then
- expect(data).toEqual([
- { prompt: 'prompt1', quality: 'standard', size: '1024x1024', style: 'vivid' },
- { prompt: 'prompt2', quality: 'standard', size: '1024x1024', style: 'vivid' },
- ]);
+ expect(result.current.builtinToolLoading[key]).toBe(false);
});
});
});
diff --git a/src/store/tool/slices/builtin/action.ts b/src/store/tool/slices/builtin/action.ts
index 4af802ae20e..15862be8e0f 100644
--- a/src/store/tool/slices/builtin/action.ts
+++ b/src/store/tool/slices/builtin/action.ts
@@ -1,22 +1,15 @@
import { StateCreator } from 'zustand/vanilla';
-import { OpenAIImagePayload } from '@/types/openai/image';
-import { DallEImageItem } from '@/types/tool/dalle';
import { setNamespace } from '@/utils/storeDebug';
import { ToolStore } from '../../store';
const n = setNamespace('builtinTool');
-interface Text2ImageParams extends Pick<OpenAIImagePayload, 'quality' | 'style' | 'size'> {
- prompts: string[];
-}
-
/**
* 代理行为接口
*/
export interface BuiltinToolAction {
- text2image: (params: Text2ImageParams) => DallEImageItem[];
toggleBuiltinToolLoading: (key: string, value: boolean) => void;
transformApiArgumentsToAiState: (key: string, params: any) => Promise<string | undefined>;
}
@@ -27,8 +20,6 @@ export const createBuiltinToolSlice: StateCreator<
[],
BuiltinToolAction
> = (set, get) => ({
- text2image: ({ prompts, size = '1024x1024' as const, quality = 'standard', style = 'vivid' }) =>
- prompts.map((p) => ({ prompt: p, quality, size, style })),
toggleBuiltinToolLoading: (key, value) => {
set({ builtinToolLoading: { [key]: value } }, false, n('toggleBuiltinToolLoading'));
},
diff --git a/src/store/tool/slices/builtin/selectors.test.ts b/src/store/tool/slices/builtin/selectors.test.ts
index 655456cf186..c9450872bc2 100644
--- a/src/store/tool/slices/builtin/selectors.test.ts
+++ b/src/store/tool/slices/builtin/selectors.test.ts
@@ -1,7 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { DalleManifest } from '@/tools/dalle';
-
import { ToolStoreState, initialState } from '../../initialState';
import { builtinToolSelectors } from './selectors';
@@ -10,34 +8,11 @@ describe('builtinToolSelectors', () => {
it('should return meta list excluding Dalle when showDalle is false', () => {
const state = {
...initialState,
- builtinTools: [
- { identifier: 'tool-1', manifest: { meta: { title: 'Tool 1' } } },
- { identifier: DalleManifest.identifier, manifest: { meta: { title: 'Dalle' } } },
- ],
- } as ToolStoreState;
- const result = builtinToolSelectors.metaList(false)(state);
- expect(result).toEqual([
- { author: 'LobeHub', identifier: 'tool-1', meta: { title: 'Tool 1' }, type: 'builtin' },
- ]);
- });
-
- it('should include Dalle when showDalle is true', () => {
- const state = {
- ...initialState,
- builtinTools: [
- { identifier: 'tool-1', manifest: { meta: { title: 'Tool 1' } } },
- { identifier: DalleManifest.identifier, manifest: { meta: { title: 'Dalle' } } },
- ],
+ builtinTools: [{ identifier: 'tool-1', manifest: { meta: { title: 'Tool 1' } } }],
} as ToolStoreState;
- const result = builtinToolSelectors.metaList(true)(state);
+ const result = builtinToolSelectors.metaList(state);
expect(result).toEqual([
{ author: 'LobeHub', identifier: 'tool-1', meta: { title: 'Tool 1' }, type: 'builtin' },
- {
- author: 'LobeHub',
- identifier: DalleManifest.identifier,
- meta: { title: 'Dalle' },
- type: 'builtin',
- },
]);
});
@@ -46,10 +21,9 @@ describe('builtinToolSelectors', () => {
...initialState,
builtinTools: [
{ identifier: 'tool-1', hidden: true, manifest: { meta: { title: 'Tool 1' } } },
- { identifier: DalleManifest.identifier, manifest: { meta: { title: 'Dalle' } } },
],
} as ToolStoreState;
- const result = builtinToolSelectors.metaList(false)(state);
+ const result = builtinToolSelectors.metaList(state);
expect(result).toEqual([]);
});
@@ -58,7 +32,7 @@ describe('builtinToolSelectors', () => {
...initialState,
builtinTools: [],
};
- const result = builtinToolSelectors.metaList(false)(state);
+ const result = builtinToolSelectors.metaList(state);
expect(result).toEqual([]);
});
});
diff --git a/src/store/tool/slices/builtin/selectors.ts b/src/store/tool/slices/builtin/selectors.ts
index 6aaffcc472b..a85b72b2073 100644
--- a/src/store/tool/slices/builtin/selectors.ts
+++ b/src/store/tool/slices/builtin/selectors.ts
@@ -1,32 +1,26 @@
import { LobeToolMeta } from '@lobechat/types';
import { shouldEnableTool } from '@/helpers/toolFilters';
-import { DalleManifest } from '@/tools/dalle';
import type { ToolStoreState } from '../../initialState';
-const metaList =
- (showDalle?: boolean) =>
- (s: ToolStoreState): LobeToolMeta[] =>
- s.builtinTools
- .filter((item) => {
- // Filter hidden tools
- if (item.hidden) return false;
+const metaList = (s: ToolStoreState): LobeToolMeta[] =>
+ s.builtinTools
+ .filter((item) => {
+ // Filter hidden tools
+ if (item.hidden) return false;
- // Filter Dalle if not enabled
- if (!showDalle && item.identifier === DalleManifest.identifier) return false;
+ // Filter platform-specific tools (e.g., LocalSystem desktop-only)
+ if (!shouldEnableTool(item.identifier)) return false;
- // Filter platform-specific tools (e.g., LocalSystem desktop-only)
- if (!shouldEnableTool(item.identifier)) return false;
-
- return true;
- })
- .map((t) => ({
- author: 'LobeHub',
- identifier: t.identifier,
- meta: t.manifest.meta,
- type: 'builtin',
- }));
+ return true;
+ })
+ .map((t) => ({
+ author: 'LobeHub',
+ identifier: t.identifier,
+ meta: t.manifest.meta,
+ type: 'builtin',
+ }));
export const builtinToolSelectors = {
metaList,
diff --git a/src/tools/dalle/Render/GalleyGrid.tsx b/src/tools/dalle/Render/GalleyGrid.tsx
deleted file mode 100644
index 875710f093f..00000000000
--- a/src/tools/dalle/Render/GalleyGrid.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import { useResponsive } from 'antd-style';
-import { ReactNode, memo, useMemo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import Grid from '@/components/GalleyGrid/Grid';
-
-const MAX_SIZE_DESKTOP = 640;
-const MAX_SIZE_MOBILE = 280;
-
-interface GalleyGridProps<T = any> {
- items: T[];
- renderItem: (props: T) => ReactNode;
-}
-
-const GalleyGrid = memo<GalleyGridProps>(({ items, renderItem: Render }) => {
- const { mobile } = useResponsive();
-
- const { firstRow, lastRow } = useMemo(() => {
- if (items.length === 4) {
- return {
- firstRow: items.slice(0, 2),
- lastRow: items.slice(2, 4),
- };
- }
-
- const firstCol = items.length % 3 === 0 ? 3 : items.length % 3;
-
- return {
- firstRow: items.slice(0, firstCol),
- lastRow: items.slice(firstCol, items.length),
- };
- }, [items]);
-
- const { gap, max } = useMemo(
- () => ({
- gap: mobile ? 4 : 6,
- max: (mobile ? MAX_SIZE_MOBILE : MAX_SIZE_DESKTOP) * firstRow.length,
- }),
- [mobile],
- );
-
- return (
- <Flexbox gap={gap}>
- <Grid col={firstRow.length} gap={gap} max={max}>
- {firstRow.map((i, index) => (
- <Render {...i} index={index} key={index} />
- ))}
- </Grid>
- {lastRow.length > 0 && (
- <Grid col={lastRow.length > 2 ? 3 : lastRow.length} gap={gap} max={max}>
- {lastRow.map((i, index) => (
- <Render {...i} index={index} key={index} />
- ))}
- </Grid>
- )}
- </Flexbox>
- );
-});
-
-export default GalleyGrid;
diff --git a/src/tools/dalle/Render/Item/EditMode.tsx b/src/tools/dalle/Render/Item/EditMode.tsx
deleted file mode 100644
index 9fc83bf6807..00000000000
--- a/src/tools/dalle/Render/Item/EditMode.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { Button, Select, TextArea } from '@lobehub/ui';
-import { Radio } from 'antd';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { DallEImageItem } from '@/types/tool/dalle';
-
-interface EditModeProps extends DallEImageItem {
- setEdit: (edit: boolean) => void;
-}
-
-const EditMode = memo<EditModeProps>(({ prompt, setEdit, style, size, quality }) => {
- const { t } = useTranslation('tool');
-
- return (
- <Flexbox gap={16}>
- <TextArea style={{ minHeight: 120 }} value={prompt} variant={'filled'} />
- <Flexbox horizontal justify={'space-between'}>
- 风格
- <Radio.Group
- defaultValue={style}
- options={[
- { label: 'vivid', value: 'vivid' },
- { label: 'natural', value: 'natural' },
- ]}
- />
- </Flexbox>
- <Flexbox horizontal justify={'space-between'}>
- 质量
- <Radio.Group
- defaultValue={quality}
- options={[
- { label: 'standard', value: 'standard' },
- { label: 'hd', value: 'hd' },
- ]}
- />
- </Flexbox>
- <Flexbox horizontal justify={'space-between'}>
- 尺寸
- <Select
- defaultValue={size}
- options={[
- { label: '1792x1024', value: '1792x1024' },
- { label: '1024x1024', value: '1024x1024' },
- { label: '1024x1792', value: '1024x1792' },
- ]}
- size={'small'}
- />
- </Flexbox>
-
- <Flexbox direction={'horizontal-reverse'} gap={12}>
- <Button type={'primary'}>{t('dalle.generate')}</Button>
- <Button
- onClick={() => {
- setEdit(false);
- }}
- >
- {t('cancel', { ns: 'common' })}
- </Button>
- </Flexbox>
- </Flexbox>
- );
-});
-
-export default EditMode;
diff --git a/src/tools/dalle/Render/Item/Error.tsx b/src/tools/dalle/Render/Item/Error.tsx
deleted file mode 100644
index 167e77d7e9a..00000000000
--- a/src/tools/dalle/Render/Item/Error.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { Alert, Button, Highlighter } from '@lobehub/ui';
-import { LucideRefreshCw } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
-
-interface ErrorProps {
- index: number;
- messageId: string;
-}
-
-const Error = memo<ErrorProps>(({ messageId, index }) => {
- const { t } = useTranslation('error');
- const { t: ct } = useTranslation('common');
-
- const error = useChatStore(
- (s) => chatSelectors.getMessageById(messageId)(s)?.pluginState?.['error']?.[index],
- );
- const [reInvokeToolMessage] = useChatStore((s) => [s.reInvokeToolMessage]);
-
- return (
- error && (
- <Flexbox gap={12}>
- <Alert
- extra={
- <Highlighter actionIconSize={'small'} language={'json'}>
- {JSON.stringify(error?.body || error, null, 2)}
- </Highlighter>
- }
- extraDefaultExpand
- message={t(`response.${error.errorType}` as any)}
- type={'error'}
- />
- <Button
- icon={LucideRefreshCw}
- onClick={() => reInvokeToolMessage(messageId)}
- type={'primary'}
- >
- {ct('retry')}
- </Button>
- </Flexbox>
- )
- );
-});
-
-export default Error;
diff --git a/src/tools/dalle/Render/Item/Image.tsx b/src/tools/dalle/Render/Item/Image.tsx
deleted file mode 100644
index 8ccfa84d515..00000000000
--- a/src/tools/dalle/Render/Item/Image.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { Icon, Image, Tooltip } from '@lobehub/ui';
-import { Loader2 } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import ImageFileItem from './ImageFileItem';
-
-interface ImagePreviewProps {
- imageId?: string;
- previewUrl?: string;
- prompt: string;
-}
-
-const ImagePreview = memo<ImagePreviewProps>(({ imageId, previewUrl, prompt }) => {
- const { t } = useTranslation('tool');
-
- return imageId ? (
- // <Flexbox className={styles.action}>
- // <ActionIconGroup
- // items={[{ icon: LucideEdit, key: 'edit', label: t('edit', { ns: 'common' }) }]}
- // onActionClick={(e) => {
- // if (e.key === 'edit') {
- // setEdit(true);
- // }
- // }}
- // />
- // </Flexbox>
- <ImageFileItem id={imageId} />
- ) : (
- previewUrl && (
- <Flexbox style={{ position: 'relative' }}>
- <div style={{ position: 'absolute', right: 8, top: 8, zIndex: 10 }}>
- <Tooltip title={t('dalle.downloading')}>
- <Icon icon={Loader2} size={'large'} spin />
- </Tooltip>
- </div>
- <Image alt={prompt} size={'100%'} src={previewUrl} />
- </Flexbox>
- )
- );
-});
-
-export default ImagePreview;
diff --git a/src/tools/dalle/Render/Item/ImageFileItem.tsx b/src/tools/dalle/Render/Item/ImageFileItem.tsx
deleted file mode 100644
index 26cf80a21ef..00000000000
--- a/src/tools/dalle/Render/Item/ImageFileItem.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { Image } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import { CSSProperties, memo } from 'react';
-
-import { usePlatform } from '@/hooks/usePlatform';
-import { useChatStore } from '@/store/chat';
-
-const MIN_IMAGE_SIZE = 64;
-
-export const useStyles = createStyles(({ css, token }) => ({
- deleteButton: css`
- color: #fff;
- background: ${token.colorBgMask};
-
- &:hover {
- background: ${token.colorError};
- }
- `,
- editableImage: css`
- background: ${token.colorBgContainer};
- box-shadow: 0 0 0 1px ${token.colorFill} inset;
- `,
- image: css`
- margin-block: 0 !important;
- `,
-}));
-
-interface FileItemProps {
- alwaysShowClose?: boolean;
- className?: string;
- editable?: boolean;
- id: string;
- onClick?: () => void;
- style?: CSSProperties;
-}
-const ImageFileItem = memo<FileItemProps>(({ editable, id, alwaysShowClose }) => {
- const [useFetchDalleImageItem] = useChatStore((s) => [s.useFetchDalleImageItem]);
- const IMAGE_SIZE = editable ? MIN_IMAGE_SIZE : '100%';
- const { data, isLoading } = useFetchDalleImageItem(id);
- const { styles, cx } = useStyles();
- const { isSafari } = usePlatform();
-
- return (
- <Image
- alt={data?.name || id || ''}
- alwaysShowActions={alwaysShowClose}
- height={isSafari ? 'auto' : '100%'}
- isLoading={isLoading}
- size={IMAGE_SIZE as any}
- src={data?.url}
- style={{ height: isSafari ? 'auto' : '100%' }}
- wrapperClassName={cx(styles.image, editable && styles.editableImage)}
- />
- );
-});
-
-export default ImageFileItem;
diff --git a/src/tools/dalle/Render/Item/index.tsx b/src/tools/dalle/Render/Item/index.tsx
deleted file mode 100644
index 79f67f940a5..00000000000
--- a/src/tools/dalle/Render/Item/index.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import { Highlighter, Icon } from '@lobehub/ui';
-import { Spin } from 'antd';
-import { createStyles } from 'antd-style';
-import { Loader2 } from 'lucide-react';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { useChatStore } from '@/store/chat';
-import { chatToolSelectors } from '@/store/chat/selectors';
-import { DallEImageItem } from '@/types/tool/dalle';
-
-import EditMode from './EditMode';
-import Error from './Error';
-import ImagePreview from './Image';
-
-const useStyles = createStyles(({ css, token, prefixCls }) => ({
- action: css`
- position: absolute;
- z-index: 100;
- inset-block-start: 4px;
- inset-inline-end: 4px;
- `,
- container: css`
- overflow: scroll;
- aspect-ratio: 1;
- border: 1px solid ${token.colorBorder};
- border-radius: 8px;
-
- .${prefixCls}-spin-nested-loading {
- height: 100%;
- }
- `,
-}));
-
-const ImageItem = memo<DallEImageItem & { index: number; messageId: string }>(
- ({ prompt, messageId, imageId, previewUrl, index, style, size, quality }) => {
- const { t } = useTranslation('tool');
- const { styles } = useStyles();
-
- const [edit, setEdit] = useState(false);
- const loading = useChatStore(chatToolSelectors.isDallEImageGenerating(messageId + prompt));
-
- if (edit)
- return (
- <Flexbox className={styles.container} padding={8}>
- <EditMode
- imageId={imageId}
- prompt={prompt}
- quality={quality}
- setEdit={setEdit}
- size={size}
- style={style}
- />
- </Flexbox>
- );
-
- if (imageId || previewUrl)
- return <ImagePreview imageId={imageId} previewUrl={previewUrl} prompt={prompt} />;
-
- return (
- <Flexbox className={styles.container} padding={8}>
- {loading ? (
- <Spin indicator={<Icon icon={Loader2} spin />} size={'large'} tip={t('dalle.generating')}>
- {prompt}
- </Spin>
- ) : (
- <Flexbox gap={12}>
- <Flexbox>
- <Highlighter
- actionIconSize={'small'}
- fileName={t('dalle.prompt')}
- fullFeatured
- language={'prompt'}
- showLanguage
- >
- {prompt}
- </Highlighter>
- </Flexbox>
- <Error index={index} messageId={messageId} />
- </Flexbox>
- )}
- </Flexbox>
- );
- },
-);
-
-export default ImageItem;
diff --git a/src/tools/dalle/Render/ToolBar.tsx b/src/tools/dalle/Render/ToolBar.tsx
deleted file mode 100644
index 112bb17f290..00000000000
--- a/src/tools/dalle/Render/ToolBar.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { Button } from '@lobehub/ui';
-import { Checkbox } from 'antd';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { useChatStore } from '@/store/chat';
-import { chatToolSelectors } from '@/store/chat/selectors';
-import { useUserStore } from '@/store/user';
-import { settingsSelectors } from '@/store/user/selectors';
-import { DallEImageItem } from '@/types/tool/dalle';
-
-interface ToolBarProps {
- content: DallEImageItem[];
- messageId: string;
-}
-
-const ToolBar = memo<ToolBarProps>(({ content, messageId }) => {
- const { t } = useTranslation('tool');
- const generateImageFromPrompts = useChatStore((s) => s.generateImageFromPrompts);
- const isLoading = useChatStore(chatToolSelectors.isGeneratingDallEImage);
-
- const [isAutoGenerate, setSettings] = useUserStore((s) => [
- settingsSelectors.isDalleAutoGenerating(s),
- s.setSettings,
- ]);
-
- const genImages = () => {
- generateImageFromPrompts(content, messageId);
- };
-
- const canGen = content.some((i) => !i.imageId);
-
- return (
- <Flexbox align={'center'} height={28} horizontal justify={'space-between'}>
- {t('dalle.images')}
- <Flexbox align={'center'} gap={8} horizontal>
- <Checkbox
- checked={isAutoGenerate}
- onChange={(e) => {
- setSettings({ tool: { dalle: { autoGenerate: e.target.checked } } });
- }}
- >
- {t('dalle.autoGenerate')}
- </Checkbox>
- {canGen && (
- <Button loading={isLoading} onClick={genImages} size={'small'} type={'primary'}>
- {t('dalle.generate')}
- </Button>
- )}
- </Flexbox>
- </Flexbox>
- );
-});
-
-export default ToolBar;
diff --git a/src/tools/dalle/Render/index.tsx b/src/tools/dalle/Render/index.tsx
deleted file mode 100644
index 02ad5668163..00000000000
--- a/src/tools/dalle/Render/index.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { BuiltinRenderProps } from '@lobechat/types';
-import { ActionIcon, PreviewGroup } from '@lobehub/ui';
-import { Download } from 'lucide-react';
-import { memo, useRef } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import { fileService } from '@/services/file';
-import { DallEImageItem } from '@/types/tool/dalle';
-
-import GalleyGrid from './GalleyGrid';
-import ImageItem from './Item';
-
-const DallE = memo<BuiltinRenderProps<DallEImageItem[]>>(({ content, messageId }) => {
- const currentRef = useRef(0);
-
- const handleDownload = async () => {
- // 1. Retrieve the blob URL of an image by its imageId
- const id = content[currentRef.current]?.imageId;
- if (!id) return;
- const { url, name } = await fileService.getFile(id);
- // 2. Download the image
- const link = document.createElement('a');
- link.href = url;
- link.download = name; // 设置下载的文件名
- link.click();
- };
-
- return (
- <Flexbox gap={16}>
- {/* 没想好工具条的作用 */}
- {/*<ToolBar content={content} messageId={messageId} />*/}
- <PreviewGroup
- preview={{
- // 切换图片时设置
- onChange: (current: number) => {
- currentRef.current = current;
- },
- // 点击预览显示时设置
-
- onVisibleChange: (visible: boolean, _prevVisible: boolean, current: number) => {
- currentRef.current = current;
- },
- toolbarAddon: <ActionIcon color={'#fff'} icon={Download} onClick={handleDownload} />,
- }}
- >
- <GalleyGrid items={content.map((c) => ({ ...c, messageId }))} renderItem={ImageItem} />
- </PreviewGroup>
- </Flexbox>
- );
-});
-
-export default DallE;
diff --git a/src/tools/dalle/index.ts b/src/tools/dalle/index.ts
deleted file mode 100644
index f9025b65134..00000000000
--- a/src/tools/dalle/index.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { BuiltinToolManifest } from '@lobechat/types';
-
-// import {SiOpenai} from "@icons-pack/react-simple-icons";
-
-export const DalleManifest: BuiltinToolManifest = {
- api: [
- {
- description: 'Create images from a text-only prompt.',
- name: 'text2image',
- parameters: {
- properties: {
- prompts: {
- description:
- "The user's original image description, potentially modified to abide by the lobe-image-designer policies. If the user does not suggest a number of captions to create, create four of them. If creating multiple captions, make them as diverse as possible. If the user requested modifications to previous images, the captions should not simply be longer, but rather it should be refactored to integrate the suggestions into each of the captions. Generate no more than 4 images, even if the user requests more.",
- items: {
- type: 'string',
- },
- maxItems: 4,
- minItems: 1,
- type: 'array',
- },
- quality: {
- default: 'standard',
- description:
- 'The quality of the image that will be generated. hd creates images with finer details and greater consistency across the image.',
- enum: ['standard', 'hd'],
- type: 'string',
- },
- seeds: {
- description:
- 'A list of seeds to use for each prompt. If the user asks to modify a previous image, populate this field with the seed used to generate that image from the image lobe-image-designer metadata.',
- items: {
- type: 'integer',
- },
- type: 'array',
- },
- size: {
- default: '1024x1024',
- description:
- 'The resolution of the requested image, which can be wide, square, or tall. Use 1024x1024 (square) as the default unless the prompt suggests a wide image, 1792x1024, or a full-body portrait, in which case 1024x1792 (tall) should be used instead. Always include this parameter in the request.',
- enum: ['1792x1024', '1024x1024', '1024x1792'],
- type: 'string',
- },
- style: {
- default: 'vivid',
- description:
- 'The style of the generated images. Must be one of vivid or natural. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images.',
- enum: ['vivid', 'natural'],
- type: 'string',
- },
- },
- required: ['prompts'],
- type: 'object',
- },
- },
- ],
- // due to system prompt is for training Dalle3 as a built-in tool by OpenAI,
- // there are occasional instances where the function call contains the name "dalle," leading to subsequent failures.
- // so we need a different unique identifier to avoid failure.refs:
- // https://github.com/lobehub/lobe-chat/issues/783
- // https://github.com/lobehub/lobe-chat/issues/870
- identifier: 'lobe-image-designer',
- meta: {
- avatar: `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5NiIgaGVpZ2h0PSI5NiIgZmlsbD0ibm9uZSIgc3R5bGU9ImNvbG9yOiNmZmY7ZmlsbDojMDAwIj4KICAgIDxwYXRoIGQ9Ik0wIDBoOTZ2OTZIMHoiLz4KICAgIDxwYXRoIGZpbGw9ImN1cnJlbnRDb2xvciIKICAgICAgICAgIGQ9Ik03OC44MyA0MS40NjJBMTcuOTQgMTcuOTQgMCAwIDAgNzcuMjkgMjYuNzNhMTguMTQgMTguMTQgMCAwIDAtMTkuNTM4LTguNzA0IDE3LjkzNyAxNy45MzcgMCAwIDAtMTMuNTI5LTYuMDMxIDE4LjE0MyAxOC4xNDMgMCAwIDAtMTcuMzA1IDEyLjU2IDE3Ljk0NiAxNy45NDYgMCAwIDAtMTEuOTk0IDguNzAxIDE4LjE0MyAxOC4xNDMgMCAwIDAgMi4yMzMgMjEuMjcxIDE3LjkzOCAxNy45MzggMCAwIDAgMS41NCAxNC43MzIgMTguMTQxIDE4LjE0MSAwIDAgMCAxOS41MzggOC43MDQgMTcuOTMgMTcuOTMgMCAwIDAgMTMuNTI4IDYuMDMxQTE4LjE0MiAxOC4xNDIgMCAwIDAgNjkuMDggNzEuNDI3YTE3LjkzOCAxNy45MzggMCAwIDAgMTEuOTk0LTguNzAxIDE4LjE0MSAxOC4xNDEgMCAwIDAtMi4yNDMtMjEuMjY0Wk01MS45MSA3OS4yODdjLTMuNTgzIDAtNi4zNTYtMS4xLTguNzgtMy4xMjIuMTEtLjA2LjMwMi0uMTY1LjQyNy0uMjQybDE0LjMzNi04LjI4YTIuMzI3IDIuMzI3IDAgMCAwIDEuMTc4LTIuMDRWNDUuMzkybDYuMDYgMy40OTlhLjIxNy4yMTcgMCAwIDEgLjExOC4xNjZWNjUuNzljLS4wMDEgNy41OTMtNi4zMjIgMTMuNDk3LTEzLjM0IDEzLjQ5N1pNMjIuNzc4IDY2LjkwNmExMy40NDcgMTMuNDQ3IDAgMCAxLTEuNjEtOS4wNDJjLjEwNy4wNjQuMjkzLjE3OC40MjYuMjU0TDM1LjkzIDY2LjRhMi4zMyAyLjMzIDAgMCAwIDIuMzU1IDBsMTcuNTAzLTEwLjEwNnY2Ljk5OGEuMjE3LjIxNyAwIDAgMS0uMDg3LjE4Nkw0MS4yMSA3MS44NDRhMTMuNTA3IDEzLjUwNyAwIDAgMS0xOC40MzEtNC45MzhabS0zLjc3Ny0zMS4yOTdhMTMuNDQ5IDEzLjQ0OSAwIDAgMSA3LjAyMy01LjkxNlY0Ni43NWEyLjMyNCAyLjMyNCAwIDAgMCAxLjE3NyAyLjAzOGwxNy41MDEgMTAuMTA1LTYuMDYgMy40OTlhLjIxOC4yMTggMCAwIDEtLjIwNC4wMThsLTE0LjQ5My04LjM3NEExMy41MDcgMTMuNTA3IDAgMCAxIDE5IDM1LjYwOVptNDkuNzkgMTEuNTg3TDUxLjI4OCAzNy4wOWw2LjA2LTMuNDk4YS4yMi4yMiAwIDAgMSAuMjA0LS4wMThsMTQuNDk0IDguMzdhMTMuNDk1IDEzLjQ5NSAwIDAgMS0yLjA4OCAyNC4zNDZWNDkuMjMzYTIuMzI4IDIuMzI4IDAgMCAwLTEuMTY3LTIuMDM3Wm02LjAzLTkuMDg0YTIwLjA2NCAyMC4wNjQgMCAwIDAtLjQyNS0uMjU0TDYwLjA2IDI5LjU3N2EyLjMzNyAyLjMzNyAwIDAgMC0yLjM1NSAwTDQwLjIwMyAzOS42ODN2LTYuOTk4YS4yMTguMjE4IDAgMCAxIC4wODYtLjE4NmwxNC40OTItOC4zNmExMy40OTUgMTMuNDk1IDAgMCAxIDIwLjA0IDEzLjk3M1pNMzYuOTA5IDUwLjU5bC02LjA2LTMuNDk5YS4yMS4yMSAwIDAgMS0uMTE4LS4xNjZWMzAuMTg3YTEzLjQ5NCAxMy40OTQgMCAwIDEgMjIuMTI4LTEwLjM2MWMtLjExLjA2LS4zLjE2NC0uNDI2LjI0bC0xNC4zMzYgOC4yODJhMi4zMzIgMi4zMzIgMCAwIDAtMS4xNzggMi4wMzhsLS4wMSAyMC4yMDRabTMuMjkyLTcuMDk3IDcuNzk1LTQuNTAzIDcuNzk2IDQuNXY5LjAwMmwtNy43OTYgNC40OTgtNy43OTUtNC41di04Ljk5N1oiLz4KPC9zdmc+Cg==`,
- title: 'DALL·E 3',
- },
- systemRole: `Whenever a description of an image is given, use lobe-image-designer to create the images and then summarize the prompts used to generate the images in plain text. If the user does not ask for a specific number of images, default to creating four captions to send to lobe-image-designer that are written to be as diverse as possible.
-
- All captions sent to lobe-image-designer must abide by the following policies:
-
-1. If the description is not in English, then translate it.
-2. Do not create more than 4 images, even if the user requests more.
-3. Don't create images of politicians or other public figures. Recommend other ideas instead.
-5. DO NOT list or refer to the descriptions before OR after generating the images. They should ONLY ever be written out ONCE, in the \`prompts\` field of the request. You do not need to ask for permission to generate, just do it!
-6. Always mention the image type (photo, oil painting, watercolor painting, illustration, cartoon, drawing, vector, render, etc.) at the beginning of the caption. Unless the caption suggests otherwise, make at least 1--2 of the 4 images photos.
-7. Diversify depictions of ALL images with people to include DESCENT and GENDER for EACH person using direct terms. Adjust only human descriptions.
- - EXPLICITLY specify these attributes, not abstractly reference them. The attributes should be specified in a minimal way and should directly describe their physical form.
- - Your choices should be grounded in reality. For example, all of a given OCCUPATION should not be the same gender or race. Additionally, focus on creating diverse, inclusive, and exploratory scenes via the properties you choose during rewrites. Make choices that may be insightful or unique sometimes.
- - Use "various" or "diverse" ONLY IF the description refers to groups of more than 3 people. Do not change the number of people requested in the original description.
- - Don't alter memes, fictional character origins, or unseen people. Maintain the original prompt's intent and prioritize quality.
- - Do not create any imagery that would be offensive.
-
-8. Silently modify descriptions that include names or hints or references of specific people or celebrities by carefully selecting a few minimal modifications to substitute references to the people with generic descriptions that don't divulge any information about their identities, except for their genders and physiques. Do this EVEN WHEN the instructions ask for the prompt to not be changed. Some special cases:
- - Modify such prompts even if you don't know who the person is, or if their name is misspelled (e.g. "Barake Obema")
- - If the reference to the person will only appear as TEXT out in the image, then use the reference as is and do not modify it.
- - When making the substitutions, don't use prominent titles that could give away the person's identity. E.g., instead of saying "president", "prime minister", or "chancellor", say "politician"; instead of saying "king", "queen", "emperor", or "empress", say "public figure"; instead of saying "Pope", say "religious figure"; and so on.
- - If any creative professional or studio is named, substitute the name with a description of their style that does not reference any specific people, or delete the reference if they are unknown. DO NOT refer to the artist or studio's style.
-
-The prompt must intricately describe every part of the image in concrete, objective detail. THINK about what the end goal of the description is, and extrapolate that to what would make satisfying images.
-All descriptions sent to lobe-image-designer should be a paragraph of text that is extremely descriptive and detailed. Each should be more than 3 sentences long.`,
- type: 'builtin',
-};
diff --git a/src/tools/index.ts b/src/tools/index.ts
index aaeaa1233b8..51dcb12934a 100644
--- a/src/tools/index.ts
+++ b/src/tools/index.ts
@@ -4,7 +4,6 @@ import { isDesktop } from '@/const/version';
import { ArtifactsManifest } from './artifacts';
import { CodeInterpreterManifest } from './code-interpreter';
-import { DalleManifest } from './dalle';
import { LocalSystemManifest } from './local-system';
import { WebBrowsingManifest } from './web-browsing';
@@ -14,11 +13,6 @@ export const builtinTools: LobeBuiltinTool[] = [
manifest: ArtifactsManifest,
type: 'builtin',
},
- {
- identifier: DalleManifest.identifier,
- manifest: DalleManifest,
- type: 'builtin',
- },
{
hidden: !isDesktop,
identifier: LocalSystemManifest.identifier,
diff --git a/src/tools/renders.ts b/src/tools/renders.ts
index fe510e26739..044cef6b926 100644
--- a/src/tools/renders.ts
+++ b/src/tools/renders.ts
@@ -2,15 +2,12 @@ import { BuiltinRender } from '@lobechat/types';
import { CodeInterpreterManifest } from './code-interpreter';
import CodeInterpreterRender from './code-interpreter/Render';
-import { DalleManifest } from './dalle';
-import DalleRender from './dalle/Render';
import { LocalSystemManifest } from './local-system';
import LocalFilesRender from './local-system/Render';
import { WebBrowsingManifest } from './web-browsing';
import WebBrowsing from './web-browsing/Render';
export const BuiltinToolsRenders: Record<string, BuiltinRender> = {
- [DalleManifest.identifier]: DalleRender as BuiltinRender,
[WebBrowsingManifest.identifier]: WebBrowsing as BuiltinRender,
[LocalSystemManifest.identifier]: LocalFilesRender as BuiltinRender,
[CodeInterpreterManifest.identifier]: CodeInterpreterRender as BuiltinRender,
diff --git a/src/tools/web-browsing/Portal/Search/Footer.tsx b/src/tools/web-browsing/Portal/Search/Footer.tsx
index 3c443d6f813..daa8bd88151 100644
--- a/src/tools/web-browsing/Portal/Search/Footer.tsx
+++ b/src/tools/web-browsing/Portal/Search/Footer.tsx
@@ -4,12 +4,12 @@ import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors, chatSelectors } from '@/store/chat/selectors';
+import { chatPortalSelectors, messageStateSelectors } from '@/store/chat/selectors';
const Footer = () => {
const [messageId, isAIGenerating, triggerAIMessage, saveSearchResult] = useChatStore((s) => [
chatPortalSelectors.toolMessageId(s),
- chatSelectors.isAIGenerating(s),
+ messageStateSelectors.isAIGenerating(s),
s.triggerAIMessage,
s.saveSearchResult,
]);