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: refactor mcp context use and support continueGeneration (#10096)

Arvin Xu2ae4aeb58d0b
diff --git a/packages/context-engine/src/processors/MessageCleanup.ts b/packages/context-engine/src/processors/MessageCleanup.ts
index 2c4560c2cc6..6e97f991d9a 100644
--- a/packages/context-engine/src/processors/MessageCleanup.ts
+++ b/packages/context-engine/src/processors/MessageCleanup.ts
@@ -66,6 +66,7 @@ export class MessageCleanupProcessor extends BaseProcessor {
content: message.content,
role: message.role,
...(message.tool_calls && { tool_calls: message.tool_calls }),
+ ...(message.reasoning && { reasoning: message.reasoning }),
};
}
diff --git a/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts b/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts
index 8df0f34adf5..0be2b34c059 100644
--- a/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts
+++ b/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts
@@ -131,6 +131,34 @@ describe('MessageCleanupProcessor', () => {
});
});
+ it('should preserve reasoning in assistant messages', async () => {
+ const processor = new MessageCleanupProcessor();
+ const reasoning = {
+ content: 'Let me think about this...',
+ signature: 'sha256:abc123',
+ };
+
+ const context = createContext([
+ {
+ content: 'Here is the answer',
+ extraField: 'remove',
+ id: 'msg5',
+ reasoning: reasoning,
+ role: 'assistant',
+ timestamp: Date.now(),
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0]).toEqual({
+ content: 'Here is the answer',
+ reasoning: reasoning,
+ role: 'assistant',
+ });
+ });
+
it('should clean tool messages with name', async () => {
const processor = new MessageCleanupProcessor();
const context = createContext([
diff --git a/src/features/Conversation/Messages/Assistant/Tool/Render/CustomRender.tsx b/src/features/Conversation/Messages/Assistant/Tool/Render/CustomRender.tsx
index becbb080e49..b8797aecc85 100644
--- a/src/features/Conversation/Messages/Assistant/Tool/Render/CustomRender.tsx
+++ b/src/features/Conversation/Messages/Assistant/Tool/Render/CustomRender.tsx
@@ -46,8 +46,8 @@ const CustomRender = memo<CustomRenderProps>(
const [loading] = useChatStore((s) => [messageStateSelectors.isPluginApiInvoking(id)(s)]);
const [isEditing, setIsEditing] = useState(false);
const { message } = App.useApp();
- const [updatePluginArguments, reInvokeToolMessage] = useChatStore((s) => [
- s.updatePluginArguments,
+ const [optimisticUpdatePluginArguments, reInvokeToolMessage] = useChatStore((s) => [
+ s.optimisticUpdatePluginArguments,
s.reInvokeToolMessage,
]);
const handleCancel = useCallback(() => {
@@ -62,7 +62,7 @@ const CustomRender = memo<CustomRenderProps>(
const newArgsString = JSON.stringify(editedObject, null, 2);
if (newArgsString !== requestArgs) {
- await updatePluginArguments(id, editedObject, true);
+ await optimisticUpdatePluginArguments(id, editedObject, true);
await reInvokeToolMessage(id);
}
setIsEditing(false);
diff --git a/src/features/Conversation/Messages/Group/Actions/WithoutContentId.tsx b/src/features/Conversation/Messages/Group/Actions/WithoutContentId.tsx
index 032e1f2c9da..2e6c52bfd6b 100644
--- a/src/features/Conversation/Messages/Group/Actions/WithoutContentId.tsx
+++ b/src/features/Conversation/Messages/Group/Actions/WithoutContentId.tsx
@@ -1,12 +1,14 @@
import { UIChatMessage } from '@lobechat/types';
-import { ActionIconGroup, type ActionIconGroupEvent, ActionIconGroupItemType } from '@lobehub/ui';
+import { ActionIconGroup, type ActionIconGroupEvent } from '@lobehub/ui';
import { useSearchParams } from 'next/navigation';
-import { memo, useCallback, useContext, useMemo } from 'react';
+import { memo, useCallback, useContext } from 'react';
import { useChatStore } from '@/store/chat';
-import { threadSelectors } from '@/store/chat/selectors';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
+import {
+ displayMessageSelectors,
+ messageStateSelectors,
+ threadSelectors,
+} from '@/store/chat/selectors';
import { InPortalThreadContext } from '../../../context/InPortalThreadContext';
import { useChatListActionsBar } from '../../../hooks/useChatListActionsBar';
@@ -17,28 +19,38 @@ interface GroupActionsProps {
}
const WithoutContentId = memo<GroupActionsProps>(({ id, data }) => {
- const [isThreadMode, hasThread] = useChatStore((s) => [
- !!s.activeThreadId,
+ const [hasThread, lastBlockId] = useChatStore((s) => [
threadSelectors.hasThreadBySourceMsgId(id)(s),
+ displayMessageSelectors.findLastMessageId(id)(s),
]);
- const isGroupSession = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);
- const { delAndRegenerate, del } = useChatListActionsBar({ hasThread });
+ const isContinuing = useChatStore((s) =>
+ lastBlockId ? messageStateSelectors.isMessageContinuing(lastBlockId)(s) : false,
+ );
+
+ const { delAndRegenerate, del, continueGeneration } = useChatListActionsBar({
+ hasThread,
+ isContinuing,
+ });
const inPortalThread = useContext(InPortalThreadContext);
- const inThread = isThreadMode || inPortalThread;
+ // const inThread = isThreadMode || inPortalThread;
- const items = useMemo(() => {
- return [delAndRegenerate, del].filter(Boolean) as ActionIconGroupItemType[];
- }, [inThread, isGroupSession]);
+ const items = [continueGeneration, delAndRegenerate, del];
const searchParams = useSearchParams();
const topic = searchParams.get('topic');
- const [deleteMessage, delAndRegenerateMessage, delAndResendThreadMessage] = useChatStore((s) => [
+ const [
+ deleteMessage,
+ delAndRegenerateMessage,
+ delAndResendThreadMessage,
+ continueGenerationMessage,
+ ] = useChatStore((s) => [
s.deleteMessage,
s.delAndRegenerateMessage,
s.delAndResendThreadMessage,
+ s.continueGenerationMessage,
]);
const onActionClick = useCallback(
@@ -46,6 +58,17 @@ const WithoutContentId = memo<GroupActionsProps>(({ id, data }) => {
if (!data) return;
switch (action.key) {
+ case 'continueGeneration': {
+ const lastMessageId = displayMessageSelectors.findLastMessageId(id)(
+ useChatStore.getState(),
+ );
+
+ if (!lastMessageId) return;
+
+ continueGenerationMessage(lastMessageId, id);
+ break;
+ }
+
case 'del': {
deleteMessage(id);
break;
diff --git a/src/features/Conversation/Messages/Group/Error/index.tsx b/src/features/Conversation/Messages/Group/Error/index.tsx
index c3d4f110ee9..a89542a8492 100644
--- a/src/features/Conversation/Messages/Group/Error/index.tsx
+++ b/src/features/Conversation/Messages/Group/Error/index.tsx
@@ -17,7 +17,7 @@ const ErrorContent = memo<ErrorContentProps>(({ error, id }) => {
const { t } = useTranslation('common');
const errorProps = useErrorContent(error);
- const [deleteMessage] = useChatStore((s) => [s.deleteMessage]);
+ const [deleteMessage] = useChatStore((s) => [s.deleteDBMessage]);
const message = <ErrorMessageExtra block data={{ error, id }} />;
if (!error?.message) {
diff --git a/src/features/Conversation/Messages/Group/GroupChildren.tsx b/src/features/Conversation/Messages/Group/GroupChildren.tsx
index 24bfd2163fb..e0a1f1a1a00 100644
--- a/src/features/Conversation/Messages/Group/GroupChildren.tsx
+++ b/src/features/Conversation/Messages/Group/GroupChildren.tsx
@@ -1,12 +1,10 @@
import { AssistantContentBlock } from '@lobechat/types';
import { createStyles } from 'antd-style';
-import { memo, use } from 'react';
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
-import { VirtuosoContext } from '@/features/Conversation/components/VirtualizedList/VirtuosoContext';
-import { useChatStore } from '@/store/chat';
-
-import { ContentBlock } from './ContentBlock';
+import GroupItem from './GroupItem';
const useStyles = createStyles(({ css }) => {
return {
@@ -30,44 +28,24 @@ const GroupChildren = memo<GroupChildrenProps>(
({ blocks, contentId, disableEditing, messageIndex, id }) => {
const { styles } = useStyles();
- const [toggleMessageEditing] = useChatStore((s) => [s.toggleMessageEditing]);
- const virtuosoRef = use(VirtuosoContext);
-
return (
<Flexbox className={styles.container} gap={8}>
{blocks.map((item, index) => {
- return item.id === contentId ? (
- <Flexbox
- key={index}
- onDoubleClick={(e) => {
- if (disableEditing || item.error || !e.altKey) return;
-
- toggleMessageEditing(item.id, true);
- virtuosoRef?.current?.scrollIntoView({
- align: 'start',
- behavior: 'auto',
- index: messageIndex,
- });
- }}
- >
- <ContentBlock index={index} {...item} />
- </Flexbox>
- ) : (
- // <motion.div
- // animate={{ height: 'auto', opacity: 1 }}
- // exit={{ height: 0, opacity: 0 }}
- // initial={{ height: 0, opacity: 0 }}
- // key={`${id}_${index}`}
- // style={{ overflow: 'hidden' }}
- // transition={{ duration: 0.3, ease: 'easeInOut' }}
- // >
- <ContentBlock index={index} key={`${id}_${index}`} {...item} />
- // </motion.div>
+ return (
+ <GroupItem
+ {...item}
+ contentId={contentId}
+ disableEditing={disableEditing}
+ index={index}
+ key={`${id}_${index}`}
+ messageIndex={messageIndex}
+ />
);
})}
</Flexbox>
);
},
+ isEqual,
);
export default GroupChildren;
diff --git a/src/features/Conversation/Messages/Group/GroupItem.tsx b/src/features/Conversation/Messages/Group/GroupItem.tsx
new file mode 100644
index 00000000000..9dec53cbfb8
--- /dev/null
+++ b/src/features/Conversation/Messages/Group/GroupItem.tsx
@@ -0,0 +1,43 @@
+import { AssistantContentBlock } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+import { memo, use } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ContentBlock } from '@/features/Conversation/Messages/Group/ContentBlock';
+import { VirtuosoContext } from '@/features/Conversation/components/VirtualizedList/VirtuosoContext';
+import { useChatStore } from '@/store/chat';
+
+interface GroupItemProps extends AssistantContentBlock {
+ contentId?: string;
+ disableEditing?: boolean;
+ index: number;
+ messageIndex: number;
+}
+
+const GroupItem = memo<GroupItemProps>(
+ ({ contentId, messageIndex, index, disableEditing, error, ...item }) => {
+ const [toggleMessageEditing] = useChatStore((s) => [s.toggleMessageEditing]);
+ const virtuosoRef = use(VirtuosoContext);
+
+ return item.id === contentId ? (
+ <Flexbox
+ onDoubleClick={(e) => {
+ if (disableEditing || error || !e.altKey) return;
+
+ toggleMessageEditing(item.id, true);
+ virtuosoRef?.current?.scrollIntoView({
+ align: 'start',
+ behavior: 'auto',
+ index: messageIndex,
+ });
+ }}
+ >
+ <ContentBlock index={index} {...item} />
+ </Flexbox>
+ ) : (
+ <ContentBlock index={index} {...item} />
+ );
+ },
+ isEqual,
+);
+export default GroupItem;
diff --git a/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx b/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx
index 3102e5f1ff9..b196427bd7e 100644
--- a/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx
@@ -90,7 +90,6 @@ const Inspectors = memo<InspectorProps>(
setShowRender,
showPluginRender,
setShowPluginRender,
- hidePluginUI = false,
type,
}) => {
const { t } = useTranslation('plugin');
@@ -127,7 +126,7 @@ const Inspectors = memo<InspectorProps>(
</Flexbox>
<Flexbox align={'center'} gap={8} horizontal>
<Flexbox className={styles.actions} horizontal>
- {showRender && !hidePluginUI && (
+ {showRender && (
<ActionIcon
icon={showPluginRender ? LogsIcon : LayoutPanelTop}
onClick={() => {
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/CustomRender.tsx b/src/features/Conversation/Messages/Group/Tool/Render/CustomRender.tsx
index 9b6ce7b9a6e..2cbdb14de4d 100644
--- a/src/features/Conversation/Messages/Group/Tool/Render/CustomRender.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Render/CustomRender.tsx
@@ -30,7 +30,7 @@ const CustomRender = memo<CustomRenderProps>(
// Determine if plugin UI should be shown based on plugin type
useEffect(() => {
if (!plugin?.type) return;
- setShowPluginRender(!['default', 'mcp'].includes(plugin.type));
+ setShowPluginRender(plugin.type !== 'default');
}, [plugin?.type, setShowPluginRender]);
// Parse and display result content
diff --git a/src/features/Conversation/Messages/Group/Tool/index.tsx b/src/features/Conversation/Messages/Group/Tool/index.tsx
index f30b96188d8..ce2b7ed3d9e 100644
--- a/src/features/Conversation/Messages/Group/Tool/index.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/index.tsx
@@ -39,8 +39,6 @@ const Tool = memo<GroupToolProps>(
<Inspectors
apiName={apiName}
arguments={requestArgs}
- // mcp don't have ui render
- hidePluginUI={type === 'mcp'}
id={id}
identifier={identifier}
index={index}
diff --git a/src/features/Conversation/Messages/Group/index.tsx b/src/features/Conversation/Messages/Group/index.tsx
index 3cc54b03d3e..9ca0b7e644a 100644
--- a/src/features/Conversation/Messages/Group/index.tsx
+++ b/src/features/Conversation/Messages/Group/index.tsx
@@ -15,7 +15,10 @@ import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
import { useAgentStore } from '@/store/agent';
import { agentChatConfigSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { chatSelectors, messageStateSelectors } from '@/store/chat/slices/message/selectors';
+import {
+ displayMessageSelectors,
+ messageStateSelectors,
+} from '@/store/chat/slices/message/selectors';
import { useGlobalStore } from '@/store/global';
import { useSessionStore } from '@/store/session';
import { sessionSelectors } from '@/store/session/selectors';
@@ -64,7 +67,9 @@ const GroupMessage = memo<GroupMessageProps>((props) => {
const [isInbox] = useSessionStore((s) => [sessionSelectors.isInboxSession(s)]);
const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);
const openChatSettings = useOpenChatSettings();
- const lastAssistantMsg = useChatStore(chatSelectors.getGroupLatestMessageWithoutTools(id));
+ const lastAssistantMsg = useChatStore(
+ displayMessageSelectors.getGroupLatestMessageWithoutTools(id),
+ );
const contentId = lastAssistantMsg?.id;
diff --git a/src/features/Conversation/hooks/useChatListActionsBar.tsx b/src/features/Conversation/hooks/useChatListActionsBar.tsx
index ca1bc04639d..34de8250470 100644
--- a/src/features/Conversation/hooks/useChatListActionsBar.tsx
+++ b/src/features/Conversation/hooks/useChatListActionsBar.tsx
@@ -1,6 +1,7 @@
import type { ActionIconGroupItemType } from '@lobehub/ui';
import { css, cx } from 'antd-style';
import {
+ ArrowDownFromLine,
Copy,
DownloadIcon,
Edit,
@@ -26,6 +27,7 @@ const translateStyle = css`
interface ChatListActionsBar {
branching: ActionIconGroupItemType;
+ continueGeneration: ActionIconGroupItemType;
copy: ActionIconGroupItemType;
del: ActionIconGroupItemType;
delAndRegenerate: ActionIconGroupItemType;
@@ -40,8 +42,13 @@ interface ChatListActionsBar {
export const useChatListActionsBar = ({
hasThread,
+ isContinuing,
isRegenerating,
-}: { hasThread?: boolean; isRegenerating?: boolean } = {}): ChatListActionsBar => {
+}: {
+ hasThread?: boolean;
+ isContinuing?: boolean;
+ isRegenerating?: boolean;
+} = {}): ChatListActionsBar => {
const { t } = useTranslation(['common', 'chat']);
return useMemo<ChatListActionsBar>(
@@ -49,7 +56,14 @@ export const useChatListActionsBar = ({
branching: {
icon: Split,
key: 'branching',
- label: t('branching', { defaultValue: 'Create Sub Topic' }),
+ label: t('branching'),
+ },
+ continueGeneration: {
+ disabled: isContinuing,
+ icon: ArrowDownFromLine,
+ key: 'continueGeneration',
+ label: t('messageAction.continueGeneration', { ns: 'chat' }),
+ spin: isContinuing,
},
copy: {
icon: Copy,
@@ -68,7 +82,6 @@ export const useChatListActionsBar = ({
icon: ListRestart,
key: 'delAndRegenerate',
label: t('messageAction.delAndRegenerate', {
- defaultValue: 'Delete and regenerate',
ns: 'chat',
}),
},
@@ -78,7 +91,7 @@ export const useChatListActionsBar = ({
edit: {
icon: Edit,
key: 'edit',
- label: t('edit', { defaultValue: 'Edit' }),
+ label: t('edit'),
},
export: {
icon: DownloadIcon,
@@ -89,12 +102,13 @@ export const useChatListActionsBar = ({
disabled: isRegenerating,
icon: RotateCcw,
key: 'regenerate',
- label: t('regenerate', { defaultValue: 'Regenerate' }),
+ label: t('regenerate'),
+ spin: isRegenerating,
},
share: {
icon: Share2,
key: 'share',
- label: t('share', { defaultValue: 'Share' }),
+ label: t('share'),
},
translate: {
children: localeOptions.map((i) => ({
@@ -112,6 +126,6 @@ export const useChatListActionsBar = ({
label: t('tts.action', { ns: 'chat' }),
},
}),
- [hasThread, isRegenerating],
+ [hasThread, isContinuing, isRegenerating],
);
};
diff --git a/src/features/PluginsUI/Render/BuiltinType/index.tsx b/src/features/PluginsUI/Render/BuiltinType/index.tsx
index 8864f211aba..63cc64ea9c9 100644
--- a/src/features/PluginsUI/Render/BuiltinType/index.tsx
+++ b/src/features/PluginsUI/Render/BuiltinType/index.tsx
@@ -1,7 +1,7 @@
+import { safeParseJSON } from '@lobechat/utils';
import { memo } from 'react';
import { BuiltinToolsRenders } from '@/tools/renders';
-import { safeParseJSON } from '@/utils/safeParseJSON';
import { useParseContent } from '../useParseContent';
diff --git a/src/features/PluginsUI/Render/MCPType/index.tsx b/src/features/PluginsUI/Render/MCPType/index.tsx
new file mode 100644
index 00000000000..56cb4e0b089
--- /dev/null
+++ b/src/features/PluginsUI/Render/MCPType/index.tsx
@@ -0,0 +1,52 @@
+import { Markdown } from '@lobehub/ui';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import Arguments from '@/features/Conversation/Messages/Group/Tool/Render/Arguments';
+import { ToolCallResult } from '@/libs/mcp';
+
+export interface MCPTypeProps {
+ apiName?: string;
+ arguments?: string;
+ content: string;
+ id: string;
+ identifier?: string;
+ loading?: boolean;
+ pluginError?: any;
+ pluginState?: ToolCallResult;
+}
+
+const MCPType = memo<MCPTypeProps>(({ pluginState, arguments: args }) => {
+ if (!pluginState) return;
+
+ const { content } = pluginState;
+
+ return (
+ <Flexbox gap={8} style={{ maxHeight: 400, overflow: 'scroll', padding: 8, width: '100%' }}>
+ <div>
+ <Arguments arguments={args} />
+ </div>
+ <Flexbox>
+ <Flexbox>
+ {content.map((item) => {
+ switch (item.type) {
+ case 'text': {
+ return (
+ <Markdown key={item.text} variant={'chat'}>
+ {item.text}
+ </Markdown>
+ );
+ }
+
+ default: {
+ return null;
+ }
+ }
+ })}
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default MCPType;
diff --git a/src/features/PluginsUI/Render/StandaloneType/Iframe.tsx b/src/features/PluginsUI/Render/StandaloneType/Iframe.tsx
index 5fd5900b502..047ee5029d5 100644
--- a/src/features/PluginsUI/Render/StandaloneType/Iframe.tsx
+++ b/src/features/PluginsUI/Render/StandaloneType/Iframe.tsx
@@ -94,9 +94,9 @@ const IFrameRender = memo<IFrameRenderProps>(({ url, id, payload, width = 600, h
});
// when plugin update state, we should update it to the message pluginState key
- const updatePluginState = useChatStore((s) => s.updatePluginState);
+ const optimisticUpdatePluginState = useChatStore((s) => s.optimisticUpdatePluginState);
useOnPluginStateUpdate((key, value) => {
- updatePluginState(id, { [key]: value });
+ optimisticUpdatePluginState(id, { [key]: value });
});
// when plugin wants to get plugin settings, send it to plugin
diff --git a/src/features/PluginsUI/Render/index.tsx b/src/features/PluginsUI/Render/index.tsx
index 3a63817b607..69476d7fd8e 100644
--- a/src/features/PluginsUI/Render/index.tsx
+++ b/src/features/PluginsUI/Render/index.tsx
@@ -4,6 +4,7 @@ import { memo } from 'react';
import BuiltinType from './BuiltinType';
import DefaultType from './DefaultType';
+import MCP from './MCPType';
import Markdown from './MarkdownType';
import Standalone from './StandaloneType';
@@ -51,6 +52,22 @@ const PluginRender = memo<PluginRenderProps>(
);
}
+ // @ts-expect-error need to update types
+ case 'mcp': {
+ return (
+ <MCP
+ apiName={payload?.apiName}
+ arguments={argumentsStr}
+ content={content}
+ id={id}
+ identifier={identifier}
+ loading={loading}
+ pluginError={pluginError}
+ pluginState={pluginState}
+ />
+ );
+ }
+
case 'markdown': {
return <Markdown content={content} loading={loading} />;
}
diff --git a/src/libs/mcp/client.ts b/src/libs/mcp/client.ts
index 5fa33f46ead..5a7c3b4b6f1 100644
--- a/src/libs/mcp/client.ts
+++ b/src/libs/mcp/client.ts
@@ -15,6 +15,7 @@ import {
McpPrompt,
McpResource,
McpTool,
+ ToolCallResult,
createMCPError,
} from './types';
@@ -374,12 +375,12 @@ export class MCPClient {
return manifest;
}
- async callTool(toolName: string, args: any) {
+ async callTool(toolName: string, args: any): Promise<ToolCallResult> {
log('Calling tool: %s with args: %O, timeout: %O', toolName, args, MCP_TOOL_TIMEOUT);
const result = await this.mcp.callTool({ arguments: args, name: toolName }, undefined, {
timeout: MCP_TOOL_TIMEOUT,
});
log('Tool call result: %O', result);
- return result;
+ return result as ToolCallResult;
}
}
diff --git a/src/libs/mcp/types.ts b/src/libs/mcp/types.ts
index d22ddc08beb..5be807d3b2b 100644
--- a/src/libs/mcp/types.ts
+++ b/src/libs/mcp/types.ts
@@ -30,6 +30,77 @@ export interface McpPrompt {
name: string;
}
+/**
+ * MCP Tool Call Result Types
+ */
+export interface TextContent {
+ _meta?: any;
+ text: string;
+ type: 'text';
+}
+
+export interface ImageContent {
+ _meta?: any;
+ data: string;
+ // base64
+ mimeType: string;
+ type: 'image';
+}
+
+export interface AudioContent {
+ _meta?: any;
+ data: string;
+ // base64
+ mimeType: string;
+ type: 'audio';
+}
+
+export interface ResourceContent {
+ _meta?: any;
+ resource: {
+ _meta?: any;
+ blob?: string;
+ mimeType?: string;
+ text?: string;
+ uri: string;
+ };
+ type: 'resource';
+}
+
+export interface ResourceLinkContent {
+ _meta?: any;
+ description?: string;
+ icons?: Array<{
+ mimeType?: string;
+ sizes?: string[];
+ src: string;
+ }>;
+ name: string;
+ title?: string;
+ type: 'resource_link';
+ uri: string;
+}
+
+export type ToolCallContent =
+ | TextContent
+ | ImageContent
+ | AudioContent
+ | ResourceContent
+ | ResourceLinkContent;
+
+export interface ToolCallResult {
+ content: ToolCallContent[];
+ isError?: boolean;
+ structuredContent?: any;
+}
+
+export interface MCPToolCallResult {
+ content: string;
+ error?: any;
+ state: ToolCallResult;
+ success: boolean;
+}
+
/**
* MCP 认证配置接口
* 支持第一阶段的手动配置和未来的 OAuth 2.1 自动化流程
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 543ca14d0e4..f2212c63a52 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -188,6 +188,7 @@ export default {
},
messageAction: {
+ continueGeneration: '继续生成',
delAndRegenerate: '删除并重新生成',
deleteDisabledByThreads: '存在子话题,不能删除',
regenerate: '重新生成',
diff --git a/src/server/routers/desktop/mcp.ts b/src/server/routers/desktop/mcp.ts
index c229a86410c..fb33cf15c85 100644
--- a/src/server/routers/desktop/mcp.ts
+++ b/src/server/routers/desktop/mcp.ts
@@ -87,13 +87,11 @@ export const mcpRouter = router({
)
.mutation(async ({ input }) => {
// Pass the validated params, toolName, and args to the service
- const data = await mcpService.callTool(
+ return await mcpService.callTool(
{ ...input.params, env: input.env },
input.toolName,
input.args,
);
-
- return JSON.stringify(data);
}),
validMcpServerInstallable: mcpProcedure
diff --git a/src/server/routers/tools/mcp.ts b/src/server/routers/tools/mcp.ts
index 05f10d01492..8525e56ee4e 100644
--- a/src/server/routers/tools/mcp.ts
+++ b/src/server/routers/tools/mcp.ts
@@ -100,8 +100,6 @@ export const mcpRouter = router({
checkStdioEnvironment(input.params);
// Pass the validated params, toolName, and args to the service
- const data = await mcpService.callTool(input.params, input.toolName, input.args);
-
- return JSON.stringify(data);
+ return await mcpService.callTool(input.params, input.toolName, input.args);
}),
});
diff --git a/src/server/services/mcp/index.test.ts b/src/server/services/mcp/index.test.ts
index 2a1629d59ca..8d579847aef 100644
--- a/src/server/services/mcp/index.test.ts
+++ b/src/server/services/mcp/index.test.ts
@@ -33,7 +33,7 @@ describe('MCPService', () => {
args: ['--test'],
};
- it('should return original data when content array is empty', async () => {
+ it('should return MCPToolCallResult when content array is empty', async () => {
mockClient.callTool.mockResolvedValue({
content: [],
isError: false,
@@ -41,10 +41,12 @@ describe('MCPService', () => {
const result = await mcpService.callTool(mockParams, 'testTool', '{}');
- expect(result).toEqual([]);
+ expect(result.content).toBe('');
+ expect(result.success).toBe(true);
+ expect(result.state).toEqual({ content: [], isError: false });
});
- it('should return original data when content is null or undefined', async () => {
+ it('should handle null content', async () => {
mockClient.callTool.mockResolvedValue({
content: null,
isError: false,
@@ -52,10 +54,11 @@ describe('MCPService', () => {
const result = await mcpService.callTool(mockParams, 'testTool', '{}');
- expect(result).toBeNull();
+ expect(result.content).toBe('');
+ expect(result.success).toBe(true);
});
- it('should return parsed JSON when single element contains valid JSON', async () => {
+ it('should return JSON string when single element contains valid JSON', async () => {
const jsonData = { message: 'Hello World', status: 'success' };
mockClient.callTool.mockResolvedValue({
content: [{ type: 'text', text: JSON.stringify(jsonData) }],
@@ -64,7 +67,8 @@ describe('MCPService', () => {
const result = await mcpService.callTool(mockParams, 'testTool', '{}');
- expect(result).toEqual(jsonData);
+ expect(result.content).toBe(JSON.stringify(jsonData));
+ expect(result.success).toBe(true);
});
it('should return plain text when single element contains non-JSON text', async () => {
@@ -76,10 +80,12 @@ describe('MCPService', () => {
const result = await mcpService.callTool(mockParams, 'testTool', '{}');
- expect(result).toBe(textData);
+ expect(result.content).toBe(textData);
+ expect(result.success).toBe(true);
+ expect(result.state.content).toEqual([{ type: 'text', text: textData }]);
});
- it('should return original data when single element has no text', async () => {
+ it('should return empty content when single element has no text', async () => {
const contentData = [{ type: 'text', text: '' }];
mockClient.callTool.mockResolvedValue({
content: contentData,
@@ -88,10 +94,12 @@ describe('MCPService', () => {
const result = await mcpService.callTool(mockParams, 'testTool', '{}');
- expect(result).toEqual(contentData);
+ expect(result.content).toBe('');
+ expect(result.success).toBe(true);
+ expect(result.state.content).toEqual(contentData);
});
- it('should return complete array when content has multiple elements', async () => {
+ it('should join multiple text elements with double newlines', async () => {
const multipleContent = [
{ type: 'text', text: 'First message' },
{ type: 'text', text: 'Second message' },
@@ -105,11 +113,12 @@ describe('MCPService', () => {
const result = await mcpService.callTool(mockParams, 'testTool', '{}');
- // 应该直接返回完整的数组,不进行任何处理
- expect(result).toEqual(multipleContent);
+ expect(result.content).toBe('First message\n\nSecond message\n\n{"json": "data"}');
+ expect(result.success).toBe(true);
+ expect(result.state.content).toEqual(multipleContent);
});
- it('should return complete array when content has two elements', async () => {
+ it('should join two text elements with double newline', async () => {
const twoContent = [
{ type: 'text', text: 'First message' },
{ type: 'text', text: 'Second message' },
@@ -122,7 +131,9 @@ describe('MCPService', () => {
const result = await mcpService.callTool(mockParams, 'testTool', '{}');
- expect(result).toEqual(twoContent);
+ expect(result.content).toBe('First message\n\nSecond message');
+ expect(result.success).toBe(true);
+ expect(result.state.content).toEqual(twoContent);
});
it('should return error result when isError is true', async () => {
@@ -135,7 +146,9 @@ describe('MCPService', () => {
const result = await mcpService.callTool(mockParams, 'testTool', '{}');
- expect(result).toEqual(errorResult);
+ expect(result.content).toBe('Error occurred');
+ expect(result.success).toBe(true);
+ expect(result.state).toEqual(errorResult);
});
it('should throw TRPCError when client throws error', async () => {
diff --git a/src/server/services/mcp/index.ts b/src/server/services/mcp/index.ts
index bc6e9143da2..1f3e7706282 100644
--- a/src/server/services/mcp/index.ts
+++ b/src/server/services/mcp/index.ts
@@ -175,29 +175,40 @@ export class MCPService {
loggableParams,
result,
);
- const { content, isError } = result;
- if (isError) return result;
-
- const data = content as { text: string; type: 'text' }[];
-
- if (!data || data.length === 0) return data;
-
- if (data.length > 1) return data;
-
- const text = data[0]?.text;
- if (!text) return data;
-
- // try to get json object, which will be stringify in the client
- const json = safeParseJSON(text);
- if (json) return json;
-
- return text;
+ // TODO: map more type
+ const content = result.content
+ ? result.content
+ .map((item) => {
+ switch (item.type) {
+ case 'text': {
+ return item.text;
+ }
+ default: {
+ return '';
+ }
+ }
+ })
+ .filter(Boolean)
+ .join('\n\n')
+ : '';
+
+ if (result.isError) return { content, state: result, success: true };
+
+ return { content, state: result, success: true };
} catch (error) {
if (error instanceof McpError) {
const mcpError = error as McpError;
- return mcpError.message;
+ return {
+ content: mcpError.message,
+ error: error,
+ state: {
+ content: [{ text: mcpError.message, type: 'text' }],
+ isError: true,
+ },
+ success: false,
+ };
}
console.error(
diff --git a/src/services/chat/contextEngineering.test.ts b/src/services/chat/contextEngineering.test.ts
index 297345e723a..64f5022b74c 100644
--- a/src/services/chat/contextEngineering.test.ts
+++ b/src/services/chat/contextEngineering.test.ts
@@ -243,6 +243,10 @@ describe('contextEngineering', () => {
type: 'text',
},
],
+ reasoning: {
+ content: 'I need to calculate the answer to life, universe, and everything.',
+ signature: 'thinking_process',
+ },
role: 'assistant',
},
]);
diff --git a/src/services/mcp.test.ts b/src/services/mcp.test.ts
index 6a028fee80d..993ff610f0a 100644
--- a/src/services/mcp.test.ts
+++ b/src/services/mcp.test.ts
@@ -305,7 +305,13 @@ describe('MCPService', () => {
mockPluginSelectors.getInstalledPluginById.mockReturnValue(() => mockPlugin);
mockPluginSelectors.getCustomPluginById.mockReturnValue(() => null);
- const mockResult = 'response data';
+ const mockResult = {
+ content: 'response data',
+ state: {
+ content: [{ text: 'response data', type: 'text' }],
+ },
+ success: true,
+ };
vi.mocked(toolsClient.mcp.callTool.mutate).mockResolvedValue(mockResult);
const payload: ChatToolPayload = {
diff --git a/src/services/mcp.ts b/src/services/mcp.ts
index ea25bdeb10b..db81ba280b8 100644
--- a/src/services/mcp.ts
+++ b/src/services/mcp.ts
@@ -4,6 +4,7 @@ import { isLocalOrPrivateUrl, safeParseJSON } from '@lobechat/utils';
import { PluginManifest } from '@lobehub/market-sdk';
import { CallReportRequest } from '@lobehub/market-types';
+import { MCPToolCallResult } from '@/libs/mcp';
import { desktopClient, toolsClient } from '@/libs/trpc/client';
import { discoverService } from './discover';
@@ -44,16 +45,16 @@ class MCPService {
const connection = plugin.customParams?.mcp;
const settingsEntries = plugin.settings
? Object.entries(plugin.settings as Record<string, any>).filter(
- ([, value]) => value !== undefined && value !== null,
- )
+ ([, value]) => value !== undefined && value !== null,
+ )
: [];
const pluginSettings =
settingsEntries.length > 0
? settingsEntries.reduce<Record<string, unknown>>((acc, [key, value]) => {
- acc[key] = value;
+ acc[key] = value;
- return acc;
- }, {})
+ return acc;
+ }, {})
: undefined;
const params = {
@@ -77,7 +78,7 @@ class MCPService {
const data = {
args,
- env: connection?.type === 'stdio' ? params.env : pluginSettings ?? connection?.env,
+ env: connection?.type === 'stdio' ? params.env : (pluginSettings ?? connection?.env),
params,
toolName: apiName,
};
@@ -89,7 +90,7 @@ class MCPService {
let success = false;
let errorCode: string | undefined;
let errorMessage: string | undefined;
- let result: any;
+ let result: MCPToolCallResult | undefined;
try {
// For desktop and stdio, use the desktopClient
@@ -119,7 +120,7 @@ class MCPService {
const requestSizeBytes = calculateObjectSizeBytes(inputParams);
// 计算响应大小
- const responseSizeBytes = success ? calculateObjectSizeBytes(result) : 0;
+ const responseSizeBytes = success && result ? calculateObjectSizeBytes(result.state) : 0;
const isCustomPlugin = !!customPlugin;
// 构造上报数据
@@ -127,10 +128,10 @@ class MCPService {
callDurationMs,
customPluginInfo: isCustomPlugin
? {
- avatar: plugin.manifest?.meta.avatar,
- description: plugin.manifest?.meta.description,
- name: plugin.manifest?.meta.title,
- }
+ avatar: plugin.manifest?.meta.avatar,
+ description: plugin.manifest?.meta.description,
+ name: plugin.manifest?.meta.title,
+ }
: undefined,
errorCode,
errorMessage,
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 8dc224d07cf..3a6e7c07979 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -39,10 +39,9 @@ export const createAgentExecutors = (context: {
traceId?: string;
};
parentId: string;
- parentMessageType: 'user' | 'assistant';
+ skipCreateFirstMessage?: boolean;
}) => {
- // 当通过 sendMessageInServer 的时候,已经有一条消息了,那么就不需要触发创建
- let shouldSkipCreateMessage = context.parentMessageType === 'assistant';
+ let shouldSkipCreateMessage = context.skipCreateFirstMessage;
const executors: Partial<Record<AgentInstruction['type'], InstructionExecutor>> = {
/**
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 8171683a6fd..bc872a0e7e1 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -44,6 +44,10 @@ export interface ConversationLifecycleAction {
id: string,
params?: { skipTrace?: boolean; traceId?: string },
) => Promise<void>;
+ /**
+ * Continue generating from current assistant message
+ */
+ continueGenerationMessage: (lastBlockId: string, messageId: string) => Promise<void>;
/**
* Deletes an existing message and generates a new one in its place
*/
@@ -75,7 +79,12 @@ export const conversationLifecycle: StateCreator<
}
const messages = displayMessageSelectors.activeDisplayMessages(get());
- const parentId = displayMessageSelectors.lastDisplayMessageId(get());
+ const lastDisplayMessageId = displayMessageSelectors.lastDisplayMessageId(get());
+
+ let parentId: string | undefined;
+ if (lastDisplayMessageId) {
+ parentId = displayMessageSelectors.findLastMessageId(lastDisplayMessageId)(get());
+ }
const chatConfig = agentChatConfigSelectors.currentChatConfig(getAgentStoreState());
const autoCreateThreshold =
@@ -230,6 +239,7 @@ export const conversationLifecycle: StateCreator<
parentMessageType: 'assistant',
ragQuery: get().internal_shouldUseRAG() ? message : undefined,
threadId: activeThreadId,
+ skipCreateFirstMessage: true,
});
//
@@ -318,6 +328,35 @@ export const conversationLifecycle: StateCreator<
await get().regenerateUserMessage(userId, params);
},
+ continueGenerationMessage: async (id, messageId) => {
+ const message = dbMessageSelectors.getDbMessageById(id)(get());
+ if (!message) return;
+
+ try {
+ // Mark message as continuing
+ set(
+ { continuingIds: [...get().continuingIds, messageId] },
+ false,
+ 'continueGenerationMessage/start',
+ );
+
+ const chats = displayMessageSelectors.mainAIChatsWithHistoryConfig(get());
+
+ await get().internal_execAgentRuntime({
+ messages: chats,
+ parentMessageId: id,
+ parentMessageType: message.role as 'assistant' | 'tool' | 'user',
+ });
+ } finally {
+ // Remove message from continuing state
+ set(
+ { continuingIds: get().continuingIds.filter((msgId) => msgId !== messageId) },
+ false,
+ 'continueGenerationMessage/end',
+ );
+ }
+ },
+
delAndRegenerateMessage: async (id) => {
const traceId = dbMessageSelectors.getTraceIdByDbMessageId(id)(get());
get().regenerateAssistantMessage(id, { skipTrace: true, traceId });
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 58b41704c55..3ecf8a61644 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -77,7 +77,7 @@ export interface StreamingExecutorAction {
internal_execAgentRuntime: (params: {
messages: UIChatMessage[];
parentMessageId: string;
- parentMessageType: 'user' | 'assistant';
+ parentMessageType: 'user' | 'assistant' | 'tool';
inSearchWorkflow?: boolean;
/**
* the RAG query content, should be embedding and used in the semantic search
@@ -85,6 +85,7 @@ export interface StreamingExecutorAction {
ragQuery?: string;
threadId?: string;
inPortalThread?: boolean;
+ skipCreateFirstMessage?: boolean;
traceId?: string;
ragMetadata?: { ragQueryId: string; fileChunks: MessageSemanticSearchChunk[] };
}) => Promise<void>;
@@ -137,7 +138,7 @@ export const streamingExecutor: StateCreator<
let output = '';
let thinking = '';
let thinkingStartAt: number;
- let duration: number;
+ let duration: number | undefined;
// to upload image
const uploadTasks: Map<string, Promise<{ id?: string; url?: string }>> = new Map();
@@ -231,7 +232,9 @@ export const streamingExecutor: StateCreator<
// update the content after fetch result
await optimisticUpdateMessageContent(messageId, content, {
toolCalls: parsedToolCalls,
- reasoning: !!reasoning ? { ...reasoning, duration } : undefined,
+ reasoning: !!reasoning
+ ? { ...reasoning, duration: duration && !isNaN(duration) ? duration : undefined }
+ : undefined,
search: !!grounding?.citations ? grounding : undefined,
imageList: finalImages.length > 0 ? finalImages : undefined,
metadata: speed ? { ...usage, ...speed } : usage,
@@ -340,6 +343,10 @@ export const streamingExecutor: StateCreator<
isFunctionCall = true;
const isInChatReasoning = get().reasoningLoadingIds.includes(messageId);
if (isInChatReasoning) {
+ if (!duration) {
+ duration = Date.now() - thinkingStartAt;
+ }
+
internal_toggleChatReasoning(
false,
messageId,
@@ -456,8 +463,8 @@ export const streamingExecutor: StateCreator<
get,
messageKey,
parentId: params.parentMessageId,
- parentMessageType,
params,
+ skipCreateFirstMessage: params.skipCreateFirstMessage,
}),
});
@@ -465,7 +472,8 @@ export const streamingExecutor: StateCreator<
let state = AgentRuntime.createInitialState({
sessionId: activeId,
messages,
- maxSteps: 20, // Prevent infinite loops
+ // Prevent infinite loops
+ maxSteps: 400,
metadata: {
sessionId: activeId,
topicId: activeTopicId,
diff --git a/src/store/chat/slices/builtinTool/actions/__tests__/localSystem.test.ts b/src/store/chat/slices/builtinTool/actions/__tests__/localSystem.test.ts
index b45b582f3a7..951f56734f9 100644
--- a/src/store/chat/slices/builtinTool/actions/__tests__/localSystem.test.ts
+++ b/src/store/chat/slices/builtinTool/actions/__tests__/localSystem.test.ts
@@ -24,10 +24,10 @@ const mockStore = {
internal_triggerLocalFileToolCalling: vi.fn(),
optimisticUpdateMessageContent: vi.fn(),
optimisticUpdateMessagePluginError: vi.fn(),
+ optimisticUpdatePluginArguments: vi.fn(),
+ optimisticUpdatePluginState: vi.fn(),
set: mockSet,
toggleLocalFileLoading: vi.fn(),
- updatePluginArguments: vi.fn(),
- updatePluginState: vi.fn(),
} as unknown as ChatStore;
const createStore = () => {
@@ -57,7 +57,7 @@ describe('localFileSlice', () => {
await store.internal_triggerLocalFileToolCalling('test-id', mockService);
expect(mockStore.toggleLocalFileLoading).toBeCalledWith('test-id', true);
- expect(mockStore.updatePluginState).toBeCalledWith('test-id', mockState);
+ expect(mockStore.optimisticUpdatePluginState).toBeCalledWith('test-id', mockState);
expect(mockStore.optimisticUpdateMessageContent).toBeCalledWith(
'test-id',
JSON.stringify(mockContent),
diff --git a/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts b/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts
index afd3970b7fa..3864ac64931 100644
--- a/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts
+++ b/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts
@@ -32,10 +32,10 @@ describe('search actions', () => {
searchLoading: {},
optimisticUpdateMessageContent: vi.fn(),
optimisticUpdateMessagePluginError: vi.fn(),
- updatePluginArguments: vi.fn(),
- updatePluginState: vi.fn(),
+ optimisticUpdatePluginArguments: vi.fn(),
+ optimisticUpdatePluginState: vi.fn(),
optimisticCreateMessage: vi.fn(),
- internal_addToolToAssistantMessage: vi.fn(),
+ optimisticAddToolToAssistantMessage: vi.fn(),
openToolUI: vi.fn(),
});
});
@@ -238,7 +238,7 @@ describe('search actions', () => {
await triggerSearchAgain(messageId, query, { aiSummary: true });
});
- expect(result.current.updatePluginArguments).toHaveBeenCalledWith(messageId, query);
+ expect(result.current.optimisticUpdatePluginArguments).toHaveBeenCalledWith(messageId, query);
expect(spy).toHaveBeenCalledWith(messageId, query, true);
});
});
@@ -285,7 +285,7 @@ describe('search actions', () => {
}),
);
- expect(result.current.internal_addToolToAssistantMessage).toHaveBeenCalledWith(
+ expect(result.current.optimisticAddToolToAssistantMessage).toHaveBeenCalledWith(
parentId,
expect.objectContaining({
identifier: 'search',
@@ -305,7 +305,7 @@ describe('search actions', () => {
});
expect(result.current.optimisticCreateMessage).not.toHaveBeenCalled();
- expect(result.current.internal_addToolToAssistantMessage).not.toHaveBeenCalled();
+ expect(result.current.optimisticAddToolToAssistantMessage).not.toHaveBeenCalled();
});
});
diff --git a/src/store/chat/slices/builtinTool/actions/interpreter.ts b/src/store/chat/slices/builtinTool/actions/interpreter.ts
index 5e4bbb35e23..72211824775 100644
--- a/src/store/chat/slices/builtinTool/actions/interpreter.ts
+++ b/src/store/chat/slices/builtinTool/actions/interpreter.ts
@@ -41,7 +41,7 @@ export const codeInterpreterSlice: StateCreator<
python: async (id: string, params: CodeInterpreterParams) => {
const {
toggleInterpreterExecuting,
- updatePluginState,
+ optimisticUpdatePluginState,
optimisticUpdateMessageContent,
uploadInterpreterFiles,
} = get();
@@ -83,7 +83,7 @@ export const codeInterpreterSlice: StateCreator<
await optimisticUpdateMessageContent(id, JSON.stringify(result));
}
} catch (error) {
- updatePluginState(id, { error });
+ optimisticUpdatePluginState(id, { error });
// 如果调用过程中出现了错误,不要触发 AI 消息
return;
} finally {
diff --git a/src/store/chat/slices/builtinTool/actions/localSystem.ts b/src/store/chat/slices/builtinTool/actions/localSystem.ts
index a14b18baa5b..2376c63feea 100644
--- a/src/store/chat/slices/builtinTool/actions/localSystem.ts
+++ b/src/store/chat/slices/builtinTool/actions/localSystem.ts
@@ -220,7 +220,7 @@ export const localSystemSlice: StateCreator<
reSearchLocalFiles: async (id, params) => {
get().toggleLocalFileLoading(id, true);
- await get().updatePluginArguments(id, params);
+ await get().optimisticUpdatePluginArguments(id, params);
return get().searchLocalFiles(id, params);
},
@@ -307,7 +307,7 @@ export const localSystemSlice: StateCreator<
try {
const { state, content } = await callingService();
if (state) {
- await get().updatePluginState(id, state as any);
+ await get().optimisticUpdatePluginState(id, state as any);
}
await get().optimisticUpdateMessageContent(id, JSON.stringify(content));
} catch (error) {
diff --git a/src/store/chat/slices/builtinTool/actions/search.ts b/src/store/chat/slices/builtinTool/actions/search.ts
index 7f911cd16cc..403c9df4049 100644
--- a/src/store/chat/slices/builtinTool/actions/search.ts
+++ b/src/store/chat/slices/builtinTool/actions/search.ts
@@ -51,9 +51,9 @@ export const searchSlice: StateCreator<
await optimisticUpdateMessageContent(id, content);
if (success) {
- await get().updatePluginState(id, state);
+ await get().optimisticUpdatePluginState(id, state);
} else {
- await get().internal_updatePluginError(id, error);
+ await get().optimisticUpdatePluginError(id, error);
}
get().toggleSearchLoading(id, false);
@@ -81,7 +81,7 @@ export const searchSlice: StateCreator<
const message = chatSelectors.getMessageById(id)(get());
if (!message || !message.plugin) return;
- const { internal_addToolToAssistantMessage, optimisticCreateMessage, openToolUI } = get();
+ const { optimisticAddToolToAssistantMessage, optimisticCreateMessage, openToolUI } = get();
// 1. 创建一个新的 tool call message
const newToolCallId = `tool_call_${nanoid()}`;
@@ -100,7 +100,7 @@ export const searchSlice: StateCreator<
const addToolItem = async () => {
if (!message.parentId || !message.plugin) return;
- await internal_addToolToAssistantMessage(message.parentId, {
+ await optimisticAddToolToAssistantMessage(message.parentId, {
id: newToolCallId,
...message.plugin,
});
@@ -124,7 +124,7 @@ export const searchSlice: StateCreator<
const { content, success, error, state } = await runtime.search(params);
if (success) {
- await get().updatePluginState(id, state);
+ await get().optimisticUpdatePluginState(id, state);
} else {
if ((error as Error).message === SEARCH_SEARXNG_NOT_CONFIG) {
await get().optimisticUpdateMessagePluginError(id, {
@@ -164,7 +164,7 @@ export const searchSlice: StateCreator<
triggerSearchAgain: async (id, data, options) => {
get().toggleSearchLoading(id, true);
- await get().updatePluginArguments(id, data);
+ await get().optimisticUpdatePluginArguments(id, data);
await get().search(id, data, options?.aiSummary);
},
diff --git a/src/store/chat/slices/message/actions/publicApi.ts b/src/store/chat/slices/message/actions/publicApi.ts
index 2ccb739a9e4..63e70dcaebc 100644
--- a/src/store/chat/slices/message/actions/publicApi.ts
+++ b/src/store/chat/slices/message/actions/publicApi.ts
@@ -31,6 +31,7 @@ export interface MessagePublicApiAction {
*/
clearMessage: () => Promise<void>;
deleteMessage: (id: string) => Promise<void>;
+ deleteDBMessage: (id: string) => Promise<void>;
deleteToolMessage: (id: string) => Promise<void>;
clearAllMessages: () => Promise<void>;
@@ -135,13 +136,30 @@ export const messagePublicApi: StateCreator<
}
},
+ deleteDBMessage: async (id) => {
+ const message = dbMessageSelectors.getDbMessageById(id)(get());
+ if (!message) return;
+
+ let ids = [message.id];
+
+ get().internal_dispatchMessage({ type: 'deleteMessages', ids });
+ const result = await messageService.removeMessages(ids, {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ });
+
+ if (result?.success && result.messages) {
+ get().replaceMessages(result.messages);
+ }
+ },
+
deleteToolMessage: async (id) => {
const message = dbMessageSelectors.getDbMessageById(id)(get());
if (!message || message.role !== 'tool') return;
const removeToolInAssistantMessage = async () => {
if (!message.parentId) return;
- await get().internal_removeToolToAssistantMessage(message.parentId, message.tool_call_id);
+ await get().optimisticRemoveToolFromAssistantMessage(message.parentId, message.tool_call_id);
};
await Promise.all([
diff --git a/src/store/chat/slices/message/initialState.ts b/src/store/chat/slices/message/initialState.ts
index 81a15cdb10a..7c6abb2599b 100644
--- a/src/store/chat/slices/message/initialState.ts
+++ b/src/store/chat/slices/message/initialState.ts
@@ -15,6 +15,10 @@ export interface ChatMessageState {
* Derived from session.type, used for caching to avoid repeated lookups
*/
activeSessionType?: 'agent' | 'group';
+ /**
+ * is the message is continuing generation (used for disable continue button)
+ */
+ continuingIds: string[];
/**
* Raw messages from database (flat structure)
*/
@@ -73,6 +77,7 @@ export interface ChatMessageState {
export const initialMessageState: ChatMessageState = {
activeId: 'inbox',
activeSessionType: undefined,
+ continuingIds: [],
dbMessagesMap: {},
groupAgentMaps: {},
groupMaps: {},
diff --git a/src/store/chat/slices/message/selectors/chat.test.ts b/src/store/chat/slices/message/selectors/chat.test.ts
index be34e757638..29b22c370f7 100644
--- a/src/store/chat/slices/message/selectors/chat.test.ts
+++ b/src/store/chat/slices/message/selectors/chat.test.ts
@@ -1,11 +1,6 @@
import { UIChatMessage } from '@lobechat/types';
-import { LobeAgentConfig } from '@lobechat/types';
-import { act } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
-import { DEFAULT_INBOX_AVATAR } from '@/const/meta';
-import { INBOX_SESSION_ID } from '@/const/session';
-import { useAgentStore } from '@/store/agent';
import { ChatStore } from '@/store/chat';
import { initialState } from '@/store/chat/initialState';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
@@ -15,7 +10,7 @@ import { merge } from '@/utils/merge';
import { chatSelectors } from './chat';
vi.mock('i18next', () => ({
- t: vi.fn((key) => key), // Simplified mock return value
+ t: vi.fn((key) => key),
}));
const initialStore = initialState as ChatStore;
@@ -31,108 +26,15 @@ const mockMessages = [
content: 'Goodbye World',
role: 'user',
},
- {
- id: 'msg3',
- content: 'Function Message',
- role: 'tool',
- tools: [
- {
- arguments: ['arg1', 'arg2'],
- identifier: 'func1',
- apiName: 'ttt',
- type: 'pluginType',
- id: 'abc',
- },
- ],
- },
-] as UIChatMessage[];
-
-const mockReasoningMessages = [
- {
- id: 'msg1',
- content: 'Hello World',
- role: 'user',
- },
- {
- id: 'msg2',
- content: 'Goodbye World',
- role: 'user',
- },
- {
- id: 'msg3',
- content: 'Content Message',
- role: 'assistant',
- reasoning: {
- content: 'Reasoning Content',
- },
- },
-] as UIChatMessage[];
-
-const mockedChats = [
- {
- id: 'msg1',
- content: 'Hello World',
- role: 'user',
- meta: {
- avatar: '😀',
- },
- },
- {
- id: 'msg2',
- content: 'Goodbye World',
- role: 'user',
- meta: {
- avatar: '😀',
- },
- },
- {
- id: 'msg3',
- content: 'Function Message',
- role: 'tool',
- meta: {
- avatar: DEFAULT_INBOX_AVATAR,
- backgroundColor: 'rgba(0,0,0,0)',
- description: 'inbox.desc',
- title: 'inbox.title',
- },
- tools: [
- {
- arguments: ['arg1', 'arg2'],
- identifier: 'func1',
- apiName: 'ttt',
- type: 'pluginType',
- id: 'abc',
- },
- ],
- },
] as UIChatMessage[];
-const mockChatStore = {
- messagesMap: {
- [messageMapKey('abc')]: mockMessages,
- },
- activeId: 'abc',
-} as ChatStore;
-
beforeAll(() => {
createServerConfigStore();
});
-afterEach(() => {
- const store = createServerConfigStore();
- store.setState((state) => ({
- featureFlags: { ...state.featureFlags, isAgentEditable: true },
- }));
-});
-
-describe('chatSelectors', () => {
+describe('chatSelectors - Backward Compatibility Layer', () => {
describe('getMessageById', () => {
- it('should return undefined if the message with the given id does not exist', () => {
- const message = chatSelectors.getMessageById('non-existent-id')(initialStore);
- expect(message).toBeUndefined();
- });
-
- it('should return the message object with the matching id', () => {
+ it('should work as backward compatibility alias for getDisplayMessageById', () => {
const state = merge(initialStore, {
messagesMap: {
[messageMapKey('abc')]: mockMessages,
@@ -140,218 +42,13 @@ describe('chatSelectors', () => {
activeId: 'abc',
});
const message = chatSelectors.getMessageById('msg1')(state);
- expect(message).toEqual(mockedChats[0]);
- });
-
- it('should return the message with the matching id', () => {
- const message = chatSelectors.getMessageById('msg1')(mockChatStore);
- expect(message).toEqual(mockedChats[0]);
- });
-
- it('should return undefined if no message matches the id', () => {
- const message = chatSelectors.getMessageById('nonexistent')(mockChatStore);
- expect(message).toBeUndefined();
- });
- });
-
- describe('currentChatsWithHistoryConfig', () => {
- it('should slice the messages according to the current agent config', () => {
- const state = merge(initialStore, {
- messagesMap: {
- [messageMapKey('abc')]: mockMessages,
- },
- activeId: 'abc',
- });
-
- const chats = chatSelectors.mainAIChatsWithHistoryConfig(state);
- expect(chats).toHaveLength(3);
- expect(chats).toEqual(mockedChats);
- });
- it('should slice the messages according to config, assuming historyCount is mocked to 2', async () => {
- const state = merge(initialStore, {
- messagesMap: {
- [messageMapKey('abc')]: mockMessages,
- },
- activeId: 'abc',
- });
- act(() => {
- useAgentStore.setState({
- activeId: 'inbox',
- agentMap: {
- inbox: {
- chatConfig: {
- historyCount: 2,
- enableHistoryCount: true,
- },
- model: 'abc',
- } as LobeAgentConfig,
- },
- });
- });
-
- const chats = chatSelectors.mainAIChatsWithHistoryConfig(state);
-
- expect(chats).toHaveLength(2);
- expect(chats).toEqual([
- {
- id: 'msg2',
- content: 'Goodbye World',
- role: 'user',
- meta: {
- avatar: '😀',
- },
- },
- {
- id: 'msg3',
- content: 'Function Message',
- role: 'tool',
- meta: {
- avatar: DEFAULT_INBOX_AVATAR,
- backgroundColor: 'rgba(0,0,0,0)',
- description: 'inbox.desc',
- title: 'inbox.title',
- },
- tools: [
- {
- apiName: 'ttt',
- arguments: ['arg1', 'arg2'],
- identifier: 'func1',
- id: 'abc',
- type: 'pluginType',
- },
- ],
- },
- ]);
- });
- });
-
- describe('chatsMessageString', () => {
- it('should concatenate the contents of all messages returned by currentChatsWithHistoryConfig', () => {
- // Prepare a state with a few messages
- const state = merge(initialStore, {
- messagesMap: {
- [messageMapKey('active-session')]: mockMessages,
- },
- activeId: 'active-session',
- });
-
- // Assume that the currentChatsWithHistoryConfig will return the last two messages
- const expectedString = mockMessages
- .slice(-2)
- .map((m) => m.content)
- .join('');
-
- // Call the selector and verify the result
- const concatenatedString = chatSelectors.mainAIChatsMessageString(state);
- expect(concatenatedString).toBe(expectedString);
-
- // Restore the mocks after the test
- vi.restoreAllMocks();
- });
- });
-
- describe('latestMessageReasoningContent', () => {
- it('should return the reasoning content of the latest message', () => {
- // Prepare a state with a few messages
- const state = merge(initialStore, {
- messagesMap: {
- [messageMapKey('active-session')]: mockReasoningMessages,
- },
- activeId: 'active-session',
- });
-
- const expectedString = mockReasoningMessages.at(-1)?.reasoning?.content;
-
- // Call the selector and verify the result
- const reasoningContent = chatSelectors.mainAILatestMessageReasoningContent(state);
- expect(reasoningContent).toBe(expectedString);
-
- // Restore the mocks after the test
- vi.restoreAllMocks();
- });
- });
-
- describe('showInboxWelcome', () => {
- it('should return false if the active session is not the inbox session', () => {
- const state = merge(initialStore, { activeId: 'someActiveId' });
- const result = chatSelectors.showInboxWelcome(state);
- expect(result).toBe(false);
- });
-
- it('should return false if there are existing messages in the inbox session', () => {
- const state = merge(initialStore, {
- activeId: INBOX_SESSION_ID,
- messagesMap: {
- [messageMapKey('inbox')]: mockMessages,
- },
- });
- const result = chatSelectors.showInboxWelcome(state);
- expect(result).toBe(false);
- });
-
- it('should return true if the active session is the inbox session and there are no existing messages', () => {
- const state = merge(initialStore, {
- activeId: INBOX_SESSION_ID,
- messages: [],
- });
- const result = chatSelectors.showInboxWelcome(state);
- expect(result).toBe(true);
- });
- });
-
- describe('currentToolMessages', () => {
- it('should return only tool messages', () => {
- const messages = [
- { id: '1', role: 'user', content: 'Hello' },
- { id: '2', role: 'assistant', content: 'Hi' },
- { id: '3', role: 'tool', content: 'Tool message 1' },
- { id: '4', role: 'user', content: 'Query' },
- { id: '5', role: 'tool', tools: [] },
- ] as UIChatMessage[];
- const state: Partial<ChatStore> = {
- activeId: 'test-id',
- dbMessagesMap: {
- [messageMapKey('test-id')]: messages,
- },
- messagesMap: {
- [messageMapKey('test-id')]: messages,
- },
- };
- const result = chatSelectors.currentToolMessages(state as ChatStore);
- expect(result).toHaveLength(2);
- expect(result.every((msg) => msg.role === 'tool')).toBe(true);
- });
-
- it('should return an empty array when no tool messages exist', () => {
- const messages = [
- { id: '1', role: 'user', content: 'Hello' },
- { id: '2', role: 'assistant', content: 'Hi' },
- ] as UIChatMessage[];
- const state: Partial<ChatStore> = {
- activeId: 'test-id',
- dbMessagesMap: {
- [messageMapKey('test-id')]: messages,
- },
- messagesMap: {
- [messageMapKey('test-id')]: messages,
- },
- };
- const result = chatSelectors.currentToolMessages(state as ChatStore);
- expect(result).toHaveLength(0);
+ expect(message?.id).toBe('msg1');
+ expect(message?.content).toBe('Hello World');
});
});
describe('currentChatKey', () => {
- it('should generate correct key with activeId only', () => {
- const state: Partial<ChatStore> = {
- activeId: 'testId',
- activeTopicId: undefined,
- };
- const result = chatSelectors.currentChatKey(state as ChatStore);
- expect(result).toBe(messageMapKey('testId', undefined));
- });
-
- it('should generate correct key with both activeId and activeTopicId', () => {
+ it('should work as backward compatibility alias for currentDisplayChatKey', () => {
const state: Partial<ChatStore> = {
activeId: 'testId',
activeTopicId: 'topicId',
@@ -359,314 +56,37 @@ describe('chatSelectors', () => {
const result = chatSelectors.currentChatKey(state as ChatStore);
expect(result).toBe(messageMapKey('testId', 'topicId'));
});
-
- it('should generate key with undefined activeId', () => {
- const state: Partial<ChatStore> = {
- activeId: undefined,
- activeTopicId: 'topicId',
- };
- const result = chatSelectors.currentChatKey(state as ChatStore);
- expect(result).toBe(messageMapKey(undefined as any, 'topicId'));
- });
-
- it('should generate key with empty string activeId', () => {
- const state: Partial<ChatStore> = {
- activeId: '',
- activeTopicId: undefined,
- };
- const result = chatSelectors.currentChatKey(state as ChatStore);
- expect(result).toBe(messageMapKey('', undefined));
- });
});
- describe('activeBaseChats with group chat messages', () => {
- it('should retrieve agent meta for group chat messages with groupId and agentId', () => {
- const groupChatMessages = [
- {
- id: 'msg1',
- content: 'Hello from agent',
- role: 'assistant',
- groupId: 'group-123',
- agentId: 'agent-456',
- },
- ] as UIChatMessage[];
-
+ describe('activeBaseChats', () => {
+ it('should work as backward compatibility alias for activeDisplayMessages', () => {
const state = merge(initialStore, {
messagesMap: {
- [messageMapKey('group-123')]: groupChatMessages,
+ [messageMapKey('abc')]: mockMessages,
},
- activeId: 'group-123',
+ activeId: 'abc',
});
-
const chats = chatSelectors.activeBaseChats(state);
- expect(chats).toHaveLength(1);
+ expect(chats).toHaveLength(2);
expect(chats[0].id).toBe('msg1');
- expect(chats[0].meta).toBeDefined();
});
});
- describe('getGroupLatestMessageWithoutTools', () => {
- it('should return the last child without tools', () => {
- const groupMessage = {
- id: 'group-1',
- role: 'assistantGroup',
- 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: 'assistantGroup',
- 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: 'assistantGroup',
- 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: 'assistantGroup',
- 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: 'assistantGroup',
- 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: 'assistantGroup',
- 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: 'assistantGroup',
- 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', () => {
+ describe('currentToolMessages', () => {
+ it('should work as backward compatibility alias for dbToolMessages', () => {
+ const messages = [
+ { id: '1', role: 'user', content: 'Hello' },
+ { id: '2', role: 'tool', content: 'Tool message' },
+ ] as UIChatMessage[];
const state: Partial<ChatStore> = {
activeId: 'test-id',
- messagesMap: {
- [messageMapKey('test-id')]: [],
+ dbMessagesMap: {
+ [messageMapKey('test-id')]: messages,
},
};
-
- const result = chatSelectors.getGroupLatestMessageWithoutTools('non-existent')(
- state as ChatStore,
- );
- expect(result).toBeUndefined();
+ const result = chatSelectors.currentToolMessages(state as ChatStore);
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe('tool');
});
});
});
diff --git a/src/store/chat/slices/message/selectors/chat.ts b/src/store/chat/slices/message/selectors/chat.ts
index 9ff757a5532..389af919ee1 100644
--- a/src/store/chat/slices/message/selectors/chat.ts
+++ b/src/store/chat/slices/message/selectors/chat.ts
@@ -76,8 +76,6 @@ export const chatSelectors = {
getBaseChatsByKey: displayMessageSelectors.getDisplayMessagesByKey,
- getGroupLatestMessageWithoutTools: displayMessageSelectors.getGroupLatestMessageWithoutTools,
-
getMessageById: displayMessageSelectors.getDisplayMessageById,
getSupervisorTodos: displayMessageSelectors.getSupervisorTodos,
diff --git a/src/store/chat/slices/message/selectors/dbMessage.test.ts b/src/store/chat/slices/message/selectors/dbMessage.test.ts
new file mode 100644
index 00000000000..bab9cb02fd2
--- /dev/null
+++ b/src/store/chat/slices/message/selectors/dbMessage.test.ts
@@ -0,0 +1,51 @@
+import { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { ChatStore } from '@/store/chat';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { dbMessageSelectors } from './dbMessage';
+
+describe('dbMessageSelectors', () => {
+ describe('dbToolMessages', () => {
+ it('should return only tool messages', () => {
+ const messages = [
+ { id: '1', role: 'user', content: 'Hello' },
+ { id: '2', role: 'assistant', content: 'Hi' },
+ { id: '3', role: 'tool', content: 'Tool message 1' },
+ { id: '4', role: 'user', content: 'Query' },
+ { id: '5', role: 'tool', tools: [] },
+ ] as UIChatMessage[];
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ dbMessagesMap: {
+ [messageMapKey('test-id')]: messages,
+ },
+ messagesMap: {
+ [messageMapKey('test-id')]: messages,
+ },
+ };
+ const result = dbMessageSelectors.dbToolMessages(state as ChatStore);
+ expect(result).toHaveLength(2);
+ expect(result.every((msg) => msg.role === 'tool')).toBe(true);
+ });
+
+ it('should return an empty array when no tool messages exist', () => {
+ const messages = [
+ { id: '1', role: 'user', content: 'Hello' },
+ { id: '2', role: 'assistant', content: 'Hi' },
+ ] as UIChatMessage[];
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ dbMessagesMap: {
+ [messageMapKey('test-id')]: messages,
+ },
+ messagesMap: {
+ [messageMapKey('test-id')]: messages,
+ },
+ };
+ const result = dbMessageSelectors.dbToolMessages(state as ChatStore);
+ expect(result).toHaveLength(0);
+ });
+ });
+});
diff --git a/src/store/chat/slices/message/selectors/displayMessage.test.ts b/src/store/chat/slices/message/selectors/displayMessage.test.ts
new file mode 100644
index 00000000000..1d8d59b0790
--- /dev/null
+++ b/src/store/chat/slices/message/selectors/displayMessage.test.ts
@@ -0,0 +1,818 @@
+import { UIChatMessage } from '@lobechat/types';
+import { LobeAgentConfig } from '@lobechat/types';
+import { act } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { DEFAULT_INBOX_AVATAR } from '@/const/meta';
+import { INBOX_SESSION_ID } from '@/const/session';
+import { useAgentStore } from '@/store/agent';
+import { ChatStore } from '@/store/chat';
+import { initialState } from '@/store/chat/initialState';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { createServerConfigStore } from '@/store/serverConfig/store';
+import { merge } from '@/utils/merge';
+
+import { displayMessageSelectors } from './displayMessage';
+
+vi.mock('i18next', () => ({
+ t: vi.fn((key) => key), // Simplified mock return value
+}));
+
+const initialStore = initialState as ChatStore;
+
+const mockMessages = [
+ {
+ id: 'msg1',
+ content: 'Hello World',
+ role: 'user',
+ },
+ {
+ id: 'msg2',
+ content: 'Goodbye World',
+ role: 'user',
+ },
+ {
+ id: 'msg3',
+ content: 'Function Message',
+ role: 'tool',
+ tools: [
+ {
+ arguments: ['arg1', 'arg2'],
+ identifier: 'func1',
+ apiName: 'ttt',
+ type: 'pluginType',
+ id: 'abc',
+ },
+ ],
+ },
+] as UIChatMessage[];
+
+const mockReasoningMessages = [
+ {
+ id: 'msg1',
+ content: 'Hello World',
+ role: 'user',
+ },
+ {
+ id: 'msg2',
+ content: 'Goodbye World',
+ role: 'user',
+ },
+ {
+ id: 'msg3',
+ content: 'Content Message',
+ role: 'assistant',
+ reasoning: {
+ content: 'Reasoning Content',
+ },
+ },
+] as UIChatMessage[];
+
+const mockedChats = [
+ {
+ id: 'msg1',
+ content: 'Hello World',
+ role: 'user',
+ meta: {
+ avatar: '😀',
+ },
+ },
+ {
+ id: 'msg2',
+ content: 'Goodbye World',
+ role: 'user',
+ meta: {
+ avatar: '😀',
+ },
+ },
+ {
+ id: 'msg3',
+ content: 'Function Message',
+ role: 'tool',
+ meta: {
+ avatar: DEFAULT_INBOX_AVATAR,
+ backgroundColor: 'rgba(0,0,0,0)',
+ description: 'inbox.desc',
+ title: 'inbox.title',
+ },
+ tools: [
+ {
+ arguments: ['arg1', 'arg2'],
+ identifier: 'func1',
+ apiName: 'ttt',
+ type: 'pluginType',
+ id: 'abc',
+ },
+ ],
+ },
+] as UIChatMessage[];
+
+const mockChatStore = {
+ messagesMap: {
+ [messageMapKey('abc')]: mockMessages,
+ },
+ activeId: 'abc',
+} as ChatStore;
+
+beforeAll(() => {
+ createServerConfigStore();
+});
+
+afterEach(() => {
+ const store = createServerConfigStore();
+ store.setState((state) => ({
+ featureFlags: { ...state.featureFlags, isAgentEditable: true },
+ }));
+});
+
+describe('displayMessageSelectors', () => {
+ describe('getDisplayMessageById', () => {
+ it('should return undefined if the message with the given id does not exist', () => {
+ const message =
+ displayMessageSelectors.getDisplayMessageById('non-existent-id')(initialStore);
+ expect(message).toBeUndefined();
+ });
+
+ it('should return the message object with the matching id', () => {
+ const state = merge(initialStore, {
+ messagesMap: {
+ [messageMapKey('abc')]: mockMessages,
+ },
+ activeId: 'abc',
+ });
+ const message = displayMessageSelectors.getDisplayMessageById('msg1')(state);
+ expect(message).toEqual(mockedChats[0]);
+ });
+
+ it('should return the message with the matching id', () => {
+ const message = displayMessageSelectors.getDisplayMessageById('msg1')(mockChatStore);
+ expect(message).toEqual(mockedChats[0]);
+ });
+
+ it('should return undefined if no message matches the id', () => {
+ const message = displayMessageSelectors.getDisplayMessageById('nonexistent')(mockChatStore);
+ expect(message).toBeUndefined();
+ });
+ });
+
+ describe('mainAIChatsWithHistoryConfig', () => {
+ it('should slice the messages according to the current agent config', () => {
+ const state = merge(initialStore, {
+ messagesMap: {
+ [messageMapKey('abc')]: mockMessages,
+ },
+ activeId: 'abc',
+ });
+
+ const chats = displayMessageSelectors.mainAIChatsWithHistoryConfig(state);
+ expect(chats).toHaveLength(3);
+ expect(chats).toEqual(mockedChats);
+ });
+
+ it('should slice the messages according to config, assuming historyCount is mocked to 2', async () => {
+ const state = merge(initialStore, {
+ messagesMap: {
+ [messageMapKey('abc')]: mockMessages,
+ },
+ activeId: 'abc',
+ });
+ act(() => {
+ useAgentStore.setState({
+ activeId: 'inbox',
+ agentMap: {
+ inbox: {
+ chatConfig: {
+ historyCount: 2,
+ enableHistoryCount: true,
+ },
+ model: 'abc',
+ } as LobeAgentConfig,
+ },
+ });
+ });
+
+ const chats = displayMessageSelectors.mainAIChatsWithHistoryConfig(state);
+
+ expect(chats).toHaveLength(2);
+ expect(chats).toEqual([
+ {
+ id: 'msg2',
+ content: 'Goodbye World',
+ role: 'user',
+ meta: {
+ avatar: '😀',
+ },
+ },
+ {
+ id: 'msg3',
+ content: 'Function Message',
+ role: 'tool',
+ meta: {
+ avatar: DEFAULT_INBOX_AVATAR,
+ backgroundColor: 'rgba(0,0,0,0)',
+ description: 'inbox.desc',
+ title: 'inbox.title',
+ },
+ tools: [
+ {
+ apiName: 'ttt',
+ arguments: ['arg1', 'arg2'],
+ identifier: 'func1',
+ id: 'abc',
+ type: 'pluginType',
+ },
+ ],
+ },
+ ]);
+ });
+ });
+
+ describe('mainAIChatsMessageString', () => {
+ it('should concatenate the contents of all messages returned by mainAIChatsWithHistoryConfig', () => {
+ // Prepare a state with a few messages
+ const state = merge(initialStore, {
+ messagesMap: {
+ [messageMapKey('active-session')]: mockMessages,
+ },
+ activeId: 'active-session',
+ });
+
+ // Assume that the mainAIChatsWithHistoryConfig will return the last two messages
+ const expectedString = mockMessages
+ .slice(-2)
+ .map((m) => m.content)
+ .join('');
+
+ // Call the selector and verify the result
+ const concatenatedString = displayMessageSelectors.mainAIChatsMessageString(state);
+ expect(concatenatedString).toBe(expectedString);
+
+ // Restore the mocks after the test
+ vi.restoreAllMocks();
+ });
+ });
+
+ describe('mainAILatestMessageReasoningContent', () => {
+ it('should return the reasoning content of the latest message', () => {
+ // Prepare a state with a few messages
+ const state = merge(initialStore, {
+ messagesMap: {
+ [messageMapKey('active-session')]: mockReasoningMessages,
+ },
+ activeId: 'active-session',
+ });
+
+ const expectedString = mockReasoningMessages.at(-1)?.reasoning?.content;
+
+ // Call the selector and verify the result
+ const reasoningContent = displayMessageSelectors.mainAILatestMessageReasoningContent(state);
+ expect(reasoningContent).toBe(expectedString);
+
+ // Restore the mocks after the test
+ vi.restoreAllMocks();
+ });
+ });
+
+ describe('showInboxWelcome', () => {
+ it('should return false if the active session is not the inbox session', () => {
+ const state = merge(initialStore, { activeId: 'someActiveId' });
+ const result = displayMessageSelectors.showInboxWelcome(state);
+ expect(result).toBe(false);
+ });
+
+ it('should return false if there are existing messages in the inbox session', () => {
+ const state = merge(initialStore, {
+ activeId: INBOX_SESSION_ID,
+ messagesMap: {
+ [messageMapKey('inbox')]: mockMessages,
+ },
+ });
+ const result = displayMessageSelectors.showInboxWelcome(state);
+ expect(result).toBe(false);
+ });
+
+ it('should return true if the active session is the inbox session and there are no existing messages', () => {
+ const state = merge(initialStore, {
+ activeId: INBOX_SESSION_ID,
+ messages: [],
+ });
+ const result = displayMessageSelectors.showInboxWelcome(state);
+ expect(result).toBe(true);
+ });
+ });
+
+ describe('currentDisplayChatKey', () => {
+ it('should generate correct key with activeId only', () => {
+ const state: Partial<ChatStore> = {
+ activeId: 'testId',
+ activeTopicId: undefined,
+ };
+ const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);
+ expect(result).toBe(messageMapKey('testId', undefined));
+ });
+
+ it('should generate correct key with both activeId and activeTopicId', () => {
+ const state: Partial<ChatStore> = {
+ activeId: 'testId',
+ activeTopicId: 'topicId',
+ };
+ const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);
+ expect(result).toBe(messageMapKey('testId', 'topicId'));
+ });
+
+ it('should generate key with undefined activeId', () => {
+ const state: Partial<ChatStore> = {
+ activeId: undefined,
+ activeTopicId: 'topicId',
+ };
+ const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);
+ expect(result).toBe(messageMapKey(undefined as any, 'topicId'));
+ });
+
+ it('should generate key with empty string activeId', () => {
+ const state: Partial<ChatStore> = {
+ activeId: '',
+ activeTopicId: undefined,
+ };
+ const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);
+ expect(result).toBe(messageMapKey('', undefined));
+ });
+ });
+
+ describe('activeDisplayMessages with group chat messages', () => {
+ it('should retrieve agent meta for group chat messages with groupId and agentId', () => {
+ const groupChatMessages = [
+ {
+ id: 'msg1',
+ content: 'Hello from agent',
+ role: 'assistant',
+ groupId: 'group-123',
+ agentId: 'agent-456',
+ },
+ ] as UIChatMessage[];
+
+ const state = merge(initialStore, {
+ messagesMap: {
+ [messageMapKey('group-123')]: groupChatMessages,
+ },
+ activeId: 'group-123',
+ });
+
+ const chats = displayMessageSelectors.activeDisplayMessages(state);
+ expect(chats).toHaveLength(1);
+ expect(chats[0].id).toBe('msg1');
+ expect(chats[0].meta).toBeDefined();
+ });
+ });
+
+ describe('getGroupLatestMessageWithoutTools', () => {
+ it('should return the last child without tools', () => {
+ const groupMessage = {
+ id: 'group-1',
+ role: 'assistantGroup',
+ 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 = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-1')(
+ state as ChatStore,
+ );
+ expect(result).toBeDefined();
+ expect(result?.id).toBe('child-3');
+ expect(result?.content).toBe('Final response');
+ });
+
+ it('should return undefined if the last child has tools', () => {
+ const groupMessage = {
+ id: 'group-2',
+ role: 'assistantGroup',
+ 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 = displayMessageSelectors.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: 'assistantGroup',
+ 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 = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-3')(
+ state as ChatStore,
+ );
+ expect(result).toBeDefined();
+ expect(result?.id).toBe('child-2');
+ expect(result?.content).toBe('Final response');
+ });
+
+ it('should return undefined 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 = displayMessageSelectors.getGroupLatestMessageWithoutTools('msg-1')(
+ state as ChatStore,
+ );
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined for group messages without children', () => {
+ const groupMessage = {
+ id: 'group-4',
+ role: 'assistantGroup',
+ content: '',
+ children: undefined,
+ } as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [groupMessage],
+ },
+ };
+
+ const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-4')(
+ state as ChatStore,
+ );
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined for group messages with empty children array', () => {
+ const groupMessage = {
+ id: 'group-5',
+ role: 'assistantGroup',
+ content: '',
+ children: [],
+ } as unknown as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [groupMessage],
+ },
+ };
+
+ const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-5')(
+ state as ChatStore,
+ );
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined if all children have tools', () => {
+ const groupMessage = {
+ id: 'group-6',
+ role: 'assistantGroup',
+ 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 = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-6')(
+ state as ChatStore,
+ );
+ expect(result).toBeUndefined();
+ });
+
+ it('should handle empty tools array as no tools', () => {
+ const groupMessage = {
+ id: 'group-7',
+ role: 'assistantGroup',
+ 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 = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-7')(
+ state as ChatStore,
+ );
+ expect(result).toBeDefined();
+ expect(result?.id).toBe('child-1');
+ });
+
+ it('should return undefined when message is not found', () => {
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [],
+ },
+ };
+
+ const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('non-existent')(
+ state as ChatStore,
+ );
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe('findLastMessageId', () => {
+ it('should return message id when no children or tools', () => {
+ const message = {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Simple message',
+ } as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [message],
+ },
+ };
+
+ const result = displayMessageSelectors.findLastMessageId('msg-1')(state as ChatStore);
+ expect(result).toBe('msg-1');
+ });
+
+ it('should find the last child id', () => {
+ const groupMessage = {
+ id: 'group-1',
+ role: 'assistantGroup',
+ content: '',
+ children: [
+ {
+ id: 'child-1',
+ content: 'First response',
+ },
+ {
+ id: 'child-2',
+ content: 'Second response',
+ },
+ ],
+ } as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [groupMessage],
+ },
+ };
+
+ const result = displayMessageSelectors.findLastMessageId('group-1')(state as ChatStore);
+ expect(result).toBe('child-2');
+ });
+
+ it('should return tool result_msg_id when no children', () => {
+ const messageWithTools = {
+ id: 'msg-with-tools',
+ role: 'assistant',
+ content: 'Message with tools',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ result_msg_id: 'tool-result-1',
+ },
+ {
+ id: 'tool-2',
+ identifier: 'test2',
+ apiName: 'test2',
+ arguments: '{}',
+ type: 'default',
+ result_msg_id: 'tool-result-2',
+ },
+ ],
+ } as unknown as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [messageWithTools],
+ },
+ };
+
+ const result = displayMessageSelectors.findLastMessageId('msg-with-tools')(
+ state as ChatStore,
+ );
+ expect(result).toBe('tool-result-2');
+ });
+
+ it('should prioritize children over tools', () => {
+ const message = {
+ id: 'msg-1',
+ role: 'assistantGroup',
+ content: '',
+ children: [
+ {
+ id: 'child-1',
+ content: 'Child message',
+ },
+ ],
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ result_msg_id: 'tool-result-1',
+ },
+ ],
+ } as unknown as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [message],
+ },
+ };
+
+ const result = displayMessageSelectors.findLastMessageId('msg-1')(state as ChatStore);
+ expect(result).toBe('child-1');
+ });
+
+ it('should return undefined for non-existent message', () => {
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [],
+ },
+ };
+
+ const result = displayMessageSelectors.findLastMessageId('non-existent')(state as ChatStore);
+ expect(result).toBeUndefined();
+ });
+
+ it('should return last child with tools result_msg_id', () => {
+ const messageWithChildrenAndTools = {
+ id: 'msg-1',
+ role: 'assistantGroup',
+ content: '',
+ children: [
+ {
+ id: 'child-1',
+ content: 'First child',
+ },
+ {
+ id: 'child-2',
+ content: 'Second child with tools',
+ tools: [
+ {
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+ result_msg_id: 'tool-result-id',
+ },
+ ],
+ },
+ ],
+ } as unknown as UIChatMessage;
+
+ const state: Partial<ChatStore> = {
+ activeId: 'test-id',
+ messagesMap: {
+ [messageMapKey('test-id')]: [messageWithChildrenAndTools],
+ },
+ };
+
+ const result = displayMessageSelectors.findLastMessageId('msg-1')(state as ChatStore);
+ expect(result).toBe('tool-result-id');
+ });
+ });
+});
diff --git a/src/store/chat/slices/message/selectors/displayMessage.ts b/src/store/chat/slices/message/selectors/displayMessage.ts
index bf6ef066694..c7812f3bb26 100644
--- a/src/store/chat/slices/message/selectors/displayMessage.ts
+++ b/src/store/chat/slices/message/selectors/displayMessage.ts
@@ -1,4 +1,4 @@
-import { UIChatMessage } from '@lobechat/types';
+import { AssistantContentBlock, UIChatMessage } from '@lobechat/types';
import { DEFAULT_USER_AVATAR } from '@/const/meta';
import { INBOX_SESSION_ID } from '@/const/session';
@@ -250,12 +250,62 @@ const getGroupLatestMessageWithoutTools = (id: string) => (s: ChatStoreState) =>
// Return the last child only if it doesn't have tools
if (!lastChild.tools || lastChild.tools.length === 0) {
+ if (!lastChild.content) return;
+
return lastChild;
}
return;
};
+/**
+ * Helper to find last message ID in an AssistantContentBlock
+ */
+const findLastBlockId = (block: AssistantContentBlock | undefined): string | undefined => {
+ if (!block) return undefined;
+
+ // Check tools for result message ID
+ if (block.tools && block.tools.length > 0) {
+ const lastTool = block.tools.at(-1);
+ return lastTool?.result_msg_id;
+ }
+
+ // Return block ID
+ return block.id;
+};
+
+/**
+ * Recursively finds the last message ID in a message tree
+ * Priority: children > tools > self
+ */
+const findLastMessageIdRecursive = (node: UIChatMessage | undefined): string | undefined => {
+ if (!node) return undefined;
+
+ // Priority 1: Dive into children recursively
+ if (node.children && node.children.length > 0) {
+ const lastChild = node.children.at(-1);
+ return findLastBlockId(lastChild);
+ }
+
+ // Priority 2: Check tools for result message ID
+ if (node.tools && node.tools.length > 0) {
+ const lastTool = node.tools.at(-1);
+ return lastTool?.result_msg_id;
+ }
+
+ // Priority 3: Return self ID
+ return node.id;
+};
+
+/**
+ * Finds the last (deepest) message ID from a display message
+ * Recursively traverses children and tools to find the actual last message
+ */
+const findLastMessageId = (id: string) => (s: ChatStoreState) => {
+ const message = getDisplayMessageById(id)(s);
+ return findLastMessageIdRecursive(message);
+};
+
// ============= Supervisor Selectors ========== //
const isSupervisorLoading = (groupId: string) => (s: ChatStoreState) =>
@@ -281,6 +331,7 @@ export const displayMessageSelectors = {
activeDisplayMessages,
currentChatLoadingState,
currentDisplayChatKey,
+ findLastMessageId,
getDisplayMessageById,
getDisplayMessagesByKey,
getGroupLatestMessageWithoutTools,
diff --git a/src/store/chat/slices/message/selectors/messageState.ts b/src/store/chat/slices/message/selectors/messageState.ts
index 23a95f242ac..539a9fcd5ac 100644
--- a/src/store/chat/slices/message/selectors/messageState.ts
+++ b/src/store/chat/slices/message/selectors/messageState.ts
@@ -5,6 +5,7 @@ import { getDbMessageByToolCallId } from './dbMessage';
const isMessageEditing = (id: string) => (s: ChatStoreState) => s.messageEditingIds.includes(id);
const isMessageLoading = (id: string) => (s: ChatStoreState) => s.messageLoadingIds.includes(id);
const isMessageRegenerating = (id: string) => (s: ChatStoreState) => s.regeneratingIds.includes(id);
+const isMessageContinuing = (id: string) => (s: ChatStoreState) => s.continuingIds.includes(id);
const isMessageGenerating = (id: string) => (s: ChatStoreState) => s.chatLoadingIds.includes(id);
const isMessageInRAGFlow = (id: string) => (s: ChatStoreState) =>
@@ -70,6 +71,7 @@ export const messageStateSelectors = {
isHasMessageLoading,
isInRAGFlow,
isInToolsCalling,
+ isMessageContinuing,
isMessageEditing,
isMessageGenerating,
isMessageInChatReasoning,
diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.ts
index e3d5d2f2835..57f23b39da3 100644
--- a/src/store/chat/slices/plugin/action.test.ts
+++ b/src/store/chat/slices/plugin/action.test.ts
@@ -544,7 +544,7 @@ describe('ChatPluginAction', () => {
const { result } = renderHook(() => useChatStore());
await act(async () => {
- await result.current.updatePluginState(messageId, pluginStateValue);
+ await result.current.optimisticUpdatePluginState(messageId, pluginStateValue);
});
expect(messageService.updateMessagePluginState).toHaveBeenCalledWith(
@@ -887,7 +887,7 @@ describe('ChatPluginAction', () => {
const { result } = renderHook(() => useChatStore());
await act(async () => {
- await result.current.updatePluginArguments(messageId, newArguments);
+ await result.current.optimisticUpdatePluginArguments(messageId, newArguments);
});
expect(messageService.updateMessagePluginArguments).toHaveBeenCalledWith(
@@ -1103,7 +1103,7 @@ describe('ChatPluginAction', () => {
const { result } = renderHook(() => useChatStore());
await act(async () => {
- await result.current.internal_updatePluginError(messageId, error);
+ await result.current.optimisticUpdatePluginError(messageId, error);
});
expect(messageService.updateMessage).toHaveBeenCalledWith(
@@ -1144,7 +1144,7 @@ describe('ChatPluginAction', () => {
});
await act(async () => {
- await result.current.internal_addToolToAssistantMessage(messageId, {
+ await result.current.optimisticAddToolToAssistantMessage(messageId, {
identifier,
arguments: '{"oldKey":"oldValue"}',
id: 'newId',
diff --git a/src/store/chat/slices/plugin/action.ts b/src/store/chat/slices/plugin/action.ts
deleted file mode 100644
index 5678aeea7fd..00000000000
--- a/src/store/chat/slices/plugin/action.ts
+++ /dev/null
@@ -1,539 +0,0 @@
-/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
-import { ToolNameResolver } from '@lobechat/context-engine';
-import {
- ChatMessageError,
- ChatToolPayload,
- CreateMessageParams,
- MessageToolCall,
- ToolsCallingContext,
- UIChatMessage,
-} from '@lobechat/types';
-import { LobeChatPluginManifest, PluginErrorType } from '@lobehub/chat-plugin-sdk';
-import isEqual from 'fast-deep-equal';
-import { t } from 'i18next';
-import { StateCreator } from 'zustand/vanilla';
-
-import { chatService } from '@/services/chat';
-import { mcpService } from '@/services/mcp';
-import { messageService } from '@/services/message';
-import { ChatStore } from '@/store/chat/store';
-import { useToolStore } from '@/store/tool';
-import { pluginSelectors } from '@/store/tool/selectors';
-import { builtinTools } from '@/tools';
-import { merge } from '@/utils/merge';
-import { safeParseJSON } from '@/utils/safeParseJSON';
-import { setNamespace } from '@/utils/storeDebug';
-
-import { dbMessageSelectors, displayMessageSelectors } from '../message/selectors';
-import { threadSelectors } from '../thread/selectors';
-
-const n = setNamespace('plugin');
-
-export interface ChatPluginAction {
- createAssistantMessageByPlugin: (content: string, parentId: string) => Promise<void>;
- fillPluginMessageContent: (
- id: string,
- content: string,
- triggerAiMessage?: boolean,
- ) => Promise<void>;
-
- invokeBuiltinTool: (id: string, payload: ChatToolPayload) => Promise<void>;
- invokeDefaultTypePlugin: (id: string, payload: any) => Promise<string | undefined>;
- invokeMarkdownTypePlugin: (id: string, payload: ChatToolPayload) => Promise<void>;
- invokeMCPTypePlugin: (id: string, payload: ChatToolPayload) => Promise<string | undefined>;
-
- invokeStandaloneTypePlugin: (id: string, payload: ChatToolPayload) => Promise<void>;
-
- reInvokeToolMessage: (id: string) => Promise<void>;
- triggerAIMessage: (params: {
- parentId?: string;
- traceId?: string;
- threadId?: string;
- inPortalThread?: boolean;
- inSearchWorkflow?: boolean;
- }) => Promise<void>;
- summaryPluginContent: (id: string) => Promise<void>;
-
- /**
- * @deprecated V1 method
- */
- triggerToolCalls: (
- id: string,
- params?: { threadId?: string; inPortalThread?: boolean; inSearchWorkflow?: boolean },
- ) => Promise<void>;
- updatePluginState: (id: string, value: any) => Promise<void>;
- updatePluginArguments: <T = any>(id: string, value: T, replace?: boolean) => Promise<void>;
-
- internal_addToolToAssistantMessage: (id: string, tool: ChatToolPayload) => Promise<void>;
- internal_removeToolToAssistantMessage: (id: string, tool_call_id?: string) => Promise<void>;
- /**
- * use the optimistic update value to update the message tools to database
- */
- internal_refreshToUpdateMessageTools: (id: string) => Promise<void>;
-
- internal_callPluginApi: (id: string, payload: ChatToolPayload) => Promise<string | undefined>;
- internal_invokeDifferentTypePlugin: (id: string, payload: ChatToolPayload) => Promise<any>;
- internal_togglePluginApiCalling: (
- loading: boolean,
- id?: string,
- action?: string,
- ) => AbortController | undefined;
- internal_transformToolCalls: (toolCalls: MessageToolCall[]) => ChatToolPayload[];
- internal_updatePluginError: (id: string, error: ChatMessageError) => Promise<void>;
- internal_constructToolsCallingContext: (id: string) => ToolsCallingContext | undefined;
-}
-
-export const chatPlugin: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ChatPluginAction
-> = (set, get) => ({
- createAssistantMessageByPlugin: async (content, parentId) => {
- const newMessage: CreateMessageParams = {
- content,
- parentId,
- role: 'assistant',
- sessionId: get().activeId,
- topicId: get().activeTopicId, // if there is activeTopicId,then add it to topicId
- };
-
- const result = await messageService.createMessage(newMessage);
- get().replaceMessages(result.messages);
- },
-
- fillPluginMessageContent: async (id, content, triggerAiMessage) => {
- const { triggerAIMessage, optimisticUpdateMessageContent } = get();
-
- await optimisticUpdateMessageContent(id, content);
-
- if (triggerAiMessage) await triggerAIMessage({ parentId: id });
- },
- invokeBuiltinTool: async (id, payload) => {
- // run tool api call
- // @ts-ignore
- const { [payload.apiName]: action } = get();
- if (!action) return;
-
- const content = safeParseJSON(payload.arguments);
-
- if (!content) return;
-
- return await action(id, content);
- },
-
- invokeDefaultTypePlugin: async (id, payload) => {
- const { internal_callPluginApi } = get();
-
- const data = await internal_callPluginApi(id, payload);
-
- if (!data) return;
-
- return data;
- },
-
- invokeMarkdownTypePlugin: async (id, payload) => {
- const { internal_callPluginApi } = get();
-
- await internal_callPluginApi(id, payload);
- },
-
- invokeStandaloneTypePlugin: async (id, payload) => {
- const result = await useToolStore.getState().validatePluginSettings(payload.identifier);
- if (!result) return;
-
- // if the plugin settings is not valid, then set the message with error type
- if (!result.valid) {
- const updateResult = await messageService.updateMessageError(id, {
- body: {
- error: result.errors,
- message: '[plugin] your settings is invalid with plugin manifest setting schema',
- },
- message: t('response.PluginSettingsInvalid', { ns: 'error' }),
- type: PluginErrorType.PluginSettingsInvalid as any,
- });
-
- if (updateResult?.success && updateResult.messages) {
- get().replaceMessages(updateResult.messages);
- }
- return;
- }
- },
-
- reInvokeToolMessage: async (id) => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
- if (!message || message.role !== 'tool' || !message.plugin) return;
-
- // if there is error content, then clear the error
- if (!!message.pluginError) {
- get().optimisticUpdateMessagePluginError(id, null);
- }
-
- const payload: ChatToolPayload = { ...message.plugin, id: message.tool_call_id! };
-
- await get().internal_invokeDifferentTypePlugin(id, payload);
- },
-
- triggerAIMessage: async ({ parentId, traceId, threadId, inPortalThread, inSearchWorkflow }) => {
- const { internal_execAgentRuntime } = get();
-
- const chats = inPortalThread
- ? threadSelectors.portalAIChatsWithHistoryConfig(get())
- : displayMessageSelectors.mainAIChatsWithHistoryConfig(get());
-
- await internal_execAgentRuntime({
- messages: chats,
- parentMessageId: parentId ?? chats.at(-1)!.id,
- parentMessageType: 'user',
- traceId,
- threadId,
- inPortalThread,
- inSearchWorkflow,
- });
- },
-
- summaryPluginContent: async (id) => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
- if (!message || message.role !== 'tool') return;
-
- await get().internal_execAgentRuntime({
- messages: [
- {
- role: 'assistant',
- content: '作为一名总结专家,请结合以上系统提示词,将以下内容进行总结:',
- },
- {
- ...message,
- content: message.content,
- role: 'assistant',
- name: undefined,
- tool_call_id: undefined,
- },
- ] as UIChatMessage[],
- parentMessageId: message.id,
- parentMessageType: 'assistant',
- });
- },
-
- triggerToolCalls: async (assistantId, { threadId, inPortalThread, inSearchWorkflow } = {}) => {
- const message = displayMessageSelectors.getDisplayMessageById(assistantId)(get());
- if (!message || !message.tools) return;
-
- let shouldCreateMessage = false;
- let latestToolId = '';
- const messagePools = message.tools.map(async (payload) => {
- const toolMessage: CreateMessageParams = {
- content: '',
- parentId: assistantId,
- plugin: payload,
- role: 'tool',
- sessionId: get().activeId,
- tool_call_id: payload.id,
- threadId,
- topicId: get().activeTopicId, // if there is activeTopicId,then add it to topicId
- groupId: message.groupId, // Propagate groupId from parent message for group chat
- };
-
- const result = await get().optimisticCreateMessage(toolMessage);
- if (!result) return;
-
- // trigger the plugin call
- const data = await get().internal_invokeDifferentTypePlugin(result.id, payload);
-
- if (data && !['markdown', 'standalone'].includes(payload.type)) {
- shouldCreateMessage = true;
- latestToolId = result.id;
- }
- });
-
- await Promise.all(messagePools);
-
- await get().internal_toggleMessageInToolsCalling(false, assistantId);
-
- // only default type tool calls should trigger AI message
- if (!shouldCreateMessage) return;
-
- const traceId = dbMessageSelectors.getTraceIdByDbMessageId(latestToolId)(get());
-
- await get().triggerAIMessage({ traceId, threadId, inPortalThread, inSearchWorkflow });
- },
- updatePluginState: async (id, value) => {
- const { replaceMessages } = get();
-
- // optimistic update
- get().internal_dispatchMessage({ id, type: 'updateMessage', value: { pluginState: value } });
-
- const result = await messageService.updateMessagePluginState(id, value, {
- sessionId: get().activeId,
- topicId: get().activeTopicId,
- });
-
- if (result?.success && result.messages) {
- replaceMessages(result.messages);
- }
- },
-
- updatePluginArguments: async (id, value, replace = false) => {
- const { refreshMessages } = get();
- const toolMessage = displayMessageSelectors.getDisplayMessageById(id)(get());
- if (!toolMessage || !toolMessage?.tool_call_id) return;
-
- let assistantMessage = displayMessageSelectors.getDisplayMessageById(
- toolMessage?.parentId || '',
- )(get());
-
- const prevArguments = toolMessage?.plugin?.arguments;
- const prevJson = safeParseJSON(prevArguments || '');
- const nextValue = replace ? (value as any) : merge(prevJson || {}, value);
- if (isEqual(prevJson, nextValue)) return;
-
- // optimistic update
- get().internal_dispatchMessage({
- id,
- type: 'updateMessagePlugin',
- value: { arguments: JSON.stringify(nextValue) },
- });
-
- // 同样需要更新 assistantMessage 的 pluginArguments
- if (assistantMessage) {
- get().internal_dispatchMessage({
- id: assistantMessage.id,
- type: 'updateMessageTools',
- tool_call_id: toolMessage?.tool_call_id,
- value: { arguments: JSON.stringify(nextValue) },
- });
- assistantMessage = displayMessageSelectors.getDisplayMessageById(assistantMessage?.id)(get());
- }
-
- const updateAssistantMessage = async () => {
- if (!assistantMessage) return;
- await messageService.updateMessage(assistantMessage!.id, {
- tools: assistantMessage?.tools,
- });
- };
-
- await Promise.all([
- messageService.updateMessagePluginArguments(id, nextValue),
- updateAssistantMessage(),
- ]);
-
- await refreshMessages();
- },
-
- internal_addToolToAssistantMessage: async (id, tool) => {
- const assistantMessage = displayMessageSelectors.getDisplayMessageById(id)(get());
- if (!assistantMessage) return;
-
- const { internal_dispatchMessage, internal_refreshToUpdateMessageTools } = get();
- internal_dispatchMessage({
- type: 'addMessageTool',
- value: tool,
- id: assistantMessage.id,
- });
-
- await internal_refreshToUpdateMessageTools(id);
- },
-
- internal_removeToolToAssistantMessage: async (id, tool_call_id) => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
- if (!message || !tool_call_id) return;
-
- const { internal_dispatchMessage, internal_refreshToUpdateMessageTools } = get();
-
- // optimistic update
- internal_dispatchMessage({ type: 'deleteMessageTool', tool_call_id, id: message.id });
-
- // update the message tools
- await internal_refreshToUpdateMessageTools(id);
- },
- internal_refreshToUpdateMessageTools: async (id) => {
- const message = dbMessageSelectors.getDbMessageById(id)(get());
- if (!message || !message.tools) return;
-
- const { internal_toggleMessageLoading, replaceMessages } = get();
-
- internal_toggleMessageLoading(true, id);
- const result = await messageService.updateMessage(
- id,
- { tools: message.tools },
- {
- sessionId: get().activeId,
- topicId: get().activeTopicId,
- },
- );
- internal_toggleMessageLoading(false, id);
-
- if (result?.success && result.messages) {
- replaceMessages(result.messages);
- }
- },
-
- internal_callPluginApi: async (id, payload) => {
- const { optimisticUpdateMessageContent, internal_togglePluginApiCalling } = get();
- let data: string;
-
- try {
- const abortController = internal_togglePluginApiCalling(
- true,
- id,
- n('fetchPlugin/start') as string,
- );
-
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
-
- const res = await chatService.runPluginApi(payload, {
- signal: abortController?.signal,
- trace: { observationId: message?.observationId, traceId: message?.traceId },
- });
- data = res.text;
-
- // save traceId
- if (res.traceId) {
- await messageService.updateMessage(id, { traceId: res.traceId });
- }
- } catch (error) {
- console.log(error);
- const err = error as Error;
-
- // ignore the aborted request error
- if (!err.message.includes('The user aborted a request.')) {
- const result = await messageService.updateMessageError(id, error as any);
- if (result?.success && result.messages) {
- get().replaceMessages(result.messages);
- }
- }
-
- data = '';
- }
-
- internal_togglePluginApiCalling(false, id, n('fetchPlugin/end') as string);
- // 如果报错则结束了
- if (!data) return;
-
- await optimisticUpdateMessageContent(id, data);
-
- return data;
- },
-
- internal_invokeDifferentTypePlugin: async (id, payload) => {
- switch (payload.type) {
- case 'standalone': {
- return await get().invokeStandaloneTypePlugin(id, payload);
- }
-
- case 'markdown': {
- return await get().invokeMarkdownTypePlugin(id, payload);
- }
-
- case 'builtin': {
- return await get().invokeBuiltinTool(id, payload);
- }
-
- // @ts-ignore
- case 'mcp': {
- return await get().invokeMCPTypePlugin(id, payload);
- }
-
- default: {
- return await get().invokeDefaultTypePlugin(id, payload);
- }
- }
- },
- invokeMCPTypePlugin: async (id, payload) => {
- const {
- optimisticUpdateMessageContent,
- internal_togglePluginApiCalling,
- internal_constructToolsCallingContext,
- } = get();
- let data: string = '';
-
- try {
- const abortController = internal_togglePluginApiCalling(
- true,
- id,
- n('fetchPlugin/start') as string,
- );
-
- const context = internal_constructToolsCallingContext(id);
- const result = await mcpService.invokeMcpToolCall(payload, {
- signal: abortController?.signal,
- topicId: context?.topicId,
- });
-
- if (!!result) data = result;
- } catch (error) {
- console.log(error);
- const err = error as Error;
-
- // ignore the aborted request error
- if (!err.message.includes('The user aborted a request.')) {
- const result = await messageService.updateMessageError(id, error as any);
- if (result?.success && result.messages) {
- get().replaceMessages(result.messages);
- }
- }
- }
-
- internal_togglePluginApiCalling(false, id, n('fetchPlugin/end') as string);
- // 如果报错则结束了
- if (!data) return;
-
- await optimisticUpdateMessageContent(id, data);
-
- return data;
- },
-
- internal_togglePluginApiCalling: (loading, id, action) => {
- return get().internal_toggleLoadingArrays('pluginApiLoadingIds', loading, id, action);
- },
-
- internal_transformToolCalls: (toolCalls) => {
- const toolNameResolver = new ToolNameResolver();
-
- // Build manifests map from tool store
- const toolStoreState = useToolStore.getState();
- const manifests: Record<string, LobeChatPluginManifest> = {};
-
- // Get all installed plugins
- const installedPlugins = pluginSelectors.installedPlugins(toolStoreState);
- for (const plugin of installedPlugins) {
- if (plugin.manifest) {
- manifests[plugin.identifier] = plugin.manifest as LobeChatPluginManifest;
- }
- }
-
- // Get all builtin tools
- for (const tool of builtinTools) {
- if (tool.manifest) {
- manifests[tool.identifier] = tool.manifest as LobeChatPluginManifest;
- }
- }
-
- return toolNameResolver.resolve(toolCalls, manifests);
- },
- internal_updatePluginError: async (id, error) => {
- const { replaceMessages } = get();
-
- get().internal_dispatchMessage({ id, type: 'updateMessage', value: { error } });
- const result = await messageService.updateMessage(
- id,
- { error },
- {
- sessionId: get().activeId,
- topicId: get().activeTopicId,
- },
- );
- if (result?.success && result.messages) {
- replaceMessages(result.messages);
- }
- },
-
- internal_constructToolsCallingContext: (id: string) => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
- if (!message) return;
-
- return {
- topicId: message.topicId,
- };
- },
-});
diff --git a/src/store/chat/slices/plugin/actions/index.ts b/src/store/chat/slices/plugin/actions/index.ts
new file mode 100644
index 00000000000..3e576208134
--- /dev/null
+++ b/src/store/chat/slices/plugin/actions/index.ts
@@ -0,0 +1,39 @@
+import { StateCreator } from 'zustand/vanilla';
+
+import { ChatStore } from '@/store/chat/store';
+
+import { PluginInternalsAction, pluginInternals } from './internals';
+import { PluginOptimisticUpdateAction, pluginOptimisticUpdate } from './optimisticUpdate';
+import { PluginTypesAction, pluginTypes } from './pluginTypes';
+import { PluginPublicApiAction, pluginPublicApi } from './publicApi';
+import { PluginWorkflowAction, pluginWorkflow } from './workflow';
+
+/**
+ * Combined plugin action interface
+ * Aggregates all plugin-related actions
+ */
+export interface ChatPluginAction
+ extends PluginPublicApiAction,
+ PluginOptimisticUpdateAction,
+ PluginTypesAction,
+ PluginWorkflowAction,
+ PluginInternalsAction {
+ /**/
+}
+
+/**
+ * Combined plugin action creator
+ * Merges all plugin action modules
+ */
+export const chatPlugin: StateCreator<
+ ChatStore,
+ [['zustand/devtools', never]],
+ [],
+ ChatPluginAction
+> = (...params) => ({
+ ...pluginPublicApi(...params),
+ ...pluginOptimisticUpdate(...params),
+ ...pluginTypes(...params),
+ ...pluginWorkflow(...params),
+ ...pluginInternals(...params),
+});
diff --git a/src/store/chat/slices/plugin/actions/internals.ts b/src/store/chat/slices/plugin/actions/internals.ts
new file mode 100644
index 00000000000..a444ff25be7
--- /dev/null
+++ b/src/store/chat/slices/plugin/actions/internals.ts
@@ -0,0 +1,83 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
+import { ToolNameResolver } from '@lobechat/context-engine';
+import { MessageToolCall, ToolsCallingContext } from '@lobechat/types';
+import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
+import { StateCreator } from 'zustand/vanilla';
+
+import { ChatStore } from '@/store/chat/store';
+import { useToolStore } from '@/store/tool';
+import { pluginSelectors } from '@/store/tool/selectors';
+import { builtinTools } from '@/tools';
+import { Action } from '@/utils/storeDebug';
+
+import { displayMessageSelectors } from '../../message/selectors';
+
+/**
+ * Internal utility methods and runtime state management
+ * These are building blocks used by other actions
+ */
+export interface PluginInternalsAction {
+ /**
+ * Toggle plugin API calling state
+ */
+ internal_togglePluginApiCalling: (
+ loading: boolean,
+ id?: string,
+ action?: Action,
+ ) => AbortController | undefined;
+
+ /**
+ * Transform tool calls from runtime format to storage format
+ */
+ internal_transformToolCalls: (toolCalls: MessageToolCall[]) => any[];
+
+ /**
+ * Construct tools calling context for plugin invocation
+ */
+ internal_constructToolsCallingContext: (id: string) => ToolsCallingContext | undefined;
+}
+
+export const pluginInternals: StateCreator<
+ ChatStore,
+ [['zustand/devtools', never]],
+ [],
+ PluginInternalsAction
+> = (set, get) => ({
+ internal_togglePluginApiCalling: (loading, id, action) => {
+ return get().internal_toggleLoadingArrays('pluginApiLoadingIds', loading, id, action);
+ },
+
+ internal_transformToolCalls: (toolCalls) => {
+ const toolNameResolver = new ToolNameResolver();
+
+ // Build manifests map from tool store
+ const toolStoreState = useToolStore.getState();
+ const manifests: Record<string, LobeChatPluginManifest> = {};
+
+ // Get all installed plugins
+ const installedPlugins = pluginSelectors.installedPlugins(toolStoreState);
+ for (const plugin of installedPlugins) {
+ if (plugin.manifest) {
+ manifests[plugin.identifier] = plugin.manifest as LobeChatPluginManifest;
+ }
+ }
+
+ // Get all builtin tools
+ for (const tool of builtinTools) {
+ if (tool.manifest) {
+ manifests[tool.identifier] = tool.manifest as LobeChatPluginManifest;
+ }
+ }
+
+ return toolNameResolver.resolve(toolCalls, manifests);
+ },
+
+ internal_constructToolsCallingContext: (id: string) => {
+ const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+ if (!message) return;
+
+ return {
+ topicId: message.topicId,
+ };
+ },
+});
diff --git a/src/store/chat/slices/plugin/actions/optimisticUpdate.ts b/src/store/chat/slices/plugin/actions/optimisticUpdate.ts
new file mode 100644
index 00000000000..9dc7aa20c20
--- /dev/null
+++ b/src/store/chat/slices/plugin/actions/optimisticUpdate.ts
@@ -0,0 +1,188 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
+import { ChatMessageError, ChatToolPayload } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+import { StateCreator } from 'zustand/vanilla';
+
+import { messageService } from '@/services/message';
+import { ChatStore } from '@/store/chat/store';
+import { merge } from '@/utils/merge';
+import { safeParseJSON } from '@/utils/safeParseJSON';
+
+import { displayMessageSelectors } from '../../message/selectors';
+
+/**
+ * Optimistic update operations for plugin-related data
+ * All methods follow the pattern: update frontend first, then persist to database
+ */
+export interface PluginOptimisticUpdateAction {
+ /**
+ * Update plugin state with optimistic update
+ */
+ optimisticUpdatePluginState: (id: string, value: any) => Promise<void>;
+
+ /**
+ * Update plugin arguments with optimistic update
+ */
+ optimisticUpdatePluginArguments: <T = any>(
+ id: string,
+ value: T,
+ replace?: boolean,
+ ) => Promise<void>;
+
+ /**
+ * Add tool to assistant message with optimistic update
+ */
+ optimisticAddToolToAssistantMessage: (id: string, tool: ChatToolPayload) => Promise<void>;
+
+ /**
+ * Remove tool from assistant message with optimistic update
+ */
+ optimisticRemoveToolFromAssistantMessage: (id: string, tool_call_id?: string) => Promise<void>;
+
+ /**
+ * Update plugin error with optimistic update
+ */
+ optimisticUpdatePluginError: (id: string, error: ChatMessageError) => Promise<void>;
+
+ /**
+ * Use the optimistic update value to update the message tools to database
+ */
+ internal_refreshToUpdateMessageTools: (id: string) => Promise<void>;
+}
+
+export const pluginOptimisticUpdate: StateCreator<
+ ChatStore,
+ [['zustand/devtools', never]],
+ [],
+ PluginOptimisticUpdateAction
+> = (set, get) => ({
+ optimisticUpdatePluginState: async (id, value) => {
+ const { replaceMessages } = get();
+
+ // optimistic update
+ get().internal_dispatchMessage({ id, type: 'updateMessage', value: { pluginState: value } });
+
+ const result = await messageService.updateMessagePluginState(id, value, {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ });
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ optimisticUpdatePluginArguments: async (id, value, replace = false) => {
+ const { refreshMessages } = get();
+ const toolMessage = displayMessageSelectors.getDisplayMessageById(id)(get());
+ if (!toolMessage || !toolMessage?.tool_call_id) return;
+
+ let assistantMessage = displayMessageSelectors.getDisplayMessageById(
+ toolMessage?.parentId || '',
+ )(get());
+
+ const prevArguments = toolMessage?.plugin?.arguments;
+ const prevJson = safeParseJSON(prevArguments || '');
+ const nextValue = replace ? (value as any) : merge(prevJson || {}, value);
+ if (isEqual(prevJson, nextValue)) return;
+
+ // optimistic update
+ get().internal_dispatchMessage({
+ id,
+ type: 'updateMessagePlugin',
+ value: { arguments: JSON.stringify(nextValue) },
+ });
+
+ // 同样需要更新 assistantMessage 的 pluginArguments
+ if (assistantMessage) {
+ get().internal_dispatchMessage({
+ id: assistantMessage.id,
+ type: 'updateMessageTools',
+ tool_call_id: toolMessage?.tool_call_id,
+ value: { arguments: JSON.stringify(nextValue) },
+ });
+ assistantMessage = displayMessageSelectors.getDisplayMessageById(assistantMessage?.id)(get());
+ }
+
+ const updateAssistantMessage = async () => {
+ if (!assistantMessage) return;
+ await messageService.updateMessage(assistantMessage!.id, {
+ tools: assistantMessage?.tools,
+ });
+ };
+
+ await Promise.all([
+ messageService.updateMessagePluginArguments(id, nextValue),
+ updateAssistantMessage(),
+ ]);
+
+ await refreshMessages();
+ },
+
+ optimisticAddToolToAssistantMessage: async (id, tool) => {
+ const assistantMessage = displayMessageSelectors.getDisplayMessageById(id)(get());
+ if (!assistantMessage) return;
+
+ const { internal_dispatchMessage, internal_refreshToUpdateMessageTools } = get();
+ internal_dispatchMessage({
+ type: 'addMessageTool',
+ value: tool,
+ id: assistantMessage.id,
+ });
+
+ await internal_refreshToUpdateMessageTools(id);
+ },
+
+ optimisticRemoveToolFromAssistantMessage: async (id, tool_call_id) => {
+ const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+ if (!message || !tool_call_id) return;
+
+ const { internal_dispatchMessage, internal_refreshToUpdateMessageTools } = get();
+
+ // optimistic update
+ internal_dispatchMessage({ type: 'deleteMessageTool', tool_call_id, id: message.id });
+
+ // update the message tools
+ await internal_refreshToUpdateMessageTools(id);
+ },
+
+ optimisticUpdatePluginError: async (id, error) => {
+ const { replaceMessages } = get();
+
+ get().internal_dispatchMessage({ id, type: 'updateMessage', value: { error } });
+ const result = await messageService.updateMessage(
+ id,
+ { error },
+ {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ },
+ );
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ internal_refreshToUpdateMessageTools: async (id) => {
+ const { dbMessageSelectors } = await import('../../message/selectors');
+ const message = dbMessageSelectors.getDbMessageById(id)(get());
+ if (!message || !message.tools) return;
+
+ const { internal_toggleMessageLoading, replaceMessages } = get();
+
+ internal_toggleMessageLoading(true, id);
+ const result = await messageService.updateMessage(
+ id,
+ { tools: message.tools },
+ {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ },
+ );
+ internal_toggleMessageLoading(false, id);
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+});
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
new file mode 100644
index 00000000000..fb5951777d5
--- /dev/null
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -0,0 +1,213 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
+import { ChatToolPayload } from '@lobechat/types';
+import { PluginErrorType } from '@lobehub/chat-plugin-sdk';
+import { t } from 'i18next';
+import { StateCreator } from 'zustand/vanilla';
+
+import { MCPToolCallResult } from '@/libs/mcp';
+import { chatService } from '@/services/chat';
+import { mcpService } from '@/services/mcp';
+import { messageService } from '@/services/message';
+import { ChatStore } from '@/store/chat/store';
+import { useToolStore } from '@/store/tool';
+import { safeParseJSON } from '@/utils/safeParseJSON';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { displayMessageSelectors } from '../../message/selectors';
+
+const n = setNamespace('plugin');
+
+/**
+ * Plugin type-specific implementations
+ * Each method handles a specific type of plugin invocation
+ */
+export interface PluginTypesAction {
+ /**
+ * Invoke builtin tool
+ */
+ invokeBuiltinTool: (id: string, payload: ChatToolPayload) => Promise<void>;
+
+ /**
+ * Invoke default type plugin (returns data)
+ */
+ invokeDefaultTypePlugin: (id: string, payload: any) => Promise<string | undefined>;
+
+ /**
+ * Invoke markdown type plugin
+ */
+ invokeMarkdownTypePlugin: (id: string, payload: ChatToolPayload) => Promise<void>;
+
+ /**
+ * Invoke MCP type plugin
+ */
+ invokeMCPTypePlugin: (id: string, payload: ChatToolPayload) => Promise<string | undefined>;
+
+ /**
+ * Invoke standalone type plugin
+ */
+ invokeStandaloneTypePlugin: (id: string, payload: ChatToolPayload) => Promise<void>;
+
+ /**
+ * Internal method to call plugin API
+ */
+ internal_callPluginApi: (id: string, payload: ChatToolPayload) => Promise<string | undefined>;
+}
+
+export const pluginTypes: StateCreator<
+ ChatStore,
+ [['zustand/devtools', never]],
+ [],
+ PluginTypesAction
+> = (set, get) => ({
+ invokeBuiltinTool: async (id, payload) => {
+ // run tool api call
+ // @ts-ignore
+ const { [payload.apiName]: action } = get();
+ if (!action) return;
+
+ const content = safeParseJSON(payload.arguments);
+
+ if (!content) return;
+
+ return await action(id, content);
+ },
+
+ invokeDefaultTypePlugin: async (id, payload) => {
+ const { internal_callPluginApi } = get();
+
+ const data = await internal_callPluginApi(id, payload);
+
+ if (!data) return;
+
+ return data;
+ },
+
+ invokeMarkdownTypePlugin: async (id, payload) => {
+ const { internal_callPluginApi } = get();
+
+ await internal_callPluginApi(id, payload);
+ },
+
+ invokeStandaloneTypePlugin: async (id, payload) => {
+ const result = await useToolStore.getState().validatePluginSettings(payload.identifier);
+ if (!result) return;
+
+ // if the plugin settings is not valid, then set the message with error type
+ if (!result.valid) {
+ const updateResult = await messageService.updateMessageError(id, {
+ body: {
+ error: result.errors,
+ message: '[plugin] your settings is invalid with plugin manifest setting schema',
+ },
+ message: t('response.PluginSettingsInvalid', { ns: 'error' }),
+ type: PluginErrorType.PluginSettingsInvalid as any,
+ });
+
+ if (updateResult?.success && updateResult.messages) {
+ get().replaceMessages(updateResult.messages);
+ }
+ return;
+ }
+ },
+
+ invokeMCPTypePlugin: async (id, payload) => {
+ const {
+ optimisticUpdateMessageContent,
+ internal_togglePluginApiCalling,
+ internal_constructToolsCallingContext,
+ optimisticUpdatePluginState,
+ optimisticUpdateMessagePluginError,
+ } = get();
+ let data: MCPToolCallResult | undefined;
+
+ try {
+ const abortController = internal_togglePluginApiCalling(
+ true,
+ id,
+ n('fetchPlugin/start') as string,
+ );
+
+ const context = internal_constructToolsCallingContext(id);
+ const result = await mcpService.invokeMcpToolCall(payload, {
+ signal: abortController?.signal,
+ topicId: context?.topicId,
+ });
+
+ if (!!result) data = result;
+ } catch (error) {
+ console.log(error);
+ const err = error as Error;
+
+ // ignore the aborted request error
+ if (!err.message.includes('The user aborted a request.')) {
+ const result = await messageService.updateMessageError(id, error as any);
+ if (result?.success && result.messages) {
+ get().replaceMessages(result.messages);
+ }
+ }
+ }
+
+ internal_togglePluginApiCalling(false, id, n('fetchPlugin/end') as string);
+
+ // 如果报错则结束了
+
+ if (!data) return;
+
+ await Promise.all([
+ optimisticUpdateMessageContent(id, data.content),
+ (async () => {
+ if (data.success) await optimisticUpdatePluginState(id, data.state);
+ else await optimisticUpdateMessagePluginError(id, data.error);
+ })(),
+ ]);
+
+ return data.content;
+ },
+
+ internal_callPluginApi: async (id, payload) => {
+ const { optimisticUpdateMessageContent, internal_togglePluginApiCalling } = get();
+ let data: string;
+
+ try {
+ const abortController = internal_togglePluginApiCalling(
+ true,
+ id,
+ n('fetchPlugin/start') as string,
+ );
+
+ const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+
+ const res = await chatService.runPluginApi(payload, {
+ signal: abortController?.signal,
+ trace: { observationId: message?.observationId, traceId: message?.traceId },
+ });
+ data = res.text;
+
+ // save traceId
+ if (res.traceId) {
+ await messageService.updateMessage(id, { traceId: res.traceId });
+ }
+ } catch (error) {
+ console.log(error);
+ const err = error as Error;
+
+ // ignore the aborted request error
+ if (!err.message.includes('The user aborted a request.')) {
+ const result = await messageService.updateMessageError(id, error as any);
+ if (result?.success && result.messages) {
+ get().replaceMessages(result.messages);
+ }
+ }
+
+ data = '';
+ }
+
+ internal_togglePluginApiCalling(false, id, n('fetchPlugin/end') as string);
+ // 如果报错则结束了
+ if (!data) return;
+
+ await optimisticUpdateMessageContent(id, data);
+
+ return data;
+ },
+});
diff --git a/src/store/chat/slices/plugin/actions/publicApi.ts b/src/store/chat/slices/plugin/actions/publicApi.ts
new file mode 100644
index 00000000000..70c7337a65c
--- /dev/null
+++ b/src/store/chat/slices/plugin/actions/publicApi.ts
@@ -0,0 +1,115 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
+import { ChatToolPayload, UIChatMessage } from '@lobechat/types';
+import { StateCreator } from 'zustand/vanilla';
+
+import { ChatStore } from '@/store/chat/store';
+
+import { displayMessageSelectors } from '../../message/selectors';
+
+/**
+ * Public API for plugin operations
+ * These methods are called by UI components or other business scenarios
+ */
+export interface PluginPublicApiAction {
+ /**
+ * Fill plugin message content and optionally trigger AI message
+ */
+ fillPluginMessageContent: (
+ id: string,
+ content: string,
+ triggerAiMessage?: boolean,
+ ) => Promise<void>;
+
+ /**
+ * Re-invoke a tool message (retry failed plugin call)
+ */
+ reInvokeToolMessage: (id: string) => Promise<void>;
+
+ /**
+ * Summary plugin content using AI
+ */
+ summaryPluginContent: (id: string) => Promise<void>;
+
+ /**
+ * Invoke different type of plugin based on payload type
+ * This is the unified entry point for plugin invocation
+ */
+ internal_invokeDifferentTypePlugin: (id: string, payload: ChatToolPayload) => Promise<any>;
+}
+
+export const pluginPublicApi: StateCreator<
+ ChatStore,
+ [['zustand/devtools', never]],
+ [],
+ PluginPublicApiAction
+> = (set, get) => ({
+ fillPluginMessageContent: async (id, content, triggerAiMessage) => {
+ const { triggerAIMessage, optimisticUpdateMessageContent } = get();
+
+ await optimisticUpdateMessageContent(id, content);
+
+ if (triggerAiMessage) await triggerAIMessage({ parentId: id });
+ },
+
+ reInvokeToolMessage: async (id) => {
+ const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+ if (!message || message.role !== 'tool' || !message.plugin) return;
+
+ // if there is error content, then clear the error
+ if (!!message.pluginError) {
+ get().optimisticUpdateMessagePluginError(id, null);
+ }
+
+ const payload: ChatToolPayload = { ...message.plugin, id: message.tool_call_id! };
+
+ await get().internal_invokeDifferentTypePlugin(id, payload);
+ },
+
+ summaryPluginContent: async (id) => {
+ const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+ if (!message || message.role !== 'tool') return;
+
+ await get().internal_execAgentRuntime({
+ messages: [
+ {
+ role: 'assistant',
+ content: '作为一名总结专家,请结合以上系统提示词,将以下内容进行总结:',
+ },
+ {
+ ...message,
+ content: message.content,
+ role: 'assistant',
+ name: undefined,
+ tool_call_id: undefined,
+ },
+ ] as UIChatMessage[],
+ parentMessageId: message.id,
+ parentMessageType: 'assistant',
+ });
+ },
+
+ internal_invokeDifferentTypePlugin: async (id, payload) => {
+ switch (payload.type) {
+ case 'standalone': {
+ return await get().invokeStandaloneTypePlugin(id, payload);
+ }
+
+ case 'markdown': {
+ return await get().invokeMarkdownTypePlugin(id, payload);
+ }
+
+ case 'builtin': {
+ return await get().invokeBuiltinTool(id, payload);
+ }
+
+ // @ts-ignore
+ case 'mcp': {
+ return await get().invokeMCPTypePlugin(id, payload);
+ }
+
+ default: {
+ return await get().invokeDefaultTypePlugin(id, payload);
+ }
+ }
+ },
+});
diff --git a/src/store/chat/slices/plugin/actions/workflow.ts b/src/store/chat/slices/plugin/actions/workflow.ts
new file mode 100644
index 00000000000..81abc549de8
--- /dev/null
+++ b/src/store/chat/slices/plugin/actions/workflow.ts
@@ -0,0 +1,121 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
+import { CreateMessageParams } from '@lobechat/types';
+import { StateCreator } from 'zustand/vanilla';
+
+import { messageService } from '@/services/message';
+import { ChatStore } from '@/store/chat/store';
+
+import { dbMessageSelectors, displayMessageSelectors } from '../../message/selectors';
+import { threadSelectors } from '../../thread/selectors';
+
+/**
+ * Workflow orchestration actions
+ * Handle complex business flows involving multiple steps
+ */
+export interface PluginWorkflowAction {
+ /**
+ * Create an assistant message by plugin result
+ */
+ createAssistantMessageByPlugin: (content: string, parentId: string) => Promise<void>;
+
+ /**
+ * Trigger AI message after tool calls
+ */
+ triggerAIMessage: (params: {
+ parentId?: string;
+ traceId?: string;
+ threadId?: string;
+ inPortalThread?: boolean;
+ inSearchWorkflow?: boolean;
+ }) => Promise<void>;
+
+ /**
+ * Trigger tool calls (V1 deprecated method)
+ * @deprecated
+ */
+ triggerToolCalls: (
+ id: string,
+ params?: { threadId?: string; inPortalThread?: boolean; inSearchWorkflow?: boolean },
+ ) => Promise<void>;
+}
+
+export const pluginWorkflow: StateCreator<
+ ChatStore,
+ [['zustand/devtools', never]],
+ [],
+ PluginWorkflowAction
+> = (set, get) => ({
+ createAssistantMessageByPlugin: async (content, parentId) => {
+ const newMessage: CreateMessageParams = {
+ content,
+ parentId,
+ role: 'assistant',
+ sessionId: get().activeId,
+ topicId: get().activeTopicId, // if there is activeTopicId,then add it to topicId
+ };
+
+ const result = await messageService.createMessage(newMessage);
+ get().replaceMessages(result.messages);
+ },
+
+ triggerAIMessage: async ({ parentId, traceId, threadId, inPortalThread, inSearchWorkflow }) => {
+ const { internal_execAgentRuntime } = get();
+
+ const chats = inPortalThread
+ ? threadSelectors.portalAIChatsWithHistoryConfig(get())
+ : displayMessageSelectors.mainAIChatsWithHistoryConfig(get());
+
+ await internal_execAgentRuntime({
+ messages: chats,
+ parentMessageId: parentId ?? chats.at(-1)!.id,
+ parentMessageType: 'user',
+ traceId,
+ threadId,
+ inPortalThread,
+ inSearchWorkflow,
+ });
+ },
+
+ triggerToolCalls: async (assistantId, { threadId, inPortalThread, inSearchWorkflow } = {}) => {
+ const message = displayMessageSelectors.getDisplayMessageById(assistantId)(get());
+ if (!message || !message.tools) return;
+
+ let shouldCreateMessage = false;
+ let latestToolId = '';
+ const messagePools = message.tools.map(async (payload) => {
+ const toolMessage: CreateMessageParams = {
+ content: '',
+ parentId: assistantId,
+ plugin: payload,
+ role: 'tool',
+ sessionId: get().activeId,
+ tool_call_id: payload.id,
+ threadId,
+ topicId: get().activeTopicId, // if there is activeTopicId,then add it to topicId
+ groupId: message.groupId, // Propagate groupId from parent message for group chat
+ };
+
+ const result = await get().optimisticCreateMessage(toolMessage);
+ if (!result) return;
+
+ // trigger the plugin call
+ const data = await get().internal_invokeDifferentTypePlugin(result.id, payload);
+
+ if (data && !['markdown', 'standalone'].includes(payload.type)) {
+ shouldCreateMessage = true;
+ latestToolId = result.id;
+ }
+ });
+
+ await Promise.all(messagePools);
+
+ await get().internal_toggleMessageInToolsCalling(false, assistantId);
+
+ // only default type tool calls should trigger AI message
+ if (!shouldCreateMessage) return;
+
+ const traceId = dbMessageSelectors.getTraceIdByDbMessageId(latestToolId)(get());
+
+ await get().triggerAIMessage({ traceId, threadId, inPortalThread, inSearchWorkflow });
+ },
+});
diff --git a/src/store/chat/store.ts b/src/store/chat/store.ts
index 180604213f2..18b4cb2f48e 100644
--- a/src/store/chat/store.ts
+++ b/src/store/chat/store.ts
@@ -10,7 +10,7 @@ import { ChatBuiltinToolAction, chatToolSlice } from './slices/builtinTool/actio
import { ChatPortalAction, chatPortalSlice } from './slices/portal/action';
import { ChatTranslateAction, chatTranslate } from './slices/translate/action';
import { ChatMessageAction, chatMessage } from './slices/message/actions';
-import { ChatPluginAction, chatPlugin } from './slices/plugin/action';
+import { ChatPluginAction, chatPlugin } from './slices/plugin/actions';
import { ChatTopicAction, chatTopic } from './slices/topic/action';
import { ChatAIChatAction, chatAiChat } from './slices/aiChat/actions';
import { ChatTTSAction, chatTTS } from './slices/tts/action';